dsh-client-auto-continue 0.11.3 → 0.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -203,6 +203,46 @@ function fillTemplate(template, ctx) {
203
203
  return template.replace(/\{code\}/g, ctx.facts?.code ?? "").replace(/\{message\}/g, ctx.facts?.message ?? "").replace(/\{status\}/g, ctx.facts?.status !== void 0 ? String(ctx.facts.status) : "").replace(/\{tool\}/g, ctx.tool ?? "").replace(/\{turn\}/g, ctx.turn !== void 0 ? String(ctx.turn) : "").replace(/\{errorCount\}/g, ctx.errorCount !== void 0 ? String(ctx.errorCount) : "").replace(/\{sessionTitle\}/g, ctx.sessionTitle ?? "").replace(/\{elapsed\}/g, formatElapsed(ctx.elapsedMs)).replace(/\{result\}/g, ctx.result ?? "");
204
204
  }
205
205
  var TOOL_RESULT_CAP = 160;
206
+ function stableFingerprint(value) {
207
+ let first = 2166136261;
208
+ let second = 2654435769;
209
+ let length = 0;
210
+ const feed = (text) => {
211
+ length += text.length;
212
+ for (let i = 0; i < text.length; i += 1) {
213
+ const code = text.charCodeAt(i);
214
+ first = Math.imul(first ^ code, 16777619) >>> 0;
215
+ second = Math.imul(second ^ code, 2246822507) >>> 0;
216
+ second = (second ^ second >>> 13) >>> 0;
217
+ }
218
+ };
219
+ const walk = (part) => {
220
+ if (part === null) {
221
+ feed("null");
222
+ } else if (Array.isArray(part)) {
223
+ feed("[");
224
+ for (const item of part) {
225
+ walk(item);
226
+ feed(",");
227
+ }
228
+ feed("]");
229
+ } else if (typeof part === "object") {
230
+ feed("{");
231
+ const record = part;
232
+ for (const key of Object.keys(record).sort()) {
233
+ feed(JSON.stringify(key));
234
+ feed(":");
235
+ walk(record[key]);
236
+ feed(",");
237
+ }
238
+ feed("}");
239
+ } else {
240
+ feed(`${typeof part}:${JSON.stringify(part) ?? String(part)}`);
241
+ }
242
+ };
243
+ walk(value);
244
+ return `${first.toString(16).padStart(8, "0")}${second.toString(16).padStart(8, "0")}:${length}`;
245
+ }
206
246
  function extractText(blocks, cap) {
207
247
  let out = "";
208
248
  const walk = (value) => {
@@ -222,10 +262,262 @@ function extractText(blocks, cap) {
222
262
  walk(blocks);
223
263
  return out.slice(0, cap);
224
264
  }
265
+ function toolCorrelationKey(data, callId) {
266
+ if (callId === void 0 || typeof data.turn !== "number" || typeof data.step !== "number") {
267
+ return void 0;
268
+ }
269
+ return JSON.stringify([data.turn, data.step, callId]);
270
+ }
271
+ function resultBlock(data) {
272
+ return data.message?.content?.find((part) => part.type === "tool-result");
273
+ }
274
+ function toolResultCallId(data) {
275
+ if (resultBlock(data) === void 0) return void 0;
276
+ const sourceId = data.message?.source?.kind === "tool" ? data.message.source.callId : void 0;
277
+ const blockId = resultBlock(data)?.toolCallId;
278
+ const source = typeof sourceId === "string" && sourceId !== "" ? sourceId : void 0;
279
+ const block = typeof blockId === "string" && blockId !== "" ? blockId : void 0;
280
+ if (source !== void 0 && block !== void 0 && source !== block) return void 0;
281
+ return source ?? block;
282
+ }
225
283
  function toolResultFacts(data) {
226
- const failed = data.error !== void 0 || data.message?.content?.[0]?.isError === true;
227
- return { ok: !failed, excerpt: extractText(data.message?.content?.[0]?.content, TOOL_RESULT_CAP) };
284
+ const result = resultBlock(data);
285
+ const failed = data.error !== void 0 || result?.isError === true;
286
+ return {
287
+ ok: !failed,
288
+ excerpt: extractText(result?.content, TOOL_RESULT_CAP),
289
+ identity: stableFingerprint({ content: result?.content ?? [], isError: failed })
290
+ };
228
291
  }
292
+ var MAX_PENDING_TOOL_CALLS = 64;
293
+ var MAX_SEEN_TOOL_CALL_IDS = 256;
294
+ var ToolInvocationTracker = class {
295
+ constructor() {
296
+ this.pendingById = /* @__PURE__ */ new Map();
297
+ this.pendingInOrder = [];
298
+ this.seenCalls = /* @__PURE__ */ new Map();
299
+ this.seenInOrder = [];
300
+ this.lastEventSeq = -1;
301
+ }
302
+ reset() {
303
+ this.pendingById.clear();
304
+ this.pendingInOrder.length = 0;
305
+ this.seenCalls.clear();
306
+ this.seenInOrder.length = 0;
307
+ this.latest = void 0;
308
+ this.run = void 0;
309
+ this.repeatSignal = void 0;
310
+ this.lastEventSeq = -1;
311
+ }
312
+ /** 新回合边界:清空工具态,同时把重放水位推进到 turn/start。 */
313
+ startTurn(seq) {
314
+ if (!Number.isSafeInteger(seq) || seq < 0 || seq <= this.lastEventSeq) return;
315
+ this.reset();
316
+ this.lastEventSeq = seq;
317
+ }
318
+ /** 回合已结束:保留最后一次调用的护栏,丢弃不再可用的 loop 关联态。 */
319
+ resetRepeat() {
320
+ this.pendingById.clear();
321
+ this.pendingInOrder.length = 0;
322
+ this.seenCalls.clear();
323
+ this.seenInOrder.length = 0;
324
+ this.run = void 0;
325
+ this.repeatSignal = void 0;
326
+ }
327
+ recordCall(event) {
328
+ if (!this.acceptEventSeq(event.seq)) return false;
329
+ this.repeatSignal = void 0;
330
+ const data = event.data;
331
+ if (typeof data.name !== "string") {
332
+ this.breakCorrelation();
333
+ return true;
334
+ }
335
+ const key = `${data.name}
336
+ ${typeof data.arguments === "string" ? data.arguments : ""}`;
337
+ const callId = typeof data.callId === "string" && data.callId !== "" ? data.callId : void 0;
338
+ const id = toolCorrelationKey(data, callId);
339
+ if (id === void 0) {
340
+ this.breakCorrelation({
341
+ id: void 0,
342
+ name: data.name,
343
+ key,
344
+ result: void 0,
345
+ resultSeq: void 0
346
+ });
347
+ return true;
348
+ }
349
+ const seen = this.seenCalls.get(id);
350
+ if (seen !== void 0) {
351
+ this.breakCorrelation({
352
+ id: void 0,
353
+ name: data.name,
354
+ key,
355
+ result: void 0,
356
+ resultSeq: void 0
357
+ });
358
+ return true;
359
+ }
360
+ const call = {
361
+ id,
362
+ name: data.name,
363
+ key,
364
+ result: void 0,
365
+ resultSeq: void 0
366
+ };
367
+ this.latest = call;
368
+ this.pendingById.set(id, call);
369
+ this.pendingInOrder.push(call);
370
+ this.seenCalls.set(id, call);
371
+ this.seenInOrder.push(id);
372
+ this.trim(call);
373
+ return true;
374
+ }
375
+ recordResult(event) {
376
+ if (!this.acceptEventSeq(event.seq)) return void 0;
377
+ const data = event.data;
378
+ const id = toolCorrelationKey(data, toolResultCallId(data));
379
+ if (id === void 0) {
380
+ this.breakCorrelation(this.latest);
381
+ return void 0;
382
+ }
383
+ const surfaceOp = event.surfaceOp;
384
+ if (typeof surfaceOp === "object" && surfaceOp !== null) {
385
+ const call2 = this.seenCalls.get(id);
386
+ if (surfaceOp.start !== surfaceOp.end || call2 === void 0 || call2.result === void 0 || call2.resultSeq !== surfaceOp.start) {
387
+ this.breakCorrelation(this.latest);
388
+ return void 0;
389
+ }
390
+ call2.result = toolResultFacts(data);
391
+ call2.resultSeq = event.seq;
392
+ this.breakCorrelation(this.latest);
393
+ return void 0;
394
+ }
395
+ const call = this.pendingById.get(id);
396
+ if (call === void 0) {
397
+ const seen = this.seenCalls.get(id);
398
+ const duplicate = seen?.result;
399
+ const incoming = toolResultFacts(data);
400
+ if (seen !== void 0 && duplicate !== void 0 && seen.resultSeq === event.seq && duplicate.identity === incoming.identity) {
401
+ return void 0;
402
+ }
403
+ if (seen !== void 0 && duplicate !== void 0) {
404
+ seen.result = void 0;
405
+ seen.resultSeq = void 0;
406
+ }
407
+ this.breakCorrelation(this.latest);
408
+ return void 0;
409
+ }
410
+ if (call.result !== void 0) {
411
+ const incoming = toolResultFacts(data);
412
+ if (call.resultSeq === event.seq && call.result.identity === incoming.identity) {
413
+ return void 0;
414
+ }
415
+ call.result = void 0;
416
+ call.resultSeq = void 0;
417
+ this.breakCorrelation(this.latest);
418
+ return void 0;
419
+ }
420
+ call.result = toolResultFacts(data);
421
+ call.resultSeq = event.seq;
422
+ return this.drainCompleted();
423
+ }
424
+ guard() {
425
+ const latest = this.latest;
426
+ if (latest === void 0) return { kind: "none" };
427
+ if (latest.result === void 0) return { kind: "pending", tool: latest.name };
428
+ if (latest.result.ok) {
429
+ return { kind: "done", tool: latest.name, result: latest.result.excerpt };
430
+ }
431
+ return { kind: "failed", tool: latest.name };
432
+ }
433
+ lastTool() {
434
+ return this.latest?.name;
435
+ }
436
+ /** 下一模型 step 是稳定边界;此前 replacement/新调用会先清除候选。 */
437
+ confirmRepeatAtStep(seq) {
438
+ if (!this.acceptEventSeq(seq)) return void 0;
439
+ const signal = this.pendingInOrder.length === 0 ? this.repeatSignal : void 0;
440
+ this.repeatSignal = void 0;
441
+ return signal;
442
+ }
443
+ /** 非工具 surface range replacement(如 compaction summary)同样终止旧工具证据。 */
444
+ recordSurfaceReplacement(seq) {
445
+ if (!this.acceptEventSeq(seq)) return;
446
+ this.breakCorrelation(this.latest);
447
+ }
448
+ restore(events, untilSeq) {
449
+ this.reset();
450
+ for (const event of events) {
451
+ if (event.seq >= untilSeq) continue;
452
+ if (event.type === "turn/start") this.startTurn(event.seq);
453
+ else if (event.type === "step/start") this.confirmRepeatAtStep(event.seq);
454
+ else if (event.type === "tool/call") this.recordCall(event);
455
+ else if (event.type === "tool/result") this.recordResult(event);
456
+ else if ((event.type === "user/message" || event.type === "assistant/message") && typeof event.surfaceOp === "object" && event.surfaceOp !== null) {
457
+ this.recordSurfaceReplacement(event.seq);
458
+ }
459
+ }
460
+ }
461
+ acceptEventSeq(seq) {
462
+ if (!Number.isSafeInteger(seq) || seq < 0) {
463
+ this.breakCorrelation(this.latest);
464
+ return false;
465
+ }
466
+ if (seq <= this.lastEventSeq) return false;
467
+ this.lastEventSeq = seq;
468
+ return true;
469
+ }
470
+ breakCorrelation(latest, preserve) {
471
+ this.pendingById.clear();
472
+ this.pendingInOrder.length = 0;
473
+ this.invalidateRunHistory();
474
+ this.latest = latest;
475
+ if (preserve?.id !== void 0 && preserve.result === void 0 && this.seenCalls.get(preserve.id) === preserve) {
476
+ this.pendingById.set(preserve.id, preserve);
477
+ this.pendingInOrder.push(preserve);
478
+ }
479
+ }
480
+ invalidateRunHistory() {
481
+ this.run = void 0;
482
+ this.repeatSignal = void 0;
483
+ }
484
+ trim(current) {
485
+ while (this.pendingInOrder.length > MAX_PENDING_TOOL_CALLS) {
486
+ this.breakCorrelation(current, current);
487
+ }
488
+ while (this.seenInOrder.length > MAX_SEEN_TOOL_CALL_IDS) {
489
+ const id = this.seenInOrder.shift();
490
+ if (id !== void 0) {
491
+ this.seenCalls.delete(id);
492
+ this.breakCorrelation(current, current);
493
+ }
494
+ }
495
+ }
496
+ drainCompleted() {
497
+ let advanced = false;
498
+ while (this.pendingInOrder[0]?.result !== void 0) {
499
+ const call = this.pendingInOrder.shift();
500
+ if (call === void 0 || call.result === void 0) break;
501
+ advanced = true;
502
+ if (call.id !== void 0) this.pendingById.delete(call.id);
503
+ this.advanceRun(call);
504
+ }
505
+ if (!advanced) return void 0;
506
+ return this.refreshRepeatSignal();
507
+ }
508
+ advanceRun(call) {
509
+ if (call.result === void 0) return;
510
+ if (this.run?.key === call.key && this.run.identity === call.result.identity) {
511
+ this.run.count += 1;
512
+ } else {
513
+ this.run = { key: call.key, tool: call.name, identity: call.result.identity, count: 1 };
514
+ }
515
+ }
516
+ refreshRepeatSignal() {
517
+ this.repeatSignal = this.pendingInOrder.length === 0 && this.run !== void 0 ? { tool: this.run.tool, count: this.run.count } : void 0;
518
+ return this.repeatSignal;
519
+ }
520
+ };
229
521
  function effectiveCooldown(consecutive, base, factor, max) {
230
522
  const multiplier = Math.pow(factor, consecutive);
231
523
  return Math.min(Math.max(base, base * multiplier), Math.max(base, max));
@@ -244,38 +536,56 @@ function emptyDayStats() {
244
536
  }
245
537
  var freshState = () => ({
246
538
  consecutive: 0,
247
- lastAutoAt: 0,
248
539
  lastAttemptAt: 0,
249
- lastSentText: "",
540
+ pendingEchoMessageIds: /* @__PURE__ */ new Map(),
250
541
  pendingTimer: void 0,
251
542
  running: void 0,
252
543
  queued: 0,
253
544
  subagent: false,
254
545
  lastFailure: void 0,
255
546
  lastFailureAt: 0,
256
- lastTool: void 0,
257
- lastToolResult: void 0,
547
+ tools: new ToolInvocationTracker(),
258
548
  lastTurn: void 0,
259
549
  pendingRecoveryAt: 0,
260
550
  shortRun: 0,
261
551
  lastShortAt: 0,
262
552
  lastAssistantText: "",
263
553
  sameTextRun: 0,
264
- toolRun: void 0,
554
+ streamTail: "",
555
+ streamLastSegment: "",
556
+ streamRepeatRun: 0,
265
557
  loopFired: false,
266
- loopCancelled: false,
267
558
  loopRetryTimer: void 0
268
559
  });
269
560
  var RECOVERY_WINDOW_MS = 10 * 60 * 1e3;
270
561
  var ECHO_WINDOW_MS = 10 * 60 * 1e3;
562
+ var MAX_PENDING_ECHO_MESSAGE_IDS = 64;
563
+ function prunePendingEchoMessageIds(state, now) {
564
+ for (const [messageId, queuedAt] of state.pendingEchoMessageIds) {
565
+ if (now - queuedAt > ECHO_WINDOW_MS) state.pendingEchoMessageIds.delete(messageId);
566
+ }
567
+ }
568
+ function trackPendingEcho(state, messageId) {
569
+ const now = Date.now();
570
+ prunePendingEchoMessageIds(state, now);
571
+ state.pendingEchoMessageIds.set(messageId, now);
572
+ while (state.pendingEchoMessageIds.size > MAX_PENDING_ECHO_MESSAGE_IDS) {
573
+ const oldest = state.pendingEchoMessageIds.keys().next();
574
+ if (oldest.done) break;
575
+ state.pendingEchoMessageIds.delete(oldest.value);
576
+ }
577
+ }
578
+ function forgetPendingEcho(state, messageId) {
579
+ state.pendingEchoMessageIds.delete(messageId);
580
+ }
271
581
  function isOurEcho(state, event) {
272
582
  if (event.type !== "user/message") return false;
273
583
  const message = event.data;
274
584
  if (message.source.kind !== "user") return false;
275
- if (state.lastSentText === "") return false;
276
- if (Date.now() - state.lastAutoAt > ECHO_WINDOW_MS) return false;
277
- const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("");
278
- return text === state.lastSentText;
585
+ if (state.pendingEchoMessageIds.size === 0) return false;
586
+ const now = Date.now();
587
+ prunePendingEchoMessageIds(state, now);
588
+ return state.pendingEchoMessageIds.delete(message.id);
279
589
  }
280
590
 
281
591
  // src/host/engine.ts
@@ -301,6 +611,41 @@ var NOTICE_COPY = {
301
611
  stoppedBody: (sessionId, count) => `${sessionId}: ${count} consecutive failures; manual intervention required`
302
612
  }
303
613
  };
614
+ var LOOP_GUARD_CANCEL_CAUSE = {
615
+ kind: "hook",
616
+ reason: "dsh-auto-continue:loop-guard"
617
+ };
618
+ var STREAM_NEAR_DUPLICATE_MAX_CHARS = 2048;
619
+ var STREAM_TAIL_MAX_CHARS = 4096;
620
+ function snapshotSessionEvents(session) {
621
+ const compatible = session;
622
+ if (typeof compatible.snapshotEvents === "function") return compatible.snapshotEvents();
623
+ if (compatible.events !== void 0) return compatible.events;
624
+ throw new TypeError("session exposes neither snapshotEvents() nor events");
625
+ }
626
+ function parseFailureFacts(value) {
627
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
628
+ const failure = value;
629
+ const code = typeof failure.code === "string" && failure.code.trim() !== "" ? failure.code : void 0;
630
+ const message = typeof failure.message === "string" && failure.message.trim() !== "" ? failure.message : void 0;
631
+ const status = typeof failure.status === "number" && Number.isFinite(failure.status) ? failure.status : void 0;
632
+ if (code === void 0 && message === void 0 && status === void 0) return void 0;
633
+ return {
634
+ code: code ?? "UNKNOWN",
635
+ message: message ?? code ?? `HTTP ${status}`,
636
+ ...status !== void 0 ? { status } : {}
637
+ };
638
+ }
639
+ function readReasonKind(value) {
640
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
641
+ const kind = value.kind;
642
+ return typeof kind === "string" && kind.trim() !== "" ? kind : void 0;
643
+ }
644
+ function isLoopGuardCancelReason(value) {
645
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
646
+ const cause = value;
647
+ return cause.kind === LOOP_GUARD_CANCEL_CAUSE.kind && cause.reason === LOOP_GUARD_CANCEL_CAUSE.reason;
648
+ }
304
649
  var AutoContinueRunner = class {
305
650
  /**
306
651
  * @param ctx - host plugin context (agents registry, session events, settings).
@@ -316,10 +661,15 @@ var AutoContinueRunner = class {
316
661
  this.noticeListeners = /* @__PURE__ */ new Set();
317
662
  this.stateListeners = /* @__PURE__ */ new Set();
318
663
  this.disposed = false;
319
- this.disposeSessionEvents = ctx.on(
320
- "session/event",
321
- (session, event) => this.onHostEvent(session, event)
322
- );
664
+ this.disposeSessionEvents = ctx.on("session/event", (session, event) => {
665
+ try {
666
+ this.onHostEvent(session, event);
667
+ } catch (error) {
668
+ console.error(
669
+ `[auto-continue] 会话事件处理异常 ${session.id}: ${error instanceof Error ? error.message : String(error)}`
670
+ );
671
+ }
672
+ });
323
673
  const config = this.getConfig();
324
674
  if (config.scanOnBoot) {
325
675
  void this.bootScanLoop();
@@ -404,40 +754,23 @@ var AutoContinueRunner = class {
404
754
  */
405
755
  onHostEvent(session, event) {
406
756
  const sessionId = session.id;
757
+ if ((event.type === "user/message" || event.type === "assistant/message") && typeof event.surfaceOp === "object" && event.surfaceOp !== null) {
758
+ this.state(sessionId).tools.recordSurfaceReplacement(event.seq);
759
+ return;
760
+ }
407
761
  if (event.type === "tool/call") {
408
- const name = event.data.name;
409
- if (typeof name === "string") {
410
- const state = this.state(sessionId);
411
- state.lastTool = name;
412
- state.lastToolResult = "pending";
413
- state.shortRun = 0;
414
- const key = `${name}
415
- ${event.data.arguments}`;
416
- if (state.toolRun?.key === key) {
417
- state.toolRun.waiting = true;
418
- } else {
419
- state.toolRun = { key, count: 1, lastResult: void 0, waiting: false };
420
- }
421
- }
762
+ const state = this.state(sessionId);
763
+ if (state.tools.recordCall(event)) state.shortRun = 0;
422
764
  } else if (event.type === "tool/result") {
423
765
  const state = this.state(sessionId);
424
- if (state.lastToolResult === "pending") {
425
- const facts = toolResultFacts(event.data);
426
- state.lastToolResult = facts;
427
- const run = state.toolRun;
428
- if (run !== void 0 && run.waiting) {
429
- run.waiting = false;
430
- if (run.lastResult !== void 0 && run.lastResult === facts.excerpt) {
431
- run.count += 1;
432
- this.checkLoop(sessionId, state);
433
- } else {
434
- run.lastResult = facts.excerpt;
435
- run.count = 1;
436
- }
437
- } else if (run !== void 0 && !run.waiting) {
438
- run.lastResult = facts.excerpt;
439
- }
440
- }
766
+ state.tools.recordResult(event);
767
+ } else if (event.type === "step/start") {
768
+ const state = this.state(sessionId);
769
+ const repeat = state.tools.confirmRepeatAtStep(event.seq);
770
+ if (repeat !== void 0) this.checkLoop(sessionId, state, repeat);
771
+ } else if (event.type === "assistant/chunk") {
772
+ const state = this.state(sessionId);
773
+ this.onAssistantChunk(sessionId, state, event);
441
774
  } else if (event.type === "assistant/message") {
442
775
  const state = this.state(sessionId);
443
776
  this.onAssistantMessage(sessionId, state, event);
@@ -450,6 +783,98 @@ ${event.data.arguments}`;
450
783
  if (!Array.isArray(content)) return "";
451
784
  return content.filter((part) => part.type === "text").map((part) => part.text).join("");
452
785
  }
786
+ assistantChunkText(event) {
787
+ return event.data.chunk.type === "text-delta" ? event.data.chunk.text : "";
788
+ }
789
+ normalizedSegment(text) {
790
+ return text.replace(/\s+/g, " ").trim();
791
+ }
792
+ isNearDuplicateSegment(left, right) {
793
+ if (left === right) return true;
794
+ const leftLen = left.length;
795
+ const rightLen = right.length;
796
+ const longer = Math.max(leftLen, rightLen);
797
+ const shorter = Math.min(leftLen, rightLen);
798
+ if (shorter === 0 || shorter / longer < 0.85) return false;
799
+ if (longer > STREAM_NEAR_DUPLICATE_MAX_CHARS) return false;
800
+ const maxDistance = Math.max(6, Math.floor(longer * 0.08));
801
+ if (Math.abs(leftLen - rightLen) > maxDistance) return false;
802
+ return this.withinEditDistance(left, right, maxDistance);
803
+ }
804
+ withinEditDistance(left, right, maxDistance) {
805
+ if (left === right) return true;
806
+ if (maxDistance < 0) return false;
807
+ const leftLen = left.length;
808
+ const rightLen = right.length;
809
+ if (Math.abs(leftLen - rightLen) > maxDistance) return false;
810
+ if (leftLen === 0 || rightLen === 0) return Math.max(leftLen, rightLen) <= maxDistance;
811
+ const unreachable = maxDistance + 1;
812
+ let previous = new Int32Array(rightLen + 1);
813
+ let current = new Int32Array(rightLen + 1);
814
+ previous.fill(unreachable);
815
+ for (let col = 0; col <= Math.min(rightLen, maxDistance); col += 1) {
816
+ previous[col] = col;
817
+ }
818
+ for (let row = 1; row <= leftLen; row += 1) {
819
+ current.fill(unreachable);
820
+ if (row <= maxDistance) current[0] = row;
821
+ const firstCol = Math.max(1, row - maxDistance);
822
+ const lastCol = Math.min(rightLen, row + maxDistance);
823
+ let minInRow = unreachable;
824
+ for (let col = firstCol; col <= lastCol; col += 1) {
825
+ const insertion = (current[col - 1] ?? unreachable) + 1;
826
+ const deletion = (previous[col] ?? unreachable) + 1;
827
+ const substitution = (previous[col - 1] ?? unreachable) + (left.charCodeAt(row - 1) === right.charCodeAt(col - 1) ? 0 : 1);
828
+ const score = Math.min(insertion, deletion, substitution, unreachable);
829
+ current[col] = score;
830
+ if (score < minInRow) minInRow = score;
831
+ }
832
+ if (minInRow > maxDistance) return false;
833
+ [previous, current] = [current, previous];
834
+ }
835
+ return (previous[rightLen] ?? unreachable) <= maxDistance;
836
+ }
837
+ noteStreamSegment(sessionId, state, segment) {
838
+ const normalized = this.normalizedSegment(segment);
839
+ const config = this.getConfig();
840
+ if (normalized === "") return;
841
+ if (normalized.length < config.loopShortChars) {
842
+ state.streamLastSegment = "";
843
+ state.streamRepeatRun = 0;
844
+ return;
845
+ }
846
+ if (state.streamLastSegment !== "" && this.isNearDuplicateSegment(normalized, state.streamLastSegment)) {
847
+ state.streamRepeatRun += 1;
848
+ state.streamLastSegment = normalized;
849
+ } else {
850
+ state.streamLastSegment = normalized;
851
+ state.streamRepeatRun = 1;
852
+ }
853
+ if (state.streamRepeatRun >= config.loopRepeatText) {
854
+ this.log(
855
+ `检测到流式消息内复读 ${sessionId}: 连续 ${state.streamRepeatRun} 段近似重复文本`
856
+ );
857
+ this.interruptLoop(sessionId, state);
858
+ }
859
+ }
860
+ onAssistantChunk(sessionId, state, event) {
861
+ if (!this.getConfig().loopGuard || !state.running || state.loopFired) return;
862
+ const chunk = this.assistantChunkText(event);
863
+ if (chunk === "") return;
864
+ const merged = `${state.streamTail}${chunk}`.replace(/\r/g, "");
865
+ const pieces = merged.split(/\n(?:[ \t]*\n)+/u);
866
+ const tail = pieces.pop() ?? "";
867
+ for (const piece of pieces) this.noteStreamSegment(sessionId, state, piece);
868
+ if (tail.length <= STREAM_TAIL_MAX_CHARS) {
869
+ state.streamTail = tail;
870
+ return;
871
+ }
872
+ state.streamTail = tail.slice(-STREAM_TAIL_MAX_CHARS);
873
+ if (/\S/u.test(tail)) {
874
+ state.streamLastSegment = "";
875
+ state.streamRepeatRun = 0;
876
+ }
877
+ }
453
878
  onAssistantMessage(sessionId, state, event) {
454
879
  if (!this.getConfig().loopGuard) return;
455
880
  const text = this.assistantText(event);
@@ -471,53 +896,55 @@ ${event.data.arguments}`;
471
896
  state.shortRun = 0;
472
897
  state.lastShortAt = 0;
473
898
  }
899
+ const streamTail = state.streamTail;
900
+ state.streamTail = "";
901
+ if (streamTail !== "") this.noteStreamSegment(sessionId, state, streamTail);
902
+ state.streamLastSegment = "";
903
+ state.streamRepeatRun = 0;
474
904
  this.checkLoop(sessionId, state);
475
905
  }
476
906
  /** 两个循环信号的公共检查; 命中且本回合未打断过则打断。 */
477
- checkLoop(sessionId, state) {
907
+ checkLoop(sessionId, state, toolRepeat) {
478
908
  if (!this.getConfig().loopGuard) return;
479
909
  if (state.loopFired) return;
480
910
  if (!state.running) return;
481
911
  const config = this.getConfig();
482
912
  if (state.sameTextRun >= config.loopRepeatText) {
483
913
  this.log(`检测到空转循环 ${sessionId}: 连续 ${state.sameTextRun} 条相同消息`);
484
- void this.interruptLoop(sessionId, state);
914
+ this.interruptLoop(sessionId, state);
485
915
  } else if (state.shortRun >= config.loopShortCount) {
486
916
  this.log(`检测到空转循环 ${sessionId}: 连续 ${state.shortRun} 条短句且无工具调用`);
487
- void this.interruptLoop(sessionId, state);
488
- } else if (state.toolRun !== void 0 && state.toolRun.count >= config.loopToolRepeat) {
489
- const toolName = state.toolRun.key.split("\n")[0] ?? "?";
490
- this.log(`检测到工具死循环 ${sessionId}: 「${toolName}」连续 ${state.toolRun.count} 次(同参数同结果)`);
491
- void this.interruptLoop(sessionId, state);
917
+ this.interruptLoop(sessionId, state);
918
+ } else if (toolRepeat !== void 0 && toolRepeat.count >= config.loopToolRepeat) {
919
+ this.log(`检测到工具死循环 ${sessionId}: 「${toolRepeat.tool}」连续 ${toolRepeat.count} 次(同参数同结果)`);
920
+ this.interruptLoop(sessionId, state);
492
921
  }
493
922
  }
494
923
  /**
495
924
  * 打断运行中的回合: cancel(带来源标记)+ 进冷却。
496
- * 随后的 turn/end aborted 会因 loopCancelled 走「可恢复中断」路径,
497
- * 用 loopText 重启回合——不会与用户手动停止混淆。
925
+ * 只有随后持久化的 turn/end 精确携带专属 hook cause 时,
926
+ * 才会用 loopText 重启回合——DSH 的 first-cause 语义保证用户 Stop 优先。
498
927
  */
499
- async interruptLoop(sessionId, state) {
928
+ interruptLoop(sessionId, state) {
500
929
  if (state.loopFired) return;
501
930
  if (Date.now() - state.lastAttemptAt < this.cooldownFor(state)) {
502
931
  this.log(`跳过循环打断 ${sessionId}: 处于冷却期`);
503
932
  return;
504
933
  }
505
934
  state.loopFired = true;
506
- state.loopCancelled = true;
507
935
  state.lastAttemptAt = Date.now();
508
- this.bumpStat({ looped: 1 });
509
936
  try {
510
937
  const agent = this.ctx.agents.get(sessionId);
511
938
  if (agent === void 0) {
512
939
  this.log(`打断循环失败 ${sessionId}: 无 live agent`);
513
- state.loopCancelled = false;
940
+ state.loopFired = false;
514
941
  return;
515
942
  }
516
- agent.cancel({ kind: "user" }, { keepInbox: true });
943
+ agent.cancel(LOOP_GUARD_CANCEL_CAUSE, { keepInbox: true });
517
944
  this.log(`已打断循环 ${sessionId}: cancel 已受理`);
518
945
  } catch (error) {
519
946
  this.log(`打断循环失败 ${sessionId}: ${error instanceof Error ? error.message : String(error)}`);
520
- state.loopCancelled = false;
947
+ state.loopFired = false;
521
948
  }
522
949
  }
523
950
  onSessionEvent(sessionId, event) {
@@ -525,15 +952,15 @@ ${event.data.arguments}`;
525
952
  switch (event.type) {
526
953
  case "turn/start":
527
954
  state.running = true;
528
- state.lastTool = void 0;
529
- state.lastToolResult = void 0;
955
+ state.tools.startTurn(event.seq);
530
956
  state.shortRun = 0;
531
957
  state.lastShortAt = 0;
532
958
  state.lastAssistantText = "";
533
959
  state.sameTextRun = 0;
534
- state.toolRun = void 0;
960
+ state.streamTail = "";
961
+ state.streamLastSegment = "";
962
+ state.streamRepeatRun = 0;
535
963
  state.loopFired = false;
536
- state.loopCancelled = false;
537
964
  if (state.loopRetryTimer !== void 0) {
538
965
  clearTimeout(state.loopRetryTimer);
539
966
  state.loopRetryTimer = void 0;
@@ -542,22 +969,31 @@ ${event.data.arguments}`;
542
969
  break;
543
970
  case "turn/end": {
544
971
  state.running = false;
972
+ const loopCancelPending = state.loopFired;
973
+ state.loopFired = false;
545
974
  this.cancelPending(sessionId, "收到新的 turn/end");
546
975
  const reason = event.data.reason;
547
- if (reason.kind === "completed") {
976
+ const reasonKind = readReasonKind(reason);
977
+ if (reasonKind === void 0) {
978
+ console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: reason 无法解释`);
979
+ break;
980
+ }
981
+ if (reasonKind === "completed") {
548
982
  state.consecutive = 0;
549
983
  state.lastFailure = void 0;
550
984
  this.noteRecovery(sessionId, "completed");
551
- } else if (reason.kind === "aborted") {
552
- if (state.loopCancelled) {
553
- state.loopCancelled = false;
554
- state.loopFired = false;
985
+ } else if (reasonKind === "aborted") {
986
+ if (isLoopGuardCancelReason(reason.reason)) {
987
+ if (loopCancelPending) this.bumpStat({ looped: 1 });
555
988
  state.pendingRecoveryAt = 0;
556
989
  state.shortRun = 0;
557
990
  state.lastShortAt = 0;
558
991
  state.lastAssistantText = "";
559
992
  state.sameTextRun = 0;
560
- state.toolRun = void 0;
993
+ state.streamTail = "";
994
+ state.streamLastSegment = "";
995
+ state.streamRepeatRun = 0;
996
+ state.tools.resetRepeat();
561
997
  const cooldown = this.cooldownFor(state);
562
998
  const remaining = cooldown - (Date.now() - state.lastAttemptAt);
563
999
  if (remaining > 0) {
@@ -578,22 +1014,22 @@ ${event.data.arguments}`;
578
1014
  state.consecutive = 0;
579
1015
  state.pendingRecoveryAt = 0;
580
1016
  }
581
- } else if (reason.kind === "blocked") {
582
- } else if (reason.kind === "interrupted") {
1017
+ } else if (reasonKind === "blocked") {
1018
+ } else if (reasonKind === "interrupted") {
583
1019
  state.consecutive = 0;
584
1020
  state.pendingRecoveryAt = 0;
585
- } else if (reason.kind === "error") {
586
- const error = reason.error;
587
- state.lastFailure = {
588
- code: typeof error.code === "string" ? error.code : "UNKNOWN",
589
- message: typeof error.message === "string" ? error.message : String(error),
590
- ...typeof error.status === "number" ? { status: error.status } : {}
591
- };
1021
+ } else if (reasonKind === "error") {
1022
+ const failure = parseFailureFacts(reason.error);
1023
+ if (failure === void 0) {
1024
+ console.error(`[auto-continue] 忽略畸形 turn/end ${sessionId}: error details 无法解释`);
1025
+ break;
1026
+ }
1027
+ state.lastFailure = failure;
592
1028
  state.lastTurn = event.data.turn;
593
1029
  state.lastFailureAt = Date.now();
594
1030
  this.noteRecovery(sessionId, "error");
595
1031
  this.onTurnFailure(sessionId, "turn/end:error", state.lastFailure);
596
- } else if (reason.kind === "max-tokens") {
1032
+ } else if (reasonKind === "max-tokens") {
597
1033
  state.lastFailureAt = Date.now();
598
1034
  this.noteRecovery(sessionId, "error");
599
1035
  this.schedule(sessionId, "turn/end:max-tokens");
@@ -789,16 +1225,19 @@ ${event.data.arguments}`;
789
1225
  }
790
1226
  state.lastAttemptAt = Date.now();
791
1227
  try {
792
- agent.followup(
793
- createUserMessage({
794
- content: [{ type: "text", text }],
795
- source: { kind: "user" }
796
- })
797
- );
1228
+ const message = createUserMessage({
1229
+ content: [{ type: "text", text }],
1230
+ source: { kind: "user" }
1231
+ });
1232
+ trackPendingEcho(state, message.id);
1233
+ try {
1234
+ agent.followup(message);
1235
+ } catch (error) {
1236
+ forgetPendingEcho(state, message.id);
1237
+ throw error;
1238
+ }
798
1239
  const now = Date.now();
799
1240
  state.consecutive += 1;
800
- state.lastAutoAt = now;
801
- state.lastSentText = text;
802
1241
  state.pendingRecoveryAt = now;
803
1242
  this.bumpStat({ sent: 1, ...state.lastFailure !== void 0 ? { code: state.lastFailure.code } : {} });
804
1243
  this.log(`已自动发送「${text}」到 ${sessionId}(${reason}), 第 ${state.consecutive} 次连续`);
@@ -838,7 +1277,7 @@ ${event.data.arguments}`;
838
1277
  buildContinueText(config, state, template) {
839
1278
  let text = fillTemplate(template, {
840
1279
  facts: state.lastFailure,
841
- tool: state.lastTool,
1280
+ tool: state.tools.lastTool(),
842
1281
  turn: state.lastTurn,
843
1282
  errorCount: state.consecutive + 1,
844
1283
  elapsedMs: state.lastFailureAt > 0 ? Date.now() - state.lastFailureAt : void 0
@@ -854,12 +1293,7 @@ ${event.data.arguments}`;
854
1293
  }
855
1294
  /** 上一步工具调用的护栏状态(实时路径, 由 mux 帧维护)。 */
856
1295
  currentGuard(state) {
857
- if (state.lastTool === void 0 || state.lastToolResult === void 0) return { kind: "none" };
858
- if (state.lastToolResult === "pending") return { kind: "pending", tool: state.lastTool };
859
- if (state.lastToolResult.ok) {
860
- return { kind: "done", tool: state.lastTool, result: state.lastToolResult.excerpt };
861
- }
862
- return { kind: "failed", tool: state.lastTool };
1296
+ return state.tools.guard();
863
1297
  }
864
1298
  async bootScanLoop() {
865
1299
  await this.scanLoop(Infinity, 3e3);
@@ -892,8 +1326,21 @@ ${event.data.arguments}`;
892
1326
  for (const agent of this.ctx.agents.list()) {
893
1327
  const session = agent.session;
894
1328
  if (session.header.origin === "subagent") continue;
895
- candidates.push({ sessionId: session.id, events: session.events });
1329
+ const events = snapshotSessionEvents(session);
1330
+ const lastActivityAt = events.reduce(
1331
+ (latest, event) => Math.max(latest, event.time),
1332
+ Number.isFinite(session.header.createdAt) ? session.header.createdAt : 0
1333
+ );
1334
+ candidates.push({
1335
+ sessionId: session.id,
1336
+ events,
1337
+ lastActivityAt,
1338
+ listIndex: candidates.length
1339
+ });
896
1340
  }
1341
+ candidates.sort(
1342
+ (left, right) => right.lastActivityAt - left.lastActivityAt || left.listIndex - right.listIndex
1343
+ );
897
1344
  for (const candidate of candidates.slice(0, config.scanLimit)) {
898
1345
  if (this.disposed) return true;
899
1346
  const state = this.state(candidate.sessionId);
@@ -912,7 +1359,8 @@ ${event.data.arguments}`;
912
1359
  }
913
1360
  if (lastEnd === void 0) continue;
914
1361
  const reason = lastEnd.data.reason;
915
- if (!isNonHumanReason(reason.kind)) continue;
1362
+ const reasonKind = readReasonKind(reason);
1363
+ if (reasonKind === void 0 || !isNonHumanReason(reasonKind)) continue;
916
1364
  if (lastEnd.time < now - config.freshMs) continue;
917
1365
  let superseded = false;
918
1366
  for (const event of events) {
@@ -923,30 +1371,27 @@ ${event.data.arguments}`;
923
1371
  }
924
1372
  if (superseded) continue;
925
1373
  this.applyGuardFromEvents(state, events, lastEnd.seq);
926
- this.log(`扫描发现中断 ${candidate.sessionId}(turn/end:${reason.kind}), 安排自动继续`);
927
- this.schedule(candidate.sessionId, `scan:turn/end:${reason.kind}`);
1374
+ const scanReason = `scan:turn/end:${reasonKind}`;
1375
+ this.log(`扫描发现中断 ${candidate.sessionId}(turn/end:${reasonKind}), 交给恢复策略处理`);
1376
+ if (reasonKind === "error") {
1377
+ const failure = parseFailureFacts(reason.error);
1378
+ if (failure === void 0) {
1379
+ console.error(`[auto-continue] 忽略畸形扫描 turn/end ${candidate.sessionId}: error details 无法解释`);
1380
+ continue;
1381
+ }
1382
+ state.lastFailure = failure;
1383
+ state.lastTurn = lastEnd.data.turn;
1384
+ state.lastFailureAt = lastEnd.time;
1385
+ this.onTurnFailure(candidate.sessionId, scanReason, state.lastFailure);
1386
+ } else {
1387
+ this.schedule(candidate.sessionId, scanReason);
1388
+ }
928
1389
  }
929
1390
  return true;
930
1391
  }
931
1392
  /** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */
932
1393
  applyGuardFromEvents(state, events, untilSeq) {
933
- state.lastTool = void 0;
934
- state.lastToolResult = void 0;
935
- let call;
936
- for (const event of events) {
937
- if (event.seq >= untilSeq) continue;
938
- if (event.type === "tool/call") call = event;
939
- }
940
- if (call === void 0) return;
941
- state.lastTool = call.data.name;
942
- state.lastToolResult = "pending";
943
- for (const event of events) {
944
- if (event.seq <= call.seq || event.seq >= untilSeq) continue;
945
- if (event.type === "tool/result") {
946
- state.lastToolResult = toolResultFacts(event.data);
947
- break;
948
- }
949
- }
1394
+ state.tools.restore(events, untilSeq);
950
1395
  }
951
1396
  };
952
1397
 
@@ -1000,7 +1445,7 @@ var AutoContinueSchema = z2.object({
1000
1445
  loopWindowMs: z2.natural().min(1e3).default(3e4),
1001
1446
  /** Consecutive short sentences trip the loop guard. */
1002
1447
  loopShortCount: z2.natural().min(2).default(12),
1003
- /** Consecutive identical short sentences trip the loop guard (strongest spinning signal). */
1448
+ /** Consecutive identical assistant messages trip the loop guard (strongest signal; also used for streamed intra-message repetition). */
1004
1449
  loopRepeatText: z2.natural().min(2).default(4),
1005
1450
  /** Consecutive identical tool calls with identical arguments AND results trip the loop guard. */
1006
1451
  loopToolRepeat: z2.natural().min(2).default(5),