@cortex-agent/server 2026.6.18 → 2026.6.24
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/defaults/CORTEX.md +5 -0
- package/defaults/config/thread-templates.json +12 -6
- package/defaults/context/user/CORTEX.md +2 -2
- package/defaults/hooks/ask-user-question-hook.mjs +7 -1
- package/defaults/hooks/exit-plan-mode-hook.mjs +7 -1
- package/defaults/hooks/memory-ref-tracker.mjs +1 -0
- package/defaults/hooks/new-session-hook.mjs +1 -0
- package/defaults/hooks/post-task-hook.mjs +1 -0
- package/defaults/hooks/rules-loader.mjs +1 -0
- package/defaults/hooks/sensitive-file-edit.mjs +1 -0
- package/defaults/hooks/session-activity-tracker.mjs +1 -0
- package/defaults/hooks/task-status-check.mjs +1 -0
- package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
- package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
- package/defaults/prompts/directives/coder-reviewer.md +6 -6
- package/defaults/prompts/directives/coder.md +14 -15
- package/defaults/prompts/systemPrompts/coder.md +6 -1
- package/defaults/prompts/systemPrompts/direct.md +5 -0
- package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web.md +6 -1
- package/defaults/prompts/systemPrompts/worker.md +6 -1
- package/dist/agent-adapter/claude/adapter-tui.d.ts +12 -0
- package/dist/agent-adapter/claude/adapter-tui.js +15 -0
- package/dist/agent-adapter/claude/adapter.d.ts +110 -1
- package/dist/agent-adapter/claude/adapter.js +123 -2
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +45 -0
- package/dist/agent-adapter/claude/bg-task-tracker.js +91 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
- package/dist/agent-adapter/pi/event-parser.js +12 -2
- package/dist/agent-adapter/types.d.ts +19 -0
- package/dist/core/auth.d.ts +36 -0
- package/dist/core/auth.js +85 -0
- package/dist/core/gateway-generator.js +10 -1
- package/dist/core/locales/en.d.ts +12 -0
- package/dist/core/locales/slices/interactions.d.ts +6 -0
- package/dist/core/locales/slices/interactions.js +14 -0
- package/dist/core/locales/slices/status.d.ts +6 -0
- package/dist/core/locales/slices/status.js +16 -0
- package/dist/core/status-format.d.ts +14 -0
- package/dist/core/status-format.js +23 -1
- package/dist/core/types/agent-types.d.ts +5 -0
- package/dist/core/types/thread-types.d.ts +15 -1
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +4 -1
- package/dist/domain/agents/facade.d.ts +13 -0
- package/dist/domain/agents/facade.js +36 -1
- package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
- package/dist/domain/costs/rate-limit-throttle.js +23 -2
- package/dist/domain/costs/resume-registry.d.ts +30 -0
- package/dist/domain/costs/resume-registry.js +68 -0
- package/dist/domain/mcp/core-server.js +5 -0
- package/dist/domain/mcp/feishu/index.js +5 -51
- package/dist/domain/mcp/feishu-server.js +3 -2
- package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
- package/dist/domain/mcp/tools/manager-qa.js +72 -0
- package/dist/domain/mcp/tools/task-ops.js +4 -2
- package/dist/domain/mcp/tools/thread-ops.js +2 -1
- package/dist/domain/mcp/tui-server.js +2 -1
- package/dist/domain/memory/user-context.d.ts +6 -5
- package/dist/domain/memory/user-context.js +12 -7
- package/dist/domain/remote/client-bootstrap.js +14 -2
- package/dist/domain/remote/client-hot-reload.d.ts +9 -2
- package/dist/domain/remote/client-hot-reload.js +77 -6
- package/dist/domain/remote/client-manager.d.ts +1 -1
- package/dist/domain/remote/client-manager.js +31 -5
- package/dist/domain/remote/cortex-client-config.d.ts +32 -0
- package/dist/domain/remote/cortex-client-config.js +49 -0
- package/dist/domain/remote/cortex-client.js +11 -7
- package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
- package/dist/domain/scheduling/jobs/task-dispatch.js +22 -0
- package/dist/domain/sessions/session-hooks.d.ts +31 -1
- package/dist/domain/sessions/session-hooks.js +69 -17
- package/dist/domain/system/doctor.d.ts +63 -0
- package/dist/domain/system/doctor.js +362 -0
- package/dist/domain/tasks/dispatcher.js +8 -0
- package/dist/domain/tasks/system/cortex-run.js +4 -2
- package/dist/domain/tasks/system/task-cli.js +7 -4
- package/dist/domain/tasks/system/task-state.d.ts +10 -1
- package/dist/domain/tasks/system/task-state.js +31 -1
- package/dist/domain/threads/prompt-builder.d.ts +7 -4
- package/dist/domain/threads/prompt-builder.js +9 -8
- package/dist/domain/threads/runner.d.ts +8 -1
- package/dist/domain/threads/runner.js +111 -18
- package/dist/domain/threads/state-machine.d.ts +5 -0
- package/dist/domain/threads/state-machine.js +16 -0
- package/dist/entry/app.js +44 -5
- package/dist/entry/cli.js +10 -0
- package/dist/entry/doctor-cli.d.ts +12 -0
- package/dist/entry/doctor-cli.js +76 -0
- package/dist/entry/init.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +7 -1
- package/dist/hooks/exit-plan-mode-hook.mjs +7 -1
- package/dist/hooks/memory-ref-tracker.mjs +1 -0
- package/dist/hooks/new-session-hook.mjs +1 -0
- package/dist/hooks/post-task-hook.mjs +1 -0
- package/dist/hooks/rules-loader.mjs +1 -0
- package/dist/hooks/sensitive-file-edit.mjs +1 -0
- package/dist/hooks/session-activity-tracker.mjs +1 -0
- package/dist/hooks/task-status-check.mjs +1 -0
- package/dist/hooks/tasks-yaml-guard.mjs +1 -0
- package/dist/orchestration/agent-runner.js +30 -4
- package/dist/orchestration/bg-continuation.d.ts +26 -0
- package/dist/orchestration/bg-continuation.js +34 -0
- package/dist/orchestration/conversation-runner.d.ts +3 -0
- package/dist/orchestration/conversation-runner.js +5 -2
- package/dist/orchestration/interactions/interaction-handlers.js +13 -2
- package/dist/orchestration/lifecycle.d.ts +5 -2
- package/dist/orchestration/lifecycle.js +87 -3
- package/dist/orchestration/manager-qa.d.ts +56 -0
- package/dist/orchestration/manager-qa.js +223 -0
- package/dist/orchestration/resume-dispatcher.d.ts +27 -0
- package/dist/orchestration/resume-dispatcher.js +145 -0
- package/dist/orchestration/routing/webhook.d.ts +1 -1
- package/dist/orchestration/routing/webhook.js +75 -14
- package/dist/orchestration/status-helpers.d.ts +3 -0
- package/dist/orchestration/status-helpers.js +16 -0
- package/dist/orchestration/thread-callback.d.ts +17 -1
- package/dist/orchestration/thread-callback.js +57 -36
- package/dist/orchestration/turn-notify.d.ts +26 -0
- package/dist/orchestration/turn-notify.js +66 -0
- package/dist/platform/adapters/feishu.d.ts +16 -0
- package/dist/platform/adapters/feishu.js +67 -6
- package/dist/store/plugin-sync.d.ts +21 -0
- package/dist/store/plugin-sync.js +119 -0
- package/dist/store/schedule-repo.d.ts +6 -0
- package/dist/store/schedule-repo.js +11 -1
- package/dist/store/thread-repo.js +14 -0
- package/dist/store/version-migrations.d.ts +23 -4
- package/dist/store/version-migrations.js +167 -9
- package/dist/tui/App.js +11 -7
- package/dist/tui/components/Dashboard.js +26 -11
- package/dist/tui/components/InputBox.js +43 -4
- package/dist/tui/components/SidePanel.js +1 -1
- package/package.json +1 -1
- package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
- package/dist/domain/mcp/feishu/bitable.js +0 -168
- package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
- package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
- package/dist/domain/mcp/feishu/docx.d.ts +0 -3
- package/dist/domain/mcp/feishu/docx.js +0 -163
- package/dist/domain/mcp/feishu/drive.d.ts +0 -23
- package/dist/domain/mcp/feishu/drive.js +0 -66
- package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
- package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
- package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
- package/dist/domain/mcp/feishu/sheets.js +0 -119
- package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
- package/dist/domain/mcp/feishu/wiki.js +0 -77
|
@@ -165,6 +165,18 @@ export declare class ClaudeTuiSession {
|
|
|
165
165
|
* have JsonlTail watching a non-existent path and timing out on first turn.
|
|
166
166
|
*/
|
|
167
167
|
export declare function computeJsonlPath(cwd: string, sessionId: string): string;
|
|
168
|
+
/**
|
|
169
|
+
* Decide whether a TUI session should spawn with `--resume <id>` (vs `--session-id <id>`).
|
|
170
|
+
*
|
|
171
|
+
* `--resume` only succeeds when a Claude transcript already exists for that id. A *fresh* TUI
|
|
172
|
+
* session pre-registers its channel→sessionId mapping BEFORE the first Claude turn (so transcript
|
|
173
|
+
* replay / session naming work), which makes the orchestrator's generic "a session mapping exists
|
|
174
|
+
* ⇒ resume" heuristic ask to resume an id that has no transcript yet — Claude then exits with
|
|
175
|
+
* "No conversation found with session ID: <id>". Gating the resume request on the transcript
|
|
176
|
+
* actually existing keeps the first turn on `--session-id` (create) and lets only later turns /
|
|
177
|
+
* reconnects use `--resume`. Self-healing: a deleted transcript also correctly falls back to create.
|
|
178
|
+
*/
|
|
179
|
+
export declare function resolveTuiResume(requestedResume: boolean, jsonlPath: string, exists?: (p: string) => boolean): boolean;
|
|
168
180
|
/**
|
|
169
181
|
* Convenience factory: real JsonlTail wired to the path. Used by production code; tests inject
|
|
170
182
|
* a custom factory instead.
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// output: ClaudeTuiSession — interactive Claude under tmux with jsonl tail; implements turn lifecycle
|
|
3
3
|
// pos: DR-0012 Phase 2 — parallel adapter to claude/adapter.ts; selects via spawn-args mode='tui'
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
5
6
|
import * as path from 'path';
|
|
6
7
|
import { createLogger } from '../../core/log.js';
|
|
7
8
|
import { JsonlTail, JsonlEventNormalizer } from './jsonl-tail.js';
|
|
@@ -492,6 +493,20 @@ export function computeJsonlPath(cwd, sessionId) {
|
|
|
492
493
|
const encoded = cwd.replace(/[/.]/g, '-');
|
|
493
494
|
return path.join(TUI_JSONL_BASE, encoded, `${sessionId}.jsonl`);
|
|
494
495
|
}
|
|
496
|
+
/**
|
|
497
|
+
* Decide whether a TUI session should spawn with `--resume <id>` (vs `--session-id <id>`).
|
|
498
|
+
*
|
|
499
|
+
* `--resume` only succeeds when a Claude transcript already exists for that id. A *fresh* TUI
|
|
500
|
+
* session pre-registers its channel→sessionId mapping BEFORE the first Claude turn (so transcript
|
|
501
|
+
* replay / session naming work), which makes the orchestrator's generic "a session mapping exists
|
|
502
|
+
* ⇒ resume" heuristic ask to resume an id that has no transcript yet — Claude then exits with
|
|
503
|
+
* "No conversation found with session ID: <id>". Gating the resume request on the transcript
|
|
504
|
+
* actually existing keeps the first turn on `--session-id` (create) and lets only later turns /
|
|
505
|
+
* reconnects use `--resume`. Self-healing: a deleted transcript also correctly falls back to create.
|
|
506
|
+
*/
|
|
507
|
+
export function resolveTuiResume(requestedResume, jsonlPath, exists = existsSync) {
|
|
508
|
+
return requestedResume && exists(jsonlPath);
|
|
509
|
+
}
|
|
495
510
|
/**
|
|
496
511
|
* Convenience factory: real JsonlTail wired to the path. Used by production code; tests inject
|
|
497
512
|
* a custom factory instead.
|
|
@@ -1,8 +1,111 @@
|
|
|
1
1
|
import { Capability } from '../capabilities.js';
|
|
2
|
-
import type { AgentAdapter, AgentSpawnConfig, AgentProcess, Backend } from '../types.js';
|
|
2
|
+
import type { AgentAdapter, AgentSpawnConfig, AgentProcess, Backend, ContinuationSink } from '../types.js';
|
|
3
3
|
import { CancelledError } from './defaults.js';
|
|
4
|
+
import { CortexAgentContext } from './spawn-args.js';
|
|
4
5
|
import { type TmuxExec } from './tmux-control.js';
|
|
5
6
|
import { extractAskUserQuestions, getCurrentPlanFilePath, mergeSubstantialOutput } from './event-parser.js';
|
|
7
|
+
interface ClaudeSessionOptions {
|
|
8
|
+
needsResume: boolean;
|
|
9
|
+
model?: string | null;
|
|
10
|
+
isUserInitiated?: boolean;
|
|
11
|
+
callbackSource?: string | null;
|
|
12
|
+
scheduleTaskId?: string | null;
|
|
13
|
+
sessionKey?: string | null;
|
|
14
|
+
claudeAgent?: string | null;
|
|
15
|
+
systemPrompt?: string | null;
|
|
16
|
+
appendSystemPrompt?: string | null;
|
|
17
|
+
outputStyle?: string | null;
|
|
18
|
+
tools?: string | null;
|
|
19
|
+
pluginDirs?: string[] | null;
|
|
20
|
+
anthropicBaseUrl?: string;
|
|
21
|
+
extraEnv?: Record<string, string>;
|
|
22
|
+
/** Extra CLI options from profile (e.g. {"--thinking": "xhigh"}). */
|
|
23
|
+
extraOption?: Record<string, string>;
|
|
24
|
+
/** Cortex execution context surfaced to the MCP server child as CORTEX_THREAD_ID/PROFILE/PROJECT/SESSION_NAME env vars.
|
|
25
|
+
* Captured at spawn time; later turns on the same session reuse the original snapshot. */
|
|
26
|
+
context?: CortexAgentContext;
|
|
27
|
+
}
|
|
28
|
+
declare class ClaudeSession {
|
|
29
|
+
private proc;
|
|
30
|
+
private rl;
|
|
31
|
+
sessionId: string;
|
|
32
|
+
private channel;
|
|
33
|
+
private sessionKey;
|
|
34
|
+
/** Model name requested via --model CLI arg (used as fallback for cost_record). */
|
|
35
|
+
modelName: string | null;
|
|
36
|
+
private isUserInitiated;
|
|
37
|
+
private callbackSource;
|
|
38
|
+
private scheduleTaskId;
|
|
39
|
+
private claudeAgent;
|
|
40
|
+
private systemPrompt;
|
|
41
|
+
private appendSystemPrompt;
|
|
42
|
+
private outputStyle;
|
|
43
|
+
private tools;
|
|
44
|
+
private pluginDirs;
|
|
45
|
+
private anthropicBaseUrl;
|
|
46
|
+
private extraEnv;
|
|
47
|
+
private extraOption;
|
|
48
|
+
private context;
|
|
49
|
+
private currentTurn;
|
|
50
|
+
/** Tracks in-flight background tasks (run_in_background) for this session. */
|
|
51
|
+
private bgTracker;
|
|
52
|
+
/** Set by orchestration to receive spontaneous background-task continuation turns. */
|
|
53
|
+
private continuationSink;
|
|
54
|
+
private alive;
|
|
55
|
+
private needsResume;
|
|
56
|
+
private idleTimer;
|
|
57
|
+
private turnIdleTimer;
|
|
58
|
+
private maxTimer;
|
|
59
|
+
private stderr;
|
|
60
|
+
private cumulativeCostUsd;
|
|
61
|
+
/** Captured from result event's modelUsage key for cost_record. */
|
|
62
|
+
lastModelName: string | null;
|
|
63
|
+
/** Captured from result event's usage for cost_record (per-turn, non-cumulative). */
|
|
64
|
+
lastTokenUsage: {
|
|
65
|
+
input: number;
|
|
66
|
+
output: number;
|
|
67
|
+
cacheCreation: number;
|
|
68
|
+
cacheRead: number;
|
|
69
|
+
} | null;
|
|
70
|
+
constructor(channel: string, sessionId: string, options: ClaudeSessionOptions);
|
|
71
|
+
private toSpawnOptions;
|
|
72
|
+
private handleProcessClose;
|
|
73
|
+
private spawnProcess;
|
|
74
|
+
private createTurnStreams;
|
|
75
|
+
private registerTurn;
|
|
76
|
+
/** Register/replace the continuation sink. Persists across normal turns; lives as long
|
|
77
|
+
* as the pooled session, until close()/kill(). */
|
|
78
|
+
setContinuationSink(sink: ContinuationSink): void;
|
|
79
|
+
clearContinuationSink(): void;
|
|
80
|
+
/** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
|
|
81
|
+
* background task finishes. Its assistant text / result are routed to continuationSink
|
|
82
|
+
* (not to a send() promise — there is no caller awaiting it). */
|
|
83
|
+
private openContinuationTurn;
|
|
84
|
+
private writeTurnStdin;
|
|
85
|
+
private startTurnIdleTimer;
|
|
86
|
+
sendMessage(userMessage: string, options: {
|
|
87
|
+
files?: any[];
|
|
88
|
+
callbackSource?: string | null;
|
|
89
|
+
scheduleTaskId?: string | null;
|
|
90
|
+
isUserInitiated?: boolean;
|
|
91
|
+
onProgress?: ((progress: any) => void) | null;
|
|
92
|
+
onAssistantMessage?: ((text: string) => void) | null;
|
|
93
|
+
onToolUse?: ((name: string, input: any) => void) | null;
|
|
94
|
+
onCompact?: ((info: {
|
|
95
|
+
trigger: string;
|
|
96
|
+
preTokens?: number;
|
|
97
|
+
}) => void) | null;
|
|
98
|
+
}): Promise<any>;
|
|
99
|
+
private bumpTurnIdleTimer;
|
|
100
|
+
private handleResultEvent;
|
|
101
|
+
private handleAssistantEvent;
|
|
102
|
+
private handleLine;
|
|
103
|
+
private closeTurnLogs;
|
|
104
|
+
private resetIdleTimer;
|
|
105
|
+
close(): void;
|
|
106
|
+
kill(): boolean;
|
|
107
|
+
isAlive(): boolean;
|
|
108
|
+
}
|
|
6
109
|
export declare function closeSession(channel: string, sessionKey?: string): void;
|
|
7
110
|
/** Close all sessions whose key starts with the given prefix (used by Thread cleanup). */
|
|
8
111
|
export declare function closeSessionsByPrefix(prefix: string): void;
|
|
@@ -76,10 +179,16 @@ export declare function recoverTuiOrphans(exec?: TmuxExec): {
|
|
|
76
179
|
found: string[];
|
|
77
180
|
killed: string[];
|
|
78
181
|
};
|
|
182
|
+
/** Construct a ClaudeSession WITHOUT spawning the `claude` child process, for unit
|
|
183
|
+
* testing handleLine / continuation routing. Initializes only the fields the line
|
|
184
|
+
* handlers touch. Callers should stub createTurnStreams to avoid log file I/O and
|
|
185
|
+
* register cleanup via t.after(() => session.close()) to clear the idle timer. */
|
|
186
|
+
declare function makeSessionForTest(): ClaudeSession;
|
|
79
187
|
export declare const _test: {
|
|
80
188
|
extractAskUserQuestions: typeof extractAskUserQuestions;
|
|
81
189
|
mergeSubstantialOutput: typeof mergeSubstantialOutput;
|
|
82
190
|
computeSpawnArgs: typeof computeSpawnArgsForConfig;
|
|
191
|
+
makeSessionForTest: typeof makeSessionForTest;
|
|
83
192
|
};
|
|
84
193
|
export { getCurrentPlanFilePath };
|
|
85
194
|
export { CancelledError };
|
|
@@ -15,10 +15,11 @@ import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
|
|
|
15
15
|
import { createEventStream } from '../normalize/event-stream.js';
|
|
16
16
|
import { CancelledError, CORE_MCP_CONFIG, IDLE_SESSION_TIMEOUT, LOGS_DIR, MAX_TIMEOUT, TURN_IDLE_TIMEOUT, } from './defaults.js';
|
|
17
17
|
import { buildClaudeEnv, buildSpawnArgs } from './spawn-args.js';
|
|
18
|
-
import { ClaudeTuiSession, defaultTailFactory } from './adapter-tui.js';
|
|
18
|
+
import { ClaudeTuiSession, defaultTailFactory, computeJsonlPath, resolveTuiResume } from './adapter-tui.js';
|
|
19
19
|
import { TmuxControl } from './tmux-control.js';
|
|
20
20
|
import { TUI_TMUX_NAME_PREFIX } from './defaults.js';
|
|
21
21
|
import { buildPrompt, clearActivePlanFile, extractAskUserQuestions, extractResult, formatEvent, getCurrentPlanFilePath, isPlanFilePath, mergeSubstantialOutput, setActivePlanFile, } from './event-parser.js';
|
|
22
|
+
import { BgTaskTracker, routeLine } from './bg-task-tracker.js';
|
|
22
23
|
const log = createLogger('claude-bridge');
|
|
23
24
|
/** Single source of truth for ClaudeSession fields → ClaudeSpawnOptions CLI args translation.
|
|
24
25
|
* Used by both ClaudeSession.toSpawnOptions() (production) and _test.computeSpawnArgs (lock-in test). */
|
|
@@ -58,6 +59,10 @@ class ClaudeSession {
|
|
|
58
59
|
extraOption;
|
|
59
60
|
context;
|
|
60
61
|
currentTurn = null;
|
|
62
|
+
/** Tracks in-flight background tasks (run_in_background) for this session. */
|
|
63
|
+
bgTracker = new BgTaskTracker();
|
|
64
|
+
/** Set by orchestration to receive spontaneous background-task continuation turns. */
|
|
65
|
+
continuationSink = null;
|
|
61
66
|
alive = false;
|
|
62
67
|
needsResume;
|
|
63
68
|
idleTimer = null;
|
|
@@ -181,11 +186,61 @@ class ClaudeSession {
|
|
|
181
186
|
onProgress: options.onProgress || null,
|
|
182
187
|
onAssistantMessage: options.onAssistantMessage || null,
|
|
183
188
|
onToolUse: options.onToolUse || null,
|
|
189
|
+
onCompact: options.onCompact || null,
|
|
184
190
|
rawStream: streams.rawStream,
|
|
185
191
|
txtStream: streams.txtStream,
|
|
186
192
|
killed: false,
|
|
187
193
|
};
|
|
188
194
|
}
|
|
195
|
+
/** Register/replace the continuation sink. Persists across normal turns; lives as long
|
|
196
|
+
* as the pooled session, until close()/kill(). */
|
|
197
|
+
setContinuationSink(sink) {
|
|
198
|
+
this.continuationSink = sink;
|
|
199
|
+
}
|
|
200
|
+
clearContinuationSink() {
|
|
201
|
+
this.continuationSink = null;
|
|
202
|
+
}
|
|
203
|
+
/** Open a synthetic turn to capture the spontaneous continuation the CLI emits after a
|
|
204
|
+
* background task finishes. Its assistant text / result are routed to continuationSink
|
|
205
|
+
* (not to a send() promise — there is no caller awaiting it). */
|
|
206
|
+
openContinuationTurn() {
|
|
207
|
+
this.bgTracker.disarmContinuation();
|
|
208
|
+
const streams = this.createTurnStreams('[background-task continuation]');
|
|
209
|
+
const sink = this.continuationSink;
|
|
210
|
+
this.currentTurn = {
|
|
211
|
+
resolve: (value) => { try {
|
|
212
|
+
sink?.onResult(value);
|
|
213
|
+
}
|
|
214
|
+
catch (e) {
|
|
215
|
+
log.warn('continuation onResult threw:', e.message);
|
|
216
|
+
} },
|
|
217
|
+
reject: (err) => { log.warn('continuation turn rejected:', err?.message ?? String(err)); },
|
|
218
|
+
resultData: null,
|
|
219
|
+
planFilePath: null,
|
|
220
|
+
enteredPlanMode: false,
|
|
221
|
+
exitedPlanMode: false,
|
|
222
|
+
askUserQuestions: [],
|
|
223
|
+
finalOutput: null,
|
|
224
|
+
longestOutput: null,
|
|
225
|
+
turnCount: 0,
|
|
226
|
+
onProgress: null,
|
|
227
|
+
onAssistantMessage: sink ? (text) => { try {
|
|
228
|
+
sink.onAssistantText(text);
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
log.warn('continuation onAssistantText threw:', e.message);
|
|
232
|
+
} } : null,
|
|
233
|
+
onToolUse: sink?.onToolUse ? (name, input) => { try {
|
|
234
|
+
sink.onToolUse(name, input);
|
|
235
|
+
}
|
|
236
|
+
catch { } } : null,
|
|
237
|
+
onCompact: null,
|
|
238
|
+
rawStream: streams.rawStream,
|
|
239
|
+
txtStream: streams.txtStream,
|
|
240
|
+
killed: false,
|
|
241
|
+
spontaneous: true,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
189
244
|
writeTurnStdin(prompt) {
|
|
190
245
|
const stdinMsg = JSON.stringify({
|
|
191
246
|
type: 'user',
|
|
@@ -263,6 +318,11 @@ class ClaudeSession {
|
|
|
263
318
|
this.lastModelName = keys[0];
|
|
264
319
|
}
|
|
265
320
|
const result = extractResult(turn.resultData, this.sessionId, false, 0, '', turn.planFilePath, turn.enteredPlanMode, turn.exitedPlanMode, turn.askUserQuestions, turn.finalOutput, turn.longestOutput);
|
|
321
|
+
// Surface how many background tasks are still running. >0 tells orchestration to hold
|
|
322
|
+
// the status in a "waiting" state; the CLI will spontaneously emit a continuation turn
|
|
323
|
+
// once they finish (routed via continuationSink).
|
|
324
|
+
if (result.resolved)
|
|
325
|
+
result.value.pendingBackgroundTasks = this.bgTracker.pendingCount;
|
|
266
326
|
this.currentTurn = null;
|
|
267
327
|
if (this.turnIdleTimer)
|
|
268
328
|
clearTimeout(this.turnIdleTimer);
|
|
@@ -322,10 +382,33 @@ class ClaudeSession {
|
|
|
322
382
|
this.currentTurn.rawStream.write(line + '\n');
|
|
323
383
|
try {
|
|
324
384
|
const data = JSON.parse(line);
|
|
385
|
+
// Context compaction boundary: Claude emits a system/compact_boundary line the instant it
|
|
386
|
+
// decides to compact. Surface it to the active turn so observers (e.g. Slack) can notify.
|
|
387
|
+
if (data.type === 'system' && data.subtype === 'compact_boundary' && this.currentTurn?.onCompact) {
|
|
388
|
+
const meta = data.compact_metadata ?? {};
|
|
389
|
+
try {
|
|
390
|
+
this.currentTurn.onCompact({
|
|
391
|
+
trigger: typeof meta.trigger === 'string' ? meta.trigger : 'auto',
|
|
392
|
+
preTokens: typeof meta.pre_tokens === 'number' ? meta.pre_tokens : undefined,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
catch (e) {
|
|
396
|
+
log.warn('onCompact threw:', e.message);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
325
399
|
if (data.type === 'rate_limit_event' && data.rate_limit_info) {
|
|
326
400
|
const mode = this.anthropicBaseUrl?.match(/\/m\/([^/]+)\//)?.[1] || undefined;
|
|
327
401
|
handleRateLimitEvent(data.rate_limit_info, mode).catch(e => log.error('handleRateLimitEvent error:', e));
|
|
328
402
|
}
|
|
403
|
+
// Track background-task lifecycle on every line (even with no active turn) so the
|
|
404
|
+
// pending count stays accurate across the turn boundary.
|
|
405
|
+
this.bgTracker.observe(data);
|
|
406
|
+
// No active turn: a background task that just finished re-invokes the model and the
|
|
407
|
+
// CLI emits a spontaneous continuation turn. Open a synthetic turn for it so its
|
|
408
|
+
// output is routed (to continuationSink) instead of being dropped.
|
|
409
|
+
if (!this.currentTurn && this.continuationSink && routeLine(this.bgTracker, data, false) === 'open-continuation') {
|
|
410
|
+
this.openContinuationTurn();
|
|
411
|
+
}
|
|
329
412
|
if (data.type === 'result' && this.currentTurn) {
|
|
330
413
|
this.handleResultEvent(this.currentTurn, data);
|
|
331
414
|
return;
|
|
@@ -353,6 +436,13 @@ class ClaudeSession {
|
|
|
353
436
|
resetIdleTimer() {
|
|
354
437
|
if (this.idleTimer)
|
|
355
438
|
clearTimeout(this.idleTimer);
|
|
439
|
+
// While background tasks are still running, the session must stay alive to receive the
|
|
440
|
+
// spontaneous continuation turn — even through a long silent wait. Don't arm idle-close
|
|
441
|
+
// (the overall maxTimer still bounds session lifetime).
|
|
442
|
+
if (this.bgTracker.hasPending()) {
|
|
443
|
+
this.idleTimer = null;
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
356
446
|
this.idleTimer = setTimeout(() => {
|
|
357
447
|
log.info(`Session ${this.sessionId.substring(0, 8)} idle for 65min, closing`);
|
|
358
448
|
this.close();
|
|
@@ -365,6 +455,7 @@ class ClaudeSession {
|
|
|
365
455
|
clearTimeout(this.maxTimer);
|
|
366
456
|
if (this.turnIdleTimer)
|
|
367
457
|
clearTimeout(this.turnIdleTimer);
|
|
458
|
+
this.continuationSink = null;
|
|
368
459
|
if (!this.proc || !this.alive) {
|
|
369
460
|
sessions.delete(this.sessionKey);
|
|
370
461
|
return;
|
|
@@ -400,6 +491,7 @@ class ClaudeSession {
|
|
|
400
491
|
clearTimeout(this.maxTimer);
|
|
401
492
|
if (this.turnIdleTimer)
|
|
402
493
|
clearTimeout(this.turnIdleTimer);
|
|
494
|
+
this.continuationSink = null;
|
|
403
495
|
if (!this.proc || this.proc.exitCode !== null)
|
|
404
496
|
return false;
|
|
405
497
|
this.alive = false;
|
|
@@ -487,12 +579,16 @@ function getOrCreateTuiSession(config, sessionIdEffective) {
|
|
|
487
579
|
const channel = config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey;
|
|
488
580
|
const cwd = config.cwd || DATA_DIR;
|
|
489
581
|
const opts = sessionOptionsFromSpawnConfig({ ...config, sessionId: sessionIdEffective });
|
|
582
|
+
// `--resume` only works once a transcript exists. A fresh TUI session pre-registers its
|
|
583
|
+
// sessionId before the first turn, so config.resume can be true with no transcript yet —
|
|
584
|
+
// gate it on the jsonl actually existing, else the first turn fails "No conversation found".
|
|
585
|
+
const needsResume = resolveTuiResume(config.resume, computeJsonlPath(cwd, sessionIdEffective));
|
|
490
586
|
const sessionConfig = {
|
|
491
587
|
channel,
|
|
492
588
|
sessionId: sessionIdEffective,
|
|
493
589
|
sessionKey: key,
|
|
494
590
|
cwd,
|
|
495
|
-
needsResume
|
|
591
|
+
needsResume,
|
|
496
592
|
tools: opts.tools,
|
|
497
593
|
systemPrompt: opts.systemPrompt,
|
|
498
594
|
appendSystemPrompt: opts.appendSystemPrompt,
|
|
@@ -611,6 +707,7 @@ export class ClaudeAdapter {
|
|
|
611
707
|
files,
|
|
612
708
|
onAssistantMessage: (text) => stream.push({ type: 'assistant_text', text }),
|
|
613
709
|
onToolUse: (name, input) => stream.push({ type: 'tool_use', toolUseId: '', name, input }),
|
|
710
|
+
onCompact: (info) => stream.push({ type: 'context_compacted', trigger: info.trigger, preTokens: info.preTokens }),
|
|
614
711
|
onProgress: (p) => {
|
|
615
712
|
stream.push({ type: 'turn_progress', numTurns: p?.num_turns ?? 0 });
|
|
616
713
|
},
|
|
@@ -662,6 +759,7 @@ export class ClaudeAdapter {
|
|
|
662
759
|
}
|
|
663
760
|
},
|
|
664
761
|
events: stream.iterable,
|
|
762
|
+
setContinuationSink(sink) { session.setContinuationSink(sink); },
|
|
665
763
|
// Intentionally does NOT call session.close(): sessions are pooled per sessionKey and
|
|
666
764
|
// reused across runAgentOnce turns. Pool-level cleanup goes through ClaudeAdapter.close(key)
|
|
667
765
|
// or the legacy closeSession / closeSessionsByPrefix exports.
|
|
@@ -772,10 +870,33 @@ export function recoverTuiOrphans(exec) {
|
|
|
772
870
|
log.info(`recoverTuiOrphans: swept ${killed.length}/${found.length} orphan tmux sessions (prefix=${TUI_TMUX_NAME_PREFIX})`);
|
|
773
871
|
return { found, killed };
|
|
774
872
|
}
|
|
873
|
+
/** Construct a ClaudeSession WITHOUT spawning the `claude` child process, for unit
|
|
874
|
+
* testing handleLine / continuation routing. Initializes only the fields the line
|
|
875
|
+
* handlers touch. Callers should stub createTurnStreams to avoid log file I/O and
|
|
876
|
+
* register cleanup via t.after(() => session.close()) to clear the idle timer. */
|
|
877
|
+
function makeSessionForTest() {
|
|
878
|
+
const s = Object.create(ClaudeSession.prototype);
|
|
879
|
+
s.sessionId = 'test-session';
|
|
880
|
+
s.channel = 'test';
|
|
881
|
+
s.sessionKey = 'test';
|
|
882
|
+
s.bgTracker = new BgTaskTracker();
|
|
883
|
+
s.continuationSink = null;
|
|
884
|
+
s.currentTurn = null;
|
|
885
|
+
s.idleTimer = null;
|
|
886
|
+
s.turnIdleTimer = null;
|
|
887
|
+
s.maxTimer = null;
|
|
888
|
+
s.cumulativeCostUsd = 0;
|
|
889
|
+
s.lastTokenUsage = null;
|
|
890
|
+
s.lastModelName = null;
|
|
891
|
+
s.alive = true;
|
|
892
|
+
s.proc = null;
|
|
893
|
+
return s;
|
|
894
|
+
}
|
|
775
895
|
export const _test = {
|
|
776
896
|
extractAskUserQuestions,
|
|
777
897
|
mergeSubstantialOutput,
|
|
778
898
|
computeSpawnArgs: computeSpawnArgsForConfig,
|
|
899
|
+
makeSessionForTest,
|
|
779
900
|
};
|
|
780
901
|
// Re-exported for webhook consumer (parity with pre-refactor claude-bridge.ts:286 export)
|
|
781
902
|
export { getCurrentPlanFilePath };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracks in-flight background tasks (run_in_background Bash/Agent) for a single
|
|
3
|
+
* persistent Claude session, by observing the CLI's stream-json `system` events.
|
|
4
|
+
*
|
|
5
|
+
* Observed lifecycle (real shapes, see /tmp/bg-capture.mjs):
|
|
6
|
+
* - launch: { type:'system', subtype:'task_started', task_id, task_type }
|
|
7
|
+
* - completion: { type:'system', subtype:'task_updated', task_id, patch:{status:'completed'} }
|
|
8
|
+
* { type:'system', subtype:'task_notification', task_id, status:'completed', summary }
|
|
9
|
+
*
|
|
10
|
+
* IMPORTANT: task_updated{completed} and task_notification are TWO separate events, and the
|
|
11
|
+
* CLI emits task_updated FIRST — sometimes seconds before the matching task_notification
|
|
12
|
+
* (gaps up to ~24s observed when several run_in_background tasks finish close together).
|
|
13
|
+
* task_notification is the one that actually re-invokes the model (the continuation turn).
|
|
14
|
+
* So pending is keyed off task_notification ONLY; clearing on task_updated would let the
|
|
15
|
+
* count hit 0 while continuation turns are still undelivered, sealing a turn "done"
|
|
16
|
+
* prematurely (a continuation result resolving in that gap snapshots pendingCount==0).
|
|
17
|
+
*
|
|
18
|
+
* When a background task completes the CLI spontaneously re-invokes the model and
|
|
19
|
+
* emits a fresh turn whose terminating `result` carries `origin.kind:'task-notification'`
|
|
20
|
+
* (see isContinuationResult). The adapter uses pendingCount to decide whether a turn's
|
|
21
|
+
* result should be sealed ("done") or held in a "waiting" state, and continuationArmed
|
|
22
|
+
* to recognize the spontaneous continuation turn that follows.
|
|
23
|
+
*/
|
|
24
|
+
export declare class BgTaskTracker {
|
|
25
|
+
private readonly pending;
|
|
26
|
+
/** Set when a background task completes; the spontaneous continuation turn that
|
|
27
|
+
* follows is recognized via this flag. Cleared by disarmContinuation(). */
|
|
28
|
+
continuationArmed: boolean;
|
|
29
|
+
/** Observe one parsed stream-json event. Idempotent per task_id. */
|
|
30
|
+
observe(data: any): void;
|
|
31
|
+
get pendingCount(): number;
|
|
32
|
+
hasPending(): boolean;
|
|
33
|
+
disarmContinuation(): void;
|
|
34
|
+
}
|
|
35
|
+
/** A `result` event produced by a background-task continuation turn carries
|
|
36
|
+
* origin.kind === 'task-notification'. Used to distinguish a spontaneous
|
|
37
|
+
* continuation result from a normal turn result. */
|
|
38
|
+
export declare function isContinuationResult(data: any): boolean;
|
|
39
|
+
/** How a parsed stream-json line should be routed by the session's handleLine. */
|
|
40
|
+
export type LineRoute = 'normal' | 'open-continuation' | 'ignore';
|
|
41
|
+
/**
|
|
42
|
+
* Decide how a parsed line should be routed given whether a turn is currently active.
|
|
43
|
+
* Pure: depends only on the tracker's armed state and the event type.
|
|
44
|
+
*/
|
|
45
|
+
export declare function routeLine(tracker: BgTaskTracker, data: any, hasActiveTurn: boolean): LineRoute;
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// input: parsed Claude stream-json events (system/result)
|
|
2
|
+
// output: BgTaskTracker (pending background-task count) + isContinuationResult
|
|
3
|
+
// pos: CC backend background-task continuation tracking (pure, no I/O)
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
/**
|
|
6
|
+
* Tracks in-flight background tasks (run_in_background Bash/Agent) for a single
|
|
7
|
+
* persistent Claude session, by observing the CLI's stream-json `system` events.
|
|
8
|
+
*
|
|
9
|
+
* Observed lifecycle (real shapes, see /tmp/bg-capture.mjs):
|
|
10
|
+
* - launch: { type:'system', subtype:'task_started', task_id, task_type }
|
|
11
|
+
* - completion: { type:'system', subtype:'task_updated', task_id, patch:{status:'completed'} }
|
|
12
|
+
* { type:'system', subtype:'task_notification', task_id, status:'completed', summary }
|
|
13
|
+
*
|
|
14
|
+
* IMPORTANT: task_updated{completed} and task_notification are TWO separate events, and the
|
|
15
|
+
* CLI emits task_updated FIRST — sometimes seconds before the matching task_notification
|
|
16
|
+
* (gaps up to ~24s observed when several run_in_background tasks finish close together).
|
|
17
|
+
* task_notification is the one that actually re-invokes the model (the continuation turn).
|
|
18
|
+
* So pending is keyed off task_notification ONLY; clearing on task_updated would let the
|
|
19
|
+
* count hit 0 while continuation turns are still undelivered, sealing a turn "done"
|
|
20
|
+
* prematurely (a continuation result resolving in that gap snapshots pendingCount==0).
|
|
21
|
+
*
|
|
22
|
+
* When a background task completes the CLI spontaneously re-invokes the model and
|
|
23
|
+
* emits a fresh turn whose terminating `result` carries `origin.kind:'task-notification'`
|
|
24
|
+
* (see isContinuationResult). The adapter uses pendingCount to decide whether a turn's
|
|
25
|
+
* result should be sealed ("done") or held in a "waiting" state, and continuationArmed
|
|
26
|
+
* to recognize the spontaneous continuation turn that follows.
|
|
27
|
+
*/
|
|
28
|
+
export class BgTaskTracker {
|
|
29
|
+
pending = new Set();
|
|
30
|
+
/** Set when a background task completes; the spontaneous continuation turn that
|
|
31
|
+
* follows is recognized via this flag. Cleared by disarmContinuation(). */
|
|
32
|
+
continuationArmed = false;
|
|
33
|
+
/** Observe one parsed stream-json event. Idempotent per task_id. */
|
|
34
|
+
observe(data) {
|
|
35
|
+
if (!data || data.type !== 'system')
|
|
36
|
+
return;
|
|
37
|
+
const id = typeof data.task_id === 'string' ? data.task_id : null;
|
|
38
|
+
if (!id)
|
|
39
|
+
return;
|
|
40
|
+
switch (data.subtype) {
|
|
41
|
+
case 'task_started':
|
|
42
|
+
this.pending.add(id);
|
|
43
|
+
break;
|
|
44
|
+
case 'task_updated':
|
|
45
|
+
// Intentionally a no-op for pending/arming, even on status 'completed'.
|
|
46
|
+
// task_updated marks the task's WORK as finished, but the CLI emits the
|
|
47
|
+
// matching task_notification LATER (observed gaps up to ~24s with several
|
|
48
|
+
// parallel tasks). task_notification is the event that actually re-invokes
|
|
49
|
+
// the model (the continuation turn). If we cleared pending here, the count
|
|
50
|
+
// could reach 0 while notifications are still undelivered, and a continuation
|
|
51
|
+
// turn resolving in that gap would seal the turn "done" prematurely. Pending
|
|
52
|
+
// is therefore keyed off task_notification only (see below).
|
|
53
|
+
break;
|
|
54
|
+
case 'task_notification':
|
|
55
|
+
// Emitted when a background task finishes (status 'completed' or error);
|
|
56
|
+
// this is the event that re-invokes the model. It is the authoritative
|
|
57
|
+
// completion-delivery signal, so it (and only it) clears pending + arms.
|
|
58
|
+
this.pending.delete(id);
|
|
59
|
+
this.continuationArmed = true;
|
|
60
|
+
break;
|
|
61
|
+
default:
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
get pendingCount() {
|
|
66
|
+
return this.pending.size;
|
|
67
|
+
}
|
|
68
|
+
hasPending() {
|
|
69
|
+
return this.pending.size > 0;
|
|
70
|
+
}
|
|
71
|
+
disarmContinuation() {
|
|
72
|
+
this.continuationArmed = false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** A `result` event produced by a background-task continuation turn carries
|
|
76
|
+
* origin.kind === 'task-notification'. Used to distinguish a spontaneous
|
|
77
|
+
* continuation result from a normal turn result. */
|
|
78
|
+
export function isContinuationResult(data) {
|
|
79
|
+
return data?.type === 'result' && data?.origin?.kind === 'task-notification';
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Decide how a parsed line should be routed given whether a turn is currently active.
|
|
83
|
+
* Pure: depends only on the tracker's armed state and the event type.
|
|
84
|
+
*/
|
|
85
|
+
export function routeLine(tracker, data, hasActiveTurn) {
|
|
86
|
+
if (hasActiveTurn)
|
|
87
|
+
return 'normal';
|
|
88
|
+
if (data?.type === 'assistant' && tracker.continuationArmed)
|
|
89
|
+
return 'open-continuation';
|
|
90
|
+
return 'ignore';
|
|
91
|
+
}
|
|
@@ -19,8 +19,10 @@ export declare function createPIEventParserState(): PIEventParserState;
|
|
|
19
19
|
* returns [] on subsequent bootstrap hits (Option A per Plan Review N2H-3).
|
|
20
20
|
*
|
|
21
21
|
* Dropped events (return []): turn_start, turn_end, message_start, agent_start,
|
|
22
|
-
* queue_update,
|
|
22
|
+
* queue_update, compaction_end, auto_retry_end, successful non-bootstrap
|
|
23
23
|
* response, message_update without text_delta, fire-and-forget extension_ui_request.
|
|
24
24
|
* message_end emits a turn_progress heartbeat (non-terminal, state.turnProgressCount++).
|
|
25
|
+
* compaction_start emits a context_compacted event (user notification); compaction_end is dropped
|
|
26
|
+
* to avoid a duplicate notice.
|
|
25
27
|
*/
|
|
26
28
|
export declare function piRpcLineToNormalized(line: string, state: PIEventParserState): NormalizedEvent[];
|
|
@@ -14,9 +14,11 @@ export function createPIEventParserState() {
|
|
|
14
14
|
* returns [] on subsequent bootstrap hits (Option A per Plan Review N2H-3).
|
|
15
15
|
*
|
|
16
16
|
* Dropped events (return []): turn_start, turn_end, message_start, agent_start,
|
|
17
|
-
* queue_update,
|
|
17
|
+
* queue_update, compaction_end, auto_retry_end, successful non-bootstrap
|
|
18
18
|
* response, message_update without text_delta, fire-and-forget extension_ui_request.
|
|
19
19
|
* message_end emits a turn_progress heartbeat (non-terminal, state.turnProgressCount++).
|
|
20
|
+
* compaction_start emits a context_compacted event (user notification); compaction_end is dropped
|
|
21
|
+
* to avoid a duplicate notice.
|
|
20
22
|
*/
|
|
21
23
|
export function piRpcLineToNormalized(line, state) {
|
|
22
24
|
if (!line)
|
|
@@ -104,6 +106,14 @@ export function piRpcLineToNormalized(line, state) {
|
|
|
104
106
|
if (type === 'auto_retry_start') {
|
|
105
107
|
return [{ type: 'rate_limit', raw: ev }];
|
|
106
108
|
}
|
|
109
|
+
// --- compaction_start → context_compacted (user notification) ---
|
|
110
|
+
// compaction_end is intentionally dropped below to avoid a duplicate notice.
|
|
111
|
+
if (type === 'compaction_start') {
|
|
112
|
+
const reason = typeof ev['reason'] === 'string' && ev['reason'].length > 0
|
|
113
|
+
? ev['reason']
|
|
114
|
+
: 'auto';
|
|
115
|
+
return [{ type: 'context_compacted', trigger: reason }];
|
|
116
|
+
}
|
|
107
117
|
// --- message_end → turn_progress (live heartbeat per assistant turn) ---
|
|
108
118
|
if (type === 'message_end') {
|
|
109
119
|
state.turnProgressCount++;
|
|
@@ -121,7 +131,7 @@ export function piRpcLineToNormalized(line, state) {
|
|
|
121
131
|
return handleExtensionUiRequest(ev);
|
|
122
132
|
}
|
|
123
133
|
// Silently drop all other events (turn_start/end, message_start/end, agent_start,
|
|
124
|
-
// queue_update,
|
|
134
|
+
// queue_update, compaction_end, auto_retry_end, successful non-bootstrap response).
|
|
125
135
|
return [];
|
|
126
136
|
}
|
|
127
137
|
// ---------------------------------------------------------------------------
|
|
@@ -85,6 +85,22 @@ export interface AgentSpawnConfig {
|
|
|
85
85
|
taskProject?: string | null;
|
|
86
86
|
};
|
|
87
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Session-level sink for background-task continuation turns (run_in_background Bash/Agent).
|
|
90
|
+
* After a background task finishes, the Claude CLI spontaneously re-invokes the model and
|
|
91
|
+
* emits a follow-up turn with no caller awaiting it. The adapter routes that turn here so
|
|
92
|
+
* orchestration can merge it into the originating reply and seal the status once the
|
|
93
|
+
* background tasks are done. Only the Claude backend implements this (capability-gated).
|
|
94
|
+
*/
|
|
95
|
+
export interface ContinuationSink {
|
|
96
|
+
/** Assistant text from the continuation turn (append to the original reply). */
|
|
97
|
+
onAssistantText: (text: string) => void;
|
|
98
|
+
/** Optional tool_use trace from the continuation turn. */
|
|
99
|
+
onToolUse?: (name: string, input: any) => void;
|
|
100
|
+
/** Continuation turn's terminating result. `result.pendingBackgroundTasks` is the number
|
|
101
|
+
* of background tasks still running (0 ⇒ safe to seal the status as complete). */
|
|
102
|
+
onResult: (result: AgentResult) => void;
|
|
103
|
+
}
|
|
88
104
|
export interface AgentProcess {
|
|
89
105
|
sessionKey: string;
|
|
90
106
|
/** May be null at spawn time; adapter fills in asynchronously when the backend assigns a session id. */
|
|
@@ -93,6 +109,9 @@ export interface AgentProcess {
|
|
|
93
109
|
send(message: UserMessage): Promise<AgentResult>;
|
|
94
110
|
/** Async iterable of normalized events. Iterator returns done after close(). */
|
|
95
111
|
events: AsyncIterable<NormalizedEvent>;
|
|
112
|
+
/** Register a sink for spontaneous background-task continuation turns (Claude backend only).
|
|
113
|
+
* Persists across normal turns; the adapter clears it on session close/kill. */
|
|
114
|
+
setContinuationSink?(sink: ContinuationSink): void;
|
|
96
115
|
close(): Promise<void>;
|
|
97
116
|
kill(): boolean;
|
|
98
117
|
}
|