@whyshu/argent-engine 0.8.0-rc.9 → 0.13.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/MANIFEST.json +102 -40
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +2 -2
  7. package/engine/core/lib/account-token.mjs +37 -0
  8. package/engine/core/lib/redact.mjs +34 -0
  9. package/engine/core/mcp/billing-upload.mjs +77 -0
  10. package/engine/core/mcp/erp-server.mjs +300 -0
  11. package/engine/core/mcp/gateway.mjs +333 -0
  12. package/engine/core/mcp/meter.mjs +101 -0
  13. package/engine/core/mcp/server.mjs +245 -0
  14. package/engine/core/mcp/vault.mjs +78 -0
  15. package/engine/scripts/appointment-worker.mjs +456 -35
  16. package/engine/scripts/appointment_grab.py +1389 -264
  17. package/engine/scripts/appointment_rules.py +118 -0
  18. package/engine/scripts/argent-timers.mjs +227 -0
  19. package/engine/scripts/argent-web-preflight.mjs +123 -0
  20. package/engine/scripts/argent-web-verify.mjs +105 -0
  21. package/engine/scripts/billing-upload.mjs +26 -0
  22. package/engine/scripts/build-engine-package.mjs +7 -1
  23. package/engine/scripts/capability-packs.lock.json +323 -300
  24. package/engine/scripts/check-version-consistency.mjs +14 -1
  25. package/engine/scripts/collect-intel.mjs +108 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  27. package/engine/scripts/daily-report-timers.sh +36 -3
  28. package/engine/scripts/daily-report.mjs +78 -2
  29. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  30. package/engine/scripts/engine-manifest.mjs +90 -0
  31. package/engine/scripts/engine-runtime-install.mjs +92 -0
  32. package/engine/scripts/erp-ui-install.mjs +127 -0
  33. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  34. package/engine/scripts/erp-ui-verify.mjs +135 -0
  35. package/engine/scripts/flow-requirements.json +122 -99
  36. package/engine/scripts/full-exec-worker.mjs +251 -0
  37. package/engine/scripts/gen-preset-rows.mjs +1 -1
  38. package/engine/scripts/invoice_lip_runner.py +1 -0
  39. package/engine/scripts/invoice_runner.py +17 -6
  40. package/engine/scripts/invoice_stageb.py +21 -4
  41. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  42. package/engine/scripts/lib/intel-card.mjs +43 -0
  43. package/engine/scripts/lib/invoice_names.py +23 -0
  44. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  45. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  46. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  47. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  48. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  49. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  50. package/engine/scripts/lib/ml-items.mjs +40 -0
  51. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  52. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  53. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  54. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  55. package/engine/scripts/line_pack.py +196 -0
  56. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  57. package/engine/scripts/migrate-providers.mjs +3 -3
  58. package/engine/scripts/ml-ads-advice.mjs +140 -0
  59. package/engine/scripts/ml-ads.mjs +40 -0
  60. package/engine/scripts/ml-category-baseline.mjs +174 -0
  61. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  62. package/engine/scripts/ml-insight-run.sh +183 -0
  63. package/engine/scripts/ml-insight-timers.sh +224 -0
  64. package/engine/scripts/ml-listing-audit.mjs +170 -0
  65. package/engine/scripts/ml-market-matrix.mjs +84 -0
  66. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  67. package/engine/scripts/ml-messages.mjs +145 -0
  68. package/engine/scripts/npm-publish-argent.mjs +14 -0
  69. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  70. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  71. package/engine/scripts/ops-digest.mjs +98 -0
  72. package/engine/scripts/ops-verify.mjs +67 -0
  73. package/engine/scripts/orchestrator.py +410 -20
  74. package/engine/scripts/orchestrator_br.py +146 -4
  75. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  76. package/engine/scripts/publish-engine.mjs +111 -0
  77. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  78. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  79. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  80. package/engine/scripts/vertical-lint.mjs +12 -1
  81. package/engine/scripts/web-switch.mjs +121 -0
  82. package/engine/scripts/wenyao_fill_template.py +52 -15
  83. package/engine/scripts/wenyao_run.py +2 -1
  84. package/engine/skills/README.md +3 -3
  85. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  86. package/engine/skills/douyin-upload/SKILL.md +74 -0
  87. package/engine/skills/internal.json +28 -0
  88. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  89. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  90. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  91. package/engine/skills/ml-invoice/SKILL.md +2 -2
  92. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  93. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  94. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  95. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  96. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  97. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  98. package/engine/skills/tencent-upload/SKILL.md +60 -0
  99. package/engine/skills/weibo-upload/SKILL.md +106 -0
  100. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  101. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  102. package/engine/version.mjs +1 -1
  103. package/engine/verticals/README.md +7 -0
  104. package/engine/verticals/_engine-words.baseline.txt +27 -59
  105. package/engine/verticals/mercadolibre/manifest.json +132 -6
  106. package/package.json +5 -1
@@ -2209,7 +2209,8 @@ def _cdp_port_map_path() -> Path:
2209
2209
  return Path(resolve_data_dir()["dir"]) / "cdp-port-map.json"
2210
2210
 
2211
2211
 
