@whyshu/argent-engine 0.8.0-rc.3 → 0.8.0-rc.5

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 (39) hide show
  1. package/MANIFEST.json +36 -20
  2. package/engine/VERSION +1 -1
  3. package/engine/core/contracts/argent.contracts.json +1 -1
  4. package/engine/scripts/argent-doctor.mjs +34 -1
  5. package/engine/scripts/argent-schedule.mjs +6 -0
  6. package/engine/scripts/build-engine-package.mjs +1 -1
  7. package/engine/scripts/capability-packs.lock.json +36 -36
  8. package/engine/scripts/check-argent-desktop.mjs +91 -0
  9. package/engine/scripts/daily-report-run.sh +68 -0
  10. package/engine/scripts/daily-report-status.mjs +130 -0
  11. package/engine/scripts/daily-report-timer-plist.sh +89 -0
  12. package/engine/scripts/daily-report-timers.sh +162 -0
  13. package/engine/scripts/daily-report.mjs +79 -4
  14. package/engine/scripts/erp_invoice_shadow.py +62 -0
  15. package/engine/scripts/erp_invoice_writeback.py +93 -0
  16. package/engine/scripts/flow-requirements.json +3 -3
  17. package/engine/scripts/flow-timers.sh +11 -0
  18. package/engine/scripts/flow_config.py +14 -0
  19. package/engine/scripts/flow_source.py +10 -1
  20. package/engine/scripts/flow_sources/__init__.py +1 -0
  21. package/engine/scripts/flow_sources/erp.py +54 -0
  22. package/engine/scripts/huangwei-preflight.sh +42 -0
  23. package/engine/scripts/invoice_lip_runner.py +43 -0
  24. package/engine/scripts/lib/daily-report-status.mjs +227 -0
  25. package/engine/scripts/lib/plugin-packages.mjs +3 -0
  26. package/engine/scripts/orchestrator.py +173 -5
  27. package/engine/scripts/orchestrator_br.py +89 -1
  28. package/engine/scripts/publish-release-0.8.0-rc.4.sh +18 -0
  29. package/engine/scripts/query_runner.py +2 -3
  30. package/engine/scripts/release-gate-0.8.mjs +1 -0
  31. package/engine/scripts/skuflow_invoice_runner.py +145 -0
  32. package/engine/scripts/verify-release-0.8.0-rc.4.sh +16 -0
  33. package/engine/scripts/vertical-lint.mjs +19 -0
  34. package/engine/tools/agentic/README.md +95 -0
  35. package/engine/tools/agentic/mcp_server.py +212 -0
  36. package/engine/tools/agentic/ml_agent_tools.py +602 -0
  37. package/engine/version.mjs +1 -1
  38. package/engine/verticals/mercadolibre/flows.json +3 -1
  39. package/package.json +1 -1
