@whyshu/argent-engine 0.8.0-rc.9 → 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 (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
@@ -0,0 +1,333 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * gateway.mjs —— Argent MCP 网关(stdio)
4
+ *
5
+ * 为什么要有它(2026-11-03 决策):
6
+ * 客户机 profile 里现在挂着 2 条 MCP(`mcp-argent-engine` + `mcp-argent-ml`),ERP 那套 15 个
7
+ * officeTools 还困在服务端 —— 工具面散在 3 处。网关把它们收成**一个 endpoint**,
8
+ * 并在同一个进程里做:路由 / 审计 / 计量 / 脱敏钩子 / 上游降级。
9
+ *
10
+ * 设计要点:
11
+ * · **不重写工具**:每个上游仍是独立进程(engine 用 core/mcp/server.mjs,ERP 用 erp-server.mjs),
12
+ * 网关只做 JSON-RPC 转发 + 命名空间前缀(`engine.*` / `erp.*` / `ml.*`)。
13
+ * · **上游挂了不拖垮网关**:某个上游起不来 ⇒ 它的工具不出现在 tools/list,调用返回结构化错误。
14
+ * · **审计/计量只记事件**:`<dataDir>/gateway/audit.jsonl`(工具/耗时/ok)与
15
+ * `events.jsonl`(可计费动作)。⛔ 不记参数与结果正文。
16
+ * · stdio 传输(dsh-mcp-client 已支持);HTTP 常驻版本下一步在 core/mcp/http.mjs 的基础上加。
17
+ *
18
+ * 用法(dsh profile insert 时指向本文件即可):
19
+ * command: <node> args: [<repo>/core/mcp/gateway.mjs]
20
+ * 环境变量:
21
+ * ARGENT_DATA_DIR 审计/计量落盘根(默认 ~/.dsh/argent)
22
+ * ARGENT_GATEWAY_ML=1 额外挂 ml 上游(需要 python + tools/agentic/mcp_server.py)
23
+ * ARGENT_GATEWAY_NOPREFIX=1 不加上游前缀(调试用)
24
+ */
25
+ import { spawn } from 'node:child_process'
26
+ import { appendEvent, loadIdemSet } from './meter.mjs'
27
+ import { loadVault, saveVault, tokenizeEntities } from './vault.mjs'
28
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
29
+ import { homedir } from 'node:os'
30
+ import { dirname, join, resolve } from 'node:path'
31
+ import { fileURLToPath } from 'node:url'
32
+
33
+ const HERE = dirname(fileURLToPath(import.meta.url))
34
+ const REPO = resolve(HERE, '..', '..')
35
+ const DATA_DIR = process.env.ARGENT_DATA_DIR || join(homedir(), '.dsh', 'argent')
36
+ const GATEWAY_DIR = join(DATA_DIR, 'gateway')
37
+ const NO_PREFIX = process.env.ARGENT_GATEWAY_NOPREFIX === '1'
38
+ const SERVER_INFO = { name: 'argent-gateway', version: readFileSync(new URL('../../VERSION', import.meta.url), 'utf8').trim() || '0.0.0' }
39
+
40
+ /**
41
+ * 结果脱敏(代号化):把实体名换成 `[客户A]` 之类再交给模型。
42
+ * 只在 `ARGENT_GATEWAY_VAULT=1` 时启用;映射表落本机 vault.json(0600),⛔ 不上报。
43
+ * @returns {{text:string, tokens:number}}
44
+ */
45
+ export function applyVaultToText(vault, text) {
46
+ try {
47
+ const j = JSON.parse(text)
48
+ const before = Object.keys(vault.byToken).length
49
+ const out = tokenizeEntities(vault, j)
50
+ const tokens = Object.keys(vault.byToken).length - before
51
+ if (tokens > 0) saveVault(vault)
52
+ return { text: JSON.stringify(out), tokens }
53
+ } catch {
54
+ return { text, tokens: 0 }
55
+ }
56
+ }
57
+
58
+ /** 结果是否算"成功":MCP isError 之外,还要看工具自己返回的 `{"ok":false,...}`(如写开关未开) */
59
+ export function resultOk(res) {
60
+ if (!res || res.isError) return false
61
+ try {
62
+ const text = res.content && res.content[0] && res.content[0].text
63
+ if (typeof text === 'string') {
64
+ const j = JSON.parse(text)
65
+ if (j && j.ok === false) return false
66
+ }
67
+ } catch { /* 非 JSON 结果照常算成功 */ }
68
+ return true
69
+ }
70
+
71
+ /** 只读工具名(不计费)——按语义后缀判,不维护第二份清单 */
72
+ export function isReadOnlyTool(name) {
73
+ return /(^|[._])(search|list|detail|status|info|snapshot|dashboard|version|license|ledger|sop|doctor|report|failures|preflight|audit|tenant_info|prepare_action)(_|$)/.test(String(name || ''))
74
+ }
75
+
76
+ export class Upstream {
77
+ constructor(id, cmd, args, env = {}) {
78
+ this.id = id
79
+ this.pending = new Map()
80
+ this.nextId = 1
81
+ this.buf = ''
82
+ this.tools = []
83
+ this.alive = false
84
+ this.child = spawn(cmd, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, ...env } })
85
+ this.child.stdout.setEncoding('utf8')
86
+ this.child.stdout.on('data', (c) => this._onData(c))
87
+ this.child.stderr.on('data', (c) => process.stderr.write(`[${id}] ${c}`))
88
+ this.child.on('exit', (code) => { this.alive = false; for (const p of this.pending.values()) p.reject(new Error(`${id} upstream exited (${code})`)); this.pending.clear() })
89
+ this.alive = true
90
+ }
91
+
92
+ _onData(chunk) {
93
+ this.buf += chunk
94
+ let i
95
+ while ((i = this.buf.indexOf('\n')) >= 0) {
96
+ const line = this.buf.slice(0, i).trim(); this.buf = this.buf.slice(i + 1)
97
+ if (!line) continue
98
+ let msg; try { msg = JSON.parse(line) } catch { continue }
99
+ const p = this.pending.get(msg.id)
100
+ if (!p) continue
101
+ this.pending.delete(msg.id)
102
+ if (msg.error) p.reject(new Error(msg.error.message || 'upstream error'))
103
+ else p.resolve(msg.result)
104
+ }
105
+ }
106
+
107
+ rpc(method, params, timeoutMs = 60000) {
108
+ const id = this.nextId++
109
+ return new Promise((res, rej) => {
110
+ const t = setTimeout(() => { this.pending.delete(id); rej(new Error(`${this.id} timeout after ${timeoutMs}ms`)) }, timeoutMs)
111
+ t.unref?.()
112
+ this.pending.set(id, {
113
+ resolve: (v) => { clearTimeout(t); res(v) },
114
+ reject: (e) => { clearTimeout(t); rej(e) },
115
+ })
116
+ this.child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)
117
+ })
118
+ }
119
+
120
+ async init() {
121
+ await this.rpc('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: SERVER_INFO })
122
+ this.child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`)
123
+ const t = await this.rpc('tools/list', {})
124
+ this.tools = (t && t.tools) || []
125
+ return this.tools
126
+ }
127
+
128
+ call(name, args) { return this.rpc('tools/call', { name, arguments: args }, 180000) }
129
+ close() { try { this.child.kill('SIGTERM') } catch { /* noop */ } }
130
+ }
131
+
132
+ function audit(row) {
133
+ try {
134
+ mkdirSync(GATEWAY_DIR, { recursive: true })
135
+ appendFileSync(join(GATEWAY_DIR, 'audit.jsonl'), JSON.stringify({ at: new Date().toISOString(), ...row }) + '\n')
136
+ } catch { /* 审计写失败不影响调用 */ }
137
+ }
138
+
139
+ export class Gateway {
140
+ constructor({ upstreams } = {}) {
141
+ this.upstreams = upstreams || Gateway.defaultUpstreams()
142
+ this.routes = new Map() // 对外工具名 → {up, name}
143
+ this.ready = false
144
+ this.idemSet = loadIdemSet(DATA_DIR)
145
+ this.vault = process.env.ARGENT_GATEWAY_VAULT === '1' ? loadVault(DATA_DIR) : null
146
+ }
147
+
148
+ static defaultUpstreams() {
149
+ const ups = [new Upstream('engine', process.execPath, [join(REPO, 'core', 'mcp', 'server.mjs')])]
150
+ if (existsSync(join(REPO, 'core', 'mcp', 'erp-server.mjs'))) {
151
+ ups.push(new Upstream('erp', process.execPath, [join(REPO, 'core', 'mcp', 'erp-server.mjs')]))
152
+ }
153
+ if (process.env.ARGENT_GATEWAY_ML === '1') {
154
+ const py = process.env.ARGENT_ENGINE_PY || join(DATA_DIR, 'venv', 'bin', 'python3')
155
+ const srv = join(REPO, 'tools', 'agentic', 'mcp_server.py')
156
+ if (existsSync(py) && existsSync(srv)) ups.push(new Upstream('ml', py, [srv], { PYTHONPATH: join(REPO, 'scripts') }))
157
+ }
158
+ return ups
159
+ }
160
+
161
+ async start() {
162
+ for (const up of this.upstreams) {
163
+ try {
164
+ const tools = await up.init()
165
+ for (const t of tools) {
166
+ const exposed = NO_PREFIX ? t.name : `${up.id}.${t.name}`
167
+ this.routes.set(exposed, { up, name: t.name, tool: t })
168
+ }
169
+ } catch (e) {
170
+ process.stderr.write(`[gateway] 上游 ${up.id} 不可用(跳过):${String(e.message).slice(0, 160)}\n`)
171
+ }
172
+ }
173
+ this.ready = true
174
+ return this.listTools()
175
+ }
176
+
177
+ listTools() {
178
+ const out = []
179
+ for (const [exposed, r] of this.routes) {
180
+ out.push({
181
+ name: exposed,
182
+ description: r.tool.description || '',
183
+ inputSchema: r.tool.inputSchema || { type: 'object', properties: {} },
184
+ annotations: r.tool.annotations || (isReadOnlyTool(exposed) ? { readOnlyHint: true } : { readOnlyHint: false, destructiveHint: true }),
185
+ })
186
+ }
187
+ return out
188
+ }
189
+
190
+ async call(exposed, args = {}) {
191
+ const r = this.routes.get(exposed)
192
+ const started = Date.now()
193
+ if (!r) {
194
+ audit({ event: 'unknown_tool', tool: exposed })
195
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify({ ok: false, code: 'unknown_tool', tool: exposed }) }] }
196
+ }
197
+ if (!isReadOnlyTool(exposed)) {
198
+ const lic = await this.licenseState()
199
+ if (lic.ok === false) {
200
+ audit({ event: 'license_blocked', tool: exposed, reason: lic.reason })
201
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify({ ok: false, code: 'license_required', reason: lic.reason, hint: '本机许可无效/过期 ⇒ 写操作被网关拦下(只读不受影响)' }) }] }
202
+ }
203
+ }
204
+ if (!r.up.alive) {
205
+ audit({ event: 'upstream_down', tool: exposed, upstream: r.up.id })
206
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify({ ok: false, code: 'upstream_unavailable', upstream: r.up.id, hint: '该上游进程已退出(参数错误/依赖缺失);重开网关或修上游' }) }] }
207
+ }
208
+ try {
209
+ const res = await r.up.call(r.name, args)
210
+ const ms = Date.now() - started
211
+ const ok = resultOk(res)
212
+ let out = res
213
+ if (this.vault && ok && exposed.startsWith('erp.') && res && res.content && res.content[0]) {
214
+ const r = applyVaultToText(this.vault, res.content[0].text)
215
+ if (r.tokens > 0) {
216
+ out = { ...res, content: [{ ...res.content[0], text: r.text }, ...res.content.slice(1)] }
217
+ audit({ event: 'vault', tool: exposed, tokens: r.tokens })
218
+ }
219
+ }
220
+ audit({ event: 'call', tool: exposed, upstream: r.up.id, ms, ok })
221
+ if (!isReadOnlyTool(exposed)) {
222
+ const idem = String(args.idempotencyKey || args.idem || '')
223
+ const m = appendEvent(DATA_DIR, { action: exposed, idem, points: 1, tenant: process.env.ARGENT_TENANT || '', ok, idemSet: this.idemSet })
224
+ if (m.duplicate) audit({ event: 'meter_duplicate', tool: exposed, idem })
225
+ }
226
+ return out
227
+ } catch (e) {
228
+ const ms = Date.now() - started
229
+ audit({ event: 'error', tool: exposed, upstream: r.up.id, ms, error: String(e.message).slice(0, 160) })
230
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify({ ok: false, code: 'upstream_error', tool: exposed, message: String(e.message).slice(0, 300) }) }] }
231
+ }
232
+ }
233
+
234
+ /** 许可状态(5 分钟缓存;引擎不可达 ⇒ 放行但 audit 记 unknown,避免"网关把系统锁死") */
235
+ async licenseState() {
236
+ // 默认**关**(开发机通常没有许可文件;客户机应设 PARENT=1 打开)
237
+ if (process.env.ARGENT_GATEWAY_LICENSE_GATE !== '1') return { ok: true, reason: 'gate_disabled' }
238
+ const now = Date.now()
239
+ if (this._lic && now - this._lic.at < 5 * 60 * 1000) return this._lic.value
240
+ const route = this.routes.get('engine.argent_license')
241
+ let value = { ok: true, reason: 'unknown_allowed' }
242
+ if (route && route.up.alive) {
243
+ try {
244
+ const res = await route.up.call(route.name, {})
245
+ const j = JSON.parse((res.content && res.content[0] && res.content[0].text) || '{}')
246
+ const state = j.state || j.status || ''
247
+ if (state === 'denied' || j.ok === false) value = { ok: false, reason: String(state || 'denied') }
248
+ else value = { ok: true, reason: String(state || 'valid') }
249
+ } catch { /* 引擎异常 ⇒ 放行 */ }
250
+ }
251
+ this._lic = { at: now, value }
252
+ return value
253
+ }
254
+
255
+ close() { for (const u of this.upstreams) u.close() }
256
+ }
257
+
258
+ /* ── 前端:stdio(默认) / HTTP(常驻,多窗口共享一份 vault 与计量) ─────── */
259
+ const send = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`)
260
+
261
+ /** 与传输无关的 JSON-RPC 处理(stdio 与 HTTP 共用,⛔ 不写两份) */
262
+ export function rpcHandler(gw) {
263
+ return async (msg) => {
264
+ const { id, method, params } = msg || {}
265
+ if (method === 'initialize') return { jsonrpc: '2.0', id, result: { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: SERVER_INFO } }
266
+ if (method === 'notifications/initialized') return null
267
+ if (method === 'ping') return { jsonrpc: '2.0', id, result: {} }
268
+ if (method === 'tools/list') return { jsonrpc: '2.0', id, result: { tools: gw.listTools() } }
269
+ if (method === 'tools/call') return { jsonrpc: '2.0', id, result: await gw.call(params && params.name, (params && params.arguments) || {}) }
270
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } }
271
+ }
272
+ }
273
+
274
+ function startStdio(gw) {
275
+ const handle = rpcHandler(gw)
276
+ process.stdin.setEncoding('utf8')
277
+ let buf = ''
278
+ process.stdin.on('data', async (chunk) => {
279
+ buf += chunk
280
+ let i
281
+ while ((i = buf.indexOf('\n')) >= 0) {
282
+ const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1)
283
+ if (!line) continue
284
+ let msg; try { msg = JSON.parse(line) } catch { continue }
285
+ const out = await handle(msg)
286
+ if (out) send(out)
287
+ }
288
+ })
289
+ }
290
+
291
+ async function startHttp(gw, port, bind) {
292
+ const { createServer } = await import('node:http')
293
+ const handle = rpcHandler(gw)
294
+ const server = createServer(async (req, res) => {
295
+ const j = (code, body) => { res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(body)) }
296
+ if (req.method === 'GET' && (req.url === '/health' || req.url === '/mcp/health')) {
297
+ return j(200, { ok: true, tools: gw.routes.size, upstreams: [...new Set([...gw.routes.values()].map((r) => r.up.id))] })
298
+ }
299
+ if (!(req.method === 'POST' && (req.url === '/mcp' || req.url === '/mcp/'))) return j(404, { error: 'not_found' })
300
+ let raw = ''
301
+ for await (const c of req) raw += c
302
+ let body
303
+ try { body = JSON.parse(raw || '{}') } catch { return j(400, { error: 'bad_json' }) }
304
+ const out = await handle(body)
305
+ if (!out) return j(202, { ok: true })
306
+ return j(200, out)
307
+ })
308
+ await new Promise((resolve) => server.listen(port, bind, resolve))
309
+ process.stderr.write(`[gateway] HTTP 就绪:http://${bind}:${port}/mcp(tools ${gw.routes.size})\n`)
310
+ return server
311
+ }
312
+
313
+ async function main() {
314
+ const gw = new Gateway()
315
+ await gw.start()
316
+ process.stderr.write(`[gateway] 就绪:${gw.routes.size} 个工具(${[...new Set([...gw.routes.values()].map((r) => r.up.id))].join(' / ')})\n`)
317
+
318
+ const httpMode = process.env.ARGENT_GATEWAY_HTTP === '1'
319
+ let server = null
320
+ if (httpMode) {
321
+ const port = Number(process.env.ARGENT_GATEWAY_PORT || 8791)
322
+ const bind = process.env.ARGENT_GATEWAY_BIND || '127.0.0.1'
323
+ server = await startHttp(gw, port, bind)
324
+ } else {
325
+ startStdio(gw)
326
+ }
327
+
328
+ const shutdown = () => { try { server && server.close() } catch { /* noop */ } gw.close(); process.exit(0) }
329
+ process.on('SIGTERM', shutdown)
330
+ process.on('SIGINT', shutdown)
331
+ }
332
+
333
+ if (process.argv[1] && /gateway\.mjs$/.test(process.argv[1])) main()
@@ -0,0 +1,101 @@
1
+ /**
2
+ * meter.mjs —— 计费事件的**本地台账 + 签名批次**(v0.9.0)
3
+ *
4
+ * 为什么需要签名:客户机是"可被改动"的环境,事件必须能证明"没被事后篡改",
5
+ * 否则服务端对账时无法判断是漏报还是改过。
6
+ *
7
+ * 落盘(全部在 `<dataDir>/gateway/`,0600):
8
+ * events.jsonl 追加式事件(一行一条;含 idem 幂等键)
9
+ * events.signed.jsonl 签名批次(每批 {batchId, fromSeq, toSeq, count, hmac})
10
+ * billing.key HMAC 密钥(首次自动生成,0600;⛔ 不进仓库、不上报)
11
+ * signoff.json 已签到的最大 seq(避免重复签)
12
+ *
13
+ * 口径(与 configs/billing-actions.json 一致):
14
+ * · 只在**动作成功**时记;读/提议/失败不计;
15
+ * · 同一 `idem` 只记一次(重试/重放不重复计费);
16
+ * · ⛔ 不记录参数与结果正文(只 action / points / tenant / user / ts)。
17
+ */
18
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, openSync, closeSync, readFileSync, writeSync } from 'node:fs'
19
+ import { createHmac, randomUUID } from 'node:crypto'
20
+ import { join } from 'node:path'
21
+
22
+ const KEYS = ['at', 'action', 'idem', 'points', 'tenant', 'user', 'ok']
23
+
24
+ function dirOf(dataDir) {
25
+ const d = join(dataDir, 'gateway')
26
+ mkdirSync(d, { recursive: true })
27
+ return d
28
+ }
29
+
30
+ /** 读密钥;不存在则生成(0600) */
31
+ export function loadOrCreateKey(dataDir) {
32
+ const f = join(dirOf(dataDir), 'billing.key')
33
+ if (existsSync(f)) return readFileSync(f, 'utf8').trim()
34
+ const key = randomUUID().replace(/-/g, '') + randomUUID().replace(/-/g, '')
35
+ const fd = openSync(f, 'w', 0o600)
36
+ writeSync(fd, key)
37
+ closeSync(fd)
38
+ try { chmodSync(f, 0o600) } catch { /* noop */ }
39
+ return key
40
+ }
41
+
42
+ function readLines(file) {
43
+ if (!existsSync(file)) return []
44
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean)
45
+ }
46
+
47
+ /** 已存在的幂等键集合(启动时读一次;之后内存维护) */
48
+ export function loadIdemSet(dataDir) {
49
+ const set = new Set()
50
+ for (const line of readLines(join(dirOf(dataDir), 'events.jsonl'))) {
51
+ try { const e = JSON.parse(line); if (e.idem) set.add(e.idem) } catch { /* 跳过坏行 */ }
52
+ }
53
+ return set
54
+ }
55
+
56
+ /**
57
+ * 追加一条事件。
58
+ * @returns {{ok:boolean, duplicate?:boolean, seq?:number}}
59
+ */
60
+ export function appendEvent(dataDir, { action, idem = '', points = 0, tenant = '', user = '', ok = true, idemSet } = {}) {
61
+ if (!ok) return { ok: false, reason: 'not_successful' }
62
+ if (idem && idemSet && idemSet.has(idem)) return { ok: true, duplicate: true }
63
+ const dir = dirOf(dataDir)
64
+ const file = join(dir, 'events.jsonl')
65
+ const seq = readLines(file).length + 1
66
+ const ev = { at: new Date().toISOString(), seq, action, idem, points, tenant, user }
67
+ appendFileSync(file, JSON.stringify(ev) + '\n')
68
+ if (idem && idemSet) idemSet.add(idem)
69
+ return { ok: true, seq }
70
+ }
71
+
72
+ /** 把 events.jsonl 里尚未签名的事件打包签名(幂等:靠 signoff.json 的 toSeq) */
73
+ export function signPending(dataDir, { key } = {}) {
74
+ const dir = dirOf(dataDir)
75
+ const events = readLines(join(dir, 'events.jsonl')).map((l) => JSON.parse(l))
76
+ const signoffFile = join(dir, 'signoff.json')
77
+ let signedTo = 0
78
+ try { signedTo = JSON.parse(readFileSync(signoffFile, 'utf8')).toSeq || 0 } catch { /* first run */ }
79
+ const pending = events.filter((e) => (e.seq || 0) > signedTo)
80
+ if (!pending.length) return { ok: true, signed: 0, toSeq: signedTo }
81
+ const hm = createHmac('sha256', key || loadOrCreateKey(dataDir))
82
+ // 规范化:字段顺序固定,避免签名依赖 JSON 键序
83
+ const canonical = pending.map((e) => KEYS.map((k) => (k === 'at' || k === 'action' || k === 'idem' ? (e[k] || '') : e[k] === undefined ? '' : String(e[k]))).join('\u0001')).join('\n')
84
+ const hmac = hm.update(canonical).digest('hex')
85
+ const batch = { batchId: randomUUID(), fromSeq: pending[0].seq, toSeq: pending[pending.length - 1].seq, count: pending.length, hmac, at: new Date().toISOString() }
86
+ appendFileSync(join(dir, 'events.signed.jsonl'), JSON.stringify(batch) + '\n')
87
+ const fd = openSync(signoffFile, 'w', 0o600)
88
+ writeSync(fd, JSON.stringify({ toSeq: batch.toSeq, batchId: batch.batchId }))
89
+ closeSync(fd)
90
+ return { ok: true, signed: batch.count, toSeq: batch.toSeq, batchId: batch.batchId }
91
+ }
92
+
93
+ /** 校验一个批次(测试/服务端对账可用同一实现) */
94
+ export function verifyBatch(events, batch, key) {
95
+ const canonical = events
96
+ .filter((e) => e.seq >= batch.fromSeq && e.seq <= batch.toSeq)
97
+ .map((e) => KEYS.map((k) => (k === 'at' || k === 'action' || k === 'idem' ? (e[k] || '') : e[k] === undefined ? '' : String(e[k]))).join('\u0001'))
98
+ .join('\n')
99
+ const expect = createHmac('sha256', key).update(canonical).digest('hex')
100
+ return expect === batch.hmac
101
+ }