@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
@@ -0,0 +1,93 @@
1
+ """发票写回 ERP(ARGENT_WRITEBACK=erp):字段 + 附件引用。
2
+
3
+ ⛔ 不打印 token;附件走 machine 上传端点(≤2MB),再把 attachment `_id` 同时作为
4
+ fileToken/attachmentId 传给 /agent-tasks/invoice-finalize(attachInvoiceFile 幂等)。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import json
10
+ import mimetypes
11
+ import os
12
+ import urllib.error
13
+ import urllib.request
14
+ from pathlib import Path
15
+
16
+ from erp_invoice_shadow import ATTACHMENT_MAP, to_erp_fields
17
+
18
+
19
+ def _config() -> dict:
20
+ env = os.environ
21
+ candidates = []
22
+ if env.get('ARGENT_AGENT_REPORT'):
23
+ candidates.append(Path(env['ARGENT_AGENT_REPORT']))
24
+ data_dir = Path(env.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
25
+ candidates += [data_dir / 'agent-report.json', Path.home() / '.dsh-argent' / 'argent' / 'agent-report.json']
26
+ for f in candidates:
27
+ try:
28
+ d = json.loads(f.read_text())
29
+ if d.get('serverUrl') and d.get('tenantAppId') and d.get('machineId') and d.get('machineToken'):
30
+ return d
31
+ except Exception:
32
+ continue
33
+ raise RuntimeError('ERP 写回:找不到 agent-report.json(serverUrl/tenantAppId/machineId/machineToken)')
34
+
35
+
36
+ def _post(path: str, body: dict) -> tuple[int, dict]:
37
+ cfg = _config()
38
+ url = f"{str(cfg['serverUrl']).rstrip('/')}{path}"
39
+ req = urllib.request.Request(url, data=json.dumps(body, ensure_ascii=False).encode('utf-8'), method='POST',
40
+ headers={'content-type': 'application/json', 'authorization': f"Bearer {cfg['machineToken']}"})
41
+ try:
42
+ with urllib.request.urlopen(req, timeout=60) as resp:
43
+ raw = resp.read().decode('utf-8', errors='replace')
44
+ return resp.status, (json.loads(raw) if raw else {})
45
+ except urllib.error.HTTPError as e:
46
+ raw = e.read().decode('utf-8', errors='replace')
47
+ try:
48
+ return e.code, json.loads(raw)
49
+ except Exception:
50
+ return e.code, {'ok': False, 'error': {'code': 'http_error', 'message': raw[:500]}}
51
+
52
+
53
+ def upload_attachment(path) -> dict:
54
+ p = Path(path)
55
+ data = base64.b64encode(p.read_bytes()).decode('ascii')
56
+ mime = mimetypes.guess_type(p.name)[0] or 'application/octet-stream'
57
+ cfg = _config()
58
+ status, doc = _post(f"/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/attachments", {
59
+ 'filename': p.name, 'mime': mime, 'dataBase64': data, 'kind': 'invoice-file',
60
+ })
61
+ att = (doc.get('data') or {}).get('attachment') or {}
62
+ if not doc.get('ok') or not att.get('_id'):
63
+ raise RuntimeError(f"ERP 附件上传失败(HTTP {status}):{(doc.get('error') or {}).get('message') or doc}")
64
+ return {
65
+ 'attachmentId': str(att['_id']), 'fileToken': str(att['_id']),
66
+ 'filename': att.get('filename') or p.name, 'mime': att.get('mime') or mime,
67
+ 'size': att.get('size') if isinstance(att.get('size'), int) else p.stat().st_size,
68
+ }
69
+
70
+
71
+ def finalize(record_id: str, fields: dict, attachments: list) -> bool:
72
+ cfg = _config()
73
+ body = {'sourceRecordId': str(record_id), 'fields': fields or {}, 'attachments': attachments or []}
74
+ status, doc = _post(f"/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/agent-tasks/invoice-finalize", body)
75
+ return bool(doc.get('ok')), status, doc
76
+
77
+
78
+ def write_fields(rids, patch) -> bool:
79
+ fields, _skipped = to_erp_fields(patch or {})
80
+ if not fields:
81
+ return True
82
+ for rid in rids or []:
83
+ ok, _status, _doc = finalize(rid, fields, [])
84
+ if not ok:
85
+ return False
86
+ return True
87
+
88
+
89
+ def upload_and_finalize(rid, field, path) -> bool:
90
+ att = upload_attachment(path)
91
+ erp_field = ATTACHMENT_MAP.get(field, field)
92
+ ok, _status, _doc = finalize(rid, {}, [{**att, 'field': erp_field}])
93
+ return ok
@@ -157,7 +157,7 @@
157
157
  },
158
158
  "minPlan": "enterprise",
159
159
  "pack": {
160
- "version": "1.2.186",
160
+ "version": "1.2.188",
161
161
  "scripts": [
162
162
  "scripts/wenyao-invoice-writeback.mjs",
163
163
  "scripts/invoice_lip_runner.py",
@@ -260,7 +260,7 @@
260
260
  ],
261
261
  "minPlan": "enterprise",
262
262
  "pack": {
263
- "version": "1.3.192",
263
+ "version": "1.3.194",
264
264
  "scripts": [
265
265
  "scripts/poll-fulfillment.sh",
266
266
  "scripts/orchestrator.py",
@@ -340,7 +340,7 @@
340
340
  "minPlan": "pro",
341
341
  "_minPlanNote": "**2026-10-09(变现分层落地)**:`enterprise` → **`pro`**。判据 = 用户已确认的产品模型「分界线 = **价值更高 / 风险更高 ⇒ 企业版**」:日报是**只读**能力(官方 API 只读查询 + 生成推送,⛔ 不写客户任何系统、⛔ 不动浏览器),与 `full`(箱唛/写操作)、`invoice`(发票/门户写操作)不同档 ⇒ 归 **Pro**。⛔ 只改**档位下限**,⛔ 不改流程行为、⛔ 不改价格口径;`daily-report` 的能力包版本随引擎前进(见 pack.version)。已装机器**不因本改动被卸载/停用**(缩权只影响后续下发,见 entitlements.plans._why 与 docs 策划案 §4.4)。",
342
342
  "pack": {
343
- "version": "1.1.183",
343
+ "version": "1.1.185",
344
344
  "scripts": [
345
345
  "scripts/daily-report.mjs",
346
346
  "scripts/daily-report.sh",
@@ -17,13 +17,14 @@
17
17
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, appendFileSync, readdirSync } from 'node:fs'
18
18
  import { dirname, join } from 'node:path'
19
19
  import { homedir } from 'node:os'
20
+ import { resolveDataDir } from './lib/argent-datadir.mjs'
20
21
 
21
22
  const arg = (n, d = '') => { const i = process.argv.indexOf(n); return i >= 0 ? (process.argv[i + 1] ?? d) : d }
22
23
  const APPLY = process.argv.includes('--apply')
23
24
  const JSON_OUT = process.argv.includes('--json')
24
25
  const DAYS = Math.max(1, Number(arg('--days', '7')) || 7)
25
26
  const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
26
- const DATA = process.env.ARGENT_DATA_DIR || join(DSH_HOME, 'argent')
27
+ const DATA = resolveDataDir({ env: process.env }).dir
27
28
  const REGISTRY = join(DATA, 'flow-sessions.jsonl')
28
29
  const SESSIONS = join(DSH_HOME, 'sessions')
29
30
  const ARCHIVE = join(DATA, 'session-archive')
@@ -62,6 +62,8 @@ SOURCES: dict = {
62
62
  'cases-json': {'needs_args': ('--from-json 或 source.file',), 'registry_driven': True,
63
63
  'module': 'flow_sources.cases_json',
64
64
  'note': '批量清单文件(生成器产出的待处理单元;日报走这条)'},
65
+ 'erp': {'needs_args': (), 'registry_driven': True, 'module': 'flow_sources.erp',
66
+ 'note': 'ERP Shipment/Invoice 只读数据面(0.8 去 lip Phase 2;machine token 只读)'},
65
67
  'cli-json': {'needs_args': ('--ticket', '--fields-from-json'), 'registry_driven': False, 'inline': True,
66
68
  'note': '手工/外部喂字段(会话与排障用)'},
67
69
  'conversation': {'needs_args': ('--ticket', '--fields-from-json'), 'registry_driven': False, 'inline': True,
@@ -100,7 +102,14 @@ def _assert_kinds_aligned() -> None:
100
102
 
101
103
 
102
104
  def declared_kind(spec: dict) -> str:
103
- """该流程在注册表里声明的数据面(`source.kind`),缺省 feishu-base(历史行为)。"""
105
+ """该流程在注册表里声明的数据面(`source.kind`),缺省 feishu-base(历史行为)。
106
+
107
+ 0.8 去 lip 过渡开关:ARGENT_FLOW_SOURCE=erp 时,所有流程统一改走 ERP source
108
+ (字段名由适配器保持 lip 兼容),用于先灰度、再删除 lip 源。
109
+ """
110
+ override = os.environ.get('ARGENT_FLOW_SOURCE', '').strip()
111
+ if override:
112
+ return override
104
113
  return str((spec.get('source') or {}).get('kind') or 'feishu-base')
105
114
 
106
115
 
@@ -15,6 +15,7 @@ import importlib
15
15
  MODULES: dict = {
16
16
  'feishu-base': 'flow_sources.feishu_base',
17
17
  'cases-json': 'flow_sources.cases_json',
18
+ 'erp': 'flow_sources.erp',
18
19
  }
19
20
 
20
21
 
@@ -0,0 +1,54 @@
1
+ """ERP 数据面(0.8 去 lip,Phase 2)。
2
+
3
+ 从 ERP 机器只读接口拉取 Shipment/Invoice 并映射成旧流程认识的字段;
4
+ 不再读 lip 表。身份 = 本机 agent-report.json 的 machine token。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import urllib.request
11
+ import urllib.error
12
+ from pathlib import Path
13
+
14
+ KIND = 'erp'
15
+
16
+
17
+ def _config() -> dict:
18
+ env = os.environ
19
+ candidates = []
20
+ if env.get('ARGENT_AGENT_REPORT'):
21
+ candidates.append(Path(env['ARGENT_AGENT_REPORT']))
22
+ data_dir = Path(env.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
23
+ candidates += [data_dir / 'agent-report.json', Path.home() / '.dsh-argent' / 'argent' / 'agent-report.json']
24
+ for f in candidates:
25
+ try:
26
+ d = json.loads(f.read_text())
27
+ if d.get('serverUrl') and d.get('tenantAppId') and d.get('machineId') and d.get('machineToken'):
28
+ return d
29
+ except Exception:
30
+ continue
31
+ return {}
32
+
33
+
34
+ def pull(spec, args):
35
+ cfg = _config()
36
+ if not cfg:
37
+ raise SystemExit('ERP source:找不到 agent-report.json(serverUrl/tenantAppId/machineId/machineToken)')
38
+ base = str(cfg['serverUrl']).rstrip('/')
39
+ url = f"{base}/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/erp-source?limit=5000"
40
+ req = urllib.request.Request(url, headers={'authorization': f"Bearer {cfg['machineToken']}"})
41
+ try:
42
+ with urllib.request.urlopen(req, timeout=60) as resp:
43
+ doc = json.loads(resp.read().decode('utf-8', errors='replace') or '{}')
44
+ except urllib.error.HTTPError as e:
45
+ raise SystemExit(f'ERP source HTTP {e.code}: {e.read().decode("utf-8", errors="replace")[:500]}')
46
+ except Exception as e:
47
+ raise SystemExit(f'ERP source 不可达:{e}')
48
+ items = (doc.get('data') or {}).get('items') or []
49
+ out = []
50
+ for it in items:
51
+ rid = str(it.get('recordId') or (it.get('fields') or {}).get('recordId') or '')
52
+ if rid:
53
+ out.append((rid, it.get('fields') or {}))
54
+ return out
@@ -59,7 +59,7 @@ export const PLUGINS_DIR = join(REPO, 'plugins')
59
59
  /** bundle 目录名前缀 —— 安装器与门禁按它认"这是智能体 bundle"。 */
60
60
  export const BUNDLE_PREFIX = 'argent-agent-'
61
61
  /** bundle 版本(包自身语义化版本;与平台版本、能力包版本是三条轴)。 */
62
- export const BUNDLE_VERSION = '0.1.1'
62
+ export const BUNDLE_VERSION = '0.1.2'
63
63
  /** `@whyshu/argent-*` 依赖的兼容区间(⛔ 不是宿主 peer —— 那套区间判据只认 `@deepseek-ai/dsh*`)。 */
64
64
  export const ARGENT_PLUGIN_RANGE = '>=0.1.0 <0.3'
65
65
  /** 宿主 node 门槛(与安装器 `MIN_NODE` 对齐;与既有插件 `engines.node` 的写法逐字同源)。 */
@@ -74,6 +74,14 @@ def _load_env():
74
74
 
75
75
  _load_env()
76
76
  # lark-cli shebang「/usr/bin/env node」需 node 在 PATH(launchd/ssh 最小 PATH 兼容)
77
+ try:
78
+ from erp_invoice_shadow import shadow_record, append_shadow # noqa: E402
79
+ except Exception: # 半坏机器/旧包没有该模块时只关闭 shadow,不影响 lip
80
+ shadow_record = append_shadow = None
81
+ try:
82
+ from erp_invoice_writeback import write_fields as erp_write_fields, upload_and_finalize as erp_upload_and_finalize # noqa: E402
83
+ except Exception: # ERP 写回模块缺失时只在 erp 模式报错
84
+ erp_write_fields = erp_upload_and_finalize = None
77
85
  _EXTRA_PATH = [p for p in (f"{HOME}/.local/bin", f"{HOME}/node/bin",
78
86
  "/opt/homebrew/bin", "/usr/local/bin")
79
87
  if p not in (os.environ.get("PATH") or "").split(":")]
@@ -97,6 +105,9 @@ F_HS = "HS编码"
97
105
  F_MAT = "材质"
98
106
  F_FILE = "发票文件"
99
107
  F_LABEL = "大货标签"
108
+
109
+ def _writeback_mode() -> str:
110
+ return (os.environ.get("ARGENT_WRITEBACK") or "lip").strip().lower()
100
111
  F_ERR = "发票错误信息"
101
112
  F_FULL_ST = "FULL状态"
102
113
  F_SKU = "SKU"
@@ -351,6 +362,22 @@ def lip_update(rids, patch):
351
362
  _audit_write(rids, patch, False, f"越界字段: {bad}")
352
363
  raise SystemExit(f"❌ 拒绝写回:{bad} 不在发票字段白名单 {sorted(WRITE_FIELDS)} 内"
353
364
  f"(只允许改发票相关字段,其余字段由运营/其他流程负责)")
365
+ mode = _writeback_mode()
366
+ if mode == "erp":
367
+ if erp_write_fields is None:
368
+ raise SystemExit("❌ ARGENT_WRITEBACK=erp:ERP 写回模块不可用(缺 erp_invoice_writeback.py)")
369
+ try:
370
+ ok = erp_write_fields(rids, patch)
371
+ except Exception as e:
372
+ _audit_write(rids, patch, False, str(e)[:200])
373
+ raise SystemExit(f"❌ ERP 发票写回失败:{e}")
374
+ _audit_write(rids, patch, ok, "" if ok else "ERP invoice-finalize 失败")
375
+ return ok
376
+ if mode == "shadow" and shadow_record is not None:
377
+ try:
378
+ append_shadow(shadow_record(rids, patch, source="lip_update"), DATA)
379
+ except Exception as e:
380
+ log(f"ERP shadow 记录失败(不影响 lip 写回): {e}")
354
381
  d = _cli("base", "+record-batch-update", "--base-token", BASE_TOKEN,
355
382
  "--table-id", TABLE_ID,
356
383
  "--json", json.dumps({"record_id_list": rids, "patch": patch}, ensure_ascii=False))
@@ -460,6 +487,22 @@ def lip_upload_attachment(rid, field, path, row=None):
460
487
  上传标签时查不到自己那条 ⇒ 归一失效、附件越挂越多)。
