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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/MANIFEST.json +102 -40
  2. package/bin/runtime-install.mjs +92 -0
  3. package/engine/VERSION +1 -1
  4. package/engine/configs/billing-actions.json +30 -0
  5. package/engine/configs/mcp-tools.snapshot.json +47 -0
  6. package/engine/core/contracts/argent.contracts.json +2 -2
  7. package/engine/core/lib/account-token.mjs +37 -0
  8. package/engine/core/lib/redact.mjs +34 -0
  9. package/engine/core/mcp/billing-upload.mjs +77 -0
  10. package/engine/core/mcp/erp-server.mjs +300 -0
  11. package/engine/core/mcp/gateway.mjs +333 -0
  12. package/engine/core/mcp/meter.mjs +101 -0
  13. package/engine/core/mcp/server.mjs +245 -0
  14. package/engine/core/mcp/vault.mjs +78 -0
  15. package/engine/scripts/appointment-worker.mjs +456 -35
  16. package/engine/scripts/appointment_grab.py +1389 -264
  17. package/engine/scripts/appointment_rules.py +118 -0
  18. package/engine/scripts/argent-timers.mjs +227 -0
  19. package/engine/scripts/argent-web-preflight.mjs +123 -0
  20. package/engine/scripts/argent-web-verify.mjs +105 -0
  21. package/engine/scripts/billing-upload.mjs +26 -0
  22. package/engine/scripts/build-engine-package.mjs +7 -1
  23. package/engine/scripts/capability-packs.lock.json +323 -300
  24. package/engine/scripts/check-version-consistency.mjs +14 -1
  25. package/engine/scripts/collect-intel.mjs +108 -0
  26. package/engine/scripts/daily-report-timer-plist.sh +18 -4
  27. package/engine/scripts/daily-report-timers.sh +36 -3
  28. package/engine/scripts/daily-report.mjs +78 -2
  29. package/engine/scripts/dsh-web-doctor.mjs +84 -0
  30. package/engine/scripts/engine-manifest.mjs +90 -0
  31. package/engine/scripts/engine-runtime-install.mjs +92 -0
  32. package/engine/scripts/erp-ui-install.mjs +127 -0
  33. package/engine/scripts/erp-ui-preflight.mjs +104 -0
  34. package/engine/scripts/erp-ui-verify.mjs +135 -0
  35. package/engine/scripts/flow-requirements.json +122 -99
  36. package/engine/scripts/full-exec-worker.mjs +251 -0
  37. package/engine/scripts/gen-preset-rows.mjs +1 -1
  38. package/engine/scripts/invoice_lip_runner.py +1 -0
  39. package/engine/scripts/invoice_runner.py +17 -6
  40. package/engine/scripts/invoice_stageb.py +21 -4
  41. package/engine/scripts/lib/bootcheck-wiring.mjs +7 -5
  42. package/engine/scripts/lib/intel-card.mjs +43 -0
  43. package/engine/scripts/lib/invoice_names.py +23 -0
  44. package/engine/scripts/lib/ml-ads-core.mjs +100 -18
  45. package/engine/scripts/lib/ml-ads-rules.mjs +275 -0
  46. package/engine/scripts/lib/ml-bridge-auth.mjs +50 -0
  47. package/engine/scripts/lib/ml-category-core.mjs +120 -0
  48. package/engine/scripts/lib/ml-insight-core.mjs +621 -0
  49. package/engine/scripts/lib/ml-insight-facts.mjs +424 -0
  50. package/engine/scripts/lib/ml-items.mjs +40 -0
  51. package/engine/scripts/lib/ml-listing-core.mjs +342 -0
  52. package/engine/scripts/lib/ml-market-core.mjs +774 -0
  53. package/engine/scripts/lib/plugin-packages.mjs +13 -0
  54. package/engine/scripts/lib/webdriver_ipc.py +61 -1
  55. package/engine/scripts/line_pack.py +196 -0
  56. package/engine/scripts/mcp-gateway-switch.mjs +100 -0
  57. package/engine/scripts/migrate-providers.mjs +3 -3
  58. package/engine/scripts/ml-ads-advice.mjs +140 -0
  59. package/engine/scripts/ml-ads.mjs +40 -0
  60. package/engine/scripts/ml-category-baseline.mjs +174 -0
  61. package/engine/scripts/ml-insight-diagnose.mjs +247 -0
  62. package/engine/scripts/ml-insight-run.sh +183 -0
  63. package/engine/scripts/ml-insight-timers.sh +224 -0
  64. package/engine/scripts/ml-listing-audit.mjs +170 -0
  65. package/engine/scripts/ml-market-matrix.mjs +84 -0
  66. package/engine/scripts/ml-market-snapshot.mjs +261 -0
  67. package/engine/scripts/ml-messages.mjs +145 -0
  68. package/engine/scripts/npm-publish-argent.mjs +14 -0
  69. package/engine/scripts/ops-codefix-pr.mjs +87 -0
  70. package/engine/scripts/ops-codefix-queue.mjs +30 -0
  71. package/engine/scripts/ops-digest.mjs +98 -0
  72. package/engine/scripts/ops-verify.mjs +67 -0
  73. package/engine/scripts/orchestrator.py +410 -20
  74. package/engine/scripts/orchestrator_br.py +146 -4
  75. package/engine/scripts/plugin-bootcheck.mjs +50 -1
  76. package/engine/scripts/publish-engine.mjs +111 -0
  77. package/engine/scripts/restart-dsh-with-tunnel.sh +129 -0
  78. package/engine/scripts/skuflow_invoice_runner.py +43 -3
  79. package/engine/scripts/v0.9-acceptance.mjs +107 -0
  80. package/engine/scripts/vertical-lint.mjs +12 -1
  81. package/engine/scripts/web-switch.mjs +121 -0
  82. package/engine/scripts/wenyao_fill_template.py +52 -15
  83. package/engine/scripts/wenyao_run.py +2 -1
  84. package/engine/skills/README.md +3 -3
  85. package/engine/skills/bilibili-upload/SKILL.md +109 -0
  86. package/engine/skills/douyin-upload/SKILL.md +74 -0
  87. package/engine/skills/internal.json +28 -0
  88. package/engine/skills/kuaishou-upload/SKILL.md +109 -0
  89. package/engine/skills/ml-appointment-safety/SKILL.md +42 -0
  90. package/engine/skills/ml-full-appointment/SKILL.md +23 -0
  91. package/engine/skills/ml-invoice/SKILL.md +2 -2
  92. package/engine/skills/ml-invoice/references/template-fill-contract.md +1 -1
  93. package/engine/skills/ml-label-recovery/SKILL.md +43 -0
  94. package/engine/skills/ml-listing-audit/SKILL.md +66 -0
  95. package/engine/skills/ml-store-daily-report/SKILL.md +68 -0
  96. package/engine/skills/ml-store-daily-report/scripts/generate.js +35 -0
  97. package/engine/skills/ml-store-insight/SKILL.md +81 -0
  98. package/engine/skills/tencent-upload/SKILL.md +60 -0
  99. package/engine/skills/weibo-upload/SKILL.md +106 -0
  100. package/engine/skills/whyshu-social-ops/SKILL.md +136 -0
  101. package/engine/skills/xiaohongshu-upload/SKILL.md +122 -0
  102. package/engine/version.mjs +1 -1
  103. package/engine/verticals/README.md +7 -0
  104. package/engine/verticals/_engine-words.baseline.txt +27 -59
  105. package/engine/verticals/mercadolibre/manifest.json +132 -6
  106. package/package.json +5 -1
@@ -1,56 +1,335 @@
1
1
  #!/usr/bin/env python3
2
2
  """FULL 抢预约 worker 的浏览器执行器(参数全部来自 AppointmentTask,不读 lip)。
3
3
 
4
- - 日期范围严格使用任务 dateFrom/dateTo;
5
- - 逐日三态:disabled(不可选)/ selectable_no_slot(可选但无时段)/ selectable_booking_failed / booked;
4
+ 2026-11-16 FULL 预约循环改造(黑五不放号 ⇒ 长期值守)。把原来的「3 次重试失败就抛、
5
+ 周期循环 maxCycles 到点就退」拆成**显式状态机 + 滚动游标**:
6
+
7
+ PREPARING ──页面就绪──────────────→ SCANNING
8
+ PREPARING ──A 态:无配送方式选项───→ NO_DELIVERY_OPTION ─┐
9
+ PREPARING ──页面/导航异常──────────→ PAGE_ERROR ─────────┤
10
+ SCANNING ──B 态:6 个月扫完全灰───→ CALENDAR_ALL_DISABLED ┤→ 刷新该 tab 的页面
11
+ SCANNING ──发现可选日─────────────→ BOOKING │ (page.reload,⛔ 不新开 tab)
12
+ BOOKING ──成功──────────────────→ BOOKED(结束) │ 等待 20–40s 随机抖动(防风控)
13
+ BOOKING ──不可选/无时段/提交失败─→ BOOKING_FAILED ──────┘ 游标重置到今天 → 回到 PREPARING
14
+
15
+ · A 态(`Vehículo` 下拉无选项 / 直接提示不可预约)与 B 态(日历能渲染、日期全灰)各自的
16
+ 下一步写在 `STATE_NEXT_STEP` 里,由 `_refresh_and_wait()` 这一个出口执行。
17
+ · `BOOKING_FAILED` 的下一步不是立刻刷新:先把该日标记为「本窗口已尝试」,在同一窗口继续
18
+ 下一候选/下一月;**窗口耗尽**才刷新+重置游标(见 `_window_exhausted()`)。
19
+ · 日期扫描 = **滚动游标**(`ScanCursor`):记住上次扫到哪个月,同一窗口内不从头重扫;
20
+ 刷新后游标重置到今天所在月(刷新后平台可能出现新的可选日)。
21
+ · 盲扫上限 = 从今天所在月起最多 `MAX_SCAN_MONTHS`(=6) 个自然月(含当月,即最多翻 5 次月);
22
+ 到上限仍无可选 ⇒ 刷新。range 模式的上界 = 运营给定的 `dateTo`(显式目标不受盲扫上限约束)。
23
+ · 循环**不设最大轮数**:唯一终止 = 抢到 / 运营停止(ERP `stopRequestedAt` → worker SIGTERM
24
+ → `main()` 里的 KeyboardInterrupt 收尾)。
25
+ · ⛔ 循环里**不新开标签页**(每店 5 tab 并发,预约步骤长期占用 1 个 tab);刷新 = 当前页 reload。
26
+ · range / available_days 两种模式语义保留;range 每轮只打开一次日历(2026-10-21 修复,别改回去)。
27
+ · JSONL 事件形状不变:`{'event':'cycle'|'progress','cycle':n,'checks':n,'dateStates':{...}}`
28
+ (cycle 事件另带既有可选键 `summary`;状态迁移细节走 `_log`/stderr,不往事件里加新键)。
29
+ · dateStates 取值沿用旧口径:disabled / selectable / selectable_no_slot /
30
+ selectable_booking_failed / date_not_found / pending / booked。
31
+
32
+ - 日期范围严格使用任务 dateFrom/dateTo(range 模式只点运营给的日期,⛔ 不跳日出范围);
6
33
  - 预约成功即停,不执行 FULL 步骤 5-8;
7
34
  - 由 appointment-worker.mjs 启动;stdout 最后一行 JSON 为结果。
8
35
  """
9
36
  import argparse
10
37
  import asyncio
11
- import time
12
38
  import json
13
39
  import os
40
+ import random
41
+ import re
14
42
  import signal
15
43
  import sys
44
+ import urllib.request
45
+ from dataclasses import dataclass, field
16
46
  from datetime import date, datetime, timedelta, timezone
17
47
  from pathlib import Path
18
48
  from types import SimpleNamespace
49
+ from typing import Any, Awaitable, Callable, Optional
19
50
 
20
51
  ROOT = Path(__file__).resolve().parent
21
52
  sys.path.insert(0, str(ROOT))
22
53
 
23
54
  import orchestrator as O # noqa: E402
55
+ from appointment_rules import compile_rule as compile_rule_dates # noqa: E402
24
56
 
25
57
 
