@whyshu/argent-engine 0.8.0-rc.8 → 0.13.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/MANIFEST.json +109 -43
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +3 -3
  7. package/engine/core/contracts/verbs.schema.json +64 -1
  8. package/engine/core/lib/account-token.mjs +37 -0
  9. package/engine/core/lib/contract.mjs +30 -0
  10. package/engine/core/lib/redact.mjs +34 -0
  11. package/engine/core/mcp/billing-upload.mjs +77 -0
  12. package/engine/core/mcp/erp-server.mjs +300 -0
  13. package/engine/core/mcp/gateway.mjs +333 -0
  14. package/engine/core/mcp/meter.mjs +101 -0
  15. package/engine/core/mcp/server.mjs +416 -2
  16. package/engine/core/mcp/vault.mjs +78 -0
  17. package/engine/scripts/appointment-worker.mjs +456 -35
  18. package/engine/scripts/appointment_grab.py +1389 -264
  19. package/engine/scripts/appointment_rules.py +118 -0
  20. package/engine/scripts/argent-timers.mjs +227 -0
  21. package/engine/scripts/argent-web-preflight.mjs +123 -0
  22. package/engine/scripts/argent-web-verify.mjs +105 -0
  23. package/engine/scripts/billing-upload.mjs +26 -0
  24. package/engine/scripts/build-doc-index.mjs +68 -0
  25. package/engine/scripts/build-engine-package.mjs +7 -1
  26. package/engine/scripts/capability-packs.lock.json +323 -300
  27. package/engine/scripts/check-docs-drift.mjs +51 -4
  28. package/engine/scripts/check-version-consistency.mjs +14 -1
  29. package/engine/scripts/ci-run.sh +2 -2
  30. package/engine/scripts/collect-intel.mjs +108 -0
  31. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  32. package/engine/scripts/daily-report-timers.sh +36 -3
  33. package/engine/scripts/daily-report.mjs +78 -2
  34. package/engine/scripts/doc-status.mjs +212 -0
  35. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  36. package/engine/scripts/engine-manifest.mjs +90 -0
  37. package/engine/scripts/engine-runtime-install.mjs +92 -0
  38. package/engine/scripts/erp-ui-install.mjs +127 -0
  39. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  40. package/engine/scripts/erp-ui-verify.mjs +135 -0
  41. package/engine/scripts/flow-requirements.json +122 -99
  42. package/engine/scripts/full-exec-worker.mjs +251 -0
  43. package/engine/scripts/gen-preset-rows.mjs +1 -1
  44. package/engine/scripts/invoice_lip_runner.py +1 -0
  45. package/engine/scripts/invoice_runner.py +17 -6
  46. package/engine/scripts/invoice_stageb.py +21 -4
  47. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  48. package/engine/scripts/lib/intel-card.mjs +43 -0
  49. package/engine/scripts/lib/invoice_names.py +23 -0
  50. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  51. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  52. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  53. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  54. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  55. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  56. package/engine/scripts/lib/ml-items.mjs +40 -0
  57. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  58. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  59. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  60. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  61. package/engine/scripts/line_pack.py +196 -0
  62. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  63. package/engine/scripts/migrate-providers.mjs +3 -3
  64. package/engine/scripts/ml-ads-advice.mjs +140 -0
  65. package/engine/scripts/ml-ads.mjs +221 -0
  66. package/engine/scripts/ml-category-baseline.mjs +174 -0
  67. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  68. package/engine/scripts/ml-insight-run.sh +183 -0
  69. package/engine/scripts/ml-insight-timers.sh +224 -0
  70. package/engine/scripts/ml-listing-audit.mjs +170 -0
  71. package/engine/scripts/ml-market-matrix.mjs +84 -0
  72. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  73. package/engine/scripts/ml-messages.mjs +145 -0
  74. package/engine/scripts/ml-oauth-setup.mjs +1 -1
  75. package/engine/scripts/npm-publish-argent.mjs +14 -0
  76. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  77. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  78. package/engine/scripts/ops-digest.mjs +98 -0
  79. package/engine/scripts/ops-verify.mjs +67 -0
  80. package/engine/scripts/orchestrator.py +410 -20
  81. package/engine/scripts/orchestrator_br.py +146 -4
  82. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  83. package/engine/scripts/publish-engine.mjs +111 -0
  84. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  85. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  86. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  87. package/engine/scripts/vertical-lint.mjs +12 -1
  88. package/engine/scripts/web-switch.mjs +121 -0
  89. package/engine/scripts/wenyao_fill_template.py +52 -15
  90. package/engine/scripts/wenyao_run.py +2 -1
  91. package/engine/skills/README.md +3 -3
  92. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  93. package/engine/skills/douyin-upload/SKILL.md +74 -0
  94. package/engine/skills/internal.json +28 -0
  95. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  96. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  97. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  98. package/engine/skills/ml-invoice/SKILL.md +2 -2
  99. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  100. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  101. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  102. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  103. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  104. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  105. package/engine/skills/tencent-upload/SKILL.md +60 -0
  106. package/engine/skills/weibo-upload/SKILL.md +106 -0
  107. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  108. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  109. package/engine/version.mjs +1 -1
  110. package/engine/verticals/README.md +7 -0
  111. package/engine/verticals/_engine-words.baseline.txt +27 -59
  112. package/engine/verticals/mercadolibre/manifest.json +132 -6
  113. package/package.json +5 -1