461
488
  """
462
489
  path = Path(path)
490
+ if _writeback_mode() == "erp":
491
+ if erp_upload_and_finalize is None:
492
+ raise SystemExit("❌ ARGENT_WRITEBACK=erp:ERP 附件写回模块不可用")
493
+ try:
494
+ ok = erp_upload_and_finalize(rid, field, path)
495
+ except Exception as e:
496
+ _audit_write([rid], {field: path.name}, False, str(e)[:200])
497
+ raise SystemExit(f"❌ ERP 附件写回失败:{e}")
498
+ _audit_write([rid], {field: path.name}, ok, "" if ok else "ERP 附件写回失败")
499
+ return ok
500
+ if _writeback_mode() == "shadow" and shadow_record is not None:
501
+ try:
502
+ append_shadow(shadow_record([rid], {}, source="lip_upload_attachment",
503
+ attachments=[{"field": field, "filename": path.name}]), DATA)
504
+ except Exception as e:
505
+ log(f"ERP shadow 附件记录失败(不影响 lip 上传): {e}")
463
506
  same = _same_name_attachments(row, field, path.name)
464
507
  if row is not None and same and not _needs_refresh(same, path):
465
508
  if len(same) > 1:
@@ -59,6 +59,9 @@ export const PLUGIN_PACKAGES = [
59
59
  // · 发布流水线(`scripts/npm-publish-argent.mjs --only argent-shell`)按本清单认包
60
60
  // —— 不登记 ⇒ Lead 用**官方**发布脚本发不出它。
61
61
  { id: 'argent-shell', npm: `${NPM_SCOPE}/argent-shell` },
62
+ // Desktop 端 ERP 连接器(2026-10-29):单 bundle + 单 insert,只做 office/ERP 通道
63
+ // (快照/对话/建会话/本地任务),不装 core/skin/flow/gateway ⇒ 与 web 端套装解耦。
64
+ { id: 'argent-desktop', npm: `${NPM_SCOPE}/argent-desktop` },
62
65
  ]
63
66
 
64
67
  /**
@@ -2545,6 +2545,19 @@ FALLBACK_DATE_JS = r"""() => {
2545
2545
  }
