@whyshu/argent-engine 0.8.0-rc.2 → 0.8.0-rc.4

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 (33) hide show
  1. package/MANIFEST.json +30 -21
  2. package/engine/VERSION +1 -1
  3. package/engine/core/contracts/argent.contracts.json +1 -1
  4. package/engine/scripts/appointment-create.mjs +2 -2
  5. package/engine/scripts/argent-machine-setup.mjs +3 -1
  6. package/engine/scripts/argent-runner.mjs +4 -2
  7. package/engine/scripts/build-engine-package.mjs +1 -1
  8. package/engine/scripts/capability-packs.lock.json +19 -19
  9. package/engine/scripts/check-argent-desktop.mjs +91 -0
  10. package/engine/scripts/erp_invoice_shadow.py +62 -0
  11. package/engine/scripts/erp_invoice_writeback.py +93 -0
  12. package/engine/scripts/flow-requirements.json +3 -3
  13. package/engine/scripts/flow-session-retention.mjs +2 -1
  14. package/engine/scripts/flow_source.py +10 -1
  15. package/engine/scripts/flow_sources/__init__.py +1 -0
  16. package/engine/scripts/flow_sources/erp.py +54 -0
  17. package/engine/scripts/gen-agent-bundles.mjs +1 -1
  18. package/engine/scripts/invoice_lip_runner.py +43 -0
  19. package/engine/scripts/lib/plugin-packages.mjs +3 -0
  20. package/engine/scripts/orchestrator.py +173 -5
  21. package/engine/scripts/orchestrator_br.py +89 -1
  22. package/engine/scripts/query_runner.py +2 -3
  23. package/engine/scripts/release-gate-0.8.mjs +81 -0
  24. package/engine/scripts/session-handoff.mjs +2 -1
  25. package/engine/scripts/skuflow_invoice_runner.py +145 -0
  26. package/engine/scripts/xzh-browser.sh +2 -1
  27. package/engine/scripts/xzh_browser.py +1 -1
  28. package/engine/skills/ml-fulfillment-sop/references/agentic-runtime-v3.md +1 -1
  29. package/engine/tools/agentic/README.md +95 -0
  30. package/engine/tools/agentic/mcp_server.py +212 -0
  31. package/engine/tools/agentic/ml_agent_tools.py +602 -0
  32. package/engine/version.mjs +1 -1
  33. package/package.json +1 -1
