dsh-client-auto-continue 0.18.0 → 0.19.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.
- package/CHANGELOG.md +25 -0
- package/README.md +230 -310
- package/README.ru.md +382 -0
- package/README.zh.md +229 -308
- package/docs/auto-continue-workflow.archify.json +3 -3
- package/docs/auto-continue-workflow.en.archify.json +3 -3
- package/docs/auto-continue-workflow.en.html +1 -1
- package/docs/auto-continue-workflow.html +1 -1
- package/docs/auto-continue-workflow.ru.svg +530 -0
- package/docs/banner-ru-dark.svg +38 -0
- package/docs/banner-ru.svg +38 -0
- package/docs/demo-ru-static.svg +115 -0
- package/docs/demo-ru.svg +147 -0
- package/docs/releases/v0.19.0.md +62 -0
- package/docs/social-preview.png +0 -0
- package/docs/social-preview.svg +30 -1
- package/lib/client.js +297 -99
- package/lib/client.js.map +3 -3
- package/lib/index.js +258 -43
- package/lib/types/client/auto-continue-icon.d.ts +7 -0
- package/lib/types/client/bridge.d.ts +2 -0
- package/lib/types/client/composer-toggle.d.ts +2 -0
- package/lib/types/client/locales.d.ts +5 -0
- package/lib/types/client/settings-card.d.ts +1 -0
- package/lib/types/host/engine.d.ts +47 -4
- package/lib/types/index.d.ts +8 -0
- package/lib/types/shared/core.d.ts +15 -1
- package/locale/ru.json +6 -0
- package/package.json +5 -3
- package/scripts/build-docs-assets.mjs +126 -0
- package/src/client/auto-continue-icon.tsx +6 -27
- package/src/client/bridge.ts +26 -6
- package/src/client/composer-toggle.tsx +22 -11
- package/src/client/index.ts +5 -1
- package/src/client/locales.ts +215 -40
- package/src/client/settings-card.tsx +8 -2
- package/src/client/settings-notifications.ts +3 -2
- package/src/client/styles.ts +17 -19
- package/src/host/engine.ts +283 -41
- package/src/host/settings-migration.ts +1 -1
- package/src/index.ts +12 -1
- package/src/shared/core.ts +26 -2
package/src/host/engine.ts
CHANGED
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
isNonHumanReason,
|
|
31
31
|
isOurEcho,
|
|
32
32
|
isNetworkFailure,
|
|
33
|
+
isSessionMode,
|
|
33
34
|
isTransientAgentError,
|
|
34
35
|
isTransientFailure,
|
|
35
36
|
resolveConfig,
|
|
@@ -42,6 +43,7 @@ import {
|
|
|
42
43
|
type DayStats,
|
|
43
44
|
type RecoveryAttempt,
|
|
44
45
|
type FailureFacts,
|
|
46
|
+
type SessionMode,
|
|
45
47
|
type SessionState,
|
|
46
48
|
type NotifyAction,
|
|
47
49
|
type NotifyOptions,
|
|
@@ -52,37 +54,53 @@ import { probeConnectivity, type ConnectivityProbe } from './connectivity.ts';
|
|
|
52
54
|
|
|
53
55
|
const NOTICE_COPY = {
|
|
54
56
|
zh: {
|
|
55
|
-
notContinuedTitle: 'dsh-auto-continue:
|
|
57
|
+
notContinuedTitle: 'dsh-auto-continue: 请处理会话错误',
|
|
56
58
|
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
57
|
-
`${sessionId}:
|
|
59
|
+
`${sessionId}: ${summary}。请处理此错误后再继续。`,
|
|
58
60
|
resumeAction: '立即续跑',
|
|
59
61
|
pauseAction: '暂停该会话 1 小时',
|
|
60
|
-
continuedTitle: 'dsh-auto-continue:
|
|
62
|
+
continuedTitle: 'dsh-auto-continue: 已发送继续消息',
|
|
61
63
|
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
62
|
-
`${sessionId}: 已发送「${text}
|
|
63
|
-
stoppedTitle: 'dsh-auto-continue:
|
|
64
|
+
`${sessionId}: 已发送「${text}」(连续尝试 ${count} 次)`,
|
|
65
|
+
stoppedTitle: 'dsh-auto-continue: 已达到重试上限',
|
|
64
66
|
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
65
|
-
`${sessionId}:
|
|
67
|
+
`${sessionId}: 已连续尝试恢复 ${count} 次。请检查会话后再继续。`,
|
|
66
68
|
loopCapTitle: 'dsh-auto-continue: 自主循环已到上限',
|
|
67
69
|
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
68
70
|
`${sessionId}: 已自主续跑 ${count} 轮, 循环暂停; 发一条消息或重新开启循环即可继续`,
|
|
69
71
|
},
|
|
70
72
|
en: {
|
|
71
|
-
notContinuedTitle: 'dsh-auto-continue:
|
|
73
|
+
notContinuedTitle: 'dsh-auto-continue: Review session error',
|
|
72
74
|
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
73
|
-
`${sessionId}:
|
|
75
|
+
`${sessionId}: ${summary}. Resolve this error before continuing.`,
|
|
74
76
|
resumeAction: 'Resume now',
|
|
75
77
|
pauseAction: 'Pause this session for 1 hour',
|
|
76
|
-
continuedTitle: 'dsh-auto-continue:
|
|
78
|
+
continuedTitle: 'dsh-auto-continue: Continue message sent',
|
|
77
79
|
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
78
|
-
`${sessionId}: Sent "${text}" (consecutive
|
|
79
|
-
stoppedTitle: 'dsh-auto-continue:
|
|
80
|
+
`${sessionId}: Sent "${text}" (consecutive attempts: ${count})`,
|
|
81
|
+
stoppedTitle: 'dsh-auto-continue: Retry limit reached',
|
|
80
82
|
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
81
|
-
`${sessionId}: ${count}
|
|
83
|
+
`${sessionId}: Consecutive recovery attempts: ${count}. Review the conversation before continuing.`,
|
|
82
84
|
loopCapTitle: 'dsh-auto-continue: Autonomous loop limit reached',
|
|
83
85
|
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
84
86
|
`${sessionId}: Stopped after ${count} autonomous rounds; send a message or turn the loop back on to keep going`,
|
|
85
87
|
},
|
|
88
|
+
ru: {
|
|
89
|
+
notContinuedTitle: 'dsh-auto-continue: продолжение не выполнено',
|
|
90
|
+
permanentErrorBody: (sessionId: SessionId, summary: string) =>
|
|
91
|
+
`${sessionId}: постоянная ошибка ${summary}; нужно вмешательство вручную`,
|
|
92
|
+
resumeAction: 'Продолжить сейчас',
|
|
93
|
+
pauseAction: 'Приостановить сессию на 1 час',
|
|
94
|
+
continuedTitle: 'dsh-auto-continue: продолжено автоматически',
|
|
95
|
+
continuedBody: (sessionId: SessionId, text: string, count: number) =>
|
|
96
|
+
`${sessionId}: отправлено «${text}» (попытка подряд: ${count})`,
|
|
97
|
+
stoppedTitle: 'dsh-auto-continue: авто-продолжение остановлено',
|
|
98
|
+
stoppedBody: (sessionId: SessionId, count: number) =>
|
|
99
|
+
`${sessionId}: сбоев подряд: ${count}; нужно вмешательство вручную`,
|
|
100
|
+
loopCapTitle: 'dsh-auto-continue: достигнут лимит автономного цикла',
|
|
101
|
+
loopCapBody: (sessionId: SessionId, count: number) =>
|
|
102
|
+
`${sessionId}: остановлено после ${count} автономных раундов; отправьте сообщение или включите цикл снова, чтобы продолжить`,
|
|
103
|
+
},
|
|
86
104
|
} as const satisfies Record<AutoContinueLocale, Record<string, unknown>>;
|
|
87
105
|
|
|
88
106
|
/** Durable cancel identity reserved for this plugin's loop guard. */
|
|
@@ -157,6 +175,13 @@ const CHILD_CAUSE_COPY = {
|
|
|
157
175
|
'max-tokens': 'output ceiling reached',
|
|
158
176
|
error: 'retryable error',
|
|
159
177
|
},
|
|
178
|
+
ru: {
|
|
179
|
+
'open-turn': 'ход прерван после начала',
|
|
180
|
+
disposed: 'хост уничтожил агента',
|
|
181
|
+
interrupted: 'закрыт восстановлением после сбоя',
|
|
182
|
+
'max-tokens': 'достигнут лимит вывода',
|
|
183
|
+
error: 'повторяемая ошибка',
|
|
184
|
+
},
|
|
160
185
|
} as const satisfies Record<AutoContinueLocale, Record<ChildInterruptCause, string>>;
|
|
161
186
|
|
|
162
187
|
/** Structural view of `ctx.goals`; declared locally because devDeps target an older host. */
|
|
@@ -300,6 +325,12 @@ function readCancelCause(value: unknown): string | undefined {
|
|
|
300
325
|
return readReasonKind(reason.reason);
|
|
301
326
|
}
|
|
302
327
|
|
|
328
|
+
/** Whether the host closed an `aborted` turn (restart, reload, teardown) rather than the user. */
|
|
329
|
+
function isHostCancel(value: unknown): boolean {
|
|
330
|
+
const cause = readCancelCause(value);
|
|
331
|
+
return cause !== undefined && RESTART_CANCEL_CAUSES.has(cause);
|
|
332
|
+
}
|
|
333
|
+
|
|
303
334
|
/**
|
|
304
335
|
* Decide whether a child session's tail is a restart interruption worth waking
|
|
305
336
|
* its root session for. Returns `undefined` when the child finished normally,
|
|
@@ -412,8 +443,15 @@ async function pumpStream<T>(
|
|
|
412
443
|
}
|
|
413
444
|
|
|
414
445
|
/** 插件主体: 一条 mux 流 + 一条 host 流 + 启动/重连扫描。 */
|
|
446
|
+
/** Soft cap on cached subagent lineage entries before stale ones are pruned. */
|
|
447
|
+
const LINEAGE_CACHE_LIMIT = 2000;
|
|
448
|
+
|
|
415
449
|
export class AutoContinueRunner {
|
|
416
450
|
private readonly states = new Map<SessionId, SessionState>();
|
|
451
|
+
/** Cached subagent lineage: session id -> direct parent id (undefined when the header has none). */
|
|
452
|
+
private readonly parents = new Map<SessionId, SessionId | undefined>();
|
|
453
|
+
/** Sessions already identified as subagents, including event views without header metadata. */
|
|
454
|
+
private readonly subagentSessions = new Set<SessionId>();
|
|
417
455
|
private readonly pauseUntil = new Map<SessionId, number>();
|
|
418
456
|
private dayStats: DayStats = emptyDayStats();
|
|
419
457
|
private readonly recoveryAttempts: RecoveryAttempt[] = [];
|
|
@@ -506,7 +544,7 @@ export class AutoContinueRunner {
|
|
|
506
544
|
void this.bootScanLoop();
|
|
507
545
|
}
|
|
508
546
|
this.log(
|
|
509
|
-
`已启动(
|
|
547
|
+
`已启动(文本="${config.continueText}", 宽限 ${config.graceMs}ms, ` +
|
|
510
548
|
`冷却 ${config.cooldownMs}ms, 最多连续 ${config.maxConsecutive} 次)`,
|
|
511
549
|
);
|
|
512
550
|
}
|
|
@@ -557,6 +595,29 @@ export class AutoContinueRunner {
|
|
|
557
595
|
}
|
|
558
596
|
|
|
559
597
|
private sessionConfig(sessionId: SessionId): AutoContinueConfig {
|
|
598
|
+
const config = this.getConfig();
|
|
599
|
+
if (this.isSubagentSession(sessionId)) {
|
|
600
|
+
// A subagent inherits only the enabled/off decision of its main
|
|
601
|
+
// conversation (an explicit mode stored for the child wins). It never runs
|
|
602
|
+
// the autonomous loop or the loop guard, and the startup scan keeps leaving
|
|
603
|
+
// it to its parent: those three stay parent-only.
|
|
604
|
+
const enabled = this.subagentRecoveryEnabled(sessionId);
|
|
605
|
+
return {
|
|
606
|
+
...config,
|
|
607
|
+
paused: config.paused || !enabled,
|
|
608
|
+
resumeCompletedTurns: false,
|
|
609
|
+
loopGuard: false,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
return this.ownSessionConfig(sessionId);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* The session's own mode, ignoring subagent inheritance. The stored-session
|
|
617
|
+
* sweep and the restart hand-off (`resumeInterruptedChildren`) use this, so
|
|
618
|
+
* turning live subagent recovery off never silently disables them.
|
|
619
|
+
*/
|
|
620
|
+
private ownSessionConfig(sessionId: SessionId): AutoContinueConfig {
|
|
560
621
|
const config = this.getConfig();
|
|
561
622
|
const mode = sessionMode(config.sessionModes, sessionId);
|
|
562
623
|
return {
|
|
@@ -619,6 +680,8 @@ export class AutoContinueRunner {
|
|
|
619
680
|
state.offlineWait = undefined;
|
|
620
681
|
}
|
|
621
682
|
this.states.clear();
|
|
683
|
+
this.parents.clear();
|
|
684
|
+
this.subagentSessions.clear();
|
|
622
685
|
}
|
|
623
686
|
|
|
624
687
|
private state(sessionId: SessionId): SessionState {
|
|
@@ -630,21 +693,184 @@ export class AutoContinueRunner {
|
|
|
630
693
|
return state;
|
|
631
694
|
}
|
|
632
695
|
|
|
633
|
-
/**
|
|
634
|
-
private
|
|
635
|
-
|
|
636
|
-
|
|
696
|
+
/** Record a subagent session's lineage and its parent id when the header carries one. */
|
|
697
|
+
private noteSubagent(sessionId: SessionId, parentSession?: SessionId): void {
|
|
698
|
+
this.subagentSessions.add(sessionId);
|
|
699
|
+
if (parentSession !== undefined && parentSession !== '') {
|
|
700
|
+
this.parents.set(sessionId, parentSession);
|
|
701
|
+
} else if (!this.parents.has(sessionId)) {
|
|
702
|
+
this.parents.set(sessionId, undefined);
|
|
703
|
+
}
|
|
637
704
|
}
|
|
638
705
|
|
|
639
706
|
/** Read durable origin from the live agent for direct action paths as well. */
|
|
640
707
|
private isSubagent(sessionId: SessionId, state: SessionState): boolean {
|
|
641
708
|
if (state.subagent) return true;
|
|
642
|
-
const
|
|
643
|
-
if (
|
|
644
|
-
|
|
709
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
710
|
+
if (header?.origin !== 'subagent') return false;
|
|
711
|
+
state.subagent = true;
|
|
712
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
645
713
|
return true;
|
|
646
714
|
}
|
|
647
715
|
|
|
716
|
+
/** Header origin, cached set or state flag; for paths that only have the session id. */
|
|
717
|
+
private isSubagentSession(sessionId: SessionId): boolean {
|
|
718
|
+
if (this.subagentSessions.has(sessionId)) return true;
|
|
719
|
+
const state = this.states.get(sessionId);
|
|
720
|
+
if (state?.subagent === true) return true;
|
|
721
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
722
|
+
if (header?.origin !== 'subagent') return false;
|
|
723
|
+
this.noteSubagent(sessionId, header.parentSession);
|
|
724
|
+
return true;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* Direct subagent parent id. DSH stores fork lineage in the same
|
|
729
|
+
* `header.parentSession` field, so only a session whose header origin is
|
|
730
|
+
* `subagent` may be followed upward: an ordinary ancestor (the visible main
|
|
731
|
+
* conversation, even a forked one) is the top of the recovery lineage.
|
|
732
|
+
*/
|
|
733
|
+
private parentOf(sessionId: SessionId): SessionId | undefined {
|
|
734
|
+
if (this.parents.has(sessionId)) return this.parents.get(sessionId);
|
|
735
|
+
const header = this.ctx.agents.get(sessionId)?.session?.header;
|
|
736
|
+
// No live header yet: leave the lineage unresolved so a later live agent
|
|
737
|
+
// with the same id can still provide it instead of caching "no parent".
|
|
738
|
+
if (header === undefined) return undefined;
|
|
739
|
+
if (header.origin !== 'subagent') {
|
|
740
|
+
this.parents.set(sessionId, undefined); // known ordinary: top of the lineage
|
|
741
|
+
return undefined;
|
|
742
|
+
}
|
|
743
|
+
const parent = header.parentSession;
|
|
744
|
+
this.noteSubagent(sessionId, parent);
|
|
745
|
+
return parent;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** Explicit session mode stored for this exact id, if the user gave one. */
|
|
749
|
+
private explicitMode(sessionId: SessionId): SessionMode | undefined {
|
|
750
|
+
const modes = this.getConfig().sessionModes;
|
|
751
|
+
const mode = modes[sessionId];
|
|
752
|
+
return Object.prototype.hasOwnProperty.call(modes, sessionId) && isSessionMode(mode) ? mode : undefined;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* A subagent's effective mode, or `undefined` when the lineage cannot be
|
|
757
|
+
* verified. An intermediate parent that is no longer live (and was never seen
|
|
758
|
+
* here) used to stop the walk early, fall back to the profile default and
|
|
759
|
+
* resume a child whose main conversation is Off; refusing the send is safe.
|
|
760
|
+
*/
|
|
761
|
+
private resolveSubagentMode(sessionId: SessionId): SessionMode | undefined {
|
|
762
|
+
const own = this.explicitMode(sessionId);
|
|
763
|
+
if (own !== undefined) return own;
|
|
764
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
765
|
+
let current: SessionId = sessionId;
|
|
766
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
767
|
+
const known = this.parents.has(current);
|
|
768
|
+
const header = this.ctx.agents.get(current)?.session?.header;
|
|
769
|
+
// The chain is not visible yet (an intermediate parent never live here), so
|
|
770
|
+
// neither its mode nor its pause can be verified. Refuse the send and
|
|
771
|
+
// re-resolve on the next event once that ancestor appears.
|
|
772
|
+
if (!known && header === undefined) return undefined;
|
|
773
|
+
const parent = known
|
|
774
|
+
? this.parents.get(current)
|
|
775
|
+
: header?.origin === 'subagent' ? header.parentSession : undefined;
|
|
776
|
+
if (parent === undefined || parent === '') {
|
|
777
|
+
// A subagent without `parentSession` is unlinked: nothing to inherit. Check the
|
|
778
|
+
// cached flag too, so this still holds once the child's header is gone.
|
|
779
|
+
if (header?.origin === 'subagent' || this.subagentSessions.has(current)) return undefined;
|
|
780
|
+
return this.explicitMode(current) ?? 'default';
|
|
781
|
+
}
|
|
782
|
+
if (seen.has(parent)) return undefined;
|
|
783
|
+
seen.add(parent);
|
|
784
|
+
current = parent;
|
|
785
|
+
}
|
|
786
|
+
return undefined;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** Whether the setting and the inherited main-chat mode allow live recovery for this child. */
|
|
790
|
+
private subagentRecoveryEnabled(sessionId: SessionId): boolean {
|
|
791
|
+
if (!this.getConfig().resumeSubagentSessions) return false;
|
|
792
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
793
|
+
return mode !== undefined && mode !== 'off';
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** Modes children inherit from their main conversation, for the composer's display. */
|
|
797
|
+
inheritedSubagentModes(): Record<string, SessionMode> {
|
|
798
|
+
this.pruneLineage();
|
|
799
|
+
const inherited: Record<string, SessionMode> = {};
|
|
800
|
+
for (const sessionId of this.parents.keys()) {
|
|
801
|
+
// Only children that are still loaded can show a composer; skip the rest.
|
|
802
|
+
if (this.ctx.agents.get(sessionId) === undefined) continue;
|
|
803
|
+
if (!this.isSubagentSession(sessionId)) continue;
|
|
804
|
+
if (this.explicitMode(sessionId) !== undefined) continue;
|
|
805
|
+
const mode = this.resolveSubagentMode(sessionId);
|
|
806
|
+
// Children never run the autonomous loop, so a loop parent means recovery for them.
|
|
807
|
+
if (mode !== undefined) inherited[sessionId] = mode === 'loop' ? 'recover' : mode;
|
|
808
|
+
}
|
|
809
|
+
return inherited;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* Keep the lineage caches bounded on long-lived hosts. Once the cache grows,
|
|
814
|
+
* entries for sessions that are no longer loaded are dropped; they are re-read
|
|
815
|
+
* from the live header if the session comes back.
|
|
816
|
+
*/
|
|
817
|
+
private pruneLineage(): void {
|
|
818
|
+
if (this.parents.size + this.subagentSessions.size <= LINEAGE_CACHE_LIMIT) return;
|
|
819
|
+
// `states` keeps its own `subagent` flag, so dropping a non-loaded child here loses nothing.
|
|
820
|
+
const keep = (sessionId: SessionId) => this.ctx.agents.get(sessionId) !== undefined;
|
|
821
|
+
const needed = new Set<SessionId>();
|
|
822
|
+
for (const sessionId of this.parents.keys()) {
|
|
823
|
+
if (!keep(sessionId)) continue;
|
|
824
|
+
// Keep the chain above a loaded child so its inherited mode still resolves.
|
|
825
|
+
let current: SessionId | undefined = sessionId;
|
|
826
|
+
for (let depth = 0; depth < 32 && current !== undefined && !needed.has(current); depth += 1) {
|
|
827
|
+
needed.add(current);
|
|
828
|
+
current = this.parents.get(current);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
for (const sessionId of [...this.parents.keys()]) if (!needed.has(sessionId)) this.parents.delete(sessionId);
|
|
832
|
+
for (const sessionId of [...this.subagentSessions]) if (!needed.has(sessionId) && !keep(sessionId)) this.subagentSessions.delete(sessionId);
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/** Mark a child session; drop only queued sends that its effective policy no longer allows. */
|
|
836
|
+
private markSubagent(sessionId: SessionId, state: SessionState, parentSession?: SessionId): void {
|
|
837
|
+
const first = !state.subagent;
|
|
838
|
+
state.subagent = true;
|
|
839
|
+
this.noteSubagent(sessionId, parentSession);
|
|
840
|
+
if (first && !this.subagentRecoveryEnabled(sessionId)) this.cancelPending(sessionId, '子代理会话');
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** Pause deadline, including the parents' "pause this session 1h" for subagents. */
|
|
844
|
+
private effectivePauseUntil(sessionId: SessionId): number {
|
|
845
|
+
let until = this.pauseUntil.get(sessionId) ?? 0;
|
|
846
|
+
if (!this.isSubagentSession(sessionId)) return until;
|
|
847
|
+
// parentOf() only follows subagent-origin sessions, so fork lineage of the
|
|
848
|
+
// main conversation is never treated as a parent for pause purposes.
|
|
849
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
850
|
+
let current: SessionId | undefined = sessionId;
|
|
851
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
852
|
+
current = this.parentOf(current);
|
|
853
|
+
if (current === undefined || current === '' || seen.has(current)) break;
|
|
854
|
+
seen.add(current);
|
|
855
|
+
until = Math.max(until, this.pauseUntil.get(current) ?? 0);
|
|
856
|
+
}
|
|
857
|
+
return until;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** Whether this session sits below `ancestorId` in the subagent lineage (never fork lineage). */
|
|
861
|
+
private isDescendantOf(sessionId: SessionId, ancestorId: SessionId): boolean {
|
|
862
|
+
const seen = new Set<SessionId>([sessionId]);
|
|
863
|
+
let current: SessionId | undefined = sessionId;
|
|
864
|
+
for (let depth = 0; depth < 32; depth += 1) {
|
|
865
|
+
current = this.parentOf(current);
|
|
866
|
+
if (current === undefined || current === '') return false;
|
|
867
|
+
if (current === ancestorId) return true;
|
|
868
|
+
if (seen.has(current)) return false;
|
|
869
|
+
seen.add(current);
|
|
870
|
+
}
|
|
871
|
+
return false;
|
|
872
|
+
}
|
|
873
|
+
|
|
648
874
|
/**
|
|
649
875
|
* 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
|
|
650
876
|
* 然后交给回合状态机。
|
|
@@ -653,10 +879,12 @@ export class AutoContinueRunner {
|
|
|
653
879
|
const sessionId = session.id;
|
|
654
880
|
const sessionState = this.states.get(sessionId);
|
|
655
881
|
if (session.header?.origin === 'subagent') {
|
|
656
|
-
this.markSubagent(sessionId, sessionState ?? this.state(sessionId));
|
|
657
|
-
|
|
882
|
+
this.markSubagent(sessionId, sessionState ?? this.state(sessionId), session.header.parentSession);
|
|
883
|
+
} else if (sessionState?.subagent) {
|
|
884
|
+
// Origin known from an earlier frame; keep the lineage fresh and process the
|
|
885
|
+
// event normally instead of ignoring a subagent's live turn.
|
|
886
|
+
this.noteSubagent(sessionId, session.header?.parentSession ?? this.parentOf(sessionId));
|
|
658
887
|
}
|
|
659
|
-
if (sessionState?.subagent) return;
|
|
660
888
|
if (sessionState?.maintenanceTurn !== undefined &&
|
|
661
889
|
sessionState.maintenanceTurn === (event.data as { turn?: number }).turn &&
|
|
662
890
|
event.type !== 'turn/start' && event.type !== 'turn/end') return;
|
|
@@ -1096,7 +1324,13 @@ export class AutoContinueRunner {
|
|
|
1096
1324
|
|
|
1097
1325
|
private onTurnFailure(sessionId: SessionId, reason: string, failure: FailureFacts): void {
|
|
1098
1326
|
const config = this.getConfig();
|
|
1099
|
-
if (
|
|
1327
|
+
if (this.isSubagentSession(sessionId)) {
|
|
1328
|
+
// Subagents inherit only the main conversation's enabled/off decision; an
|
|
1329
|
+
// Off parent or the disabled setting means no live recovery at all. The
|
|
1330
|
+
// global pause is not checked here, so diagnostics for permanent errors
|
|
1331
|
+
// match ordinary sessions while paused.
|
|
1332
|
+
if (!this.subagentRecoveryEnabled(sessionId)) return;
|
|
1333
|
+
} else if (sessionMode(config.sessionModes, sessionId) === 'off') return;
|
|
1100
1334
|
if (config.classify && !isTransientFailure(failure, config.retryableErrorPatterns)) {
|
|
1101
1335
|
const copy = NOTICE_COPY[config.locale];
|
|
1102
1336
|
const summary = `${failure.code}${failure.status !== undefined ? ` (HTTP ${failure.status})` : ''}`;
|
|
@@ -1136,6 +1370,12 @@ export class AutoContinueRunner {
|
|
|
1136
1370
|
this.log(`通知按钮: 暂停 ${sessionId} 1 小时`);
|
|
1137
1371
|
this.pauseUntil.set(sessionId, Date.now() + 60 * 60 * 1000);
|
|
1138
1372
|
this.cancelPending(sessionId, '通知按钮暂停该会话');
|
|
1373
|
+
// A paused main conversation also suspends the subagents it owns.
|
|
1374
|
+
for (const candidate of this.states.keys()) {
|
|
1375
|
+
if (candidate !== sessionId && this.isDescendantOf(candidate, sessionId)) {
|
|
1376
|
+
this.cancelPending(candidate, '父会话已暂停');
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1139
1379
|
}
|
|
1140
1380
|
}
|
|
1141
1381
|
|
|
@@ -1205,12 +1445,13 @@ export class AutoContinueRunner {
|
|
|
1205
1445
|
/** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
|
|
1206
1446
|
async resumeNow(sessionId: SessionId): Promise<void> {
|
|
1207
1447
|
if (this.disposed) return;
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1448
|
+
// Subagent recovery is opt-out and inherits the main conversation's mode: an
|
|
1449
|
+
// Off child must not receive a send through the explicit button either, even
|
|
1450
|
+
// though a manual send bypasses the paused flag.
|
|
1451
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
1452
|
+
// A manual send replaces every queued one: leave a pending cooldown or
|
|
1453
|
+
// offline retry armed and the reader receives the continuation twice.
|
|
1454
|
+
this.cancelPending(sessionId, '手动续跑');
|
|
1214
1455
|
try {
|
|
1215
1456
|
await this.fire(sessionId, MANUAL_NOTIFICATION_REASON, true);
|
|
1216
1457
|
} catch (error) {
|
|
@@ -1233,12 +1474,11 @@ export class AutoContinueRunner {
|
|
|
1233
1474
|
const state = this.state(sessionId);
|
|
1234
1475
|
const config = this.sessionConfig(sessionId);
|
|
1235
1476
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
1236
|
-
if (this.isSubagent(sessionId, state)) return; // 子代理会话由父代理处理, 不抢跑
|
|
1237
1477
|
if (config.paused) {
|
|
1238
1478
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
1239
1479
|
return;
|
|
1240
1480
|
}
|
|
1241
|
-
if (Date.now() <
|
|
1481
|
+
if (Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
1242
1482
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1243
1483
|
return;
|
|
1244
1484
|
}
|
|
@@ -1351,12 +1591,14 @@ export class AutoContinueRunner {
|
|
|
1351
1591
|
// 宽限期内循环被关闭: 发送前必须重新检查开关, 与 :silent 恢复同样处理。
|
|
1352
1592
|
// 否则「关掉循环」后仍会多发出一次续跑。
|
|
1353
1593
|
if (isLoopReason(reason) && !config.resumeCompletedTurns) return;
|
|
1354
|
-
|
|
1594
|
+
// Direct sends (notifications) must respect the setting and the inherited
|
|
1595
|
+
// mode even though they bypass the paused flag below.
|
|
1596
|
+
if (this.isSubagentSession(sessionId) && !this.subagentRecoveryEnabled(sessionId)) return;
|
|
1355
1597
|
if (config.paused && !manualResume) {
|
|
1356
1598
|
this.log(`跳过 ${sessionId}(${reason}): 自动继续已暂停`);
|
|
1357
1599
|
return;
|
|
1358
1600
|
}
|
|
1359
|
-
if (!manualResume && Date.now() <
|
|
1601
|
+
if (!manualResume && Date.now() < this.effectivePauseUntil(sessionId)) {
|
|
1360
1602
|
this.log(`跳过 ${sessionId}(${reason}): 会话暂停中`);
|
|
1361
1603
|
return;
|
|
1362
1604
|
}
|
|
@@ -1648,7 +1890,9 @@ export class AutoContinueRunner {
|
|
|
1648
1890
|
const event = events[i];
|
|
1649
1891
|
if (event?.type === 'turn/end') { lastEnd = event; break; }
|
|
1650
1892
|
}
|
|
1651
|
-
|
|
1893
|
+
let reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
1894
|
+
// A host-closed tail (`disposed`/`legacy`) is a restart signature, not a user stop.
|
|
1895
|
+
if (reasonKind === 'aborted' && isHostCancel(lastEnd?.data.reason)) reasonKind = 'interrupted';
|
|
1652
1896
|
const lastStart = latestTurnStart(events);
|
|
1653
1897
|
const maintenance = lastStart?.data.turn === lastEnd?.data.turn && isMaintenanceTurnStart(lastStart);
|
|
1654
1898
|
const silent = reasonKind === 'no-visible-output' && config.resumeSilentTurns;
|
|
@@ -1790,7 +2034,7 @@ export class AutoContinueRunner {
|
|
|
1790
2034
|
continue;
|
|
1791
2035
|
}
|
|
1792
2036
|
const sessionId = record.header.id;
|
|
1793
|
-
if (this.
|
|
2037
|
+
if (this.ownSessionConfig(sessionId).paused || Date.now() < (this.pauseUntil.get(sessionId) ?? 0)) continue;
|
|
1794
2038
|
if (record.header.origin === 'subagent') {
|
|
1795
2039
|
// 子会话的记账完全交给 childSwept。若沿用 storedSwept(它在下面为 root 记账),
|
|
1796
2040
|
// 配额用尽的那一批会被永久标成"已裁决": 之后每轮都在这里被挡掉, 775 个子会话
|
|
@@ -1836,6 +2080,7 @@ export class AutoContinueRunner {
|
|
|
1836
2080
|
freshAt = events[events.length - 1]?.time ?? 0;
|
|
1837
2081
|
} else {
|
|
1838
2082
|
reasonKind = readReasonKind(lastEnd?.data.reason);
|
|
2083
|
+
if (reasonKind === 'aborted' && isHostCancel(lastEnd?.data.reason)) reasonKind = 'interrupted';
|
|
1839
2084
|
freshAt = lastEnd?.time ?? 0;
|
|
1840
2085
|
}
|
|
1841
2086
|
// 过期或被取代的永久错误与 live 扫描一致地静默跳过, 不再单独上报。
|
|
@@ -1926,7 +2171,7 @@ export class AutoContinueRunner {
|
|
|
1926
2171
|
// live 会话由实时事件路径负责; 冷读它既费钱又会与写归属相撞。
|
|
1927
2172
|
if (this.ctx.agents.get(sessionId) !== undefined) return;
|
|
1928
2173
|
if (this.childScanned >= CHILD_SWEEP_LIMIT) return;
|
|
1929
|
-
if (this.
|
|
2174
|
+
if (this.ownSessionConfig(sessionId).paused) return;
|
|
1930
2175
|
const rootId = resolveRootHeader(header, headersById);
|
|
1931
2176
|
if (rootId === undefined || rootId === sessionId) {
|
|
1932
2177
|
// 每轮扫描都会重走这里; 只记一次, 否则 15 分钟 freshMs 窗口内会刷出数万行噪声。
|
|
@@ -2070,10 +2315,7 @@ export class AutoContinueRunner {
|
|
|
2070
2315
|
if (end === undefined) return false;
|
|
2071
2316
|
const kind = readReasonKind(end.data.reason);
|
|
2072
2317
|
if (kind === 'completed') return true;
|
|
2073
|
-
if (kind === 'aborted')
|
|
2074
|
-
const cause = readCancelCause(end.data.reason);
|
|
2075
|
-
return cause !== undefined && RESTART_CANCEL_CAUSES.has(cause);
|
|
2076
|
-
}
|
|
2318
|
+
if (kind === 'aborted') return isHostCancel(end.data.reason);
|
|
2077
2319
|
return false;
|
|
2078
2320
|
}
|
|
2079
2321
|
|
|
@@ -49,7 +49,7 @@ export function migrateLegacySettings(
|
|
|
49
49
|
if (disposed) return;
|
|
50
50
|
// YAML errors may quote other plugins' secrets, so do not log the source
|
|
51
51
|
// or parser exception. Leave the original document available for repair.
|
|
52
|
-
migration.logger.error('[auto-continue] Could not import settings-legacy.yaml
|
|
52
|
+
migration.logger.error('[auto-continue] Could not import settings-legacy.yaml. Automatic recovery and loop guard are paused. Check the legacy settings file and profile permissions, then restart DSH.');
|
|
53
53
|
};
|
|
54
54
|
// Do not return this task to Cordis: profile edits require the owning entry
|
|
55
55
|
// to be active, and Loader.await() must not wait for this migration itself.
|
package/src/index.ts
CHANGED
|
@@ -23,6 +23,8 @@ import type {} from '@deepseek-ai/dsh-settings';
|
|
|
23
23
|
|
|
24
24
|
/** Settings namespace of the auto-continue plugin (lowercase kebab-case). */
|
|
25
25
|
export const AUTO_CONTINUE_NS = 'auto-continue';
|
|
26
|
+
/** Interval for SSE comment frames on the status bridge, so idle connections are not dropped. */
|
|
27
|
+
const BRIDGE_HEARTBEAT_MS = 20_000;
|
|
26
28
|
|
|
27
29
|
/** Wire schema; blank localized text fields tell resolveConfig() to select the active locale's defaults. */
|
|
28
30
|
const settingsFields = {
|
|
@@ -36,6 +38,8 @@ const settingsFields = {
|
|
|
36
38
|
continueTextMaxTokens: z.string().default(''),
|
|
37
39
|
/** Resume observed model activity that completes without visible output. */
|
|
38
40
|
resumeSilentTurns: z.boolean().default(true),
|
|
41
|
+
/** Resume interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never enter the autonomous loop. */
|
|
42
|
+
resumeSubagentSessions: z.boolean().default(false),
|
|
39
43
|
/** Autonomous mode: hand the thread back to the agent after every completed turn, looping until the user stops it. The consecutive-failure cap only throttles failures, never successful completions. */
|
|
40
44
|
resumeCompletedTurns: z.boolean().default(false),
|
|
41
45
|
/** Text sent to resume a silent turn (same placeholders as `continueText`). */
|
|
@@ -202,6 +206,7 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
|
|
|
202
206
|
recoveryAttempts: runner.recentRecoveryAttempts(),
|
|
203
207
|
sessionPolicy: {
|
|
204
208
|
modes: config.sessionModes,
|
|
209
|
+
inheritedModes: runner.inheritedSubagentModes(),
|
|
205
210
|
defaultMode: config.resumeCompletedTurns ? 'loop' : 'recover',
|
|
206
211
|
paused: config.paused,
|
|
207
212
|
writable: writableSettings() !== undefined,
|
|
@@ -236,9 +241,15 @@ export function apply(ctx: Context, config?: AutoContinueEntryConfig): void {
|
|
|
236
241
|
res.write(data);
|
|
237
242
|
};
|
|
238
243
|
sseClients.add(send);
|
|
239
|
-
|
|
244
|
+
// Comment frames keep idle connections alive through proxies, sleep and security software (#86).
|
|
245
|
+
const heartbeat = setInterval(() => {
|
|
246
|
+
try { res.write(': ping\n\n'); } catch { /* the close handler cleans up */ }
|
|
247
|
+
}, BRIDGE_HEARTBEAT_MS);
|
|
248
|
+
heartbeat.unref?.();
|
|
249
|
+
const close = () => { clearInterval(heartbeat); res.end(); };
|
|
240
250
|
closeClients.add(close);
|
|
241
251
|
req.on('close', () => {
|
|
252
|
+
clearInterval(heartbeat);
|
|
242
253
|
sseClients.delete(send);
|
|
243
254
|
closeClients.delete(close);
|
|
244
255
|
});
|
package/src/shared/core.ts
CHANGED
|
@@ -15,16 +15,21 @@ declare module '@deepseek-ai/dsh-llm' {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
/** Supported UI/config locales; missing and unsupported values use English. */
|
|
18
|
-
export type AutoContinueLocale = 'en' | 'zh';
|
|
18
|
+
export type AutoContinueLocale = 'en' | 'zh' | 'ru';
|
|
19
19
|
|
|
20
20
|
export function resolveLocale(locale: unknown): AutoContinueLocale {
|
|
21
|
-
|
|
21
|
+
if (typeof locale !== 'string') return 'en';
|
|
22
|
+
if (/^zh(?:-|$)/i.test(locale)) return 'zh';
|
|
23
|
+
if (/^ru(?:-|$)/i.test(locale)) return 'ru';
|
|
24
|
+
return 'en';
|
|
22
25
|
}
|
|
23
26
|
|
|
24
27
|
export type SessionMode = 'default' | 'off' | 'recover' | 'loop';
|
|
25
28
|
|
|
26
29
|
export interface SessionPolicy {
|
|
27
30
|
modes: Record<string, SessionMode>;
|
|
31
|
+
/** Modes a child inherits from its main conversation, keyed by child id. */
|
|
32
|
+
inheritedModes?: Record<string, SessionMode>;
|
|
28
33
|
defaultMode: 'recover' | 'loop';
|
|
29
34
|
paused: boolean;
|
|
30
35
|
writable: boolean;
|
|
@@ -66,6 +71,21 @@ export const LOCALIZED_TEXT_DEFAULTS = {
|
|
|
66
71
|
loopText:
|
|
67
72
|
'(You may be stuck in a loop. Stop repeating the last action and continue with a different approach.)',
|
|
68
73
|
},
|
|
74
|
+
ru: {
|
|
75
|
+
continueText: 'Продолжай',
|
|
76
|
+
continueTextMaxTokens: 'Продолжай',
|
|
77
|
+
continueTextSilent:
|
|
78
|
+
'Продолжай. Предыдущий ход закончился только внутренним рассуждением: ни ответа, ни вызова инструмента, поэтому пользователь ничего не увидел. Каждый ход должен заканчиваться вызовом инструмента или видимым ответом.',
|
|
79
|
+
continueTextLoop: 'Продолжай',
|
|
80
|
+
continueTextInterrupted:
|
|
81
|
+
'Продолжай. Хост перезапустился, пока предыдущий ход ещё выполнялся; вызовы инструментов, незавершённые на момент перезапуска, записаны с неизвестным результатом. Продолжай с места остановки, проверяя внешнее состояние перед повтором действий с возможными побочными эффектами.',
|
|
82
|
+
guardPendingText:
|
|
83
|
+
'(Предыдущий инструмент «{tool}», возможно, не завершился. Проверь его состояние перед продолжением и не запускай его повторно.)',
|
|
84
|
+
guardDoneText:
|
|
85
|
+
'(Предыдущий инструмент «{tool}» завершился успешно. Результат: {result}; не запускай его повторно, продолжай с этого места.)',
|
|
86
|
+
loopText:
|
|
87
|
+
'(Похоже, ты застрял в цикле. Перестань повторять последнее действие и продолжай другим способом.)',
|
|
88
|
+
},
|
|
69
89
|
} as const satisfies Record<AutoContinueLocale, Record<string, string>>;
|
|
70
90
|
|
|
71
91
|
/** The `auto-continue` settings section (all fields optional on the wire; the host schema carries defaults). */
|
|
@@ -80,6 +100,8 @@ export interface AutoContinueSettings {
|
|
|
80
100
|
continueTextMaxTokens?: string;
|
|
81
101
|
/** Resume observed model activity that completes without visible output. */
|
|
82
102
|
resumeSilentTurns?: boolean;
|
|
103
|
+
/** Resume interrupted subagent sessions when their main conversation has auto-continue enabled. Subagents never enter the autonomous loop. */
|
|
104
|
+
resumeSubagentSessions?: boolean;
|
|
83
105
|
/** Autonomous mode: hand the thread back to the agent after every completed turn, looping until the user stops it. The consecutive-failure cap only throttles failures, never successful completions. */
|
|
84
106
|
resumeCompletedTurns?: boolean;
|
|
85
107
|
/** Text sent to resume a silent turn (same placeholders as `continueText`). */
|
|
@@ -161,6 +183,7 @@ export const DEFAULT_CONFIG: AutoContinueConfig = {
|
|
|
161
183
|
...LOCALIZED_TEXT_DEFAULTS.en,
|
|
162
184
|
usePluginSource: false,
|
|
163
185
|
resumeSilentTurns: true,
|
|
186
|
+
resumeSubagentSessions: false,
|
|
164
187
|
resumeCompletedTurns: false,
|
|
165
188
|
continueTextLoop: '',
|
|
166
189
|
guardTools: true,
|
|
@@ -240,6 +263,7 @@ export function resolveConfig(section: AutoContinueSettings | undefined): AutoCo
|
|
|
240
263
|
continueText: text,
|
|
241
264
|
continueTextMaxTokens: maxTokensText,
|
|
242
265
|
resumeSilentTurns: booleanOr(value.resumeSilentTurns, DEFAULT_CONFIG.resumeSilentTurns),
|
|
266
|
+
resumeSubagentSessions: booleanOr(value.resumeSubagentSessions, DEFAULT_CONFIG.resumeSubagentSessions),
|
|
243
267
|
resumeCompletedTurns: booleanOr(value.resumeCompletedTurns, DEFAULT_CONFIG.resumeCompletedTurns),
|
|
244
268
|
continueTextSilent: silentText,
|
|
245
269
|
continueTextLoop: loopText,
|