2546
2546
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2547
2547
  }
2548
+ // 目标月不在视图:若视图已是**更晚的月份**(目标 10/30、日历已翻到 11 月),
2549
+ // 直接选视图内第一个可用日(>= 目标);⛔ 不再为了“精确目标日”继续翻到 12 月。
2550
+ const viewMonth = viewMonths[0];
2551
+ const viewDate = new Date(viewYear, viewMonth, 1);
2552
+ const targetMonthDate = new Date(target.getFullYear(), target.getMonth(), 1);
2553
+ if (viewDate > targetMonthDate) {
2554
+ for (let i = 0; i < n; i++) {
2555
+ const t = (days[i].textContent || '').trim();
2556
+ if (/^\d+$/.test(t) && !days[i].classList.contains('day--disabled')) {
2557
+ return {found: true, idx: i, mode: 'next_available', header: headerText};
2558
+ }
2559
+ }
2560
+ }
2548
2561
  return {found: false, needFlip: true, mode: 'header', header: headerText};
2549
2562
  }
2550
2563
  // header 不可靠:降级为「目标日数字 + 视图内该数字后的第一个可用格」(last resort)
@@ -7270,6 +7283,16 @@ class RunState:
7270
7283
  terminal_evidence: str = ""
7271
7284
 
7272
7285
 
