@whyshu/argent-engine 0.14.5 → 0.14.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/MANIFEST.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "schema": 1,
3
3
  "package": "@whyshu/argent-engine",
4
4
  "files": {
5
- "VERSION": "475bb4c68d135a249416c4ad975cf4ad4fb5d970ba2696c827df0d8dbfc00118",
5
+ "VERSION": "0fc9cda3be894c84f7388e58b041f8c8314af9243b9171041c40ed1ffe0afaf3",
6
6
  "agents/catalog.json": "5356a812f2554dfd3115370363d4c3f787a82c9e5928a85d05b2a07c9e4b324d",
7
7
  "configs/_aliases.proposed.json": "3a59edf80563bcc20d410d488decad6fd787bd3de9489321367b0783904cd3e5",
8
8
  "configs/_migration-plan.proposed.json": "dd9f90b0b9b2f217dd23367a618402e57997d44f7fddcfa88a7cadf52e056c0d",
@@ -14,7 +14,7 @@
14
14
  "configs/mcp-tools.snapshot.json": "cfa94a6ba64a7ae9d133a4a878ce3d5e0e85e554ccd3e3ebaf0d51ad750acf6a",
15
15
  "configs/notify.json": "cb9ef11c1c498fcf99af99ec50271b8a2598061b77ed73a6099032e837474ef0",
16
16
  "core/cli/argent.mjs": "9a8977324c238ca4e20435f9817eb7ec76157da32b1d510977dc03e0feb416a9",
17
- "core/contracts/argent.contracts.json": "b8e27587d2cb8e4c6aff2a0b8d7e76667a237d1317dac3d004e06b061261b61d",
17
+ "core/contracts/argent.contracts.json": "bcf5b4b7a2adb503b014719e3ab7eb5bc715d9237d4e6bfb32e6076c5afc10cd",
18
18
  "core/contracts/verbs.schema.json": "54d726181c11536eb30bd25090584a7af103e4c0462f8ef078053c8177e19dcb",
19
19
  "core/lib/account-token.mjs": "35faad2c34e67755c1867f74a74885f0f268d5daabe01d339cf30dc747f86501",
20
20
  "core/lib/argent-datadir.mjs": "1fdd799c933382c4f9e36bd4af33d51b8ac4a466a9d67a8f2296bb267b5251ac",
@@ -193,7 +193,7 @@
193
193
  "scripts/flow_write_verify.py": "a9123838b00cb60b43fbc761f6dae740dfa3692906c2985e9b98a7c4538c2491",
194
194
  "scripts/fulfillment.js": "8de1ea386ebfe628caf4eaf2df5f1941938c07d4b8b2dcf79a78d45ac231669f",
195
195
  "scripts/fulfillment_sites.py": "7120ddcd891b1de588b4c80420af9b7291bfd2e582a7bb41cf9fcd91a0699fe7",
196
- "scripts/full-exec-worker.mjs": "ddc10b18ee29ff85b782a1145ef0e94e32af3397c16d7e4697ac3925796bf805",
196
+ "scripts/full-exec-worker.mjs": "6b5c409a1861356836f28027eb9f9d6e9b90f2a07f2efe566556a23280252208",
197
197
  "scripts/gen-agent-bundles.mjs": "3ab452fb7b1026a1bfab02977c85229985b390db4bc8458ce974b94bc207ed17",
198
198
  "scripts/gen-preset-rows.mjs": "1c074432be25148e9babce7ea1cb68d8fcef257abc2329f66b4ce488bc504578",
199
199
  "scripts/handover-sheet.mjs": "4e27095ccdd79586391abf7a7d5eb7aabbc3f0d7d9a1dd5161e9af8e8a9338de",
package/engine/VERSION CHANGED
@@ -1 +1 @@
1
- 0.14.5
1
+ 0.14.7
@@ -1,6 +1,6 @@
1
1
  {
2
- "argentVersion": "0.14.5",
3
- "_syncNote": "argentVersion 必须与仓库根 VERSION 同批更新:发布前置校验 scripts/check-version-consistency.mjs;2026-11-24 按 VERSION=0.14.5 校正。",
2
+ "argentVersion": "0.14.7",
3
+ "_syncNote": "argentVersion 必须与仓库根 VERSION 同批更新:发布前置校验 scripts/check-version-consistency.mjs;2026-11-24 按 VERSION=0.14.7 校正。",
4
4
  "principle": "宿主无关:宿主只依赖 `argent <verb>`;确定性逻辑在 CLI/MCP,不在提示词里。",
5
5
  "verbs": {
6
6
  "version": {
@@ -146,7 +146,12 @@ async function shutdown(signal = 'SIGTERM') {
146
146
  process.on('SIGTERM', () => { void shutdown('SIGTERM') })
147
147
  process.on('SIGINT', () => { void shutdown('SIGINT') })
148
148
 
149
- async function runAppointmentPhase(ctx) {
149
+ function apiPath(taskId, suffix) {
150
+ return `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(taskId)}${suffix}`
151
+ }
152
+
153
+ /** 抢预约参数(原 runAppointmentPhase 的前半段,字段原样保留)。 */
154
+ function buildAppointmentBody(ctx) {
150
155
  const task = ctx.task
151
156
  const record = ctx.record
152
157
  const ruleSnapshot = task.appointmentRuleSnapshot || null
@@ -155,7 +160,7 @@ async function runAppointmentPhase(ctx) {
155
160
  const d = new Date(today.getTime() + n * 86400000)
156
161
  return d.toISOString().slice(0, 10)
157
162
  }
158
- const body = {
163
+ return {
159
164
  store: task.store,
160
165
  sku: record.sku || '',
161
166
  quantity: Number(record.qty) || undefined,
@@ -170,89 +175,135 @@ async function runAppointmentPhase(ctx) {
170
175
  timeTo: ruleSnapshot ? undefined : '21:00',
171
176
  windowText: ruleSnapshot ? `FULL 时间规则:${ruleSnapshot.name || ''}` : 'FULL 自动预约',
172
177
  }
173
- const out = await new Promise((resolve) => {
174
- const child = spawn(PYTHON, [join(ENGINE, 'scripts', 'appointment_grab.py'), '--task-json', JSON.stringify(body)], {
175
- cwd: ENGINE,
176
- env: { ...process.env, PYTHONPATH: 'scripts', PATH: `${dirname(process.execPath)}:${process.env.PATH || ''}` },
177
- })
178
- activeChildren.add(child)
179
- let stdout = ''; let stderr = ''
180
- child.stdout.on('data', (b) => { stdout += String(b) })
181
- child.stderr.on('data', (b) => { stderr += String(b) })
182
- child.on('close', () => { activeChildren.delete(child); resolve(`${stdout}\n${stderr}`.trim()) })
183
- child.on('error', (e) => { activeChildren.delete(child); resolve(`WORKER_ERROR: ${e.message}`) })
178
+ }
179
+
180
+ /* ── 批次屏障修复(2026-12-02)───────────────────────────────────────────
181
+ * 旧实现先 `await Promise.all(抢预约)` 再跑标签。抢预约是**长期值守**(不设最大轮数,
182
+ * 只有抢到 / 被停才退),同批里只要有一条在抢号,标签任务就被无限期挂住——实测
183
+ * TL-261119-0027 被同店两条抢号任务卡了 7.5 小时,箱唛一直没下来。
184
+ * 现在:抢号**转后台**(独立子进程 + 独立心跳续租),标签批立刻执行;抢号结束回写
185
+ * 结果并 release,下一轮 claim 按新 phase 自然进入 label_ready,不需要人工介入。
186
+ */
187
+ const grabJobs = new Map() // taskId -> { ctx, child, body }
188
+ const leaseIds = new Set() // 需要心跳续租的任务 id(标签批 + 后台抢号)
189
+ let hbTimer = null
190
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
191
+
192
+ function ensureHeartbeat() {
193
+ if (hbTimer) return
194
+ hbTimer = setInterval(() => {
195
+ for (const id of [...leaseIds]) {
196
+ api('POST', apiPath(id, '/heartbeat'), { workerId })
197
+ .then((r) => {
198
+ if (String(r?.task?.status || '') !== 'cancelled') return
199
+ const job = grabJobs.get(id)
200
+ if (!job) return
201
+ console.log('[worker] 任务已人工接管取消,终止抢号子进程', id)
202
+ try { job.child.kill('SIGTERM') } catch { /* noop */ }
203
+ })
204
+ .catch(() => {})
205
+ }
206
+ }, 30_000)
207
+ hbTimer.unref?.()
208
+ }
209
+
210
+ function maybeStopHeartbeat() {
211
+ if (!leaseIds.size && hbTimer) { clearInterval(hbTimer); hbTimer = null }
212
+ }
213
+
214
+ /** 抢预约转后台:立刻返回,不阻塞同批标签任务。 */
215
+ function startGrab(ctx) {
216
+ const id = String(ctx.task.id)
217
+ const body = buildAppointmentBody(ctx)
218
+ const child = spawn(PYTHON, [join(ENGINE, 'scripts', 'appointment_grab.py'), '--task-json', JSON.stringify(body)], {
219
+ cwd: ENGINE,
220
+ env: { ...process.env, PYTHONPATH: 'scripts', PATH: `${dirname(process.execPath)}:${process.env.PATH || ''}` },
184
221
  })
222
+ activeChildren.add(child)
223
+ activeTasks.set(id, ctx.task)
224
+ leaseIds.add(id)
225
+ ensureHeartbeat()
226
+ grabJobs.set(id, { ctx, child, body })
227
+ let out = ''
228
+ child.stdout.on('data', (b) => { out += String(b) })
229
+ child.stderr.on('data', (b) => { out += String(b) })
230
+ child.on('close', () => { activeChildren.delete(child); void finishGrab(id, out) })
231
+ child.on('error', (e) => { activeChildren.delete(child); void finishGrab(id, `${out}\nWORKER_ERROR: ${e.message}`) })
232
+ console.log(`[worker] 抢预约转后台(不阻塞标签批)task=${id} store=${ctx.task.store || ''}`)
233
+ }
234
+
235
+ /** 抢号收尾:回写结果(含预约成功)→ release,让下一轮 claim 进入标签阶段。 */
236
+ async function finishGrab(id, out) {
237
+ const job = grabJobs.get(id)
238
+ grabJobs.delete(id)
239
+ activeTasks.delete(id)
240
+ const body = (job && job.body) || {}
185
241
  let result = null
186
242
  for (const line of String(out).split('\n').reverse()) {
187
243
  try { const j = JSON.parse(line); if (j && j.status) { result = j; break } } catch { /* next */ }
188
244
  }
245
+ let ok = false
189
246
  if (!result) {
190
- await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(task.id)}/result`, {
191
- workerId, status: 'failed', error: '抢预约未返回结果',
192
- }).catch(() => {})
193
- return false
194
- }
195
- const ok = ['booked', 'succeeded', 'success'].includes(String(result.status || ''))
196
- if (!ok) {
197
- await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(task.id)}/result`, {
247
+ await api('POST', apiPath(id, '/result'), { workerId, status: 'failed', error: '抢预约未返回结果' }).catch(() => {})
248
+ } else if (!['booked', 'succeeded', 'success'].includes(String(result.status || ''))) {
249
+ await api('POST', apiPath(id, '/result'), {
198
250
  workerId, status: 'failed', error: String(result.summary || result.status || '抢预约失败').slice(0, 400),
199
251
  }).catch(() => {})
200
- return false
201
- }
202
- const r = await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(task.id)}/appointment-result`, {
203
- workerId,
204
- result: {
205
- date: result.date || '',
206
- slot: result.slot || '',
207
- summary: result.summary || `预约成功:${result.date || ''} ${result.slot || ''}`.trim(),
208
- windowText: body.windowText,
209
- },
210
- })
211
- if (!r || r.ok === false) {
212
- console.warn('[worker] 预约结果回写失败', task.id, r?.message || r?.error?.message || '')
213
- return false
252
+ } else {
253
+ const r = await api('POST', apiPath(id, '/appointment-result'), {
254
+ workerId,
255
+ result: {
256
+ date: result.date || '',
257
+ slot: result.slot || '',
258
+ summary: result.summary || `预约成功:${result.date || ''} ${result.slot || ''}`.trim(),
259
+ windowText: body.windowText || '',
260
+ },
261
+ }).catch((e) => ({ ok: false, message: e.message }))
262
+ ok = Boolean(r && r.ok !== false)
263
+ if (!ok) console.warn('[worker] 预约结果回写失败', id, r?.message || r?.error?.message || '')
214
264
  }
215
- ctx.task.phase = 'label_ready'
216
- return true
265
+ if (!ok) await sleep(60_000) // 失败退避 60s:避免同一任务被立刻重 claim 成热循环
266
+ await api('POST', apiPath(id, '/release'), {
267
+ workerId, reason: ok ? 'appointment_ok_requeue' : 'appointment_fail_requeue',
268
+ }).catch(() => {})
269
+ leaseIds.delete(id)
270
+ maybeStopHeartbeat()
217
271
  }
218
272
 
219
273
  async function executeBatch(tasks) {
220
274
  const contexts = []
221
275
  for (const t of tasks) {
222
276
  activeTasks.set(String(t.id), t)
223
- const c = await api('GET', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(t.id)}/context`)
277
+ const c = await api('GET', apiPath(t.id, '/context'))
224
278
  contexts.push({ task: c.task || t, record: c.record })
225
279
  }
226
- let cancelSeen = false
227
- const hb = setInterval(() => {
228
- for (const t of tasks) {
229
- api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(t.id)}/heartbeat`, { workerId })
230
- .then((r) => {
231
- if (String(r?.task?.status || '') === 'cancelled') {
232
- cancelSeen = true
233
- console.log('[worker] 任务已人工接管取消,终止子进程', t.id)
234
- for (const child of activeChildren) { try { child.kill('SIGTERM') } catch { /* noop */ } }
235
- }
236
- })
237
- .catch(() => {})
280
+ // 抢预约 → 后台;标签 → 本批同步执行(只等标签,不等抢号)
281
+ const waiting = contexts.filter((x) => String(x.task.phase || '') === 'appointment_wait')
282
+ for (const x of waiting) {
283
+ try { startGrab(x) } catch (e) {
284
+ console.warn('[worker] 抢预约启动失败', x.task.id, e.message)
285
+ await api('POST', apiPath(x.task.id, '/result'), {
286
+ workerId, status: 'failed', error: String(e.message || e).slice(0, 400),
287
+ }).catch(() => {})
288
+ await api('POST', apiPath(x.task.id, '/release'), { workerId, reason: 'appointment_spawn_failed' }).catch(() => {})
289
+ activeTasks.delete(String(x.task.id))
238
290
  }
239
- }, 30_000)
291
+ }
292
+ const labels = contexts.filter((x) => !String(x.task.phase || '') || ['label_ready', 'executing'].includes(String(x.task.phase || '')))
293
+ if (!labels.length) return
294
+ for (const x of labels) leaseIds.add(String(x.task.id))
295
+ ensureHeartbeat()
240
296
  try {
241
- // 一个槽位先处理抢预约阶段;抢到后同一批继续进入标签执行。
242
- const waiting = contexts.filter((x) => String(x.task.phase || '') === 'appointment_wait')
243
- if (waiting.length) {
244
- await Promise.all(waiting.map(async (x) => {
245
- try { await runAppointmentPhase(x) } catch (e) {
246
- console.warn('[worker] 抢预约阶段异常', x.task.id, e.message)
247
- await api('POST', `/api/argent/v1/tenants/${encodeURIComponent(APP)}/full-executions/${encodeURIComponent(x.task.id)}/result`, {
248
- workerId, status: 'failed', error: String(e.message || e).slice(0, 400),
249
- }).catch(() => {})
250
- }
251
- }))
252
- }
253
- const labels = contexts.filter((x) => !String(x.task.phase || '') || ['label_ready', 'executing'].includes(String(x.task.phase || '')))
254
- if (!labels.length) return
255
- const dir = await mkdtemp(join(tmpdir(), 'argent-full-exec-'))
297
+ await runLabelBatch(labels)
298
+ } finally {
299
+ for (const x of labels) { leaseIds.delete(String(x.task.id)); activeTasks.delete(String(x.task.id)) }
300
+ maybeStopHeartbeat()
301
+ }
302
+ }
303
+
304
+ /** 标签批:一条 orchestrator 子进程跑完本批(原 executeBatch 的标签段,逐行保留)。 */
305
+ async function runLabelBatch(labels) {
306
+ const dir = await mkdtemp(join(tmpdir(), 'argent-full-exec-'))
256
307
  const file = join(dir, 'records.json')
257
308
  await writeFile(file, JSON.stringify(labels.map((x) => x.record)), 'utf8')
258
309
  let out = ''
@@ -324,10 +375,6 @@ async function executeBatch(tasks) {
324
375
  completedSteps: Array.isArray(result.completed_steps) ? result.completed_steps : [],
325
376
  }).catch((e) => console.warn('[worker] 回写失败', ctx.task.id, e.message))
326
377
  }
327
- } finally {
328
- clearInterval(hb)
329
- for (const t of tasks) activeTasks.delete(String(t.id))
330
- }
331
378
  }
332
379
 
333
380
  const storeBusy = new Set()
@@ -1 +1 @@
1
- export const VERSION = "0.14.5"
1
+ export const VERSION = "0.14.7"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whyshu/argent-engine",
3
- "version": "0.14.5",
3
+ "version": "0.14.7",
4
4
  "description": "Argent 引擎(L1):流程/台账/重试/守卫/审计/浏览器自动化 —— 逐字节来自 argent-dsh 仓库",
5
5
  "type": "module",
6
6
  "engines": {