2212
- def write_cdp_port_map(store_id: str, store_name: str, env_name: str, port: int) -> None:
2212
+ def write_cdp_port_map(store_id: str, store_name: str, env_name: str, port: int,
2213
+ download_dir: str = "") -> None:
2213
2214
  """把 startBrowser 返回的 debuggingPort 写入 cdp-port-map.json(替代进程扫描)。
2214
2215
 
2215
2216
  格式与 init-ml.sh 产物一致:storeId → {store_name, env_name, cdp_port}。
@@ -2221,7 +2222,9 @@ def write_cdp_port_map(store_id: str, store_name: str, env_name: str, port: int)
2221
2222
  data = json.loads(path.read_text(encoding="utf-8"))
2222
2223
  except Exception:
2223
2224
  data = {}
2224
- data[store_id] = {"store_name": store_name, "env_name": env_name, "cdp_port": int(port)}
2225
+ data[store_id] = {"store_name": store_name, "env_name": env_name, "cdp_port": int(port),
2226
+ "download_dir": str(download_dir or ""),
2227
+ "updated_at": time.strftime("%Y-%m-%dT%H:%M:%S")}
2225
2228
  try:
2226
2229
  path.parent.mkdir(parents=True, exist_ok=True)
2227
2230
  path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
@@ -3337,6 +3340,67 @@ class PlaywrightClient:
3337
3340
  pass
3338
3341
  self._pw = self._browser = self._context = self._page = None
3339
3342
 
3343
+ async def close_noise_tabs(self) -> int:
3344
+ """关闭与流程无关的「噪音标签页」(2026-11-18)。
3345
+
3346
+ 背景:紫鸟窗口重启会**恢复上次会话的标签**(如卖家菜单 personas-interesadas),
3347
+ 这些页面既不是我们开的、也与抢号无关,堆在窗口里会误导运营。
3348
+ 只关明确的噪音:personas-interesadas / seller-menu / ato-complaint / 登录页 / 首页 /resumen。
3349
+ ⛔ 窗口守卫:永远保留至少 1 个标签;不碰 /inbounds/ 货件页与其他流程的页面。
3350
+ """
3351
+ if self._context is None:
3352
+ return 0
3353
+ noise_marks = ('personas-interesadas', 'seller-menu', 'ato-complaint',
3354
+ '/login', 'identification', '/resumen', '/resumo')
3355
+ closed = 0
3356
+ for pg in list(self._context.pages):
3357
+ try:
3358
+ if pg.is_closed():
3359
+ continue
3360
+ url = str(pg.url or "")
3361
+ if not url or url == "about:blank":
3362
+ continue
3363
+ if "/inbounds/" in url:
3364
+ continue
3365
+ if self._page is not None and pg is self._page:
3366
+ continue
3367
+ if not any(mk in url for mk in noise_marks):
3368
+ continue
3369
+ if len(self._context.pages) > 1:
3370
+ await pg.close()
3371
+ closed += 1
3372
+ except Exception:
3373
+ continue
3374
+ if closed:
3375
+ print(f"[{time.strftime('%H:%M:%S')}] 🧹 已清理与流程无关的噪音标签 {closed} 个", file=sys.stderr, flush=True)
3376
+ return closed
3377
+
3378
+ async def close_shipment_tabs(self, shipment_id: str) -> int:
3379
+ """关闭**同一货件**的残留标签页(保留当前页与窗口最后一个标签;防误伤其他流程)。
3380
+
3381
+ 2026-11-18:多任务/重定向会留下同单号重复 tab,积累后窗口标签越来越多;
3382
+ 每次准备预约页前清一次,只动 URL 含 /inbounds/<shipment_id> 的页。
3383
+ """
3384
+ if self._context is None or not shipment_id:
3385
+ return 0
3386
+ key = f"/inbounds/{shipment_id}"
3387
+ closed = 0
3388
+ for pg in list(self._context.pages):
3389
+ try:
3390
+ if pg.is_closed() or pg is self._page:
3391
+ continue
3392
+ if key not in str(pg.url or ""):
3393
+ continue
3394
+ if len(self._context.pages) > 1:
3395
+ await pg.close()
3396
+ closed += 1
3397
+ except Exception:
3398
+ continue
3399
+ if closed:
3400
+ print(f"[{time.strftime('%H:%M:%S')}] 🧹 已清理同货件残留标签 {closed} 个({key})",
3401
+ file=sys.stderr, flush=True)
3402
+ return closed
3403
+
3340
3404
  # ---- 页面导航 ----
3341
3405
 
3342
3406
  async def navigate(self, url: str, step: int = 0, wait_after: float = 0.0,
@@ -8248,6 +8312,19 @@ class Orchestrator:
8248
8312
  return None
8249
8313
  ports = _discover_cdp_ports()
8250
8314
  matched = _match_port_by_user_data_dir(store_id, ports)
8315
+ if matched is None:
8316
+ # 2026-11-18:店铺窗口被关掉(含标签误关导致窗口退出)时,端口重发现找不到端口。
8317
+ # 这里自动补一步「CLI/WebDriver 开店窗口」再重新发现,避免任务直接失败。
8318
+ self._log(f" 🪟 端口重发现:店铺 {store_id} 无运行窗口(当前 {ports})⇒ 自动开店窗口重试")
8319
+ try:
8320
+ self._open_store()
8321
+ await_sleep = None
8322
+ ports2 = _discover_cdp_ports()
8323
+ matched = _match_port_by_user_data_dir(store_id, ports2)
8324
+ self._log(f" 🪟 开店后端口发现:{ports2} ⇒ matched={matched}")
8325
+ except Exception as exc: # noqa: BLE001
8326
+ self._log(f" ⚠️ 自动开店失败(仍按失败处理):{str(exc)[:160]}")
8327
+ matched = None
8251
8328
  if matched is None:
8252
8329
  self._log(f" ⚠️ 端口重发现:未匹配到店铺 {store_id} 的监听端口(当前 {ports},实例重启窗口?)")
8253
8330
  return None
@@ -9481,6 +9558,25 @@ class Orchestrator:
9481
9558
  return (f"⚠️ 表内货件号 {sid} 在 inbounds 查不到,+1/+2 也查不到 ⇒ "
9482
9559
  f"可能已关闭(历史行正常现象)或确为坏号,需人工核对后再续跑")
9483
9560
 
9561
+ async def _existing_appointment_text(self) -> str:
9562
+ """取「已有预约」卡片附近的文本(用于解析已预约日期/时段,改约判断用)。只读,不点按钮。"""
9563
+ try:
9564
+ return await self.browser.page.evaluate(
9565
+ """() => {
9566
+ const btns = [...document.querySelectorAll('button')]
9567
+ .filter(b => /Cancelar reserva/i.test(b.innerText || ''));
9568
+ if (!btns.length) return '';
9569
+ let el = btns[0];
9570
+ for (let i = 0; i < 6 && el; i += 1) {
9571
+ el = el.parentElement;
9572
+ if (el && el.innerText && el.innerText.length > 40) return el.innerText.slice(0, 1200);
9573
+ }
9574
+ return (document.body.innerText || '').slice(0, 1200);
9575
+ }"""
9576
+ ) or ''
9577
+ except Exception:
9578
+ return ''
9579
+
9484
9580
  async def _has_existing_appointment(self) -> bool:
9485
9581
  """检测预约页是否已有预约:页面含「Cancelar reserva」按钮(已有预约的标识)。"""
9486
9582
  try:
@@ -9829,7 +9925,9 @@ class Orchestrator:
9829
9925
  return ev
9830
9926
 
9831
9927
  async def _book_appointment(self, hour_idx: int, date_offset: int = 1, exact_date: str = '',
9832
- time_from: str = '', time_to: str = '') -> None:
9928
+ time_from: str = '', time_to: str = '',
9929
+ time_ranges: Optional[list[dict]] = None,
9930
+ min_lead_hours: float = 0) -> None:
9833
9931
  """预约页表单填写+提交:运输方式 → 日期(平台今天+date_offset) → 时段(hour_idx) → 双 Confirmar → 等跳转。