26
- DATE_CELL_JS = r"""(targetIso) => {
27
- const days = document.querySelectorAll('div.day');
28
- const MONTHS = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];
29
- const my = document.querySelector('.focus-ui-datepicker__content__month-year');
30
- const header = my ? (my.textContent || '').trim().toLowerCase() : '';
31
- const target = new Date(targetIso + 'T12:00:00');
32
- const viewMonths = MONTHS.map((m, mi) => header.includes(m) ? mi : -1).filter(x => x >= 0);
33
- const ym = header.match(/(\d{4})/);
34
- if (!viewMonths.length || !ym) return {found:false, reason:'header_unreliable', header};
35
- const viewYear = parseInt(ym[1], 10);
36
- let month = viewMonths[0] - 1, prev = 0, started = false;
37
- for (let i = 0; i < days.length; i++) {
38
- const t = (days[i].textContent || '').trim();
39
- if (!/^\d+$/.test(t)) continue;
40
- const d = parseInt(t, 10);
41
- if (d === 1 && (prev > 1 || prev === 0)) {
42
- if (!started) { started = true; month = viewMonths[0]; } else { month++; }
43
- }
44
- prev = d;
45
- if (started && month === target.getMonth() && d === target.getDate()) {
46
- const cls = days[i].className || '';
47
- return {found:true, idx:i, disabled: cls.includes('day--disabled'), cls, header};
48
- }
49
- }
50
- return {found:false, reason:'not_in_view', header};
51
- }"""
58
+ # ══════════════════════════════════════════════════════════════════════════════
59
+ # 显式状态机(把原来的"等号"拆开:每个状态只有一个明确的下一步)
60
+ # ══════════════════════════════════════════════════════════════════════════════
61
+ STATE_PREPARING = 'preparing'
62
+ STATE_SCANNING = 'scanning'
63
+ STATE_BOOKING = 'booking'
64
+ # A 态:配送方式下拉无选项 / 平台直接提示不可预约
65
+ STATE_NO_DELIVERY_OPTION = 'no_delivery_option'
66
+ # B 态:日历能渲染,但 6 个月窗口内日期全灰
67
+ STATE_CALENDAR_ALL_DISABLED = 'calendar_all_disabled'
68
+ # 有可选日,但点日/选时段/提交没成功
69
+ STATE_BOOKING_FAILED = 'booking_failed'
70
+ # 页面/翻月/日历读取异常(刷新自愈)
71
+ STATE_PAGE_ERROR = 'page_error'
72
+ # 终态
73
+ STATE_BOOKED = 'booked'
74
+ STATE_EXISTING = 'existing'
75
+ # 平台把 appointment-v2 重定向到 /details(货件已处理完成/无需预约)⇒ 终态失败,别空转
76
+ STATE_NOT_APPLICABLE = 'not_applicable'
77
+
78
+
79
+ # ── 改约(2026-11-17):把页面上「已有预约」的日期/时段解析出来,与任务窗口比对 ──
80
+ # 平台是西语界面:日期形如 "18 de noviembre de 2026" / "18/11/2026" / "nov 18",
81
+ # 时段形如 "09:30" / "9:30 a. m."。只做保守解析:解析不出就返回空,交给人工判断(不猜)。
82
+ ES_MONTHS = {
83
+ 'enero': 1, 'febrero': 2, 'marzo': 3, 'abril': 4, 'mayo': 5, 'junio': 6,
84
+ 'julio': 7, 'agosto': 8, 'septiembre': 9, 'setiembre': 9, 'octubre': 10,
85
+ 'noviembre': 11, 'diciembre': 12,
86
+ 'ene': 1, 'feb': 2, 'mar': 3, 'abr': 4, 'may': 5, 'jun': 6,
87
+ 'jul': 7, 'ago': 8, 'sep': 9, 'sept': 9, 'oct': 10, 'nov': 11, 'dic': 12,
88
+ }
89
+
90
+
91
+ def parse_existing_appointment(text: str) -> dict:
92
+ """从「已有预约」卡片文本里解析日期与时段。
93
+
94
+ 返回 {'date': 'YYYY-MM-DD'|'', 'slot': 'HH:MM'|''};解析不出即空串。
95
+ """
96
+ out = {'date': '', 'slot': ''}
97
+ t = str(text or '')
98
+ if not t:
99
+ return out
100
+ low = t.lower()
101
+ # ① 18 de noviembre de 2026 / 18 noviembre 2026
102
+ m = re.search(r'(\d{1,2})\s+de?\s*([a-záéíóú]+)\.?\s*(?:de\s*)?(\d{4})', low)
103
+ if m:
104
+ day = int(m.group(1))
105
+ mon = ES_MONTHS.get(m.group(2).strip('.'))
106
+ year = int(m.group(3))
107
+ if mon and 1 <= day <= 31:
108
+ try:
109
+ out['date'] = date(year, mon, day).isoformat()
110
+ except ValueError:
111
+ pass
112
+ # ② 18/11/2026 或 2026-11-18
113
+ if not out['date']:
114
+ m = re.search(r'(\d{1,2})/(\d{1,2})/(\d{4})', t)
115
+ if m:
116
+ try:
117
+ out['date'] = date(int(m.group(3)), int(m.group(2)), int(m.group(1))).isoformat()
118
+ except ValueError:
119
+ pass
120
+ if not out['date']:
121
+ m = re.search(r'(\d{4})-(\d{2})-(\d{2})', t)
122
+ if m:
123
+ try:
124
+ out['date'] = date(int(m.group(1)), int(m.group(2)), int(m.group(3))).isoformat()
125
+ except ValueError:
126
+ pass
127
+ # ③ 时段 09:30 / 9:30 a. m.
128
+ m = re.search(r'(\d{1,2}):(\d{2})\s*(a\.?\s*m\.?|p\.?\s*m\.?)?', low)
129
+ if m:
130
+ hour = int(m.group(1))
131
+ minute = int(m.group(2))
132
+ ampm = (m.group(3) or '').replace('.', '').replace(' ', '')
133
+ if ampm.startswith('p') and hour < 12:
134
+ hour += 12
135
+ if ampm.startswith('a') and hour == 12:
136
+ hour = 0
137
+ if 0 <= hour <= 23 and 0 <= minute <= 59:
138
+ out['slot'] = f'{hour:02d}:{minute:02d}'
139
+ return out
140
+
141
+
142
+ def window_matches(date_iso: str, slot: str, task: dict) -> bool:
143
+ """已有预约是否已满足任务窗口(日期在范围/星期内、时段在时间窗内)。缺信息 ⇒ 不认定满足。"""
144
+ if not date_iso:
145
+ return False
146
+ try:
147
+ d = date.fromisoformat(date_iso)
148
+ except ValueError:
149
+ return False
150
+ mode = str(task.get('dateMode') or 'range')
151
+ if mode == 'available_days':
152
+ days = int(task.get('availableDays') or 0)
153
+ if days <= 0:
154
+ return False
155
+ if d < date.today() or d > date.today() + timedelta(days=days):
156
+ return False
157
+ else:
158
+ try:
159
+ lo = date.fromisoformat(str(task.get('dateFrom') or '')[:10])
160
+ hi = date.fromisoformat(str(task.get('dateTo') or '')[:10])
161
+ except ValueError:
162
+ return False
163
+ if not (lo <= d <= hi):
164
+ return False
165
+ weekdays = [int(x) for x in (task.get('weekdays') or []) if str(x).isdigit()]
166
+ if weekdays and (d.isoweekday() not in weekdays):
167
+ return False
168
+ tf = str(task.get('timeFrom') or '')
169
+ tt = str(task.get('timeTo') or '')
170
+ if slot and tf and tt:
171
+ def mins(hhmm):
172
+ try:
173
+ h, m = hhmm.split(':')[:2]
174
+ return int(h) * 60 + int(m)
175
+ except Exception:
176
+ return None
177
+ cur, lo_t, hi_t = mins(slot), mins(tf), mins(tt)
178
+ if cur is not None and lo_t is not None and hi_t is not None and not (lo_t <= cur <= hi_t):
179
+ return False
180
+ return True
181
+
182
+
183
+ # 每个异常态的**唯一下一步**(实现见 `AppointmentLoop._refresh_and_wait` / `_try_candidates`)
184
+ STATE_NEXT_STEP = {
185
+ STATE_NO_DELIVERY_OPTION:
186
+ '刷新该 tab 的页面(page.reload)→ 等 20–40s 抖动 → 游标重置到今天 → 重新准备页面(继续等平台放号)',
187
+ STATE_CALENDAR_ALL_DISABLED:
188
+ '刷新该 tab 的页面(page.reload)→ 等 20–40s 抖动 → 游标重置到今天 → 从今天重扫(刷新后可能有新可选日)',
189
+ STATE_BOOKING_FAILED:
190
+ '该日标记为「本窗口已尝试」→ 同窗口继续下一候选/下一月;窗口耗尽才刷新+重置游标',
191
+ STATE_PAGE_ERROR:
192
+ '刷新该 tab 的页面(page.reload)→ 等 20–40s 抖动 → 游标重置到今天 → 重新准备页面',
193
+ }
194
+
195
+ # 盲扫窗口:从今天所在月起最多看 6 个自然月(含当月,即最多翻 5 次月)。
196
+ MAX_SCAN_MONTHS = 6
197
+ # 未知内部异常(不是平台形态类)连续这么多次 ⇒ 判失败收手,避免 bug 把 tab 焊死。
198
+ # ⚠️ 平台形态类(A/B 三态 + page_error)**不计入**该上限,它们是无限值守的一部分。
199
+ MAX_UNEXPECTED_ERRORS = 5
200
+
201
+ MONTHS_ES = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio',
202
+ 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre']
203
+
204
+ # 预约失败文案 → dateStates 口径(沿用旧实现的 marker 判定,⛔ 不再改口径)
205
+ _DISABLED_MARKERS = ('不可选', '目标日期')
206
+ _NO_SLOT_MARKERS = ('可用时段不足', '未渲染出可选时段', '时间选择失败', '未写入日期时间',
207
+ '指定时间范围内无可预约时段')
208
+
209
+
210
+ class PageError(RuntimeError):
211
+ """页面/日历读取或翻月异常(可刷新自愈)。"""
212
+
213
+
214
+ class PrepareError(RuntimeError):
215
+ """预约页准备失败,带机器可判状态:no_delivery_option / page_error / existing。"""
216
+
217
+ def __init__(self, state: str, message: str):
218
+ super().__init__(message)
219
+ self.state = state
220
+
221
+
222
+ class BookingError(RuntimeError):
223
+ """单日预约失败;kind ∈ {disabled, selectable_no_slot, selectable_booking_failed}。"""
224
+
225
+ def __init__(self, kind: str, message: str):
226
+ super().__init__(message)
227
+ self.kind = kind
228
+
229
+
230
+ # `_try_candidates` 的哨兵:本轮已刷新(页面刚重开、未准备好)⇒ 本轮到此结束
231
+ _PASS_ENDED = object()
232
+
233
+
234
+ def classify_booking_error(message: str) -> str:
235
+ """预约失败文案 → dateStates 口径(旧实现的 marker 判定,集中一处)。"""
236
+ msg = str(message or '')
237
+ if any(k in msg for k in _DISABLED_MARKERS):
238
+ return 'disabled'
239
+ if any(k in msg for k in _NO_SLOT_MARKERS):
240
+ return 'selectable_no_slot'
241
+ return 'selectable_booking_failed'
242
+
243
+
244
+ def month_index(year: int, month: int) -> int:
245
+ return int(year) * 12 + (int(month) - 1)
246
+
247
+
248
+ def month_from_index(idx: int) -> tuple[int, int]:
249
+ return idx // 12, idx % 12 + 1
250
+
251
+
252
+ def parse_header_month(header: str) -> Optional[tuple[int, int]]:
253
+ """日历 header(如 `octubre 2026` / `oct 2026`)→ (year, month);读不出返回 None。"""
254
+ h = str(header or '').lower()
255
+ ym = re.search(r'(\d{4})', h)
256
+ if not ym:
257
+ return None
258
+ hits = [i for i, m in enumerate(MONTHS_ES) if m in h]
259
+ if not hits:
260
+ return None
261
+ return int(ym.group(1)), hits[0] + 1
262
+
263
+
264
+ # ══════════════════════════════════════════════════════════════════════════════
265
+ # 可注入的节奏("刷新节奏 20–40 秒随机抖动";测试传 0 + 立即返回的 sleep)
266
+ # ══════════════════════════════════════════════════════════════════════════════
267
+ @dataclass
268
+ class Pacing:
269
+ """值守节奏。`sleep` 也一并注入,测试用 0 延迟即可把整条状态机跑成同步。"""
270
+
271
+ refresh_min_sec: float = 20.0
272
+ refresh_max_sec: float = 40.0
273
+ scan_pause_sec: float = 0.8
274
+ prepare_attempts: int = 3
275
+ prepare_retry_sec: float = 3.0
276
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep
277
+ rng: random.Random = field(default_factory=random.Random)
278
+
279
+ def refresh_delay(self) -> float:
280
+ lo, hi = float(self.refresh_min_sec), float(self.refresh_max_sec)
281
+ if hi < lo:
282
+ lo, hi = hi, lo
283
+ return self.rng.uniform(lo, hi) if hi > lo else lo
284
+
285
+
286
+ @dataclass
287
+ class ScanCursor:
288
+ """滚动游标:记住「上次扫到哪个月」。
289
+
290
+ `start_idx` = 本窗口起点(游标重置时的今天所在月);`idx` = 当前应扫的月。
291
+ `flips` = 本窗口已翻月次数(用于 6 个月盲扫上限判定)。
292
+ 刷新页面后由 `reset(today)` 重置到今天所在月 —— 这是"刷新后从今天重来"的唯一实现点。
293
+ """
294
+
295
+ start_idx: int
296
+ idx: int
297
+
298
+ @classmethod
299
+ def at(cls, today: date) -> 'ScanCursor':
300
+ i = month_index(today.year, today.month)
301
+ return cls(i, i)
302
+
303
+ def reset(self, today: date) -> None:
304
+ i = month_index(today.year, today.month)
305
+ self.start_idx = i
306
+ self.idx = i
307
+
308
+ def sync(self, idx: int) -> None:
309
+ """视图实际停的月比游标更靠后时前移游标(⛔ 不回退,避免重复扫已扫月)。"""
310
+ if idx > self.idx:
311
+ self.idx = idx
52
312
 
313
+ def advance(self) -> None:
314
+ self.idx += 1
53
315
 
