@whyshu/argent-engine 0.8.0-rc.3 → 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.
- package/MANIFEST.json +20 -12
- package/engine/VERSION +1 -1
- package/engine/scripts/build-engine-package.mjs +1 -1
- package/engine/scripts/capability-packs.lock.json +12 -12
- package/engine/scripts/check-argent-desktop.mjs +91 -0
- package/engine/scripts/erp_invoice_shadow.py +62 -0
- package/engine/scripts/erp_invoice_writeback.py +93 -0
- package/engine/scripts/flow-requirements.json +3 -3
- package/engine/scripts/flow_source.py +10 -1
- package/engine/scripts/flow_sources/__init__.py +1 -0
- package/engine/scripts/flow_sources/erp.py +54 -0
- package/engine/scripts/invoice_lip_runner.py +43 -0
- package/engine/scripts/lib/plugin-packages.mjs +3 -0
- package/engine/scripts/orchestrator.py +173 -5
- package/engine/scripts/orchestrator_br.py +89 -1
- package/engine/scripts/query_runner.py +2 -3
- package/engine/scripts/release-gate-0.8.mjs +1 -0
- package/engine/scripts/skuflow_invoice_runner.py +145 -0
- package/engine/tools/agentic/README.md +95 -0
- package/engine/tools/agentic/mcp_server.py +212 -0
- package/engine/tools/agentic/ml_agent_tools.py +602 -0
- package/engine/version.mjs +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Argent Agentic ML Tools v1 —— 只读探针(M1)。
|
|
3
|
+
|
|
4
|
+
只通过 ziniao-cli page 操作当前店铺窗口;不直接点写操作。
|
|
5
|
+
MCP 包装层后续复用本模块函数。
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import shlex
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
import urllib.request
|
|
19
|
+
import urllib.error
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
DATA_DIR = Path(os.environ.get("ARGENT_DATA_DIR") or (Path.home() / ".dsh" / "argent"))
|
|
23
|
+
CDP_MAP = DATA_DIR / "cdp-port-map.json"
|
|
24
|
+
EVIDENCE_DIR = Path(os.environ.get("ARGENT_EVIDENCE_DIR") or (DATA_DIR / "evidence"))
|
|
25
|
+
DEFAULT_TIMEOUT = 60000
|
|
26
|
+
ML_BASE = "https://myaccount.mercadolibre.com.mx"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _run(cmd: list[str], timeout: int = DEFAULT_TIMEOUT) -> dict:
|
|
30
|
+
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
|
31
|
+
raw = (p.stdout or "").strip()
|
|
32
|
+
try:
|
|
33
|
+
data = json.loads(raw) if raw else {}
|
|
34
|
+
except json.JSONDecodeError:
|
|
35
|
+
data = {}
|
|
36
|
+
if p.returncode != 0:
|
|
37
|
+
return {"ok": False, "error": {"code": "ZINIAO_CLI_FAILED", "message": (p.stderr or raw or "cli failed")[:800]}, "raw": raw[:2000]}
|
|
38
|
+
if not data:
|
|
39
|
+
return {"ok": True, "raw": raw[:2000]}
|
|
40
|
+
return data
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def resolve_store(store: str = "", store_id: str = "", open_store: bool = False) -> tuple[str, str]:
|
|
44
|
+
"""返回 (store_id, store_name)。优先显式 id;否则从 cdp-port-map 按名称解析。"""
|
|
45
|
+
if store_id:
|
|
46
|
+
name = store
|
|
47
|
+
try:
|
|
48
|
+
d = json.loads(CDP_MAP.read_text()) if CDP_MAP.exists() else {}
|
|
49
|
+
for sid, v in d.items():
|
|
50
|
+
if sid == store_id:
|
|
51
|
+
name = v.get("store_name", name)
|
|
52
|
+
except Exception:
|
|
53
|
+
pass
|
|
54
|
+
return store_id, name
|
|
55
|
+
if not store:
|
|
56
|
+
raise SystemExit("需要 --store 或 --store-id")
|
|
57
|
+
try:
|
|
58
|
+
d = json.loads(CDP_MAP.read_text()) if CDP_MAP.exists() else {}
|
|
59
|
+
except Exception:
|
|
60
|
+
d = {}
|
|
61
|
+
for sid, v in d.items():
|
|
62
|
+
if v.get("store_name") == store:
|
|
63
|
+
return sid, store
|
|
64
|
+
# 兜底:ziniao-cli store list(cdp-port-map 可能只在生产数据目录)
|
|
65
|
+
out = _run(["ziniao-cli", "store", "list"], timeout=30000)
|
|
66
|
+
for it in (((out.get("data") or {}).get("items")) or []):
|
|
67
|
+
if it.get("storeName") == store and it.get("storeId"):
|
|
68
|
+
return str(it["storeId"]), store
|
|
69
|
+
if not open_store:
|
|
70
|
+
raise SystemExit(f"未找到店铺:{store}(可加 --open-store)")
|
|
71
|
+
out = _run(["ziniao-cli", "store", "open", "--name", store, "--expected-name", store], timeout=180000)
|
|
72
|
+
sid = str(((out.get("data") or {}).get("storeId")) or "")
|
|
73
|
+
if not sid:
|
|
74
|
+
raise SystemExit(f"打开店铺失败:{json.dumps(out, ensure_ascii=False)[:400]}")
|
|
75
|
+
return sid, store
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def page_visit(store_id: str, url: str) -> dict:
|
|
79
|
+
return _run(["ziniao-cli", "page", "visit", "--store-id", store_id, "--url", url,
|
|
80
|
+
"--wait-until", "domcontentloaded", "--timeout", str(DEFAULT_TIMEOUT)])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def page_exec_json(store_id: str, script: str) -> dict:
|
|
84
|
+
out = _run(["ziniao-cli", "page", "exec", "--store-id", store_id, "--script", script,
|
|
85
|
+
"--timeout", str(DEFAULT_TIMEOUT)])
|
|
86
|
+
if not out.get("ok"):
|
|
87
|
+
return out
|
|
88
|
+
data = ((out.get("data") or {}).get("data") or {})
|
|
89
|
+
result = data.get("result")
|
|
90
|
+
if isinstance(result, str):
|
|
91
|
+
try:
|
|
92
|
+
return {"ok": True, "value": json.loads(result), "targetId": data.get("targetId")}
|
|
93
|
+
except json.JSONDecodeError:
|
|
94
|
+
return {"ok": True, "value": result, "targetId": data.get("targetId")}
|
|
95
|
+
return {"ok": True, "value": result, "targetId": data.get("targetId")}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def screenshot(store_id: str, name: str) -> str:
|
|
99
|
+
day = dt.datetime.now().strftime("%Y%m%d")
|
|
100
|
+
outdir = EVIDENCE_DIR / day
|
|
101
|
+
outdir.mkdir(parents=True, exist_ok=True)
|
|
102
|
+
path = outdir / f"{name}-{dt.datetime.now().strftime('%H%M%S')}.png"
|
|
103
|
+
out = _run(["ziniao-cli", "page", "screenshot", "--store-id", store_id, "--timeout", str(DEFAULT_TIMEOUT)])
|
|
104
|
+
src = (((out.get("data") or {}).get("data") or {}).get("filePath")
|
|
105
|
+
or ((out.get("data") or {}).get("filePath")) or "")
|
|
106
|
+
if not (out.get("ok") and src and Path(src).exists()):
|
|
107
|
+
return ""
|
|
108
|
+
shutil.copy2(src, path)
|
|
109
|
+
return str(path)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _envelope(tool: str, data: dict, evidence: dict, started: float) -> dict:
|
|
113
|
+
return {
|
|
114
|
+
"ok": True,
|
|
115
|
+
"tool": tool,
|
|
116
|
+
"data": data,
|
|
117
|
+
"evidence": evidence,
|
|
118
|
+
"warnings": [],
|
|
119
|
+
"durationMs": int((time.time() - started) * 1000),
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
HUB_JS = r"""
|
|
124
|
+
(() => {
|
|
125
|
+
const text = (document.body.innerText || '').replace(/\s+/g, ' ').trim();
|
|
126
|
+
const has = (s) => text.includes(s);
|
|
127
|
+
const cards = Array.from(document.querySelectorAll('[data-testid], .andes-card, section, li'))
|
|
128
|
+
.map(e => ({tag: e.tagName, testid: e.getAttribute('data-testid') || '',
|
|
129
|
+
cls: String(e.className || '').slice(0, 120),
|
|
130
|
+
text: (e.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 160)}))
|
|
131
|
+
.filter(x => x.text && /envío|envio|etiqueta|bulto|preparaci|reserva|cita|autorizaci/i.test(x.text))
|
|
132
|
+
.slice(0, 30);
|
|
133
|
+
return JSON.stringify({
|
|
134
|
+
url: location.href,
|
|
135
|
+
title: document.title,
|
|
136
|
+
text: text.slice(0, 5000),
|
|
137
|
+
markers: {
|
|
138
|
+
prepare: has('Vas a enviar'),
|
|
139
|
+
appointmentCard: has('Elige cómo y cuándo vas a enviar'),
|
|
140
|
+
packagingDone: has('Revisaste la preparación'),
|
|
141
|
+
labelsDone: has('Descargaste las etiquetas'),
|
|
142
|
+
boxLabelsDone: has('Preparaste e identificaste'),
|
|
143
|
+
boxLabelsPending: has('Prepara bultos') || has('Debes completar las tareas anteriores'),
|
|
144
|
+
appointmentCancelled: /Reserva cancelada|reserva cancelada|cita cancelada/i.test(text),
|
|
145
|
+
platformError: /Algo salió mal|No pudimos mostrar/i.test(document.title + ' ' + text)
|
|
146
|
+
},
|
|
147
|
+
cards
|
|
148
|
+
});
|
|
149
|
+
})()
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def probe_hub(store: str, shipment_no: str, store_id: str = "", record_id: str = "",
|
|
154
|
+
open_store: bool = False) -> dict:
|
|
155
|
+
started = time.time()
|
|
156
|
+
sid, sname = resolve_store(store, store_id, open_store)
|
|
157
|
+
url = f"{ML_BASE}/shipping/inbounds/{shipment_no}/hub-v2"
|
|
158
|
+
nav = page_visit(sid, url)
|
|
159
|
+
if not nav.get("ok"):
|
|
160
|
+
return {"ok": False, "tool": "ml_probe_hub", "error": nav.get("error") or {"code": "NAV_FAILED"}}
|
|
161
|
+
time.sleep(2)
|
|
162
|
+
ev = page_exec_json(sid, HUB_JS)
|
|
163
|
+
if not ev.get("ok"):
|
|
164
|
+
return {"ok": False, "tool": "ml_probe_hub", "error": ev.get("error") or {"code": "EXEC_FAILED"}}
|
|
165
|
+
v = ev.get("value") or {}
|
|
166
|
+
m = v.get("markers") or {}
|
|
167
|
+
shot = screenshot(sid, f"hub-{shipment_no}")
|
|
168
|
+
if m.get("platformError"):
|
|
169
|
+
return {"ok": False, "tool": "ml_probe_hub",
|
|
170
|
+
"error": {"code": "PLATFORM_ERROR_PAGE", "message": "MercadoLibre 返回错误页", "retryable": True},
|
|
171
|
+
"evidence": {"screenshotPath": shot}, "durationMs": int((time.time() - started) * 1000)}
|
|
172
|
+
items = {
|
|
173
|
+
"prepare": bool(m.get("prepare")),
|
|
174
|
+
"appointment": bool(m.get("appointmentCard")),
|
|
175
|
+
"packaging": bool(m.get("packagingDone")),
|
|
176
|
+
"labels": bool(m.get("labelsDone")),
|
|
177
|
+
"boxLabels": bool(m.get("boxLabelsDone")),
|
|
178
|
+
}
|
|
179
|
+
complete = items["labels"] and items["boxLabels"] and (m.get("appointmentCancelled") or items["appointment"])
|
|
180
|
+
data = {
|
|
181
|
+
"shipmentNo": shipment_no,
|
|
182
|
+
"store": sname,
|
|
183
|
+
"storeId": sid,
|
|
184
|
+
"recordId": record_id,
|
|
185
|
+
"operationallyComplete": bool(complete),
|
|
186
|
+
"items": items,
|
|
187
|
+
"markers": m,
|
|
188
|
+
"page": {"url": v.get("url"), "title": v.get("title")},
|
|
189
|
+
"cards": v.get("cards") or [],
|
|
190
|
+
}
|
|
191
|
+
return _envelope("ml_probe_hub", data, {"screenshotPath": shot, "capturedAt": dt.datetime.now().isoformat(timespec="seconds")}, started)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
ENGINE_DIR = Path(os.environ.get("ARGENT_ENGINE_DIR") or (Path.home() / ".argent-dsh"))
|
|
195
|
+
ENGINE_PY = os.environ.get("ARGENT_ENGINE_PY") or str(Path.home() / ".dsh" / "argent" / "venv" / "bin" / "python")
|
|
196
|
+
FULFILLMENT_ENV = os.environ.get("ARGENT_FULFILLMENT_ENV") or str(Path.home() / ".dsh" / "argent" / "fulfillment.env")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _erp_machine_config() -> dict:
|
|
200
|
+
"""读取本机 machine token 配置;0.8 起完成态写 ERP,不再写 lip。"""
|
|
201
|
+
candidates = []
|
|
202
|
+
explicit = os.environ.get("ARGENT_AGENT_REPORT") or ""
|
|
203
|
+
if explicit:
|
|
204
|
+
candidates.append(Path(explicit))
|
|
205
|
+
candidates += [
|
|
206
|
+
DATA_DIR / "agent-report.json",
|
|
207
|
+
Path.home() / ".dsh" / "argent" / "agent-report.json",
|
|
208
|
+
Path.home() / ".dsh-argent" / "argent" / "agent-report.json",
|
|
209
|
+
]
|
|
210
|
+
for f in candidates:
|
|
211
|
+
try:
|
|
212
|
+
d = json.loads(f.read_text())
|
|
213
|
+
if d.get("serverUrl") and d.get("tenantAppId") and d.get("machineId") and d.get("machineToken"):
|
|
214
|
+
return d
|
|
215
|
+
except Exception:
|
|
216
|
+
continue
|
|
217
|
+
return {}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _erp_finalize_ticket(record_id: str, store: str, shipment_no: str, summary: str = "") -> dict:
|
|
221
|
+
cfg = _erp_machine_config()
|
|
222
|
+
if not cfg:
|
|
223
|
+
return {"ok": False, "error": {"code": "ERP_CONFIG_MISSING", "message": "找不到 agent-report.json(serverUrl/tenantAppId/machineId/machineToken)"}}
|
|
224
|
+
url = f"{str(cfg['serverUrl']).rstrip('/')}/api/argent/v1/tenants/{cfg['tenantAppId']}/machines/{cfg['machineId']}/agent-tasks/finalize"
|
|
225
|
+
body = json.dumps({
|
|
226
|
+
"sourceRecordId": record_id,
|
|
227
|
+
"shipmentNo": shipment_no,
|
|
228
|
+
"summary": summary or f"FULL 完成:{shipment_no}",
|
|
229
|
+
"output": {"store": store, "shipmentNo": shipment_no, "sourceRecordId": record_id},
|
|
230
|
+
}, ensure_ascii=False).encode("utf-8")
|
|
231
|
+
req = urllib.request.Request(url, data=body, method="POST", headers={
|
|
232
|
+
"content-type": "application/json",
|
|
233
|
+
"authorization": f"Bearer {cfg['machineToken']}",
|
|
234
|
+
})
|
|
235
|
+
try:
|
|
236
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
237
|
+
raw = resp.read().decode("utf-8", errors="replace")
|
|
238
|
+
data = json.loads(raw) if raw else {}
|
|
239
|
+
if not data.get("ok"):
|
|
240
|
+
return {"ok": False, "error": (data.get("error") or {"code": "ERP_FINALIZE_FAILED", "message": raw[:500]})}
|
|
241
|
+
return {"ok": True, "data": data.get("data") or {}}
|
|
242
|
+
except urllib.error.HTTPError as e:
|
|
243
|
+
raw = e.read().decode("utf-8", errors="replace")
|
|
244
|
+
try:
|
|
245
|
+
data = json.loads(raw)
|
|
246
|
+
except Exception:
|
|
247
|
+
data = {}
|
|
248
|
+
return {"ok": False, "error": (data.get("error") or {"code": "ERP_HTTP_ERROR", "message": raw[:500], "status": e.code})}
|
|
249
|
+
except Exception as e:
|
|
250
|
+
return {"ok": False, "error": {"code": "ERP_UNREACHABLE", "message": str(e)[:500]}}
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def finalize_ticket(record_id: str, store: str, approval_token: str = "", shipment_no: str = "") -> dict:
|
|
254
|
+
"""在 agent/MCP 完成步骤1-8 后,用 hub-v2 五项验证并写 ERP 完成态(0.8 去 lip)。"""
|
|
255
|
+
|
|
256
|
+
started = time.time()
|
|
257
|
+
expected = os.environ.get("ARGENT_WRITE_APPROVAL", "")
|
|
258
|
+
if not expected or approval_token != expected:
|
|
259
|
+
return {"ok": False, "tool": "ml_finalize_ticket", "error": {"code": "APPROVAL_REQUIRED", "message": "需要有效 approvalToken"}}
|
|
260
|
+
if not shipment_no:
|
|
261
|
+
return {"ok": False, "tool": "ml_finalize_ticket", "error": {"code": "MISSING_SHIPMENT", "message": "shipmentNo 必填"}}
|
|
262
|
+
hub = probe_hub(store, shipment_no, "", record_id, False)
|
|
263
|
+
items = (hub.get("data") or {}).get("items") or {}
|
|
264
|
+
if not hub.get("ok") or not items or not all(bool(items.get(k)) for k in ("prepare", "appointment", "packaging", "labels", "boxLabels")):
|
|
265
|
+
return {"ok": False, "tool": "ml_finalize_ticket", "error": {"code": "HUB_NOT_COMPLETE", "message": "hub-v2 五项未全部完成", "items": items}}
|
|
266
|
+
# 0.8 去 lip:只写 ERP AgentTask,不再 PUT lip 表。
|
|
267
|
+
erp = _erp_finalize_ticket(record_id, store, shipment_no)
|
|
268
|
+
if not erp.get("ok"):
|
|
269
|
+
return {"ok": False, "tool": "ml_finalize_ticket", "error": erp.get("error") or {"code": "ERP_FINALIZE_FAILED", "message": "ERP 完成态写入失败"}}
|
|
270
|
+
return {"ok": True, "tool": "ml_finalize_ticket", "data": {"recordId": record_id, "shipmentNo": shipment_no, "erp": erp.get("data"), "hubItems": items}, "durationMs": int((time.time() - started) * 1000)}
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def run_full_step(record_id: str, step: int, allow_write: bool = False, approval_token: str = "",
|
|
274
|
+
timeout_s: int = 600, shop: str = "", record: dict | None = None) -> dict:
|
|
275
|
+
"""受控调用现有 FULL 编排器单步(确定性工具;写步骤需审批 token)。
|
|
276
|
+
|
|
277
|
+
仅本地/受信环境使用;agent 不应直接拼 shell。
|
|
278
|
+
"""
|
|
279
|
+
started = time.time()
|
|
280
|
+
expected = os.environ.get("ARGENT_WRITE_APPROVAL", "")
|
|
281
|
+
if allow_write:
|
|
282
|
+
if not expected or approval_token != expected:
|
|
283
|
+
return {"ok": False, "tool": "ml_run_full_step",
|
|
284
|
+
"error": {"code": "APPROVAL_REQUIRED", "message": "写步骤需要有效 approvalToken", "needsDecision": True}}
|
|
285
|
+
if not ENGINE_DIR.exists() or not Path(ENGINE_PY).exists():
|
|
286
|
+
return {"ok": False, "tool": "ml_run_full_step",
|
|
287
|
+
"error": {"code": "ENGINE_NOT_AVAILABLE", "message": f"找不到引擎 {ENGINE_DIR} / {ENGINE_PY}"}}
|
|
288
|
+
step_num = int(step)
|
|
289
|
+
if step_num < 1 or step_num > 8:
|
|
290
|
+
return {"ok": False, "tool": "ml_run_full_step", "error": {"code": "INVALID_STEP", "message": "step 需为 1-8"}}
|
|
291
|
+
args = [f"--mode", "step", "--step", str(step_num), "--record-id", str(record_id)]
|
|
292
|
+
if record:
|
|
293
|
+
args += ["--record-json", shlex.quote(json.dumps(record, ensure_ascii=False)), "--no-lip"]
|
|
294
|
+
if allow_write:
|
|
295
|
+
args.append("--allow-write")
|
|
296
|
+
cmd = (
|
|
297
|
+
f'set -a; . "{FULFILLMENT_ENV}"; set +a; '
|
|
298
|
+
f'exec "{ENGINE_PY}" scripts/orchestrator.py ' + " ".join(args)
|
|
299
|
+
)
|
|
300
|
+
try:
|
|
301
|
+
p = subprocess.run(["bash", "-lc", cmd], cwd=str(ENGINE_DIR), capture_output=True, text=True, timeout=timeout_s)
|
|
302
|
+
except subprocess.TimeoutExpired:
|
|
303
|
+
return {"ok": False, "tool": "ml_run_full_step", "error": {"code": "TIMEOUT", "message": f"执行超过 {timeout_s}s", "retryable": True}}
|
|
304
|
+
out = (p.stdout or "").strip()
|
|
305
|
+
result = None
|
|
306
|
+
for line in reversed(out.splitlines()):
|
|
307
|
+
if line.startswith("{") and line.endswith("}"):
|
|
308
|
+
try:
|
|
309
|
+
result = json.loads(line)
|
|
310
|
+
break
|
|
311
|
+
except json.JSONDecodeError:
|
|
312
|
+
continue
|
|
313
|
+
if result is None:
|
|
314
|
+
result = {"status": "failed", "error": {"message": (p.stderr or out or "no json result")[-800:]}}
|
|
315
|
+
ok = str(result.get("status")) in ("success", "partial") and not result.get("failed_step")
|
|
316
|
+
evidence = {
|
|
317
|
+
"logTail": "\n".join(out.splitlines()[-30:])[-4000:],
|
|
318
|
+
"exitCode": p.returncode,
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
"ok": bool(ok), "tool": "ml_run_full_step",
|
|
322
|
+
"data": {"recordId": record_id, "step": step_num, "allowWrite": allow_write, "result": result},
|
|
323
|
+
"evidence": evidence,
|
|
324
|
+
"warnings": [],
|
|
325
|
+
"durationMs": int((time.time() - started) * 1000),
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
APPT_JS = r"""
|
|
330
|
+
(() => {
|
|
331
|
+
const text = (document.body.innerText || '').replace(/\s+/g, ' ').trim();
|
|
332
|
+
const opts = Array.from(document.querySelectorAll('[role="option"], li[role="option"], [class*=andes-list] li'))
|
|
333
|
+
.map(e => {
|
|
334
|
+
const cs = getComputedStyle(e);
|
|
335
|
+
const t = (e.innerText || '').replace(/\s+/g, ' ').trim();
|
|
336
|
+
return t ? {
|
|
337
|
+
text: t.slice(0, 120),
|
|
338
|
+
ariaDisabled: e.getAttribute('aria-disabled'),
|
|
339
|
+
disabled: e.hasAttribute('disabled'),
|
|
340
|
+
pointerEvents: cs.pointerEvents,
|
|
341
|
+
opacity: cs.opacity,
|
|
342
|
+
cls: String(e.className || '').slice(0, 120)
|
|
343
|
+
} : null;
|
|
344
|
+
}).filter(Boolean);
|
|
345
|
+
const options = opts.filter(o => /Vehículo|Colecta|proveedor|domicilio/i.test(o.text));
|
|
346
|
+
const days = Array.from(document.querySelectorAll('div.day'));
|
|
347
|
+
const hours = Array.from(document.querySelectorAll('div.hour'));
|
|
348
|
+
return JSON.stringify({
|
|
349
|
+
url: location.href,
|
|
350
|
+
title: document.title,
|
|
351
|
+
text: text.slice(0, 5000),
|
|
352
|
+
transportOptions: options,
|
|
353
|
+
calendar: {
|
|
354
|
+
visible: days.length > 0,
|
|
355
|
+
dayCount: days.length,
|
|
356
|
+
hourCount: hours.length,
|
|
357
|
+
enabledDayCount: days.filter(d => !/disabled/i.test(String(d.className || ''))).length
|
|
358
|
+
},
|
|
359
|
+
platformUnavailable: /Temporalmente no disponible/i.test(text),
|
|
360
|
+
noSlots: /No contamos con citas|no hay citas|sin citas disponibles|vuelve a intentarlo en los próximos días/i.test(text),
|
|
361
|
+
existingAppointment: /Cancelar reserva/i.test(text),
|
|
362
|
+
platformError: /Algo salió mal|No pudimos mostrar/i.test(document.title + ' ' + text),
|
|
363
|
+
allOptionCount: opts.length
|
|
364
|
+
});
|
|
365
|
+
})()
|
|
366
|
+
"""
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def probe_appointment(store: str, shipment_no: str, store_id: str = "", open_store: bool = False,
|
|
370
|
+
click_dropdown: bool = True, no_visit: bool = False) -> dict:
|
|
371
|
+
started = time.time()
|
|
372
|
+
sid, sname = resolve_store(store, store_id, open_store)
|
|
373
|
+
url = f"{ML_BASE}/shipping/inbounds/{shipment_no}/appointment-v2"
|
|
374
|
+
if not no_visit:
|
|
375
|
+
nav = page_visit(sid, url)
|
|
376
|
+
if not nav.get("ok"):
|
|
377
|
+
return {"ok": False, "tool": "ml_probe_appointment", "error": nav.get("error") or {"code": "NAV_FAILED"}}
|
|
378
|
+
time.sleep(3)
|
|
379
|
+
v = {}
|
|
380
|
+
# 页面数据异步加载:先重试只读抽取;不要在“已打开下拉”时误点关闭。
|
|
381
|
+
for _ in range(4):
|
|
382
|
+
ev = page_exec_json(sid, APPT_JS)
|
|
383
|
+
if not ev.get("ok"):
|
|
384
|
+
return {"ok": False, "tool": "ml_probe_appointment", "error": ev.get("error") or {"code": "EXEC_FAILED"}}
|
|
385
|
+
v = ev.get("value") or {}
|
|
386
|
+
if v.get("transportOptions"):
|
|
387
|
+
break
|
|
388
|
+
time.sleep(2)
|
|
389
|
+
if click_dropdown and not v.get("transportOptions"):
|
|
390
|
+
click_js = r"""
|
|
391
|
+
(() => {
|
|
392
|
+
const el = document.querySelector('#shipment-type-selection-dropdown-id-trigger, [id*=shipment-type-selection][id$=-trigger], [class*=dropdown__trigger]');
|
|
393
|
+
if (!el) return JSON.stringify({clicked:false});
|
|
394
|
+
el.click();
|
|
395
|
+
return JSON.stringify({clicked:true});
|
|
396
|
+
})()
|
|
397
|
+
"""
|
|
398
|
+
page_exec_json(sid, click_js)
|
|
399
|
+
time.sleep(2)
|
|
400
|
+
ev2 = page_exec_json(sid, APPT_JS)
|
|
401
|
+
if ev2.get("ok"):
|
|
402
|
+
v = ev2.get("value") or v
|
|
403
|
+
shot = screenshot(sid, f"appointment-{shipment_no}")
|
|
404
|
+
if v.get("platformError"):
|
|
405
|
+
return {"ok": False, "tool": "ml_probe_appointment",
|
|
406
|
+
"error": {"code": "PLATFORM_ERROR_PAGE", "message": "MercadoLibre 返回错误页", "retryable": True},
|
|
407
|
+
"evidence": {"screenshotPath": shot}, "durationMs": int((time.time() - started) * 1000)}
|
|
408
|
+
data = {
|
|
409
|
+
"shipmentNo": shipment_no,
|
|
410
|
+
"store": sname,
|
|
411
|
+
"storeId": sid,
|
|
412
|
+
"transportOptions": v.get("transportOptions") or [],
|
|
413
|
+
"calendar": v.get("calendar") or {},
|
|
414
|
+
"platformUnavailable": bool(v.get("platformUnavailable")),
|
|
415
|
+
"noSlots": bool(v.get("noSlots")),
|
|
416
|
+
"status": "no_appointment_slots" if v.get("noSlots") else ("existing_appointment" if v.get("existingAppointment") else "probed"),
|
|
417
|
+
"existingAppointment": bool(v.get("existingAppointment")),
|
|
418
|
+
"page": {"url": v.get("url"), "title": v.get("title")},
|
|
419
|
+
}
|
|
420
|
+
return _envelope("ml_probe_appointment", data, {"screenshotPath": shot, "capturedAt": dt.datetime.now().isoformat(timespec="seconds")}, started)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def open_appointment_slots(store: str, shipment_no: str, store_id: str = "", open_store: bool = False) -> dict:
|
|
424
|
+
"""只读打开预约页并展开运输方式/日期选择,返回可用日期与时段(不提交预约)。"""
|
|
425
|
+
started = time.time()
|
|
426
|
+
sid, sname = resolve_store(store, store_id, open_store)
|
|
427
|
+
url = f"{ML_BASE}/shipping/inbounds/{shipment_no}/appointment"
|
|
428
|
+
last_err = ""
|
|
429
|
+
for attempt in range(3):
|
|
430
|
+
nav = page_visit(sid, url)
|
|
431
|
+
if not nav.get("ok"):
|
|
432
|
+
last_err = str(nav.get("error") or "navigate failed")
|
|
433
|
+
time.sleep(20)
|
|
434
|
+
continue
|
|
435
|
+
time.sleep(5)
|
|
436
|
+
ev = page_exec_json(sid, APPT_JS)
|
|
437
|
+
if not ev.get("ok"):
|
|
438
|
+
last_err = str(ev.get("error") or "probe failed")
|
|
439
|
+
time.sleep(20)
|
|
440
|
+
continue
|
|
441
|
+
v = ev.get("value") or {}
|
|
442
|
+
if v.get("platformError") or "Algo salió mal" in str(v.get("title") or ""):
|
|
443
|
+
last_err = "platform_error"
|
|
444
|
+
time.sleep(45)
|
|
445
|
+
continue
|
|
446
|
+
break
|
|
447
|
+
else:
|
|
448
|
+
return {"ok": False, "tool": "ml_open_appointment_slots", "error": {"code": "PLATFORM_ERROR", "message": last_err or "预约页暂不可用", "retryable": True}}
|
|
449
|
+
# 展开运输方式
|
|
450
|
+
page_exec_json(sid, "(() => { const el=document.querySelector('#shipment-type-selection-dropdown-id-trigger'); if(el) el.click(); return JSON.stringify({clicked:Boolean(el)}); })()")
|
|
451
|
+
time.sleep(2)
|
|
452
|
+
opts = page_exec_json(sid, "JSON.stringify(Array.from(document.querySelectorAll('[role=option], .andes-list__item')).map(e=>({text:(e.innerText||'').replace(/\\s+/g,' ').trim(), aria:e.getAttribute('aria-disabled')})).filter(x=>x.text))")
|
|
453
|
+
options = []
|
|
454
|
+
if opts.get("ok") and isinstance(opts.get("value"), list):
|
|
455
|
+
options = opts["value"]
|
|
456
|
+
chosen = next((o for o in options if "Vehículo particular" in str(o.get("text")) and str(o.get("aria")) != "true"), None)
|
|
457
|
+
if chosen:
|
|
458
|
+
page_exec_json(sid, "(() => { const opts=Array.from(document.querySelectorAll('[role=option], .andes-list__item')); const el=opts.find(e=>/Vehículo particular/i.test(e.innerText||'')); if(!el) return JSON.stringify({clicked:false}); el.click(); return JSON.stringify({clicked:true}); })()")
|
|
459
|
+
time.sleep(3)
|
|
460
|
+
# 点开日期输入框
|
|
461
|
+
page_exec_json(sid, "(() => { const el=document.querySelector('input[id^=\"_r_\"]'); if(!el) return JSON.stringify({clicked:false}); el.click(); return JSON.stringify({clicked:true,id:el.id}); })()")
|
|
462
|
+
time.sleep(2)
|
|
463
|
+
cal = page_exec_json(sid, "(() => { const days=Array.from(document.querySelectorAll('div.day')).map(d=>({text:(d.innerText||'').trim(),cls:String(d.className||'')})); const hours=Array.from(document.querySelectorAll('div.hour')).map(h=>({text:(h.innerText||'').trim(),cls:String(h.className||'')})); return JSON.stringify({days, hours}); })()")
|
|
464
|
+
days = (cal.get("value") or {}).get("days") if cal.get("ok") else []
|
|
465
|
+
hours = (cal.get("value") or {}).get("hours") if cal.get("ok") else []
|
|
466
|
+
available_days = [d for d in (days or []) if "disabled" not in str(d.get("cls"))]
|
|
467
|
+
available_hours = [h for h in (hours or []) if "disabled" not in str(h.get("cls"))]
|
|
468
|
+
return _envelope("ml_open_appointment_slots", {
|
|
469
|
+
"shipmentNo": shipment_no, "store": sname, "storeId": sid,
|
|
470
|
+
"transportOptions": options, "selectedTransport": chosen.get("text") if chosen else "",
|
|
471
|
+
"availableDays": available_days, "availableHours": available_hours,
|
|
472
|
+
"dayCount": len(available_days), "hourCount": len(available_hours),
|
|
473
|
+
}, {"screenshotPath": screenshot(sid, f"slots-{shipment_no}"), "capturedAt": dt.datetime.now().isoformat(timespec="seconds")}, started)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def watch_appointment(store: str, shipment_no: str, store_id: str = "", open_store: bool = False,
|
|
477
|
+
interval_sec: int = 60, max_seconds: int = 300, no_visit: bool = False) -> dict:
|
|
478
|
+
"""停留预约页低频刷新,等待放号;只读,不提交预约。
|
|
479
|
+
|
|
480
|
+
返回:{ok, data:{shipmentNo,store,status,observations,...}, evidence}
|
|
481
|
+
status: no_slots / slots_available / existing_appointment / platform_error / timeout
|
|
482
|
+
"""
|
|
483
|
+
started = time.time()
|
|
484
|
+
sid, sname = resolve_store(store, store_id, open_store)
|
|
485
|
+
url = f"{ML_BASE}/shipping/inbounds/{shipment_no}/appointment-v2"
|
|
486
|
+
if not no_visit:
|
|
487
|
+
nav = page_visit(sid, url)
|
|
488
|
+
if not nav.get("ok"):
|
|
489
|
+
return {"ok": False, "tool": "ml_watch_appointment", "error": nav.get("error") or {"code": "NAV_FAILED"}}
|
|
490
|
+
time.sleep(3)
|
|
491
|
+
interval = max(15, min(900, int(interval_sec or 60)))
|
|
492
|
+
deadline = started + max(30, min(7200, int(max_seconds or 300)))
|
|
493
|
+
observations = []
|
|
494
|
+
last_status = ""
|
|
495
|
+
shot = ""
|
|
496
|
+
while time.time() < deadline:
|
|
497
|
+
ev = page_exec_json(sid, APPT_JS)
|
|
498
|
+
if ev.get("ok"):
|
|
499
|
+
v = ev.get("value") or {}
|
|
500
|
+
if v.get("platformError"):
|
|
501
|
+
status = "platform_error"
|
|
502
|
+
elif v.get("noSlots"):
|
|
503
|
+
status = "no_slots"
|
|
504
|
+
elif v.get("existingAppointment"):
|
|
505
|
+
status = "existing_appointment"
|
|
506
|
+
elif v.get("transportOptions"):
|
|
507
|
+
status = "slots_available"
|
|
508
|
+
else:
|
|
509
|
+
status = "unknown"
|
|
510
|
+
now = dt.datetime.now().isoformat(timespec="seconds")
|
|
511
|
+
observations.append({"at": now, "status": status, "page": {"url": v.get("url"), "title": v.get("title")},
|
|
512
|
+
"transportOptions": len(v.get("transportOptions") or []), "days": (v.get("calendar") or {}).get("dayCount", 0)})
|
|
513
|
+
if status != last_status:
|
|
514
|
+
shot = screenshot(sid, f"watch-{shipment_no}-{status}")
|
|
515
|
+
last_status = status
|
|
516
|
+
if status in ("slots_available", "existing_appointment"):
|
|
517
|
+
return _envelope("ml_watch_appointment", {
|
|
518
|
+
"shipmentNo": shipment_no, "store": sname, "storeId": sid,
|
|
519
|
+
"status": status, "observations": observations, "page": {"url": v.get("url"), "title": v.get("title")},
|
|
520
|
+
"transportOptions": v.get("transportOptions") or [], "calendar": v.get("calendar") or {},
|
|
521
|
+
}, {"screenshotPath": shot, "capturedAt": now}, started)
|
|
522
|
+
else:
|
|
523
|
+
observations.append({"at": dt.datetime.now().isoformat(timespec="seconds"), "status": "probe_error",
|
|
524
|
+
"error": str((ev.get("error") or {}).get("message") or ev.get("error"))[:200]})
|
|
525
|
+
status = "probe_error"
|
|
526
|
+
# 同标签页刷新,不重开窗口
|
|
527
|
+
try:
|
|
528
|
+
page_exec_json(sid, "(() => { location.reload(); return JSON.stringify({reloaded:true}); })()")
|
|
529
|
+
except Exception:
|
|
530
|
+
pass
|
|
531
|
+
time.sleep(interval)
|
|
532
|
+
return _envelope("ml_watch_appointment", {
|
|
533
|
+
"shipmentNo": shipment_no, "store": sname, "storeId": sid,
|
|
534
|
+
"status": "timeout", "observations": observations,
|
|
535
|
+
}, {"screenshotPath": shot, "capturedAt": dt.datetime.now().isoformat(timespec="seconds")}, started)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def main(argv=None) -> int:
|
|
539
|
+
ap = argparse.ArgumentParser(description="Argent Agentic ML tools (M1 read-only)")
|
|
540
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
541
|
+
for name in ("probe-hub", "probe-appointment"):
|
|
542
|
+
p = sub.add_parser(name)
|
|
543
|
+
p.add_argument("--shipment", required=True)
|
|
544
|
+
p.add_argument("--store", default="")
|
|
545
|
+
p.add_argument("--store-id", default="")
|
|
546
|
+
p.add_argument("--record-id", default="")
|
|
547
|
+
p.add_argument("--open-store", action="store_true")
|
|
548
|
+
p.add_argument("--current-page", action="store_true", help="不导航,直接读取当前页面")
|
|
549
|
+
p.add_argument("--json", action="store_true")
|
|
550
|
+
p = sub.add_parser("open-appointment-slots")
|
|
551
|
+
p.add_argument("--shipment", required=True)
|
|
552
|
+
p.add_argument("--store", default="")
|
|
553
|
+
p.add_argument("--store-id", default="")
|
|
554
|
+
p.add_argument("--open-store", action="store_true")
|
|
555
|
+
p.add_argument("--json", action="store_true")
|
|
556
|
+
p = sub.add_parser("watch-appointment")
|
|
557
|
+
p.add_argument("--shipment", required=True)
|
|
558
|
+
p.add_argument("--store", default="")
|
|
559
|
+
p.add_argument("--store-id", default="")
|
|
560
|
+
p.add_argument("--open-store", action="store_true")
|
|
561
|
+
p.add_argument("--current-page", action="store_true")
|
|
562
|
+
p.add_argument("--interval-sec", type=int, default=60)
|
|
563
|
+
p.add_argument("--max-seconds", type=int, default=300)
|
|
564
|
+
p.add_argument("--json", action="store_true")
|
|
565
|
+
p = sub.add_parser("finalize-ticket")
|
|
566
|
+
p.add_argument("--record-id", required=True)
|
|
567
|
+
p.add_argument("--shipment", required=True)
|
|
568
|
+
p.add_argument("--store", required=True)
|
|
569
|
+
p.add_argument("--approval-token", required=True)
|
|
570
|
+
p.add_argument("--json", action="store_true")
|
|
571
|
+
p = sub.add_parser("run-full-step")
|
|
572
|
+
p.add_argument("--record-json", default="", help="ERP-only 合成记录 JSON;与 --record-id 一起用")
|
|
573
|
+
p.add_argument("--record-id", required=True)
|
|
574
|
+
p.add_argument("--step", type=int, required=True)
|
|
575
|
+
p.add_argument("--allow-write", action="store_true")
|
|
576
|
+
p.add_argument("--approval-token", default="")
|
|
577
|
+
p.add_argument("--timeout-s", type=int, default=600)
|
|
578
|
+
p.add_argument("--json", action="store_true")
|
|
579
|
+
ap.add_argument("--evidence-dir")
|
|
580
|
+
a = ap.parse_args(argv)
|
|
581
|
+
if a.evidence_dir:
|
|
582
|
+
global EVIDENCE_DIR
|
|
583
|
+
EVIDENCE_DIR = Path(a.evidence_dir)
|
|
584
|
+
if a.cmd == "probe-hub":
|
|
585
|
+
out = probe_hub(a.store, a.shipment, a.store_id, a.record_id, a.open_store)
|
|
586
|
+
elif a.cmd == "open-appointment-slots":
|
|
587
|
+
out = open_appointment_slots(a.store, a.shipment, a.store_id, a.open_store)
|
|
588
|
+
elif a.cmd == "watch-appointment":
|
|
589
|
+
out = watch_appointment(a.store, a.shipment, a.store_id, a.open_store, a.interval_sec, a.max_seconds, no_visit=a.current_page)
|
|
590
|
+
elif a.cmd == "finalize-ticket":
|
|
591
|
+
out = finalize_ticket(a.record_id, a.store, a.approval_token, a.shipment)
|
|
592
|
+
elif a.cmd == "run-full-step":
|
|
593
|
+
_record = json.loads(a.record_json) if getattr(a, "record_json", "") else None
|
|
594
|
+
out = run_full_step(a.record_id, a.step, a.allow_write, a.approval_token, a.timeout_s, record=_record)
|
|
595
|
+
else:
|
|
596
|
+
out = probe_appointment(a.store, a.shipment, a.store_id, a.open_store, no_visit=a.current_page)
|
|
597
|
+
print(json.dumps(out, ensure_ascii=False, indent=1 if a.json else None))
|
|
598
|
+
return 0 if out.get("ok") else 1
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
if __name__ == "__main__":
|
|
602
|
+
sys.exit(main())
|
package/engine/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = "0.8.0-rc.
|
|
1
|
+
export const VERSION = "0.8.0-rc.4"
|