@whyshu/argent-engine 0.14.1 → 0.14.3
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 +7 -4
- package/engine/VERSION +1 -1
- package/engine/core/contracts/argent.contracts.json +2 -2
- package/engine/scripts/argent-timers.mjs +1 -0
- package/engine/scripts/flow-requirements.json +1 -0
- package/engine/scripts/platform-appointment-scan.py +313 -0
- package/engine/scripts/platform-scan-run.sh +46 -0
- package/engine/scripts/platform-scan-timers.sh +77 -0
- package/engine/version.mjs +1 -1
- package/package.json +1 -1
package/MANIFEST.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"schema": 1,
|
|
3
3
|
"package": "@whyshu/argent-engine",
|
|
4
4
|
"files": {
|
|
5
|
-
"VERSION": "
|
|
5
|
+
"VERSION": "f562b78d53673f1c58695eacf0753914674f1930a8ef51196cffca98ed8bee12",
|
|
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": "
|
|
17
|
+
"core/contracts/argent.contracts.json": "6f3b925258c219b605ae769f5c5a77db1582abb0af5817e704af4b2420b0105f",
|
|
18
18
|
"core/contracts/verbs.schema.json": "54d726181c11536eb30bd25090584a7af103e4c0462f8ef078053c8177e19dcb",
|
|
19
19
|
"core/lib/account-token.mjs": "35faad2c34e67755c1867f74a74885f0f268d5daabe01d339cf30dc747f86501",
|
|
20
20
|
"core/lib/argent-datadir.mjs": "1fdd799c933382c4f9e36bd4af33d51b8ac4a466a9d67a8f2296bb267b5251ac",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"scripts/argent-runner.mjs": "a4996d382cddc16d77cd760715eb89daf6fc38115df31d98a9a706d828009f15",
|
|
71
71
|
"scripts/argent-schedule.mjs": "4d2485f454094ae7d9978334e0ee995aef22fdc7058f3694c1f7d363e8a51f09",
|
|
72
72
|
"scripts/argent-setup-check.mjs": "44d3558ae6eebd5cc2dd25752019d3386190e63006b544e1ceee3f4f1c526aff",
|
|
73
|
-
"scripts/argent-timers.mjs": "
|
|
73
|
+
"scripts/argent-timers.mjs": "bed030b80972f447fec4d13eaa6fd63b6ebe462f2a2fa47aec6388dc6bb4c50f",
|
|
74
74
|
"scripts/argent-upgrade.mjs": "ba75148cb3c27b4aab2b184d1320d4b57a203adf8b90214fa3d62880685a0d81",
|
|
75
75
|
"scripts/argent-web-preflight.mjs": "7aa67912098b23cab2dec68d78830f7e5dc1d6c9cb915f4e00628fcd47bb694d",
|
|
76
76
|
"scripts/argent-web-verify.mjs": "9690885f7b379da87d879018e254e563ad6631b56381ee293ee06796ce605694",
|
|
@@ -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": "
|
|
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",
|
|
@@ -311,6 +311,9 @@
|
|
|
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": "955732419259690258cfd5001eb9c9ac9c54a717b125398c18ac53e301a5fc8e",
|
|
315
|
+
"scripts/platform-scan-run.sh": "0590e3b3a51835e22f2772d0f312cf988e8d6301cea4cd2255ca2509bfc119c7",
|
|
316
|
+
"scripts/platform-scan-timers.sh": "6ed5f1e6576c1b2dc652860ff60004a49eac0a3acb5d4ddcc25bf3ebb82cd8ff",
|
|
314
317
|
"scripts/plugin-bootcheck.mjs": "bbfbfc9ec0fa409f9ca52012ecdd3b7b068bb4c0b31d49da491f1efc8784d977",
|
|
315
318
|
"scripts/plugin-composition.json": "99c545b56828d81882bc126eac3c3826e04146c3bb68be288a2b3c3e4ed11b9d",
|
|
316
319
|
"scripts/poc-mcp-host.mjs": "5c4befdc95f98bf9c84f94bb525b245248c751e08e3fc09bb987781e9e4859cb",
|
package/engine/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
0.14.
|
|
1
|
+
0.14.3
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
|
-
"argentVersion": "0.14.
|
|
3
|
-
"_syncNote": "argentVersion 必须与仓库根 VERSION 同批更新:发布前置校验 scripts/check-version-consistency.mjs;2026-11-24 按 VERSION=0.14.
|
|
2
|
+
"argentVersion": "0.14.3",
|
|
3
|
+
"_syncNote": "argentVersion 必须与仓库根 VERSION 同批更新:发布前置校验 scripts/check-version-consistency.mjs;2026-11-24 按 VERSION=0.14.3 校正。",
|
|
4
4
|
"principle": "宿主无关:宿主只依赖 `argent <verb>`;确定性逻辑在 CLI/MCP,不在提示词里。",
|
|
5
5
|
"verbs": {
|
|
6
6
|
"version": {
|
|
@@ -37,6 +37,7 @@ export const KNOWN_LABELS = Object.freeze({
|
|
|
37
37
|
'com.whyshu.fulfillment-poll': { desc: '旧轮询(已退役,应清理)', kind: 'retired' },
|
|
38
38
|
// 2026-11-27:客户机实测清单里出现但我们漏收录的(截图里显示"未知"的正是这些)
|
|
39
39
|
'com.whyshu.ml-insight-timer': { desc: '店铺诊断(每小时 :20 跟随日报快照)', kind: 'insight', statusFile: 'ml-insight-diagnose-status.json' },
|
|
40
|
+
'com.whyshu.platform-appointment-scan': { desc: '平台预约只读扫描(每 30 分钟)', kind: 'insight', statusFile: 'platform-scan-status.json' },
|
|
40
41
|
'com.whyshu.ziniao-keepalive': { desc: '紫鸟浏览器保活(每 3 分钟)', kind: 'host' },
|
|
41
42
|
'com.whyshu.caffeinate': { desc: '防休眠(常驻)', kind: 'host' },
|
|
42
43
|
'com.whyshu.xzh-browser': { desc: '鑫中航浏览器(常驻,旧流程遗留)', kind: 'host' },
|
|
@@ -0,0 +1,313 @@
|
|
|
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 socket
|
|
18
|
+
import sys
|
|
19
|
+
import time
|
|
20
|
+
import urllib.request
|
|
21
|
+
from datetime import date, datetime, timezone
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
INBOUNDS_PATH = "/shipping/inbounds?page={page}"
|
|
25
|
+
MONTHS = {
|
|
26
|
+
"enero": 1, "febrero": 2, "marzo": 3, "abril": 4, "mayo": 5, "junio": 6,
|
|
27
|
+
"julio": 7, "agosto": 8, "septiembre": 9, "setiembre": 9, "octubre": 10,
|
|
28
|
+
"noviembre": 11, "diciembre": 12,
|
|
29
|
+
}
|
|
30
|
+
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)
|
|
31
|
+
QTY_RE = re.compile(r"^\s*([\d.,]+)")
|
|
32
|
+
STATUS_MAP = {
|
|
33
|
+
"pendiente de recepción": "pending_reception",
|
|
34
|
+
"pendiente de recepcion": "pending_reception",
|
|
35
|
+
"en preparación": "preparing",
|
|
36
|
+
"en preparacion": "preparing",
|
|
37
|
+
"reserva cancelada": "cancelled",
|
|
38
|
+
"reserva cancelada.": "cancelled",
|
|
39
|
+
"vencido": "expired",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_spanish_datetime(text: str) -> dict[str, Any]:
|
|
44
|
+
raw = str(text or "").strip()
|
|
45
|
+
m = DATE_RE.search(raw)
|
|
46
|
+
if not m:
|
|
47
|
+
return {"date": "", "time": "", "datetime": "", "raw": raw}
|
|
48
|
+
day, month_name, year, hh, mm = m.groups()
|
|
49
|
+
month = MONTHS.get(month_name.lower())
|
|
50
|
+
if not month:
|
|
51
|
+
return {"date": "", "time": "", "datetime": "", "raw": raw}
|
|
52
|
+
try:
|
|
53
|
+
d = date(int(year), month, int(day))
|
|
54
|
+
except ValueError:
|
|
55
|
+
return {"date": "", "time": "", "datetime": "", "raw": raw}
|
|
56
|
+
h = int(hh) if hh is not None else 0
|
|
57
|
+
mi = int(mm) if mm is not None else 0
|
|
58
|
+
if h > 23 or mi > 59:
|
|
59
|
+
h = mi = 0
|
|
60
|
+
return {
|
|
61
|
+
"date": d.isoformat(),
|
|
62
|
+
"time": f"{h:02d}:{mi:02d}" if hh is not None else "",
|
|
63
|
+
"datetime": f"{d.isoformat()}T{h:02d}:{mi:02d}:00",
|
|
64
|
+
"raw": raw,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse_quantity(text: str) -> int | None:
|
|
69
|
+
m = QTY_RE.search(str(text or ""))
|
|
70
|
+
if not m:
|
|
71
|
+
return None
|
|
72
|
+
raw = m.group(1).replace(".", "").replace(",", ".")
|
|
73
|
+
try:
|
|
74
|
+
return int(float(raw))
|
|
75
|
+
except ValueError:
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def normalize_status(text: str) -> str:
|
|
80
|
+
t = str(text or "").strip().lower()
|
|
81
|
+
return STATUS_MAP.get(t, t.replace(" ", "_"))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parse_row(texts: dict[str, str], store: str, page_no: int) -> dict[str, Any] | None:
|
|
85
|
+
inbound = texts.get("Envío", "")
|
|
86
|
+
m = re.search(r"#(\d{6,})", inbound)
|
|
87
|
+
if not m:
|
|
88
|
+
return None
|
|
89
|
+
shipment_no = m.group(1)
|
|
90
|
+
appointment_text = texts.get("Cita reservada", "")
|
|
91
|
+
appt = parse_spanish_datetime(appointment_text)
|
|
92
|
+
status_text = texts.get("Estado", "")
|
|
93
|
+
status = normalize_status(status_text)
|
|
94
|
+
cancelled = status == "cancelled"
|
|
95
|
+
return {
|
|
96
|
+
"store": store,
|
|
97
|
+
"shipmentNo": shipment_no,
|
|
98
|
+
"declaredQty": parse_quantity(next((v for k, v in texts.items() if k.startswith("Unidades declaradas") or k.startswith("Declaradas")), "")),
|
|
99
|
+
"appointmentText": " ".join(appointment_text.split())[:300],
|
|
100
|
+
"appointmentDate": appt["date"],
|
|
101
|
+
"appointmentTime": appt["time"],
|
|
102
|
+
"appointmentAt": (f"{appt['date']}T{appt['time']}:00-06:00" if appt["date"] and appt["time"] else appt["datetime"]),
|
|
103
|
+
"warehouse": "",
|
|
104
|
+
"status": status,
|
|
105
|
+
"statusText": status_text.strip()[:100],
|
|
106
|
+
"appointmentBooked": bool(appt["date"]) and not cancelled,
|
|
107
|
+
"cancelled": cancelled,
|
|
108
|
+
"page": page_no,
|
|
109
|
+
"source": "platform_scan",
|
|
110
|
+
"scannedAt": datetime.now(timezone.utc).isoformat(),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _rows_from_page(page: Any, store: str, page_no: int) -> list[dict[str, Any]]:
|
|
115
|
+
rows = page.locator("table tr").all()
|
|
116
|
+
out: list[dict[str, Any]] = []
|
|
117
|
+
for row in rows:
|
|
118
|
+
cells = row.locator("td").all()
|
|
119
|
+
if not cells:
|
|
120
|
+
continue
|
|
121
|
+
texts: dict[str, str] = {}
|
|
122
|
+
for cell in cells:
|
|
123
|
+
title = cell.get_attribute("data-title") or ""
|
|
124
|
+
if not title:
|
|
125
|
+
continue
|
|
126
|
+
try:
|
|
127
|
+
text = cell.inner_text(timeout=3000)
|
|
128
|
+
except Exception:
|
|
129
|
+
text = ""
|
|
130
|
+
# 列表页的预约/仓库/状态在同一行;保留完整文本供解析。
|
|
131
|
+
texts[title] = text
|
|
132
|
+
if "Envío" not in texts:
|
|
133
|
+
continue
|
|
134
|
+
item = parse_row(texts, store, page_no)
|
|
135
|
+
if not item:
|
|
136
|
+
continue
|
|
137
|
+
# 仓库是预约单元格里的第二段;单独抓一下 class 更稳。
|
|
138
|
+
try:
|
|
139
|
+
wh = row.locator(".inbound-warehouse-name").first.inner_text(timeout=2000).strip()
|
|
140
|
+
if wh:
|
|
141
|
+
item["warehouse"] = wh[:200]
|
|
142
|
+
except Exception:
|
|
143
|
+
pass
|
|
144
|
+
out.append(item)
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
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]:
|
|
149
|
+
url = f"{str(api_base).rstrip('/')}/api/argent/v1/tenants/{tenant_app}/machines/{machine_id}/platform-appointments/scan"
|
|
150
|
+
body = json.dumps({
|
|
151
|
+
"store": result.get("store"),
|
|
152
|
+
"items": result.get("items") or [],
|
|
153
|
+
"scannedAt": result.get("scannedAt"),
|
|
154
|
+
"source": "platform_scan",
|
|
155
|
+
"complete": bool(complete),
|
|
156
|
+
}, ensure_ascii=False).encode("utf-8")
|
|
157
|
+
req = urllib.request.Request(url, data=body, method="POST", headers={
|
|
158
|
+
"Content-Type": "application/json",
|
|
159
|
+
"Authorization": f"Bearer {machine_token}",
|
|
160
|
+
})
|
|
161
|
+
try:
|
|
162
|
+
with urllib.request.urlopen(req, timeout=30) as r:
|
|
163
|
+
return {"ok": 200 <= r.status < 300, "status": r.status, "body": r.read(5000).decode("utf-8", "replace")}
|
|
164
|
+
except Exception as e: # noqa: BLE001
|
|
165
|
+
return {"ok": False, "error": str(e)[:500]}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def scan(store: str, cdp_port: int, *, base_url: str, max_pages: int = 20, wait_sec: float = 8.0) -> dict[str, Any]:
|
|
169
|
+
from playwright.sync_api import sync_playwright
|
|
170
|
+
|
|
171
|
+
items: list[dict[str, Any]] = []
|
|
172
|
+
seen: set[str] = set()
|
|
173
|
+
pages: list[int] = []
|
|
174
|
+
with sync_playwright() as p:
|
|
175
|
+
browser = p.chromium.connect_over_cdp(f"http://127.0.0.1:{int(cdp_port)}", timeout=15_000)
|
|
176
|
+
ctx = browser.contexts[0] if browser.contexts else browser.new_context()
|
|
177
|
+
# 清掉上一次被 SIGKILL/超时留下的列表页,避免每轮扫描无限堆标签页;
|
|
178
|
+
# 只关 shipping/inbounds 列表页,绝不碰 /inbounds/<货件号>/... 的预约/执行页。
|
|
179
|
+
for old_page in list(ctx.pages):
|
|
180
|
+
try:
|
|
181
|
+
old_url = old_page.url or ""
|
|
182
|
+
if "/shipping/inbounds" in old_url and "/inbounds/" not in old_url:
|
|
183
|
+
old_page.close()
|
|
184
|
+
except Exception:
|
|
185
|
+
pass
|
|
186
|
+
page = ctx.new_page()
|
|
187
|
+
page.set_default_timeout(30_000)
|
|
188
|
+
try:
|
|
189
|
+
for page_no in range(1, max_pages + 1):
|
|
190
|
+
page.goto(str(base_url).rstrip("/") + INBOUNDS_PATH.format(page=page_no), wait_until="domcontentloaded", timeout=30_000)
|
|
191
|
+
time.sleep(wait_sec)
|
|
192
|
+
page_rows = _rows_from_page(page, store, page_no)
|
|
193
|
+
fresh = [x for x in page_rows if x["shipmentNo"] not in seen]
|
|
194
|
+
for x in fresh:
|
|
195
|
+
seen.add(x["shipmentNo"])
|
|
196
|
+
items.append(x)
|
|
197
|
+
pages.append(page_no)
|
|
198
|
+
if not page_rows or not fresh:
|
|
199
|
+
break
|
|
200
|
+
finally:
|
|
201
|
+
try: page.close()
|
|
202
|
+
except Exception: pass
|
|
203
|
+
return {
|
|
204
|
+
"ok": True,
|
|
205
|
+
"store": store,
|
|
206
|
+
"cdpPort": int(cdp_port),
|
|
207
|
+
"pages": pages,
|
|
208
|
+
"count": len(items),
|
|
209
|
+
"items": items,
|
|
210
|
+
"scannedAt": datetime.now(timezone.utc).isoformat(),
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def scan_all(*, cdp_map: str, base_url: str, max_pages: int, wait_sec: float) -> dict[str, Any]:
|
|
215
|
+
"""按 cdp-port-map 逐个店铺只读扫描;一个店失败不阻断其他店。"""
|
|
216
|
+
path = pathlib.Path(cdp_map).expanduser()
|
|
217
|
+
data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
218
|
+
stores = []
|
|
219
|
+
for _sid, row in (data or {}).items():
|
|
220
|
+
name = str((row or {}).get("store_name") or "").strip()
|
|
221
|
+
port = int((row or {}).get("cdp_port") or 0)
|
|
222
|
+
if name and port:
|
|
223
|
+
stores.append((name, port))
|
|
224
|
+
stores = sorted(set(stores))
|
|
225
|
+
results = []
|
|
226
|
+
for name, port in stores:
|
|
227
|
+
# 先做 TCP 探针:窗口没开就立即跳过,避免 Playwright 在死端口上等很久。
|
|
228
|
+
try:
|
|
229
|
+
with socket.create_connection(("127.0.0.1", int(port)), timeout=1.5):
|
|
230
|
+
pass
|
|
231
|
+
except Exception as e: # noqa: BLE001
|
|
232
|
+
results.append({"ok": False, "store": name, "cdpPort": port, "count": 0, "error": f"CDP 端口未监听:{str(e)[:120]}"})
|
|
233
|
+
continue
|
|
234
|
+
print(f"[scan] store={name} cdp={port} start", flush=True)
|
|
235
|
+
try:
|
|
236
|
+
r = scan(name, port, base_url=base_url, max_pages=max_pages, wait_sec=wait_sec)
|
|
237
|
+
except Exception as e: # noqa: BLE001
|
|
238
|
+
r = {"ok": False, "store": name, "cdpPort": port, "error": str(e)[:300]}
|
|
239
|
+
print(f"[scan] store={name} done ok={r.get('ok')} count={r.get('count', 0)}", flush=True)
|
|
240
|
+
results.append(r)
|
|
241
|
+
return {"ok": True, "mode": "all_stores", "stores": len(stores), "results": results, "scannedAt": datetime.now(timezone.utc).isoformat()}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def run_once(args: Any) -> dict[str, Any]:
|
|
245
|
+
try:
|
|
246
|
+
if not str(args.base_url or "").strip():
|
|
247
|
+
raise ValueError("缺少 --base-url / SELLER_CENTER_BASE")
|
|
248
|
+
if args.all_stores:
|
|
249
|
+
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))
|
|
250
|
+
if r.get("ok") and str(args.api_base or "").strip() and args.machine_token and args.machine_id and args.tenant_app:
|
|
251
|
+
for one in r.get("results") or []:
|
|
252
|
+
if one.get("ok"):
|
|
253
|
+
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)
|
|
254
|
+
else:
|
|
255
|
+
if not args.store or not args.cdp_port:
|
|
256
|
+
raise ValueError("单店模式需要 --store 和 --cdp-port;或使用 --all-stores")
|
|
257
|
+
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))
|
|
258
|
+
except Exception as e: # noqa: BLE001
|
|
259
|
+
r = {"ok": False, "store": args.store, "cdpPort": args.cdp_port, "error": str(e)[:500]}
|
|
260
|
+
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:
|
|
261
|
+
r["post"] = post_snapshot(
|
|
262
|
+
api_base=args.api_base, tenant_app=args.tenant_app, machine_id=args.machine_id,
|
|
263
|
+
machine_token=args.machine_token, result=r, complete=False,
|
|
264
|
+
)
|
|
265
|
+
return r
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def print_result(args: Any, r: dict[str, Any]) -> None:
|
|
269
|
+
text = json.dumps(r, ensure_ascii=False, indent=2)
|
|
270
|
+
if args.out:
|
|
271
|
+
with open(args.out, "w", encoding="utf-8") as f:
|
|
272
|
+
f.write(text + "\n")
|
|
273
|
+
if args.json:
|
|
274
|
+
print(text, flush=True)
|
|
275
|
+
else:
|
|
276
|
+
if r.get("mode") == "all_stores":
|
|
277
|
+
print(f"[scan] all_stores={r.get('stores')} results={len(r.get('results') or [])} ok={r.get('ok')}", flush=True)
|
|
278
|
+
for one in (r.get("results") or []):
|
|
279
|
+
print(f" {one.get('store')}: ok={one.get('ok')} count={one.get('count', 0)} post={(one.get('post') or {}).get('ok')}", flush=True)
|
|
280
|
+
else:
|
|
281
|
+
print(f"[scan] store={args.store} pages={r.get('pages')} count={r.get('count', 0)} ok={r.get('ok')}", flush=True)
|
|
282
|
+
for x in (r.get("items") or [])[:10]:
|
|
283
|
+
print(json.dumps(x, ensure_ascii=False), flush=True)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def main(argv: list[str] | None = None) -> int:
|
|
287
|
+
ap = argparse.ArgumentParser(description="只读扫描店铺 Full 已预约货件")
|
|
288
|
+
ap.add_argument("--store", default="", help="店铺名(--all-stores 时不需要)")
|
|
289
|
+
ap.add_argument("--all-stores", action="store_true", help="按 cdp-port-map 扫描全部店铺")
|
|
290
|
+
ap.add_argument("--cdp-map", default=os.path.expanduser("~/.dsh/argent/cdp-port-map.json"))
|
|
291
|
+
ap.add_argument("--cdp-port", type=int, default=0, help="店铺 browser CDP 端口(单店模式需要)")
|
|
292
|
+
ap.add_argument("--base-url", default=os.environ.get("SELLER_CENTER_BASE", ""), help="Seller Center base URL(或 SELLER_CENTER_BASE)")
|
|
293
|
+
ap.add_argument("--max-pages", type=int, default=20)
|
|
294
|
+
ap.add_argument("--wait", type=float, default=8.0)
|
|
295
|
+
ap.add_argument("--watch-minutes", type=float, default=0, help=">0 时常驻循环,按分钟间隔重复扫描")
|
|
296
|
+
ap.add_argument("--json", action="store_true", help="只输出 JSON,不打印进度")
|
|
297
|
+
ap.add_argument("--out", default="", help="JSON 输出文件(可选)")
|
|
298
|
+
ap.add_argument("--api-base", default=os.environ.get("ARGENT_ERP_BASE", ""), help="ERP API base(可选,设置后上报快照)")
|
|
299
|
+
ap.add_argument("--tenant-app", default=os.environ.get("ARGENT_TENANT_APP_ID", ""))
|
|
300
|
+
ap.add_argument("--machine-id", default=os.environ.get("ARGENT_MACHINE_ID", ""))
|
|
301
|
+
ap.add_argument("--machine-token", default=os.environ.get("ARGENT_MACHINE_TOKEN", ""), help="机器 token(只从 env/参数,不写日志)")
|
|
302
|
+
args = ap.parse_args(argv)
|
|
303
|
+
while True:
|
|
304
|
+
r = run_once(args)
|
|
305
|
+
print_result(args, r)
|
|
306
|
+
wait_min = float(args.watch_minutes or 0)
|
|
307
|
+
if wait_min <= 0:
|
|
308
|
+
return 0 if r.get("ok") else 1
|
|
309
|
+
time.sleep(max(60.0, wait_min * 60.0))
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
if __name__ == "__main__":
|
|
313
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# platform-scan-run.sh —— 只读平台预约扫描器的定时入口(launchd 直跑)。
|
|
3
|
+
# 由 platform-scan-timers.sh 安装;不预约、不取消、不占 FULL 槽位。
|
|
4
|
+
set -euo pipefail
|
|
5
|
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
6
|
+
. "$SCRIPT_DIR/lib/argent-datadir.sh"
|
|
7
|
+
DATA_HOME="${ARGENT_DATA_DIR_RESOLVED:?数据根解析失败:请显式给 ARGENT_DATA_DIR}"
|
|
8
|
+
REPORT="$DATA_HOME/agent-report.json"
|
|
9
|
+
ENV_FILE="$DATA_HOME/daily-report.env"
|
|
10
|
+
STATUS="$DATA_HOME/platform-scan-status.json"
|
|
11
|
+
LOG_DIR="$DATA_HOME/platform-scan-logs"
|
|
12
|
+
LOCK="$DATA_HOME/platform-scan.lock"
|
|
13
|
+
mkdir -p "$LOG_DIR"
|
|
14
|
+
now() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }
|
|
15
|
+
write_status() { # $1=exit $2=error
|
|
16
|
+
/usr/bin/python3 - "$STATUS" "$1" "${2:-}" "$STARTED" <<'PYEOF' 2>/dev/null || true
|
|
17
|
+
import json,sys,datetime
|
|
18
|
+
path,code,err,started=sys.argv[1:5]
|
|
19
|
+
now=datetime.datetime.now(datetime.timezone.utc)
|
|
20
|
+
try: doc=json.load(open(path))
|
|
21
|
+
except Exception: doc={}
|
|
22
|
+
doc.update({"lastRunAt":doc.get("lastRunAt") or started,"lastFinishAt":now.isoformat().replace("+00:00","Z"),"lastExit":int(code) if str(code).lstrip("-").isdigit() else 1,"lastError":err,"nextDueAt":(now+datetime.timedelta(minutes=30)).isoformat().replace("+00:00","Z")})
|
|
23
|
+
open(path,"w").write(json.dumps(doc,ensure_ascii=False,indent=2)+"\n")
|
|
24
|
+
PYEOF
|
|
25
|
+
}
|
|
26
|
+
env_get() { [ -f "$ENV_FILE" ] || return 0; grep -E "^[[:space:]]*$1=" "$ENV_FILE" 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '"' | tr -d "'" | sed 's/[[:space:]]*$//'; }
|
|
27
|
+
if [ -f "$DATA_HOME/platform-scan.env" ]; then . "$DATA_HOME/platform-scan.env"; fi
|
|
28
|
+
if [ "$(env_get PLATFORM_SCAN_ENABLED)" != "true" ]; then exit 0; fi
|
|
29
|
+
if [ -d "$LOCK" ]; then exit 0; fi
|
|
30
|
+
mkdir "$LOCK" 2>/dev/null || exit 0
|
|
31
|
+
trap 'rmdir "$LOCK" 2>/dev/null || true' EXIT
|
|
32
|
+
if [ ! -f "$REPORT" ]; then write_status 1 "agent-report.json 缺失"; exit 1; fi
|
|
33
|
+
TOKEN="$("/usr/bin/python3" -c 'import json,sys; print(json.load(open(sys.argv[1])).get("machineToken",""))' "$REPORT" 2>/dev/null || true)"
|
|
34
|
+
APP="$("/usr/bin/python3" -c 'import json,sys; print(json.load(open(sys.argv[1])).get("tenantAppId","ly-0001"))' "$REPORT" 2>/dev/null || true)"
|
|
35
|
+
MID="$("/usr/bin/python3" -c 'import json,sys; print(json.load(open(sys.argv[1])).get("machineId",""))' "$REPORT" 2>/dev/null || true)"
|
|
36
|
+
BASE="$(env_get SELLER_CENTER_BASE)"
|
|
37
|
+
if [ -z "$BASE" ]; then echo "缺少 SELLER_CENTER_BASE:请在 $DATA_HOME/platform-scan.env 配置" >&2; write_status 1 "SELLER_CENTER_BASE 未配置"; exit 1; fi
|
|
38
|
+
PYBIN="$HOME/.dsh/argent/venv/bin/python3"; [ -x "$PYBIN" ] || PYBIN="$("/usr/bin/which" python3)"
|
|
39
|
+
STARTED="$(now)"
|
|
40
|
+
set +e
|
|
41
|
+
ARGENT_MACHINE_TOKEN="$TOKEN" ARGENT_ERP_BASE="${ARGENT_ERP_BASE:-https://whyshu.com}" ARGENT_TENANT_APP_ID="$APP" ARGENT_MACHINE_ID="$MID" SELLER_CENTER_BASE="$BASE" \
|
|
42
|
+
"$PYBIN" "$SCRIPT_DIR/platform-appointment-scan.py" --all-stores --max-pages 5 --wait 6 >>"$LOG_DIR/platform-scan.log" 2>&1
|
|
43
|
+
CODE=$?
|
|
44
|
+
set -e
|
|
45
|
+
write_status "$CODE" ""
|
|
46
|
+
exit "$CODE"
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# platform-scan-timers.sh —— 只读平台预约扫描器的 launchd 安装/卸载/状态。
|
|
3
|
+
# bash scripts/platform-scan-timers.sh install [--force] [--allow-non-production]
|
|
4
|
+
# bash scripts/platform-scan-timers.sh uninstall
|
|
5
|
+
# bash scripts/platform-scan-timers.sh status
|
|
6
|
+
# bash scripts/platform-scan-timers.sh run-now
|
|
7
|
+
set -euo pipefail
|
|
8
|
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
9
|
+
. "$SCRIPT_DIR/lib/argent-datadir.sh"
|
|
10
|
+
LABEL="com.whyshu.platform-appointment-scan"
|
|
11
|
+
AGENTS="$HOME/Library/LaunchAgents"
|
|
12
|
+
DATA_HOME="${ARGENT_DATA_DIR_RESOLVED:?数据根解析失败:请显式给 ARGENT_DATA_DIR}"
|
|
13
|
+
RUNNER="$SCRIPT_DIR/platform-scan-run.sh"
|
|
14
|
+
LOG_DIR="$DATA_HOME/platform-scan-logs"
|
|
15
|
+
PLIST="$AGENTS/$LABEL.plist"
|
|
16
|
+
ENV_FILE="$DATA_HOME/platform-scan.env"
|
|
17
|
+
|
|
18
|
+
usage() { sed -n '2,9p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; }
|
|
19
|
+
is_production() {
|
|
20
|
+
/usr/bin/python3 - "$DATA_HOME/config.json" <<'PYEOF' 2>/dev/null || exit 1
|
|
21
|
+
import json,sys
|
|
22
|
+
try:
|
|
23
|
+
d=json.load(open(sys.argv[1])); r=(d.get('dailyReport') or {}).get('role',''); a=len((d.get('dailyReport') or {}).get('allowedChatIds') or [])
|
|
24
|
+
raise SystemExit(0 if r=='production' or a>0 else 1)
|
|
25
|
+
except SystemExit: raise
|
|
26
|
+
except Exception: raise SystemExit(1)
|
|
27
|
+
PYEOF
|
|
28
|
+
}
|
|
29
|
+
gen() {
|
|
30
|
+
cat <<PLIST
|
|
31
|
+
<?xml version="1.0" encoding="UTF-8"?>
|
|
32
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
33
|
+
<plist version="1.0">
|
|
34
|
+
<dict>
|
|
35
|
+
<key>Label</key><string>$LABEL</string>
|
|
36
|
+
<key>ProgramArguments</key><array><string>/bin/bash</string><string>$RUNNER</string></array>
|
|
37
|
+
<key>StartInterval</key><integer>1800</integer>
|
|
38
|
+
<key>RunAtLoad</key><false/>
|
|
39
|
+
<key>AbandonProcessGroup</key><true/>
|
|
40
|
+
<key>EnvironmentVariables</key><dict>
|
|
41
|
+
<key>ARGENT_DATA_DIR</key><string>$DATA_HOME</string>
|
|
42
|
+
<key>PATH</key><string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
|
|
43
|
+
</dict>
|
|
44
|
+
<key>StandardOutPath</key><string>$LOG_DIR/platform-scan.out.log</string>
|
|
45
|
+
<key>StandardErrorPath</key><string>$LOG_DIR/platform-scan.err.log</string>
|
|
46
|
+
<key>WorkingDirectory</key><string>$HOME</string>
|
|
47
|
+
</dict>
|
|
48
|
+
</plist>
|
|
49
|
+
PLIST
|
|
50
|
+
}
|
|
51
|
+
do_install() {
|
|
52
|
+
local allow=0
|
|
53
|
+
for a in "$@"; do case "$a" in --allow-non-production) allow=1;; --force) :;; *) echo "未知参数 $a" >&2; exit 2;; esac; done
|
|
54
|
+
if [ "$allow" = 0 ] && ! is_production; then echo "❌ 拒绝安装:本机不是生产机(需 config.json dailyReport.role=production 或 --allow-non-production)" >&2; exit 3; fi
|
|
55
|
+
mkdir -p "$AGENTS" "$LOG_DIR" "$DATA_HOME"
|
|
56
|
+
if [ -n "${SELLER_CENTER_BASE:-}" ]; then printf 'SELLER_CENTER_BASE=%s\n' "$SELLER_CENTER_BASE" > "$ENV_FILE"; chmod 600 "$ENV_FILE"; fi
|
|
57
|
+
gen > "$PLIST"; chmod 644 "$PLIST"
|
|
58
|
+
launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true
|
|
59
|
+
launchctl bootstrap "gui/$(id -u)" "$PLIST"
|
|
60
|
+
echo "✅ 已安装 $LABEL(每 30 分钟)"
|
|
61
|
+
}
|
|
62
|
+
do_uninstall() {
|
|
63
|
+
if [ -f "$PLIST" ]; then launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true; rm -f "$PLIST"; echo "✅ 已卸载 $LABEL"; fi
|
|
64
|
+
}
|
|
65
|
+
do_status() {
|
|
66
|
+
if launchctl list 2>/dev/null | grep -q "[[:space:]]$LABEL\$"; then echo "$LABEL: loaded"; else echo "$LABEL: missing"; fi
|
|
67
|
+
cat "$DATA_HOME/platform-scan-status.json" 2>/dev/null || true
|
|
68
|
+
}
|
|
69
|
+
cmd="${1:-}"; shift || true
|
|
70
|
+
case "$cmd" in
|
|
71
|
+
install) do_install "$@" ;;
|
|
72
|
+
uninstall) do_uninstall ;;
|
|
73
|
+
status) do_status ;;
|
|
74
|
+
run-now) bash "$RUNNER" ;;
|
|
75
|
+
print-plist) gen ;;
|
|
76
|
+
*) usage; exit 2 ;;
|
|
77
|
+
esac
|
package/engine/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = "0.14.
|
|
1
|
+
export const VERSION = "0.14.3"
|