7286
+ class NullFeishu:
7287
+ """ERP-only 记录源:不读写 lip,所有 Feishu 写操作 no-op。"""
7288
+ dry_run = True
7289
+
7290
+ def __getattr__(self, name):
7291
+ if name == "build_card":
7292
+ return lambda *a, **k: {}
7293
+ return lambda *a, **k: None
7294
+
7295
+
7273
7296
  class Orchestrator:
7274
7297
  """8 步 FULL 货件流程编排器。"""
7275
7298
 
@@ -7279,7 +7302,10 @@ class Orchestrator:
7279
7302
  self.sel = selectors
7280
7303
  self.args = args or argparse.Namespace(no_lock=False)
7281
7304
  self.browser = build_browser_client(cfg, selectors) # KB-085:ZINIAO_MODE=selenium 用 SeleniumClient
7282
- self.feishu = FeishuClient(cfg)
7305
+ if getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", None):
7306
+ self.feishu = NullFeishu()
7307
+ else:
7308
+ self.feishu = FeishuClient(cfg)
7283
7309
  self.state = RunState()
7284
7310
  # 2026-09-19:点 Generar etiquetas **之前**页面是否已有「Declara al menos」提示。
7285
7311
  # 点击前就有 = 残留文案(页面流转留下的旧校验),**不能**当作"checkbox 未生效"的证据;