316
+ @property
317
+ def flips(self) -> int:
318
+ return max(0, self.idx - self.start_idx)
319
+
320
+ @property
321
+ def year_month(self) -> tuple[int, int]:
322
+ return month_from_index(self.idx)
323
+
324
+ def as_dict(self) -> dict:
325
+ y, m = self.year_month
326
+ sy, sm = month_from_index(self.start_idx)
327
+ return {'month': f'{y:04d}-{m:02d}', 'windowStart': f'{sy:04d}-{sm:02d}', 'flips': self.flips}
328
+
329
+
330
+ # ══════════════════════════════════════════════════════════════════════════════
331
+ # 页面脚本(沿用原实现;DATE_CELL_JS 已删 —— 逐日状态改由 SCAN_DAYS_JS 一次读全月)
332
+ # ══════════════════════════════════════════════════════════════════════════════
54
333
  SCAN_DAYS_JS = r"""() => {
55
334
  const days = [...document.querySelectorAll('div.day')];
56
335
  const MONTHS = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre'];
@@ -78,11 +357,19 @@ SCAN_DAYS_JS = r"""() => {
78
357
  }"""
79
358
 
80
359
 
360
+ _CLI_PACING = {'refresh_min': None, 'refresh_max': None}
361
+
362
+
81
363
  def load_task() -> dict:
82
364
  ap = argparse.ArgumentParser()
83
365
  ap.add_argument('--task-json', required=True)
84
366
  ap.add_argument('--cdp-hint', default='')
367
+ # 2026-11-18:刷新节奏可由 worker 从 ERP 实时下发(运营自调),默认沿用 Pacing 的 20–40s
368
+ ap.add_argument('--refresh-min', type=float, default=None)
369
+ ap.add_argument('--refresh-max', type=float, default=None)
85
370
  args = ap.parse_args()
371
+ _CLI_PACING['refresh_min'] = args.refresh_min
372
+ _CLI_PACING['refresh_max'] = args.refresh_max
86
373
  return json.loads(args.task_json)
87
374
 
88
375
 
@@ -95,63 +382,167 @@ def iso_day(d) -> date:
95
382
  return dt.astimezone(timezone(timedelta(hours=8))).date()
96
383
 
97
384
 
98
- async def _close_appointment_tab(orch) -> int:
99
- """停止/失败时关闭本任务用的预约标签页;若它是窗口最后 1 个标签,先开一个占位页再关。
385
+ # ══════════════════════════════════════════════════════════════════════════════
386
+ # 预约页准备(真实页面动作;失败一律翻译成带状态的 PrepareError)
387
+ # ══════════════════════════════════════════════════════════════════════════════
388
+ async def prepare_appointment_page(orch, *, attempts: int = 3, retry_delay: float = 3.0,
389
+ sleep: Optional[Callable[[float], Awaitable[None]]] = None) -> None:
390
+ """进入预约页并选好运输方式/地址,打开日期日历;页面慢/弹窗允许重试。
100
391
 
101
- 紫鸟窗口守卫要求不能把最后标签关掉(会退出 Chromium 窗口、丢 CDP)。
102
- 这里用 about:blank 占位保持窗口存活,再关闭预约页,避免用户看到残留任务标签。
392
+ ⛔ 不再用裸 RuntimeError:失败必须带状态,状态机才知道下一步(A 态要刷新继续等)。
393
+ · 下拉打不开 / 下拉里没有 `Vehículo` 选项 / 平台直接提示不可预约 ⇒ `no_delivery_option`
394
+ · 其它页面/超时/导航异常 ⇒ `page_error`
395
+ · 页面显示已有预约(`Cancelar reserva`) ⇒ `existing`(调用方按"不重复抢"处理)
103
396
  """
104
- closed = 0
105
- try:
106
- page = getattr(orch.browser, 'page', None)
107
- if page is None or page.is_closed():
108
- return 0
109
- url = str(getattr(page, 'url', '') or '')
110
- # 只清理本任务/预约页,避免误关用户主门户标签
111
- if ('appointment-v2' not in url) and (str(getattr(orch.state, 'shipment_id', '') or '') not in url):
112
- return 0
113
- ctx = page.context
114
- if len(ctx.pages) <= 1:
115
- try:
116
- await ctx.new_page() # 占位,保持窗口不退出
117
- except Exception:
118
- return 0
119
- await page.close()
120
- closed = 1
121
- orch._log(' 🗂️ 已关闭抢预约任务标签页(保留占位页,防窗口退出)')
122
- except Exception as e:
123
- try: orch._log(f' ⚠️ 关闭预约标签页失败:{str(e)[:120]}')
124
- except Exception: pass
125
- return closed
126
-
397
+ sleep = sleep or asyncio.sleep
398
+ attempts = max(1, int(attempts))
127
399
 
128
- def _bump_page_check(orch) -> int:
129
- n = int(getattr(orch, '_appt_page_checks', 0)) + 1
130
- setattr(orch, '_appt_page_checks', n)
131
- return n
400
+ async def _guard_url(_stage: str) -> None:
401
+ """交互后检查 URL:被跳到卖家菜单/登录页等 ⇒ 立刻判 page_error(附阶段与 URL)。"""
402
+ try:
403
+ _u = str(orch.browser.page.url or "")
404
+ except Exception:
405
+ return
406
+ marks = ('personas-interesadas', 'seller-menu', 'ato-complaint', '/login', 'identification')
407
+ if _u and any(mk in _u for mk in marks):
408
+ raise PrepareError(STATE_PAGE_ERROR,
409
+ f'[{_stage}] 后页面被跳转到 {_u[:120]}')
132
410
 
411
+ async def _dismiss_blockers(_page) -> None:
412
+ """关掉会拦截点击的 cookie 横幅/浮层(2026-11-18:实测点击超时多为覆盖层拦截)。"""
413
+ for name in ('Aceptar cookies', 'Aceptar todo', 'Aceptar', 'Entendido', 'Continuar sin aceptar'):
414
+ try:
415
+ btn = _page.get_by_role('button', name=name, exact=False).first
416
+ if await btn.count() and await btn.is_visible():
417
+ await btn.click(timeout=2500)
418
+ await sleep(0.3)
419
+ return
420
+ except Exception:
421
+ continue
133
422
 
134
- async def prepare_appointment_page(orch) -> None:
135
- """进入预约页并选好运输方式/地址,打开日期日历;页面慢/弹窗允许重试。"""
136
- last = None
137
- for attempt in range(3):
423
+ last_state = STATE_NO_DELIVERY_OPTION
424
+ last_msg = ''
425
+ for attempt in range(attempts):
138
426
  try:
139
427
  _bump_page_check(orch)
428
+ # 2026-11-18:先清掉同货件的残留标签页(多任务/重定向会留重复 tab,越积越多)
429
+ try:
430
+ await orch.browser.close_shipment_tabs(str(orch.state.shipment_id or ''))
431
+ # ⛔ 不在这里清「噪音标签」:同店多个任务共用窗口时,另一个正在跑的任务的 tab
432
+ # 可能刚好被平台跳到 personas-interesadas,清掉它等于把人家正在用的页面关掉
433
+ # (实测 2026-11-18:2店 2 条任务只剩 1 个 tab)。噪音标签由 URL 守卫自愈 + 人工清理。
434
+ except Exception:
435
+ pass
140
436
  await orch.browser.visit_plan_page('appointment-v2', orch.state.shipment_id, step=4)
437
+ # 2026-11-18:有的货件平台不提供预约页,直接跳到 /details(如「Procesamiento finalizado」
438
+ # 的旧货件)⇒ 判「无需预约」终态;继续循环只会占着槽位空转(实测 74670907 卡了一天)。
439
+ try:
440
+ _page = orch.browser.page
441
+ _url = str(getattr(_page, 'url', '') or '')
442
+ _title = await _page.title()
443
+ except Exception:
444
+ _url, _title = '', ''
445
+ # 2026-11-18:预约页被平台/浏览器跳到别的页面(卖家菜单、登录页等)时,
446
+ # 之前会继续按"页面形态异常"空刷;这里明确识别并给出可读原因,交给刷新重试。
447
+ _redirect_marks = ('personas-interesadas', 'seller-menu', '/login', 'identification', 'ato-complaint')
448
+ if _url and any(_mk in _url for _mk in _redirect_marks):
449
+ raise PrepareError(STATE_PAGE_ERROR,
450
+ f'预约页被跳转到其他页面({_url[:120]})⇒ 按登录态/误导航处理,刷新重试')
451
+ if '/details' in _url or 'Detalle del envío' in str(_title or ''):
452
+ raise PrepareError(STATE_NOT_APPLICABLE,
453
+ f'平台把预约页重定向到货件详情页(该货件无需预约/已处理完成):{_url[:120]}')
454
+ await _guard_url('打开预约页')
455
+ # 2026-11-18:平台错误页/无号提示页上**不要点任何元素**——实测点击会触发页面跳转到
456
+ # 卖家菜单 personas-interesadas(导航历史:typed appointment → link personas 交替)。
457
+ _err_text = ''
458
+ try:
459
+ _err_text = await orch.browser.page.evaluate(
460
+ "() => ((document.title || '') + ' ' + ((document.body && document.body.innerText) || '').slice(0, 600))")
461
+ except Exception:
462
+ _err_text = ''
463
+ _err_marks = ('Algo salió mal', 'Tenemos más tráfico', 'No contamos con citas',
464
+ 'vuelve a intentarlo en los próximos días')
465
+ if _err_text and any(_mk in str(_err_text) for _mk in _err_marks):
466
+ # 2026-11-19 用户实测:页面标题/顶部仍显示平台错误,但**预约表单实际已出现**
467
+ # (配送方式可选、日历可选)。旧逻辑只看错误文案就刷新 ⇒ 把可操作表单刷掉。
468
+ # ⇒ 表单存在时一律继续走预约步骤;只有"错误页且没有任何表单元素"才刷新。
469
+ _form_present = False
470
+ try:
471
+ _form_present = bool(await orch.browser.page.evaluate(
472
+ """() => !!(document.querySelector('#shipment-type-selection-dropdown-id-trigger')
473
+ || document.querySelector('input[readonly]')
474
+ || document.querySelectorAll('div.day').length
475
+ || document.querySelectorAll('div.hour').length
476
+ || document.querySelectorAll('.andes-card').length)"""))
477
+ except Exception:
478
+ _form_present = False
479
+ if not _form_present:
480
+ raise PrepareError(STATE_NO_DELIVERY_OPTION,
481
+ f'平台错误页/无号提示(不交互,直接刷新等待):{str(_err_text)[:100]}')
482
+ _safe_log(orch, ' ℹ️ 平台顶部提示错误但预约表单已出现 ⇒ 继续走预约步骤(不刷新)')
483
+ try:
484
+ await _dismiss_blockers(orch.browser.page)
485
+ except PrepareError:
486
+ raise
487
+ except Exception:
488
+ pass
489
+ await _guard_url('关闭 cookie 横幅')
141
490
  if await orch._has_existing_appointment():
142
- raise RuntimeError('已有预约存在,不重复抢')
491
+ # 2026-11-17 改约:把页面上的已有预约日期/时段解析出来,供 intent=reschedule 判断
492
+ text = ''
493
+ try:
494
+ text = await orch._existing_appointment_text()
495
+ except Exception:
496
+ text = ''
497
+ info = parse_existing_appointment(text)
498
+ info['text'] = str(text or '')[:400]
499
+ setattr(orch, '_appt_existing_info', info)
500
+ raise PrepareError(STATE_EXISTING,
501
+ '已有预约存在(页面显示 Cancelar reserva)')
143
502
  page = orch.browser.page
144
- trigger = page.locator('#shipment-type-selection-dropdown-id-trigger')
145
- await trigger.wait_for(state='visible', timeout=30000)
146
- await trigger.click()
147
- await asyncio.sleep(0.8)
503
+ try:
504
+ trigger = page.locator('#shipment-type-selection-dropdown-id-trigger')
505
+ await trigger.wait_for(state='visible', timeout=30000)
506
+ except Exception as exc:
507
+ # A 态:配送方式下拉压根没渲染出来(平台直接提示不可预约 / 表单未出)
508
+ raise PrepareError(STATE_NO_DELIVERY_OPTION,
509
+ f'配送方式下拉不可见(平台未放配送方式/页面不可预约):{str(exc)[:120]}') from exc
510
+ try:
511
+ await trigger.click(timeout=8000)
512
+ await _guard_url('点击配送方式下拉')
513
+ except PrepareError:
514
+ raise
515
+ except Exception as exc:
516
+ # 2026-11-18:页面可选但点击被 cookie 横幅/浮层拦截 ⇒ 关掉遮蔽物再试,最后 JS click 兜底
517
+ await _dismiss_blockers(orch.browser.page)
518
+ try:
519
+ await trigger.click(timeout=8000)
520
+ except Exception:
521
+ try:
522
+ await trigger.evaluate("el => el.click()")
523
+ except Exception:
524
+ raise PrepareError(STATE_NO_DELIVERY_OPTION,
525
+ f'配送方式下拉点击失败:{str(exc)[:120]}') from exc
526
+ await sleep(0.8)
148
527
  option = page.get_by_role('option', name='Vehículo particular', exact=False).first
149
- if await option.count() == 0:
528
+ n_opt = await option.count()
529
+ if n_opt == 0:
150
530
  option = page.get_by_role('option', name='Vehículo', exact=False).first
151
- if await option.count() == 0:
152
- raise RuntimeError('未找到 Vehículo 运输选项')
531
+ n_opt = await option.count()
532
+ if n_opt == 0:
533
+ # 兜底:部分版本下拉项不是 role=option(实测黑五改版),用文本定位
534
+ for sel in ('li:has-text("Vehículo particular")', 'li:has-text("Vehículo")',
535
+ '.andes-list__item:has-text("Vehículo")', '[role="listitem"]:has-text("Vehículo")'):
536
+ option = page.locator(sel).first
537
+ n_opt = await option.count()
538
+ if n_opt:
539
+ break
540
+ if n_opt == 0:
541
+ raise PrepareError(STATE_NO_DELIVERY_OPTION,
542
+ '配送方式下拉无 Vehículo 选项(平台未放配送方式)')
153
543
  await option.click()