9834
9932
 
9835
9933
  页面必须已在 appointment-v2(调用方保证);hour_idx=0 选第一个可用时段(现状),
@@ -10046,24 +10144,45 @@ class Orchestrator:
10046
10144
  hour_texts.append(((await loc.nth(_i).text_content()) or "").strip())
10047
10145
  except Exception:
10048
10146
  hour_texts.append("")
10049
- if time_from or time_to:
10147
+ if time_ranges or time_from or time_to or min_lead_hours:
10050
10148
  def _minutes(t: str) -> int:
10051
10149
  m = re.search(r"(\d{1,2})[::.](\d{2})", t or "")
10052
10150
  if not m:
10053
10151
  return -1
10054
10152
  return int(m.group(1)) * 60 + int(m.group(2))
10055
- lo = _minutes(time_from) if time_from else 0
10056
- hi = _minutes(time_to) if time_to else 24 * 60
10153
+ ranges: list[tuple[int, int]] = []
10154
+ if time_ranges:
10155
+ for seg in time_ranges:
10156
+ lo = _minutes(str((seg or {}).get('from') or ''))
10157
+ hi = _minutes(str((seg or {}).get('to') or ''))
10158
+ if lo >= 0 and hi >= 0 and lo < hi:
10159
+ ranges.append((lo, hi))
10160
+ elif time_from or time_to:
10161
+ ranges = [(_minutes(time_from) if time_from else 0,
10162
+ _minutes(time_to) if time_to else 24 * 60)]
10163
+ target_date = str(exact_date or getattr(self, '_last_booked_date', '') or '')[:10]
10057
10164
  chosen_idx = -1
10058
10165
  for _i, _text in enumerate(hour_texts):
10059
10166
  _start = _minutes(_text)
10060
- if _start >= 0 and lo <= _start < hi:
10061
- chosen_idx = _i
10062
- break
10167
+ if _start < 0:
10168
+ continue
10169
+ if ranges and not any(lo <= _start < hi for lo, hi in ranges):
10170
+ continue
10171
+ if min_lead_hours and target_date:
10172
+ try:
10173
+ from appointment_rules import min_lead_ok
10174
+ if not min_lead_ok(target_date, _text, float(min_lead_hours)):
10175
+ self._log(f" ⏭️ 跳过 {target_date} {_text}:距现在不足 {float(min_lead_hours):g} 小时(安全提前量)")
10176
+ continue
10177
+ except Exception:
10178
+ pass
10179
+ chosen_idx = _i
10180
+ break
10063
10181
  if chosen_idx < 0:
