dsh-chief 1.0.0 → 1.2.0

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.
@@ -0,0 +1,627 @@
1
+ import crypto from 'node:crypto'
2
+
3
+ export const AUTO_CONTINUE_SOURCE_KIND = 'dsh-chief-auto-continue'
4
+ export const MAX_CONSECUTIVE_AUTO_CONTINUE = 3
5
+
6
+ const TRANSIENT_ERROR_PATTERNS = [
7
+ /econnreset/i,
8
+ /etimedout/i,
9
+ /epipe/i,
10
+ /enotfound/i,
11
+ /econnrefused/i,
12
+ /eai_again/i,
13
+ /socket hang up/i,
14
+ /fetch failed/i,
15
+ /network(?:\s+error|\s+timeout|\s+unavailable)?/i,
16
+ /timeout/i,
17
+ /timed out/i,
18
+ /premature close/i,
19
+ /stream(?:\s+error|\s+aborted|\s+closed|\s+ended)/i,
20
+ /malformed_response/i,
21
+ /empty response/i,
22
+ /rate.?limit/i,
23
+ /too many requests/i,
24
+ /overload(?:ed)?/i,
25
+ /service unavailable/i,
26
+ /bad gateway/i,
27
+ /gateway timeout/i,
28
+ /temporarily unavailable/i,
29
+ /internal server error/i,
30
+ /connection reset/i,
31
+ /broken pipe/i,
32
+ /\b(?:408|425|429|500|502|503|504|520|521|522|523|524)\b/,
33
+ ]
34
+
35
+ const PERMANENT_ERROR_PATTERNS = [
36
+ /invalid[_\s-]*api[_\s-]*key/i,
37
+ /unauthorized/i,
38
+ /authentication/i,
39
+ /forbidden/i,
40
+ /permission denied/i,
41
+ /insufficient[_\s-]*(?:balance|quota|funds|credits)/i,
42
+ /quota[_\s-]*exceeded/i,
43
+ /billing/i,
44
+ /payment required/i,
45
+ /model[_\s-]*not[_\s-]*found/i,
46
+ /context[_\s-]*(?:length|window)[_\s-]*exceeded/i,
47
+ /maximum context length/i,
48
+ /content[_\s-]*policy/i,
49
+ /safety/i,
50
+ /\b(?:401|402|403|404)\b/,
51
+ ]
52
+
53
+ const TRANSIENT_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504, 520, 521, 522, 523, 524])
54
+ const PERMANENT_STATUS_CODES = new Set([400, 401, 402, 403, 404, 422])
55
+
56
+ function clampText(text, maxLen = 240) {
57
+ const s = String(text || '').replace(/\s+/g, ' ').trim()
58
+ return s.length > maxLen ? s.slice(0, maxLen) + '...' : s
59
+ }
60
+
61
+ /**
62
+ * 跟踪单回合内工具调用生命周期,用于区分「已无任何活动空转」与「执行中/已完成部分工具后的意外中断」,
63
+ * 并在续跑提示词中注入幂等检查提醒,防止重复产生副作用。
64
+ */
65
+ export class ToolInvocationTracker {
66
+ constructor() {
67
+ this.pending = new Map()
68
+ this.done = new Set()
69
+ this.seq = 0
70
+ }
71
+
72
+ reset() {
73
+ this.pending.clear()
74
+ this.done.clear()
75
+ this.seq = 0
76
+ }
77
+
78
+ onCall(data = {}) {
79
+ const rawId = data.toolCallId || data.callId || data.id
80
+ const name = String(data.name || data.toolName || 'tool').trim() || 'tool'
81
+ const key = rawId ? String(rawId) : `${name}#${++this.seq}`
82
+ this.pending.set(key, { key, name, at: Date.now() })
83
+ return key
84
+ }
85
+
86
+ onResult(data = {}) {
87
+ const rawId = data.toolCallId || data.callId || data.id
88
+ if (rawId && this.pending.has(String(rawId))) {
89
+ const k = String(rawId)
90
+ const rec = this.pending.get(k)
91
+ this.pending.delete(k)
92
+ this.done.add(rec ? rec.name : k)
93
+ return
94
+ }
95
+ const name = String(data.name || data.toolName || '').trim()
96
+ if (name) {
97
+ for (const [k, rec] of this.pending.entries()) {
98
+ if (rec.name === name) {
99
+ this.pending.delete(k)
100
+ this.done.add(name)
101
+ return
102
+ }
103
+ }
104
+ this.done.add(name)
105
+ return
106
+ }
107
+ const first = this.pending.keys().next()
108
+ if (!first.done) {
109
+ const k = first.value
110
+ const rec = this.pending.get(k)
111
+ this.pending.delete(k)
112
+ this.done.add(rec ? rec.name : k)
113
+ }
114
+ }
115
+
116
+ summary() {
117
+ return {
118
+ pendingCount: this.pending.size,
119
+ doneCount: this.done.size,
120
+ pendingNames: [...this.pending.values()].map(x => x.name),
121
+ doneNames: [...this.done.values()],
122
+ }
123
+ }
124
+ }
125
+
126
+ /** 解析 turn/end reason,支持对象格式及 nested reason.kind。 */
127
+ export function parseFailureFacts(err) {
128
+ if (!err || typeof err !== 'object') {
129
+ const msg = typeof err === 'string' ? err : ''
130
+ return msg ? { code: 'UNKNOWN_ERROR', status: undefined, message: msg } : undefined
131
+ }
132
+ const code = String(err.code || err.name || err.type || 'UNKNOWN_ERROR').trim()
133
+ const rawStatus = err.status ?? err.statusCode ?? err.httpStatus
134
+ const status = Number.isFinite(Number(rawStatus)) ? Number(rawStatus) : undefined
135
+ const message = clampText(err.message || err.detail || err.reason || code, 400)
136
+ return { code, status, message }
137
+ }
138
+
139
+ /** 判定错误是否属于可恢复的瞬态失败。永久性错误(鉴权/余额不足/模型不存在/超长上下文)返回 false。 */
140
+ export function isTransientFailure(failure) {
141
+ if (!failure || typeof failure !== 'object') return false
142
+ const status = failure.status
143
+ const combined = `${failure.code || ''} ${failure.message || ''}`.trim()
144
+
145
+ if (typeof status === 'number') {
146
+ if (TRANSIENT_STATUS_CODES.has(status)) return true
147
+ if (PERMANENT_STATUS_CODES.has(status)) {
148
+ // 某些网关在 400/422 下仍可能包装 MALFORMED_RESPONSE 等瞬态格式异常
149
+ if (/malformed_response|empty response/i.test(combined)) return true
150
+ return false
151
+ }
152
+ }
153
+
154
+ for (const re of PERMANENT_ERROR_PATTERNS) {
155
+ if (re.test(combined)) return false
156
+ }
157
+ for (const re of TRANSIENT_ERROR_PATTERNS) {
158
+ if (re.test(combined)) return true
159
+ }
160
+ return false
161
+ }
162
+
163
+ /** 解析 DSH turn/end 事件的原因分类。 */
164
+ export function classifyTurnEndReason(reason, eventData = null) {
165
+ const extraFailure = eventData && typeof eventData === 'object' && eventData.error !== undefined
166
+ ? parseFailureFacts(eventData.error)
167
+ : undefined
168
+ if (typeof reason === 'string') {
169
+ const kind = reason.trim().toLowerCase()
170
+ return kind ? { kind, nestedKind: '', failure: extraFailure } : undefined
171
+ }
172
+ if (!reason || typeof reason !== 'object') return undefined
173
+ const kind = typeof reason.kind === 'string' ? reason.kind.trim().toLowerCase() : ''
174
+ if (!kind) return undefined
175
+ const nestedObj = reason.reason && typeof reason.reason === 'object' ? reason.reason : null
176
+ const nestedKind = nestedObj && typeof nestedObj.kind === 'string'
177
+ ? nestedObj.kind.trim().toLowerCase()
178
+ : ''
179
+ const rawErr = reason.error !== undefined
180
+ ? reason.error
181
+ : (nestedObj && nestedObj.error !== undefined ? nestedObj.error : undefined)
182
+ const failure = rawErr !== undefined ? parseFailureFacts(rawErr) : extraFailure
183
+ return { kind, nestedKind, failure }
184
+ }
185
+
186
+ function buildContinuePrompt(trigger, toolSummary = {}, failure = null) {
187
+ const pendingCount = Number(toolSummary.pendingCount) || 0
188
+ const doneCount = Number(toolSummary.doneCount) || 0
189
+
190
+ let lead = '检测到上一轮执行意外收尾,请基于当前进度与目标继续推进,直到任务完整收口。'
191
+ if (trigger === 'turn/end:max-tokens') {
192
+ lead = '上一轮因输出长度达到上限(max-tokens)被截断,请紧接上文未完成的部分继续推进。'
193
+ } else if (trigger.endsWith(':silent') || trigger === 'turn/end:no-visible-output') {
194
+ lead = '检测到上一轮未输出有效可见内容即结束,请直接承接上下文继续执行未完成步骤或给出明确结论。'
195
+ } else if (trigger === 'turn/end:interrupted') {
196
+ lead = '检测到上一轮执行途中意外中断,请核对现状后继续推进未完成任务。'
197
+ } else if (trigger === 'turn/end:error') {
198
+ const detail = failure
199
+ ? [failure.code, failure.status ? `HTTP ${failure.status}` : '', failure.message].filter(Boolean).join(' · ')
200
+ : ''
201
+ lead = `上一轮因临时异常中断(${clampText(detail || '网络或接口抖动', 120)}),请核对现场后继续完成任务。`
202
+ } else if (trigger === 'idle-stall') {
203
+ lead = '检测到当前会话仍有未完结工作却停滞空转,请继续推进关键步骤并附可验证结果。'
204
+ }
205
+
206
+ let guardText = ''
207
+ if (pendingCount > 0) {
208
+ const pendingList = Array.isArray(toolSummary.pendingNames) && toolSummary.pendingNames.length
209
+ ? `(涉及工具:${toolSummary.pendingNames.slice(0, 4).join('、')})`
210
+ : ''
211
+ guardText = `\n[幂等安全提醒] 中断前仍有工具调用未收尾${pendingList},请先检查文件/状态是否已写入,确认未产生重复副作用后再继续执行。`
212
+ } else if (doneCount > 0) {
213
+ const doneList = Array.isArray(toolSummary.doneNames) && toolSummary.doneNames.length
214
+ ? `(已完成:${toolSummary.doneNames.slice(0, 4).join('、')})`
215
+ : ''
216
+ guardText = `\n[幂等安全提醒] 上一轮已有工具调用完成${doneList},请先核实已有产出,切勿重复执行会覆盖或叠加副作用的步骤。`
217
+ }
218
+
219
+ return `[DSH 参谋长 · 断线续跑] ${lead}${guardText}`
220
+ }
221
+
222
+ /**
223
+ * 创建宿主侧 Auto-Continue 恢复引擎(对齐 dsh-auto-continue 状态机):
224
+ * - 监听 session/event 全生命周期
225
+ * - 在网络/限流/截断/无输出/意外打断时指数退避续跑
226
+ * - 尊重人类主动停止 (aborted)、人类发新消息、永久错误 (401/403/余额不足等) 与参谋长停机状态 (stopped)
227
+ */
228
+ export function createAutoContinueEngine(options = {}) {
229
+ const {
230
+ getAgent,
231
+ createMessage = null,
232
+ isChiefStopped = () => false,
233
+ resolveRootSessionId = (sid) => sid,
234
+ onLog = () => {},
235
+ baseDelayMs = 1500,
236
+ maxConsecutive = MAX_CONSECUTIVE_AUTO_CONTINUE,
237
+ echoTtlMs = 30_000,
238
+ } = options
239
+
240
+ const sessions = new Map()
241
+
242
+ function getSessionState(sessionId) {
243
+ const sid = String(sessionId || '').trim()
244
+ if (!sid) return null
245
+ let st = sessions.get(sid)
246
+ if (!st) {
247
+ st = {
248
+ sessionId: sid,
249
+ consecutive: 0,
250
+ lastAttemptAt: 0,
251
+ lastFailure: null,
252
+ lastToolSummary: { pendingCount: 0, doneCount: 0, pendingNames: [], doneNames: [] },
253
+ turnOutput: 'none', // 'none' | 'silent' | 'visible'
254
+ sawModelActivity: false,
255
+ tools: new ToolInvocationTracker(),
256
+ timer: null,
257
+ pendingEchoes: new Map(), // messageId -> expiresAt
258
+ stats: { scheduled: 0, sent: 0, skippedPermanent: 0, skippedStopped: 0, skippedAborted: 0 },
259
+ }
260
+ sessions.set(sid, st)
261
+ }
262
+ return st
263
+ }
264
+
265
+ function pruneEchoes(st) {
266
+ const now = Date.now()
267
+ for (const [id, exp] of st.pendingEchoes.entries()) {
268
+ if (exp <= now) st.pendingEchoes.delete(id)
269
+ }
270
+ }
271
+
272
+ function trackEcho(st, messageId) {
273
+ if (!messageId) return
274
+ pruneEchoes(st)
275
+ st.pendingEchoes.set(String(messageId), Date.now() + echoTtlMs)
276
+ }
277
+
278
+ function isOurMessage(st, event) {
279
+ const data = event && event.data ? event.data : {}
280
+ const msg = data.message && typeof data.message === 'object' ? data.message : data
281
+ const srcKind = String((data.source && data.source.kind) || (msg.source && msg.source.kind) || '').trim()
282
+ if (srcKind === AUTO_CONTINUE_SOURCE_KIND || srcKind === 'dsh-chief' || srcKind === 'dsh-chief-relay') {
283
+ return true
284
+ }
285
+ const id = String(data.id || data.messageId || msg.id || '').trim()
286
+ pruneEchoes(st)
287
+ if (id && st.pendingEchoes.has(id)) {
288
+ st.pendingEchoes.delete(id)
289
+ return true
290
+ }
291
+ return false
292
+ }
293
+
294
+ function cancelPending(sessionId, why = '') {
295
+ const st = getSessionState(sessionId)
296
+ if (!st) return false
297
+ let had = false
298
+ if (st.timer) {
299
+ clearTimeout(st.timer)
300
+ st.timer = null
301
+ had = true
302
+ }
303
+ if (had && why) onLog(sessionId, `取消自动续跑(${why})`)
304
+ return had
305
+ }
306
+
307
+ function computeDelayMs(st) {
308
+ const exp = Math.min(4, Math.max(0, st.consecutive))
309
+ return Math.round(baseDelayMs * Math.pow(2, exp))
310
+ }
311
+
312
+ async function fire(sessionId, trigger, { detail = '' } = {}) {
313
+ const st = getSessionState(sessionId)
314
+ if (!st) return { ok: false, skipped: 'invalid-session' }
315
+ st.timer = null
316
+
317
+ const rootId = resolveRootSessionId(sessionId) || sessionId
318
+ if (isChiefStopped(rootId, sessionId)) {
319
+ st.stats.skippedStopped += 1
320
+ onLog(sessionId, '参谋长处于停止状态(stopped),跳过自动续跑')
321
+ return { ok: false, skipped: 'chief-stopped' }
322
+ }
323
+
324
+ if (st.consecutive >= maxConsecutive) {
325
+ onLog(sessionId, `已达连续自动续跑上限(${maxConsecutive} 次),等待人工确认或成功回合恢复`)
326
+ return { ok: false, skipped: 'max-consecutive' }
327
+ }
328
+
329
+ const agent = typeof getAgent === 'function' ? await getAgent(sessionId) : null
330
+ if (!agent) {
331
+ onLog(sessionId, `未找到活跃会话句柄,跳过续跑(${trigger})`)
332
+ return { ok: false, skipped: 'no-agent' }
333
+ }
334
+ if (agent.status === 'running') {
335
+ return { ok: false, skipped: 'agent-running' }
336
+ }
337
+ if (typeof agent.followup !== 'function') {
338
+ onLog(sessionId, `会话不支持 followup 接口,无法发送断线续跑(${trigger})`)
339
+ return { ok: false, skipped: 'no-followup' }
340
+ }
341
+
342
+ const text = buildContinuePrompt(trigger, st.lastToolSummary, st.lastFailure) + (detail ? `\n补充上下文:${clampText(detail, 180)}` : '')
343
+ const fallbackId = `ac-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`
344
+ let envelope = null
345
+ if (typeof createMessage === 'function') {
346
+ try {
347
+ envelope = await createMessage(text, AUTO_CONTINUE_SOURCE_KIND)
348
+ } catch {
349
+ envelope = null
350
+ }
351
+ }
352
+ if (!envelope || typeof envelope !== 'object') {
353
+ envelope = {
354
+ id: fallbackId,
355
+ role: 'user',
356
+ content: [{ type: 'text', text }],
357
+ source: { kind: AUTO_CONTINUE_SOURCE_KIND },
358
+ timestamp: Date.now(),
359
+ }
360
+ } else if (!envelope.id) {
361
+ envelope = { ...envelope, id: fallbackId }
362
+ }
363
+ const msgId = String(envelope.id)
364
+
365
+ st.lastAttemptAt = Date.now()
366
+ trackEcho(st, msgId)
367
+ try {
368
+ const ret = agent.followup(envelope)
369
+ if (ret && typeof ret.then === 'function') await ret
370
+ st.consecutive += 1
371
+ st.stats.sent += 1
372
+ onLog(sessionId, `断线续跑已触发(原因:${trigger},第 ${st.consecutive}/${maxConsecutive} 次尝试)`)
373
+ return { ok: true, msgId, trigger, consecutive: st.consecutive }
374
+ } catch (err) {
375
+ st.pendingEchoes.delete(msgId)
376
+ const msg = String(err && err.message ? err.message : err)
377
+ onLog(sessionId, `断线续跑投递失败(${trigger}):${msg}`)
378
+ return { ok: false, error: msg }
379
+ }
380
+ }
381
+
382
+ function schedule(sessionId, trigger, opts = {}) {
383
+ const st = getSessionState(sessionId)
384
+ if (!st) return { scheduled: false, reason: 'invalid-session' }
385
+ const rootId = resolveRootSessionId(sessionId) || sessionId
386
+ if (isChiefStopped(rootId, sessionId)) {
387
+ st.stats.skippedStopped += 1
388
+ cancelPending(sessionId, '参谋长处于停止状态')
389
+ return { scheduled: false, reason: 'chief-stopped' }
390
+ }
391
+ if (st.consecutive >= maxConsecutive) {
392
+ return { scheduled: false, reason: 'max-consecutive' }
393
+ }
394
+
395
+ cancelPending(sessionId)
396
+ const delay = typeof opts.delayMs === 'number' ? Math.max(0, opts.delayMs) : computeDelayMs(st)
397
+ st.stats.scheduled += 1
398
+ st.timer = setTimeout(() => {
399
+ void fire(sessionId, trigger, { detail: opts.detail || '' })
400
+ }, delay)
401
+ if (st.timer && typeof st.timer.unref === 'function') st.timer.unref()
402
+ return { scheduled: true, delayMs: delay, trigger }
403
+ }
404
+
405
+ function onSessionEvent(session, event) {
406
+ if (!session || !session.id || !event || typeof event !== 'object') return null
407
+ const sessionId = String(session.id).trim()
408
+ if (!sessionId) return null
409
+ const st = getSessionState(sessionId)
410
+ if (!st) return null
411
+
412
+ const data = event.data && typeof event.data === 'object' ? event.data : {}
413
+ switch (event.type) {
414
+ case 'turn/start':
415
+ cancelPending(sessionId)
416
+ st.sawModelActivity = false
417
+ st.turnOutput = 'none'
418
+ st.tools.reset()
419
+ return { action: 'turn-started' }
420
+
421
+ case 'step/start':
422
+ case 'llm/call':
423
+ case 'llm/start':
424
+ case 'llm/response':
425
+ st.sawModelActivity = true
426
+ if (st.turnOutput === 'none') st.turnOutput = 'silent'
427
+ return null
428
+
429
+ case 'assistant/chunk': {
430
+ if (event.surfaceOp) return null
431
+ st.sawModelActivity = true
432
+ const chunk = data.chunk && typeof data.chunk === 'object' ? data.chunk : null
433
+ let visible = false
434
+ if (chunk) {
435
+ visible = (chunk.type === 'text-delta' && typeof chunk.text === 'string' && chunk.text.trim() !== '')
436
+ || chunk.type === 'tool-call-delta'
437
+ || (chunk.type === 'block-start' && chunk.blockType !== 'reasoning' && chunk.blockType !== 'text')
438
+ || (chunk.type === 'block-end' && chunk.block && chunk.block.type !== 'reasoning' && (chunk.block.type !== 'text' || String(chunk.block.text || '').trim() !== ''))
439
+ } else if (typeof data.text === 'string' && data.text.trim() !== '') {
440
+ visible = true
441
+ }
442
+ if (visible) {
443
+ st.turnOutput = 'visible'
444
+ } else if (st.turnOutput === 'none' && (!chunk || (chunk.type !== 'usage' && chunk.type !== 'finish'))) {
445
+ st.turnOutput = 'silent'
446
+ }
447
+ return null
448
+ }
449
+
450
+ case 'assistant/message': {
451
+ if (event.surfaceOp) return null
452
+ st.sawModelActivity = true
453
+ const content = data.message && Array.isArray(data.message.content)
454
+ ? data.message.content
455
+ : (Array.isArray(data.content) ? data.content : null)
456
+ const hasVisibleBlocks = Array.isArray(content) && content.some(c => {
457
+ if (!c || typeof c !== 'object') return false
458
+ if (c.type === 'reasoning') return false
459
+ if (c.type === 'text') return String(c.text || '').trim() !== ''
460
+ return true
461
+ })
462
+ if ((typeof data.text === 'string' && data.text.trim() !== '') || hasVisibleBlocks) {
463
+ st.turnOutput = 'visible'
464
+ } else if (st.turnOutput === 'none') {
465
+ st.turnOutput = 'silent'
466
+ }
467
+ return null
468
+ }
469
+
470
+ case 'tool/call':
471
+ st.sawModelActivity = true
472
+ st.tools.onCall(data)
473
+ return null
474
+
475
+ case 'tool/result':
476
+ st.sawModelActivity = true
477
+ st.tools.onResult(data)
478
+ return null
479
+
480
+ case 'user/message':
481
+ if (event.surfaceOp) return null
482
+ if (isOurMessage(st, event)) return { action: 'ignored-echo' }
483
+ {
484
+ const srcKind = String((data.source && data.source.kind) || '').trim()
485
+ if (!srcKind || srcKind === 'user') {
486
+ st.consecutive = 0
487
+ st.lastFailure = null
488
+ cancelPending(sessionId, '用户发送了新消息')
489
+ return { action: 'user-intervened' }
490
+ }
491
+ }
492
+ return null
493
+
494
+ case 'turn/end': {
495
+ const parsed = classifyTurnEndReason(data.reason, data)
496
+ if (!parsed) return null
497
+ st.lastToolSummary = st.tools.summary()
498
+ const rootId = resolveRootSessionId(sessionId) || sessionId
499
+ const stopped = isChiefStopped(rootId, sessionId)
500
+
501
+ if (parsed.kind === 'aborted' || parsed.nestedKind === 'aborted') {
502
+ st.stats.skippedAborted += 1
503
+ st.consecutive = 0
504
+ st.lastFailure = null
505
+ cancelPending(sessionId, '人工停止回合')
506
+ return { action: 'aborted', scheduled: false }
507
+ }
508
+
509
+ if (parsed.kind === 'blocked' || parsed.nestedKind === 'blocked') {
510
+ cancelPending(sessionId, '策略拦截')
511
+ return { action: 'blocked', scheduled: false }
512
+ }
513
+
514
+ if (stopped) {
515
+ st.stats.skippedStopped += 1
516
+ cancelPending(sessionId, '参谋长已停止')
517
+ return { action: 'chief-stopped', scheduled: false }
518
+ }
519
+
520
+ if (parsed.kind === 'no-visible-output' || (parsed.kind === 'completed' && st.turnOutput === 'silent' && st.lastToolSummary.doneCount === 0)) {
521
+ st.lastFailure = null
522
+ const res = schedule(sessionId, `turn/end:${parsed.kind}:silent`)
523
+ return { action: 'silent-scheduled', ...res }
524
+ }
525
+
526
+ if (parsed.kind === 'completed') {
527
+ if (st.turnOutput === 'visible' || st.lastToolSummary.doneCount > 0) {
528
+ st.consecutive = 0
529
+ st.lastFailure = null
530
+ }
531
+ return { action: 'completed', scheduled: false }
532
+ }
533
+
534
+ if (parsed.kind === 'max-tokens') {
535
+ st.lastFailure = null
536
+ const res = schedule(sessionId, 'turn/end:max-tokens')
537
+ return { action: 'max-tokens-scheduled', ...res }
538
+ }
539
+
540
+ if (parsed.kind === 'interrupted') {
541
+ if (parsed.nestedKind === 'error' && parsed.failure && !isTransientFailure(parsed.failure)) {
542
+ st.lastFailure = parsed.failure
543
+ st.stats.skippedPermanent += 1
544
+ onLog(sessionId, `检测到永久性错误(${parsed.failure.code}${parsed.failure.status ? ` HTTP ${parsed.failure.status}` : ''}),跳过自动续跑`)
545
+ return { action: 'permanent-error-skipped', failure: parsed.failure, scheduled: false }
546
+ }
547
+ st.lastFailure = parsed.failure || null
548
+ const res = schedule(sessionId, 'turn/end:interrupted')
549
+ return { action: 'interrupted-scheduled', ...res }
550
+ }
551
+
552
+ if (parsed.kind === 'error') {
553
+ const failure = parsed.failure
554
+ || (data.error !== undefined ? parseFailureFacts(data.error) : null)
555
+ || { code: 'UNKNOWN_ERROR', status: undefined, message: '' }
556
+ st.lastFailure = failure
557
+ if (!isTransientFailure(failure)) {
558
+ st.stats.skippedPermanent += 1
559
+ onLog(sessionId, `检测到永久性错误(${failure.code}${failure.status ? ` HTTP ${failure.status}` : ''}),跳过自动续跑`)
560
+ return { action: 'permanent-error-skipped', failure, scheduled: false }
561
+ }
562
+ const res = schedule(sessionId, 'turn/end:error')
563
+ return { action: 'transient-error-scheduled', failure, ...res }
564
+ }
565
+ return null
566
+ }
567
+
568
+ default:
569
+ return null
570
+ }
571
+ }
572
+
573
+ function notifyIdleOrInterrupt(sessionId, { kind = 'idle-stall', reason = '', failure = null, immediate = false } = {}) {
574
+ const sid = String(sessionId || '').trim()
575
+ if (!sid) return { scheduled: false, reason: 'no-session' }
576
+ const st = getSessionState(sid)
577
+ if (!st) return { scheduled: false, reason: 'no-session' }
578
+ const rootId = resolveRootSessionId(sid) || sid
579
+ if (isChiefStopped(rootId, sid)) {
580
+ st.stats.skippedStopped += 1
581
+ cancelPending(sid, '参谋长处于停止状态')
582
+ return { scheduled: false, reason: 'chief-stopped' }
583
+ }
584
+ if (failure) {
585
+ st.lastFailure = parseFailureFacts(failure) || null
586
+ if (st.lastFailure && !isTransientFailure(st.lastFailure)) {
587
+ st.stats.skippedPermanent += 1
588
+ return { scheduled: false, reason: 'permanent-error' }
589
+ }
590
+ }
591
+ return schedule(sid, kind, { detail: reason, ...(immediate ? { delayMs: 0 } : {}) })
592
+ }
593
+
594
+ function getStats(sessionId = '') {
595
+ if (sessionId) {
596
+ const st = sessions.get(String(sessionId).trim())
597
+ if (!st) return { consecutive: 0, hasPendingTimer: false, stats: { scheduled: 0, sent: 0, skippedPermanent: 0, skippedStopped: 0, skippedAborted: 0 } }
598
+ return {
599
+ consecutive: st.consecutive,
600
+ hasPendingTimer: Boolean(st.timer),
601
+ lastFailure: st.lastFailure,
602
+ lastToolSummary: st.lastToolSummary,
603
+ stats: { ...st.stats },
604
+ }
605
+ }
606
+ return { trackedSessions: sessions.size }
607
+ }
608
+
609
+ function dispose() {
610
+ for (const st of sessions.values()) {
611
+ if (st.timer) {
612
+ clearTimeout(st.timer)
613
+ st.timer = null
614
+ }
615
+ }
616
+ sessions.clear()
617
+ }
618
+
619
+ return {
620
+ onSessionEvent,
621
+ notifyIdleOrInterrupt,
622
+ cancelSession: cancelPending,
623
+ fireNow: fire,
624
+ getStats,
625
+ dispose,
626
+ }
627
+ }