| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454 |
- const path = require('path');
- const { readCredentialContext } = require('../core/credentials');
- const {
- listEndpoints,
- findEndpoint,
- searchEndpoints,
- summarizeEndpoint,
- hydrateEndpoint,
- loadCatalog
- } = require('../core/api-catalog');
- const { callSocialGateway, redactSecret } = require('../providers/voc-gateway');
- const { callEcommerceGateway } = require('../providers/ecommerce-gateway');
- const { callOverseasGateway } = require('../providers/overseas-gateway');
- const {
- buildRechargeInfo,
- buildMissingNewApiTokenMessage,
- buildRechargeRequiredMessage,
- buildPermissionDeniedMessage
- } = require('../core/payment-links');
- const { okResult, errorResult } = require('../core/result-envelope');
- const { contextForTool, createStepContext, usageHeaders, writeUsageContext } = require('../core/usage-context');
- const { processMedia, replaceMediaUrls } = require('../features/media/media-pipeline');
- function buildCallTemplate(endpoint) {
- const args = { id: endpoint.id, params: {} };
- for (const param of endpoint.params || []) {
- if (param.required || param.default !== undefined) {
- args.params[param.name] = param.default !== undefined ? param.default : `<${param.name}>`;
- }
- }
- return args;
- }
- async function searchVocApis(input = {}) {
- const catalog = loadCatalog();
- const query = input.query || input.q || input.keyword || '';
- const matches = (query || input.platform || input.tag)
- ? searchEndpoints({ query, platform: input.platform, tag: input.tag, limit: input.limit || 20 })
- : listEndpoints();
- const results = matches.map(summarizeEndpoint);
- const lines = [
- '## VOC 转发接口清单',
- '',
- `社媒网关:${catalog.gateway?.social?.baseUrl || ''}(小红书/抖音内容、评论等,channel=social,默认)。`,
- catalog.gateway?.ecommerce?.baseUrl
- ? `电商与创作者数据网关:${catalog.gateway.ecommerce.baseUrl}(京东/淘宝天猫/1688/抖音电商/TikTok Shop/闲鱼/得物 等电商商品搜索·详情·价格·评论·店铺,抖音星图/小红书蒲公英创作者数据,及微信/微博/B站/知乎/头条/IMDb 等内容平台,channel=ecommerce)。`
- : '',
- catalog.gateway?.overseas?.baseUrl
- ? `海外电商选品网关:${catalog.gateway.overseas.baseUrl}(亚马逊海外站点类目树/Best Seller·产品详情与销量·ABA 关键词·评论·数据监控等选品数据,channel=overseas)。`
- : '',
- '通用转发:任意 proxyPath 透传到对应上游;通道由接口的 channel 字段决定,未登记接口可传 channel 覆盖。billing 只表示调用单位,人民币价格以 voc_billing_query 返回的服务端价目为准。',
- query ? `匹配关键词「${query}」的接口(${results.length} 条):` : `全部已登记接口(${results.length} 条):`,
- '',
- ...results.map(
- item =>
- `- ${item.id} | ${item.title}(${item.method} ${item.proxyPath},通道 ${item.channel},计费单位 ${item.billing ?? 1} ${item.billingUnit})必填参数: ${item.requiredParams.join(', ') || '无'}`
- ),
- '',
- '下一步:用 voc_api_doc 读取某个接口的详细参数文档,再用 voc_api_call 传参调用。',
- '清单里没有的接口,可直接用 voc_api_call 传 rawPath + method + params 调用。'
- ];
- return okResult({
- assistantMessage: lines.join('\n'),
- summary: { total: results.length, query: query || null },
- data: { endpoints: results, gateway: catalog.gateway, platforms: catalog.platforms }
- });
- }
- async function getVocApiDoc(input = {}) {
- const idOrPath = input.id || input.endpointId || input.proxyPath || input.rawPath || input.path;
- if (!idOrPath) {
- return errorResult('请提供接口 id 或 proxyPath(可先用 voc_api_search 查清单)。', {
- data: { endpoints: listEndpoints().map(summarizeEndpoint) }
- });
- }
- let endpoint = findEndpoint(idOrPath);
- if (!endpoint) {
- return errorResult(`清单里没有找到接口「${idOrPath}」。可用 voc_api_search 查询,或直接用 voc_api_call 传 rawPath 调用未登记接口。`, {
- data: { endpoints: listEndpoints().map(summarizeEndpoint) }
- });
- }
- endpoint = hydrateEndpoint(endpoint);
- const paramLines = (endpoint.params || []).map(p => {
- const flag = p.required ? '必填' : '可选';
- const def = p.default !== undefined ? `,默认 ${JSON.stringify(p.default)}` : '';
- return `- ${p.name}(${p.in}, ${p.type}, ${flag}${def}):${p.desc || ''}`;
- });
- const template = buildCallTemplate(endpoint);
- const lines = [
- `## ${endpoint.title}(${endpoint.id})`,
- '',
- endpoint.summary || '',
- '',
- `请求:${endpoint.method} ${endpoint.proxyPath}(计费 ${endpoint.billing || 1} 次,通道 ${endpoint.channel || 'social'})`,
- '',
- '参数:',
- ...paramLines,
- '',
- endpoint.responseHint ? `返回:${endpoint.responseHint}` : '',
- '',
- '调用示例(传给 voc_api_call):',
- '```json',
- JSON.stringify(template, null, 2),
- '```',
- '',
- 'token 优先用 NewAPI(fmode-api)的 sk- token(计费已迁移);没有 sk- 时回退用充值/开通页复制的、以 r: 开头的会话 token。'
- ].filter(line => line !== '');
- return okResult({
- assistantMessage: lines.join('\n'),
- summary: { id: endpoint.id, method: endpoint.method, proxyPath: endpoint.proxyPath, channel: endpoint.channel || 'social' },
- data: { endpoint, callTemplate: template }
- });
- }
- function resolveParamValue(name, params, input) {
- if (params && Object.prototype.hasOwnProperty.call(params, name)) return params[name];
- if (Object.prototype.hasOwnProperty.call(input, name)) return input[name];
- return undefined;
- }
- function buildRequestParts(endpoint, input) {
- const params = input.params && typeof input.params === 'object' ? input.params : {};
- const query = {};
- const body = {};
- const missing = [];
- const target = (param) => {
- const where = param.in || endpoint.paramsIn || (endpoint.method === 'GET' ? 'query' : 'body');
- return where === 'query' ? query : body;
- };
- for (const param of endpoint.params || []) {
- const hasDefault = param.default !== undefined;
- let value = resolveParamValue(param.name, params, input);
- if ((value === undefined || value === null || value === '') && param.default !== undefined) {
- value = param.default;
- }
- // Empty defaults are meaningful for a few upstream contracts (for
- // example Douyin's search_id/backtrace on the first page). Preserve them
- // while still treating an omitted required value as missing.
- if (value === undefined || value === null || (value === '' && !hasDefault)) {
- if (param.required) missing.push(param.name);
- continue;
- }
- target(param)[param.name] = value;
- }
- return { query, body: endpoint.method === 'GET' ? undefined : body, missing };
- }
- function buildRawRequestParts(input) {
- const method = String(input.method || 'GET').toUpperCase();
- const explicitQuery = input.query && typeof input.query === 'object' ? input.query : null;
- const explicitBody = input.body && typeof input.body === 'object' ? input.body : null;
- const params = input.params && typeof input.params === 'object' ? input.params : {};
- if (method === 'GET') {
- return { method, query: explicitQuery || params, body: undefined };
- }
- return { method, query: explicitQuery || {}, body: explicitBody || params };
- }
- function findRecordTime(value, depth = 0) {
- if (!value || typeof value !== 'object' || depth > 5) return '';
- if (typeof value.recordTime === 'string' && value.recordTime.trim()) {
- return value.recordTime.trim();
- }
- for (const nested of Object.values(value)) {
- const found = findRecordTime(nested, depth + 1);
- if (found) return found;
- }
- return '';
- }
- function assessFreshness(json, endpoint, now = Date.now()) {
- const recordTime = findRecordTime(json);
- const maxAgeHours = Number(endpoint?.maxRecommendedAgeHours);
- if (!recordTime || !Number.isFinite(maxAgeHours) || maxAgeHours <= 0) {
- return { recordTime: recordTime || null, maxAgeHours: null, ageHours: null, stale: false };
- }
- const timestamp = Date.parse(recordTime);
- if (!Number.isFinite(timestamp)) {
- return { recordTime, maxAgeHours, ageHours: null, stale: false };
- }
- const ageHours = Math.max(0, (now - timestamp) / (60 * 60 * 1000));
- return { recordTime, maxAgeHours, ageHours, stale: ageHours > maxAgeHours };
- }
- async function callVocApi(input = {}) {
- const idOrPath = input.id || input.endpointId;
- const rawPath = input.rawPath || input.proxyPath || (idOrPath ? null : input.path);
- let endpoint = idOrPath || rawPath ? findEndpoint(idOrPath || rawPath) : undefined;
- if (!endpoint && !rawPath) {
- return errorResult('请提供接口 id(先用 voc_api_search 查清单),或提供 rawPath + method 调用未登记接口。', {
- data: { endpoints: listEndpoints().map(summarizeEndpoint) }
- });
- }
- if (endpoint) endpoint = hydrateEndpoint(endpoint);
- // 计费优先走 NewAPI(fmode-api)的 sk- token;该 token 鉴权失败(含「未入仓」类报错)时
- // 自动回退平台 sessionToken 重试。注意:以前因为 sk- 直接请求会命中「入仓」错误,这里曾经
- // 直接拒绝 sk- token;现在改为「优先 sk-、鉴权失败再回退 sessionToken」,并对外只给友好提示。
- const credentials = readCredentialContext(input);
- const newapiToken = credentials.newApiToken;
- const sessionToken = credentials.sessionToken;
- const token = newapiToken || sessionToken;
- const fallbackToken = (newapiToken && sessionToken && newapiToken !== sessionToken) ? sessionToken : '';
- if (!token) {
- const recharge = await buildRechargeInfo();
- return {
- status: 'needs_token',
- assistantMessage: buildMissingNewApiTokenMessage(recharge.paymentUrl, recharge, { platformLabel: '社交平台' }),
- summary: { endpoint: endpoint?.id || rawPath, errorKind: 'missing_token', recoverable: true },
- data: { recharge },
- files: [],
- nextActions: [
- '从 ~/.claude/settings.json 取 env.ANTHROPIC_AUTH_TOKEN(sk-),用 FMODE_API_KEY=sk-… 或入参 newapiToken 传入后重新调用',
- '仍不行再回退以 r: 开头的会话 token;仅当确认是 402 余额不足时才打开充值链接'
- ],
- warnings: [],
- errors: []
- };
- }
- let proxyPath;
- let method;
- let query;
- let body;
- if (endpoint) {
- proxyPath = endpoint.proxyPath;
- method = endpoint.method;
- const parts = buildRequestParts(endpoint, input);
- if (parts.missing.length) {
- const missingMessage = `缺少必填参数:${parts.missing.join(', ')}。这不是类目/关键词/余额问题,请补齐参数后再调用(可用 voc_api_doc 查看参数说明)。`;
- return {
- status: 'needs_input',
- assistantMessage: missingMessage,
- summary: { endpoint: endpoint.id, missing: parts.missing },
- data: { endpoint: summarizeEndpoint(endpoint), missing: parts.missing },
- files: [],
- nextActions: ['用 voc_api_doc 核对必填参数', '补齐参数后重新调用'],
- warnings: [],
- errors: [{ message: `缺少必填参数:${parts.missing.join(', ')}`, kind: 'request', httpStatus: 0 }]
- };
- }
- query = parts.query;
- body = parts.body;
- } else {
- proxyPath = rawPath;
- const parts = buildRawRequestParts(input);
- method = parts.method;
- query = parts.query;
- body = parts.body;
- }
- // 已登记接口可带 channel 字段:social 走社媒中转网关(voc-social,小红书/抖音内容评论等),
- // ecommerce 走创作者数据网关(voc-e-commerce,星图/蒲公英创作者侧结构化数据)。两套网关鉴权、计费、
- // 错误处理完全同源,只是根地址不同。VOC 默认 social;未登记的 rawPath 调用可用 input.channel 覆盖。
- const channel = String((endpoint && endpoint.channel) || input.channel || 'social').toLowerCase();
- const callGateway = channel === 'overseas'
- ? callOverseasGateway
- : channel === 'ecommerce'
- ? callEcommerceGateway
- : callSocialGateway;
- const usageContext = contextForTool({ ...input, skillId: input.skillId || 'voc-api-catalog' });
- const stepContext = createStepContext(usageContext, input.stepId || endpoint?.id || proxyPath);
- const outputDir = path.resolve(input.outputDir || input.output || path.join('outputs', usageContext.usageTraceId));
- const usageContextFile = writeUsageContext(usageContext, outputDir);
- try {
- const result = await callGateway({
- proxyPath,
- method,
- query,
- body,
- token,
- fallbackToken,
- baseUrl: input.baseUrl,
- retries: Number.isFinite(input.retries) ? input.retries : 3,
- headers: usageHeaders(stepContext)
- });
- // Generic catalog calls can return covers, detail images, videos, audio,
- // or buyer-show media just like the dedicated trend tools. Persist all of
- // them through the local-only pipeline before exposing the response.
- const mediaResult = await processMedia(result.data, {
- outputDir,
- usageTraceId: usageContext.usageTraceId,
- platform: channel
- });
- const normalizedData = replaceMediaUrls(result.data, mediaResult.replacements);
- const normalizedRaw = replaceMediaUrls(result.json, mediaResult.replacements);
- const mediaFiles = [...mediaResult.files, mediaResult.manifestFile].filter(Boolean);
- const freshness = assessFreshness(result.json, endpoint);
- if (freshness.stale) {
- const ageLabel = freshness.ageHours.toFixed(1);
- return {
- status: 'stale_data',
- assistantMessage: [
- `接口 ${proxyPath} 返回了数据,但 recordTime=${freshness.recordTime},快照已滞后约 ${ageLabel} 小时。`,
- '',
- `该接口当前按 ${freshness.maxAgeHours} 小时作为可用时效门槛,本次结果只能作为历史参考,不能表述为当前页面数据。`
- ].join('\n'),
- summary: {
- endpoint: endpoint?.id || proxyPath,
- channel,
- method,
- proxyPath,
- billing: endpoint?.billing || 1,
- httpStatus: result.httpStatus,
- authMode: result.authMode,
- fallbackUsed: Boolean(result.fallbackUsed),
- mediaCount: mediaResult.items.length,
- ...freshness
- },
- data: { result: normalizedData, raw: normalizedRaw },
- files: [...mediaFiles, ...(usageContextFile ? [usageContextFile] : [])],
- nextActions: ['优先改用淘宝详情 V7 重试', '稍后重试并重新检查 recordTime'],
- warnings: [`数据快照超过 ${freshness.maxAgeHours} 小时时效门槛`, ...mediaResult.warnings],
- errors: []
- };
- }
- return okResult({
- assistantMessage: `调用成功:${proxyPath}(${method},${channel} 通道)。`,
- summary: {
- endpoint: endpoint?.id || proxyPath,
- channel,
- method,
- proxyPath,
- billing: endpoint?.billing || 1,
- httpStatus: result.httpStatus,
- authMode: result.authMode,
- fallbackUsed: Boolean(result.fallbackUsed),
- mediaCount: mediaResult.items.length,
- ...freshness
- },
- data: { result: normalizedData, raw: normalizedRaw, usage: stepContext },
- files: [...mediaFiles, ...(usageContextFile ? [usageContextFile] : [])],
- warnings: mediaResult.warnings
- });
- } catch (error) {
- const kind = String(error && (error.kind || error.errorKind) || 'upstream');
- const httpStatus = Number(error && error.httpStatus) || 0;
- const safeMessage = redactSecret(error && error.message ? error.message : 'request failed');
- if (kind === 'auth') {
- // sk- 与 sessionToken(若有)都未通过校验。不把底层「未入仓」/鉴权报错甩给用户,只给友好提示。
- const recharge = await buildRechargeInfo({ sessionToken });
- return {
- status: 'needs_valid_token',
- assistantMessage: [
- '当前 token 没有通过校验,暂时不能调用该接口——这是 token 缺失/无效/失效的**可恢复**问题,不是关键词/类目/参数问题,也不代表这个功能用不了、更不是余额不足。',
- '',
- '优先自救:NewAPI(fmode-api)计费用的 `sk-` 就是 Claude Code 的 `ANTHROPIC_AUTH_TOKEN`(在 `~/.claude/settings.json` 的 `env` 里)。请取出它(确认 `sk-` 开头、`ANTHROPIC_BASE_URL` 指向 `api.fmode.cn`),用 `FMODE_API_KEY=sk-…` 或入参 `newapiToken` 传入后重试。',
- '',
- '若 `sk-` 仍校验不过,再回退以 `r:` 开头的会话 token。',
- '',
- '只有接口明确返回 402 时才会提供当前用户充值入口。'
- ].join('\n'),
- summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus, recoverable: true },
- data: { recharge },
- files: [],
- nextActions: [
- '从 ~/.claude/settings.json 取 env.ANTHROPIC_AUTH_TOKEN(sk-),用 FMODE_API_KEY=sk-… 或入参 newapiToken 传入后重试',
- '仍不行再回退以 r: 开头的 session token;仅当确认是 402 余额不足时才打开充值链接'
- ],
- warnings: [],
- errors: []
- };
- }
- if (kind === 'billing') {
- const recharge = await buildRechargeInfo({ sessionToken });
- const rechargeStatus = recharge.personalized ? 'needs_recharge' : 'needs_session';
- return {
- status: rechargeStatus,
- assistantMessage: buildRechargeRequiredMessage(recharge.paymentUrl, recharge, { platformLabel: 'VOC' }),
- summary: {
- endpoint: endpoint?.id || proxyPath,
- channel,
- errorKind: recharge.personalized ? kind : 'missing_session_for_recharge',
- billingErrorKind: kind,
- httpStatus
- },
- data: { recharge },
- files: [],
- nextActions: recharge.personalized
- ? [`打开免登录充值链接:${recharge.balanceUrl}`, '充值到账后使用相同参数继续调用']
- : ['恢复当前用户 Session Token 后打开个人充值页', '充值到账后使用相同参数继续调用'],
- warnings: [],
- errors: []
- };
- }
- if (kind === 'permission') {
- // 403:用户被禁用/无权限,区别于余额不足,不引导充值。
- return {
- status: 'needs_permission',
- assistantMessage: buildPermissionDeniedMessage({ platformLabel: '社交平台' }),
- summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus },
- data: {},
- files: [],
- nextActions: ['联系服务方确认账号状态或接口权限后重试'],
- warnings: [],
- errors: []
- };
- }
- if (kind === 'request') {
- return {
- status: 'needs_input',
- assistantMessage: [
- `接口 ${proxyPath} 返回了入参/请求错误(${safeMessage})。`,
- '',
- '这不是余额不足,也不是类目不支持:请检查参数是否符合接口文档(可用 voc_api_doc 查看),修正后重试。'
- ].join('\n'),
- summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus },
- data: { message: safeMessage },
- files: [],
- nextActions: ['用 voc_api_doc 核对参数', '修正参数后重新调用'],
- warnings: [],
- errors: [{ message: safeMessage, kind, httpStatus }]
- };
- }
- if (kind === 'unsupported') {
- return {
- status: 'not_supported',
- assistantMessage: `接口 ${proxyPath} 当前不支持该商品或该数据口径(${safeMessage})。`,
- summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus },
- data: { message: safeMessage },
- files: [],
- nextActions: ['改用淘宝详情 V7 获取基础详情', '不要把该响应作为不完整商品详情继续使用'],
- warnings: [],
- errors: []
- };
- }
- return {
- status: 'upstream_unstable',
- assistantMessage: [
- `接口 ${proxyPath} 这次调用失败,是上游数据接口返回错误或暂时不稳定(如 5xx、连接超时、fetch failed)。`,
- '',
- '这不是关键词问题,也不是类目不支持、也不是余额不足:通常稍后重试即可(本工具已自动重试若干次)。'
- ].join('\n'),
- summary: { endpoint: endpoint?.id || proxyPath, errorKind: kind, httpStatus },
- data: { message: safeMessage },
- files: [],
- nextActions: ['稍后重试该接口调用'],
- warnings: [],
- errors: [{ message: safeMessage, kind, httpStatus }]
- };
- }
- }
- module.exports = {
- searchVocApis,
- getVocApiDoc,
- callVocApi,
- buildRequestParts,
- findRecordTime,
- assessFreshness
- };
|