voc-api-catalog-run.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. const path = require('path');
  2. const { readCredentialContext } = require('../core/credentials');
  3. const {
  4. listEndpoints,
  5. findEndpoint,
  6. searchEndpoints,
  7. summarizeEndpoint,
  8. hydrateEndpoint,
  9. loadCatalog
  10. } = require('../core/api-catalog');
  11. const { callSocialGateway, redactSecret } = require('../providers/voc-gateway');
  12. const { callEcommerceGateway } = require('../providers/ecommerce-gateway');
  13. const { callOverseasGateway } = require('../providers/overseas-gateway');
  14. const {
  15. buildRechargeInfo,
  16. buildMissingNewApiTokenMessage,
  17. buildRechargeRequiredMessage,
  18. buildPermissionDeniedMessage
  19. } = require('../core/payment-links');
  20. const { okResult, errorResult } = require('../core/result-envelope');
  21. const { contextForTool, createStepContext, usageHeaders, writeUsageContext } = require('../core/usage-context');
  22. const { processMedia, replaceMediaUrls } = require('../features/media/media-pipeline');
  23. function buildCallTemplate(endpoint) {
  24. const args = { id: endpoint.id, params: {} };
  25. for (const param of endpoint.params || []) {
  26. if (param.required || param.default !== undefined) {
  27. args.params[param.name] = param.default !== undefined ? param.default : `<${param.name}>`;
  28. }
  29. }
  30. return args;
  31. }
  32. async function searchVocApis(input = {}) {
  33. const catalog = loadCatalog();
  34. const query = input.query || input.q || input.keyword || '';
  35. const matches = (query || input.platform || input.tag)
  36. ? searchEndpoints({ query, platform: input.platform, tag: input.tag, limit: input.limit || 20 })
  37. : listEndpoints();
  38. const results = matches.map(summarizeEndpoint);
  39. const lines = [
  40. '## VOC 转发接口清单',
  41. '',
  42. `社媒网关:${catalog.gateway?.social?.baseUrl || ''}(小红书/抖音内容、评论等,channel=social,默认)。`,
  43. catalog.gateway?.ecommerce?.baseUrl
  44. ? `电商与创作者数据网关:${catalog.gateway.ecommerce.baseUrl}(京东/淘宝天猫/1688/抖音电商/TikTok Shop/闲鱼/得物 等电商商品搜索·详情·价格·评论·店铺,抖音星图/小红书蒲公英创作者数据,及微信/微博/B站/知乎/头条/IMDb 等内容平台,channel=ecommerce)。`
  45. : '',
  46. catalog.gateway?.overseas?.baseUrl
  47. ? `海外电商选品网关:${catalog.gateway.overseas.baseUrl}(亚马逊海外站点类目树/Best Seller·产品详情与销量·ABA 关键词·评论·数据监控等选品数据,channel=overseas)。`
  48. : '',
  49. '通用转发:任意 proxyPath 透传到对应上游;通道由接口的 channel 字段决定,未登记接口可传 channel 覆盖。billing 只表示调用单位,人民币价格以 voc_billing_query 返回的服务端价目为准。',
  50. query ? `匹配关键词「${query}」的接口(${results.length} 条):` : `全部已登记接口(${results.length} 条):`,
  51. '',
  52. ...results.map(
  53. item =>
  54. `- ${item.id} | ${item.title}(${item.method} ${item.proxyPath},通道 ${item.channel},计费单位 ${item.billing ?? 1} ${item.billingUnit})必填参数: ${item.requiredParams.join(', ') || '无'}`
  55. ),
  56. '',
  57. '下一步:用 voc_api_doc 读取某个接口的详细参数文档,再用 voc_api_call 传参调用。',
  58. '清单里没有的接口,可直接用 voc_api_call 传 rawPath + method + params 调用。'
  59. ];
  60. return okResult({
  61. assistantMessage: lines.join('\n'),
  62. summary: { total: results.length, query: query || null },
  63. data: { endpoints: results, gateway: catalog.gateway, platforms: catalog.platforms }
  64. });
  65. }
  66. async function getVocApiDoc(input = {}) {
  67. const idOrPath = input.id || input.endpointId || input.proxyPath || input.rawPath || input.path;
  68. if (!idOrPath) {
  69. return errorResult('请提供接口 id 或 proxyPath(可先用 voc_api_search 查清单)。', {
  70. data: { endpoints: listEndpoints().map(summarizeEndpoint) }
  71. });
  72. }
  73. let endpoint = findEndpoint(idOrPath);
  74. if (!endpoint) {
  75. return errorResult(`清单里没有找到接口「${idOrPath}」。可用 voc_api_search 查询,或直接用 voc_api_call 传 rawPath 调用未登记接口。`, {
  76. data: { endpoints: listEndpoints().map(summarizeEndpoint) }
  77. });
  78. }
  79. endpoint = hydrateEndpoint(endpoint);
  80. const paramLines = (endpoint.params || []).map(p => {
  81. const flag = p.required ? '必填' : '可选';
  82. const def = p.default !== undefined ? `,默认 ${JSON.stringify(p.default)}` : '';
  83. return `- ${p.name}(${p.in}, ${p.type}, ${flag}${def}):${p.desc || ''}`;
  84. });
  85. const template = buildCallTemplate(endpoint);
  86. const lines = [
  87. `## ${endpoint.title}(${endpoint.id})`,
  88. '',
  89. endpoint.summary || '',
  90. '',
  91. `请求:${endpoint.method} ${endpoint.proxyPath}(计费 ${endpoint.billing || 1} 次,通道 ${endpoint.channel || 'social'})`,
  92. '',
  93. '参数:',
  94. ...paramLines,
  95. '',
  96. endpoint.responseHint ? `返回:${endpoint.responseHint}` : '',
  97. '',
  98. '调用示例(传给 voc_api_call):',
  99. '```json',
  100. JSON.stringify(template, null, 2),
  101. '```',
  102. '',
  103. 'token 优先用 NewAPI(fmode-api)的 sk- token(计费已迁移);没有 sk- 时回退用充值/开通页复制的、以 r: 开头的会话 token。'
  104. ].filter(line => line !== '');
  105. return okResult({
  106. assistantMessage: lines.join('\n'),
  107. summary: { id: endpoint.id, method: endpoint.method, proxyPath: endpoint.proxyPath, channel: endpoint.channel || 'social' },
  108. data: { endpoint, callTemplate: template }
  109. });
  110. }
  111. function resolveParamValue(name, params, input) {
  112. if (params && Object.prototype.hasOwnProperty.call(params, name)) return params[name];
  113. if (Object.prototype.hasOwnProperty.call(input, name)) return input[name];
  114. return undefined;
  115. }
  116. function buildRequestParts(endpoint, input) {
  117. const params = input.params && typeof input.params === 'object' ? input.params : {};
  118. const query = {};
  119. const body = {};
  120. const missing = [];
  121. const target = (param) => {
  122. const where = param.in || endpoint.paramsIn || (endpoint.method === 'GET' ? 'query' : 'body');
  123. return where === 'query' ? query : body;
  124. };
  125. for (const param of endpoint.params || []) {
  126. const hasDefault = param.default !== undefined;
  127. let value = resolveParamValue(param.name, params, input);
  128. if ((value === undefined || value === null || value === '') && param.default !== undefined) {
  129. value = param.default;
  130. }
  131. // Empty defaults are meaningful for a few upstream contracts (for
  132. // example Douyin's search_id/backtrace on the first page). Preserve them
  133. // while still treating an omitted required value as missing.
  134. if (value === undefined || value === null || (value === '' && !hasDefault)) {
  135. if (param.required) missing.push(param.name);
  136. continue;
  137. }
  138. target(param)[param.name] = value;
  139. }
  140. return { query, body: endpoint.method === 'GET' ? undefined : body, missing };
  141. }
  142. function buildRawRequestParts(input) {
  143. const method = String(input.method || 'GET').toUpperCase();
  144. const explicitQuery = input.query && typeof input.query === 'object' ? input.query : null;
  145. const explicitBody = input.body && typeof input.body === 'object' ? input.body : null;
  146. const params = input.params && typeof input.params === 'object' ? input.params : {};
  147. if (method === 'GET') {
  148. return { method, query: explicitQuery || params, body: undefined };
  149. }
  150. return { method, query: explicitQuery || {}, body: explicitBody || params };
  151. }
  152. function findRecordTime(value, depth = 0) {
  153. if (!value || typeof value !== 'object' || depth > 5) return '';
  154. if (typeof value.recordTime === 'string' && value.recordTime.trim()) {
  155. return value.recordTime.trim();
  156. }
  157. for (const nested of Object.values(value)) {
  158. const found = findRecordTime(nested, depth + 1);
  159. if (found) return found;
  160. }
  161. return '';
  162. }
  163. function assessFreshness(json, endpoint, now = Date.now()) {
  164. const recordTime = findRecordTime(json);
  165. const maxAgeHours = Number(endpoint?.maxRecommendedAgeHours);
  166. if (!recordTime || !Number.isFinite(maxAgeHours) || maxAgeHours <= 0) {
  167. return { recordTime: recordTime || null, maxAgeHours: null, ageHours: null, stale: false };
  168. }
  169. const timestamp = Date.parse(recordTime);
  170. if (!Number.isFinite(timestamp)) {
  171. return { recordTime, maxAgeHours, ageHours: null, stale: false };
  172. }
  173. const ageHours = Math.max(0, (now - timestamp) / (60 * 60 * 1000));
  174. return { recordTime, maxAgeHours, ageHours, stale: ageHours > maxAgeHours };
  175. }
  176. async function callVocApi(input = {}) {
  177. const idOrPath = input.id || input.endpointId;
  178. const rawPath = input.rawPath || input.proxyPath || (idOrPath ? null : input.path);
  179. let endpoint = idOrPath || rawPath ? findEndpoint(idOrPath || rawPath) : undefined;
  180. if (!endpoint && !rawPath) {
  181. return errorResult('请提供接口 id(先用 voc_api_search 查清单),或提供 rawPath + method 调用未登记接口。', {
  182. data: { endpoints: listEndpoints().map(summarizeEndpoint) }
  183. });
  184. }
  185. if (endpoint) endpoint = hydrateEndpoint(endpoint);
  186. // 计费优先走 NewAPI(fmode-api)的 sk- token;该 token 鉴权失败(含「未入仓」类报错)时
  187. // 自动回退平台 sessionToken 重试。注意:以前因为 sk- 直接请求会命中「入仓」错误,这里曾经
  188. // 直接拒绝 sk- token;现在改为「优先 sk-、鉴权失败再回退 sessionToken」,并对外只给友好提示。
  189. const credentials = readCredentialContext(input);
  190. const newapiToken = credentials.newApiToken;
  191. const sessionToken = credentials.sessionToken;
  192. const token = newapiToken || sessionToken;
  193. const fallbackToken = (newapiToken && sessionToken && newapiToken !== sessionToken) ? sessionToken : '';
  194. if (!token) {
  195. const recharge = await buildRechargeInfo();
  196. return {
  197. status: 'needs_token',
  198. assistantMessage: buildMissingNewApiTokenMessage(recharge.paymentUrl, recharge, { platformLabel: '社交平台' }),
  199. summary: { endpoint: endpoint?.id || rawPath, errorKind: 'missing_token', recoverable: true },
  200. data: { recharge },
  201. files: [],
  202. nextActions: [
  203. '从 ~/.claude/settings.json 取 env.ANTHROPIC_AUTH_TOKEN(sk-),用 FMODE_API_KEY=sk-… 或入参 newapiToken 传入后重新调用',
  204. '仍不行再回退以 r: 开头的会话 token;仅当确认是 402 余额不足时才打开充值链接'
  205. ],
  206. warnings: [],
  207. errors: []
  208. };
  209. }
  210. let proxyPath;
  211. let method;
  212. let query;
  213. let body;
  214. if (endpoint) {
  215. proxyPath = endpoint.proxyPath;
  216. method = endpoint.method;
  217. const parts = buildRequestParts(endpoint, input);
  218. if (parts.missing.length) {
  219. const missingMessage = `缺少必填参数:${parts.missing.join(', ')}。这不是类目/关键词/余额问题,请补齐参数后再调用(可用 voc_api_doc 查看参数说明)。`;
  220. return {
  221. status: 'needs_input',
  222. assistantMessage: missingMessage,
  223. summary: { endpoint: endpoint.id, missing: parts.missing },
  224. data: { endpoint: summarizeEndpoint(endpoint), missing: parts.missing },
  225. files: [],
  226. nextActions: ['用 voc_api_doc 核对必填参数', '补齐参数后重新调用'],
  227. warnings: [],
  228. errors: [{ message: `缺少必填参数:${parts.missing.join(', ')}`, kind: 'request', httpStatus: 0 }]
  229. };
  230. }
  231. query = parts.query;
  232. body = parts.body;
  233. } else {
  234. proxyPath = rawPath;
  235. const parts = buildRawRequestParts(input);
  236. method = parts.method;
  237. query = parts.query;
  238. body = parts.body;
  239. }
  240. // 已登记接口可带 channel 字段:social 走社媒中转网关(voc-social,小红书/抖音内容评论等),
  241. // ecommerce 走创作者数据网关(voc-e-commerce,星图/蒲公英创作者侧结构化数据)。两套网关鉴权、计费、
  242. // 错误处理完全同源,只是根地址不同。VOC 默认 social;未登记的 rawPath 调用可用 input.channel 覆盖。
  243. const channel = String((endpoint && endpoint.channel) || input.channel || 'social').toLowerCase();
  244. const callGateway = channel === 'overseas'
  245. ? callOverseasGateway
  246. : channel === 'ecommerce'
  247. ? callEcommerceGateway
  248. : callSocialGateway;
  249. const usageContext = contextForTool({ ...input, skillId: input.skillId || 'voc-api-catalog' });
  250. const stepContext = createStepContext(usageContext, input.stepId || endpoint?.id || proxyPath);
  251. const outputDir = path.resolve(input.outputDir || input.output || path.join('outputs', usageContext.usageTraceId));
  252. const usageContextFile = writeUsageContext(usageContext, outputDir);
  253. try {
  254. const result = await callGateway({
  255. proxyPath,
  256. method,
  257. query,
  258. body,
  259. token,
  260. fallbackToken,
  261. baseUrl: input.baseUrl,
  262. retries: Number.isFinite(input.retries) ? input.retries : 3,
  263. headers: usageHeaders(stepContext)
  264. });
  265. // Generic catalog calls can return covers, detail images, videos, audio,
  266. // or buyer-show media just like the dedicated trend tools. Persist all of
  267. // them through the local-only pipeline before exposing the response.
  268. const mediaResult = await processMedia(result.data, {
  269. outputDir,
  270. usageTraceId: usageContext.usageTraceId,
  271. platform: channel
  272. });
  273. const normalizedData = replaceMediaUrls(result.data, mediaResult.replacements);
  274. const normalizedRaw = replaceMediaUrls(result.json, mediaResult.replacements);
  275. const mediaFiles = [...mediaResult.files, mediaResult.manifestFile].filter(Boolean);
  276. const freshness = assessFreshness(result.json, endpoint);
  277. if (freshness.stale) {
  278. const ageLabel = freshness.ageHours.toFixed(1);
  279. return {
  280. status: 'stale_data',
  281. assistantMessage: [
  282. `接口 ${proxyPath} 返回了数据,但 recordTime=${freshness.recordTime},快照已滞后约 ${ageLabel} 小时。`,
  283. '',
  284. `该接口当前按 ${freshness.maxAgeHours} 小时作为可用时效门槛,本次结果只能作为历史参考,不能表述为当前页面数据。`
  285. ].join('\n'),
  286. summary: {
  287. endpoint: endpoint?.id || proxyPath,
  288. channel,
  289. method,
  290. proxyPath,
  291. billing: endpoint?.billing || 1,
  292. httpStatus: result.httpStatus,
  293. authMode: result.authMode,
  294. fallbackUsed: Boolean(result.fallbackUsed),
  295. mediaCount: mediaResult.items.length,
  296. ...freshness
  297. },
  298. data: { result: normalizedData, raw: normalizedRaw },
  299. files: [...mediaFiles, ...(usageContextFile ? [usageContextFile] : [])],
  300. nextActions: ['优先改用淘宝详情 V7 重试', '稍后重试并重新检查 recordTime'],
  301. warnings: [`数据快照超过 ${freshness.maxAgeHours} 小时时效门槛`, ...mediaResult.warnings],
  302. errors: []
  303. };
  304. }
  305. return okResult({
  306. assistantMessage: `调用成功:${proxyPath}(${method},${channel} 通道)。`,
  307. summary: {
  308. endpoint: endpoint?.id || proxyPath,
  309. channel,
  310. method,
  311. proxyPath,
  312. billing: endpoint?.billing || 1,
  313. httpStatus: result.httpStatus,
  314. authMode: result.authMode,
  315. fallbackUsed: Boolean(result.fallbackUsed),
  316. mediaCount: mediaResult.items.length,
  317. ...freshness
  318. },
  319. data: { result: normalizedData, raw: normalizedRaw, usage: stepContext },
  320. files: [...mediaFiles, ...(usageContextFile ? [usageContextFile] : [])],
  321. warnings: mediaResult.warnings
  322. });
  323. } catch (error) {
  324. const kind = String(error && (error.kind || error.errorKind) || 'upstream');
  325. const httpStatus = Number(error && error.httpStatus) || 0;
  326. const safeMessage = redactSecret(error && error.message ? error.message : 'request failed');
  327. if (kind === 'auth') {
  328. // sk- 与 sessionToken(若有)都未通过校验。不把底层「未入仓」/鉴权报错甩给用户,只给友好提示。
  329. const recharge = await buildRechargeInfo({ sessionToken });
  330. return {
  331. status: 'needs_valid_token',
  332. assistantMessage: [
  333. '当前 token 没有通过校验,暂时不能调用该接口——这是 token 缺失/无效/失效的**可恢复**问题,不是关键词/类目/参数问题,也不代表这个功能用不了、更不是余额不足。',
  334. '',
  335. '优先自救: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` 传入后重试。',
  336. '',
  337. '若 `sk-` 仍校验不过,再回退以 `r:` 开头的会话 token。',
  338. '',
  339. '只有接口明确返回 402 时才会提供当前用户充值入口。'
  340. ].join('\n'),
  341. summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus, recoverable: true },
  342. data: { recharge },
  343. files: [],
  344. nextActions: [
  345. '从 ~/.claude/settings.json 取 env.ANTHROPIC_AUTH_TOKEN(sk-),用 FMODE_API_KEY=sk-… 或入参 newapiToken 传入后重试',
  346. '仍不行再回退以 r: 开头的 session token;仅当确认是 402 余额不足时才打开充值链接'
  347. ],
  348. warnings: [],
  349. errors: []
  350. };
  351. }
  352. if (kind === 'billing') {
  353. const recharge = await buildRechargeInfo({ sessionToken });
  354. const rechargeStatus = recharge.personalized ? 'needs_recharge' : 'needs_session';
  355. return {
  356. status: rechargeStatus,
  357. assistantMessage: buildRechargeRequiredMessage(recharge.paymentUrl, recharge, { platformLabel: 'VOC' }),
  358. summary: {
  359. endpoint: endpoint?.id || proxyPath,
  360. channel,
  361. errorKind: recharge.personalized ? kind : 'missing_session_for_recharge',
  362. billingErrorKind: kind,
  363. httpStatus
  364. },
  365. data: { recharge },
  366. files: [],
  367. nextActions: recharge.personalized
  368. ? [`打开免登录充值链接:${recharge.balanceUrl}`, '充值到账后使用相同参数继续调用']
  369. : ['恢复当前用户 Session Token 后打开个人充值页', '充值到账后使用相同参数继续调用'],
  370. warnings: [],
  371. errors: []
  372. };
  373. }
  374. if (kind === 'permission') {
  375. // 403:用户被禁用/无权限,区别于余额不足,不引导充值。
  376. return {
  377. status: 'needs_permission',
  378. assistantMessage: buildPermissionDeniedMessage({ platformLabel: '社交平台' }),
  379. summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus },
  380. data: {},
  381. files: [],
  382. nextActions: ['联系服务方确认账号状态或接口权限后重试'],
  383. warnings: [],
  384. errors: []
  385. };
  386. }
  387. if (kind === 'request') {
  388. return {
  389. status: 'needs_input',
  390. assistantMessage: [
  391. `接口 ${proxyPath} 返回了入参/请求错误(${safeMessage})。`,
  392. '',
  393. '这不是余额不足,也不是类目不支持:请检查参数是否符合接口文档(可用 voc_api_doc 查看),修正后重试。'
  394. ].join('\n'),
  395. summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus },
  396. data: { message: safeMessage },
  397. files: [],
  398. nextActions: ['用 voc_api_doc 核对参数', '修正参数后重新调用'],
  399. warnings: [],
  400. errors: [{ message: safeMessage, kind, httpStatus }]
  401. };
  402. }
  403. if (kind === 'unsupported') {
  404. return {
  405. status: 'not_supported',
  406. assistantMessage: `接口 ${proxyPath} 当前不支持该商品或该数据口径(${safeMessage})。`,
  407. summary: { endpoint: endpoint?.id || proxyPath, channel, errorKind: kind, httpStatus },
  408. data: { message: safeMessage },
  409. files: [],
  410. nextActions: ['改用淘宝详情 V7 获取基础详情', '不要把该响应作为不完整商品详情继续使用'],
  411. warnings: [],
  412. errors: []
  413. };
  414. }
  415. return {
  416. status: 'upstream_unstable',
  417. assistantMessage: [
  418. `接口 ${proxyPath} 这次调用失败,是上游数据接口返回错误或暂时不稳定(如 5xx、连接超时、fetch failed)。`,
  419. '',
  420. '这不是关键词问题,也不是类目不支持、也不是余额不足:通常稍后重试即可(本工具已自动重试若干次)。'
  421. ].join('\n'),
  422. summary: { endpoint: endpoint?.id || proxyPath, errorKind: kind, httpStatus },
  423. data: { message: safeMessage },
  424. files: [],
  425. nextActions: ['稍后重试该接口调用'],
  426. warnings: [],
  427. errors: [{ message: safeMessage, kind, httpStatus }]
  428. };
  429. }
  430. }
  431. module.exports = {
  432. searchVocApis,
  433. getVocApiDoc,
  434. callVocApi,
  435. buildRequestParts,
  436. findRecordTime,
  437. assessFreshness
  438. };