@@ -9610,6 +9636,52 @@ class Orchestrator:
9610
9636
  "why": (verdict.get("lift") or {}).get("reason") or "",
9611
9637
  })
9612
9638
 
9639
+ async def _open_appointment_via_hub(self) -> None:
9640
+ """从列表/hub 进入 appointment-v2(新 UI 的两跳;已在预约页则 no-op)。
9641
+
9642
+ 只读判断 + 两次点击(Completar envío / Elige cómo…),不提交预约。
9643
+ """
9644
+ sid = str(self.state.shipment_id or "")
9645
+ if not sid:
9646
+ return
9647
+ try:
9648
+ url = self.browser.page.url or ""
9649
+ except Exception: # noqa: BLE001
9650
+ url = ""
9651
+ if "appointment" in url:
9652
+ return
9653
+ if "/hub" not in url:
9654
+ try:
9655
+ clicked = await self.browser.click_button("Completar envío", "button", step=4, wait_after=0)
9656
+ except Exception: # noqa: BLE001
9657
+ clicked = "notfound"
9658
+ if clicked != "clicked":
9659
+ # 可能已经停在 hub(步骤3正常收口)⇒ 不因找不到按钮而失败
9660
+ self._log(" ℹ️ 未命中「Completar envío」按钮(可能已在 hub)⇒ 继续找预约入口")
9661
+ else:
9662
+ self._log(" ✅ 已点「Completar envío」⇒ 进入 hub")
9663
+ for _ in range(10):
9664
+ try:
9665
+ if "/hub" in (self.browser.page.url or "") or "appointment" in (self.browser.page.url or ""):
9666
+ break
9667
+ except Exception: # noqa: BLE001
9668
+ pass
9669
+ await asyncio.sleep(1)
9670
+ try:
9671
+ await self.browser.page.wait_for_selector('a[href*="/appointment"]', timeout=20000)
9672
+ await self.browser.click_selector('a[href*="/appointment"]', step=4, wait_after=3)
9673
+ self._log(" ✅ 已点「Elige cómo y cuándo…」⇒ appointment-v2")
9674
+ except Exception as exc: # noqa: BLE001
9675
+ self._log(f" ⚠️ hub 预约入口未命中({type(exc).__name__})⇒ 回退直接 URL")
9676
+ await self.browser.visit_plan_page("appointment-v2", sid, step=4)
9677
+ for _ in range(15):
9678
+ try:
9679
+ if "appointment" in (self.browser.page.url or ""):
9680
+ return
9681
+ except Exception: # noqa: BLE001
9682
+ pass
9683
+ await asyncio.sleep(1)
9684
+
9613
9685
  async def step4_appointment(self) -> None:
9614
9686
  self._log("步骤4 货件预约时间")
9615
9687
  # 同店步骤4互斥锁(方案C,2026-08-14):**保守串行**,不是已验证的平台规则。
@@ -9650,6 +9722,10 @@ class Orchestrator:
9650
9722
  f"{(_cap.get('lift') or {}).get('reason')}")
9651
9723
  # 4a. 进入预约页(优先用货件号拼 URL,其次从 URL 提取 inbound ID)
9652
9724
  await self.browser.visit_plan_page("appointment-v2", self.state.shipment_id, step=4)
9725
+ # 4a1. 新 UI 兜底(2026-10-29):/appointment-v2 在「刚建单、尚未点 Completar envío」
9726
+ # 时会重定向回列表页(实测 80893392:列表 → Completar envío → hub → Elige cómo…)。
9727
+ # 直接 URL 只对已进入预约页的货件有效;这里补两跳,避免把“页面形态”误判成失败。
9728
+ await self._open_appointment_via_hub()
9653
9729
  # 4a2. 已有预约检测(2026-08-25 实测:预约成功后中断/重跑时,页面显示
9654
9730
  # 已预约状态(含 Cancelar reserva 按钮)而非空白表单——旧逻辑继续
9655
9731
  # 走选运输方式流程 → 日历区 Confirmar 找不到 → 误报失败。
@@ -9675,6 +9751,7 @@ class Orchestrator:
9675
9751
  self._log(f" 📅 改选更晚的日期:平台今天 +{date_offset} 天")
9676
9752
  await self.browser.visit_plan_page("appointment-v2",
9677
9753
  self.state.shipment_id, step=4)
9754
+ await self._open_appointment_via_hub()
9678
9755
  for attempt in range(3): # 同一日期内的时段重试
9679
9756
  if attempt > 0:
9680
9757
  self._log(f" 🔁 预约提交未生效,换下一时段重试(第 {attempt + 1}/3 次)")
@@ -11607,6 +11684,14 @@ class Orchestrator:
11607
11684
 
11608
11685
  async def step7_box_labels(self) -> None:
11609
11686
  self._log("步骤7 打印箱唛")
11687
+ # 续跑/并发:hub-v2 已确认箱唛下载完成时,不再重复生成/勾 fragile;
11688
+ # 80908724 实测:agent 已生成箱唛,orchestrator 再进 volumes 找不到 fragile checkbox。
11689
+ truth = await self._hub_truth()
11690
+ truth_items = truth.get("items") if isinstance(truth, dict) else {}
11691
+ if isinstance(truth_items, dict) and truth_items.get("boxLabels") is True:
11692
+ self._log(" 🛰️ hub 已确认箱唛下载完成,跳过步骤7重复生成")
11693
+ self._mark_done(7)
11694
+ return
11610
11695
  await self.browser.visit_plan_page("volumes", self.state.shipment_id, step=7)
