@whyshu/argent-engine 0.8.0-rc.11 → 0.8.0-rc.13

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 (38) hide show
  1. package/MANIFEST.json +34 -7
  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 +40 -0
  6. package/engine/core/lib/account-token.mjs +37 -0
  7. package/engine/core/lib/redact.mjs +34 -0
  8. package/engine/core/mcp/billing-upload.mjs +77 -0
  9. package/engine/core/mcp/erp-server.mjs +296 -0
  10. package/engine/core/mcp/gateway.mjs +333 -0
  11. package/engine/core/mcp/meter.mjs +101 -0
  12. package/engine/core/mcp/vault.mjs +78 -0
  13. package/engine/scripts/appointment_grab.py +100 -20
  14. package/engine/scripts/argent-web-preflight.mjs +123 -0
  15. package/engine/scripts/argent-web-verify.mjs +105 -0
  16. package/engine/scripts/billing-upload.mjs +26 -0
  17. package/engine/scripts/build-engine-package.mjs +7 -1
  18. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  19. package/engine/scripts/engine-runtime-install.mjs +92 -0
  20. package/engine/scripts/erp-ui-install.mjs +127 -0
  21. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  22. package/engine/scripts/erp-ui-verify.mjs +135 -0
  23. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  24. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  25. package/engine/scripts/migrate-providers.mjs +3 -3
  26. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  27. package/engine/scripts/web-switch.mjs +121 -0
  28. package/engine/skills/README.md +3 -3
  29. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  30. package/engine/skills/douyin-upload/SKILL.md +74 -0
  31. package/engine/skills/internal.json +28 -0
  32. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  33. package/engine/skills/tencent-upload/SKILL.md +60 -0
  34. package/engine/skills/weibo-upload/SKILL.md +106 -0
  35. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  36. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  37. package/engine/version.mjs +1 -1
  38. package/package.json +5 -1