154
- await asyncio.sleep(1.2)
544
+ await _guard_url('选择 Vehículo')
545
+ await sleep(1.2)
155
546
  try:
156
547
  await orch.browser.page.wait_for_selector('.andes-list__item-action', timeout=8000)
157
548
  btns = orch.browser.page.locator('.andes-list__item-action')
@@ -159,92 +550,755 @@ async def prepare_appointment_page(orch) -> None:
159
550
  for i in range(await btns.count()):
160
551
  txt = (await btns.nth(i).text_content() or '')
161
552
  if 'MXCD05' in txt:
162
- target = (btns.nth(i), txt); break
553
+ target = (btns.nth(i), txt)
554
+ break
163
555
  if target is None:
164
556
  raise RuntimeError('未找到指定仓库 MXCD05')
165
557
  await target[0].scroll_into_view_if_needed(timeout=5000)
166
- await asyncio.sleep(0.4)
558
+ await sleep(0.4)
167
559
  await target[0].click()
168
560
  try:
169
561
  cont = orch.browser.page.locator('button', has_text='Continuar').first
170
562
  await cont.click(force=True, timeout=5000)
171
563
  except Exception:
172
564
  pass
173
- await asyncio.sleep(1)
565
+ await sleep(1)
174
566
  except Exception:
175
567
  pass
176
568
  await orch.browser.wait_for_selector('input[readonly]', timeout=15, step=4, action='date_input')
177
569
  await orch.browser.click_selector_with_fallback(4, 'date_input')
178
- await asyncio.sleep(1)
570
+ await sleep(1)
179
571
  return
572
+ except PrepareError as exc:
573
+ if exc.state == STATE_EXISTING:
574
+ raise
575
+ last_state, last_msg = exc.state, str(exc)
576
+ _safe_log(orch, f' ⚠️ 预约页准备第 {attempt + 1}/{attempts} 次失败({last_state}): {last_msg[:140]}')
577
+ except Exception as exc: # noqa: BLE001 —— 任何页面异常都不许把循环打死
578
+ last_state, last_msg = STATE_PAGE_ERROR, f'{type(exc).__name__}: {str(exc)[:140]}'
579
+ _safe_log(orch, f' ⚠️ 预约页准备第 {attempt + 1}/{attempts} 次失败(page_error): {last_msg[:140]}')
580
+ if attempt < attempts - 1:
581
+ await sleep(retry_delay)
582
+ # 2026-11-19 用户口径:预约页进不去时,先看 hub 的预约卡片再决定(⛔ 不要因为预约页报错就判失败)
583
+ if last_state in (STATE_NO_DELIVERY_OPTION, STATE_PAGE_ERROR):
584
+ try:
585
+ hub = await self.driver.probe_hub_appointment()
586
+ if hub.get('exists'):
587
+ _safe_log(orch, f' 📋 hub 显示已有预约:{hub.get("date") or "?"} {hub.get("slot") or ""}(预约页报错,改由 hub 判定)')
588
+ setattr(orch, '_appt_existing_info', {k: hub.get(k, '') for k in ('date', 'slot', 'text')})
589
+ return STATE_EXISTING
590
+ except Exception:
591
+ pass
592
+ raise PrepareError(last_state, f'预约页准备失败({attempts} 次,最后状态={last_state}):{last_msg}')
593
+
594
+
595
+ def _safe_log(orch, msg: str) -> None:
596
+ try:
597
+ orch._log(msg)
598
+ except Exception:
599
+ pass
600
+
601
+
602
+ def _bump_page_check(orch) -> int:
603
+ n = int(getattr(orch, '_appt_page_checks', 0)) + 1
604
+ setattr(orch, '_appt_page_checks', n)
605
+ return n
606
+
607
+
608
+ # ══════════════════════════════════════════════════════════════════════════════
609
+ # 页面驱动:状态机只认这组原语(测试用假 driver 顶替,零真实店铺)
610
+ # ══════════════════════════════════════════════════════════════════════════════
611
+ class OrchestratorDriver:
612
+ """把 orchestrator 的页面动作收敛成状态机需要的几个原语。
613
+
614
+ · `prepare_page`:进预约页/选运输方式/开日历(失败抛 PrepareError 带状态)
615
+ · `reload_page`:**刷新当前 tab**(page.reload,⛔ 不新开标签页)
616
+ · `today` / `checks`:时钟与"页面检查次数"
617
+ · `calendar_state` / `scan_view` / `align_month`:日历状态、整月逐日状态、翻到指定月
618
+ · `book_day`:提交某天(range=严格目标日;available_days=今天+N 天偏移语义)
619
+ """
620
+
621
+ def __init__(self, orch, *, pacing: Optional[Pacing] = None):
622
+ self.orch = orch
623
+ self.pacing = pacing or Pacing()
624
+
625
+ # ---- 日志 / 计数 ----
626
+ def log(self, msg: str) -> None:
627
+ _safe_log(self.orch, msg)
628
+
629
+ def checks(self) -> int:
630
+ return int(getattr(self.orch, '_appt_page_checks', 0))
631
+
632
+ async def today(self) -> date:
633
+ try:
634
+ return (await self.orch._platform_today()).date()
635
+ except Exception:
636
+ return datetime.now().date()
637
+
638
+ # ---- 页面生命周期 ----
639
+ async def prepare_page(self) -> None:
640
+ await prepare_appointment_page(self.orch,
641
+ attempts=self.pacing.prepare_attempts,
642
+ retry_delay=self.pacing.prepare_retry_sec,
643
+ sleep=self.pacing.sleep)
644
+
645
+ async def probe_hub_appointment(self) -> dict:
646
+ """从 **hub 页**判断是否已有预约(2026-11-19 用户口径)。
647
+
648
+ 背景:预约页(appointment-v2)在平台繁忙/改版时大概率进不去(Algo salió mal /
649
+ Tenemos más tráfico),拿它判断"是否已预约"会失败;而 hub 页能看到预约卡片。
650
+ 做法:导航到 `…/inbounds/<shipment>/hub-v2`,dump 文本,识别 Cancelar reserva /
651
+ Reserva de cita / Cita programada 等卡片;返回 {exists, date, slot, text}。
652
+ ⚠️ 只读(navigate + innerText),不点任何写按钮。
653
+ """
654
+ try:
655
+ sid = str(getattr(getattr(self.orch, 'state', None), 'shipment_id', '') or '')
656
+ if not sid:
657
+ return {'exists': False}
658
+ base = str(getattr(O, 'ML_BASE_URL', 'https://vendedores.mercadolibre.com.mx') or 'https://vendedores.mercadolibre.com.mx').rstrip('/')
659
+ url = f'{base}/shipping/inbounds/{sid}/hub-v2'
660
+ page = self.orch.browser.page
661
+ await page.goto(url, wait_until='domcontentloaded', timeout=60000)
662
+ await asyncio.sleep(3.0)
663
+ text = str(await page.evaluate('() => (document.body ? document.body.innerText : "")') or '')
664
+ if not text:
665
+ return {'exists': False, 'url': url}
666
+ exists = bool(re.search(r'Cancelar reserva|Reserva de cita|Cita programada|Cita confirmada|ya (tienes|tiene) una (cita|reserva)', text, re.I))
667
+ info = {'exists': exists, 'url': url, 'text': text[:600]}
668
+ if exists:
669
+ parsed = parse_existing_appointment(text)
670
+ info.update({'date': parsed.get('date', ''), 'slot': parsed.get('slot', '')})
671
+ return info
180
672
  except Exception as exc:
181
- last = exc
182
- orch._log(f' ⚠️ 预约页准备第 {attempt + 1}/3 次失败: {str(exc)[:100]}')
183
- await asyncio.sleep(3)
184
- raise RuntimeError(f'预约页准备失败:{last}')
185
-
186
-
187
- async def calendar_month_state(orch) -> dict:
188
- return await orch._calendar_state()
189
-
190
-
191
- async def find_date_cell(orch, target: date) -> dict:
192
- """返回目标 date 的 {found,idx,disabled},必要时翻月。"""
193
- target_month = target.month - 1
194
- target_year = target.year
195
- for _ in range(4):
196
- st = await calendar_month_state(orch)
197
- header = (st.get('header') or '').lower()
198
- months = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre']
199
- vis = [i for i, m in enumerate(months) if m in header]
200
- yr = year_of(header)
201
- if target_month in vis and (yr is None or target_year == yr):
202
- r = await orch.browser.page.evaluate(DATE_CELL_JS, target.isoformat())
203
- return r if isinstance(r, dict) else json.loads(r)
204
- await orch._flip_month(st, target_month, target_year)
205
- await asyncio.sleep(0.8)
206
- return {'found': False, 'reason': 'flip_failed'}
207
-
208
-
209
- async def scan_available_days(orch, need: int, max_months: int = 4) -> dict:
210
- await prepare_appointment_page(orch)
211
- collected = {}; order = []; selected = []
212
- for _ in range(max_months):
213
- r = await orch.browser.page.evaluate(SCAN_DAYS_JS)
214
- r = r if isinstance(r, dict) else json.loads(r)
215
- for item in r.get('dates') or []:
216
- d = item.get('date')
217
- if not d or d in collected:
673
+ return {'exists': False, 'error': f'{type(exc).__name__}: {str(exc)[:120]}'}
674
+
675
+ async def calendar_has_choices(self) -> bool:
676
+ """页面当前是否有可选日 / 可选时段可见(即使还没被选中)。刷新前复核用。"""
677
+ try:
678
+ return bool(await self.orch.browser.page.evaluate("""() => {
679
+ const days = [...document.querySelectorAll('div.day')];
680
+ for (const d of days) {
681
+ const cls = String(d.className || '');
682
+ const dis = d.getAttribute('aria-disabled');
683
+ if (dis === 'true' || /disabled/i.test(cls)) continue;
684
+ if (/^\\d+$/.test((d.textContent || '').trim())) return true;
685
+ }
686
+ if ([...document.querySelectorAll('div.hour')].length > 0) return true;
687
+ const cards = document.querySelectorAll('.andes-card');
688
+ for (const c of cards) { if (/Confirmar/i.test(c.innerText || '')) return true; }
689
+ return false;
690
+ }"""))
691
+ except Exception:
692
+ return False
693
+
694
+ async def has_selection_or_existing(self) -> bool:
695
+ """页面是否处于「人工/自动选择进行中」或「已有预约」状态(⛔ 此时禁止刷新)。
696
+
697
+ 2026-11-19 用户实测:日历已出现、时间已选中,但状态机下一轮判成"无号"就 reload,
698
+ 把还没点确认的选择整个刷掉(浪费一次放号)。判据(任一):
699
+ · 有 Cancelar reserva 按钮(已有预约)
700
+ · 只读日期输入框已写入具体日期/时间(如 "20 de noviembre, 9:45 hs")
701
+ · 日历有选中日(div.day 带 selected/active)或时段带 selected/active
702
+ """
703
+ try:
704
+ return bool(await self.orch.browser.page.evaluate("""() => {
705
+ if ([...document.querySelectorAll('button')].some(b => /Cancelar reserva/i.test(b.innerText || ''))) return true;
706
+ const inputs = [...document.querySelectorAll('input[readonly]')];
707
+ if (inputs.some(i => \\d{1,2}\\s+de\\s+[a-záéíóú]+.*\\d{1,2}[::]\\d{2}/i.test(String(i.value || '')))) return true;
708
+ if (document.querySelector('div.day.selected, div.day--selected, .day.selected, .focus-ui-datepicker__day--selected')) return true;
709
+ const hours = [...document.querySelectorAll('div.hour')].filter(h => /selected|active/i.test(String(h.className || '')));
710
+ if (hours.length) return true;
711
+ return false;
712
+ }"""))
713
+ except Exception:
714
+ return False
715
+
716
+ async def reload_page(self) -> None:
717
+ """刷新当前 tab(同一标签页 reload;⛔ 不 new_page —— 每店 5 tab 并发,不能占更多)。"""
718
+ page = self.orch.browser.page
719
+ await page.reload(wait_until='domcontentloaded', timeout=30000)
720
+ await self.pacing.sleep(1.0)
721
+
722
+ # ---- 日历读取 ----
723
+ async def calendar_state(self) -> dict:
724
+ st = await self.orch._calendar_state()
725
+ return st if isinstance(st, dict) else {}
726
+
727
+ async def scan_view(self) -> dict:
728
+ raw = await self.orch.browser.page.evaluate(SCAN_DAYS_JS)
729
+ return raw if isinstance(raw, dict) else json.loads(raw)
730
+
731
+ async def align_month(self, year: int, month: int) -> None:
732
+ """把日历停到 `year-month`(`_flip_month` 的 fiber 直达优先;失败抛 PageError)。"""
733
+ last = ''
734
+ for _ in range(3):
735
+ st = await self.calendar_state()
736
+ header = (st or {}).get('header') or ''
737
+ got = parse_header_month(header)
738
+ if got is None:
739
+ # 日历没打开/还没渲染 ⇒ 不猜月份、更不乱翻月:交状态机刷新自愈
740
+ raise PageError(f'日历未打开或 header 不可解析(header={header!r})')
741
+ if got == (int(year), int(month)):
742
+ return
743
+ try:
744
+ new_st = await self.orch._flip_month(st, int(month) - 1, int(year))
745
+ except Exception as exc:
746
+ raise PageError(f'翻月失败(→ {year}-{month:02d}):{str(exc)[:160]}') from exc
747
+ got = parse_header_month((new_st or {}).get('header') or '')
748
+ if got == (int(year), int(month)):
749
+ return
750
+ last = f'{(new_st or {}).get("header") or "?"}'
751
+ await self.pacing.sleep(0.8)
752
+ raise PageError(f'翻月未到达目标月 {year}-{month:02d}(最后视图={last or "?"})')
753
+
754
+ # ---- 预约 ----
755
+ async def book_day(self, day: date, *, today: date, exact: bool,
756
+ time_from: str = '', time_to: str = '',
757
+ time_ranges: Optional[list[dict]] = None,
758
+ min_lead_hours: float = 0) -> dict:
759
+ """提交某天;成功返回 {date, slot},失败抛 BookingError(kind 即 dateStates 口径)。"""
760
+ offset = (day - today).days
761
+ try:
762
+ if not exact:
763
+ # available_days 语义(旧行为):每次尝试重新进预约页,再按"今天+N 天"偏移选日
764
+ _bump_page_check(self.orch)
765
+ await self.orch.browser.visit_plan_page('appointment-v2',
766
+ self.orch.state.shipment_id, step=4)
767
+ # 与 FULL 步骤4、其他抢预约任务共用同店预约锁:只串行化"提交预约",不占整个流程
768
+ self.orch._acquire_store_step4_lock(force=True)
769
+ try:
770
+ kwargs: dict[str, Any] = {'hour_idx': 0, 'date_offset': offset,
771
+ 'time_from': time_from, 'time_to': time_to,
772
+ 'time_ranges': time_ranges, 'min_lead_hours': min_lead_hours}
773
+ if exact:
774
+ # range 模式严格目标日期:只点运营给的日期,⛔ 不允许 _pick_date 跳到范围外
775
+ kwargs['exact_date'] = day.isoformat()
776
+ await self.orch._book_appointment(**kwargs)
777
+ finally:
778
+ self.orch._release_store_step4_lock()
779
+ except Exception as exc:
780
+ raise BookingError(classify_booking_error(str(exc)), str(exc)) from exc
781
+ actual = str(getattr(self.orch, '_last_booked_date', '') or day.isoformat())
782
+ slot = str(getattr(self.orch, '_last_booked_slot', '') or 'first')
783
+ if exact and actual != day.isoformat():
784
+ raise BookingError('selectable_booking_failed',
785
+ f'严格日期校验失败:目标 {day.isoformat()},实际页面选中 {actual}(不提交)')
786
+ return {'date': actual, 'slot': slot}
787
+
788
+
789
+ # ══════════════════════════════════════════════════════════════════════════════
790
+ # 值守循环(显式状态机 + 滚动游标;循环本身没有最大轮数)
791
+ # ══════════════════════════════════════════════════════════════════════════════
792
+ class AppointmentLoop:
793
+ """FULL 预约值守循环。
794
+
795
+ · `run()` 的返回值与旧 run_task 的 result 形状兼容(status/date/slot/dateStates/summary)。
796
+ · 唯一正常终止:抢到(booked)。页面显示已有预约 ⇒ 按旧口径返回 failed(不重复抢)。
797
+ · `max_rounds` 仅供测试注入(生产默认 None = 无上限);`Pacing.sleep` 可注入 ⇒ 测试 0 延迟。
798
+ """
799
+
800
+ def __init__(self, driver, *, date_mode: str = 'range',
801
+ from_date: Optional[date] = None, to_date: Optional[date] = None,
802
+ weekdays: Optional[set[int]] = None,
803
+ time_from: str = '', time_to: str = '',
804
+ rule_spec: Optional[dict] = None,
805
+ rule_min_lead_hours: float = 0,
806
+ available_days: int = 0,
807
+ pacing: Optional[Pacing] = None,
808
+ max_scan_months: int = MAX_SCAN_MONTHS,
809
+ max_rounds: Optional[int] = None,
810
+ task: Optional[dict] = None):
811
+ if date_mode not in ('range', 'available_days', 'rule'):
812
+ raise ValueError(f'未知 dateMode:{date_mode}')
813
+ self.driver = driver
814
+ self.task = dict(task or {})
815
+ self.existing_info: dict = {}
816
+ self.existing_cancelled = False
817
+ self.date_mode = date_mode
818
+ self.from_date = from_date
819
+ self.to_date = to_date
820
+ self.weekdays = frozenset(int(x) for x in (weekdays or ()))
821
+ self.time_from = time_from
822
+ self.time_to = time_to
823
+ self.need = max(1, int(available_days or 0))
824
+ self.rule_spec = rule_spec if isinstance(rule_spec, dict) else None
825
+ self.rule_min_lead_hours = float(rule_min_lead_hours or 0)
826
+ self.rule_windows: dict[str, list[dict]] = {}
827
+ self.pacing = pacing or Pacing()
828
+ self.max_scan_months = max(1, int(max_scan_months))
829
+ self.max_rounds = max_rounds
830
+
831
+ self.today: date = date.today()
832
+ self.cursor: Optional[ScanCursor] = None
833
+ self.targets: list[date] = []
834
+ self._target_set: set[str] = set()
835
+ self._max_target_idx: Optional[int] = None
836
+
837
+ self.state = STATE_PREPARING
838
+ self.round_no = 0
839
+ self.refreshes = 0
840
+ self.date_states: dict[str, str] = {}
841
+ self.saw_selectable = False
842
+ self.tried: set[str] = set()
843
+ self.trace: list[dict] = [] # 状态迁移轨迹(测试/复盘用)
844
+ self.events: list[dict] = [] # 已输出的 JSONL 事件(测试/复盘用)
845
+ self._consecutive_errors = 0
846
+
847
+ # ── 结果/事件 ──────────────────────────────────────────────────────────
848
+ def _result_booked(self, actual: str, slot: str, summary: str = '') -> dict:
849
+ self._transition(STATE_BOOKED, f'{actual} {slot}')
850
+ self._emit_progress()
851
+ return {'status': 'booked', 'date': actual, 'slot': slot,
852
+ 'dateStates': dict(self.date_states), 'cycles': self.round_no,
853
+ 'refreshes': self.refreshes, 'windowMode': self.date_mode,
854
+ 'summary': summary or f'{actual} {slot} 预约成功'}
855
+
856
+ def _result_existing(self) -> dict:
857
+ # 2026-11-19 用户定调:**「已有预约」不是失败**(平台本来就有预约=目标已达成)。
858
+ # 改为成功收口(booked/succeeded),保留平台已有日期/时段;不在窗口时只作提示,不改判失败。
859
+ self._transition(STATE_EXISTING, 'page-shows-existing-appointment')
860
+ info = self.existing_info or {}
861
+ date_iso = str(info.get('date') or '')
862
+ slot = str(info.get('slot') or '')
863
+ when = f'{date_iso} {slot}'.strip() or '平台已有预约(日期/时段未解析)'
864
+ summary = f'平台已有预约:{when}(未重复抢,视为已预约)'
865
+ try:
866
+ if date_iso and not window_matches(date_iso, slot, self.task):
867
+ summary += ';不在本次窗口,如需改约请用改约流程'
868
+ except Exception:
869
+ pass
870
+ return {'status': 'booked', 'date': date_iso, 'slot': slot,
871
+ 'dateStates': dict(self.date_states), 'cycles': self.round_no,
872
+ 'refreshes': self.refreshes, 'windowMode': self.date_mode,
873
+ 'existingDate': date_iso, 'existingSlot': slot, 'summary': summary}
874
+
875
+ async def _handle_existing(self) -> Optional[dict]:
876
+ """页面出现已有预约时:
877
+ · 日期/时段已满足任务窗口 ⇒ 视为成功(不重复抢)
878
+ · intent=reschedule 且不满足 ⇒ 取消旧预约后继续按新窗口抢(只取消一次)
879
+ · 其它 ⇒ 旧口径收口(failed + existingDate/existingSlot)
880
+ """
881
+ orch = getattr(self.driver, 'orch', None)
882
+ self.existing_info = dict(getattr(orch, '_appt_existing_info', {}) or {})
883
+ info = self.existing_info
884
+ self.driver.log(f' 📋 页面已有预约:{info.get("date") or "?"} {info.get("slot") or ""}'
885
+ f'(intent={self.task.get("intent") or "grab"})')
886
+ if info.get('date') and window_matches(str(info['date']), str(info.get('slot') or ''), self.task):
887
+ self.driver.log(' ✅ 已有预约已满足任务窗口 ⇒ 不重复抢,直接判定成功')
888
+ return self._result_booked(
889
+ str(info['date']), str(info.get('slot') or ''),
890
+ summary=f'改约确认:平台已有预约 {info["date"]} {info.get("slot") or ""},且满足任务窗口(未重复预约)')
891
+ if str(self.task.get('intent') or '') == 'reschedule' and not self.existing_cancelled:
892
+ if orch is None:
893
+ return self._result_failed('改约失败:无法访问 orchestrator 取消入口')
894
+ self.driver.log(' 🔁 改约:已有预约与窗口不符 ⇒ 先取消旧预约,再按新窗口抢号')
895
+ ok = await orch._safe_cancel_appointment()
896
+ if not ok:
897
+ return self._result_failed('改约失败:取消旧预约未成功,请人工在平台取消后重试')
898
+ self.existing_cancelled = True
899
+ setattr(orch, '_appt_existing_info', {})
900
+ self.driver.log(' ✅ 旧预约已取消,继续值守抢新窗口')
901
+ return None
902
+ return self._result_existing()
903
+
904
+ def _result_failed(self, summary: str) -> dict:
905
+ return {'status': 'failed', 'dateStates': dict(self.date_states), 'cycles': self.round_no,
906
+ 'refreshes': self.refreshes, 'windowMode': self.date_mode, 'summary': summary}
907
+
908
+ def _transition(self, state: str, reason: str = '') -> None:
909
+ self.trace.append({'round': self.round_no, 'from': self.state, 'to': state,
910
+ 'reason': reason})
911
+ self.driver.log(f' 🔀 {self.state} → {state}({reason or "-"})'
912
+ + (f'|下一步:{STATE_NEXT_STEP[state]}' if state in STATE_NEXT_STEP else ''))
913
+ self.state = state
914
+
915
+ def _emit(self, event: str, summary: str = '') -> None:
916
+ """输出事件。**形状保持旧口径**:core 四键 + cycle 的既有可选 summary。"""
917
+ payload = {'event': event, 'cycle': self.round_no, 'checks': self.driver.checks(),
918
+ 'dateStates': dict(self.date_states)}
919
+ if summary:
920
+ payload['summary'] = summary
921
+ self.events.append(payload)
922
+ print(json.dumps(payload, ensure_ascii=False), flush=True)
923
+
924
+ def _emit_progress(self) -> None:
925
+ self._emit('progress')
926
+
927
+ def _emit_cycle(self, reason: str = '') -> None:
928
+ self._emit('cycle', f'{self.state}: {reason}' if reason else self.state)
929
+
930
+ # ── 刷新(A/B/page_error 的唯一出口)─────────────────────────────────────
931
+ async def _refresh_and_wait(self, state: str, reason: str) -> bool:
932
+ """刷新该 tab 的页面 → 抖动等待 → 游标重置到今天 → 回到 PREPARING。
933
+
934
+ 返回 True=已刷新;False=因页面处于选择/已预约状态而**暂缓刷新**(2026-11-19 修复):
935
+ ⛔ 判断过程中(日历已出现、日期/时间已选中、已有预约)绝不强制 reload,
936
+ 否则会把还没走完的预约步骤整个刷掉 == 浪费一次放号。
937
+ """
938
+ if self.state != state:
939
+ self._transition(state, reason)
940
+ # 刷新前最后一道保险:页面已有选中/已预约 ⇒ 不刷新,稍等后返回让主循环再判断
941
+ try:
942
+ if await self.driver.has_selection_or_existing():
943
+ self.driver.log(' ⏸️ 页面已有选中日期/时间或已有预约 ⇒ 暂不刷新(避免刷掉未完成的预约操作)')
944
+ await self.pacing.sleep(2.0)
945
+ return False
946
+ except Exception:
947
+ pass
948
+ # 2026-11-19 二次修复:日历/时段刚渲染出来的竞态——等 1.2s 再复核一次,
949
+ # 有可选日/可选时段就绝不刷新(交回扫描/提交),避免"刚刷出日历就被刷掉"。
950
+ try:
951
+ await asyncio.sleep(1.2)
952
+ view = await self.driver.scan_view()
953
+ self._absorb_view(view)
954
+ cands = self._candidates(view)
955
+ if cands or await self.driver.calendar_has_choices():
956
+ self.driver.log(' ⏸️ 刷新前复核:日历/时段已出现 ⇒ 不刷新(改为继续提交/判断)')
957
+ return False
958
+ except Exception:
959
+ pass
960
+ self.refreshes += 1
961
+ try:
962
+ await self.driver.reload_page()
963
+ except Exception as exc: # noqa: BLE001 —— 刷新失败也不退出:下一轮 prepare 会重新进页面
964
+ self.driver.log(f' ⚠️ 刷新预约页失败(下一轮重新进入预约页兜底):{str(exc)[:160]}')
965
+ self.today = await self.driver.today()
966
+ self.cursor.reset(self.today) # 刷新后游标重置到今天(可能出现新可选日)
967
+ self.tried.clear() # 新窗口 ⇒ 已尝试日重新可试
968
+ delay = self.pacing.refresh_delay()
969
+ self.driver.log(f' ⏳ 刷新后等待 {delay:.1f}s(20–40s 抖动防风控)→ 游标重置到 '
970
+ f'{self.cursor.as_dict()["windowStart"]},从今天重扫')
971
+ self._emit_cycle(f'{reason}|refreshes={self.refreshes}|wait={delay:.1f}s')
972
+ await self.pacing.sleep(delay)
973
+ return True
974
+
975
+ # ── 日期目标 ───────────────────────────────────────────────────────────
976
+ def _min_lead_days(self) -> int:
977
+ """最早可预约日 = 今天 + N 天。默认 1;巴西站点平台规则 = 至少 2 天后才可选。
978
+
979
+ env `ARGENT_APPOINTMENT_MIN_DAY` 可覆盖(运维/压测用);否则按店铺名站点判定。
980
+ """
981
+ raw = str(os.environ.get('ARGENT_APPOINTMENT_MIN_DAY') or '').strip()
982
+ if raw.isdigit():
983
+ return max(1, int(raw))
984
+ store = str((self.task or {}).get('store') or '')
985
+ return 3 if '巴西' in store else 1
986
+
987
+ def _compute_targets(self, today: date) -> list[date]:
988
+ """range 模式的目标日 = [max(dateFrom, 今天+N) .. dateTo] ∩ 星期过滤(N=站点最小提前量)。"""
989
+ if self.date_mode == 'rule':
990
+ if not self.rule_spec:
991
+ raise ValueError('rule 模式缺少规则配置')
992
+ allowed = compile_rule_dates(self.rule_spec, today)
993
+ self.rule_windows = allowed
994
+ lead = self._min_lead_days()
995
+ cutoff = today + timedelta(days=lead)
996
+ targets = [date.fromisoformat(k) for k in sorted(allowed) if date.fromisoformat(k) >= cutoff]
997
+ self.driver.log(f' 📐 时间规则:今天(墨西哥)={today.isoformat()} · 规则可约 {len(allowed)} 天 · 实际目标 {len(targets)} 天(平台最早=今天+{lead}天)')
998
+ return targets
999
+ if not self.from_date or not self.to_date:
1000
+ raise ValueError('range 模式需要 dateFrom/dateTo')
1001
+ targets: list[date] = []
1002
+ lead = self._min_lead_days()
1003
+ self.driver.log(f' 📅 最早可约日 = 今天+{lead} 天({"巴西站点规则" if lead >= 3 else "默认"})')
1004
+ d = max(self.from_date, today + timedelta(days=lead))
1005
+ while d <= self.to_date:
1006
+ if (not self.weekdays) or d.isoweekday() in self.weekdays:
1007
+ targets.append(d)
1008
+ d += timedelta(days=1)
1009
+ return targets
1010
+
1011
+ def _initial_states(self) -> dict[str, str]:
1012
+ if self.date_mode in ('range', 'rule'):
1013
+ return {d.isoformat(): 'pending' for d in self.targets}
1014
+ return {}
1015
+
1016
+ # ── 主循环 ─────────────────────────────────────────────────────────────
1017
+ async def run(self) -> dict:
1018
+ self.today = await self.driver.today()
1019
+ self.cursor = ScanCursor.at(self.today)
1020
+ self.driver.log(f' 🔁 值守循环启动:mode={self.date_mode}|today={self.today.isoformat()}'
1021
+ f'|盲扫上限={self.max_scan_months}个月|刷新抖动='
1022
+ f'{self.pacing.refresh_min_sec:g}–{self.pacing.refresh_max_sec:g}s'
1023
+ f'|循环无最大轮数(运营 stopRequestedAt 停止)')
1024
+ if self.date_mode in ('range', 'rule'):
1025
+ self.targets = self._compute_targets(self.today)
1026
+ if not self.targets:
1027
+ return self._result_failed('当前时间规则下没有可预约日期(可能已过今日窗口/全部被跳过)')
1028
+ self._target_set = {d.isoformat() for d in self.targets}
1029
+ self._max_target_idx = month_index(self.targets[-1].year, self.targets[-1].month)
1030
+
1031
+ while True:
1032
+ self.round_no += 1
1033
+ if self.date_mode == 'rule':
1034
+ self.today = await self.driver.today()
1035
+ self.targets = self._compute_targets(self.today)
1036
+ self._target_set = {d.isoformat() for d in self.targets}
1037
+ self._max_target_idx = month_index(self.targets[-1].year, self.targets[-1].month) if self.targets else None
1038
+ self.date_states = self._initial_states()
1039
+ if self.date_mode == 'rule' and not self.targets:
1040
+ await self._refresh_and_wait(STATE_CALENDAR_ALL_DISABLED, 'rule-no-targets')
218
1041
  continue
