collect-product-review-sample.cjs 6.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Use the existing VOC MCP directly; no digital-human delegation or new login.
  2. // One collection call per invocation, no retries and no automatic alternatives.
  3. if (process.argv[2] === 'call') require('../server/industry-collection-guard.cjs').assertPaidCollectionAllowed();
  4. const fs = require('node:fs');
  5. const path = require('node:path');
  6. const crypto = require('node:crypto');
  7. const { createRequire } = require('node:module');
  8. const pluginRoot = 'C:/Users/JSHY/AppData/Roaming/npm/node_modules/@vocmarket/voc-skill';
  9. const req = createRequire(path.join(pluginRoot, 'mcp/src/server.js'));
  10. const { Client } = req('@modelcontextprotocol/sdk/client/index.js');
  11. const { StdioClientTransport } = req('@modelcontextprotocol/sdk/client/stdio.js');
  12. const { readCredentialContext } = req('./core/credentials.js');
  13. const credentials = readCredentialContext({});
  14. const [mode, label, family, itemId, pageArg = '1'] = process.argv.slice(2);
  15. const base = path.resolve('work/product-reviews/live-r1');
  16. const out = path.join(base, label || 'docs');
  17. function save(file, value) {
  18. fs.mkdirSync(path.dirname(file), { recursive: true });
  19. let raw = JSON.stringify(value, null, 2);
  20. for (const secret of [credentials.newApiToken, credentials.sessionToken]) {
  21. if (secret) raw = raw.split(secret).join('[REDACTED]');
  22. }
  23. fs.writeFileSync(file, raw + '\n', { flag: 'wx' });
  24. }
  25. const transport = new StdioClientTransport({ command: process.execPath,
  26. args: [path.join(pluginRoot, 'mcp/src/server.js')], cwd: pluginRoot, stderr: 'pipe',
  27. env: { ...process.env, VOC_SKILL_NO_UPDATE_CHECK: '1' } });
  28. transport.stderr?.on('data', () => {});
  29. const client = new Client({ name: 'ksf-direct-review-sampling', version: '1.0.0' });
  30. async function call(name, args, file, timeout = 30000) {
  31. const result = await client.callTool({ name, arguments: args }, undefined, { timeout });
  32. save(file, { request: { name, arguments: args }, response: result });
  33. return result.structuredContent || result;
  34. }
  35. (async () => {
  36. try {
  37. await client.connect(transport, { timeout: 15000 });
  38. if (mode === 'docs') {
  39. for (const id of ['jd.get_item_comments_v1', 'taobao.get_item_comment_v3']) {
  40. const result = await call('voc_api_doc', { id }, path.join(out, id + '.json'));
  41. console.log(JSON.stringify({ endpoint: id, status: result.status,
  42. params: result.data?.endpoint?.params, responseHint: result.data?.endpoint?.responseHint }));
  43. }
  44. return;
  45. }
  46. if (mode === 'usage') {
  47. const reservation = JSON.parse(fs.readFileSync(path.join(out, 'reservation.json'), 'utf8'));
  48. const result = await call('voc_usage_report', { usageTraceId: reservation.usageTraceId,
  49. groupBy: ['usageTraceId', 'module', 'endpoint'], limit: 1000, pageSize: 200, refresh: true },
  50. path.join(out, 'usage-' + Date.now() + '.json'));
  51. console.log(JSON.stringify({ status: result.status, summary: result.summary, data: result.data }));
  52. return;
  53. }
  54. if (mode !== 'call' || !/^[a-z0-9-]+$/.test(label || '') || !['jd', 'taobao'].includes(family)
  55. || !/^\d+$/.test(itemId || '') || !/^\d+$/.test(pageArg)) throw Error('INVALID_ARGUMENTS');
  56. if (!credentials.newApiToken || credentials.sessionToken) throw Error('EXPECTED_EXISTING_SINGLE_AUTH_NO_FALLBACK');
  57. if (fs.existsSync(out)) throw Error('OUTPUT_EXISTS_CHECK_STATUS_DO_NOT_REPEAT');
  58. const reservations = fs.existsSync(base) ? fs.readdirSync(base)
  59. .filter(n => fs.existsSync(path.join(base, n, 'reservation.json'))) : [];
  60. // Operational cap for this limited sample; it does not reset the shared ¥50.
  61. if (reservations.length >= 10) throw Error('TEN_CALL_OPERATIONAL_CAP');
  62. const usageTraceId = 'usage_ksf_reviews_20261106_' + crypto.randomUUID();
  63. const endpoint = family === 'jd' ? 'jd.get_item_comments_v1' : 'taobao.get_item_comment_v3';
  64. const catalog = JSON.parse(fs.readFileSync(path.resolve('work/product-reviews/current/catalog.json'), 'utf8'));
  65. const product = catalog.records.find(r => r.record_id === family + ':' + itemId);
  66. if (!product || product.relatedCounts?.reviews) throw Error('EXPECTED_PRODUCT_WITHOUT_STORED_REVIEWS');
  67. const historical = JSON.parse(fs.readFileSync(path.resolve('work/product-reviews/volume-evidence-r1.json'), 'utf8'));
  68. if (!historical[family + ':' + itemId]?.countText) throw Error('REVIEW_VOLUME_EVIDENCE_REQUIRED');
  69. const params = { itemId, page: family === 'jd' ? pageArg : Number(pageArg) };
  70. if (family === 'taobao') params.orderType = 'general'; // Documented general order, not a likes sort.
  71. for (const previous of reservations) {
  72. const prior = JSON.parse(fs.readFileSync(path.join(base, previous, 'reservation.json'), 'utf8'));
  73. if (prior.endpoint === endpoint && prior.params.itemId === itemId && String(prior.params.page) === pageArg) {
  74. throw Error('REQUEST_ALREADY_RESERVED_OR_EXECUTED_CHECK_RECEIPT_DO_NOT_REPEAT');
  75. }
  76. }
  77. const reservation = { endpoint, params, usageTraceId, maxNewCostCny: 0.30,
  78. maxGatewayRequests: 1, retries: 0, automaticFallback: false,
  79. timestamp: new Date().toISOString(), scope: 'limited_missing_high_volume_product_reviews',
  80. sharedPriorBudgetCny: 50, priorUnreconciledCostsRetained: true,
  81. catalogGeneration: catalog.generation, historicalCountDisplay: historical[family + ':' + itemId].countText };
  82. save(path.join(out, 'reservation.json'), reservation);
  83. console.log(JSON.stringify({ started: true, endpoint, itemId, page: params.page, maxNewCostCny: 0.30, usageTraceId }));
  84. const result = await call('voc_api_call', { id: endpoint, params, retries: 0, usageTraceId,
  85. skillId: 'ksf-review-gap-sampling', outputDir: path.join(out, 'tool-output') },
  86. path.join(out, 'mcp-result.json'), 600000);
  87. console.log(JSON.stringify({ status: result.status, summary: result.summary,
  88. dataKeys: Object.keys(result.data || {}), errors: result.errors }));
  89. } finally {
  90. await client.close();
  91. await transport.close();
  92. }
  93. })().catch(error => {
  94. // Do not echo URLs, headers or credential-bearing error messages.
  95. console.log(JSON.stringify({ ok: false, error: error.name, resultMayBeUncertain: mode === 'call' }));
  96. process.exitCode = 1;
  97. });