@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,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
+ }
@@ -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
+ }
@@ -10,6 +10,7 @@ import argparse
10
10
  import asyncio
11
11
  import time
12
12
  import json
13
+ import urllib.request
13
14
  import os
14
15
  import signal
15
16
  import sys
@@ -98,29 +99,46 @@ def iso_day(d) -> date:
98
99
  async def _close_appointment_tab(orch) -> int:
99
100
  """停止/失败时关闭本任务用的预约标签页;若它是窗口最后 1 个标签,先开一个占位页再关。
100
101
 
101
- 紫鸟窗口守卫要求不能把最后标签关掉(会退出 Chromium 窗口、丢 CDP)。
102
- 这里用 about:blank 占位保持窗口存活,再关闭预约页,避免用户看到残留任务标签。
102
+ 2026-11-07 修复("停止后标签页仍在"):
103
+ · 旧实现只看 `orch.browser.page`(当前页),stop 时当前页可能已不是预约页(或被切走)⇒ 漏关;
104
+ · 改为**遍历所有 context 的所有 page**,按 URL 匹配 appointment-v2(或本任务货件号 + appointment);
105
+ · 失败不再静默吞掉:返回实际关闭数,main 的停止摘要按真实结果生成(不再硬编码"已关闭")。
103
106
  """
104
107
  closed = 0
108
+ shipment_id = str(getattr(getattr(orch, 'state', None), 'shipment_id', '') or '')
105
109
  try:
106
- page = getattr(orch.browser, 'page', None)
107
- if page is None or page.is_closed():
108
- return 0
109
- url = str(getattr(page, 'url', '') or '')
110
- # 只清理本任务/预约页,避免误关用户主门户标签
111
- if ('appointment-v2' not in url) and (str(getattr(orch.state, 'shipment_id', '') or '') not in url):
112
- return 0
113
- ctx = page.context
114
- if len(ctx.pages) <= 1:
110
+ contexts = list(getattr(orch.browser, 'contexts', []) or [])
111
+ for ctx in contexts:
115
112
  try:
116
- await ctx.new_page() # 占位,保持窗口不退出
113
+ pages = list(ctx.pages)
117
114
  except Exception:
118
- return 0
119
- await page.close()
120
- closed = 1
121
- orch._log(' 🗂️ 已关闭抢预约任务标签页(保留占位页,防窗口退出)')
115
+ continue
116
+ for page in pages:
117
+ try:
118
+ if page.is_closed():
119
+ continue
120
+ url = str(getattr(page, 'url', '') or '')
121
+ is_appt = ('appointment-v2' in url) or (
122
+ 'appointment' in url and shipment_id and shipment_id in url
123
+ )
124
+ if not is_appt:
125
+ continue
126
+ if len(ctx.pages) <= 1:
127
+ try:
128
+ await ctx.new_page() # 占位,保持窗口不退出
129
+ except Exception:
130
+ return closed
131
+ await page.close()
132
+ closed += 1
133
+ orch._log(f' 🗂️ 已关闭抢预约任务标签页({url[:100]})')
134
+ except Exception as e:
135
+ try: orch._log(f' ⚠️ 关闭预约标签页失败:{str(e)[:120]}')
136
+ except Exception: pass
137
+ if not closed:
138
+ try: orch._log(' ⚠️ 停止时未找到待关闭的预约标签页(可能已被用户关闭)')
139
+ except Exception: pass
122
140
  except Exception as e:
123
- try: orch._log(f' ⚠️ 关闭预约标签页失败:{str(e)[:120]}')
141
+ try: orch._log(f' ⚠️ 关闭预约标签页异常:{str(e)[:120]}')
124
142
  except Exception: pass
125
143
  return closed
126
144
 
@@ -275,6 +293,8 @@ async def run_task(task: dict) -> dict:
275
293
  args = SimpleNamespace(record_id='', sku=task.get('sku', ''), qty=task.get('quantity'), box=task.get('boxCount'),
276
294
  shipment_id=task.get('shipmentNo') or '', store_name=store, no_lock=True)
277
295
  orch = O.Orchestrator(cfg, sel, args)