10182
+ _desc = '、'.join(f'{a // 60:02d}:{a % 60:02d}-{b // 60:02d}:{b % 60:02d}' for a, b in ranges) or '-'
10064
10183
  raise StepError(4, "business",
10065
- f"预约失败:指定时间范围内无可预约时段({time_from or '-'}~{time_to or '-'};"
10066
- f"该日实际时段 {len(hour_texts)} 个)",
10184
+ f"预约失败:规则允许时间内无可预约时段(规则={_desc};"
10185
+ f"最早提前={float(min_lead_hours or 0):g}h;该日实际时段 {len(hour_texts)} 个)",
10067
10186
  recovery_attempted=["appointment_hour_range"])
10068
10187
  hour_idx = chosen_idx
10069
10188
  hour_text = (hour_texts[hour_idx] if hour_idx < len(hour_texts) else "") or ""
@@ -11523,7 +11642,7 @@ class Orchestrator:
11523
11642
  files = f"dir_probe_failed:{str(exc)[:60]}"
11524
11643
  return f"{page_info} | 下载目录最新pdf: {files[:200]}"
11525
11644
 
11526
- async def _download_box_label_with_retry(self, box_name: str) -> bool:
11645
+ async def _download_box_label_with_retry(self, box_name: str, upload: bool = True) -> bool:
11527
11646
  """KB-135:箱唛下载「等 PDF → 等不到就再点一次下载再等」最多 N 轮。
11528
11647
 
11529
11648
  调用时机:调用方已完成首轮「Descarga todas + 弹窗 Descargar etiquetas」(保持原
@@ -11557,7 +11676,7 @@ class Orchestrator:
11557
11676
  wait = (BOX_LABEL_DL_FIRST_TIMEOUT if i == 1 else BOX_LABEL_DL_RETRY_TIMEOUT)
11558
11677
  ok = await self._download_and_upload(
11559
11678
  "box", box_name, pattern="Envio-*-Etiquetas-de-bultos.pdf", step=7,
11560
- biz_actions=BOX_LABEL_BIZ_ACTIONS, wait_timeout=wait)
11679
+ biz_actions=BOX_LABEL_BIZ_ACTIONS, wait_timeout=wait, upload=upload)
11561
11680
  if ok:
11562
11681
  if i > 1:
11563
11682
  self._log(f" ✅ 箱唛 PDF 在第 {i} 轮重试后捕获(KB-135:下载未落盘类偶发)")
@@ -11703,9 +11822,11 @@ class Orchestrator:
11703
11822
  self._log("步骤7 打印箱唛")
11704
11823
  # 续跑/并发:hub-v2 已确认箱唛下载完成时,不再重复生成/勾 fragile;
11705
11824
  # 80908724 实测:agent 已生成箱唛,orchestrator 再进 volumes 找不到 fragile checkbox。
11706
- truth = await self._hub_truth()
11825
+ truth = {} if getattr(self, "force_box_labels", False) else await self._hub_truth()
11707
11826
  truth_items = truth.get("items") if isinstance(truth, dict) else {}
11708
- if isinstance(truth_items, dict) and truth_items.get("boxLabels") is True:
11827
+ # 2026-11-24(0.13 阶段2):强制下载模式跳过 hub 的“已完成”短路;
11828
+ # 只下载箱唛,不因 hub 自报已下载而直接返回。
11829
+ if not getattr(self, "force_box_labels", False) and isinstance(truth_items, dict) and truth_items.get("boxLabels") is True:
11709
11830
  self._log(" 🛰️ hub 已确认箱唛下载完成,跳过步骤7重复生成")
11710
11831
  self._mark_done(7)
11711
11832
  return
@@ -11758,6 +11879,21 @@ class Orchestrator:
11758
11879
  if r != "downloaded":
11759
11880
  raise StepError(7, "selector_not_found", f"箱唛弹窗下载失败 ({r})",
11760
11881
  recovery_attempted=["role_dialog", "leaf_normal"])
11882
+ # 2026-11-24(0.13 阶段2):download-box-label 模式只下载箱唛 PDF;
11883
+ # 不勾 fragile、不点 Continuar、不写飞书/ERP,拿到文件即收口。
11884
+ if getattr(self, "box_download_only", False):
11885
+ if self.cfg.table_mode == TABLE_MODE_LIP:
11886
+ box_name = f"{self.state.shipment_id}-{self.state.box}箱-{self._safe_name(self.state.name)}.pdf"
11887
+ else:
11888
+ store_tag = self._safe_name(self.state.store_name or self.cfg.store_name)
11889
+ box_name = (f"{self.state.shipment_id}+{self.state.box}箱+{store_tag}"
11890
+ f"+{self._record_tag()}.pdf")
11891
+ ok = await self._download_box_label_with_retry(box_name, upload=False)
11892
+ if not ok:
11893
+ raise StepError(7, "business", "只下载箱唛模式未捕获 PDF(未生成/下载超时)",
11894
+ recovery_attempted=["boxlabel_download_only"])
11895
+ self._mark_done(7)
11896
+ return
11761
11897
  # 7f. 勾选 fragile checkbox(容器原生点击)
11762
11898
  r = await self.browser.click_checkboxes(
11763
11899
  '[data-testid="checkbox-fragils-consolidation"]', step=7, wait_after=1.0)
@@ -12167,7 +12303,8 @@ class Orchestrator:
12167
12303
  download_trigger: Optional[Callable[[], Any]] = None,
12168
12304
  wait_timeout: float = 60.0,
12169
12305
  step: Optional[int] = None,
12170
- biz_actions: str = "") -> bool:
12306
+ biz_actions: str = "",
12307
+ upload: bool = True) -> bool:
12171
12308
  """通用下载+上传:触发下载→轮询本 record 目标文件→按 record 前缀重命名→上传。
