@whyshu/argent-engine 0.8.0-rc.9 → 0.13.28

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 (106) hide show
  1. package/MANIFEST.json +102 -40
  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 +2 -2
  7. package/engine/core/lib/account-token.mjs +37 -0
  8. package/engine/core/lib/redact.mjs +34 -0
  9. package/engine/core/mcp/billing-upload.mjs +77 -0
  10. package/engine/core/mcp/erp-server.mjs +300 -0
  11. package/engine/core/mcp/gateway.mjs +333 -0
  12. package/engine/core/mcp/meter.mjs +101 -0
  13. package/engine/core/mcp/server.mjs +245 -0
  14. package/engine/core/mcp/vault.mjs +78 -0
  15. package/engine/scripts/appointment-worker.mjs +456 -35
  16. package/engine/scripts/appointment_grab.py +1389 -264
  17. package/engine/scripts/appointment_rules.py +118 -0
  18. package/engine/scripts/argent-timers.mjs +227 -0
  19. package/engine/scripts/argent-web-preflight.mjs +123 -0
  20. package/engine/scripts/argent-web-verify.mjs +105 -0
  21. package/engine/scripts/billing-upload.mjs +26 -0
  22. package/engine/scripts/build-engine-package.mjs +7 -1
  23. package/engine/scripts/capability-packs.lock.json +323 -300
  24. package/engine/scripts/check-version-consistency.mjs +14 -1
  25. package/engine/scripts/collect-intel.mjs +108 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  27. package/engine/scripts/daily-report-timers.sh +36 -3
  28. package/engine/scripts/daily-report.mjs +78 -2
  29. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  30. package/engine/scripts/engine-manifest.mjs +90 -0
  31. package/engine/scripts/engine-runtime-install.mjs +92 -0
  32. package/engine/scripts/erp-ui-install.mjs +127 -0
  33. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  34. package/engine/scripts/erp-ui-verify.mjs +135 -0
  35. package/engine/scripts/flow-requirements.json +122 -99
  36. package/engine/scripts/full-exec-worker.mjs +251 -0
  37. package/engine/scripts/gen-preset-rows.mjs +1 -1
  38. package/engine/scripts/invoice_lip_runner.py +1 -0
  39. package/engine/scripts/invoice_runner.py +17 -6
  40. package/engine/scripts/invoice_stageb.py +21 -4
  41. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  42. package/engine/scripts/lib/intel-card.mjs +43 -0
  43. package/engine/scripts/lib/invoice_names.py +23 -0
  44. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  45. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  46. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  47. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  48. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  49. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  50. package/engine/scripts/lib/ml-items.mjs +40 -0
  51. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  52. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  53. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  54. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  55. package/engine/scripts/line_pack.py +196 -0
  56. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  57. package/engine/scripts/migrate-providers.mjs +3 -3
  58. package/engine/scripts/ml-ads-advice.mjs +140 -0
  59. package/engine/scripts/ml-ads.mjs +40 -0
  60. package/engine/scripts/ml-category-baseline.mjs +174 -0
  61. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  62. package/engine/scripts/ml-insight-run.sh +183 -0
  63. package/engine/scripts/ml-insight-timers.sh +224 -0
  64. package/engine/scripts/ml-listing-audit.mjs +170 -0
  65. package/engine/scripts/ml-market-matrix.mjs +84 -0
  66. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  67. package/engine/scripts/ml-messages.mjs +145 -0
  68. package/engine/scripts/npm-publish-argent.mjs +14 -0
  69. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  70. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  71. package/engine/scripts/ops-digest.mjs +98 -0
  72. package/engine/scripts/ops-verify.mjs +67 -0
  73. package/engine/scripts/orchestrator.py +410 -20
  74. package/engine/scripts/orchestrator_br.py +146 -4
  75. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  76. package/engine/scripts/publish-engine.mjs +111 -0
  77. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  78. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  79. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  80. package/engine/scripts/vertical-lint.mjs +12 -1
  81. package/engine/scripts/web-switch.mjs +121 -0
  82. package/engine/scripts/wenyao_fill_template.py +52 -15
  83. package/engine/scripts/wenyao_run.py +2 -1
  84. package/engine/skills/README.md +3 -3
  85. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  86. package/engine/skills/douyin-upload/SKILL.md +74 -0
  87. package/engine/skills/internal.json +28 -0
  88. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  89. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  90. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  91. package/engine/skills/ml-invoice/SKILL.md +2 -2
  92. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  93. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  94. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  95. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  96. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  97. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  98. package/engine/skills/tencent-upload/SKILL.md +60 -0
  99. package/engine/skills/weibo-upload/SKILL.md +106 -0
  100. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  101. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  102. package/engine/version.mjs +1 -1
  103. package/engine/verticals/README.md +7 -0
  104. package/engine/verticals/_engine-words.baseline.txt +27 -59
  105. package/engine/verticals/mercadolibre/manifest.json +132 -6
  106. package/package.json +5 -1
@@ -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
@@ -288,12 +317,24 @@ 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',
290
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',
291
330
  ])
292
331
  export const WRITE_TOOLS = Object.freeze([
293
332
  'argent_claim', 'argent_writeback', 'argent_shadow_compare', 'argent_writeback_shadow', 'argent_claim_shadow',
294
333
  // 2026-11-02(方案 C · P2):把"宿主壳直接 spawn 脚本"的两条路径收进协议;
295
334
  // 默认 dry-run/只生成,真跑必须 confirm=true。
296
335
  'argent_skuflow_run', 'argent_orchestrator_run',
336
+ // 2026-11-24(0.13 阶段2):箱唛下载会触发平台“生成/下载”动作,按写类保守标注
337
+ 'ml_box_label_download',
297
338
  'argent_job_start', 'argent_job_cancel',
298
339
  ])
299
340
  const READ_ONLY_SET = new Set(READ_ONLY_TOOLS)
@@ -782,6 +823,36 @@ const TOOLS = {
782
823
  },
783
824
  },
784
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
+
785
856
  /** 异步任务:启动(宿主壳用它替代直接 spawn;可取消) */
786
857
  argent_job_start: {
787
858
  description: '异步任务:启动 skuflow / orchestrator(返回 jobId,可 status/cancel;默认 dry-run,confirm=true 才真跑)',
@@ -806,6 +877,180 @@ const TOOLS = {
806
877
  handler: (a) => statusJob(a),
807
878
  },
808
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
+
809
1054
  /** 异步任务:取消(写类:会发信号) */
810
1055
  argent_job_cancel: {
811
1056
  description: '异步任务取消:SIGTERM,5s 后 SIGKILL(幂等:已结束的任务返回其终态)',
@@ -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
+ }