219
- collected[d] = 'disabled' if item.get('disabled') else 'selectable'
220
- order.append(d)
221
- if not item.get('disabled'):
222
- selected.append(d)
223
- if len(selected) >= need:
224
- break
225
- if len(selected) >= need:
226
- break
227
- import re
228
- header = (r.get('header') or '').lower()
229
- months = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','octubre','noviembre','diciembre']
230
- vis = [i for i, m in enumerate(months) if m in header]
231
- yr = year_of(header)
232
- if not vis or yr is None:
233
- break
234
- nm = max(vis) + 1
235
- ny = yr + (1 if nm > 11 else 0)
236
- nm = nm % 12
237
- await orch._flip_month(await calendar_month_state(orch), nm, ny)
238
- await asyncio.sleep(0.8)
239
- return {'states': collected, 'order': order, 'selected': selected[:need]}
240
-
241
-
242
- def year_of(header: str):
243
- import re
244
- m = re.search(r'(\d{4})', header or '')
245
- return int(m.group(1)) if m else None
1042
+ self.saw_selectable = False
1043
+ try:
1044
+ result = await self._run_round()
1045
+ if result is not None:
1046
+ return result
1047
+ self._consecutive_errors = 0
1048
+ except KeyboardInterrupt:
1049
+ raise # 运营停止(SIGTERM)⇒ 交 main 收尾
1050
+ except PageError as exc:
1051
+ # 平台/页面形态类:刷新继续等(不设上限)
1052
+ await self._refresh_and_wait(STATE_PAGE_ERROR, f'page-error:{str(exc)[:120]}')
1053
+ except Exception as exc: # noqa: BLE001 —— 未知内部异常:有限次后收手,别把 tab 焊死
1054
+ self._consecutive_errors += 1
1055
+ self.driver.log(f' ❌ 值守循环未预期异常({self._consecutive_errors}/'
1056
+ f'{MAX_UNEXPECTED_ERRORS}):{type(exc).__name__}: {str(exc)[:200]}')
1057
+ if self._consecutive_errors >= MAX_UNEXPECTED_ERRORS:
1058
+ return self._result_failed(
1059
+ f'值守循环连续 {self._consecutive_errors} 次未预期异常,已停止以免占死标签页:'
1060
+ f'{type(exc).__name__}: {str(exc)[:200]}')
1061
+ await self._refresh_and_wait(STATE_PAGE_ERROR,
1062
+ f'unexpected:{type(exc).__name__}')
1063
+ if self.max_rounds and self.round_no >= self.max_rounds:
1064
+ return self._result_failed(
1065
+ f'值守循环达到测试上限 max_rounds={self.max_rounds}(生产默认无上限)')
246
1066
 
1067
+ async def _run_round(self) -> Optional[dict]:
1068
+ """一轮 = 准备页面 → 滚动扫描/预约,直到抢到或窗口耗尽(耗尽由本函数内刷新)。"""
1069
+ # ── PREPARING ──
1070
+ outcome = await self._prepare_page()
1071
+ if outcome == STATE_EXISTING:
1072
+ return await self._handle_existing()
1073
+ if outcome == STATE_NOT_APPLICABLE:
1074
+ return self._result_failed('该货件无需预约:平台把预约页重定向到货件详情页(可能已处理完成/非 FULL 入仓)')
1075
+ if outcome != 'ready':
1076
+ await self._refresh_and_wait(outcome, 'prepare-failed')
1077
+ return None
1078
+ await self._align_view_to_cursor()
1079
+ self._transition(STATE_SCANNING, 'page-ready')
1080
+
1081
+ # ── SCANNING / BOOKING ──
1082
+ defer_refresh = 0
1083
+ while True:
1084
+ view = await self.driver.scan_view()
1085
+ self._absorb_view(view)
1086
+ self._emit_progress()
1087
+ cands = self._candidates(view)
1088
+ if cands:
1089
+ self.saw_selectable = True
1090
+ self._transition(STATE_BOOKING, f'{len(cands)} 个候选日')
1091
+ result = await self._try_candidates(cands)
1092
+ if result is _PASS_ENDED:
1093
+ return None
1094
+ if result is not None:
1095
+ return result
1096
+ continue # 候选都失败:页面已重开并对齐游标,继续本窗口
1097
+ if self._window_exhausted():
1098
+ # 2026-11-19:页面渲染竞态——扫描瞬间可能日历还没渲染完;刷新前再等两次
1099
+ # (各 1.2s)重扫,出现候选直接进 booking,避免"刚出现日历就被刷新"。
1100
+ late = None
1101
+ for _delay in (1.2, 1.2):
1102
+ await asyncio.sleep(_delay)
1103
+ try:
1104
+ late_view = await self.driver.scan_view()
1105
+ except Exception:
1106
+ late_view = None
1107
+ if not late_view:
1108
+ continue
1109
+ self._absorb_view(late_view)
1110
+ late = self._candidates(late_view)
1111
+ if late:
1112
+ break
1113
+ if late:
1114
+ self.saw_selectable = True
1115
+ self._transition(STATE_BOOKING, f'{len(late)} 个候选日(窗口耗尽前复核,不刷新)')
1116
+ result = await self._try_candidates(late)
1117
+ if result is _PASS_ENDED:
1118
+ return None
1119
+ if result is not None:
1120
+ return result
1121
+ continue
1122
+ # B 态:整窗口没有可选日;否则=有可选日但都点/提交失败
1123
+ terminal = (STATE_BOOKING_FAILED if self.saw_selectable
1124
+ else STATE_CALENDAR_ALL_DISABLED)
1125
+ reloaded = await self._refresh_and_wait(terminal, 'window-exhausted')
1126
+ if not reloaded:
1127
+ defer_refresh += 1
1128
+ if defer_refresh >= 3:
1129
+ # 连续暂缓 ⇒ 结束本 round(下一 round 重新检测;⛔ 绝不在这种状态下 reload)
1130
+ return None
1131
+ await self.pacing.sleep(1.0)
1132
+ continue # 页面有选中/已预约:不刷新,继续扫描判断(等操作走完)
1133
+ return None
1134
+ if not await self._advance_month():
1135
+ await self._refresh_and_wait(STATE_PAGE_ERROR, 'flip-failed')
1136
+ return None
1137
+ await self.pacing.sleep(self.pacing.scan_pause_sec)
247
1138
 