@@ -0,0 +1,296 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * erp-server.mjs —— ERP 的 MCP 服务端(v0.9.0 · 只读第一版)
4
+ *
5
+ * 定位:把 whyshu-svr 现有的 HTTP 只读接口包成 MCP 工具,给 dsh 会话/侧栏面板用。
6
+ * ⛔ 不改 ERP 逻辑、不直连数据库、不写 whyshu-svr;只做「协议形状适配 + 轻量脱敏」。
7
+ *
8
+ * 鉴权:复用问述账号 token(`WHYSHU_API_KEY`,与 LLM 代理同一把 JWT,
9
+ * 服务端 `authenticate` 同时接受 x-api-key 与 Bearer)。
10
+ * 租户:`ARGENT_TENANT`(默认 ly-0001)。
11
+ *
12
+ * 传输:stdio(每行一个 JSON-RPC 2.0)。协议子集:initialize / notifications/initialized /
13
+ * tools/list / tools/call / ping —— 与 core/mcp/server.mjs 同款,零第三方依赖。
14
+ *
15
+ * 红线:
16
+ * · 只读:本版不支持任何写操作(`prepare_action` 需要服务端新路由,等 whyshu-svr 侧提供);
17
+ * · 脱敏:手机号打码、附件 token/URL 不返回、客户名可选代号(v2 接 vault);
18
+ * · 不落日志正文:只记 tool/耗时/ok。
19
+ */
20
+
21
+ const API_BASE = (process.env.ARGENT_API_BASE || 'https://whyshu.com').replace(/\/+$/, '')
22
+ const TENANT = String(process.env.ARGENT_TENANT || 'ly-0001').trim()
23
+ import { resolveAccountToken } from '../lib/account-token.mjs'
24
+ const TOKEN = resolveAccountToken().token
25
+ const TIMEOUT_MS = Number(process.env.ARGENT_ERP_TIMEOUT_MS || 20000)
26
+ /** 写路径总开关(默认关):ERP 上线 prepare 路由后设 ARGENT_ERP_WRITE=1 即可,无需改代码 */
27
+ const WRITE_ENABLED = process.env.ARGENT_ERP_WRITE === '1'
28
+ export const SERVER_INFO = { name: 'argent-erp', version: '0.9.0' }
29
+
30
+ import { redactDeep } from '../lib/redact.mjs'
31
+
32
+ async function apiPost(path, body = {}) {
33
+ if (!WRITE_ENABLED) throw Object.assign(new Error('写路径未启用(ARGENT_ERP_WRITE=1 才开)'), { code: 'write_disabled' })
34
+ if (!TOKEN) throw Object.assign(new Error('缺少账号 token(WHYSHU_API_KEY)'), { code: 'no_token' })
35
+ let r
36
+ try {
37
+ r = await fetch(`${API_BASE}/api/argent/v1${path}`, {
38
+ method: 'POST',
39
+ headers: { 'x-api-key': TOKEN, 'content-type': 'application/json', accept: 'application/json' },
40
+ body: JSON.stringify(body),
41
+ signal: AbortSignal.timeout(TIMEOUT_MS),
42
+ })
43
+ } catch (e) {
44
+ throw Object.assign(new Error(`ERP 不可达:${String(e.message).slice(0, 120)}`), { code: 'network' })
45
+ }
46
+ const text = await r.text()
47
+ let j = null
48
+ try { j = JSON.parse(text) } catch { j = { raw: text.slice(0, 200) } }
49
+ if (r.status === 401) throw Object.assign(new Error('账号 token 失效(401)'), { code: 'unauthorized', status: 401 })
50
+ if (!r.ok) throw Object.assign(new Error((j && j.error && j.error.message) || `ERP HTTP ${r.status}`), { code: 'http', status: r.status })
51
+ return j
52
+ }
53
+
54
+ async function apiGet(path, query = {}) {
55
+ if (!TOKEN) throw Object.assign(new Error('缺少账号 token(WHYSHU_API_KEY)'), { code: 'no_token' })
56
+ const url = new URL(`${API_BASE}/api/argent/v1${path}`)
57
+ for (const [k, v] of Object.entries(query)) {
58
+ if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, String(v))
59
+ }
60
+ const ctl = AbortSignal.timeout(TIMEOUT_MS)
61
+ const r = await fetch(url, { headers: { 'x-api-key': TOKEN, accept: 'application/json' }, signal: ctl })
62
+ const text = await r.text()
63
+ let body = null
64
+ try { body = JSON.parse(text) } catch { body = { raw: text.slice(0, 300) } }
65
+ if (!r.ok) {
66
+ const err = new Error(`ERP HTTP ${r.status}: ${(body && body.error && body.error.message) || ''}`.trim())
67
+ err.code = r.status === 401 ? 'unauthorized' : r.status === 403 ? 'forbidden' : 'http_error'
68
+ err.status = r.status
69
+ throw err
70
+ }
71
+ return body
72
+ }
73
+
74
+ const tenantPath = (suffix) => `/tenants/${encodeURIComponent(TENANT)}${suffix}`
75
+
76
+ /**
77
+ * 列表投影(2026-11-04):ERP 的 `/shipments` 每条内嵌 progress/groups/fileRefs,
78
+ * 单条 ~5KB;一次 limit=20 能把模型上下文顶爆。列表只回"看得懂的一行",重数据走 _detail。
79
+ */
80
+ const F = ['sourceRecordId', 'shipmentNo', 'shop', 'sku', 'status', 'fullStatus', 'currentStep', 'invoiceStatus', 'invoiceReady', 'boxCount', 'ready', 'updatedAt']
81
+ /** 发票列表投影:fileRefs(每条 4 组附件)→ 只留数量与状态 */
82
+ export function pickInvoice(it = {}) {
83
+ const fr = it.fileRefs || {}
84
+ const out = {
85
+ sourceRecordId: it.sourceRecordId, shipmentNo: it.shipmentNo,
86
+ invoiceStatus: it.invoiceStatus, invoiceReady: it.invoiceReady,
87
+ invoiceError: it.invoiceError || '',
88
+ files: { invoice: (fr.invoiceFile || []).length, bulkLabel: (fr.bulkLabel || []).length, fullLabel: (fr.fullLabelFile || []).length, fullCarton: (fr.fullCartonFile || []).length },
89
+ updatedAt: it.updatedAt,
90
+ }
91
+ return out
92
+ }
93
+
94
+ /** 任务列表投影:payload 里只取面板/模型要用的几项 */
95
+ export function pickTask(it = {}) {
96
+ const pl = it.payload || {}
97
+ return {
98
+ id: it._id, type: it.type, title: it.title, status: it.status,
99
+ shipmentNo: pl.shipmentNo || '', shop: pl.shop || '', stageLabel: pl.stageLabel || '',
100
+ nextAction: pl.nextAction || '', updatedAt: it.updatedAt,
101
+ }
102
+ }
103
+
104
+ export function pickShipment(it = {}) {
105
+ const out = {}
106
+ for (const k of F) if (it[k] !== undefined) out[k] = it[k]
107
+ const pg = it.progress || {}
108
+ if (pg.percent !== undefined) out.progress = { percent: pg.percent, doneCount: pg.doneCount, totalCount: pg.totalCount, currentLabel: pg.currentLabel }
109
+ return out
110
+ }
111
+
112
+ /** 工具表:**只读**,参数尽量贴近 ERP 现有 query(不发明新语义) */
113
+ export const TOOLS = {
114
+ erp_tenant_info: {
115
+ description: '当前账号与所属租户(/me + /me/tenants)',
116
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
117
+ handler: async () => ({ me: await apiGet('/me'), tenants: await apiGet('/me/tenants') }),
118
+ },
119
+ erp_shipment_search: {
120
+ description: '查货件(GET /shipments):q / status / fullStatus / ready / stage / group / page / limit',
121
+ inputSchema: {
122
+ type: 'object',
123
+ properties: {
124
+ q: { type: 'string' }, status: { type: 'string' }, fullStatus: { type: 'string' },
125
+ ready: { type: 'boolean' }, stage: { type: 'string' }, group: { type: 'string' },
126
+ page: { type: 'integer' }, limit: { type: 'integer', maximum: 50 },
127
+ },
128
+ additionalProperties: false,
129
+ },
130
+ handler: async (a) => {
131
+ const r = await apiGet(tenantPath('/shipments'), a)
132
+ const d = r.data || {}
133
+ return { total: d.total, page: d.page, limit: d.limit, items: (d.items || []).map(pickShipment) }
134
+ },
135
+ },
136
+ erp_shipment_detail: {
137
+ description: '货件详情(GET /shipments/:sourceRecordId)',
138
+ inputSchema: { type: 'object', properties: { sourceRecordId: { type: 'string' } }, required: ['sourceRecordId'], additionalProperties: false },
139
+ handler: async ({ sourceRecordId }) => apiGet(tenantPath(`/shipments/${encodeURIComponent(sourceRecordId)}`)),
140
+ },
141
+ erp_invoice_list: {
142
+ description: '查发票(GET /invoices):q / invoiceStatus / invoiceReady / page / limit',
143
+ inputSchema: {
144
+ type: 'object',
145
+ properties: { q: { type: 'string' }, invoiceStatus: { type: 'string' }, invoiceReady: { type: 'boolean' }, page: { type: 'integer' }, limit: { type: 'integer', maximum: 50 } },
146
+ additionalProperties: false,
147
+ },
148
+ handler: async (a) => {
149
+ const r = await apiGet(tenantPath('/invoices'), a)
150
+ const d = r.data || {}
151
+ return { total: d.total, page: d.page, limit: d.limit, items: (d.items || []).map(pickInvoice) }
152
+ },
153
+ },
154
+ erp_task_list: {
155
+ description: '任务列表(GET /tasks):status / type / limit',
156
+ inputSchema: { type: 'object', properties: { status: { type: 'string' }, type: { type: 'string' }, limit: { type: 'integer', maximum: 100 } }, additionalProperties: false },
157
+ handler: async (a) => {
158
+ const r = await apiGet(tenantPath('/tasks'), a)
159
+ const d = r.data || {}
160
+ const items = Array.isArray(d.items) ? d.items : []
161
+ return { items: items.map(pickTask) }
162
+ },
163
+ },
164
+ erp_run_list: {
165
+ description: '运行记录(GET /runs):cardId / limit',
166
+ inputSchema: { type: 'object', properties: { cardId: { type: 'string' }, limit: { type: 'integer', maximum: 200 } }, additionalProperties: false },
167
+ handler: async (a) => apiGet(tenantPath('/runs'), a),
168
+ },
169
+ erp_ledger_list: {
170
+ description: '台账(GET /ledger):flow / ticket / kind / days / limit',
171
+ inputSchema: {
172
+ type: 'object',
173
+ properties: { flow: { type: 'string' }, ticket: { type: 'string' }, kind: { type: 'string' }, days: { type: 'integer' }, limit: { type: 'integer' } },
174
+ additionalProperties: false,
175
+ },
176
+ handler: async (a) => apiGet(tenantPath('/ledger'), a),
177
+ },
178
+ erp_member_list: {
179
+ description: '成员(GET /members;手机号自动打码)',
180
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
181
+ handler: async () => apiGet(tenantPath('/members')),
182
+ },
183
+ erp_office_snapshot: {
184
+ description: '办公室现场快照(GET /office:KPI/在岗员工/任务流/动态)',
185
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
186
+ handler: async () => apiGet(tenantPath('/office')),
187
+ },
188
+ erp_dashboard: {
189
+ description: '仪表盘聚合(GET /dashboard)',
190
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
191
+ handler: async () => apiGet(tenantPath('/dashboard')),
192
+ },
193
+ erp_shipment_stats: {
194
+ description: '货件聚合统计(取 GET /dashboard:总数/完成率/byStage/byGroup;**适配层派生**,非 ERP 专用 stats 路由)',
195
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
196
+ handler: async () => {
197
+ const d = (await apiGet(tenantPath('/dashboard'))).data || {}
198
+ return { total: d.total || 0, completed: d.completed || 0, completionRate: d.completionRate || 0, byStage: d.byStage || {}, byGroup: d.byGroup || {} }
199
+ },
200
+ },
201
+ erp_shipment_timeline: {
202
+ description: '货件节点时间线(取 GET /shipments/:id 的 progress.nodes;**适配层派生**)',
203
+ inputSchema: { type: 'object', properties: { sourceRecordId: { type: 'string' } }, required: ['sourceRecordId'], additionalProperties: false },
204
+ handler: async ({ sourceRecordId }) => {
205
+ const d = (await apiGet(tenantPath(`/shipments/${encodeURIComponent(sourceRecordId)}`))).data || {}
206
+ const nodes = ((d.progress && d.progress.nodes) || []).map((n) => ({ key: n.key, label: n.label, status: n.status, completedAt: n.completedAt || null, ownerName: n.ownerName || '' }))
207
+ return { nodes }
208
+ },
209
+ },
210
+ erp_invoice_detail: {
211
+ description: '发票详情(复用 GET /shipments/:sourceRecordId 的 invoice/progress 段;不含附件下载地址)',
212
+ inputSchema: { type: 'object', properties: { sourceRecordId: { type: 'string' } }, required: ['sourceRecordId'], additionalProperties: false },
213
+ handler: async ({ sourceRecordId }) => {
214
+ const r = await apiGet(tenantPath(`/shipments/${encodeURIComponent(sourceRecordId)}`))
215
+ const d = r.data || {}
216
+ return { invoice: d.invoice || null, progress: d.progress || null }
217
+ },
218
+ },
219
+ erp_activity_list: {
220
+ description: '办公室动态(取 GET /office 的 activity 段):limit 默认 20',
221
+ inputSchema: { type: 'object', properties: { limit: { type: 'integer', maximum: 50 } }, additionalProperties: false },
222
+ handler: async ({ limit = 20 } = {}) => {
223
+ const r = await apiGet(tenantPath('/office'))
224
+ const items = (r.data && r.data.activity) || []
225
+ return { items: items.slice(0, Math.min(Number(limit) || 20, 50)), total: items.length }
226
+ },
227
+ },
228
+ erp_prepare_action: {
229
+ description: '生成写操作提议(POST /office/actions/prepare;需 ARGENT_ERP_WRITE=1 且 ERP 已提供该路由)。只生成提议、不执行、不计费。',
230
+ inputSchema: { type: 'object', properties: { action: { type: 'string' }, payload: { type: 'object' } }, required: ['action'], additionalProperties: false },
231
+ handler: async ({ action, payload = {} }) => {
232
+ if (!WRITE_ENABLED) return { ok: false, code: 'write_disabled', message: '写路径未启用:ARGENT_ERP_WRITE=1 才开放(需 ERP 先提供 prepare 路由)' }
233
+ const r = await apiPost(tenantPath('/office/actions/prepare'), { action, payload })
234
+ return { ok: true, proposal: r.data || r }
235
+ },
236
+ },
237
+ erp_execute_action: {
238
+ description: '执行已确认的提议(POST /office/actions/:proposalId/execute;需 ARGENT_ERP_WRITE=1)。⛔ 仅在用户明确确认后调用;成功才计费。',
239
+ inputSchema: { type: 'object', properties: { proposalId: { type: 'string' }, idempotencyKey: { type: 'string' } }, required: ['proposalId'], additionalProperties: false },
240
+ handler: async ({ proposalId }) => {
241
+ if (!WRITE_ENABLED) return { ok: false, code: 'write_disabled', message: '写路径未启用:ARGENT_ERP_WRITE=1 才开放' }
242
+ const r = await apiPost(tenantPath(`/office/actions/${encodeURIComponent(proposalId)}/execute`), {})
243
+ return { ok: true, result: r.data || r }
244
+ },
245
+ },
246
+ }
247
+
248
+ export const TOOL_NAMES = Object.freeze(Object.keys(TOOLS))
249
+
250
+ /* ── stdio JSON-RPC(与 core/mcp/server.mjs 同款协议子集) ───────────────── */
251
+ const send = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`)
252
+
253
+ export async function handle(msg) {
254
+ const { id, method, params } = msg || {}
255
+ if (method === 'initialize') {
256
+ return { jsonrpc: '2.0', id, result: { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: SERVER_INFO } }
257
+ }
258
+ if (method === 'notifications/initialized') return null
259
+ if (method === 'ping') return { jsonrpc: '2.0', id, result: {} }
260
+ if (method === 'tools/list') {
261
+ return {
262
+ jsonrpc: '2.0', id,
263
+ result: { tools: TOOL_NAMES.map((n) => ({ name: n, description: TOOLS[n].description, inputSchema: TOOLS[n].inputSchema, annotations: { readOnlyHint: !/prepare_action|execute_action/.test(n) } })) },
264
+ }
265
+ }
266
+ if (method === 'tools/call') {
267
+ const name = params && params.name
268
+ const args = (params && params.arguments) || {}
269
+ const tool = TOOLS[name]
270
+ if (!tool) return { jsonrpc: '2.0', id, result: { isError: true, content: [{ type: 'text', text: `unknown tool: ${name}` }] } }
271
+ try {
272
+ const out = await tool.handler(args)
273
+ return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(redactDeep(out)) }] } }
274
+ } catch (e) {
275
+ return { jsonrpc: '2.0', id, result: { isError: true, content: [{ type: 'text', text: JSON.stringify({ ok: false, code: e.code || 'error', message: String(e.message || e).slice(0, 300), tenant: TENANT }) }] } }
276
+ }
277
+ }
278
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `method not found: ${method}` } }
279
+ }
280
+
281
+ if (process.argv[1] && /erp-server\.mjs$/.test(process.argv[1])) {
282
+ process.stdin.setEncoding('utf8')
283
+ let buf = ''
284
+ process.stdin.on('data', async (chunk) => {
285
+ buf += chunk
286
+ let i
287
+ while ((i = buf.indexOf('\n')) >= 0) {
288
+ const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1)
289
+ if (!line) continue
290
+ let msg; try { msg = JSON.parse(line) } catch { continue }
291
+ const out = await handle(msg)
292
+ if (out) send(out)
293
+ }
294
+ })
295
+ if (!TOKEN) console.error('[argent-erp] ⚠️ 未设置 WHYSHU_API_KEY:工具会返回 no_token')
296
+ }
@@ -0,0 +1,333 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * gateway.mjs —— Argent MCP 网关(v0.9.0 第一版,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 } 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: '0.9.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()