12172
12309
 
12173
12310
  kind:附件逻辑键("label"=产品标 / "box"=箱唛)——经字段映射层解析物理附件
@@ -12208,7 +12345,7 @@ class Orchestrator:
12208
12345
  self._log(f" ⚠️ 重命名失败: {exc}")
12209
12346
  renamed = src
12210
12347
 
12211
- if self.state.record_id and self.cfg.feishu_ready:
12348
+ if self.state.record_id and self.cfg.feishu_ready and upload:
12212
12349
  # KB-095:经 upload_kind 上传(lip 双写:FULL*文件 附件 + 勾选 checkbox)
12213
12350
  # KB-129:带步骤 + 「此前已完成的业务动作」(上传失败保真,不丢业务上下文)
12214
12351
  attach_field = self.feishu.upload_kind(
@@ -12220,6 +12357,10 @@ class Orchestrator:
12220
12357
  return True
12221
12358
  else:
12222
12359
  self._log(f" 文件已重命名(未上传): {renamed.name}")
12360
+ # download-only 模式:文件落盘本身就是成功;普通模式无 record/飞书时仍按失败处理
12361
+ if not upload:
12362
+ self.state.downloaded_box_path = str(renamed)
12363
+ return True
12223
12364
  return False
12224
12365
 
12225
12366
  def _open_store(self) -> tuple[Path, Optional[int]]:
@@ -12483,6 +12624,101 @@ class Orchestrator:
12483
12624
  return None
12484
12625
 
12485
12626
  # ---- 店铺级**执行者**锁(同店同一时刻只允许一个执行者;§8.57 事故的机械约束)----
12627
+ # ── 预约并行:槽位锁 + 窗口复用(2026-11-17)─────────────────────────────
12628
+ def acquire_appt_slot_lock(self, slot_no: int) -> bool:
12629
+ """预约「槽位锁」:同店 slotNo 1..N 各一把(非阻塞),决定同店并行数。"""
12630
+ if getattr(self.args, "no_lock", False):
12631
+ return True
12632
+ key = self._store_lock_key()
12633
+ if not key:
12634
+ return True
12635
+ try:
12636
+ slot = int(slot_no or 0)
12637
+ except (TypeError, ValueError):
12638
+ slot = 0
12639
+ if slot <= 0:
12640
+ return True
12641
+ # 2026-11-18:槽位锁按**通道**隔离(manual/full 各自 1..N),否则两条线会互相占走对方 slot
12642
+ # (实测:FULL 占 1店 slot1 ⇒ 运营抢预约的 slot1 抢不到锁,每店只能跑 1 条)
12643
+ channel = str(os.environ.get("ARGENT_APPOINTMENT_CHANNEL", "manual") or "manual").strip() or "manual"
12644
+ lock_path = os.path.join(lock_dir(), f"appt-slot-{key}-{channel}-{slot}.lock")
12645
+ lock = FileLock(lock_path, site="orchestrator.appt_slot_lock")
12646
+ try:
12647
+ got = lock.try_acquire()
12648
+ except LockError as exc:
12649
+ lock.release()
12650
+ self._log(f"⚠️ 槽位锁不可用,降级为不限制({exc})")
12651
+ return True
12652
+ if not got:
12653
+ lock.release()
12654
+ self._log(f"⛔ 同店槽位 {slot} 已被占用({lock_path})⇒ 本任务让位")
12655
+ return False
12656
+ self._appt_slot_lock = lock
12657
+ try:
12658
+ f = lock.fp
12659
+ f.seek(0); f.truncate()
12660
+ f.write(json.dumps({"pid": os.getpid(), "slot": slot,
12661
+ "store": self.state.store_name or "",
12662
+ "since": time.strftime("%Y-%m-%d %H:%M:%S")}, ensure_ascii=False))
12663
+ f.flush()
12664
+ except Exception: # noqa: BLE001
12665
+ pass
12666
+ self._log(f" 🔒 预约槽位锁已获取:slot={slot}")
12667
+ return True
12668
+
12669
+ def release_appt_slot_lock(self) -> None:
12670
+ lock = getattr(self, "_appt_slot_lock", None)
12671
+ if lock is None:
12672
+ return
12673
+ try:
12674
+ lock.release()
12675
+ except Exception: # noqa: BLE001
12676
+ pass
12677
+ self._appt_slot_lock = None
12678
+
12679
+ def release_store_executor_lock(self) -> None:
12680
+ """释放开店权(同店窗口已就绪后立刻放行,让后续任务复用端口)。"""
12681
+ lock = getattr(self, "_store_exec_lock", None)
12682
+ if lock is None:
12683
+ return
12684
+ try:
12685
+ lock.release()
12686
+ except Exception: # noqa: BLE001
12687
+ pass
12688
+ self._store_exec_lock = None
12689
+
12690
+ def remember_store_window(self, port: int, download_dir: str = "") -> None:
12691
+ key = (self._cdp_store_id() or "").strip()
12692
+ if not key or not port:
12693
+ return
12694
+ try:
12695
+ write_cdp_port_map(key, self.state.store_name or "", "", int(port), str(download_dir or ""))
12696
+ except Exception as exc: # noqa: BLE001
12697
+ self._log(f" ⚠️ 写 cdp-port-map 失败(影响同店复用):{exc}")
12698
+
12699
+ def read_store_window(self, max_age_sec: int = 900):
12700
+ """读 cdp-port-map 里本店窗口 → (download_dir, port);过期/缺失返回 (None, None)。"""
12701
+ key = (self._cdp_store_id() or "").strip()
12702
+ if not key:
12703
+ return None, None
12704
+ try:
12705
+ data = json.loads(_cdp_port_map_path().read_text(encoding="utf-8"))
12706
+ except Exception: # noqa: BLE001
12707
+ return None, None
12708
+ rec = data.get(key) or {}
12709
+ port = int(rec.get("cdp_port") or 0)
12710
+ if not port:
12711
+ return None, None
12712
+ ts = str(rec.get("updated_at") or "")
12713
+ if ts:
12714
+ try:
12715
+ age = (datetime.now() - datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S")).total_seconds()
12716
+ if age > max_age_sec:
12717
+ return None, None
12718
+ except ValueError:
12719
+ pass
12720
+ return (rec.get("download_dir") or None), port
12721
+
12486
12722
  def acquire_store_executor_lock(self) -> bool:
12487
12723
  """获取店铺级执行者锁。拿不到 ⇒ False(调用方**不落表**、以 skipped 退出)。
12488
12724
 
@@ -12698,7 +12934,11 @@ class Orchestrator:
12698
12934
  else:
12699
12935
  await self.step3_select_product()
12700
12936
  elif step == 4:
12701
- await self.step4_appointment()
12937
+ if getattr(self.args, "skip_appointment", False):
12938
+ self._log(" ⏭ 跳过步骤4 预约(预约交给 FULL 预约队列,由 worker 持续抢号)")
12939
+ self._mark_done(4)
12940
+ else:
12941
+ await self.step4_appointment()
12702
12942
  elif step == 5:
12703
12943
  await self.step5_package_confirm()
12704
12944
  elif step == 6:
@@ -13240,6 +13480,9 @@ class Orchestrator:
13240
13480
  self.state.sku = rec["sku"]
13241
13481
  self.state.qty = rec["qty"]
13242
13482
  self.state.box = rec["box"]
13483
+ if _raw.get("skipAppointment") is True:
13484
+ self.args.skip_appointment = True
13485
+ self._log(" ⏭ record-json 要求跳过步骤4(预约交给 FULL 预约队列)")
13243
13486
  if rec["shipment_id"] and rec["shipment_id"] not in ("None", "null"):
13244
13487
  self.state.shipment_id = rec["shipment_id"]
13245
13488
  self._log(f" 已有货件号 {rec['shipment_id']},从步骤4继续")
@@ -13987,13 +14230,16 @@ def build_parser() -> argparse.ArgumentParser:
13987
14230
  prog="fulfillment_orchestrator.py",
13988
14231
  description="FULL 货件编排器:Playwright CDP + lark-cli 封装,返回 JSON 给 Agent。")
13989
14232
  p.add_argument("--mode", choices=["full", "dry-run", "step", "inspect", "lip-poll",
13990
- "cdp-preflight", "hub-status", "capacity-probe"],
14233
+ "cdp-preflight", "hub-status", "capacity-probe",
14234
+ "download-box-label"],
13991
14235
  default="full", help="full=全流程; dry-run=只读步骤; step=单步; inspect=自检; "
13992
14236
  "lip-poll=lip 表识别+拾取(KB-095); cdp-preflight=店铺窗口/CDP 前置检查(KB-133,只读); "
13993
14237
  "hub-status=hub-v2 真实状态**只读探针**(需求 1:判「产品标签/箱唛是否下载完成、"
13994
14238
  "预约是否被取消」;需 --shipment-id); "
13995
14239
  "capacity-probe=**仓容(库容)前置探测只读探针**(2026-10-10:判仓容满/可用/证据不足"
13996
14240
  "三态;⛔ 不点按钮、不写表、不改 defer 状态;需 --store-name)")
14241
+ p.add_argument("--force", action="store_true",
14242
+ help="download-box-label:即使 hub 称箱唛已下载也强制重新下载")
13997
14243
  p.add_argument("--hub-write-note", action="store_true",
13998
14244
  help="hub-status 模式:当 hub 判定为「运营手动完成」时,**只**写 FULL备注/当前步骤"
13999
14245
  "(识别为已完成(依据 hub-v2 实测;来源未声明));⛔ 仍不改写 FULL状态")
@@ -14003,8 +14249,12 @@ def build_parser() -> argparse.ArgumentParser:
14003
14249
  help="step 模式下的步骤号")
14004
14250
  p.add_argument("--allow-write", action="store_true",
14005
14251
  help="批准写步骤(3/4/5/7/8)执行(默认拒绝)")
14252
+ p.add_argument("--skip-appointment", action="store_true",
14253
+ help="FULL 流程跳过步骤4 预约(预约交给 ERP 的 FULL 预约队列;2026-11-18)")
14006
14254
  p.add_argument("--record-id", help="指定飞书记录 ID 定向处理(店铺从记录字段读取,忽略 --store-name 取第一条逻辑;供并发调度/定向重跑)")
14007
14255
  p.add_argument("--record-json", help="ERP-only:合成记录 JSON(record_id/sourceRecordId、sku、qty/quantity、box/boxCount、name、store_name/store、shipment_id/shipmentNo)")
14256
+ p.add_argument("--record-jsons-file", help="ERP 多标签 worker:JSON 数组文件(每项同 --record-json),父进程持店铺锁并行执行")
14257
+
14008
14258
  p.add_argument("--no-lip", action="store_true", help="不读写 lip(Feishu 写操作 no-op);常与 --record-json 使用")
14009
14259
  p.add_argument("--sku", help="SKU(配合 --record-id 使用)")
14010
14260
  p.add_argument("--qty", help="数量(配合 --record-id 使用)")
@@ -14026,6 +14276,79 @@ def build_parser() -> argparse.ArgumentParser:
14026
14276
  return p
14027
14277
 
14028
14278
 
14279
+ async def _run_batch_json_parallel(orch: "Orchestrator", args: argparse.Namespace) -> dict[str, Any]:
14280
+ """ERP 多标签 worker:JSON 数组文件 → 父进程持店铺锁,每个 record 独立子进程/标签页。"""
14281
+ path = str(getattr(args, "record_jsons_file", "") or "")
14282
+ try:
14283
+ raw = json.loads(Path(path).read_text(encoding="utf-8"))
14284
+ except Exception as exc: # noqa: BLE001
14285
+ return {"status": "failed", "error": {"step": None, "type": "business",
14286
+ "message": f"--record-jsons-file 读取失败: {exc}", "recovery_attempted": []}}
14287
+ records = raw if isinstance(raw, list) else (raw.get("records") if isinstance(raw, dict) else None)
14288
+ if not isinstance(records, list) or not records:
14289
+ return {"status": "failed", "error": {"step": None, "type": "business",
14290
+ "message": "--record-jsons-file 必须是非空 JSON 数组", "recovery_attempted": []}}
14291
+ stores = {str((r or {}).get("store_name") or (r or {}).get("store") or "") for r in records}
14292
+ stores.discard("")
14293
+ if len(stores) > 1:
14294
+ return {"status": "failed", "error": {"step": None, "type": "business",
14295
+ "message": f"同一批只能同一店铺,实际: {sorted(stores)}", "recovery_attempted": []}}
14296
+ store = args.store_name or (sorted(stores)[0] if stores else "")
14297
+ if not store:
14298
+ return {"status": "failed", "error": {"step": None, "type": "business",
14299
+ "message": "record-json 缺 store_name", "recovery_attempted": []}}
14300
+ if not orch.acquire_store_executor_lock():
14301
+ return {"status": "batch", "connections": 0, "records": len(records),
14302
+ "results": [{"status": "skipped", "record_id": (r or {}).get("record_id", ""), "reason": "store_busy"}
14303
+ for r in records], "store_busy": True}
14304
+ parallel = max(1, min(5, int(args.parallel_records or 2)))
14305
+ sem = asyncio.Semaphore(parallel)
14306
+ script = str(Path(__file__).resolve())
14307
+
14308
+ async def run_one(record: dict) -> dict[str, Any]:
14309
+ rid = str(record.get("record_id") or "")
14310
+ async with sem:
14311
+ cmd = [sys.executable, script, "--mode", "full", "--record-json", json.dumps(record, ensure_ascii=False),
14312
+ "--store-name", store, "--allow-write", "--no-store-lock", "--no-lip"]
14313
+ orch._log(f" 🚀 并行子进程: record={rid}(父进程持店铺锁)")
14314
+ proc = await asyncio.create_subprocess_exec(
14315
+ *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
14316
+ env={**os.environ, "ARGENT_NO_STORE_LOCK": "1"},
14317
+ )
14318
+ out, err = await proc.communicate()
14319
+ out_s = out.decode("utf-8", "replace")
14320
+ result = None
14321
+ for line in reversed(out_s.splitlines()):
14322
+ try:
14323
+ j = json.loads(line)
14324
+ if isinstance(j, dict) and j.get("status"):
14325
+ result = j
14326
+ break
14327
+ except Exception: # noqa: BLE001
14328
+ continue
14329
+ if result is None:
14330
+ result = {"status": "failed", "record_id": rid,
14331
+ "error": {"step": None, "type": "cli_error",
14332
+ "message": (err.decode("utf-8", "replace") or out_s)[-800:] or f"子进程退出码 {proc.returncode}"}}
14333
+ result.setdefault("record_id", rid)
14334
+ result["parallel_child_exit"] = proc.returncode
14335
+ orch._log(f" ✅ 并行子进程完成: record={rid} status={result.get('status')} exit={proc.returncode}")
14336
+ return result
14337
+
14338
+ try:
14339
+ results = await asyncio.gather(*(run_one(r) for r in records))
14340
+ finally:
14341
+ try:
14342
+ lock = getattr(orch, "_store_exec_lock", None)
14343
+ if lock is not None:
14344
+ lock.release()
14345
+ orch._store_exec_lock = None
14346
+ except Exception: # noqa: BLE001
14347
+ pass
14348
+ return {"status": "batch", "connections": 0, "records": len(records),
14349
+ "parallel": parallel, "store": store, "results": list(results)}
14350
+
14351
+
14029
14352
  async def _run_batch_parallel(orch: "Orchestrator", args: argparse.Namespace) -> dict[str, Any]:
14030
14353
  """批量并行:父进程持有店铺锁,每条记录派独立 orchestrator 子进程 + 独立标签页。"""
14031
14354
  record_ids = [r.strip() for r in str(args.records or "").split(",") if r.strip()]
@@ -14239,6 +14562,71 @@ def main(argv: Optional[list[str]] = None) -> int:
14239
14562
  print(json.dumps(out, ensure_ascii=False))
14240
14563
  return 0 if out.get("status") == "ok" else 1
14241
14564
 
14565
+ if args.mode == "download-box-label":
14566
+ # 只下载箱唛:不预约、不取消、不写飞书/ERP;下载成功即返回文件路径与 sha256。
14567
+ if not args.shipment_id:
14568
+ print(json.dumps({"status": "failed", "mode": "download-box-label", "error": {
14569
+ "step": None, "type": "business",
14570
+ "message": "download-box-label 需要 --shipment-id <货件号>",
14571
+ "recovery_attempted": []}}, ensure_ascii=False))
14572
+ return 2
14573
+ store_name = args.store_name or cfg.store_name or ""
14574
+ if not store_name:
14575
+ print(json.dumps({"status": "failed", "mode": "download-box-label", "error": {
14576
+ "step": None, "type": "business",
14577
+ "message": "download-box-label 需要 --store-name <店铺名>",
14578
+ "recovery_attempted": []}}, ensure_ascii=False))
14579
+ return 2
14580
+ cfg.store_name = store_name
14581
+ try:
14582
+ sel = Selectors()
14583
+ except StepError as exc:
14584
+ print(json.dumps({"status": "failed", "error": exc.to_dict()}, ensure_ascii=False))
14585
+ return 1
14586
+ orch = Orchestrator(cfg, sel, args)
14587
+ orch.state.store_name = store_name
14588
+ orch.state.shipment_id = args.shipment_id
14589
+ orch.state.box = str(args.box or "").strip()
14590
+ orch.state.sku = str(args.sku or "").strip()
14591
+ orch.state.name = orch.state.sku or "box-label"
14592
+ orch.state.record_id = ""
14593
+ out: dict[str, Any] = {"status": "failed", "mode": "download-box-label",
14594
+ "store": store_name, "shipment_id": args.shipment_id,
14595
+ "read_only": True, "downloaded": False}
14596
+
14597
+ async def _download_flow() -> dict[str, Any]:
14598
+ if not orch.acquire_store_executor_lock():
14599
+ return {"status": "skipped", "reason": "store_busy", "holder": orch._store_exec_holder}
14600
+ try:
14601
+ _dl, port = orch._open_store()
14602
+ if not port:
14603
+ return {"status": "failed", "message": "CDP 端口未发现(店铺窗口未就绪)"}
14604
+ orch.browser.cdp_url = f"http://127.0.0.1:{port}"
14605
+ await orch._connect_with_port_rediscovery()
14606
+ await orch._preflight_store_window(phase="download-box-label")
14607
+ orch.force_box_labels = bool(args.force)
14608
+ orch.box_download_only = True
14609
+ await orch.step7_box_labels()
14610
+ path = str(getattr(orch.state, "downloaded_box_path", "") or "")
14611
+ if not path:
14612
+ return {"status": "failed", "message": "步骤7完成但未记录下载路径"}
14613
+ import hashlib
14614
+ h = hashlib.sha256(Path(path).read_bytes()).hexdigest()
14615
+ return {"status": "ok", "downloaded": True, "file_path": path,
14616
+ "sha256": h, "size": Path(path).stat().st_size}
14617
+ except StepError as exc:
14618
+ return {"status": "failed", "error": exc.to_dict(), "message": exc.message}
14619
+ except Exception as exc: # noqa: BLE001
14620
+ return {"status": "failed", "message": f"{type(exc).__name__}: {exc}"}
14621
+ finally:
14622
+ try:
14623
+ await orch.browser.close()
14624
+ except Exception: # noqa: BLE001
14625
+ pass
14626
+ out.update(asyncio.run(_download_flow()))
14627
+ print(json.dumps(out, ensure_ascii=False))
14628
+ return 0 if out.get("status") == "ok" else 1
14629
+
14242
14630
  if args.mode == "capacity-probe":
14243
14631
  # ── 仓容前置探测的**只读** CLI(2026-10-10):运维/角色一条命令取证 ──────────────
14244
14632
  # 与步骤4 内的预检**同一份判据、同一个探针**(`capacity_precheck(lift=False)`):
@@ -14430,7 +14818,9 @@ def main(argv: Optional[list[str]] = None) -> int:
14430
14818
 
14431
14819
  orch = Orchestrator(cfg, sel, args)
14432
14820
  try:
14433
- if args.records and int(args.parallel_records or 0) > 1 and args.mode == "full":
14821
+ if args.record_jsons_file and args.mode == "full":
14822
+ result = asyncio.run(_run_batch_json_parallel(orch, args))
14823
+ elif args.records and int(args.parallel_records or 0) > 1 and args.mode == "full":
14434
14824
  result = asyncio.run(_run_batch_parallel(orch, args))
14435
14825
  else:
14436
14826
  result = asyncio.run(_run_and_close(orch, args))