296
+ global _ORCH
297
+ _ORCH = orch
278
298
  orch.state.store_name = store
279
299
  orch.state.record_id = ''
280
300
  orch.state.sku = str(task.get('sku') or '')
@@ -412,9 +432,9 @@ async def run_task(task: dict) -> dict:
412
432
  return {'status': 'failed', 'dateStates': last_states, 'cycles': cycle_no, 'summary': '本轮日期范围内未抢到预约'}
413
433
  finally:
414
434
  try:
415
- await _close_appointment_tab(orch)
435
+ _APPT_CLOSE_LAST['closed'] = await _close_appointment_tab(orch)
416
436
  except Exception:
417
- pass
437
+ _APPT_CLOSE_LAST['closed'] = 0
418
438
  try:
419
439
  await orch.browser.close()
420
440
  except Exception:
@@ -425,6 +445,58 @@ async def run_task(task: dict) -> dict:
425
445
  pass
426
446
 
427
447
 
448
+ _APPT_CLOSE_LAST = {'closed': 0}
449
+
450
+
451
+ _ORCH = None
452
+
453
+
454
+ def _http_sync(url: str, method: str = 'GET', timeout: float = 2.0):
455
+ req = urllib.request.Request(url, method=method)
456
+ with urllib.request.urlopen(req, timeout=timeout) as r:
457
+ return r.read()
458
+
459
+
460
+ def _close_appointment_tab_via_cdp(orch) -> int:
461
+ """同步 CDP 关闭(2026-11-07 第二轮修复)。
462
+
463
+ 停止信号会让事件循环提前关闭,``await page.close()`` 会报 ``no running event loop``
464
+ (客户机日志实证)⇒ 清理必须在**事件循环之外**用 CDP HTTP 同步完成。
465
+ """
466
+ closed = 0
467
+ try:
468
+ browser = getattr(orch, 'browser', None) if orch is not None else None
469
+ endpoint = str(getattr(browser, 'cdp_url', '') or '').rstrip('/')
470
+ if not endpoint:
471
+ return 0
472
+ targets = json.loads(_http_sync(f'{endpoint}/json/list').decode('utf-8', 'replace') or '[]')
473
+ appt = [t for t in targets if 'appointment-v2' in str(t.get('url') or '')]
474
+ if not appt:
475
+ try: orch._log(' ⚠️ 同步清理:未发现 appointment-v2 标签页')
476
+ except Exception: pass
477
+ return 0
478
+ # 先开占位页(保持紫鸟窗口存活),再逐个关闭预约页
479
+ try: _http_sync(f'{endpoint}/json/new?about:blank', method='PUT')
480
+ except Exception:
481
+ try: _http_sync(f'{endpoint}/json/new?about:blank')
482
+ except Exception: pass
483
+ for t in appt:
484
+ tid = str(t.get('id') or '')
485
+ if not tid: continue
486
+ try:
487
+ _http_sync(f'{endpoint}/json/close/{tid}')
488
+ closed += 1
489
+ try: orch._log(f' 🗂️ 同步 CDP 已关闭预约标签页({str(t.get("url"))[:100]})')
490
+ except Exception: pass
491
+ except Exception as e:
492
+ try: orch._log(f' ⚠️ 同步 CDP 关闭失败:{str(e)[:120]}')
493
+ except Exception: pass
494
+ except Exception as e:
495
+ try: orch._log(f' ⚠️ 同步 CDP 清理异常:{str(e)[:120]}')
496
+ except Exception: pass
497
+ return closed
498
+
499
+
428
500
  def _on_term(signum, frame):
429
501
  # SIGTERM 默认直接退出,不会执行 run_task 的 finally ⇒ 预约标签页残留。
430
502
  # 抛 KeyboardInterrupt 交给 asyncio.run 取消主任务,确保 finally 里的标签页清理执行。
@@ -438,7 +510,15 @@ def main():
438
510
  try:
439
511
  out = asyncio.run(run_task(task))
440
512
  except KeyboardInterrupt:
441
- out = {'status': 'stopped', 'summary': '收到停止请求,已关闭预约标签页'}
513
+ closed = int(_APPT_CLOSE_LAST.get('closed') or 0)
514
+ # 事件循环已关闭 ⇒ await 清理不可用;用 CDP HTTP 同步兜底(2026-11-07 客户机实证)
515
+ if _ORCH is not None:
516
+ closed = max(closed, _close_appointment_tab_via_cdp(_ORCH))
517
+ out = {
518
+ 'status': 'stopped',
519
+ 'summary': ('收到停止请求,已关闭预约标签页' if closed > 0
520
+ else '收到停止请求;未发现可关闭的预约标签页(可能已被用户关闭)'),
521
+ }
442
522
  except Exception as exc:
443
523
  out = {'status': 'failed', 'summary': f'{type(exc).__name__}: {exc}'}
444
524
  print(json.dumps(out, ensure_ascii=False), flush=True)
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * argent-web-preflight.mjs —— **启动 web 之前**的结构自检(2026-11-05)
4
+ *
5
+ * 为什么:desktop 那次 boot 失败(plugins 被重置)教训是——profile 改完到启动之间,
6
+ * 任何一环错都只表现为"启动失败",且没有报错。本脚本把能提前发现的都查一遍。
7
+ *
8
+ * 查六类:
9
+ * 1. profile package.json:bundles 是否正好 base/web-app/argent-web
10
+ * 2. patch 每一行的 name 是否可解析(包在不在 node_modules / 本地文件在不在)
11
+ * 3. node_modules/@whyshu/argent-web 是否软链到仓库
12
+ * 4. 宿主插件能否 import + apply(假 ctx)
13
+ * 5. 客户端 bundle 能否装载并注册 shell.overlay
14
+ * 6. 关键端点文件/依赖是否齐全(office-runtime/auth/health/llm-whyshu)
15
+ *
16
+ * 退出码:0 全通 | 1 有 FAIL
17
+ */
18
+ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs'
19
+ import { createRequire } from 'node:module'
20
+ import { homedir } from 'node:os'
21
+ import { join, resolve } from 'node:path'
22
+
23
+ const REPO = resolve(import.meta.dirname, '..')
24
+ const profileArg = process.argv.includes('--profile') ? process.argv[process.argv.indexOf('--profile') + 1] : 'web'
25
+ const profileDir = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'profiles', profileArg)
26
+ const req = createRequire(join(profileDir, 'package.json'))
27
+
28
+ let fails = 0
29
+ const ok = (c, msg) => { console.log(`${c ? '✅' : '❌'} ${msg}`); if (!c) fails++ }
30
+ const warn = (msg) => console.log(`⚠️ ${msg}`)
31
+
32
+ // 0) 版本门禁(2026-11-05 事故:用户用 `npx @deepseek-ai/dsh` 起 web,拉到 rc.5,
33
+ // 而 profile 插件是 rc.2 ⇒ 一堆核心插件等待服务 ⇒ 启动失败)
34
+ {
35
+ const { execFileSync } = await import('node:child_process')
36
+ let profVer = ''
37
+ try { profVer = JSON.parse(readFileSync(join(profileDir, 'node_modules', '@deepseek-ai', 'dsh-base', 'package.json'), 'utf8')).version } catch { /* ignore */ }
38
+ let hostVer = ''
39
+ try { hostVer = execFileSync('dsh', ['--version'], { encoding: 'utf8', timeout: 5000 }).trim() } catch { /* ignore */ }
40
+ if (!profVer && hostVer) {
41
+ console.log(`✅ profile 不自带 dsh 包(由宿主提供)|全局 dsh ${hostVer} ⇒ 不会版本混用`)
42
+ } else if (profVer && hostVer) {
43
+ if (profVer === hostVer) console.log(`✅ 版本一致:profile 插件 ${profVer} ⇄ 全局 dsh ${hostVer}`)
44
+ else {
45
+ console.log(`❌ 版本不一致:profile 插件 ${profVer} ≠ 全局 dsh ${hostVer}`)
46
+ console.log(` ⇒ 用不匹配的宿主启动会「一堆插件等待服务」而失败(2026-11-05 实测 rc.5 vs rc.2)`)
47
+ console.log(` 请用:npx @deepseek-ai/dsh@${profVer} web 或 dsh web(全局已装 ${hostVer})`)
48
+ fails++ // fails 在下方声明,见下
49
+ }
50
+ } else {
51
+ console.log('ℹ️ 版本门禁跳过(没读到 profile 插件版本或全局 dsh)')
52
+ }
53
+ }
54
+
55
+ // 1) package.json
56
+ const pkg = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8'))
57
+ const bundles = (pkg.dsh && pkg.dsh.profile && pkg.dsh.profile.bundles) || []
58
+ const want = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@whyshu/argent-web']
59
+ ok(JSON.stringify([...bundles].sort()) === JSON.stringify([...want].sort()), `bundles 正好 3 个(${bundles.join(', ')})`)
60
+ ok(Boolean((pkg.dependencies || {})['@whyshu/argent-web']), '依赖含 @whyshu/argent-web')
61
+
62
+ // 2) patch 每行的 name 可解析
63
+ const patch = readFileSync(join(profileDir, 'cordis.patch.yml'), 'utf8')
64
+ const names = [...patch.matchAll(/^\s+name:\s*['"]([^'"]+)['"]/gm)].map((m) => m[1])
65
+ const unresolved = []
66
+ for (const n of names) {
67
+ if (n.startsWith('./') || n.startsWith('../')) {
68
+ if (!existsSync(join(profileDir, n))) unresolved.push(`${n}(本地文件不存在)`)
69
+ continue
70
+ }
71
+ try { req.resolve(`${n}/package.json`) } catch { try { req.resolve(n) } catch { unresolved.push(n) } }
72
+ }
73
+ ok(unresolved.length === 0, unresolved.length ? `patch 有 ${unresolved.length} 个 name 解析不到:${unresolved.join(', ')}` : `patch ${names.length} 个 name 全部可解析`)
74
+
75
+ // 3) 软链
76
+ const nm = join(profileDir, 'node_modules', '@whyshu', 'argent-web')
77
+ if (!existsSync(nm)) ok(false, 'node_modules 缺 @whyshu/argent-web')
78
+ else {
79
+ ok(lstatSync(nm).isSymbolicLink() && realpathSync(nm) === realpathSync(join(REPO, 'plugins', 'argent-web')), 'node_modules/@whyshu/argent-web 软链指向仓库')
80
+ }
81
+
82
+ // 4) 宿主插件 apply
83
+ {
84
+ const mod = await import(join(REPO, 'plugins', 'argent-web', 'src', 'index.js'))
85
+ ok(typeof mod.apply === 'function' && mod.name === 'argent-web', '宿主插件可 import(name=argent-web)')
86
+ const regs = []
87
+ const plugins = []
88
+ const ctx = { webServer: { register: (e) => regs.push(e.path) }, plugin: (mod, cfg) => plugins.push({ mod, cfg }), on: () => {}, effect: (f) => f(), get: () => null }
89
+ try { await mod.apply(ctx) } catch (e) { ok(false, `apply 抛异常:${e.message}`) }
90
+ ok(regs.includes('/api/argent-web/health'), `注册 health 端点(${regs.join(', ')})`)
91
+ ok(regs.includes('/api/argent-web/account'), '注册 account 端点(积分)')
92
+ ok(regs.includes('/api/argent-web/auth'), '注册 auth 端点(一键登录)')
93
+ const mcp = plugins.find((p) => p.cfg && p.cfg.serverName === 'argent')
94
+ ok(Boolean(mcp), '自注册 MCP 网关(serverName=argent)')
95
+ ok(existsSync(join(REPO, 'plugins', 'argent-web', 'mcp', 'gateway.mjs')), '网关文件存在:mcp/gateway.mjs')
96
+ }
97
+
98
+ // 5) 客户端 bundle
99
+ {
100
+ const src = readFileSync(join(REPO, 'plugins', 'argent-web', 'dist', 'client.js'), 'utf8')
101
+ let mod = null
102
+ const reactStub = { createElement: () => null, useState: (v) => [v, () => {}], useEffect: () => {}, useCallback: (f) => f, useRef: () => ({ current: null }), useMemo: (f) => f() }
103
+ try {
104
+ new Function('window', src)({ __ModuleLoader__: { load: ({ factory }) => { mod = factory((n) => (n === 'react' ? reactStub : {})) } } })
105
+ const regs = []
106
+ mod.apply({ slots: { inject: (n, f) => { const it = f(); let r = it.next(); while (!r.done) r = it.next() }, register: (m) => { regs.push(m.name); return { dispose() {} } } } })
107
+ ok(regs.includes('shell.overlay'), `客户端注册 shell.overlay(伞伞)`)
108
+ } catch (e) { ok(false, `客户端 bundle 装载失败:${e.message}`) }
109
+ }
110
+
111
+ // 6) 关键文件
112
+ for (const f of ['src/office-runtime.js', 'src/whyshu-auth.mjs', 'src/health.mjs', 'src/llm-whyshu.mjs', 'src/lease.mjs', 'src/account-token.mjs']) {
113
+ ok(existsSync(join(REPO, 'plugins', 'argent-web', f)), `文件存在:${f}`)
114
+ }
115
+
116
+ // provider 解析(dsh 宿主内通常可解析;裸 Node 可能不行 ⇒ 只告警)
117
+ {
118
+ try { await import(join(REPO, 'plugins', 'argent-web', 'src', 'llm-whyshu.mjs')) ; console.log('✅ provider 模块可加载(问述代理)') }
119
+ catch { warn('provider 在裸 Node 下不可加载(缺 @deepseek-ai/dsh-llm*);dsh 宿主内一般可解析,若启动后模型列表没有「问述代理」再查这条') }
120
+ }
121
+
122
+ console.log(fails ? `\n❌ ${fails} 项未通过 —— 先修再启动 web` : '\n✅ 结构自检全通:可以启动 dsh web')
123
+ process.exit(fails ? 1 : 0)
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * argent-web-verify.mjs —— dsh web 的 Argent 单 bundle 验收(P5)
4
+ *
5
+ * 两段:
6
+ * A. **离线**校验 profile 是否已收敛:bundles == [dsh-base, dsh-web-app, @whyshu/argent-web],
7
+ * patch 里没有 argent-core/flow/gateway/ml/presets/llm-whyshu 残留,node_modules 指向仓库
8
+ * B. **在线**校验端点:/api/argent-web/health(轮询角色)、/api/argent-web/account(积分)
9
+ *
10
+ * 用法:
11
+ * node scripts/argent-web-verify.mjs # 自动找 web 端口(默认 3080)
12
+ * node scripts/argent-web-verify.mjs --base http://127.0.0.1:3080
13
+ * node scripts/argent-web-verify.mjs --offline # 只跑 A
14
+ *
15
+ * 退出码:0 全通 | 1 未就绪(多半是 web 没启动)| 2 结构不对
16
+ */
17
+ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs'
18
+ import { execSync } from 'node:child_process'
19
+ import { homedir } from 'node:os'
20
+ import { join } from 'node:path'
21
+
22
+ const args = process.argv.slice(2)
23
+ const offline = args.includes('--offline')
24
+ const baseArg = args.includes('--base') ? args[args.indexOf('--base') + 1] : ''
25
+ const profileDir = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'profiles', 'web')
26
+
27
+ let fails = 0
28
+ const ok = (c, msg) => { console.log(`${c ? '✅' : '❌'} ${msg}`); if (!c) fails++ }
29
+
30
+ // ── A. profile 结构 ──
31
+ const pkgFile = join(profileDir, 'package.json')
32
+ const patchFile = join(profileDir, 'cordis.patch.yml')
33
+ if (!existsSync(pkgFile)) { ok(false, `找不到 ${pkgFile}`); process.exit(2) }
34
+ const pkg = JSON.parse(readFileSync(pkgFile, 'utf8'))
35
+ const bundles = (pkg.dsh && pkg.dsh.profile && pkg.dsh.profile.bundles) || []
36
+ const want = ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@whyshu/argent-web'].sort()
37
+ ok(JSON.stringify([...bundles].sort()) === JSON.stringify(want), `bundles 收敛为 3 个(实际:${bundles.join(', ')})`)
38
+ ok(Boolean((pkg.dependencies || {})['@whyshu/argent-web']), '依赖含 @whyshu/argent-web')
39
+ const leftovers = Object.keys(pkg.dependencies || {}).filter((d) => /^(argent-(core|flow|gateway|presets)|@whyshu\/argent-(ml|skin|dsh))$/.test(d))
40
+ ok(leftovers.length === 0, `deps 无 argent 旧包残留${leftovers.length ? ':' + leftovers.join(',') : ''}`)
41
+
42
+ const patch = readFileSync(patchFile, 'utf8')
43
+ const patchLeft = ['argent-core', 'argent-flow', 'argent-gateway', 'argent-ml', 'argent-presets', 'llm-whyshu'].filter((id) => patch.includes(`id: ${id}`))
44
+ ok(patchLeft.length === 0, `patch 无旧行残留${patchLeft.length ? ':' + patchLeft.join(',') : ''}`)
45
+
46
+ const nm = join(profileDir, 'node_modules', '@whyshu', 'argent-web')
47
+ if (!existsSync(nm)) ok(false, 'node_modules 缺 @whyshu/argent-web')
48
+ else {
49
+ ok(lstatSync(nm).isSymbolicLink(), 'node_modules/@whyshu/argent-web 是软链(改仓库即生效)')
50
+ ok(realpathSync(nm) === realpathSync(join(process.cwd(), 'plugins', 'argent-web')), '软链指向仓库 plugins/argent-web')
51
+ }
52
+
53
+ if (offline) { console.log(fails ? `\n❌ ${fails} 项未通过` : '\n✅ profile 结构正确'); process.exit(fails ? 2 : 0) }
54
+
55
+ // ── B. 在线端点 ──
56
+ /**
57
+ * 端口发现:web 的端口可能不是 3080(可 --port 或 --base 指定)。
58
+ * 先试 3080,再用 lsof 找 dsh 进程监听端口逐个探测 /api/argent-web/health。
59
+ */
60
+ async function discoverBase() {
61
+ if (baseArg) return baseArg.replace(/\/+$/, '')
62
+ const candidates = []
63
+ try {
64
+ const out = execSync("lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null | grep -iE 'deepseek|node' | grep -oE ':[0-9]{4,5}' | tr -d ':' | sort -u", { encoding: 'utf8', timeout: 8000 })
65
+ for (const p of out.split('\n').filter(Boolean)) candidates.push(Number(p))
66
+ } catch { /* ignore */ }
67
+ for (const p of [3080, ...candidates]) {
68
+ const b = `http://127.0.0.1:${p}`
69
+ try {
70
+ const r = await fetch(`${b}/api/argent-web/health`, { signal: AbortSignal.timeout(1200) })
71
+ if (r.status) return b
72
+ } catch { /* next */ }
73
+ }
74
+ return 'http://127.0.0.1:3080'
75
+ }
76
+ const base = await discoverBase()
77
+ const get = async (p) => {
78
+ const r = await fetch(base + p, { signal: AbortSignal.timeout(8000) })
79
+ return { status: r.status, body: await r.json().catch(() => ({})) }
80
+ }
81
+ let h
82
+ try { h = await get('/api/argent-web/health') } catch (e) {
83
+ ok(false, `连不上 ${base}:${e.message}(web 没启动?启动后重跑)`)
84
+ console.log(`\n❌ ${fails} 项未通过(结构 OK,在线部分未验)`)
85
+ process.exit(1)
86
+ }
87
+ ok(h.status === 200 && h.body.ok === true, `/api/argent-web/health 200(role=${h.body.role})`)
88
+ const acct = await get('/api/argent-web/account')
89
+ ok(acct.status === 200 && acct.body.ok === true, `/api/argent-web/account 200(积分=${acct.body.points} · 套餐=${acct.body.plan})`)
90
+ // poller 模式的 health 由 office-runtime 生成,不带 role 字段 ⇒ 用 /api/argent-office 是否可达来判定
91
+ let mode = h.body.role
92
+ if (!mode) {
93
+ const probe = await fetch(`${base}/api/argent-office/snapshot`, { signal: AbortSignal.timeout(3000) }).catch(() => null)
94
+ mode = probe && probe.status < 500 ? 'poller' : 'ui'
95
+ }
96
+
97
+ if (mode === 'poller') {
98
+ const off = await get('/api/argent-office/snapshot').catch(() => null)
99
+ ok(Boolean(off && off.status < 500), `poller 模式:/api/argent-office 可达(${off && off.status})`)
100
+ } else {
101
+ console.log(`ℹ️ 本端为 UI 模式(轮询由 pid ${(h.body.holder && h.body.holder.pid) || '?'} 持有),跳过 ERP 端点`)
102
+ }
103
+
104
+ console.log(fails ? `\n❌ ${fails} 项未通过` : '\n✅ argent-web 全通:单 bundle + 端点 + 积分')
105
+ process.exit(fails ? 2 : 0)
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * billing-upload.mjs —— 计费事件上报 CLI(v0.9.0,默认**不发**)
4
+ *
5
+ * 用法:
6
+ * node scripts/billing-upload.mjs # 未配置 URL ⇒ 只打印 not_configured
7
+ * ARGENT_BILLING_URL=https://... node scripts/billing-upload.mjs
8
+ *
9
+ * 环境:
10
+ * ARGENT_DATA_DIR 数据根(默认 ~/.dsh/argent)
11
+ * ARGENT_BILLING_URL 上报端点(**唯一开关**;不给就绝不发)
12
+ * ARGENT_BILLING_TOKEN 可选 Bearer
13
+ *
14
+ * 退出码:0 完成(含"没东西要传")|2 有批次失败(下次会重试)
15
+ */
16
+ import { homedir } from 'node:os'
17
+ import { join } from 'node:path'
18
+ import { uploadPending } from '../core/mcp/billing-upload.mjs'
19
+
20
+ const dataDir = process.env.ARGENT_DATA_DIR || join(homedir(), '.dsh', 'argent')
21
+ const url = process.env.ARGENT_BILLING_URL || ''
22
+ const token = process.env.ARGENT_BILLING_TOKEN || ''
23
+
24
+ const r = await uploadPending({ dataDir, url, token })
25
+ console.log(JSON.stringify({ dataDir, configured: Boolean(url), ...r }))
26
+ process.exit(r.ok === false ? 0 : r.failed > 0 ? 2 : 0)
@@ -53,7 +53,8 @@ function pkgManifest() {
53
53
  description: 'Argent 引擎(L1):流程/台账/重试/守卫/审计/浏览器自动化 —— 逐字节来自 argent-dsh 仓库',
54
54
  type: 'module',
55
55
  engines: { node: '>=20' },
56
- files: ['engine/', 'MANIFEST.json', 'requirements.txt'],
56
+ files: ['engine/', 'bin/', 'MANIFEST.json', 'requirements.txt'],
57
+ bin: { 'argent-engine-runtime': 'bin/runtime-install.mjs' },
57
58
  exports: {
58
59
  './version': './engine/version.mjs',
59
60
  './registry': './engine/scripts/lib/registry.mjs',
@@ -87,6 +88,11 @@ export function build(outDir) {
87
88
  // Python 侧车需求清单(复核批指出缺口:包内没有需求清单,客户机无法装运行时)
88
89
  const REQS = ['openpyxl', 'pyyaml', 'pillow', 'playwright', 'selenium']
89
90
  writeFileSync(join(outDir, 'requirements.txt'), REQS.join('\n') + '\n')
91
+ // 自带 runtime 安装器(替代已退役启动器):客户机 npx 自拉即可更新 ~/.argent-dsh
92
+ mkdirSync(join(outDir, 'bin'), { recursive: true })
93
+ const installer = readFileSync(join(REPO, 'scripts', 'engine-runtime-install.mjs'))
94
+ writeFileSync(join(outDir, 'bin', 'runtime-install.mjs'), installer)
95
+ chmodSync(join(outDir, 'bin', 'runtime-install.mjs'), 0o755)
90
96
  writeFileSync(join(outDir, 'package.json'), pkgManifest())
91
97
  writeFileSync(join(outDir, 'MANIFEST.json'), JSON.stringify(manifest, null, 2) + '\n')
92
98
  return { outDir, count: files.length, manifest }