@@ -19,7 +19,7 @@
19
19
  * 写类 `readOnlyHint:false + destructiveHint:true`),让宿主能在**协议层**分辨只读与写类、
20
20
  * 从而收窄授权面;分类与理由见下方 {@link annotationsFor} 上方的注释块。
21
21
  */
22
- import { execFileSync } from 'node:child_process'
22
+ import { execFileSync, spawn } from 'node:child_process'
23
23
  import { cpSync, existsSync as fExists, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from 'node:fs'
24
24
  import { tmpdir } from 'node:os'
25
25
  import { existsSync, readFileSync } from 'node:fs'
@@ -87,6 +87,35 @@ function parseJsonOut(text) {
87
87
  try { return { ok: true, value: JSON.parse(text) } } catch (e) { return { ok: false, error: `JSON 解析失败:${e.message}` } }
88
88
  }
89
89
 
90
+ /**
91
+ * 跑引擎 node CLI 并解析 `--json`(2026-11-20,零命令化批次 A)。
92
+ * 只读工具专用:调用方自己保证 argv 里没有写类开关;本 helper 不做语义判断。
93
+ * 失败时仍尝试解析 stdout(部分 CLI 是"先打 JSON 再 exit 2")。
94
+ */
95
+ function runNodeJson(argv, { timeoutMs = 120000 } = {}) {
96
+ const parseLoose = (text) => {
97
+ const t = String(text || '').trim()
98
+ if (!t) return null
99
+ try { return JSON.parse(t) } catch { /* 可能前面有日志 */ }
100
+ const i = t.search(/[[{]/)
101
+ if (i < 0) return null
102
+ try { return JSON.parse(t.slice(i)) } catch { return null }
103
+ }
104
+ try {
105
+ const out = execFileSync(process.execPath, argv, { encoding: 'utf8', cwd: REPO, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 })
106
+ return { ok: true, status: 0, json: parseLoose(out), stderr: '' }
107
+ } catch (e) {
108
+ const stderr = String(e.stderr || e.message || '')
109
+ return {
110
+ ok: false,
111
+ status: typeof e.status === 'number' ? e.status : null,
112
+ json: parseLoose(String(e.stdout || '')),
113
+ stderr: stderr.slice(0, 800),
114
+ error: stderr.slice(0, 400),
115
+ }
116
+ }
117
+ }
118
+
90
119
  /** 建一个与真实环境同构的影子沙箱(排除重目录),返回路径。 */
91
120
  function makeShadow() {
92
121
  const dataDir = DATA_DIR
@@ -282,14 +311,31 @@ export function toolScope(name) {
282
311
  * · **未登记的名字 ⇒ 一律按写类回**(fail-safe:宁可多要一次确认,不可少要)。
283
312
  *
284
313
  * ⛔ 纪律:本段只被 `tools/list` 读;**不改**任何 tool 的 handler / `inputSchema` / 返回形状,
285
- * 也**不增删**工具(仍 14 个)。
314
+ * 也**不增删**工具(2026-11-02 起 19 个:新增 `argent_skuflow_run` / `argent_orchestrator_run` 与 job 三件套)。
286
315
  */
287
316
  export const READ_ONLY_TOOLS = Object.freeze([
288
317
  'argent_version', 'argent_license', 'argent_ledger', 'argent_report', 'argent_failures',
289
318
  'argent_sop', 'argent_doctor', 'argent_preflight', 'argent_writeback_audit',
319
+ 'argent_job_status',
320
+ // 2026-11-20(零命令化批次 A):两条只读业务工具(客户在会话里"问一句"即可,不用敲 CLI)
321
+ 'ml_listing_audit', 'ml_market_snapshot',
322
+ // 2026-11-20(批次 A2):系统定时器清单(客户问"定时器都在跑吗")
323
+ 'argent_timers',
324
+ // 2026-11-24(P1 L2):店铺诊断(取数 → 判据/评分 → 信号;只读)
325
+ 'ml_store_diagnose',
326
+ // 2026-11-25(P2a):广告诊断建议单(只读;按毛利算目标 ACoS)
327
+ 'ml_ads_advice',
328
+ // 2026-11-26(P2b):竞品矩阵/趋势(读本地快照,零平台请求)
329
+ 'ml_competitor_matrix',
290
330
  ])
291
331
  export const WRITE_TOOLS = Object.freeze([
292
332
  'argent_claim', 'argent_writeback', 'argent_shadow_compare', 'argent_writeback_shadow', 'argent_claim_shadow',
333
+ // 2026-11-02(方案 C · P2):把"宿主壳直接 spawn 脚本"的两条路径收进协议;
334
+ // 默认 dry-run/只生成,真跑必须 confirm=true。
335
+ 'argent_skuflow_run', 'argent_orchestrator_run',
336
+ // 2026-11-24(0.13 阶段2):箱唛下载会触发平台“生成/下载”动作,按写类保守标注
337
+ 'ml_box_label_download',
338
+ 'argent_job_start', 'argent_job_cancel',
293
339
  ])
294
340
  const READ_ONLY_SET = new Set(READ_ONLY_TOOLS)
295
341
  const WRITE_SET = new Set(WRITE_TOOLS)
@@ -301,6 +347,94 @@ export function annotationsFor(name) {
301
347
  return { readOnlyHint: false, destructiveHint: true }
302
348
  }
303
349
 
350
+ // ── 异步 job(2026-11-02,方案 C · P2 第二步)──────────────────────────────
351
+ // 为什么有:宿主壳原先是自己 spawn python 并持有 child ⇒ 能 kill。
352
+ // 切到 MCP 后同步 `execFileSync` **无法中途取消** ⇒ task_cancel 会退化成"杀连接不杀进程"。
353
+ // 这里补一套最小 job 协议(start / status / cancel),内存态:随 server 进程生灭,不落盘。
354
+ const JOBS = new Map()
355
+ const JOB_MAX_KEEP = 20
356
+ const JOB_OUTPUT_CAP = 64 * 1024
357
+ const JOB_KILL_GRACE_MS = 5000
358
+
359
+ const JOB_KINDS = {
360
+ skuflow: (record, { confirm }) => {
361
+ const argv = ['scripts/skuflow_invoice_runner.py', '--record-json', JSON.stringify(record)]
362
+ if (!confirm) argv.push('--generate-only')
363
+ return argv
364
+ },
365
+ orchestrator: (record, { confirm, step }) => {
366
+ const argv = ['scripts/orchestrator.py', '--record-json', JSON.stringify(record), '--no-lip']
367
+ if (step) argv.push('--mode', 'step', '--step', String(step))
368
+ else argv.push('--mode', confirm ? 'full' : 'dry-run')
369
+ if (confirm) argv.push('--allow-write')
370
+ return argv
371
+ },
372
+ }
373
+
374
+ /** 任务的"最后一行 JSON"(与插件原先解析 stdout 的口径一致) */
375
+ function jobResult(job) {
376
+ const line = String(job.out || '').split('\n').map((x) => x.trim()).filter((x) => x.startsWith('{')).pop() || ''
377
+ if (!line) return null
378
+ try { return JSON.parse(line) } catch { return null }
379
+ }
380
+
381
+ function jobView(job, { withResult = false } = {}) {
382
+ const view = {
383
+ ok: true, jobId: job.id, kind: job.kind, state: job.state, code: job.code,
384
+ dryRun: job.dryRun, startedAt: job.startedAt, endedAt: job.endedAt || null,
385
+ outputTail: String(job.out || '').slice(-2000), errorTail: String(job.err || '').slice(-1000),
386
+ }
387
+ if (withResult && job.state !== 'running') view.result = jobResult(job)
388
+ return view
389
+ }
390
+
391
+ function pruneJobs() {
392
+ const done = [...JOBS.values()].filter((j) => j.state !== 'running' && j.state !== 'cancelling')
393
+ for (const j of done.slice(0, Math.max(0, done.length - JOB_MAX_KEEP))) JOBS.delete(j.id)
394
+ }
395
+
396
+ function startJob({ kind, record, confirm = false, step = null, timeoutMs = 0 }) {
397
+ if (PY_FAILURE) return { ok: false, code: 2, reason: 'python_unavailable', error: PY_FAILURE }
398
+ const build = JOB_KINDS[kind]
399
+ if (!build) return { ok: false, code: 2, error: `未知 kind:${kind}(可选:${Object.keys(JOB_KINDS).join(' / ')})` }
400
+ if (!record || typeof record !== 'object') return { ok: false, code: 2, error: 'record 必须是对象' }
401
+ const argv = [join(REPO, build(record, { confirm, step })[0]), ...build(record, { confirm, step }).slice(1)]
402
+ const id = `job-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
403
+ const child = spawn(PY, argv, { cwd: REPO, env: { ...process.env, PYTHONPATH: 'scripts' }, stdio: ['ignore', 'pipe', 'pipe'] })
404
+ const job = { id, kind, argv, child, state: 'running', code: null, out: '', err: '', dryRun: !confirm, startedAt: new Date().toISOString(), endedAt: '', timer: null }
405
+ child.stdout.on('data', (b) => { job.out = (job.out + b.toString()).slice(-JOB_OUTPUT_CAP) })
406
+ child.stderr.on('data', (b) => { job.err = (job.err + b.toString()).slice(-JOB_OUTPUT_CAP) })
407
+ child.on('error', (e) => { job.state = 'failed'; job.err += String(e && e.message || e); job.endedAt = new Date().toISOString(); clearTimeout(job.timer) })
408
+ child.on('close', (code, signal) => {
409
+ job.code = code
410
+ job.state = signal ? 'cancelled' : (code === 0 ? 'done' : 'failed')
411
+ job.endedAt = new Date().toISOString()
412
+ clearTimeout(job.timer)
413
+ setTimeout(() => { try { job.child.kill('SIGKILL') } catch { /* noop */ } }, 0).unref?.()
414
+ pruneJobs()
415
+ })
416
+ if (timeoutMs > 0) { job.timer = setTimeout(() => cancelJob(id), Math.min(Number(timeoutMs), 30 * 60 * 1000)); job.timer.unref?.() }
417
+ JOBS.set(id, job)
418
+ return { ok: true, jobId: id, kind, pid: child.pid, dryRun: !confirm, startedAt: job.startedAt }
419
+ }
420
+
421
+ function statusJob({ jobId }) {
422
+ const job = JOBS.get(String(jobId || ''))
423
+ if (!job) return { ok: false, code: 2, error: `未知 jobId:${jobId}` }
424
+ return jobView(job, { withResult: true })
425
+ }
426
+
427
+ function cancelJob(jobId) {
428
+ const job = JOBS.get(String(jobId || ''))
429
+ if (!job) return { ok: false, code: 2, error: `未知 jobId:${jobId}` }
430
+ if (job.state !== 'running') return { ok: true, jobId: job.id, state: job.state }
431
+ job.state = 'cancelling'
432
+ try { job.child.kill('SIGTERM') } catch { /* 已退出 */ }
433
+ const t = setTimeout(() => { try { job.child.kill('SIGKILL') } catch { /* noop */ } }, JOB_KILL_GRACE_MS)
434
+ t.unref?.()
435
+ return { ok: true, jobId: job.id, state: 'cancelling' }
436
+ }
437
+
304
438
  const TOOLS = {
305
439
  argent_version: {
306
440
  description: 'Argent 与宿主 dsh 的版本(诊断用)',
@@ -646,8 +780,288 @@ const TOOLS = {
646
780
  : { ok: false, code: r.code, output: r.output.slice(-4000), error: r.error.slice(0, 300) }
647
781
  },
648
782
  },
783
+
784
+ /**
785
+ * SKU 流程发票(原 `office-runtime.js` 的 `spawn(scripts/skuflow_invoice_runner.py)`)。
786
+ * 默认 `--generate-only`(只生成不传),真上传必须 `confirm: true`。
787
+ */
788
+ argent_skuflow_run: {
789
+ description: 'SKU 流程发票:默认只生成(--generate-only);confirm=true 才上传。输入 = ERP 记录对象',
790
+ inputSchema: {
791
+ type: 'object',
792
+ properties: { record: { type: 'object' }, confirm: { type: 'boolean' } },
793
+ required: ['record'], additionalProperties: false,
794
+ },
795
+ handler: ({ record, confirm = false }) => {
796
+ const argv = [join(REPO, 'scripts', 'skuflow_invoice_runner.py'), '--record-json', JSON.stringify(record)]
797
+ if (!confirm) argv.push('--generate-only')
798
+ const r = runPy(argv)
799
+ if (r.reason === 'python_unavailable') return { ok: false, code: 2, reason: 'python_unavailable', error: r.error }
800
+ return { ok: r.ok, code: r.code, dryRun: !confirm, output: String(r.output || '').slice(-4000), error: String(r.error || '').slice(0, 400) }
801
+ },
802
+ },
803
+
804
+ /**
805
+ * FULL 编排器(原 `office-runtime.js` 的 `spawn(scripts/orchestrator.py)`)。
806
+ * 默认 `--mode dry-run --no-lip`(只推演、不写 lip);真跑必须 `confirm: true`(`--allow-write`)。
807
+ */
808
+ argent_orchestrator_run: {
809
+ description: 'FULL 编排器:默认 dry-run + no-lip;confirm=true 才 --allow-write(真写飞书/门户)',
810
+ inputSchema: {
811
+ type: 'object',
812
+ properties: { record: { type: 'object' }, step: { type: 'integer', minimum: 1, maximum: 8 }, confirm: { type: 'boolean' } },
813
+ required: ['record'], additionalProperties: false,
814
+ },
815
+ handler: ({ record, step, confirm = false }) => {
816
+ const argv = [join(REPO, 'scripts', 'orchestrator.py'), '--record-json', JSON.stringify(record), '--no-lip']
817
+ if (step) argv.push('--mode', 'step', '--step', String(step))
818
+ else argv.push('--mode', confirm ? 'full' : 'dry-run')
819
+ if (confirm) argv.push('--allow-write')
820
+ const r = runPy(argv)
821
+ if (r.reason === 'python_unavailable') return { ok: false, code: 2, reason: 'python_unavailable', error: r.error }
822
+ return { ok: r.ok, code: r.code, dryRun: !confirm, step: step || null, output: String(r.output || '').slice(-4000), error: String(r.error || '').slice(0, 400) }
823
+ },
824
+ },
825
+
826
+ /**
827
+ * 只下载箱唛(0.13 阶段2):不预约、不取消、不写飞书/ERP。
828
+ * 引擎侧强制重新下载(force 默认 true);返回本地 PDF 路径 + sha256,供后续 ml_artifact_attach。
829
+ */
830
+ ml_box_label_download: {
831
+ description: '只下载箱唛 PDF:不预约/不取消/不写 ERP;force=true 时跳过 hub 的已下载短路',
832
+ inputSchema: {
833
+ type: 'object',
834
+ properties: {
835
+ storeName: { type: 'string', description: '紫鸟店铺名(如 墨西哥-2店-子账号)' },
836
+ shipmentId: { type: 'string', description: '货件号' },
837
+ boxCount: { type: 'integer', minimum: 1, description: '箱数(箱唛页声明数量)' },
838
+ force: { type: 'boolean', description: '默认 true:hub 已显示下载完成也强制重新下载' },
839
+ },
840
+ required: ['storeName', 'shipmentId', 'boxCount'], additionalProperties: false,
841
+ },
842
+ handler: ({ storeName, shipmentId, boxCount, force = true }) => {
843
+ const argv = [join(REPO, 'scripts', 'orchestrator.py'), '--mode', 'download-box-label',
844
+ '--store-name', String(storeName), '--shipment-id', String(shipmentId), '--box', String(boxCount)]
845
+ if (force) argv.push('--force')
846
+ const r = runPy(argv)
847
+ if (r.reason === 'python_unavailable') return { ok: false, code: 2, reason: 'python_unavailable', error: r.error }
848
+ const last = String(r.output || '').trim().split('\n').filter(Boolean).pop() || ''
849
+ const parsed = parseJsonOut(last)
850
+ return { ok: r.ok && parsed.ok && parsed.value && parsed.value.status === 'ok',
851
+ code: r.code, result: parsed.ok ? parsed.value : null,
852
+ error: parsed.ok ? '' : String(r.error || last || '').slice(0, 500) }
853
+ },
854
+ },
855
+
856
+ /** 异步任务:启动(宿主壳用它替代直接 spawn;可取消) */
857
+ argent_job_start: {
858
+ description: '异步任务:启动 skuflow / orchestrator(返回 jobId,可 status/cancel;默认 dry-run,confirm=true 才真跑)',
859
+ inputSchema: {
860
+ type: 'object',
861
+ properties: {
862
+ kind: { type: 'string', enum: ['skuflow', 'orchestrator'] },
863
+ record: { type: 'object' },
864
+ confirm: { type: 'boolean' },
865
+ step: { type: 'integer', minimum: 1, maximum: 8 },
866
+ timeoutMs: { type: 'integer' },
867
+ },
868
+ required: ['kind', 'record'], additionalProperties: false,
869
+ },
870
+ handler: (a) => startJob(a),
871
+ },
872
+
873
+ /** 异步任务:查状态(只读) */
874
+ argent_job_status: {
875
+ description: '异步任务状态:state / code / outputTail / result(done|failed|cancelled|running|cancelling)',
876
+ inputSchema: { type: 'object', properties: { jobId: { type: 'string' } }, required: ['jobId'], additionalProperties: false },
877
+ handler: (a) => statusJob(a),
878
+ },
879
+
880
+ // ── 2026-11-20(零命令化批次 A):业务只读工具 ─────────────────────────────
881
+ // 客户面是"在 dsh 里说一句话/点一下",不是敲命令;这里是 CLI 的**只读**工具化封装。
882
+ // 两者都只发 GET(listing 读官方质量分;market 读 item 详情),⛔ 不改客户任何商品/系统;
883
+ // market 唯一本地写 = 快照 JSONL(历史用,业务产物)。
884
+ ml_listing_audit: {
885
+ description: 'Listing 体检(只读):官方 /item/{id}/performance 的质量分 + 中文整改项;按店抽样,不改任何商品',
886
+ inputSchema: {
887
+ type: 'object',
888
+ properties: {
889
+ store: { type: 'string' },
890
+ limit: { type: 'integer', minimum: 1, maximum: 50 },
891
+ offset: { type: 'integer', minimum: 0 },
892
+ },
893
+ additionalProperties: false,
894
+ },
895
+ handler: ({ store = '', limit = 10, offset = 0 } = {}) => {
896
+ const argv = [join(REPO, 'scripts', 'ml-listing-audit.mjs'), '--json', '--limit', String(Math.max(1, Math.min(50, Number(limit) || 10)))]
897
+ if (offset) argv.push('--offset', String(Math.max(0, Number(offset) || 0)))
898
+ if (store) argv.push('--store', String(store))
899
+ const r = runNodeJson(argv, { timeoutMs: 180000 })
900
+ if (!r.ok && !r.json) return { ok: false, code: r.status ?? 1, error: r.error || 'listing audit 失败' }
901
+ const doc = r.json || {}
902
+ const results = Array.isArray(doc.results) ? doc.results : []
903
+ // 只回摘要 + 最差 N 个(避免把上百条塞回会话;客户要看全量去 ERP 页)
904
+ return {
905
+ ok: true,
906
+ generatedAt: doc.generatedAt || null,
907
+ stores: results.map((x) => ({
908
+ store: x.store, site: x.site, error: x.error || '',
909
+ summary: x.summary || null,
910
+ worst: [...(x.items || [])]
911
+ .sort((a, b) => (a.score == null ? 999 : a.score) - (b.score == null ? 999 : b.score))
912
+ .slice(0, 5)
913
+ .map((it) => ({ id: it.id, title: it.title, score: it.score, grade: it.grade, pendingCount: it.pendingCount, actions: (it.actions || []).slice(0, 3) })),
914
+ })),
915
+ }
916
+ },
917
+ },
918
+
919
+ ml_market_snapshot: {
920
+ description: '市场快照(只读):自有在售 + 客户指定竞品 ID 的价格/评分/分桶已售库存 → 本地 JSONL;不改客户任何系统',
921
+ inputSchema: {
922
+ type: 'object',
923
+ properties: {
924
+ store: { type: 'string' },
925
+ itemsFile: { type: 'string' },
926
+ days: { type: 'integer', minimum: 1, maximum: 180 },
927
+ limit: { type: 'integer', minimum: 1, maximum: 200 },
928
+ },
929
+ additionalProperties: false,
930
+ },
931
+ handler: ({ store = '', itemsFile = '', days = 30, limit = 50 } = {}) => {
932
+ const argv = [join(REPO, 'scripts', 'ml-market-snapshot.mjs'), '--json',
933
+ '--days', String(Math.max(1, Math.min(180, Number(days) || 30))),
934
+ '--limit', String(Math.max(1, Math.min(200, Number(limit) || 50)))]
935
+ if (store) argv.push('--store', String(store))
936
+ if (itemsFile) argv.push('--items-file', String(itemsFile))
937
+ const r = runNodeJson(argv, { timeoutMs: 240000 })
938
+ if (!r.ok && !r.json) return { ok: false, code: r.status ?? 1, error: r.error || 'market snapshot 失败' }
939
+ const doc = r.json || {}
940
+ return {
941
+ ok: true,
942
+ caliber: doc.caliber || null,
943
+ generatedAt: doc.generatedAt || null,
944
+ stores: (Array.isArray(doc.results) ? doc.results : []).map((x) => ({
945
+ store: x.store, site: x.site, out: x.out || '', error: x.error || '',
946
+ summary: x.summary || null,
947
+ estimates: (x.estimates || []).slice(0, 10),
948
+ })),
949
+ }
950
+ },
951
+ },
952
+
953
+ argent_timers: {
954
+ description: '系统定时器清单(只读):launchctl 在册 + plist 排程 + 状态文件(worker/日报/Listing 体检/竞品快照/退役残留)',
955
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
956
+ handler: () => {
957
+ const r = runNodeJson([join(REPO, 'scripts', 'argent-timers.mjs'), '--json'], { timeoutMs: 20000 })
958
+ if (!r.json) return { ok: false, error: r.error || '定时器清单读取失败' }
959
+ return r.json
960
+ },
961
+ },
962
+
963
+ ml_competitor_matrix: {
964
+ description: '竞品矩阵/趋势(只读):自有 vs 竞品价格/评分/分桶销量/趋势(从接入日起算;销量为估算档位);不新增平台请求',
965
+ inputSchema: { type: 'object', properties: { store: { type: 'string' }, days: { type: 'integer', minimum: 1, maximum: 180 } }, additionalProperties: false },
966
+ handler: ({ store = '', days = 30 } = {}) => {
967
+ const argv = [join(REPO, 'scripts', 'ml-market-matrix.mjs'), '--json', '--days', String(Math.max(1, Math.min(180, Number(days) || 30)))]
968
+ if (store) argv.push('--store', String(store))
969
+ const r = runNodeJson(argv, { timeoutMs: 60000 })
970
+ if (!r.json) return { ok: false, error: r.error || '竞品矩阵失败' }
971
+ return { ok: true, stores: (r.json.results || []).map((x) => ({ store: x.store, site: x.site, error: x.error || '', summary: x.matrix && x.matrix.summary, items: ((x.matrix && x.matrix.items) || []).slice(0, 20).map((i) => ({ id: i.id, role: i.role, price: i.price, priceDeltaPct: i.priceDeltaPct, rating: i.rating, ratingDelta: i.ratingDelta, soldBucket: i.soldBucket })) })) }
972
+ },
973
+ },
974
+
975
+ ml_ads_advice: {
976
+ description: '广告诊断建议(只读):按毛利结构算可承受 ACoS,输出零转化/ACoS 超标/活动浪费/集中度/漏斗建议;不改预算',
977
+ inputSchema: {
978
+ type: 'object',
979
+ properties: {
980
+ store: { type: 'string' },
981
+ days: { type: 'integer', minimum: 1, maximum: 90 },
982
+ targetAcos: { type: 'number' },
983
+ margin: { type: 'number' },
984
+ minSpend: { type: 'number' },
985
+ },
986
+ additionalProperties: false,
987
+ },
988
+ handler: ({ store = '', days = 7, targetAcos = null, margin = null, minSpend = null } = {}) => {
989
+ const argv = [join(REPO, 'scripts', 'ml-ads-advice.mjs'), '--json', '--days', String(Math.max(1, Math.min(90, Number(days) || 7)))]
990
+ if (store) argv.push('--store', String(store))
991
+ if (targetAcos != null) argv.push('--target-acos', String(targetAcos))
992
+ if (margin != null) argv.push('--margin', String(margin))
993
+ if (minSpend != null) argv.push('--min-spend', String(minSpend))
994
+ const r = runNodeJson(argv, { timeoutMs: 240000 })
995
+ if (!r.json) return { ok: false, error: r.error || '广告诊断失败' }
996
+ return {
997
+ ok: true,
998
+ generatedAt: r.json.generatedAt || null,
999
+ target: r.json.config ? { targetAcos: r.json.config.targetAcos, marginRate: r.json.config.marginRate } : null,
1000
+ stores: (r.json.results || []).map((x) => ({
1001
+ store: x.store, site: x.site, error: x.error || '', window: x.window || null,
1002
+ summary: x.diagnosis && x.diagnosis.summary,
1003
+ target: x.diagnosis && x.diagnosis.target,
1004
+ findings: ((x.diagnosis && x.diagnosis.findings) || []).map((f) => ({
1005
+ ruleId: f.ruleId, level: f.level, scope: f.scope, campaignId: f.campaignId || '', campaignName: f.campaignName || '',
1006
+ metric: f.metric, value: f.value, threshold: f.threshold, action: f.action && f.action.text, estimated: f.estimated || null,
1007
+ })),
1008
+ missing: (x.diagnosis && x.diagnosis.missing) || [],
1009
+ })),
1010
+ }
1011
+ },
1012
+ },
1013
+
1014
+ ml_store_diagnose: {
1015
+ description: '店铺诊断(只读):取数→判据/评分→信号与缺数据(含归因/建议/证据链);不改任何商品',
1016
+ inputSchema: {
1017
+ type: 'object',
1018
+ properties: {
1019
+ store: { type: 'string' },
1020
+ days: { type: 'integer', minimum: 1, maximum: 28 },
1021
+ visitLimit: { type: 'integer', minimum: 1, maximum: 50 },
1022
+ priceLimit: { type: 'integer', minimum: 1, maximum: 50 },
1023
+ listingLimit: { type: 'integer', minimum: 1, maximum: 50 },
1024
+ },
1025
+ additionalProperties: false,
1026
+ },
1027
+ handler: ({ store = '', days = 7, visitLimit = 20, priceLimit = 10, listingLimit = 20 } = {}) => {
1028
+ const argv = [join(REPO, 'scripts', 'ml-insight-diagnose.mjs'), '--json',
1029
+ '--days', String(Math.max(1, Math.min(28, Number(days) || 7))),
1030
+ '--visit-limit', String(Math.max(1, Math.min(50, Number(visitLimit) || 20))),
1031
+ '--price-limit', String(Math.max(1, Math.min(50, Number(priceLimit) || 10))),
1032
+ '--listing-limit', String(Math.max(1, Math.min(50, Number(listingLimit) || 20)))]
1033
+ if (store) argv.push('--store', String(store))
1034
+ const r = runNodeJson(argv, { timeoutMs: 300000 })
1035
+ if (!r.json) return { ok: false, error: r.error || '店铺诊断失败' }
1036
+ return {
1037
+ ok: true,
1038
+ generatedAt: r.json.generatedAt || null,
1039
+ stores: (r.json.results || []).map((x) => ({
1040
+ store: x.store, site: x.site, error: x.error || '',
1041
+ score: x.diagnosis && x.diagnosis.score,
1042
+ grade: x.diagnosis && x.diagnosis.grade,
1043
+ dims: x.diagnosis && Object.fromEntries(Object.entries(x.diagnosis.dims || {}).map(([k, v]) => [k, { score: v.score, status: v.status }])),
1044
+ signals: ((x.diagnosis && x.diagnosis.signals) || []).map((s) => ({
1045
+ id: s.id, level: s.level, confidence: s.confidence, metric: s.metric, delta: s.delta,
1046
+ why: (s.attributions || []).map((a) => a.code), actions: (s.actions || []).map((a) => a.text),
1047
+ })),
1048
+ missing: (x.diagnosis && x.diagnosis.missing) || [],
1049
+ })),
1050
+ }
1051
+ },
1052
+ },
1053
+
1054
+ /** 异步任务:取消(写类:会发信号) */
1055
+ argent_job_cancel: {
1056
+ description: '异步任务取消:SIGTERM,5s 后 SIGKILL(幂等:已结束的任务返回其终态)',
1057
+ inputSchema: { type: 'object', properties: { jobId: { type: 'string' } }, required: ['jobId'], additionalProperties: false },
1058
+ handler: (a) => cancelJob(a.jobId),
1059
+ },
649
1060
  }
650
1061
 
1062
+ /** 工具名的只读清单(给宿主做兼容性矩阵/契约校验用;⛔ 不要手写第二份) */
1063
+ export const TOOL_NAMES = Object.freeze(Object.keys(TOOLS))
1064
+
651
1065
  const send = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`)
652
1066
  const reply = (id, result) => send({ jsonrpc: '2.0', id, result })
653
1067
  const fail = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } })
@@ -0,0 +1,78 @@
1
+ /**
2
+ * vault.mjs —— 代号 ↔ 真名(脱敏用,**只存本机**)
3
+ *
4
+ * 为什么要它:把"六禾园"这类实体名换成 `[客户A]` 再进模型,模型推理正常但看不到真名;
5
+ * 需要展示真名时在**本地**回填(rehydrate)。映射表落 `<dataDir>/gateway/vault.json`(0600)。
6
+ *
7
+ * 红线:
8
+ * · ⛔ 只落本机,绝不进事件/审计/上报(审计只记"脱敏了几个实体");
9
+ * · token 形状固定 `[<kind>字母]`,同值同 token(稳定,便于模型在上下文中指代);
10
+ * · kind 各自独立计数(客户A / 店铺A 不串号)。
11
+ */
12
+ import { existsSync, mkdirSync, readFileSync, chmodSync, openSync, closeSync, writeSync } from 'node:fs'
13
+ import { join } from 'node:path'
14
+
15
+ const KIND_PREFIX = { customer: '客户', company: '客户', store: '店铺', user: '人员', item: '商品' }
16
+
17
+ export function loadVault(dataDir) {
18
+ const file = join(dataDir, 'gateway', 'vault.json')
19
+ if (existsSync(file)) {
20
+ try {
21
+ const j = JSON.parse(readFileSync(file, 'utf8'))
22
+ return { file, counters: j.counters || {}, byValue: j.byValue || {}, byToken: j.byToken || {} }
23
+ } catch { /* 坏文件 ⇒ 重建(不静默丢:下面 save 时会覆盖) */ }
24
+ }
25
+ return { file, counters: {}, byValue: {}, byToken: {} }
26
+ }
27
+
28
+ export function saveVault(vault) {
29
+ const { file, counters, byValue, byToken } = vault
30
+ mkdirSync(file.slice(0, file.lastIndexOf('/')), { recursive: true })
31
+ const fd = openSync(file, 'w', 0o600)
32
+ writeSync(fd, JSON.stringify({ counters, byValue, byToken }, null, 0))
33
+ closeSync(fd)
34
+ try { chmodSync(file, 0o600) } catch { /* noop */ }
35
+ }
36
+
37
+ /** 把实体名换成稳定代号;空值/短值不处理 */
38
+ export function tokenize(vault, kind, value) {
39
+ const raw = String(value || '').trim()
40
+ if (!raw || raw.length < 2) return raw
41
+ const key = `${kind}:${raw}`
42
+ if (vault.byValue[key]) return vault.byValue[key]
43
+ const prefix = KIND_PREFIX[kind] || '实体'
44
+ const n = (vault.counters[kind] || 0) + 1
45
+ vault.counters[kind] = n
46
+ const letter = String.fromCharCode(64 + ((n - 1) % 26) + 1)
47
+ const token = `[${prefix}${letter}${n > 26 ? Math.ceil(n / 26) : ''}]`
48
+ vault.byValue[key] = token
49
+ vault.byToken[token] = raw
50
+ return token
51
+ }
52
+
53
+ /** 文本里出现代号就换回真名(只在本地展示时用) */
54
+ export function rehydrate(vault, text) {
55
+ let out = String(text || '')
56
+ for (const [token, real] of Object.entries(vault.byToken)) {
57
+ if (out.includes(token)) out = out.split(token).join(real)
58
+ }
59
+ return out
60
+ }
61
+
62
+ /** 按字段名把对象里的实体名换成代号(浅层递归,命中即换) */
63
+ export function tokenizeEntities(vault, obj, fields = /^(customer|company|buyer|contact|user|owner|store|shop)Name$/i) {
64
+ if (Array.isArray(obj)) return obj.map((v) => tokenizeEntities(vault, v, fields))
65
+ if (obj && typeof obj === 'object') {
66
+ const out = {}
67
+ for (const [k, v] of Object.entries(obj)) {
68
+ if (fields.test(k) && typeof v === 'string') {
69
+ const kind = /^(store|shop)Name$/i.test(k) ? 'store' : /^(contact|user|owner)Name$/i.test(k) ? 'user' : 'customer'
70
+ out[k] = tokenize(vault, kind, v)
71
+ continue
72
+ }
73
+ out[k] = tokenizeEntities(vault, v, fields)
74
+ }
75
+ return out
76
+ }
77
+ return obj
78
+ }