@@ -2562,6 +2562,19 @@ FALLBACK_DATE_JS = r"""() => {
2562
2562
  }
2563
2563
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2564
2564
  }
2565
+ // 目标月不在视图:若视图已是**更晚的月份**(目标 10/30、日历已翻到 11 月),
2566
+ // 直接选视图内第一个可用日(>= 目标);⛔ 不再为了“精确目标日”继续翻到 12 月。
2567
+ const viewMonth = viewMonths[0];
2568
+ const viewDate = new Date(viewYear, viewMonth, 1);
2569
+ const targetMonthDate = new Date(target.getFullYear(), target.getMonth(), 1);
2570
+ if (viewDate > targetMonthDate) {
2571
+ for (let i = 0; i < n; i++) {
2572
+ const t = (days[i].textContent || '').trim();
2573
+ if (/^\d+$/.test(t) && !days[i].classList.contains('day--disabled')) {
2574
+ return {found: true, idx: i, mode: 'next_available', header: headerText};
2575
+ }
2576
+ }
2577
+ }
2565
2578
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2566
2579
  }
2567
2580
  // header 不可靠:降级为「目标日数字 + 视图内该数字后的第一个可用格」(last resort)
@@ -9627,6 +9640,52 @@ class Orchestrator:
9627
9640
  "why": (verdict.get("lift") or {}).get("reason") or "",
9628
9641
  })
9629
9642
 
9643
+ async def _open_appointment_via_hub(self) -> None:
9644
+ """从列表/hub 进入 appointment-v2(新 UI 的两跳;已在预约页则 no-op)。
9645
+
9646
+ 只读判断 + 两次点击(Completar envío / Elige cómo…),不提交预约。
9647
+ """
9648
+ sid = str(self.state.shipment_id or "")
9649
+ if not sid:
9650
+ return
9651
+ try:
9652
+ url = self.browser.page.url or ""
9653
+ except Exception: # noqa: BLE001
9654
+ url = ""
9655
+ if "appointment" in url:
9656
+ return
9657
+ if "/hub" not in url:
9658
+ try:
9659
+ clicked = await self.browser.click_button("Completar envío", "button", step=4, wait_after=0)
9660
+ except Exception: # noqa: BLE001
9661
+ clicked = "notfound"
9662
+ if clicked != "clicked":
9663
+ # 可能已经停在 hub(步骤3正常收口)⇒ 不因找不到按钮而失败
9664
+ self._log(" ℹ️ 未命中「Completar envío」按钮(可能已在 hub)⇒ 继续找预约入口")
9665
+ else:
9666
+ self._log(" ✅ 已点「Completar envío」⇒ 进入 hub")
9667
+ for _ in range(10):
9668
+ try:
9669
+ if "/hub" in (self.browser.page.url or "") or "appointment" in (self.browser.page.url or ""):
9670
+ break
9671
+ except Exception: # noqa: BLE001
9672
+ pass
9673
+ await asyncio.sleep(1)
9674
+ try:
9675
+ await self.browser.page.wait_for_selector('a[href*="/appointment"]', timeout=20000)
9676
+ await self.browser.click_selector('a[href*="/appointment"]', step=4, wait_after=3)
9677
+ self._log(" ✅ 已点「Elige cómo y cuándo…」⇒ appointment-v2")
9678
+ except Exception as exc: # noqa: BLE001
9679
+ self._log(f" ⚠️ hub 预约入口未命中({type(exc).__name__})⇒ 回退直接 URL")
9680
+ await self.browser.visit_plan_page("appointment-v2", sid, step=4)
9681
+ for _ in range(15):
9682
+ try:
9683
+ if "appointment" in (self.browser.page.url or ""):
9684
+ return
9685
+ except Exception: # noqa: BLE001
9686
+ pass
9687
+ await asyncio.sleep(1)
9688
+
9630
9689
  async def step4_appointment(self) -> None:
9631
9690
  self._log("步骤4 货件预约时间")
9632
9691
  # 同店步骤4互斥锁(方案C,2026-08-14):**保守串行**,不是已验证的平台规则。
@@ -9667,6 +9726,10 @@ class Orchestrator:
9667
9726
  f"{(_cap.get('lift') or {}).get('reason')}")
9668
9727
  # 4a. 进入预约页(优先用货件号拼 URL,其次从 URL 提取 inbound ID)
9669
9728
  await self.browser.visit_plan_page("appointment-v2", self.state.shipment_id, step=4)
9729
+ # 4a1. 新 UI 兜底(2026-10-29):/appointment-v2 在「刚建单、尚未点 Completar envío」
9730
+ # 时会重定向回列表页(实测 80893392:列表 → Completar envío → hub → Elige cómo…)。
9731
+ # 直接 URL 只对已进入预约页的货件有效;这里补两跳,避免把“页面形态”误判成失败。
9732
+ await self._open_appointment_via_hub()
9670
9733
  # 4a2. 已有预约检测(2026-08-25 实测:预约成功后中断/重跑时,页面显示
9671
9734
  # 已预约状态(含 Cancelar reserva 按钮)而非空白表单——旧逻辑继续
9672
9735
  # 走选运输方式流程 → 日历区 Confirmar 找不到 → 误报失败。
@@ -9692,6 +9755,7 @@ class Orchestrator:
9692
9755
  self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
9693
9756
  await self.browser.visit_plan_page("appointment-v2",
9694
9757
  self.state.shipment_id, step=4)
9758
+ await self._open_appointment_via_hub()
9695
9759
  for attempt in range(3): # 同一日期内的时段重试
9696
9760
  if attempt > 0:
9697
9761
  self._log(f" 🔁 预约提交未生效,换下一时段重试(第 {attempt + 1}/3 次)")
@@ -13247,7 +13311,31 @@ class Orchestrator:
13247
13311
  return self._result("failed", failed_step=step_filter or 1, error=env_exc.to_dict(),
13248
13312
  step_summaries={}, dry_run=dry_run)
13249
13313
 
13250
- steps = [step_filter] if step_filter else list(range(1, 9))
13314
+ if self.state.shipment_id and not step_filter:
13315
+ # 已有货件号:先用 hub 只读状态判断真实进度;跳过 1-3 的重复打开/建单。
13316
+ # 实测:每次 full 都从步骤1 重开一遍,既慢又会让用户看到“明明有档期却重开”。
13317
+ try:
13318
+ _hub = await self.hub_status(self.state.shipment_id, step=0)
13319
+ _v = self._hub_verdict_of(_hub)
13320
+ self._log(f" 🛰️ 已有货件 #{self.state.shipment_id} hub 状态:"
13321
+ f"{_v.get('reason') or '不可用'}")
13322
+ if _v.get("operationally_complete"):
13323
+ self._log(" ✅ hub 判定已完成 ⇒ 不再重复步骤")
13324
+ for _s in range(1, 9):
13325
+ self._mark_done(_s)
13326
+ steps = []
13327
+ else:
13328
+ for _s in (1, 2, 3):
13329
+ self._mark_done(_s)
13330
+ steps = [4, 5, 6, 7, 8]
13331
+ except Exception as exc: # noqa: BLE001
13332
+ self._log(f" ⚠️ hub 状态探测失败,按已有货件从步骤4续跑: "
13333
+ f"{type(exc).__name__}: {exc}")
13334
+ for _s in (1, 2, 3):
13335
+ self._mark_done(_s)
13336
+ steps = [4, 5, 6, 7, 8]
13337
+ else:
13338
+ steps = [step_filter] if step_filter else list(range(1, 9))
13251
13339
  step_summaries: dict[int, Any] = {}
13252
13340
 
13253
13341
  result = await self._execute_steps(steps, allow_write, dry_run, step_summaries)
@@ -50,9 +50,8 @@ def _default_orchestrator() -> Path:
50
50
  profile_home / "scripts/orchestrator.py",
51
51
  profile_home / "roles/ml-fulfillment/scripts/orchestrator.py",
52
52
  profile_home / "skills/mercadolibre/ml-fulfillment-sop/scripts/fulfillment_orchestrator.py",
53
- Path.home() / "Code/argent-ml-seller/scripts/orchestrator.py",
54
- Path.home() / "Code/argent-ml/roles/ml-fulfillment/scripts/orchestrator.py",
55
- Path.home() / "Code/argent-ml/skills/mercadolibre/ml-fulfillment-sop/scripts/fulfillment_orchestrator.py",
53
+ # 2026-10-29:legacy 仓(argent-ml / argent-ml-seller)已归档;只认当前主线仓
54
+ Path.home() / "Code/argent-dsh/scripts/orchestrator.py",
56
55
  ]
57
56
  for c in candidates:
58
57
  if c.is_file():
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Argent 0.8 发布门禁(release gate)——只跑“影响客户机运行/发布完整性”的判据。
4
+ *
5
+ * 为什么不是直接跑 run-tests.sh:仓库里有大量历史/文档/测试夹具门禁,
6
+ * 它们对发布安全有价值,但不能把“旧文档计数”当成客户机阻塞项。
7
+ * 本清单是唯一发布门禁;其余测试继续保留在全量套件里,作为后续硬化。
8
+ *
9
+ * 用法:
10
+ * node scripts/release-gate-0.8.mjs
11
+ * node scripts/release-gate-0.8.mjs --list
12
+ * node scripts/release-gate-0.8.mjs --json
13
+ */
14
+ import { spawnSync } from 'node:child_process'
15
+ import { existsSync } from 'node:fs'
16
+ import { dirname, join, resolve } from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+
19
+ const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..')
20
+ const TESTS = [
21
+ 'scripts/tests/version-consistency.test.mjs',
22
+ 'scripts/tests/capability-pack.test.mjs',
23
+ 'scripts/tests/manifest-consistency.test.mjs',
24
+ 'scripts/tests/js-syntax.test.mjs',
25
+ 'scripts/tests/engine-package.test.mjs',
26
+ 'scripts/tests/kernel-purity.test.mjs',
27
+ 'scripts/tests/plugin-peer-coverage.test.mjs',
28
+ 'scripts/tests/is-direct-run.test.mjs',
29
+ 'scripts/tests/config-validate.test.mjs',
30
+ 'scripts/tests/profile-doctor.test.mjs',
31
+ 'scripts/tests/argent-datadir.test.mjs',
32
+ 'scripts/tests/datadir-literal-gate.test.mjs',
33
+ 'scripts/tests/datadir-writes-gate.test.mjs',
34
+ 'scripts/tests/agentic-no-lip.test.mjs',
35
+ 'scripts/tests/core-mcp-shared.test.mjs',
36
+ 'scripts/tests/mcp-tool-annotations.test.mjs',
37
+ 'scripts/tests/mcp-collapse.test.mjs',
38
+ 'scripts/tests/mcp-host-poc.test.mjs',
39
+ 'scripts/tests/setup-hook.test.mjs',
40
+ 'scripts/tests/customer-config-migrate.test.mjs',
41
+ 'scripts/tests/dsh-versions.test.mjs',
42
+ 'scripts/tests/capability-stats.test.mjs',
43
+ 'scripts/tests/readme-install-path.test.mjs',
44
+ 'scripts/tests/agent-bundle-generation.test.mjs',
45
+ ]
46
+ const OUT_OF_GATE = [
47
+ ['docs-consistency / criteria-fresh / handover-fresh', '文档/历史计数,不影响客户机运行'],
48
+ ['argent-datadir-parity', '旧的 shell/Python 二级链白名单;主 datadir 判据已在门禁内'],
49
+ ['setup-hook-wiring / argv 等', '测试会写真实数据目录;属测试夹具问题'],
50
+ ['flow-auto-retry / flow-failure / flow-preflight', '旧流程断言;0.8 RC 发布后作为硬化项'],
51
+ ['arg... 旧插件设置入口', '兼容插件,不阻塞 Agentic Runtime 发布'],
52
+ ['Python 旧流程断言', '同上;需产品级回归后再纳入'],
53
+ ]
54
+
55
+ const args = process.argv.slice(2)
56
+ if (args.includes('--list')) {
57
+ console.log(TESTS.join('\n'))
58
+ process.exit(0)
59
+ }
60
+ if (!existsSync(join(REPO, 'VERSION'))) {
61
+ console.error('不是 Argent 仓库根(缺 VERSION)')
62
+ process.exit(2)
63
+ }
64
+ let failed = 0
65
+ const rows = []
66
+ for (const rel of TESTS) {
67
+ const file = join(REPO, rel)
68
+ if (!existsSync(file)) { rows.push({ rel, ok: false, msg: 'missing' }); failed++; continue }
69
+ const r = spawnSync(process.execPath, [file], { cwd: REPO, encoding: 'utf8', timeout: 180000 })
70
+ const ok = r.status === 0
71
+ rows.push({ rel, ok, msg: String(r.stdout || r.stderr || '').trim().split('\n').slice(-1)[0] || '' })
72
+ if (!ok) failed++
73
+ }
74
+ if (args.includes('--json')) {
75
+ console.log(JSON.stringify({ release: '0.8.0-rc.2', gate: TESTS.length, failed, rows, outOfGate: OUT_OF_GATE }, null, 2))
76
+ } else {
77
+ for (const r of rows) console.log(`${r.ok ? '✅' : '❌'} ${r.rel}${r.msg ? ` ${r.msg}` : ''}`)
78
+ console.log(`\n${failed ? '❌' : '✅'} release-gate-0.8: ${TESTS.length - failed}/${TESTS.length} 通过`)
79
+ if (failed) console.log('\n不在本门禁内的历史/夹具项:\n' + OUT_OF_GATE.map(([a, b]) => ` · ${a} — ${b}`).join('\n'))
80
+ }
81
+ process.exit(failed ? 1 : 0)
@@ -9,13 +9,14 @@ import { readFileSync, readdirSync, statSync, mkdirSync, writeFileSync, existsSy
9
9
  import { join } from 'node:path'
10
10
  import { homedir } from 'node:os'
11
11
  import { zstdDecompressSync } from 'node:zlib'
12
+ import { resolveDataDir } from './lib/argent-datadir.mjs'
12
13
 
13
14
  const args = process.argv.slice(2)
14
15
  const has = (f) => args.includes(f)
15
16
  const val = (f, d) => { const i = args.indexOf(f); return i >= 0 && args[i + 1] ? args[i + 1] : d }
16
17
  const HOME = process.env.HOME || homedir()
17
18
  const ROOT = join(HOME, '.dsh', 'sessions')
18
- const OUT = join(HOME, '.dsh', 'argent', 'session-handoffs')
19
+ const OUT = join(resolveDataDir({ env: process.env }).dir, 'session-handoffs')
19
20
  const FORMAT = val('--format', 'v3'); const LIMIT = Number(val('--limit', '0')) || 0; const WRITE = has('--write')
20
21
  const DAYS = Number(val('--days', '10')) || 0 // 只处理最近 N 天内动过的主会话(0 = 全部)
21
22
  const CHILDREN = has('--include-children') // 默认**排除**子会话(delegationDepth>0)
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env python3
2
+ """SkuFlow bulkLabel 发票适配器(鑫中航;复用既有 invoice_runner/invoice_stageb)。
3
+
4
+ 输入:--record-json '<json>'(SkuFlow task.context)
5
+ 输出:stdout 最后一行 JSON {ok, invoicePath, bulkLabelPath, orderNo} 或 {ok:false,error}
6
+ 注意:默认会调用既有鑫中航上传/下载流程;离线只生成用 --generate-only。
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ HERE = Path(__file__).resolve().parent
15
+ sys.path.insert(0, str(HERE))
16
+ DATA = Path(os.environ.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
17
+
18
+ from invoice_runner import load_mapping, generate_invoice # noqa: E402
19
+
20
+
21
+ def build_record(ctx: dict) -> dict:
22
+ return {
23
+ '货件号': str(ctx.get('shipmentNo') or ''),
24
+ '店铺名称': str(ctx.get('store') or ''),
25
+ '品名': str(ctx.get('productName') or ctx.get('sku') or ''),
26
+ '数量': int(ctx.get('quantity') or 0),
27
+ '箱数': int(ctx.get('boxCount') or 0),
28
+ '国内收货仓库': '深圳仓',
29
+ '备注': str(ctx.get('content') or 'SkuFlow'),
30
+ '到达时间': str(ctx.get('shipDate') or ''),
31
+ 'sku_data': {
32
+ '品名英文': str(ctx.get('nameEn') or ctx.get('productName') or ctx.get('sku') or ''),
33
+ '海关编码': str(ctx.get('hsCode') or ''),
34
+ '材质英文': str(ctx.get('materialEn') or ''),
35
+ '材质中文': str(ctx.get('material') or ''),
36
+ '重量(kg/箱)': ctx.get('weight') or '',
37
+ '长(cm)': ctx.get('length') or '',
38
+ '宽(cm)': ctx.get('width') or '',
39
+ '高(cm)': ctx.get('height') or '',
40
+ },
41
+ }
42
+
43
+
44
+ def build_wenyao_fixture(ctx: dict, rec: dict) -> dict:
45
+ boxes = max(1, int(rec['箱数'] or 1))
46
+ return {
47
+ '产品名称': rec['品名'], '货件号': rec['货件号'], 'SKU': str(ctx.get('sku') or ''),
48
+ '店铺': str(ctx.get('store') or ''), '数量': int(rec['数量'] or 0), '箱数': boxes,
49
+ '装箱数': max(1, int(rec['数量'] or 0) // boxes),
50
+ '重量': float(ctx.get('weight') or 0), '长': float(ctx.get('length') or 0),
51
+ '宽': float(ctx.get('width') or 0), '高': float(ctx.get('height') or 0),
52
+ '材质': str(ctx.get('material') or ''), 'HS编码': str(ctx.get('hsCode') or ''),
53
+ '产品图': '',
54
+ }
55
+
56
+
57
+ def run_wenyao(ctx: dict, rec: dict, generate_only: bool) -> dict:
58
+ """文鳐:SkuFlow fixture → p3/p4 → 门户 p6-p14;门户回写由本适配器接管,不写 lip。"""
59
+ import wenyao_run as wr
60
+ shipment = rec['货件号']
61
+ fixture = build_wenyao_fixture(ctx, rec)
62
+ wr.FIX_DIR.mkdir(parents=True, exist_ok=True)
63
+ fx = wr.FIX_DIR / f'skuflow-{ctx.get("skuFlowId","")}-{shipment}.json'
64
+ fx.write_text(json.dumps(fixture, ensure_ascii=False))
65
+ template = wr.DOWN_DIR / '跨境电商-下单模板.xlsx'
66
+ if not template.exists():
67
+ raise RuntimeError(f'文鳐模板不存在: {template}')
68
+ r3 = wr.p3_fill(str(fx), str(ctx.get('nameEn') or rec['品名']), '', None,
69
+ material_en=str(ctx.get('materialEn') or ''), write_dict=False)
70
+ wr.p4_verify(r3['xlsx'], str(template))
71
+ out = {'ok': True, 'invoicePath': r3['xlsx'], 'bulkLabelPath': '', 'orderNo': shipment}
72
+ if generate_only:
73
+ return out
74
+ import wenyao_portal as wp
75
+ orig = wr._writeback
76
+ wr._writeback = lambda *a, **k: None # 门户 P13/P14 的 lip 回写由 SkuFlow/ERP 接管
77
+ try:
78
+ class A: pass
79
+ a = A(); a.shipment = shipment; a.english_name = str(ctx.get('nameEn') or rec['品名'])
80
+ r1 = {'record_id': ''}
81
+ r2 = {'fixture': fixture}
82
+ with wp.portal_lock(site=f'portal.{shipment}', timeout=wp.portal_lock_timeout(),
83
+ reporter=lambda m: None) as waited:
84
+ final = wr.p6_p14_portal(a, r1, r2, r3, 1, wp, waited)
85
+ if not final:
86
+ raise RuntimeError('文鳐大货标签未生成')
87
+ out['bulkLabelPath'] = str(final)
88
+ finally:
89
+ wr._writeback = orig
90
+ return out
91
+
92
+
93
+ def main() -> int:
94
+ ap = argparse.ArgumentParser()
95
+ ap.add_argument('--record-json', required=True)
96
+ ap.add_argument('--generate-only', action='store_true')
97
+ ap.add_argument('--template', default='')
98
+ a = ap.parse_args()
99
+ out = {}
100
+ try:
101
+ ctx = json.loads(a.record_json)
102
+ rec = build_record(ctx)
103
+ missing = [k for k in ('货件号', '店铺名称', '数量', '箱数') if not rec.get(k)]
104
+ if missing:
105
+ raise RuntimeError(f"缺字段: {', '.join(missing)}")
106
+ sku = rec['sku_data']
107
+ miss2 = [k for k in ('海关编码', '材质中文', '重量(kg/箱)', '长(cm)', '宽(cm)', '高(cm)') if not sku.get(k)]
108
+ if miss2:
109
+ raise RuntimeError(f"SKU 发票主数据缺: {', '.join(miss2)}")
110
+ forwarder = str(ctx.get('forwarder') or '')
111
+ if '文鳐' in forwarder:
112
+ out = run_wenyao(ctx, rec, a.generate_only)
113
+ print(json.dumps(out, ensure_ascii=False))
114
+ return 0 if out.get('ok') else 1
115
+ if '鑫中航' not in forwarder:
116
+ raise RuntimeError(f"未知货代: {forwarder or '(空)'}")
117
+ mapping = load_mapping()
118
+ tpl = Path(a.template) if a.template else (DATA / 'invoice-templates' / 'xzh-template.xlsx')
119
+ if not tpl.exists():
120
+ tpl = Path(str(mapping.get('templates', {}).get('鑫中航') or ''))
121
+ if not tpl.exists():
122
+ raise RuntimeError(f"模板不存在: {tpl}")
123
+ import openpyxl
124
+ wb = openpyxl.load_workbook(tpl)
125
+ out_dir = DATA / 'invoice-output'
126
+ out_dir.mkdir(parents=True, exist_ok=True)
127
+ invoice = out_dir / f"skuflow-{ctx.get('skuFlowId','')}-{rec['货件号']}.xlsx"
128
+ generate_invoice(rec, mapping, wb, invoice)
129
+ out = {'ok': True, 'invoicePath': str(invoice), 'bulkLabelPath': '', 'orderNo': rec['货件号']}
130
+ if not a.generate_only:
131
+ from invoice_stageb import upload_invoice, download_label
132
+ if not upload_invoice(str(invoice), order_no=rec['货件号']):
133
+ raise RuntimeError('鑫中航上传失败')
134
+ label = download_label(rec['货件号'])
135
+ if not label:
136
+ raise RuntimeError('大货标签下载失败')
137
+ out['bulkLabelPath'] = str(label)
138
+ except Exception as e:
139
+ out = {'ok': False, 'error': str(e)[:500]}
140
+ print(json.dumps(out, ensure_ascii=False))
141
+ return 0 if out.get('ok') else 1
142
+
143
+
144
+ if __name__ == '__main__':
145
+ raise SystemExit(main())
@@ -2,7 +2,8 @@
2
2
  # 鑫中航常驻浏览器:启动/停止/状态(保留一个标签页给登录态)
3
3
  set -u
4
4
  ROOT="${ARGENT_DSH_HOME:-$HOME/.argent-dsh}"
5
- DATA="${ARGENT_DATA_DIR:-$HOME/.dsh/argent}"
5
+ . "$ROOT/scripts/lib/argent-datadir.sh"
6
+ DATA="$ARGENT_DATA_DIR_RESOLVED"
6
7
  PY="$DATA/venv/bin/python3"
7
8
  [ -x "$PY" ] || PY="$(command -v python3)"
8
9
  LOG="$DATA/xzh-browser.log"
@@ -3,7 +3,7 @@
3
3
 
4
4
  用法:
5
5
  python3 scripts/xzh_browser.py # 前台常驻(调试)
6
- nohup ... > ~/.dsh/argent/xzh-browser.log 2>&1 &
6
+ nohup ... > <数据目录>/xzh-browser.log 2>&1 &
7
7
  启动后监听 127.0.0.1:9223;invoice_stageb 会自动 connect_over_cdp。
8
8
  """
9
9
  import json
@@ -35,5 +35,5 @@ probe → 判断 → 调用工具 → 读回验证 → 继续 / 信号 ERP / 结
35
35
  ## 完成条件
36
36
 
37
37
  - `ml_probe_hub` 五项/整票状态与任务目标一致;
38
- - 需要回写的文件已通过 `ml_writeback_lip` 读回验证;
38
+ - 需要回写的文件已通过 ERP AgentTask 完成态接口读回验证;0.8 不再写 lip 表。
39
39
  - 输出 `done` + 证据 + 耗时/成本摘要。
@@ -0,0 +1,95 @@
1
+ # Argent Agentic ML Tools(M1)
2
+
3
+ 只读探针,供本地 shadow 与后续 MCP server 复用。
4
+
5
+ ## 用法
6
+
7
+ ```bash
8
+ export ARGENT_DATA_DIR="$HOME/.dsh/argent" # 店铺映射/store list 兜底
9
+ export ARGENT_EVIDENCE_DIR="$HOME/.dsh/argent-local/evidence"
10
+
11
+ python3 tools/agentic/ml_agent_tools.py probe-hub \
12
+ --shipment 80555414 --store "墨西哥-2店-子账号" --json
13
+
14
+ python3 tools/agentic/ml_agent_tools.py probe-appointment \
15
+ --shipment 80555414 --store "墨西哥-2店-子账号" --json
16
+ ```
17
+
18
+ - 也可传 `--store-id 27494792824433`;
19
+ - 店铺窗口需已打开(本机可用 `ziniao-cli store open --name ...`);
20
+ - 只调用 `ziniao-cli page visit/exec/screenshot`,不点写按钮、不提交预约。
21
+
22
+ ## 输出
23
+
24
+ 符合 `docs/agentic-tools-contract-v1.md` 的信封;证据截图落
25
+ `$ARGENT_EVIDENCE_DIR/<日期>/`。
26
+
27
+ - `probe-hub`:五项 checklist + `operationallyComplete` + 卡片证据;
28
+ - `probe-appointment`:运输方式选项、日历可见性、平台错误页/已有预约标记。
29
+
30
+ ## M1 状态
31
+
32
+ - [x] probe-hub 本地真实店铺只读跑通:80555414 `operationallyComplete=true`;74009400 `false`(仅 appointment 未完成,labels/boxLabels 已完成);
33
+ - [x] probe-appointment 页面/选项/错误页抽取实现;74009400 正确识别 `existingAppointment=true`(已有预约时不展示运输方式下拉);
34
+ - [x] MCP stdio server(`mcp_server.py`,tools/list + tools/call 已用 80555414 实测);本地 3081 profile 已挂载(`mcp-argent-ml`);
35
+ - [ ] ERP AgentTask 派发/信号联调。
36
+
37
+ ## M1 端到端 shadow(2026-10-27 15:10)
38
+
39
+ 本地 dsh 3081 + task-board + MCP 已跑通**真实 agent 会话**:
40
+
41
+ - 任务 prompt:让 agent 调 `mcp__argent_ml__ml_probe_hub` 探测 80555414;
42
+ - 结果:agent 正确调用 MCP 工具,返回 `operationallyComplete=true`、五项全绿,
43
+ 并引用证据截图 `/Users/chester/.dsh/argent-local/evidence/20261027/hub-80555414-151020.png`;
44
+ - session:`session-50610720-0477-43d9-9e61-6ffb7934a1c1`;
45
+ - 前置修复:隔离 DSH_HOME 需要 `DEEPSEEK_API_KEY`(从本机 credentials 注入启动环境,未写入仓库)。
46
+
47
+ ## M2 ERP AgentTask 闭环(2026-10-27)
48
+
49
+ 本地 ERP `ly-agentic-local` 创建 AgentTask → `scripts/agentic-local-bridge.mjs`(ERP 侧)
50
+ → 本地 dsh task-board → agent 调 MCP `ml_probe_hub` → AgentTask `completed`。
51
+ 实测 session `session-b438c456-87f2-4d7d-b584-d9f88d09fd19`,agent 实际完成 MCP 调用。
52
+
53
+ ## 实战 canary(2026-10-27 15:28)
54
+
55
+ - 使用 lip 新 SKU 记录 `reczz28SLNgEOAjV`(HW-MX-YU-080,160 件/10 箱,墨西哥-2店-子账号);
56
+ - 步骤 1-3 成功,创建货件 **80664493**;
57
+ - 步骤 4 受阻:预约页实际返回「No contamos con citas en este momento…」,即**平台暂无可预约日期**,
58
+ 不是脚本缺陷;旧脚本将其误报为「页面形态异常」;
59
+ - 已给 `ml_probe_appointment` 增加 `noSlots` 识别与 `--current-page` 只读模式(页面限流时可直接读当前页);
60
+ - 该货件尚未预约,因此无需取消;等待平台放号后继续。
61
+
62
+ ## 受控写工具(M2)
63
+
64
+ `ml_run_full_step`:通过现有 FULL 编排器执行单步(确定性工具)。
65
+
66
+ ```bash
67
+ # 只读步骤(1/2/6)可直接跑
68
+ python3 tools/agentic/ml_agent_tools.py run-full-step --record-id reczz... --step 1 --json
69
+ # 写步骤必须带 approvalToken(环境变量 ARGENT_WRITE_APPROVAL 校验)
70
+ ARGENT_WRITE_APPROVAL=local-canary python3 tools/agentic/ml_agent_tools.py run-full-step \
71
+ --record-id reczz... --step 4 --allow-write --approval-token local-canary --json
72
+ ```
73
+
74
+ 生产由 ERP 签发 approval token;本地仅用于受控 canary。
75
+
76
+ ## 受控写工具实测(M2)
77
+
78
+ - `ml_run_full_step` 已挂到本地 MCP(`mcp__argent_ml__ml_run_full_step`);
79
+ - 只读 step1 实测 success;
80
+ - 写 step4 带本地审批 token 实测:工具正确返回 `ok:false`,引擎失败原因为平台暂无可预约日期;
81
+ - 本地审批 token 仅存于隔离 profile env(`ARGENT_WRITE_APPROVAL`),不进入仓库。
82
+
83
+ ## 预约放号 watcher(M3.5)
84
+
85
+ `ml_watch_appointment`:停留预约页低频刷新等待放号(只读)。
86
+
87
+ ```bash
88
+ python3 tools/agentic/ml_agent_tools.py watch-appointment \
89
+ --shipment 80664493 --store 墨西哥-2店-子账号 --interval-sec 60 --max-seconds 600 --json
90
+ ```
91
+
92
+ - 只刷新同一标签页,不重开店铺窗口;
93
+ - 返回 `slots_available` / `existing_appointment` 即停止;
94
+ - 平台错误页/无号继续等待,超时返回 observations;
95
+ - 自动预约(写)仍由 `ml_run_full_step` + approvalToken 执行。