11611
11696
  await asyncio.sleep(3)
11612
11697
  # 7.0 页面就绪验证:确认在箱数填写页(volumes)。8/18 并发实测 visit 后被
@@ -11660,6 +11745,12 @@ class Orchestrator:
11660
11745
  r = await self.browser.click_checkboxes(
11661
11746
  '[data-testid="checkbox-fragils-consolidation"]', step=7, wait_after=1.0)
11662
11747
  if not r.startswith("checked"):
11748
+ truth2 = await self._hub_truth()
11749
+ truth2_items = truth2.get("items") if isinstance(truth2, dict) else {}
11750
+ if isinstance(truth2_items, dict) and truth2_items.get("boxLabels") is True:
11751
+ self._log(" 🛰️ 箱唛已下载完成(hub 复核),跳过 fragile 收口")
11752
+ self._mark_done(7)
11753
+ return
11663
11754
  raise StepError(7, "selector_not_found", f"未找到 fragile checkbox ({r})",
11664
11755
  recovery_attempted=["fiber_onChange"])
11665
11756
  # 7g. 等加载旋转层消失再点 Continuar(箱唛生成后约5秒loading)
@@ -12870,7 +12961,7 @@ class Orchestrator:
12870
12961
  dry_run = mode == "dry-run"
12871
12962
  # ⑧:dry-run 期间所有字段写入在 update_field 里被拦(唯一写入口)
12872
12963
  try:
12873
- self.feishu.dry_run = bool(dry_run)
12964
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
12874
12965
  except Exception: # noqa: BLE001
12875
12966
  pass
12876
12967
  record_ids = [r.strip() for r in str(self.args.records).split(",") if r.strip()]
@@ -13084,7 +13175,58 @@ class Orchestrator:
13084
13175
  # 定向重跑),店铺从记录字段取(store_name),无需 --store-name;若同时给
13085
13176
  # --store-name 且不匹配则报错提示;
13086
13177
  # --store-name:过滤查询第一条店铺名匹配的 Pending+就绪;缺省:第一条 Pending+就绪
13087
- if record_id:
13178
+ _record_json = getattr(self.args, "record_json", "") or ""
13179
+ if _record_json:
13180
+ try:
13181
+ _raw = json.loads(_record_json)
13182
+ except Exception as exc: # noqa: BLE001
13183
+ return {"status": "failed", "record_id": None, "shipment_id": None,
13184
+ "sku": None, "completed_steps": [], "failed_step": None,
13185
+ "error": {"step": None, "type": "business",
13186
+ "message": f"--record-json 解析失败: {exc}",
13187
+ "recovery_attempted": []},
13188
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13189
+ "write_steps": list(WRITE_STEPS)}
13190
+
13191
+ def _s(*keys):
13192
+ for _k in keys:
13193
+ if _raw.get(_k) not in (None, ""):
13194
+ return str(_raw.get(_k))
13195
+ return ""
13196
+
13197
+ rec = {
13198
+ "record_id": _s("record_id", "sourceRecordId") or "erp-record",
13199
+ "sku": _s("sku"),
13200
+ "qty": _s("qty", "quantity"),
13201
+ "box": _s("box", "boxCount"),
13202
+ "name": _s("name", "productName") or _s("sku"),
13203
+ "store_name": _s("store_name", "store") or (store_name or ""),
13204
+ "shipment_id": _s("shipment_id", "shipmentNo"),
13205
+ }
13206
+ _missing = [k for k in ("sku", "qty", "box", "store_name") if not rec[k]]
13207
+ if _missing:
13208
+ return {"status": "failed", "record_id": rec["record_id"], "shipment_id": None,
13209
+ "sku": rec["sku"], "completed_steps": [], "failed_step": None,
13210
+ "error": {"step": None, "type": "business",
13211
+ "message": f"--record-json 缺字段: {_missing}",
13212
+ "recovery_attempted": []},
13213
+ "files_uploaded": {}, "dry_run": mode == "dry-run",
13214
+ "write_steps": list(WRITE_STEPS)}
13215
+ if store_name and rec["store_name"] != store_name:
13216
+ raise StepError(0, "business",
13217
+ f"--record-json 的店铺 {rec['store_name']} "
13218
+ f"与 --store-name {store_name} 不匹配")
13219
+ self._log(f"🎯 ERP-only 记录 {rec['record_id']}(店铺:{rec['store_name']})")
13220
+ self.state.record_id = rec["record_id"]
13221
+ self.state.name = rec["name"]
13222
+ self.state.store_name = rec["store_name"]
13223
+ self.state.sku = rec["sku"]
13224
+ self.state.qty = rec["qty"]
13225
+ self.state.box = rec["box"]
13226
+ if rec["shipment_id"] and rec["shipment_id"] not in ("None", "null"):
13227
+ self.state.shipment_id = rec["shipment_id"]
13228
+ self._log(f" 已有货件号 {rec['shipment_id']},从步骤4继续")
13229
+ elif record_id:
13088
13230
  rec = self.feishu.get_record(record_id)