1139
+ async def _prepare_page(self) -> str:
1140
+ """PREPARING:返回 'ready' / STATE_EXISTING / 失败态(no_delivery_option/page_error)。"""
1141
+ self._transition(STATE_PREPARING, 'round-start')
1142
+ try:
1143
+ await self.driver.prepare_page()
1144
+ return 'ready'
1145
+ except PrepareError as exc:
1146
+ if exc.state == STATE_EXISTING:
1147
+ return STATE_EXISTING
1148
+ state = exc.state if exc.state in (STATE_NO_DELIVERY_OPTION, STATE_PAGE_ERROR) \
1149
+ else STATE_PAGE_ERROR
1150
+ self._transition(state, f'prepare-failed:{str(exc)[:120]}')
1151
+ return state
1152
+ except Exception as exc: # noqa: BLE001
1153
+ self._transition(STATE_PAGE_ERROR, f'prepare-error:{type(exc).__name__}')
1154
+ self.driver.log(f' ⚠️ 预约页准备异常:{type(exc).__name__}: {str(exc)[:160]}')
1155
+ return STATE_PAGE_ERROR
1156
+
1157
+ def _parse_view_month(self, view: dict) -> tuple[int, int]:
1158
+ got = parse_header_month((view or {}).get('header') or '')
1159
+ if not got:
1160
+ raise PageError(f'日历 header 不可解析(header={(view or {}).get("header")!r})')
1161
+ return got
1162
+
1163
+ async def _align_view_to_cursor(self) -> None:
1164
+ """重开页面后日历可能停在平台默认月:先按实际视图前移游标,再翻到游标月。"""
1165
+ st = await self.driver.calendar_state()
1166
+ actual = parse_header_month((st or {}).get('header') or '')
1167
+ if actual:
1168
+ self.cursor.sync(month_index(*actual))
1169
+ y, m = self.cursor.year_month
1170
+ await self.driver.align_month(y, m)
1171
+
1172
+ def _absorb_view(self, view: dict) -> None:
1173
+ """把当前视图的逐日状态吸收进 dateStates(并校验日历确实渲染了)。"""
1174
+ view_year, view_month = self._parse_view_month(view)
1175
+ dates = (view or {}).get('dates') or []
1176
+ if not dates:
1177
+ raise PageError('日历能打开但读不到任何 day 格(视图未渲染)')
1178
+ self.cursor.sync(month_index(view_year, view_month))
1179
+ tomorrow = (self.today + timedelta(days=1)).isoformat()
1180
+ if self.date_mode == 'available_days':
1181
+ for item in dates:
1182
+ iso = item.get('date')
1183
+ if not iso or iso < tomorrow:
1184
+ continue
1185
+ if iso in self.tried:
1186
+ continue # 已失败的日期保留失败口径(不被重扫的旧视图覆盖)
1187
+ self.date_states[iso] = 'disabled' if item.get('disabled') else 'selectable'
1188
+ return
1189
+ # range:只维护运营给定目标日(形状与旧实现一致),其余日期不进 dateStates
1190
+ seen: dict[str, bool] = {}
1191
+ for item in dates:
1192
+ iso = item.get('date')
1193
+ if iso:
1194
+ seen[iso] = bool(item.get('disabled'))
1195
+ for iso, label in list(self.date_states.items()):
1196
+ if label not in ('pending',):
1197
+ continue
1198
+ try:
1199
+ td = date.fromisoformat(iso)
1200
+ except ValueError:
1201
+ continue
1202
+ if (td.year, td.month) != (view_year, view_month):
1203
+ continue
1204
+ if iso not in seen:
1205
+ self.date_states[iso] = 'date_not_found'
1206
+ elif seen[iso]:
1207
+ self.date_states[iso] = 'disabled'
1208
+
1209
+ def _candidates(self, view: dict) -> list[date]:
1210
+ """当前视图里可以立刻尝试预约的日期(range 只认目标日;available_days 认可选日)。"""
1211
+ tomorrow = (self.today + timedelta(days=1)).isoformat()
1212
+ out: list[date] = []
1213
+ for item in (view or {}).get('dates') or []:
1214
+ iso = item.get('date')
1215
+ if not iso or item.get('disabled'):
1216
+ continue
1217
+ if iso < tomorrow or iso in self.tried:
1218
+ continue
1219
+ if self.date_mode in ('range', 'rule') and iso not in self._target_set:
1220
+ continue
1221
+ try:
1222
+ d = date.fromisoformat(iso)
1223
+ except ValueError:
1224
+ continue
1225
+ if self.date_mode == 'available_days' and self.weekdays \
1226
+ and d.isoweekday() not in self.weekdays:
1227
+ continue
1228
+ out.append(d)
1229
+ out.sort()
1230
+ if self.date_mode == 'available_days':
1231
+ out = out[:self.need]
1232
+ return out
1233
+
1234
+ def _window_exhausted(self) -> bool:
1235
+ """本窗口扫完了吗?available_days = 6 个月盲扫上限;range = 最远目标月。"""
1236
+ if self.date_mode == 'range':
1237
+ return self._max_target_idx is not None and self.cursor.idx >= self._max_target_idx
1238
+ return self.cursor.flips >= (self.max_scan_months - 1)
1239
+
1240
+ async def _advance_month(self) -> bool:
1241
+ """向后翻一个月(滚动游标只前进);失败返回 False(调用方按 page_error 刷新)。"""
1242
+ y, m = self.cursor.year_month
1243
+ ny, nm = (y + 1, 1) if m >= 12 else (y, m + 1)
1244
+ try:
1245
+ await self.driver.align_month(ny, nm)
1246
+ except Exception as exc: # noqa: BLE001
1247
+ self.driver.log(f' ⚠️ 翻月失败(→ {ny}-{nm:02d}):{str(exc)[:160]}')
1248
+ return False
1249
+ self.cursor.advance()
1250
+ return True
1251
+
1252
+ async def _try_candidates(self, cands: list[date]) -> Any:
1253
+ """按序尝试候选日。
1254
+
1255
+ · 成功 ⇒ 返回 booked 结果 dict;
1256
+ · 全部失败但页面仍就绪 ⇒ 返回 None(本轮继续扫本窗口);
1257
+ · 页面准备失败并已刷新(本轮不能再扫)⇒ 返回 `_PASS_ENDED`。
1258
+ """
1259
+ exact = self.date_mode in ('range', 'rule')
1260
+ for day in cands:
1261
+ self._emit_progress()
1262
+ try:
1263
+ booked = await self.driver.book_day(day, today=self.today, exact=exact,
1264
+ time_from=self.time_from, time_to=self.time_to,
1265
+ time_ranges=self.rule_windows.get(day.isoformat()) if self.date_mode == 'rule' else None,
1266
+ min_lead_hours=self.rule_min_lead_hours if self.date_mode == 'rule' else 0)
1267
+ except BookingError as exc:
1268
+ kind, msg = exc.kind, str(exc)
1269
+ except Exception as exc: # noqa: BLE001 —— 任何失败都按 dateStates 口径归类
1270
+ kind, msg = classify_booking_error(str(exc)), str(exc)
1271
+ else:
1272
+ actual = str(booked.get('date') or day.isoformat())
1273
+ slot = str(booked.get('slot') or 'first')
1274
+ self.date_states[actual] = 'booked'
1275
+ return self._result_booked(actual, slot)
1276
+
1277
+ self.date_states[day.isoformat()] = kind
1278
+ self.tried.add(day.isoformat())
1279
+ self._transition(STATE_BOOKING_FAILED, f'{day.isoformat()}:{kind}')
1280
+ self.driver.log(f' ⚠️ {day.isoformat()} 预约失败({kind}):{msg[:160]}')
1281
+ self._emit_progress()
1282
+ # 预约尝试会改动页面状态 ⇒ 重开页面(旧 range 实现同样 prepared=False 重开),
1283
+ # 失败则本轮结束、由状态机走刷新;成功则继续本窗口剩余候选。
1284
+ outcome = await self._prepare_page()
1285
+ if outcome == STATE_EXISTING:
1286
+ return await self._handle_existing()
1287
+ if outcome != 'ready':
1288
+ await self._refresh_and_wait(outcome, 'prepare-after-booking-failed')
1289
+ return _PASS_ENDED
1290
+ try:
1291
+ await self._align_view_to_cursor()
1292
+ except PageError as exc:
1293
+ await self._refresh_and_wait(STATE_PAGE_ERROR, f'align-failed:{str(exc)[:120]}')
1294
+ return _PASS_ENDED
1295
+ self._transition(STATE_SCANNING, 'page-ready')
1296
+ return None
1297
+
1298
+
1299
+ # ══════════════════════════════════════════════════════════════════════════════
1300
+ # run_task:任务校验/浏览器装配/锁 —— 值守循环本体在 AppointmentLoop
1301
+ # ══════════════════════════════════════════════════════════════════════════════
248
1302
  async def run_task(task: dict) -> dict:
249
1303
  store = task.get('store') or ''
250
1304
  if not store:
@@ -261,12 +1315,14 @@ async def run_task(task: dict) -> dict:
261
1315
  if not is_mx:
262
1316
  return {'status': 'failed', 'summary': f'抢预约当前仅支持墨西哥站(MLM);{store} 属于 {platform},暂未适配,请勿执行'}
263
1317
  date_mode = task.get('dateMode') or 'range'
1318
+ rule_snapshot = task.get('ruleSnapshot') if isinstance(task.get('ruleSnapshot'), dict) else None
1319
+ rule_spec = (rule_snapshot or {}).get('spec') if rule_snapshot else None
1320
+ if rule_spec:
1321
+ date_mode = 'rule'
264
1322
  weekdays = {int(x) for x in (task.get('weekdays') or []) if str(x).isdigit() and 1 <= int(x) <= 7}
265
1323
  time_from = str(task.get('timeFrom') or '').strip()
266
1324
  time_to = str(task.get('timeTo') or '').strip()
267
1325
 
268
- def weekday_allowed(d: date) -> bool:
269
- return (not weekdays) or d.isoweekday() in weekdays
270
1326
  from_date = iso_day(task['dateFrom']) if date_mode == 'range' else None
271
1327
  to_date = iso_day(task['dateTo']) if date_mode == 'range' else None
272
1328
  cfg = O.load_config()
@@ -275,6 +1331,8 @@ async def run_task(task: dict) -> dict:
275
1331
  args = SimpleNamespace(record_id='', sku=task.get('sku', ''), qty=task.get('quantity'), box=task.get('boxCount'),
276
1332
  shipment_id=task.get('shipmentNo') or '', store_name=store, no_lock=True)
277
1333
  orch = O.Orchestrator(cfg, sel, args)
1334
+ global _ORCH
1335
+ _ORCH = orch
278
1336
  orch.state.store_name = store
279
1337
  orch.state.record_id = ''
280
1338
  orch.state.sku = str(task.get('sku') or '')
@@ -282,13 +1340,42 @@ async def run_task(task: dict) -> dict:
282
1340
  orch.state.box = str(task.get('boxCount') or '')
283
1341
  if task.get('shipmentNo'):
284
1342
  orch.state.shipment_id = str(task['shipmentNo'])
1343
+ # 槽位锁:同店并行执行位(每店 N 个;N 由 worker 的 STORE_CONCURRENCY 决定)
1344
+ slot_no = int(task.get('slotNo') or 0)
1345
+ if not orch.acquire_appt_slot_lock(slot_no):
1346
+ return {'status': 'failed',
1347
+ 'summary': f'同店槽位 {slot_no} 已被占用(先让位,稍后重新入队)'}
285
1348
  try:
286
- if not orch.acquire_store_executor_lock():
287
- return {'status': 'failed', 'summary': f'同店执行者锁冲突:{orch._store_exec_holder}'}
288
- _dl, port = orch._open_store()
289
- if not port:
290
- return {'status': 'failed', 'summary': 'CDP 端口未发现(店铺窗口未就绪)'}
1349
+ # 开店权(会换端口、踢掉别人的标签页)⇒ 同店同一时刻只允许一个进程真开窗口;
1350
+ # 窗口新鲜时**直接复用** cdp-port-map.json 里的端口,不再重复 open。
1351
+ got_open_lock = orch.acquire_store_executor_lock()
1352
+ try:
1353
+ dl_dir, port = orch.read_store_window()
1354
+ if got_open_lock and not port:
1355
+ _dl, port = orch._open_store()
1356
+ if not port:
1357
+ return {'status': 'failed', 'summary': 'CDP 端口未发现(店铺窗口未就绪)'}
1358
+ orch.remember_store_window(port, str(_dl or ''))
1359
+ dl_dir = _dl
1360
+ if not port:
1361
+ # 别的进程正在开店:等它把端口写进 map(最多 60s)
1362
+ for _ in range(60):
1363
+ await asyncio.sleep(1)
1364
+ dl_dir, port = orch.read_store_window()
1365
+ if port:
1366
+ break
1367
+ if not port:
1368
+ return {'status': 'failed', 'summary': '店铺窗口未就绪(开店权被占用且无可用端口,已等待 60s)'}
1369
+ orch._log(f' 🔗 复用店铺窗口:cdp_port={port}(无需重复开店)' if not got_open_lock
1370
+ else f' 🔗 店铺窗口:cdp_port={port}')
1371
+ finally:
1372
+ if got_open_lock:
1373
+ orch.release_store_executor_lock()
291
1374
  orch.browser.cdp_url = f'http://127.0.0.1:{port}'
1375
+ if slot_no > 1:
1376
+ stagger = random.uniform(2.5, 6.0) * (slot_no - 1)
1377
+ orch._log(f' ⏱️ 同店多槽位错峰启动:slot={slot_no} 先等 {stagger:.1f}s')
1378
+ await asyncio.sleep(stagger)
292
1379
  await orch._connect_with_port_rediscovery()
293
1380
  await orch._preflight_store_window(phase='appointment-grab')
294
1381
  if not orch.state.shipment_id:
@@ -297,124 +1384,34 @@ async def run_task(task: dict) -> dict:
297
1384
  await orch.step1_prepare()
298
1385
  await orch.step2_entry()
299
1386
  await orch.step3_select_product()
