@whyshu/argent-engine 0.14.0 → 0.14.2

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.
package/MANIFEST.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "schema": 1,
3
3
  "package": "@whyshu/argent-engine",
4
4
  "files": {
5
- "VERSION": "065582655aacd6fc83ff742a5715c04bb4a57395bf3ee4559798fa42c2ce4589",
5
+ "VERSION": "232cca15f9cab0453d820d20649067576ec18d279ce3b1dc6d2931d1eb638721",
6
6
  "agents/catalog.json": "5356a812f2554dfd3115370363d4c3f787a82c9e5928a85d05b2a07c9e4b324d",
7
7
  "configs/_aliases.proposed.json": "3a59edf80563bcc20d410d488decad6fd787bd3de9489321367b0783904cd3e5",
8
8
  "configs/_migration-plan.proposed.json": "dd9f90b0b9b2f217dd23367a618402e57997d44f7fddcfa88a7cadf52e056c0d",
@@ -14,7 +14,7 @@
14
14
  "configs/mcp-tools.snapshot.json": "cfa94a6ba64a7ae9d133a4a878ce3d5e0e85e554ccd3e3ebaf0d51ad750acf6a",
15
15
  "configs/notify.json": "cb9ef11c1c498fcf99af99ec50271b8a2598061b77ed73a6099032e837474ef0",
16
16
  "core/cli/argent.mjs": "9a8977324c238ca4e20435f9817eb7ec76157da32b1d510977dc03e0feb416a9",
17
- "core/contracts/argent.contracts.json": "0a91f5e7e915c0cbce9bf3ba0b032250a1c662d6b1f33bb9e02b70ffb279cf9c",
17
+ "core/contracts/argent.contracts.json": "f61149e1a0a7b6e9cb0a042503129b559cf02985ded788952b56138419caa4a0",
18
18
  "core/contracts/verbs.schema.json": "54d726181c11536eb30bd25090584a7af103e4c0462f8ef078053c8177e19dcb",
19
19
  "core/lib/account-token.mjs": "35faad2c34e67755c1867f74a74885f0f268d5daabe01d339cf30dc747f86501",
20
20
  "core/lib/argent-datadir.mjs": "1fdd799c933382c4f9e36bd4af33d51b8ac4a466a9d67a8f2296bb267b5251ac",
@@ -161,7 +161,7 @@
161
161
  "scripts/final-check.mjs": "45e2004e778c83fe08b35921a555b2ca57ddb375672cc965544ef1bb6ff10aa8",
162
162
  "scripts/fix-skill-frontmatter.py": "c77cb8d389bd96bc40655bbdd712435bfb06f74453a2f54dad58013f615ea748",
163
163
  "scripts/flow-auto-retry.py": "2474e649e2e7c2803c3140b5c0780648059d3aadae299ea77a706a552b1fab63",
164
- "scripts/flow-requirements.json": "bc48886dd33ec10cd4daa8a35487bd3febb26db6ee73c0c9f89ed23cf4ab4d58",
164
+ "scripts/flow-requirements.json": "2ca7e96b32b981b35620a4e555bded4cf670a508fb7195a11e824970fa0fead7",
165
165
  "scripts/flow-scaffold.py": "d886e4e5d5cf0e80991d1d1a40e54a7281d87fec7c781c89101277795e401ae1",
166
166
  "scripts/flow-session-retention.mjs": "a9a2d261dce959bcd0eb26361413b9fc10fd1cbd562f86c614face66861c9793",
167
167
  "scripts/flow-timers-plist.sh": "a7b1007526fe21923566a002ef4e50fade5cbcdef38799f1a52e50c7b9c21131",
@@ -193,7 +193,7 @@
193
193
  "scripts/flow_write_verify.py": "a9123838b00cb60b43fbc761f6dae740dfa3692906c2985e9b98a7c4538c2491",
194
194
  "scripts/fulfillment.js": "8de1ea386ebfe628caf4eaf2df5f1941938c07d4b8b2dcf79a78d45ac231669f",
195
195
  "scripts/fulfillment_sites.py": "7120ddcd891b1de588b4c80420af9b7291bfd2e582a7bb41cf9fcd91a0699fe7",
196
- "scripts/full-exec-worker.mjs": "ff62a3bacd91834a4fa51054e3979b9ef0e8cc6bf68dafbe5fdbcb1d6fc5a2b3",
196
+ "scripts/full-exec-worker.mjs": "ddc10b18ee29ff85b782a1145ef0e94e32af3397c16d7e4697ac3925796bf805",
197
197
  "scripts/gen-agent-bundles.mjs": "3ab452fb7b1026a1bfab02977c85229985b390db4bc8458ce974b94bc207ed17",
198
198
  "scripts/gen-preset-rows.mjs": "1c074432be25148e9babce7ea1cb68d8fcef257abc2329f66b4ce488bc504578",
199
199
  "scripts/handover-sheet.mjs": "4e27095ccdd79586391abf7a7d5eb7aabbc3f0d7d9a1dd5161e9af8e8a9338de",
@@ -311,6 +311,7 @@
311
311
  "scripts/patches/verify-session-migration.mjs": "0f6b3a177306fd4cbbe87b4423b7ff5f0d18e4e77bfa50b385ecc354dea90c17",
312
312
  "scripts/patches/verify-turn-outside-replace.mjs": "eeff9c907e8509652759fb3d1ce864e828a68ec882c977c8d819be165817f96d",
313
313
  "scripts/plan-role-rename.mjs": "63a52ddaeb1ca2a246fcbf069318166fe5d0abee6003e5304b3e771defb43da2",
314
+ "scripts/platform-appointment-scan.py": "e3208ea7359e3f8d93d7f5dbf1e2dafdfcc0f0695e55b111096448f4bbac7caa",
314
315
  "scripts/plugin-bootcheck.mjs": "bbfbfc9ec0fa409f9ca52012ecdd3b7b068bb4c0b31d49da491f1efc8784d977",
315
316
  "scripts/plugin-composition.json": "99c545b56828d81882bc126eac3c3826e04146c3bb68be288a2b3c3e4ed11b9d",
316
317
  "scripts/poc-mcp-host.mjs": "5c4befdc95f98bf9c84f94bb525b245248c751e08e3fc09bb987781e9e4859cb",
package/engine/VERSION CHANGED
@@ -1 +1 @@
1
- 0.14.0
1
+ 0.14.2
@@ -1,6 +1,6 @@
1
1
  {
2
- "argentVersion": "0.14.0",
3
- "_syncNote": "argentVersion 必须与仓库根 VERSION 同批更新:发布前置校验 scripts/check-version-consistency.mjs;2026-11-24 按 VERSION=0.14.0 校正。",
2
+ "argentVersion": "0.14.2",
3
+ "_syncNote": "argentVersion 必须与仓库根 VERSION 同批更新:发布前置校验 scripts/check-version-consistency.mjs;2026-11-24 按 VERSION=0.14.2 校正。",
4
4
  "principle": "宿主无关:宿主只依赖 `argent <verb>`;确定性逻辑在 CLI/MCP,不在提示词里。",
5
5
  "verbs": {
6
6
  "version": {
@@ -271,8 +271,10 @@
271
271
  "scripts/ml_hub_status.py",
272
272
  "scripts/ml_capacity_probe.py",
273
273
  "scripts/analyze-full-day.py",
274
+ "scripts/appointment_grab.py",
274
275
  "scripts/fulfillment.js",
275
276
  "scripts/full-exec-worker.mjs",
277
+ "scripts/platform-appointment-scan.py",
276
278
  "scripts/appointment_rules.py",
277
279
  "scripts/ml_schema_check.py"
278
280
  ],
@@ -126,7 +126,7 @@ async function findArtifacts(filesUploaded, sinceMs) {
126
126
  return found
127
127
  }
128
128
 
129
- let activeChild = null
129
+ const activeChildren = new Set()
130
130
  const activeTasks = new Map()
131
131
  let shuttingDown = false
132
132
 
@@ -134,7 +134,7 @@ async function shutdown(signal = 'SIGTERM') {
134
134
  if (shuttingDown) return
135
135
  shuttingDown = true
136
136
  console.log(`[worker] 收到 ${signal},停止并释放任务…`)
137
- try { activeChild?.kill('SIGTERM') } catch { /* noop */ }
137
+ for (const child of activeChildren) { try { child.kill('SIGTERM') } catch { /* noop */ } }
138
138
  for (const t of activeTasks.values()) {
139
139
  await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(t.id)}/release`, {
140
140
  workerId, reason: `worker_shutdown:${signal}`,
@@ -175,12 +175,12 @@ async function runAppointmentPhase(ctx) {
175
175
  cwd: ENGINE,
176
176
  env: { ...process.env, PYTHONPATH: 'scripts', PATH: `${dirname(process.execPath)}:${process.env.PATH || ''}` },
177
177
  })
178
- activeChild = child
178
+ activeChildren.add(child)
179
179
  let stdout = ''; let stderr = ''
180
180
  child.stdout.on('data', (b) => { stdout += String(b) })
181
181
  child.stderr.on('data', (b) => { stderr += String(b) })
182
- child.on('close', () => { activeChild = null; resolve(`${stdout}\n${stderr}`.trim()) })
183
- child.on('error', (e) => { activeChild = null; resolve(`WORKER_ERROR: ${e.message}`) })
182
+ child.on('close', () => { activeChildren.delete(child); resolve(`${stdout}\n${stderr}`.trim()) })
183
+ child.on('error', (e) => { activeChildren.delete(child); resolve(`WORKER_ERROR: ${e.message}`) })
184
184
  })
185
185
  let result = null
186
186
  for (const line of String(out).split('\n').reverse()) {
@@ -231,7 +231,7 @@ async function executeBatch(tasks) {
231
231
  if (String(r?.task?.status || '') === 'cancelled') {
232
232
  cancelSeen = true
233
233
  console.log('[worker] 任务已人工接管取消,终止子进程', t.id)
234
- try { activeChild?.kill('SIGTERM') } catch { /* noop */ }
234
+ for (const child of activeChildren) { try { child.kill('SIGTERM') } catch { /* noop */ } }
235
235
  }
236
236
  })
237
237
  .catch(() => {})
@@ -266,12 +266,12 @@ async function executeBatch(tasks) {
266
266
  ]
267
267
  if (skipSteps.length) args.push('--skip-steps', skipSteps.join(','))
268
268
  const child = spawn(PYTHON, args, { cwd: ENGINE, env: { ...process.env, PYTHONPATH: 'scripts', PATH: `${dirname(process.execPath)}:${process.env.PATH || ''}` } })
269
- activeChild = child
269
+ activeChildren.add(child)
270
270
  let stdout = ''; let stderr = ''
271
271
  child.stdout.on('data', (b) => { stdout += String(b) })
272
272
  child.stderr.on('data', (b) => { stderr += String(b) })
273
- child.on('close', () => { activeChild = null; resolve(`${stdout}\n${stderr}`.trim()) })
274
- child.on('error', (e) => { activeChild = null; resolve(`WORKER_ERROR: ${e.message}`) })
273
+ child.on('close', () => { activeChildren.delete(child); resolve(`${stdout}\n${stderr}`.trim()) })
274
+ child.on('error', (e) => { activeChildren.delete(child); resolve(`WORKER_ERROR: ${e.message}`) })
275
275
  })
276
276
  } finally {
277
277
  await rm(dir, { recursive: true, force: true }).catch(() => {})
@@ -330,22 +330,30 @@ async function executeBatch(tasks) {
330
330
  }
331
331
  }
332
332
 
333
- async function tick() {
334
- for (const store of STORES) {
335
- try {
336
- const claimed = await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/claim-batch`, {
337
- store, workerId, capacity: TABS, max: TABS,
338
- })
339
- const tasks = Array.isArray(claimed.tasks) ? claimed.tasks : []
340
- if (!tasks.length) continue
341
- console.log(`[worker] ${store}: 领取 ${tasks.length} 个任务`)
342
- await executeBatch(tasks)
343
- } catch (e) {
344
- console.warn(`[worker] ${store} 轮询失败:${e.message}`)
345
- }
333
+ const storeBusy = new Set()
334
+
335
+ async function tickStore(store) {
336
+ if (storeBusy.has(store)) return
337
+ storeBusy.add(store)
338
+ try {
339
+ const claimed = await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/claim-batch`, {
340
+ store, workerId, capacity: TABS, max: TABS,
341
+ })
342
+ const tasks = Array.isArray(claimed.tasks) ? claimed.tasks : []
343
+ if (!tasks.length) return
344
+ console.log(`[worker] ${store}: 领取 ${tasks.length} 个任务`)
345
+ await executeBatch(tasks)
346
+ } catch (e) {
347
+ console.warn(`[worker] ${store} 轮询失败:${e.message}`)
348
+ } finally {
349
+ storeBusy.delete(store)
346
350
  }
347
351
  }
348
352
 
353
+ async function tick() {
354
+ await Promise.all(STORES.map((store) => tickStore(store)))
355
+ }
356
+
349
357
  if (process.argv.includes('--check')) await preflightCheck()
350
358
  console.log(`[worker] 启动 stores=${STORES.join(',')} tabs=${TABS} base=${BASE}`)
351
359
  await tick()
@@ -0,0 +1,294 @@
1
+ #!/usr/bin/env python3
2
+ """平台预约只读扫描器(0.14.x Phase 2 MVP)。
3
+
4
+ 只读打开 Seller Center 的 Gestión de envíos Full 页面,逐页读取货件行:
5
+ · 货件号、申报数量、预约日期/时段、仓库、平台状态
6
+ · 不点击取消/预约按钮,不修改平台,不写入 ERP
7
+
8
+ 浏览器通过 CDP 复用已打开的店铺窗口;调用方负责提供 cdp_port、店名和 Seller Center base URL。
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import pathlib
16
+ import re
17
+ import sys
18
+ import time
19
+ import urllib.request
20
+ from datetime import date, datetime, timezone
21
+ from typing import Any
22
+
23
+ INBOUNDS_PATH = "/shipping/inbounds?page={page}"
24
+ MONTHS = {
25
+ "enero": 1, "febrero": 2, "marzo": 3, "abril": 4, "mayo": 5, "junio": 6,
26
+ "julio": 7, "agosto": 8, "septiembre": 9, "setiembre": 9, "octubre": 10,
27
+ "noviembre": 11, "diciembre": 12,
28
+ }
29
+ DATE_RE = re.compile(r"(\d{1,2})\s*/\s*([a-záéíóú]+)\s+(\d{4})(?:\s*,\s*(\d{1,2})\s*:\s*(\d{2}))?", re.I)
30
+ QTY_RE = re.compile(r"^\s*([\d.,]+)")
31
+ STATUS_MAP = {
32
+ "pendiente de recepción": "pending_reception",
33
+ "pendiente de recepcion": "pending_reception",
34
+ "en preparación": "preparing",
35
+ "en preparacion": "preparing",
36
+ "reserva cancelada": "cancelled",
37
+ "reserva cancelada.": "cancelled",
38
+ "vencido": "expired",
39
+ }
40
+
41
+
42
+ def parse_spanish_datetime(text: str) -> dict[str, Any]:
43
+ raw = str(text or "").strip()
44
+ m = DATE_RE.search(raw)
45
+ if not m:
46
+ return {"date": "", "time": "", "datetime": "", "raw": raw}
47
+ day, month_name, year, hh, mm = m.groups()
48
+ month = MONTHS.get(month_name.lower())
49
+ if not month:
50
+ return {"date": "", "time": "", "datetime": "", "raw": raw}
51
+ try:
52
+ d = date(int(year), month, int(day))
53
+ except ValueError:
54
+ return {"date": "", "time": "", "datetime": "", "raw": raw}
55
+ h = int(hh) if hh is not None else 0
56
+ mi = int(mm) if mm is not None else 0
57
+ if h > 23 or mi > 59:
58
+ h = mi = 0
59
+ return {
60
+ "date": d.isoformat(),
61
+ "time": f"{h:02d}:{mi:02d}" if hh is not None else "",
62
+ "datetime": f"{d.isoformat()}T{h:02d}:{mi:02d}:00",
63
+ "raw": raw,
64
+ }
65
+
66
+
67
+ def parse_quantity(text: str) -> int | None:
68
+ m = QTY_RE.search(str(text or ""))
69
+ if not m:
70
+ return None
71
+ raw = m.group(1).replace(".", "").replace(",", ".")
72
+ try:
73
+ return int(float(raw))
74
+ except ValueError:
75
+ return None
76
+
77
+
78
+ def normalize_status(text: str) -> str:
79
+ t = str(text or "").strip().lower()
80
+ return STATUS_MAP.get(t, t.replace(" ", "_"))
81
+
82
+
83
+ def parse_row(texts: dict[str, str], store: str, page_no: int) -> dict[str, Any] | None:
84
+ inbound = texts.get("Envío", "")
85
+ m = re.search(r"#(\d{6,})", inbound)
86
+ if not m:
87
+ return None
88
+ shipment_no = m.group(1)
89
+ appointment_text = texts.get("Cita reservada", "")
90
+ appt = parse_spanish_datetime(appointment_text)
91
+ status_text = texts.get("Estado", "")
92
+ status = normalize_status(status_text)
93
+ cancelled = status == "cancelled"
94
+ return {
95
+ "store": store,
96
+ "shipmentNo": shipment_no,
97
+ "declaredQty": parse_quantity(next((v for k, v in texts.items() if k.startswith("Unidades declaradas") or k.startswith("Declaradas")), "")),
98
+ "appointmentText": " ".join(appointment_text.split())[:300],
99
+ "appointmentDate": appt["date"],
100
+ "appointmentTime": appt["time"],
101
+ "appointmentAt": (f"{appt['date']}T{appt['time']}:00-06:00" if appt["date"] and appt["time"] else appt["datetime"]),
102
+ "warehouse": "",
103
+ "status": status,
104
+ "statusText": status_text.strip()[:100],
105
+ "appointmentBooked": bool(appt["date"]) and not cancelled,
106
+ "cancelled": cancelled,
107
+ "page": page_no,
108
+ "source": "platform_scan",
109
+ "scannedAt": datetime.now(timezone.utc).isoformat(),
110
+ }
111
+
112
+
113
+ def _rows_from_page(page: Any, store: str, page_no: int) -> list[dict[str, Any]]:
114
+ rows = page.locator("table tr").all()
115
+ out: list[dict[str, Any]] = []
116
+ for row in rows:
117
+ cells = row.locator("td").all()
118
+ if not cells:
119
+ continue
120
+ texts: dict[str, str] = {}
121
+ for cell in cells:
122
+ title = cell.get_attribute("data-title") or ""
123
+ if not title:
124
+ continue
125
+ try:
126
+ text = cell.inner_text(timeout=3000)
127
+ except Exception:
128
+ text = ""
129
+ # 列表页的预约/仓库/状态在同一行;保留完整文本供解析。
130
+ texts[title] = text
131
+ if "Envío" not in texts:
132
+ continue
133
+ item = parse_row(texts, store, page_no)
134
+ if not item:
135
+ continue
136
+ # 仓库是预约单元格里的第二段;单独抓一下 class 更稳。
137
+ try:
138
+ wh = row.locator(".inbound-warehouse-name").first.inner_text(timeout=2000).strip()
139
+ if wh:
140
+ item["warehouse"] = wh[:200]
141
+ except Exception:
142
+ pass
143
+ out.append(item)
144
+ return out
145
+
146
+
147
+ def post_snapshot(*, api_base: str, tenant_app: str, machine_id: str, machine_token: str, result: dict[str, Any], complete: bool = False) -> dict[str, Any]:
148
+ url = f"{str(api_base).rstrip('/')}/api/argent/v1/tenants/{tenant_app}/machines/{machine_id}/platform-appointments/scan"
149
+ body = json.dumps({
150
+ "store": result.get("store"),
151
+ "items": result.get("items") or [],
152
+ "scannedAt": result.get("scannedAt"),
153
+ "source": "platform_scan",
154
+ "complete": bool(complete),
155
+ }, ensure_ascii=False).encode("utf-8")
156
+ req = urllib.request.Request(url, data=body, method="POST", headers={
157
+ "Content-Type": "application/json",
158
+ "Authorization": f"Bearer {machine_token}",
159
+ })
160
+ try:
161
+ with urllib.request.urlopen(req, timeout=30) as r:
162
+ return {"ok": 200 <= r.status < 300, "status": r.status, "body": r.read(5000).decode("utf-8", "replace")}
163
+ except Exception as e: # noqa: BLE001
164
+ return {"ok": False, "error": str(e)[:500]}
165
+
166
+
167
+ def scan(store: str, cdp_port: int, *, base_url: str, max_pages: int = 20, wait_sec: float = 8.0) -> dict[str, Any]:
168
+ from playwright.sync_api import sync_playwright
169
+
170
+ items: list[dict[str, Any]] = []
171
+ seen: set[str] = set()
172
+ pages: list[int] = []
173
+ with sync_playwright() as p:
174
+ browser = p.chromium.connect_over_cdp(f"http://127.0.0.1:{int(cdp_port)}")
175
+ ctx = browser.contexts[0] if browser.contexts else browser.new_context()
176
+ page = ctx.new_page()
177
+ page.set_default_timeout(30_000)
178
+ try:
179
+ for page_no in range(1, max_pages + 1):
180
+ page.goto(str(base_url).rstrip("/") + INBOUNDS_PATH.format(page=page_no), wait_until="domcontentloaded", timeout=45_000)
181
+ time.sleep(wait_sec)
182
+ page_rows = _rows_from_page(page, store, page_no)
183
+ fresh = [x for x in page_rows if x["shipmentNo"] not in seen]
184
+ for x in fresh:
185
+ seen.add(x["shipmentNo"])
186
+ items.append(x)
187
+ pages.append(page_no)
188
+ if not page_rows or not fresh:
189
+ break
190
+ finally:
191
+ try: page.close()
192
+ except Exception: pass
193
+ return {
194
+ "ok": True,
195
+ "store": store,
196
+ "cdpPort": int(cdp_port),
197
+ "pages": pages,
198
+ "count": len(items),
199
+ "items": items,
200
+ "scannedAt": datetime.now(timezone.utc).isoformat(),
201
+ }
202
+
203
+
204
+ def scan_all(*, cdp_map: str, base_url: str, max_pages: int, wait_sec: float) -> dict[str, Any]:
205
+ """按 cdp-port-map 逐个店铺只读扫描;一个店失败不阻断其他店。"""
206
+ path = pathlib.Path(cdp_map).expanduser()
207
+ data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
208
+ stores = []
209
+ for _sid, row in (data or {}).items():
210
+ name = str((row or {}).get("store_name") or "").strip()
211
+ port = int((row or {}).get("cdp_port") or 0)
212
+ if name and port:
213
+ stores.append((name, port))
214
+ stores = sorted(set(stores))
215
+ results = []
216
+ for name, port in stores:
217
+ try:
218
+ r = scan(name, port, base_url=base_url, max_pages=max_pages, wait_sec=wait_sec)
219
+ except Exception as e: # noqa: BLE001
220
+ r = {"ok": False, "store": name, "cdpPort": port, "error": str(e)[:300]}
221
+ results.append(r)
222
+ return {"ok": True, "mode": "all_stores", "stores": len(stores), "results": results, "scannedAt": datetime.now(timezone.utc).isoformat()}
223
+
224
+
225
+ def run_once(args: Any) -> dict[str, Any]:
226
+ try:
227
+ if not str(args.base_url or "").strip():
228
+ raise ValueError("缺少 --base-url / SELLER_CENTER_BASE")
229
+ if args.all_stores:
230
+ r = scan_all(cdp_map=args.cdp_map, base_url=args.base_url, max_pages=max(1, min(args.max_pages, 50)), wait_sec=max(1.0, args.wait))
231
+ if r.get("ok") and str(args.api_base or "").strip() and args.machine_token and args.machine_id and args.tenant_app:
232
+ for one in r.get("results") or []:
233
+ if one.get("ok"):
234
+ one["post"] = post_snapshot(api_base=args.api_base, tenant_app=args.tenant_app, machine_id=args.machine_id, machine_token=args.machine_token, result=one, complete=False)
235
+ else:
236
+ if not args.store or not args.cdp_port:
237
+ raise ValueError("单店模式需要 --store 和 --cdp-port;或使用 --all-stores")
238
+ r = scan(args.store, args.cdp_port, base_url=args.base_url, max_pages=max(1, min(args.max_pages, 50)), wait_sec=max(1.0, args.wait))
239
+ except Exception as e: # noqa: BLE001
240
+ r = {"ok": False, "store": args.store, "cdpPort": args.cdp_port, "error": str(e)[:500]}
241
+ if (not args.all_stores) and r.get("ok") and str(args.api_base or "").strip() and args.machine_token and args.machine_id and args.tenant_app:
242
+ r["post"] = post_snapshot(
243
+ api_base=args.api_base, tenant_app=args.tenant_app, machine_id=args.machine_id,
244
+ machine_token=args.machine_token, result=r, complete=False,
245
+ )
246
+ return r
247
+
248
+
249
+ def print_result(args: Any, r: dict[str, Any]) -> None:
250
+ text = json.dumps(r, ensure_ascii=False, indent=2)
251
+ if args.out:
252
+ with open(args.out, "w", encoding="utf-8") as f:
253
+ f.write(text + "\n")
254
+ if args.json:
255
+ print(text, flush=True)
256
+ else:
257
+ if r.get("mode") == "all_stores":
258
+ print(f"[scan] all_stores={r.get('stores')} results={len(r.get('results') or [])} ok={r.get('ok')}", flush=True)
259
+ for one in (r.get("results") or []):
260
+ print(f" {one.get('store')}: ok={one.get('ok')} count={one.get('count', 0)} post={(one.get('post') or {}).get('ok')}", flush=True)
261
+ else:
262
+ print(f"[scan] store={args.store} pages={r.get('pages')} count={r.get('count', 0)} ok={r.get('ok')}", flush=True)
263
+ for x in (r.get("items") or [])[:10]:
264
+ print(json.dumps(x, ensure_ascii=False), flush=True)
265
+
266
+
267
+ def main(argv: list[str] | None = None) -> int:
268
+ ap = argparse.ArgumentParser(description="只读扫描店铺 Full 已预约货件")
269
+ ap.add_argument("--store", default="", help="店铺名(--all-stores 时不需要)")
270
+ ap.add_argument("--all-stores", action="store_true", help="按 cdp-port-map 扫描全部店铺")
271
+ ap.add_argument("--cdp-map", default=os.path.expanduser("~/.dsh/argent/cdp-port-map.json"))
272
+ ap.add_argument("--cdp-port", type=int, default=0, help="店铺 browser CDP 端口(单店模式需要)")
273
+ ap.add_argument("--base-url", default=os.environ.get("SELLER_CENTER_BASE", ""), help="Seller Center base URL(或 SELLER_CENTER_BASE)")
274
+ ap.add_argument("--max-pages", type=int, default=20)
275
+ ap.add_argument("--wait", type=float, default=8.0)
276
+ ap.add_argument("--watch-minutes", type=float, default=0, help=">0 时常驻循环,按分钟间隔重复扫描")
277
+ ap.add_argument("--json", action="store_true", help="只输出 JSON,不打印进度")
278
+ ap.add_argument("--out", default="", help="JSON 输出文件(可选)")
279
+ ap.add_argument("--api-base", default=os.environ.get("ARGENT_ERP_BASE", ""), help="ERP API base(可选,设置后上报快照)")
280
+ ap.add_argument("--tenant-app", default=os.environ.get("ARGENT_TENANT_APP_ID", ""))
281
+ ap.add_argument("--machine-id", default=os.environ.get("ARGENT_MACHINE_ID", ""))
282
+ ap.add_argument("--machine-token", default=os.environ.get("ARGENT_MACHINE_TOKEN", ""), help="机器 token(只从 env/参数,不写日志)")
283
+ args = ap.parse_args(argv)
284
+ while True:
285
+ r = run_once(args)
286
+ print_result(args, r)
287
+ wait_min = float(args.watch_minutes or 0)
288
+ if wait_min <= 0:
289
+ return 0 if r.get("ok") else 1
290
+ time.sleep(max(60.0, wait_min * 60.0))
291
+
292
+
293
+ if __name__ == "__main__":
294
+ raise SystemExit(main())
@@ -1 +1 @@
1
- export const VERSION = "0.14.0"
1
+ export const VERSION = "0.14.2"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whyshu/argent-engine",
3
- "version": "0.14.0",
3
+ "version": "0.14.2",
4
4
  "description": "Argent 引擎(L1):流程/台账/重试/守卫/审计/浏览器自动化 —— 逐字节来自 argent-dsh 仓库",
5
5
  "type": "module",
6
6
  "engines": {