13089
13231
  if rec is None:
13090
13232
  self._log(f"记录 {record_id} 不存在或无法读取,本轮退出。")
@@ -13167,7 +13309,7 @@ class Orchestrator:
13167
13309
 
13168
13310
  dry_run = mode == "dry-run"
13169
13311
  try: # ⑧:dry-run 写闸门
13170
- self.feishu.dry_run = bool(dry_run)
13312
+ self.feishu.dry_run = bool(dry_run) or bool(getattr(self.args, "no_lip", False) or getattr(self.args, "record_json", ""))
13171
13313
  except Exception: # noqa: BLE001
13172
13314
  pass
13173
13315
  # 启动标记(状态=运行中)必须与打开店铺在同一 protected 区域:后续任何异常
@@ -13230,7 +13372,31 @@ class Orchestrator:
13230
13372
  return self._result("failed", failed_step=step_filter or 1, error=env_exc.to_dict(),
13231
13373
  step_summaries={}, dry_run=dry_run)
13232
13374
 
13233
- steps = [step_filter] if step_filter else list(range(1, 9))
13375
+ if self.state.shipment_id and not step_filter:
13376
+ # 已有货件号:先用 hub 只读状态判断真实进度;跳过 1-3 的重复打开/建单。
13377
+ # 实测:每次 full 都从步骤1 重开一遍,既慢又会让用户看到“明明有档期却重开”。
13378
+ try:
13379
+ _hub = await self.hub_status(self.state.shipment_id, step=0)
13380
+ _v = self._hub_verdict_of(_hub)
13381
+ self._log(f" 🛰️ 已有货件 #{self.state.shipment_id} hub 状态:"
13382
+ f"{_v.get('reason') or '不可用'}")
13383
+ if _v.get("operationally_complete"):
13384
+ self._log(" ✅ hub 判定已完成 ⇒ 不再重复步骤")
13385
+ for _s in range(1, 9):
13386
+ self._mark_done(_s)
13387
+ steps = []
13388
+ else:
13389
+ for _s in (1, 2, 3):
13390
+ self._mark_done(_s)
13391
+ steps = [4, 5, 6, 7, 8]
13392
+ except Exception as exc: # noqa: BLE001
13393
+ self._log(f" ⚠️ hub 状态探测失败,按已有货件从步骤4续跑: "
13394
+ f"{type(exc).__name__}: {exc}")
13395
+ for _s in (1, 2, 3):
13396
+ self._mark_done(_s)
13397
+ steps = [4, 5, 6, 7, 8]
13398
+ else:
13399
+ steps = [step_filter] if step_filter else list(range(1, 9))
13234
13400
  step_summaries: dict[int, Any] = {}
13235
13401
 
13236
13402
  result = await self._execute_steps(steps, allow_write, dry_run, step_summaries)
@@ -13821,6 +13987,8 @@ def build_parser() -> argparse.ArgumentParser:
13821
13987
  p.add_argument("--allow-write", action="store_true",
13822
13988
  help="批准写步骤(3/4/5/7/8)执行(默认拒绝)")
13823
13989
  p.add_argument("--record-id", help="指定飞书记录 ID 定向处理(店铺从记录字段读取,忽略 --store-name 取第一条逻辑;供并发调度/定向重跑)")
13990
+ p.add_argument("--record-json", help="ERP-only:合成记录 JSON(record_id/sourceRecordId、sku、qty/quantity、box/boxCount、name、store_name/store、shipment_id/shipmentNo)")
13991
+ p.add_argument("--no-lip", action="store_true", help="不读写 lip(Feishu 写操作 no-op);常与 --record-json 使用")
13824
13992
  p.add_argument("--sku", help="SKU(配合 --record-id 使用)")
13825
13993
  p.add_argument("--qty", help="数量(配合 --record-id 使用)")
13826
13994
  p.add_argument("--box", help="箱数(配合 --record-id 使用)")