@@ -31,6 +31,7 @@ const TESTS = [
31
31
  'scripts/tests/argent-datadir.test.mjs',
32
32
  'scripts/tests/datadir-literal-gate.test.mjs',
33
33
  'scripts/tests/datadir-writes-gate.test.mjs',
34
+ 'scripts/tests/agentic-no-lip.test.mjs',
34
35
  'scripts/tests/core-mcp-shared.test.mjs',
35
36
  'scripts/tests/mcp-tool-annotations.test.mjs',
36
37
  'scripts/tests/mcp-collapse.test.mjs',
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env python3
2
+ """SkuFlow bulkLabel 发票适配器(鑫中航;复用既有 invoice_runner/invoice_stageb)。
3
+
4
+ 输入:--record-json '<json>'(SkuFlow task.context)
5
+ 输出:stdout 最后一行 JSON {ok, invoicePath, bulkLabelPath, orderNo} 或 {ok:false,error}
6
+ 注意:默认会调用既有鑫中航上传/下载流程;离线只生成用 --generate-only。
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ HERE = Path(__file__).resolve().parent
15
+ sys.path.insert(0, str(HERE))
16
+ DATA = Path(os.environ.get('ARGENT_DATA_DIR') or (Path.home() / '.dsh' / 'argent'))
17
+
18
+ from invoice_runner import load_mapping, generate_invoice # noqa: E402
19
+
20
+
21
+ def build_record(ctx: dict) -> dict:
22
+ return {
23
+ '货件号': str(ctx.get('shipmentNo') or ''),
24
+ '店铺名称': str(ctx.get('store') or ''),
25
+ '品名': str(ctx.get('productName') or ctx.get('sku') or ''),
26
+ '数量': int(ctx.get('quantity') or 0),
27
+ '箱数': int(ctx.get('boxCount') or 0),
28
+ '国内收货仓库': '深圳仓',
29
+ '备注': str(ctx.get('content') or 'SkuFlow'),
30
+ '到达时间': str(ctx.get('shipDate') or ''),
31
+ 'sku_data': {
32
+ '品名英文': str(ctx.get('nameEn') or ctx.get('productName') or ctx.get('sku') or ''),
33
+ '海关编码': str(ctx.get('hsCode') or ''),
34
+ '材质英文': str(ctx.get('materialEn') or ''),
35
+ '材质中文': str(ctx.get('material') or ''),
36
+ '重量(kg/箱)': ctx.get('weight') or '',
37
+ '长(cm)': ctx.get('length') or '',
38
+ '宽(cm)': ctx.get('width') or '',
39
+ '高(cm)': ctx.get('height') or '',
40
+ },
41
+ }
42
+
43
+
44
+ def build_wenyao_fixture(ctx: dict, rec: dict) -> dict:
45
+ boxes = max(1, int(rec['箱数'] or 1))
46
+ return {
47
+ '产品名称': rec['品名'], '货件号': rec['货件号'], 'SKU': str(ctx.get('sku') or ''),
48
+ '店铺': str(ctx.get('store') or ''), '数量': int(rec['数量'] or 0), '箱数': boxes,
49
+ '装箱数': max(1, int(rec['数量'] or 0) // boxes),
50
+ '重量': float(ctx.get('weight') or 0), '长': float(ctx.get('length') or 0),
51
+ '宽': float(ctx.get('width') or 0), '高': float(ctx.get('height') or 0),
52
+ '材质': str(ctx.get('material') or ''), 'HS编码': str(ctx.get('hsCode') or ''),
53
+ '产品图': '',
54
+ }
55
+
56
+
57
+ def run_wenyao(ctx: dict, rec: dict, generate_only: bool) -> dict:
58
+ """文鳐:SkuFlow fixture → p3/p4 → 门户 p6-p14;门户回写由本适配器接管,不写 lip。"""
59
+ import wenyao_run as wr
60
+ shipment = rec['货件号']
61
+ fixture = build_wenyao_fixture(ctx, rec)
62
+ wr.FIX_DIR.mkdir(parents=True, exist_ok=True)
63
+ fx = wr.FIX_DIR / f'skuflow-{ctx.get("skuFlowId","")}-{shipment}.json'
64
+ fx.write_text(json.dumps(fixture, ensure_ascii=False))
65
+ template = wr.DOWN_DIR / '跨境电商-下单模板.xlsx'
66
+ if not template.exists():
67
+ raise RuntimeError(f'文鳐模板不存在: {template}')
68
+ r3 = wr.p3_fill(str(fx), str(ctx.get('nameEn') or rec['品名']), '', None,
69
+ material_en=str(ctx.get('materialEn') or ''), write_dict=False)
70
+ wr.p4_verify(r3['xlsx'], str(template))
71
+ out = {'ok': True, 'invoicePath': r3['xlsx'], 'bulkLabelPath': '', 'orderNo': shipment}
72
+ if generate_only:
73
+ return out
74
+ import wenyao_portal as wp
75
+ orig = wr._writeback
76
+ wr._writeback = lambda *a, **k: None # 门户 P13/P14 的 lip 回写由 SkuFlow/ERP 接管
77
+ try:
78
+ class A: pass
79
+ a = A(); a.shipment = shipment; a.english_name = str(ctx.get('nameEn') or rec['品名'])
80
+ r1 = {'record_id': ''}
81
+ r2 = {'fixture': fixture}
82
+ with wp.portal_lock(site=f'portal.{shipment}', timeout=wp.portal_lock_timeout(),
83
+ reporter=lambda m: None) as waited:
84
+ final = wr.p6_p14_portal(a, r1, r2, r3, 1, wp, waited)
85
+ if not final:
86
+ raise RuntimeError('文鳐大货标签未生成')
87
+ out['bulkLabelPath'] = str(final)
88
+ finally:
89
+ wr._writeback = orig
90
+ return out
91
+
92
+
93
+ def main() -> int:
94
+ ap = argparse.ArgumentParser()
95
+ ap.add_argument('--record-json', required=True)
96
+ ap.add_argument('--generate-only', action='store_true')
97
+ ap.add_argument('--template', default='')
98
+ a = ap.parse_args()
99
+ out = {}
100
+ try:
101
+ ctx = json.loads(a.record_json)
102
+ rec = build_record(ctx)
103
+ missing = [k for k in ('货件号', '店铺名称', '数量', '箱数') if not rec.get(k)]
104
+ if missing:
105
+ raise RuntimeError(f"缺字段: {', '.join(missing)}")
106
+ sku = rec['sku_data']
107
+ miss2 = [k for k in ('海关编码', '材质中文', '重量(kg/箱)', '长(cm)', '宽(cm)', '高(cm)') if not sku.get(k)]
108
+ if miss2:
109
+ raise RuntimeError(f"SKU 发票主数据缺: {', '.join(miss2)}")
110
+ forwarder = str(ctx.get('forwarder') or '')
111
+ if '文鳐' in forwarder:
112
+ out = run_wenyao(ctx, rec, a.generate_only)
113
+ print(json.dumps(out, ensure_ascii=False))
114
+ return 0 if out.get('ok') else 1
115
+ if '鑫中航' not in forwarder:
116
+ raise RuntimeError(f"未知货代: {forwarder or '(空)'}")
117
+ mapping = load_mapping()
118
+ tpl = Path(a.template) if a.template else (DATA / 'invoice-templates' / 'xzh-template.xlsx')
119
+ if not tpl.exists():
120
+ tpl = Path(str(mapping.get('templates', {}).get('鑫中航') or ''))
121
+ if not tpl.exists():
122
+ raise RuntimeError(f"模板不存在: {tpl}")
123
+ import openpyxl
124
+ wb = openpyxl.load_workbook(tpl)
125
+ out_dir = DATA / 'invoice-output'
126
+ out_dir.mkdir(parents=True, exist_ok=True)
127
+ invoice = out_dir / f"skuflow-{ctx.get('skuFlowId','')}-{rec['货件号']}.xlsx"
128
+ generate_invoice(rec, mapping, wb, invoice)
129
+ out = {'ok': True, 'invoicePath': str(invoice), 'bulkLabelPath': '', 'orderNo': rec['货件号']}
130
+ if not a.generate_only:
131
+ from invoice_stageb import upload_invoice, download_label
132
+ if not upload_invoice(str(invoice), order_no=rec['货件号']):
133
+ raise RuntimeError('鑫中航上传失败')
134
+ label = download_label(rec['货件号'])
135
+ if not label:
136
+ raise RuntimeError('大货标签下载失败')
137
+ out['bulkLabelPath'] = str(label)
138
+ except Exception as e:
139
+ out = {'ok': False, 'error': str(e)[:500]}
140
+ print(json.dumps(out, ensure_ascii=False))
141
+ return 0 if out.get('ok') else 1
142
+
143
+
144
+ if __name__ == '__main__':
145
+ raise SystemExit(main())
@@ -0,0 +1,16 @@
1
+ #!/bin/bash
2
+ # 发布后回验(只读 npm/本地包;不发布)
3
+ set -euo pipefail
4
+ DIR="${1:-/tmp/argent-release-0.8.0-rc.4}"
5
+ echo "== npm versions =="
6
+ for p in @whyshu/argent-engine @whyshu/argent-desktop @whyshu/argent; do
7
+ printf '%s: ' "$p"; npm view "$p" version
8
+ done
9
+ echo
10
+ echo "== expected =="
11
+ echo "@whyshu/argent-engine 0.8.0-rc.4"
12
+ echo "@whyshu/argent-desktop 0.2.2"
13
+ echo "@whyshu/argent 0.1.17"
14
+ echo
15
+ echo "== tarballs =="
16
+ ls -lh "$DIR"/*.tgz
@@ -228,6 +228,25 @@ for (const vid of VIDS) {
228
228
  if (String(flow.trigger?.mode) === 'real' && !(flow.guards?.writeFields || []).length) {
229
229
  warn('guards', `${id}: mode=real 但没有声明 guards.writeFields(写路径白名单)—— 确认这是有意的`)
230
230
  }
231
+ // ── 1.35 交付方式声明(2026-10-30)──────────────────────────────────────
232
+ // `trigger.delivery`:这条流程的定时**谁在跑**
233
+ // · `session`(缺省)= 激活垫片唤醒角色会话(flow-trigger.sh → dsh 宿主);
234
+ // · `launchd-script` = launchd 直跑确定性脚本(日报:`scripts/daily-report-timers.sh`),
235
+ // ⛔ 不进 flow-timers 的安装面、⛔ 不许同时启用宿主排程(单一调度者)。
236
+ // 判据与安装器(`scripts/flow-timers.sh` / `scripts/daily-report-timers.sh`)同源:两边都读这个键。
237
+ const delivery = flow.trigger?.delivery
238
+ if (delivery !== undefined) {
239
+ const atD = `${id}: trigger.delivery`
240
+ if (!['session', 'launchd-script'].includes(String(delivery))) {
241
+ err('delivery', `${atD}=${JSON.stringify(delivery)} 不在 session|launchd-script 内`)
242
+ }
243
+ if (String(delivery) === 'launchd-script' && flow.trigger?.schedule?.enabled === true) {
244
+ err('delivery', `${atD}=launchd-script 时 trigger.schedule.enabled 必须为 false —— 同一条流程只能有一个调度者(launchd 确定性脚本 vs 宿主排程)`)
245
+ }
246
+ if (String(delivery) === 'launchd-script' && String(flow.trigger?.wake) !== 'session') {
247
+ warn('delivery', `${atD}=launchd-script 但 trigger.wake=${JSON.stringify(flow.trigger?.wake)} —— 脚本交付不需要唤醒,建议保持 session 以外的值时才改`)
248
+ }
249
+ }
231
250
  // ── 1.4 宿主排程声明(P1-A,2026-10-12)──────────────────────────────────
232
251
  // 判据与运行期读取点(`scripts/flow_config.py` 的 schedule 段)**同一套**:这里是资产门禁,
233
252
  // 那里是唯一读取点 —— 两处各判一次不是"第二份真源",而是"声明期拦住 + 运行期不静默"。
@@ -0,0 +1,95 @@
1
+ # Argent Agentic ML Tools(M1)
2
+
3
+ 只读探针,供本地 shadow 与后续 MCP server 复用。
4
+
5
+ ## 用法
6
+
7
+ ```bash
8
+ export ARGENT_DATA_DIR="$HOME/.dsh/argent" # 店铺映射/store list 兜底
9
+ export ARGENT_EVIDENCE_DIR="$HOME/.dsh/argent-local/evidence"
10
+
11
+ python3 tools/agentic/ml_agent_tools.py probe-hub \
12
+ --shipment 80555414 --store "墨西哥-2店-子账号" --json
13
+
14
+ python3 tools/agentic/ml_agent_tools.py probe-appointment \
15
+ --shipment 80555414 --store "墨西哥-2店-子账号" --json
16
+ ```
17
+
18
+ - 也可传 `--store-id 27494792824433`;
19
+ - 店铺窗口需已打开(本机可用 `ziniao-cli store open --name ...`);
20
+ - 只调用 `ziniao-cli page visit/exec/screenshot`,不点写按钮、不提交预约。
21
+
22
+ ## 输出
23
+
24
+ 符合 `docs/agentic-tools-contract-v1.md` 的信封;证据截图落
25
+ `$ARGENT_EVIDENCE_DIR/<日期>/`。
26
+
27
+ - `probe-hub`:五项 checklist + `operationallyComplete` + 卡片证据;
28
+ - `probe-appointment`:运输方式选项、日历可见性、平台错误页/已有预约标记。
29
+
30
+ ## M1 状态
31
+
32
+ - [x] probe-hub 本地真实店铺只读跑通:80555414 `operationallyComplete=true`;74009400 `false`(仅 appointment 未完成,labels/boxLabels 已完成);
33
+ - [x] probe-appointment 页面/选项/错误页抽取实现;74009400 正确识别 `existingAppointment=true`(已有预约时不展示运输方式下拉);
34
+ - [x] MCP stdio server(`mcp_server.py`,tools/list + tools/call 已用 80555414 实测);本地 3081 profile 已挂载(`mcp-argent-ml`);
35
+ - [ ] ERP AgentTask 派发/信号联调。
36
+
37
+ ## M1 端到端 shadow(2026-10-27 15:10)
38
+
39
+ 本地 dsh 3081 + task-board + MCP 已跑通**真实 agent 会话**:
40
+
41
+ - 任务 prompt:让 agent 调 `mcp__argent_ml__ml_probe_hub` 探测 80555414;
42
+ - 结果:agent 正确调用 MCP 工具,返回 `operationallyComplete=true`、五项全绿,
43
+ 并引用证据截图 `/Users/chester/.dsh/argent-local/evidence/20261027/hub-80555414-151020.png`;
44
+ - session:`session-50610720-0477-43d9-9e61-6ffb7934a1c1`;
45
+ - 前置修复:隔离 DSH_HOME 需要 `DEEPSEEK_API_KEY`(从本机 credentials 注入启动环境,未写入仓库)。
46
+
47
+ ## M2 ERP AgentTask 闭环(2026-10-27)
48
+
49
+ 本地 ERP `ly-agentic-local` 创建 AgentTask → `scripts/agentic-local-bridge.mjs`(ERP 侧)
50
+ → 本地 dsh task-board → agent 调 MCP `ml_probe_hub` → AgentTask `completed`。
51
+ 实测 session `session-b438c456-87f2-4d7d-b584-d9f88d09fd19`,agent 实际完成 MCP 调用。
52
+
53
+ ## 实战 canary(2026-10-27 15:28)
54
+
55
+ - 使用 lip 新 SKU 记录 `reczz28SLNgEOAjV`(HW-MX-YU-080,160 件/10 箱,墨西哥-2店-子账号);
56
+ - 步骤 1-3 成功,创建货件 **80664493**;
57
+ - 步骤 4 受阻:预约页实际返回「No contamos con citas en este momento…」,即**平台暂无可预约日期**,
58
+ 不是脚本缺陷;旧脚本将其误报为「页面形态异常」;
59
+ - 已给 `ml_probe_appointment` 增加 `noSlots` 识别与 `--current-page` 只读模式(页面限流时可直接读当前页);
60
+ - 该货件尚未预约,因此无需取消;等待平台放号后继续。
61
+
62
+ ## 受控写工具(M2)
63
+
64
+ `ml_run_full_step`:通过现有 FULL 编排器执行单步(确定性工具)。
65
+
66
+ ```bash
67
+ # 只读步骤(1/2/6)可直接跑
68
+ python3 tools/agentic/ml_agent_tools.py run-full-step --record-id reczz... --step 1 --json
69
+ # 写步骤必须带 approvalToken(环境变量 ARGENT_WRITE_APPROVAL 校验)
70
+ ARGENT_WRITE_APPROVAL=local-canary python3 tools/agentic/ml_agent_tools.py run-full-step \
71
+ --record-id reczz... --step 4 --allow-write --approval-token local-canary --json
72
+ ```
73
+
74
+ 生产由 ERP 签发 approval token;本地仅用于受控 canary。
75
+
76
+ ## 受控写工具实测(M2)
77
+
78
+ - `ml_run_full_step` 已挂到本地 MCP(`mcp__argent_ml__ml_run_full_step`);
79
+ - 只读 step1 实测 success;
80
+ - 写 step4 带本地审批 token 实测:工具正确返回 `ok:false`,引擎失败原因为平台暂无可预约日期;
81
+ - 本地审批 token 仅存于隔离 profile env(`ARGENT_WRITE_APPROVAL`),不进入仓库。
82
+
83
+ ## 预约放号 watcher(M3.5)
84
+
85
+ `ml_watch_appointment`:停留预约页低频刷新等待放号(只读)。
86
+
87
+ ```bash
88
+ python3 tools/agentic/ml_agent_tools.py watch-appointment \
89
+ --shipment 80664493 --store 墨西哥-2店-子账号 --interval-sec 60 --max-seconds 600 --json
90
+ ```
91
+
92
+ - 只刷新同一标签页,不重开店铺窗口;
93
+ - 返回 `slots_available` / `existing_appointment` 即停止;
94
+ - 平台错误页/无号继续等待,超时返回 observations;
95
+ - 自动预约(写)仍由 `ml_run_full_step` + approvalToken 执行。
@@ -0,0 +1,212 @@
1
+ #!/usr/bin/env python3
2
+ """Argent ML Tools MCP server(M1,stdio,只读)。
3
+
4
+ 协议:MCP JSON-RPC 2.0 over stdio;工具复用 ml_agent_tools.py。
5
+ 不依赖第三方 MCP SDK,便于客户机/本地直接运行。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import sys
11
+ import traceback
12
+ from pathlib import Path
13
+
14
+ HERE = Path(__file__).resolve().parent
15
+ sys.path.insert(0, str(HERE))
16
+ import ml_agent_tools as tools # noqa: E402
17
+
18
+ SERVER_INFO = {"name": "argent-ml-tools", "version": "0.1.0"}
19
+ PROTOCOL = "2024-11-05"
20
+
21
+ TOOLS = [
22
+ {
23
+ "name": "ml_probe_hub",
24
+ "description": "只读读取美客多 FULL hub-v2 五项状态,判断整票是否已完成。",
25
+ "inputSchema": {
26
+ "type": "object",
27
+ "properties": {
28
+ "shipmentNo": {"type": "string", "description": "货件号,如 80555414"},
29
+ "store": {"type": "string", "description": "店铺名,如 墨西哥-2店-子账号"},
30
+ "storeId": {"type": "string", "description": "店铺 ID(可选,优先于 store)"},
31
+ "recordId": {"type": "string", "description": "ERP sourceRecordId(可选,用于匹配 AgentTask)"},
32
+ },
33
+ "required": ["shipmentNo"],
34
+ },
35
+ },
36
+ {
37
+ "name": "ml_finalize_ticket",
38
+ "description": "步骤1-8 完成后用 hub-v2 五项验证并写 ERP AgentTask 完成态(需 approvalToken;0.8 不再写 lip)。",
39
+ "inputSchema": {
40
+ "type": "object",
41
+ "properties": {
42
+ "recordId": {"type": "string"},
43
+ "shipmentNo": {"type": "string"},
44
+ "store": {"type": "string"},
45
+ "approvalToken": {"type": "string"},
46
+ },
47
+ "required": ["shipmentNo", "store"],
48
+ },
49
+ },
50
+ {
51
+ "name": "ml_run_full_step",
52
+ "description": "受控调用现有 FULL 编排器执行单步(step 1-8);写步骤需要 approvalToken,仅本地/受信环境。",
53
+ "inputSchema": {
54
+ "type": "object",
55
+ "properties": {
56
+ "recordId": {"type": "string", "description": "ERP sourceRecordId"},
57
+ "step": {"type": "integer", "minimum": 1, "maximum": 8, "description": "FULL 步骤号"},
58
+ "allowWrite": {"type": "boolean", "description": "是否允许写步骤(3/4/5/7/8)"},
59
+ "approvalToken": {"type": "string", "description": "写步骤审批 token"},
60
+ "timeoutS": {"type": "integer", "minimum": 30, "maximum": 1200},
61
+ "record": {"type": "object", "description": "ERP-only 合成记录:record_id/sourceRecordId、store_name、sku、qty/quantity、box/boxCount、shipment_id/shipmentNo"},
62
+ },
63
+ "required": ["recordId", "step"],
64
+ },
65
+ },
66
+ {
67
+ "name": "ml_open_appointment_slots",
68
+ "description": "只读打开预约页、选择 Vehículo particular 并展开日期选择,返回可用日期/时段(不提交预约)。",
69
+ "inputSchema": {
70
+ "type": "object",
71
+ "properties": {
72
+ "shipmentNo": {"type": "string"},
73
+ "store": {"type": "string"},
74
+ "storeId": {"type": "string"},
75
+ },
76
+ "required": ["shipmentNo"],
77
+ },
78
+ },
79
+ {
80
+ "name": "ml_watch_appointment",
81
+ "description": "停留预约页低频刷新等待放号(只读;发现可用时段/已有预约即返回)。",
82
+ "inputSchema": {
83
+ "type": "object",
84
+ "properties": {
85
+ "shipmentNo": {"type": "string"},
86
+ "store": {"type": "string"},
87
+ "storeId": {"type": "string"},
88
+ "intervalSec": {"type": "integer", "minimum": 15, "maximum": 900},
89
+ "maxSeconds": {"type": "integer", "minimum": 30, "maximum": 7200},
90
+ },
91
+ "required": ["shipmentNo"],
92
+ },
93
+ },
94
+ {
95
+ "name": "ml_probe_appointment",
96
+ "description": "只读读取预约页运输方式/日历/错误页,不提交预约。",
97
+ "inputSchema": {
98
+ "type": "object",
99
+ "properties": {
100
+ "shipmentNo": {"type": "string", "description": "货件号"},
101
+ "store": {"type": "string", "description": "店铺名"},
102
+ "storeId": {"type": "string", "description": "店铺 ID(可选)"},
103
+ },
104
+ "required": ["shipmentNo"],
105
+ },
106
+ },
107
+ ]
108
+
109
+
110
+ def write(msg: dict) -> None:
111
+ sys.stdout.write(json.dumps(msg, ensure_ascii=False) + "\n")
112
+ sys.stdout.flush()
113
+
114
+
115
+ def result(req_id, payload):
116
+ write({"jsonrpc": "2.0", "id": req_id, "result": payload})
117
+
118
+
119
+ def error(req_id, code, message):
120
+ write({"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}})
121
+
122
+
123
+ def call_tool(name: str, args: dict) -> dict:
124
+ if name == "ml_probe_hub":
125
+ out = tools.probe_hub(
126
+ store=str(args.get("store") or ""),
127
+ shipment_no=str(args.get("shipmentNo") or ""),
128
+ store_id=str(args.get("storeId") or ""),
129
+ record_id=str(args.get("recordId") or ""),
130
+ open_store=False,
131
+ )
132
+ elif name == "ml_open_appointment_slots":
133
+ out = tools.open_appointment_slots(
134
+ str(args.get("store") or ""),
135
+ str(args.get("shipmentNo") or ""),
136
+ str(args.get("storeId") or ""),
137
+ False,
138
+ )
139
+ elif name == "ml_watch_appointment":
140
+ out = tools.watch_appointment(
141
+ str(args.get("store") or ""),
142
+ str(args.get("shipmentNo") or ""),
143
+ str(args.get("storeId") or ""),
144
+ False,
145
+ int(args.get("intervalSec") or 60),
146
+ int(args.get("maxSeconds") or 300),
147
+ )
148
+ elif name == "ml_finalize_ticket":
149
+ out = tools.finalize_ticket(
150
+ str(args.get("recordId") or ""),
151
+ str(args.get("store") or ""),
152
+ str(args.get("approvalToken") or ""),
153
+ str(args.get("shipmentNo") or ""),
154
+ )
155
+ elif name == "ml_run_full_step":
156
+ out = tools.run_full_step(
157
+ record_id=str(args.get("recordId") or ""),
158
+ step=int(args.get("step") or 0),
159
+ allow_write=bool(args.get("allowWrite")),
160
+ approval_token=str(args.get("approvalToken") or ""),
161
+ timeout_s=int(args.get("timeoutS") or 600),
162
+ record=args.get("record") or None,
163
+ )
164
+ elif name == "ml_probe_appointment":
165
+ out = tools.probe_appointment(
166
+ store=str(args.get("store") or ""),
167
+ shipment_no=str(args.get("shipmentNo") or ""),
168
+ store_id=str(args.get("storeId") or ""),
169
+ open_store=False,
170
+ )
171
+ else:
172
+ raise ValueError(f"unknown tool: {name}")
173
+ text = json.dumps(out, ensure_ascii=False)
174
+ return {"content": [{"type": "text", "text": text}], "isError": not bool(out.get("ok"))}
175
+
176
+
177
+ def main() -> int:
178
+ for line in sys.stdin:
179
+ line = line.strip()
180
+ if not line:
181
+ continue
182
+ try:
183
+ msg = json.loads(line)
184
+ except json.JSONDecodeError:
185
+ continue
186
+ method = msg.get("method")
187
+ req_id = msg.get("id")
188
+ if method == "initialize":
189
+ result(req_id, {"protocolVersion": PROTOCOL, "capabilities": {"tools": {}}, "serverInfo": SERVER_INFO})
190
+ elif method == "notifications/initialized":
191
+ continue
192
+ elif method == "ping":
193
+ result(req_id, {})
194
+ elif method == "tools/list":
195
+ result(req_id, {"tools": TOOLS})
196
+ elif method == "tools/call":
197
+ params = msg.get("params") or {}
198
+ try:
199
+ result(req_id, call_tool(str(params.get("name") or ""), params.get("arguments") or {}))
200
+ except Exception as exc: # noqa: BLE001
201
+ error(req_id, -32603, f"{type(exc).__name__}: {exc}")
202
+ elif req_id is not None:
203
+ error(req_id, -32601, f"method not found: {method}")
204
+ return 0
205
+
206
+
207
+ if __name__ == "__main__":
208
+ try:
209
+ sys.exit(main())
210
+ except Exception: # noqa: BLE001
211
+ traceback.print_exc(file=sys.stderr)
212
+ sys.exit(1)