300
- today = (await orch._platform_today()).date()
301
- cycles = int(task.get('maxCycles') or 0)
302
- cycle_no = 0
303
- last_states = {}
304
- while True:
305
- cycle_started = time.monotonic()
306
- cycle_no += 1
307
- if date_mode == 'available_days':
308
- need = int(task.get('availableDays') or 0)
309
- scan = await scan_available_days(orch, need)
310
- tomorrow = (today + timedelta(days=1)).isoformat()
311
- states = {k: v for k, v in dict(scan['states']).items() if k >= tomorrow}
312
- targets = [date.fromisoformat(x) for x in scan['selected']]
313
- targets = [d for d in targets if weekday_allowed(d)]
314
- if not targets:
315
- print(json.dumps({'event': 'cycle', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states, 'summary': '未发现可选日'}, ensure_ascii=False), flush=True)
316
- for d in targets:
317
- offset = (d - today).days
318
- try:
319
- _bump_page_check(orch)
320
- await orch.browser.visit_plan_page('appointment-v2', orch.state.shipment_id, step=4)
321
- # 与 FULL 步骤4、其他抢预约任务共用同店预约锁:只串行化“提交预约”,不占整个流程
322
- orch._acquire_store_step4_lock(force=True)
323
- try:
324
- await orch._book_appointment(hour_idx=0, date_offset=offset,
325
- time_from=time_from, time_to=time_to)
326
- finally:
327
- orch._release_store_step4_lock()
328
- actual = str(getattr(orch, '_last_booked_date', '') or d.isoformat())
329
- states[actual] = 'booked'
330
- slot = str(getattr(orch, '_last_booked_slot', '') or 'first')
331
- return {'status': 'booked', 'date': actual, 'slot': slot, 'dateStates': states, 'summary': f'{actual} {slot} 预约成功', 'windowMode': 'available_days'}
332
- except Exception as exc:
333
- msg = str(exc)
334
- if '不可选' in msg or '目标日期' in msg:
335
- states[d.isoformat()] = 'disabled'
336
- elif any(k in msg for k in ('可用时段不足', '未渲染出可选时段', '时间选择失败', '未写入日期时间',
337
- '指定时间范围内无可预约时段')):
338
- states[d.isoformat()] = 'selectable_no_slot'
339
- else:
340
- states[d.isoformat()] = 'selectable_booking_failed'
341
- orch._log(f' ⚠️ {d} 预约失败: {msg[:160]}')
342
- else:
343
- targets = []
344
- d = max(from_date, today + timedelta(days=1))
345
- while d <= to_date:
346
- if weekday_allowed(d):
347
- targets.append(d)
348
- d += timedelta(days=1)
349
- if not targets:
350
- return {'status': 'failed', 'summary': '日期范围内没有符合星期条件的可预约日期(今天及以前不算)'}
351
- states = {d.isoformat(): 'pending' for d in targets}
352
- # 2026-10-21:range 模式也改为**每轮只打开一次日历**。
353
- # 先在同一页面上扫完本轮所有目标日期;只有日期可选时才进入预约。
354
- # 旧实现每个日期都 prepare_appointment_page() 重新打开页面,导致
355
- # 一轮 3 个日期产生 6~10 次页面检查(用户看到的“轮次对不上”根因)。
356
- prepared = False
357
- for d in targets:
358
- offset = (d - today).days
359
- try:
360
- if not prepared:
361
- await prepare_appointment_page(orch)
362
- prepared = True
363
- info = await find_date_cell(orch, d)
364
- if not info.get('found'):
365
- states[d.isoformat()] = 'date_not_found'
366
- print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
367
- continue
368
- if info.get('disabled'):
369
- states[d.isoformat()] = 'disabled'
370
- print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
371
- continue
372
- except Exception as exc:
373
- prepared = False
374
- states[d.isoformat()] = 'page_error'
375
- orch._log(f' ⚠️ {d} 分类失败: {str(exc)[:120]}')
376
- print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
377
- continue
378
- print(json.dumps({'event': 'progress', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
379
- try:
380
- # 与 FULL 步骤4、其他抢预约任务共用同店预约锁:只串行化“提交预约”
381
- orch._acquire_store_step4_lock(force=True)
382
- try:
383
- # range 模式严格目标日期:只点运营给的日期,⛔ 不允许 _pick_date 跳到范围外
384
- await orch._book_appointment(hour_idx=0, date_offset=offset, exact_date=d.isoformat(),
385
- time_from=time_from, time_to=time_to)
386
- finally:
387
- orch._release_store_step4_lock()
388
- actual = str(getattr(orch, '_last_booked_date', '') or d.isoformat())
389
- if actual != d.isoformat():
390
- raise RuntimeError(f'严格日期校验失败:目标 {d.isoformat()},实际页面选中 {actual}(不提交)')
391
- states[d.isoformat()] = 'booked'
392
- slot = str(getattr(orch, '_last_booked_slot', '') or 'first')
393
- return {'status': 'booked', 'date': actual, 'slot': slot, 'dateStates': states, 'summary': f'{actual} {slot} 预约成功'}
394
- except Exception as exc:
395
- prepared = False
396
- msg = str(exc)
397
- if '不可选' in msg or '目标日期' in msg:
398
- states[d.isoformat()] = 'disabled'
399
- elif any(k in msg for k in ('可用时段不足', '未渲染出可选时段', '时间选择失败', '未写入日期时间',
400
- '指定时间范围内无可预约时段')):
401
- states[d.isoformat()] = 'selectable_no_slot'
402
- else:
403
- states[d.isoformat()] = 'selectable_booking_failed'
404
- orch._log(f' ⚠️ {d} 预约失败: {msg[:160]}')
405
- last_states = states
406
- print(json.dumps({'event': 'cycle', 'cycle': cycle_no, 'checks': int(getattr(orch, '_appt_page_checks', 0)), 'dateStates': states}, ensure_ascii=False), flush=True)
407
- if cycles and cycle_no >= cycles:
408
- break
409
- interval = max(30, min(600, int(task.get('pollIntervalSec') or 30)))
410
- elapsed = time.monotonic() - cycle_started
411
- await asyncio.sleep(max(10, interval - elapsed))
412
- return {'status': 'failed', 'dateStates': last_states, 'cycles': cycle_no, 'summary': '本轮日期范围内未抢到预约'}
1387
+ pacing = Pacing(
1388
+ refresh_min_sec=_CLI_PACING['refresh_min'] if _CLI_PACING['refresh_min'] else Pacing.refresh_min_sec,
1389
+ refresh_max_sec=_CLI_PACING['refresh_max'] if _CLI_PACING['refresh_max'] else Pacing.refresh_max_sec,
1390
+ )
1391
+ loop = AppointmentLoop(
1392
+ OrchestratorDriver(orch, pacing=pacing),
1393
+ date_mode=date_mode,
1394
+ from_date=from_date,
1395
+ to_date=to_date,
1396
+ weekdays=weekdays,
1397
+ time_from=time_from,
1398
+ time_to=time_to,
1399
+ rule_spec=rule_spec,
1400
+ rule_min_lead_hours=float((rule_snapshot or {}).get('spec', {}).get('minLeadHours') or 0) if rule_snapshot else 0,
1401
+ available_days=int(task.get('availableDays') or 0),
1402
+ pacing=pacing,
1403
+ max_scan_months=MAX_SCAN_MONTHS,
1404
+ # ⛔ 不设 max_rounds:任务模型里也没有 maxCycles(实测 ERP AppointmentTask 无该字段),
1405
+ # 值守循环的唯一终止 = 抢到 / 运营停止(stopRequestedAt → SIGTERM)。
1406
+ max_rounds=None,
1407
+ task=task,
1408
+ )
1409
+ return await loop.run()
413
1410
  finally:
414
1411
  try:
415
- await _close_appointment_tab(orch)
1412
+ _APPT_CLOSE_LAST['closed'] = await _close_appointment_tab(orch)
416
1413
  except Exception:
417
- pass
1414
+ _APPT_CLOSE_LAST['closed'] = 0
418
1415
  try:
419
1416
  await orch.browser.close()
420
1417
  except Exception:
@@ -423,6 +1420,126 @@ async def run_task(task: dict) -> dict:
423
1420
  orch.release_store_executor_lock()
424
1421
  except Exception:
425
1422
  pass
1423
+ try:
1424
+ orch.release_appt_slot_lock()
1425
+ except Exception:
1426
+ pass
1427
+
1428
+
1429
+ _APPT_CLOSE_LAST = {'closed': 0}
1430
+
1431
+
1432
+ _ORCH = None
1433
+
1434
+
1435
+ # ══════════════════════════════════════════════════════════════════════════════
1436
+ # 停止收尾(保持原实现:标签页必须关掉;同步 CDP 兜底)
1437
+ # ══════════════════════════════════════════════════════════════════════════════
1438
+ async def _close_appointment_tab(orch) -> int:
1439
+ """停止/失败时关闭本任务用的预约标签页;若它是窗口最后 1 个标签,先开一个占位页再关。
1440
+
1441
+ 2026-11-07 修复("停止后标签页仍在"):
1442
+ · 旧实现只看 `orch.browser.page`(当前页),stop 时当前页可能已不是预约页(或被切走)⇒ 漏关;
1443
+ · 改为**遍历所有 context 的所有 page**,按 URL 匹配 appointment-v2(或本任务货件号 + appointment);
1444
+ · 失败不再静默吞掉:返回实际关闭数,main 的停止摘要按真实结果生成(不再硬编码"已关闭")。
1445
+ """
1446
+ closed = 0
1447
+ shipment_id = str(getattr(getattr(orch, 'state', None), 'shipment_id', '') or '')
1448
+ try:
1449
+ contexts = list(getattr(orch.browser, 'contexts', []) or [])
1450
+ for ctx in contexts:
1451
+ try:
1452
+ pages = list(ctx.pages)
1453
+ except Exception:
1454
+ continue
1455
+ for page in pages:
1456
+ try:
1457
+ if page.is_closed():
1458
+ continue
1459
+ url = str(getattr(page, 'url', '') or '')
1460
+ # 2026-11-17 并行安全:只关**本任务**(按 shipment_id 命中)的预约页;
1461
+ # 同店并行时其它任务的 appointment-v2 标签绝不能碰。
1462
+ if shipment_id:
1463
+ is_appt = ('appointment' in url) and (shipment_id in url)
1464
+ else:
1465
+ # 无货件号(SKU-only 起步):只认当前自己的 page
1466
+ is_appt = ('appointment-v2' in url) and page is getattr(orch.browser, 'page', None)
1467
+ if not is_appt:
1468
+ continue
1469
+ if len(ctx.pages) <= 1:
1470
+ try:
1471
+ await ctx.new_page() # 占位,保持窗口不退出
1472
+ except Exception:
1473
+ return closed
1474
+ await page.close()
1475
+ closed += 1
1476
+ orch._log(f' 🗂️ 已关闭抢预约任务标签页({url[:100]})')
1477
+ except Exception as e:
1478
+ try: orch._log(f' ⚠️ 关闭预约标签页失败:{str(e)[:120]}')
1479
+ except Exception: pass
1480
+ if not closed:
1481
+ try: orch._log(' ⚠️ 停止时未找到待关闭的预约标签页(可能已被用户关闭)')
1482
+ except Exception: pass
1483
+ except Exception as e:
1484
+ try: orch._log(f' ⚠️ 关闭预约标签页异常:{str(e)[:120]}')
1485
+ except Exception: pass
1486
+ return closed
1487
+
1488
+
1489
+ def _http_sync(url: str, method: str = 'GET', timeout: float = 2.0):
1490
+ req = urllib.request.Request(url, method=method)
1491
+ with urllib.request.urlopen(req, timeout=timeout) as r:
1492
+ return r.read()
1493
+
1494
+
1495
+ def _close_appointment_tab_via_cdp(orch) -> int:
1496
+ """同步 CDP 关闭(2026-11-07 第二轮修复)。
1497
+
1498
+ 停止信号会让事件循环提前关闭,``await page.close()`` 会报 ``no running event loop``
1499
+ (客户机日志实证)⇒ 清理必须在**事件循环之外**用 CDP HTTP 同步完成。
1500
+ """
1501
+ closed = 0
1502
+ try:
1503
+ browser = getattr(orch, 'browser', None) if orch is not None else None
1504
+ endpoint = str(getattr(browser, 'cdp_url', '') or '').rstrip('/')
1505
+ if not endpoint:
1506
+ return 0
1507
+ targets = json.loads(_http_sync(f'{endpoint}/json/list').decode('utf-8', 'replace') or '[]')
1508
+ shipment_id_sync = str(getattr(getattr(orch, 'state', None), 'shipment_id', '') or '')
1509
+ appt = [t for t in targets
1510
+ if ('appointment' in str(t.get('url') or ''))
1511
+ and (not shipment_id_sync or shipment_id_sync in str(t.get('url') or ''))]
1512
+ if not appt:
1513
+ try: orch._log(' ⚠️ 同步清理:未发现 appointment-v2 标签页')
1514
+ except Exception: pass
1515
+ return 0
1516
+ # 只有预约页是窗口里最后一个页面时才开占位页;用户/店铺已有其它标签 → 直接关(不制造空页)
1517
+ others = [
1518
+ t for t in targets
1519
+ if t not in appt and str(t.get('type') or '') == 'page'
1520
+ and not str(t.get('url') or '').startswith('about:')
1521
+ and 'chrome-extension://' not in str(t.get('url') or '')
1522
+ ]
1523
+ if not others:
1524
+ try: _http_sync(f'{endpoint}/json/new?about:blank', method='PUT')
1525
+ except Exception:
1526
+ try: _http_sync(f'{endpoint}/json/new?about:blank')
1527
+ except Exception: pass
1528
+ for t in appt:
1529
+ tid = str(t.get('id') or '')
1530
+ if not tid: continue
1531
+ try:
1532
+ _http_sync(f'{endpoint}/json/close/{tid}')
1533
+ closed += 1
1534
+ try: orch._log(f' 🗂️ 同步 CDP 已关闭预约标签页({str(t.get("url"))[:100]})')
1535
+ except Exception: pass
1536
+ except Exception as e:
1537
+ try: orch._log(f' ⚠️ 同步 CDP 关闭失败:{str(e)[:120]}')
1538
+ except Exception: pass
1539
+ except Exception as e:
1540
+ try: orch._log(f' ⚠️ 同步 CDP 清理异常:{str(e)[:120]}')
1541
+ except Exception: pass
1542
+ return closed
426
1543
 
427
1544
 
428
1545
  def _on_term(signum, frame):
@@ -438,7 +1555,15 @@ def main():
438
1555
  try:
439
1556
  out = asyncio.run(run_task(task))
440
1557
  except KeyboardInterrupt:
441
- out = {'status': 'stopped', 'summary': '收到停止请求,已关闭预约标签页'}
1558
+ closed = int(_APPT_CLOSE_LAST.get('closed') or 0)
1559
+ # 事件循环已关闭 ⇒ await 清理不可用;用 CDP HTTP 同步兜底(2026-11-07 客户机实证)
1560
+ if _ORCH is not None:
1561
+ closed = max(closed, _close_appointment_tab_via_cdp(_ORCH))
1562
+ out = {
1563
+ 'status': 'stopped',
1564
+ 'summary': ('收到停止请求,已关闭预约标签页' if closed > 0
1565
+ else '收到停止请求;未发现可关闭的预约标签页(可能已被用户关闭)'),
1566
+ }
442
1567
  except Exception as exc:
443
1568
  out = {'status': 'failed', 'summary': f'{type(exc).__name__}: {exc}'}
444
1569
  print(json.dumps(out, ensure_ascii=False), flush=True)