@draht/coding-agent 2026.3.25 → 2026.4.23
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 +896 -624
- package/README.md +110 -97
- package/dist/cli/args.d.ts +7 -10
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +42 -44
- package/dist/cli/args.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +9 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +18 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +83 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -0
- package/dist/core/agent-session-runtime.js +236 -0
- package/dist/core/agent-session-runtime.js.map +1 -0
- package/dist/core/agent-session-services.d.ts +86 -0
- package/dist/core/agent-session-services.d.ts.map +1 -0
- package/dist/core/agent-session-services.js +116 -0
- package/dist/core/agent-session-services.js.map +1 -0
- package/dist/core/agent-session.d.ts +17 -47
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +166 -291
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +3 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +5 -2
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +19 -7
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +2 -0
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +2 -2
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +3 -3
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +27 -26
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts +2 -0
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +2 -2
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +2 -2
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +7 -7
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +1 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +4 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +30 -29
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js +10 -0
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +5 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +70 -8
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/index.d.ts +3 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +3 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/keybindings.d.ts +14 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +13 -14
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/model-registry.d.ts +21 -3
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +120 -71
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +4 -4
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/package-manager.d.ts +21 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +108 -43
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +1 -22
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/resolve-config-value.d.ts +6 -0
- package/dist/core/resolve-config-value.d.ts.map +1 -1
- package/dist/core/resolve-config-value.js +37 -5
- package/dist/core/resolve-config-value.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +25 -3
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +7 -4
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +18 -24
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-cwd.d.ts +19 -0
- package/dist/core/session-cwd.d.ts.map +1 -0
- package/dist/core/session-cwd.js +38 -0
- package/dist/core/session-cwd.js.map +1 -0
- package/dist/core/session-manager.d.ts +5 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +16 -8
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +3 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +5 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +3 -3
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +6 -6
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/timings.d.ts +1 -0
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/timings.js +6 -0
- package/dist/core/timings.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +19 -9
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts +23 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +150 -57
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts +13 -11
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +55 -77
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
- package/dist/core/tools/file-mutation-queue.js +4 -4
- package/dist/core/tools/file-mutation-queue.js.map +1 -1
- package/dist/core/tools/index.d.ts +9 -6
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +2 -0
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/index.d.ts +4 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -6
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +259 -422
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +3 -3
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +25 -5
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +3 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +14 -3
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
- package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
- package/dist/modes/interactive/components/earendil-announcement.js +40 -0
- package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
- package/dist/modes/interactive/components/footer.d.ts +1 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +4 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +0 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +2 -7
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +4 -2
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +48 -15
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +18 -5
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +287 -188
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +15 -11
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/print-mode.d.ts +2 -2
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +89 -72
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +1 -0
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts +2 -2
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +95 -64
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts +4 -0
- package/dist/package-manager-cli.d.ts.map +1 -0
- package/dist/package-manager-cli.js +234 -0
- package/dist/package-manager-cli.js.map +1 -0
- package/dist/prompts/commands/atomic-commit.md +17 -0
- package/dist/prompts/commands/discuss-phase.md +15 -0
- package/dist/prompts/commands/execute-phase.md +14 -0
- package/dist/prompts/commands/fix.md +14 -0
- package/dist/prompts/commands/init-project.md +16 -0
- package/dist/prompts/commands/map-codebase.md +16 -0
- package/dist/prompts/commands/new-project.md +16 -0
- package/dist/prompts/commands/next-milestone.md +16 -0
- package/dist/prompts/commands/pause-work.md +13 -0
- package/dist/prompts/commands/plan-phase.md +15 -0
- package/dist/prompts/commands/progress.md +13 -0
- package/dist/prompts/commands/quick.md +14 -0
- package/dist/prompts/commands/resume-work.md +13 -0
- package/dist/prompts/commands/review.md +15 -0
- package/dist/prompts/commands/verify-work.md +15 -0
- package/dist/utils/paths.d.ts +7 -0
- package/dist/utils/paths.d.ts.map +1 -0
- package/dist/utils/paths.js +19 -0
- package/dist/utils/paths.js.map +1 -0
- package/docs/compaction.md +5 -3
- package/docs/custom-provider.md +1 -1
- package/docs/development.md +5 -3
- package/docs/extensions.md +221 -69
- package/docs/json.md +5 -2
- package/docs/keybindings.md +2 -0
- package/docs/models.md +60 -3
- package/docs/packages.md +3 -3
- package/docs/rpc.md +23 -9
- package/docs/sdk.md +240 -84
- package/docs/session.md +3 -3
- package/docs/settings.md +12 -0
- package/docs/skills.md +3 -2
- package/docs/tree.md +6 -3
- package/examples/README.md +1 -1
- package/examples/extensions/README.md +1 -0
- package/examples/extensions/antigravity-image-gen.ts +1 -1
- package/examples/extensions/custom-compaction.ts +17 -4
- package/examples/extensions/custom-provider-gitlab-duo/index.ts +1 -1
- package/examples/extensions/doom-overlay/doom/build.sh +2 -2
- package/examples/extensions/handoff.ts +5 -2
- package/examples/extensions/hello.ts +18 -17
- package/examples/extensions/hidden-thinking-label.ts +53 -0
- package/examples/extensions/overlay-qa-tests.ts +2 -2
- package/examples/extensions/qna.ts +5 -2
- package/examples/extensions/rpc-demo.ts +3 -9
- package/examples/extensions/sandbox/index.ts +8 -4
- package/examples/extensions/status-line.ts +0 -8
- package/examples/extensions/subagent/index.ts +6 -6
- package/examples/extensions/summarize.ts +15 -4
- package/examples/extensions/todo.ts +0 -2
- package/examples/extensions/tools.ts +0 -5
- package/examples/extensions/trigger-compact.ts +11 -1
- package/examples/extensions/widget-placement.ts +4 -12
- package/examples/sdk/02-custom-model.ts +1 -1
- package/examples/sdk/09-api-keys-and-oauth.ts +3 -3
- package/examples/sdk/12-full-control.ts +1 -1
- package/examples/sdk/13-session-runtime.ts +67 -0
- package/examples/sdk/README.md +8 -5
- package/package.json +7 -8
- package/prompts/commands/atomic-commit.md +17 -0
- package/prompts/commands/discuss-phase.md +15 -0
- package/prompts/commands/execute-phase.md +14 -0
- package/prompts/commands/fix.md +14 -0
- package/prompts/commands/init-project.md +16 -0
- package/prompts/commands/map-codebase.md +16 -0
- package/prompts/commands/new-project.md +16 -0
- package/prompts/commands/next-milestone.md +16 -0
- package/prompts/commands/pause-work.md +13 -0
- package/prompts/commands/plan-phase.md +15 -0
- package/prompts/commands/progress.md +13 -0
- package/prompts/commands/quick.md +14 -0
- package/prompts/commands/resume-work.md +13 -0
- package/prompts/commands/review.md +15 -0
- package/prompts/commands/verify-work.md +15 -0
|
@@ -12,14 +12,14 @@
|
|
|
12
12
|
*
|
|
13
13
|
* Modes use this class and add their own I/O layer on top.
|
|
14
14
|
*/
|
|
15
|
-
import {
|
|
15
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
16
16
|
import { basename, dirname, join, resolve } from "node:path";
|
|
17
17
|
import { isContextOverflow, modelsAreEqual, resetApiProviders, supportsXhigh } from "@draht/ai";
|
|
18
18
|
import { getDocsPath } from "../config.js";
|
|
19
19
|
import { theme } from "../modes/interactive/theme/theme.js";
|
|
20
20
|
import { stripFrontmatter } from "../utils/frontmatter.js";
|
|
21
21
|
import { sleep } from "../utils/sleep.js";
|
|
22
|
-
import {
|
|
22
|
+
import { executeBashWithOperations } from "./bash-executor.js";
|
|
23
23
|
import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
|
|
24
24
|
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
|
|
25
25
|
import { exportSessionToHtml } from "./export-html/index.js";
|
|
@@ -29,6 +29,7 @@ import { expandPromptTemplate } from "./prompt-templates.js";
|
|
|
29
29
|
import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
|
|
30
30
|
import { createSyntheticSourceInfo } from "./source-info.js";
|
|
31
31
|
import { buildSystemPrompt } from "./system-prompt.js";
|
|
32
|
+
import { createLocalBashOperations } from "./tools/bash.js";
|
|
32
33
|
import { createAllToolDefinitions } from "./tools/index.js";
|
|
33
34
|
import { createToolDefinitionFromAgentTool, wrapToolDefinition } from "./tools/tool-definition-wrapper.js";
|
|
34
35
|
/**
|
|
@@ -95,6 +96,7 @@ export class AgentSession {
|
|
|
95
96
|
_extensionRunnerRef;
|
|
96
97
|
_initialActiveToolNames;
|
|
97
98
|
_baseToolsOverride;
|
|
99
|
+
_sessionStartEvent;
|
|
98
100
|
_extensionUIContext;
|
|
99
101
|
_extensionCommandContextActions;
|
|
100
102
|
_extensionShutdownHandler;
|
|
@@ -121,6 +123,7 @@ export class AgentSession {
|
|
|
121
123
|
this._extensionRunnerRef = config.extensionRunnerRef;
|
|
122
124
|
this._initialActiveToolNames = config.initialActiveToolNames;
|
|
123
125
|
this._baseToolsOverride = config.baseToolsOverride;
|
|
126
|
+
this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
|
|
124
127
|
// Always subscribe to agent events for internal handling
|
|
125
128
|
// (session persistence, extensions, auto-compaction, retry logic)
|
|
126
129
|
this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
|
|
@@ -134,6 +137,23 @@ export class AgentSession {
|
|
|
134
137
|
get modelRegistry() {
|
|
135
138
|
return this._modelRegistry;
|
|
136
139
|
}
|
|
140
|
+
async _getRequiredRequestAuth(model) {
|
|
141
|
+
const result = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
142
|
+
if (!result.ok) {
|
|
143
|
+
throw new Error(result.error);
|
|
144
|
+
}
|
|
145
|
+
if (result.apiKey) {
|
|
146
|
+
return { apiKey: result.apiKey, headers: result.headers };
|
|
147
|
+
}
|
|
148
|
+
const isOAuth = this._modelRegistry.isUsingOAuth(model);
|
|
149
|
+
if (isOAuth) {
|
|
150
|
+
throw new Error(`Authentication failed for "${model.provider}". ` +
|
|
151
|
+
`Credentials may have expired or network is unavailable. ` +
|
|
152
|
+
`Run '/login ${model.provider}' to re-authenticate.`);
|
|
153
|
+
}
|
|
154
|
+
throw new Error(`No API key found for ${model.provider}.\n\n` +
|
|
155
|
+
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
|
|
156
|
+
}
|
|
137
157
|
/**
|
|
138
158
|
* Install tool hooks once on the Agent instance.
|
|
139
159
|
*
|
|
@@ -143,7 +163,7 @@ export class AgentSession {
|
|
|
143
163
|
* happens here instead of in wrappers.
|
|
144
164
|
*/
|
|
145
165
|
_installAgentToolHooks() {
|
|
146
|
-
this.agent.
|
|
166
|
+
this.agent.beforeToolCall = async ({ toolCall, args }) => {
|
|
147
167
|
const runner = this._extensionRunner;
|
|
148
168
|
if (!runner?.hasHandlers("tool_call")) {
|
|
149
169
|
return undefined;
|
|
@@ -163,8 +183,8 @@ export class AgentSession {
|
|
|
163
183
|
}
|
|
164
184
|
throw new Error(`Extension failed, blocking execution: ${String(err)}`);
|
|
165
185
|
}
|
|
166
|
-
}
|
|
167
|
-
this.agent.
|
|
186
|
+
};
|
|
187
|
+
this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
|
|
168
188
|
const runner = this._extensionRunner;
|
|
169
189
|
if (!runner?.hasHandlers("tool_result")) {
|
|
170
190
|
return undefined;
|
|
@@ -185,7 +205,7 @@ export class AgentSession {
|
|
|
185
205
|
content: hookResult.content,
|
|
186
206
|
details: hookResult.details,
|
|
187
207
|
};
|
|
188
|
-
}
|
|
208
|
+
};
|
|
189
209
|
}
|
|
190
210
|
// =========================================================================
|
|
191
211
|
// Event Subscription
|
|
@@ -196,6 +216,13 @@ export class AgentSession {
|
|
|
196
216
|
l(event);
|
|
197
217
|
}
|
|
198
218
|
}
|
|
219
|
+
_emitQueueUpdate() {
|
|
220
|
+
this._emit({
|
|
221
|
+
type: "queue_update",
|
|
222
|
+
steering: [...this._steeringMessages],
|
|
223
|
+
followUp: [...this._followUpMessages],
|
|
224
|
+
});
|
|
225
|
+
}
|
|
199
226
|
// Track last assistant message for auto-compaction check
|
|
200
227
|
_lastAssistantMessage = undefined;
|
|
201
228
|
/** Internal handler for agent events - shared by subscribe and reconnect */
|
|
@@ -246,12 +273,14 @@ export class AgentSession {
|
|
|
246
273
|
const steeringIndex = this._steeringMessages.indexOf(messageText);
|
|
247
274
|
if (steeringIndex !== -1) {
|
|
248
275
|
this._steeringMessages.splice(steeringIndex, 1);
|
|
276
|
+
this._emitQueueUpdate();
|
|
249
277
|
}
|
|
250
278
|
else {
|
|
251
279
|
// Check follow-up queue
|
|
252
280
|
const followUpIndex = this._followUpMessages.indexOf(messageText);
|
|
253
281
|
if (followUpIndex !== -1) {
|
|
254
282
|
this._followUpMessages.splice(followUpIndex, 1);
|
|
283
|
+
this._emitQueueUpdate();
|
|
255
284
|
}
|
|
256
285
|
}
|
|
257
286
|
}
|
|
@@ -524,10 +553,10 @@ export class AgentSession {
|
|
|
524
553
|
validToolNames.push(name);
|
|
525
554
|
}
|
|
526
555
|
}
|
|
527
|
-
this.agent.
|
|
556
|
+
this.agent.state.tools = tools;
|
|
528
557
|
// Rebuild base system prompt with new tool set
|
|
529
558
|
this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
|
|
530
|
-
this.agent.
|
|
559
|
+
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
531
560
|
}
|
|
532
561
|
/** Whether compaction or branch summarization is currently running */
|
|
533
562
|
get isCompacting() {
|
|
@@ -541,11 +570,11 @@ export class AgentSession {
|
|
|
541
570
|
}
|
|
542
571
|
/** Current steering mode */
|
|
543
572
|
get steeringMode() {
|
|
544
|
-
return this.agent.
|
|
573
|
+
return this.agent.steeringMode;
|
|
545
574
|
}
|
|
546
575
|
/** Current follow-up mode */
|
|
547
576
|
get followUpMode() {
|
|
548
|
-
return this.agent.
|
|
577
|
+
return this.agent.followUpMode;
|
|
549
578
|
}
|
|
550
579
|
/** Current session file path, or undefined if sessions are disabled */
|
|
551
580
|
get sessionFile() {
|
|
@@ -686,9 +715,7 @@ export class AgentSession {
|
|
|
686
715
|
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}\n\n` +
|
|
687
716
|
"Then use /model to select a model.");
|
|
688
717
|
}
|
|
689
|
-
|
|
690
|
-
const apiKey = await this._modelRegistry.getApiKey(this.model);
|
|
691
|
-
if (!apiKey) {
|
|
718
|
+
if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
|
|
692
719
|
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
693
720
|
if (isOAuth) {
|
|
694
721
|
throw new Error(`Authentication failed for "${this.model.provider}". ` +
|
|
@@ -738,11 +765,11 @@ export class AgentSession {
|
|
|
738
765
|
}
|
|
739
766
|
// Apply extension-modified system prompt, or reset to base
|
|
740
767
|
if (result?.systemPrompt) {
|
|
741
|
-
this.agent.
|
|
768
|
+
this.agent.state.systemPrompt = result.systemPrompt;
|
|
742
769
|
}
|
|
743
770
|
else {
|
|
744
771
|
// Ensure we're using the base prompt (in case previous turn had modifications)
|
|
745
|
-
this.agent.
|
|
772
|
+
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
746
773
|
}
|
|
747
774
|
}
|
|
748
775
|
await this.agent.prompt(messages);
|
|
@@ -847,6 +874,7 @@ export class AgentSession {
|
|
|
847
874
|
*/
|
|
848
875
|
async _queueSteer(text, images) {
|
|
849
876
|
this._steeringMessages.push(text);
|
|
877
|
+
this._emitQueueUpdate();
|
|
850
878
|
const content = [{ type: "text", text }];
|
|
851
879
|
if (images) {
|
|
852
880
|
content.push(...images);
|
|
@@ -862,6 +890,7 @@ export class AgentSession {
|
|
|
862
890
|
*/
|
|
863
891
|
async _queueFollowUp(text, images) {
|
|
864
892
|
this._followUpMessages.push(text);
|
|
893
|
+
this._emitQueueUpdate();
|
|
865
894
|
const content = [{ type: "text", text }];
|
|
866
895
|
if (images) {
|
|
867
896
|
content.push(...images);
|
|
@@ -921,7 +950,7 @@ export class AgentSession {
|
|
|
921
950
|
await this.agent.prompt(appMessage);
|
|
922
951
|
}
|
|
923
952
|
else {
|
|
924
|
-
this.agent.
|
|
953
|
+
this.agent.state.messages.push(appMessage);
|
|
925
954
|
this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
|
|
926
955
|
this._emit({ type: "message_start", message: appMessage });
|
|
927
956
|
this._emit({ type: "message_end", message: appMessage });
|
|
@@ -975,6 +1004,7 @@ export class AgentSession {
|
|
|
975
1004
|
this._steeringMessages = [];
|
|
976
1005
|
this._followUpMessages = [];
|
|
977
1006
|
this.agent.clearAllQueues();
|
|
1007
|
+
this._emitQueueUpdate();
|
|
978
1008
|
return { steering, followUp };
|
|
979
1009
|
}
|
|
980
1010
|
/** Number of pending messages (includes both steering and follow-up) */
|
|
@@ -1000,54 +1030,6 @@ export class AgentSession {
|
|
|
1000
1030
|
this.agent.abort();
|
|
1001
1031
|
await this.agent.waitForIdle();
|
|
1002
1032
|
}
|
|
1003
|
-
/**
|
|
1004
|
-
* Start a new session, optionally with initial messages and parent tracking.
|
|
1005
|
-
* Clears all messages and starts a new session.
|
|
1006
|
-
* Listeners are preserved and will continue receiving events.
|
|
1007
|
-
* @param options.parentSession - Optional parent session path for tracking
|
|
1008
|
-
* @param options.setup - Optional callback to initialize session (e.g., append messages)
|
|
1009
|
-
* @returns true if completed, false if cancelled by extension
|
|
1010
|
-
*/
|
|
1011
|
-
async newSession(options) {
|
|
1012
|
-
const previousSessionFile = this.sessionFile;
|
|
1013
|
-
// Emit session_before_switch event with reason "new" (can be cancelled)
|
|
1014
|
-
if (this._extensionRunner?.hasHandlers("session_before_switch")) {
|
|
1015
|
-
const result = (await this._extensionRunner.emit({
|
|
1016
|
-
type: "session_before_switch",
|
|
1017
|
-
reason: "new",
|
|
1018
|
-
}));
|
|
1019
|
-
if (result?.cancel) {
|
|
1020
|
-
return false;
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
this._disconnectFromAgent();
|
|
1024
|
-
await this.abort();
|
|
1025
|
-
this.agent.reset();
|
|
1026
|
-
this.sessionManager.newSession({ parentSession: options?.parentSession });
|
|
1027
|
-
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
1028
|
-
this._steeringMessages = [];
|
|
1029
|
-
this._followUpMessages = [];
|
|
1030
|
-
this._pendingNextTurnMessages = [];
|
|
1031
|
-
this.sessionManager.appendThinkingLevelChange(this.thinkingLevel);
|
|
1032
|
-
// Run setup callback if provided (e.g., to append initial messages)
|
|
1033
|
-
if (options?.setup) {
|
|
1034
|
-
await options.setup(this.sessionManager);
|
|
1035
|
-
// Sync agent state with session manager after setup
|
|
1036
|
-
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1037
|
-
this.agent.replaceMessages(sessionContext.messages);
|
|
1038
|
-
}
|
|
1039
|
-
this._reconnectToAgent();
|
|
1040
|
-
// Emit session_switch event with reason "new" to extensions
|
|
1041
|
-
if (this._extensionRunner) {
|
|
1042
|
-
await this._extensionRunner.emit({
|
|
1043
|
-
type: "session_switch",
|
|
1044
|
-
reason: "new",
|
|
1045
|
-
previousSessionFile,
|
|
1046
|
-
});
|
|
1047
|
-
}
|
|
1048
|
-
// Emit session event to custom tools
|
|
1049
|
-
return true;
|
|
1050
|
-
}
|
|
1051
1033
|
// =========================================================================
|
|
1052
1034
|
// Model Management
|
|
1053
1035
|
// =========================================================================
|
|
@@ -1065,17 +1047,16 @@ export class AgentSession {
|
|
|
1065
1047
|
}
|
|
1066
1048
|
/**
|
|
1067
1049
|
* Set model directly.
|
|
1068
|
-
* Validates
|
|
1069
|
-
* @throws Error if no
|
|
1050
|
+
* Validates that auth is configured, saves to session and settings.
|
|
1051
|
+
* @throws Error if no auth is configured for the model
|
|
1070
1052
|
*/
|
|
1071
1053
|
async setModel(model) {
|
|
1072
|
-
|
|
1073
|
-
if (!apiKey) {
|
|
1054
|
+
if (!this._modelRegistry.hasConfiguredAuth(model)) {
|
|
1074
1055
|
throw new Error(`No API key for ${model.provider}/${model.id}`);
|
|
1075
1056
|
}
|
|
1076
1057
|
const previousModel = this.model;
|
|
1077
1058
|
const thinkingLevel = this._getThinkingLevelForModelSwitch();
|
|
1078
|
-
this.agent.
|
|
1059
|
+
this.agent.state.model = model;
|
|
1079
1060
|
this.sessionManager.appendModelChange(model.provider, model.id);
|
|
1080
1061
|
this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
|
|
1081
1062
|
// Re-clamp thinking level for new model's capabilities
|
|
@@ -1094,27 +1075,8 @@ export class AgentSession {
|
|
|
1094
1075
|
}
|
|
1095
1076
|
return this._cycleAvailableModel(direction);
|
|
1096
1077
|
}
|
|
1097
|
-
async _getScopedModelsWithApiKey() {
|
|
1098
|
-
const apiKeysByProvider = new Map();
|
|
1099
|
-
const result = [];
|
|
1100
|
-
for (const scoped of this._scopedModels) {
|
|
1101
|
-
const provider = scoped.model.provider;
|
|
1102
|
-
let apiKey;
|
|
1103
|
-
if (apiKeysByProvider.has(provider)) {
|
|
1104
|
-
apiKey = apiKeysByProvider.get(provider);
|
|
1105
|
-
}
|
|
1106
|
-
else {
|
|
1107
|
-
apiKey = await this._modelRegistry.getApiKeyForProvider(provider);
|
|
1108
|
-
apiKeysByProvider.set(provider, apiKey);
|
|
1109
|
-
}
|
|
1110
|
-
if (apiKey) {
|
|
1111
|
-
result.push(scoped);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
return result;
|
|
1115
|
-
}
|
|
1116
1078
|
async _cycleScopedModel(direction) {
|
|
1117
|
-
const scopedModels =
|
|
1079
|
+
const scopedModels = this._scopedModels.filter((scoped) => this._modelRegistry.hasConfiguredAuth(scoped.model));
|
|
1118
1080
|
if (scopedModels.length <= 1)
|
|
1119
1081
|
return undefined;
|
|
1120
1082
|
const currentModel = this.model;
|
|
@@ -1126,7 +1088,7 @@ export class AgentSession {
|
|
|
1126
1088
|
const next = scopedModels[nextIndex];
|
|
1127
1089
|
const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
|
|
1128
1090
|
// Apply model
|
|
1129
|
-
this.agent.
|
|
1091
|
+
this.agent.state.model = next.model;
|
|
1130
1092
|
this.sessionManager.appendModelChange(next.model.provider, next.model.id);
|
|
1131
1093
|
this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
|
|
1132
1094
|
// Apply thinking level.
|
|
@@ -1148,12 +1110,8 @@ export class AgentSession {
|
|
|
1148
1110
|
const len = availableModels.length;
|
|
1149
1111
|
const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
|
|
1150
1112
|
const nextModel = availableModels[nextIndex];
|
|
1151
|
-
const apiKey = await this._modelRegistry.getApiKey(nextModel);
|
|
1152
|
-
if (!apiKey) {
|
|
1153
|
-
throw new Error(`No API key for ${nextModel.provider}/${nextModel.id}`);
|
|
1154
|
-
}
|
|
1155
1113
|
const thinkingLevel = this._getThinkingLevelForModelSwitch();
|
|
1156
|
-
this.agent.
|
|
1114
|
+
this.agent.state.model = nextModel;
|
|
1157
1115
|
this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
|
|
1158
1116
|
this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
|
|
1159
1117
|
// Re-clamp thinking level for new model's capabilities
|
|
@@ -1174,7 +1132,7 @@ export class AgentSession {
|
|
|
1174
1132
|
const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
|
|
1175
1133
|
// Only persist if actually changing
|
|
1176
1134
|
const isChanging = effectiveLevel !== this.agent.state.thinkingLevel;
|
|
1177
|
-
this.agent.
|
|
1135
|
+
this.agent.state.thinkingLevel = effectiveLevel;
|
|
1178
1136
|
if (isChanging) {
|
|
1179
1137
|
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
1180
1138
|
if (this.supportsThinking() || effectiveLevel !== "off") {
|
|
@@ -1253,7 +1211,7 @@ export class AgentSession {
|
|
|
1253
1211
|
* Saves to settings.
|
|
1254
1212
|
*/
|
|
1255
1213
|
setSteeringMode(mode) {
|
|
1256
|
-
this.agent.
|
|
1214
|
+
this.agent.steeringMode = mode;
|
|
1257
1215
|
this.settingsManager.setSteeringMode(mode);
|
|
1258
1216
|
}
|
|
1259
1217
|
/**
|
|
@@ -1261,7 +1219,7 @@ export class AgentSession {
|
|
|
1261
1219
|
* Saves to settings.
|
|
1262
1220
|
*/
|
|
1263
1221
|
setFollowUpMode(mode) {
|
|
1264
|
-
this.agent.
|
|
1222
|
+
this.agent.followUpMode = mode;
|
|
1265
1223
|
this.settingsManager.setFollowUpMode(mode);
|
|
1266
1224
|
}
|
|
1267
1225
|
// =========================================================================
|
|
@@ -1276,14 +1234,12 @@ export class AgentSession {
|
|
|
1276
1234
|
this._disconnectFromAgent();
|
|
1277
1235
|
await this.abort();
|
|
1278
1236
|
this._compactionAbortController = new AbortController();
|
|
1237
|
+
this._emit({ type: "compaction_start", reason: "manual" });
|
|
1279
1238
|
try {
|
|
1280
1239
|
if (!this.model) {
|
|
1281
1240
|
throw new Error("No model selected");
|
|
1282
1241
|
}
|
|
1283
|
-
const apiKey = await this.
|
|
1284
|
-
if (!apiKey) {
|
|
1285
|
-
throw new Error(`No API key for ${this.model.provider}`);
|
|
1286
|
-
}
|
|
1242
|
+
const { apiKey, headers } = await this._getRequiredRequestAuth(this.model);
|
|
1287
1243
|
const pathEntries = this.sessionManager.getBranch();
|
|
1288
1244
|
const settings = this.settingsManager.getCompactionSettings();
|
|
1289
1245
|
const preparation = prepareCompaction(pathEntries, settings);
|
|
@@ -1326,7 +1282,7 @@ export class AgentSession {
|
|
|
1326
1282
|
}
|
|
1327
1283
|
else {
|
|
1328
1284
|
// Generate compaction result
|
|
1329
|
-
const result = await compact(preparation, this.model, apiKey, customInstructions, this._compactionAbortController.signal);
|
|
1285
|
+
const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal);
|
|
1330
1286
|
summary = result.summary;
|
|
1331
1287
|
firstKeptEntryId = result.firstKeptEntryId;
|
|
1332
1288
|
tokensBefore = result.tokensBefore;
|
|
@@ -1338,7 +1294,7 @@ export class AgentSession {
|
|
|
1338
1294
|
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
|
|
1339
1295
|
const newEntries = this.sessionManager.getEntries();
|
|
1340
1296
|
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1341
|
-
this.agent.
|
|
1297
|
+
this.agent.state.messages = sessionContext.messages;
|
|
1342
1298
|
// Get the saved compaction entry for the extension event
|
|
1343
1299
|
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1344
1300
|
if (this._extensionRunner && savedCompactionEntry) {
|
|
@@ -1348,12 +1304,33 @@ export class AgentSession {
|
|
|
1348
1304
|
fromExtension,
|
|
1349
1305
|
});
|
|
1350
1306
|
}
|
|
1351
|
-
|
|
1307
|
+
const compactionResult = {
|
|
1352
1308
|
summary,
|
|
1353
1309
|
firstKeptEntryId,
|
|
1354
1310
|
tokensBefore,
|
|
1355
1311
|
details,
|
|
1356
1312
|
};
|
|
1313
|
+
this._emit({
|
|
1314
|
+
type: "compaction_end",
|
|
1315
|
+
reason: "manual",
|
|
1316
|
+
result: compactionResult,
|
|
1317
|
+
aborted: false,
|
|
1318
|
+
willRetry: false,
|
|
1319
|
+
});
|
|
1320
|
+
return compactionResult;
|
|
1321
|
+
}
|
|
1322
|
+
catch (error) {
|
|
1323
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1324
|
+
const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
|
|
1325
|
+
this._emit({
|
|
1326
|
+
type: "compaction_end",
|
|
1327
|
+
reason: "manual",
|
|
1328
|
+
result: undefined,
|
|
1329
|
+
aborted,
|
|
1330
|
+
willRetry: false,
|
|
1331
|
+
errorMessage: aborted ? undefined : `Compaction failed: ${message}`,
|
|
1332
|
+
});
|
|
1333
|
+
throw error;
|
|
1357
1334
|
}
|
|
1358
1335
|
finally {
|
|
1359
1336
|
this._compactionAbortController = undefined;
|
|
@@ -1409,7 +1386,8 @@ export class AgentSession {
|
|
|
1409
1386
|
if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
|
|
1410
1387
|
if (this._overflowRecoveryAttempted) {
|
|
1411
1388
|
this._emit({
|
|
1412
|
-
type: "
|
|
1389
|
+
type: "compaction_end",
|
|
1390
|
+
reason: "overflow",
|
|
1413
1391
|
result: undefined,
|
|
1414
1392
|
aborted: false,
|
|
1415
1393
|
willRetry: false,
|
|
@@ -1422,7 +1400,7 @@ export class AgentSession {
|
|
|
1422
1400
|
// but we don't want it in context for the retry)
|
|
1423
1401
|
const messages = this.agent.state.messages;
|
|
1424
1402
|
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
1425
|
-
this.agent.
|
|
1403
|
+
this.agent.state.messages = messages.slice(0, -1);
|
|
1426
1404
|
}
|
|
1427
1405
|
await this._runAutoCompaction("overflow", true);
|
|
1428
1406
|
return;
|
|
@@ -1432,9 +1410,19 @@ export class AgentSession {
|
|
|
1432
1410
|
// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.
|
|
1433
1411
|
let contextTokens;
|
|
1434
1412
|
if (assistantMessage.stopReason === "error") {
|
|
1435
|
-
const
|
|
1413
|
+
const messages = this.agent.state.messages;
|
|
1414
|
+
const estimate = estimateContextTokens(messages);
|
|
1436
1415
|
if (estimate.lastUsageIndex === null)
|
|
1437
1416
|
return; // No usage data at all
|
|
1417
|
+
// Verify the usage source is post-compaction. Kept pre-compaction messages
|
|
1418
|
+
// have stale usage reflecting the old (larger) context and would falsely
|
|
1419
|
+
// trigger compaction right after one just finished.
|
|
1420
|
+
const usageMsg = messages[estimate.lastUsageIndex];
|
|
1421
|
+
if (compactionEntry &&
|
|
1422
|
+
usageMsg.role === "assistant" &&
|
|
1423
|
+
usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1438
1426
|
contextTokens = estimate.tokens;
|
|
1439
1427
|
}
|
|
1440
1428
|
else {
|
|
@@ -1449,22 +1437,41 @@ export class AgentSession {
|
|
|
1449
1437
|
*/
|
|
1450
1438
|
async _runAutoCompaction(reason, willRetry) {
|
|
1451
1439
|
const settings = this.settingsManager.getCompactionSettings();
|
|
1452
|
-
this._emit({ type: "
|
|
1440
|
+
this._emit({ type: "compaction_start", reason });
|
|
1453
1441
|
this._autoCompactionAbortController = new AbortController();
|
|
1454
1442
|
try {
|
|
1455
1443
|
if (!this.model) {
|
|
1456
|
-
this._emit({
|
|
1444
|
+
this._emit({
|
|
1445
|
+
type: "compaction_end",
|
|
1446
|
+
reason,
|
|
1447
|
+
result: undefined,
|
|
1448
|
+
aborted: false,
|
|
1449
|
+
willRetry: false,
|
|
1450
|
+
});
|
|
1457
1451
|
return;
|
|
1458
1452
|
}
|
|
1459
|
-
const
|
|
1460
|
-
if (!apiKey) {
|
|
1461
|
-
this._emit({
|
|
1453
|
+
const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
|
|
1454
|
+
if (!authResult.ok || !authResult.apiKey) {
|
|
1455
|
+
this._emit({
|
|
1456
|
+
type: "compaction_end",
|
|
1457
|
+
reason,
|
|
1458
|
+
result: undefined,
|
|
1459
|
+
aborted: false,
|
|
1460
|
+
willRetry: false,
|
|
1461
|
+
});
|
|
1462
1462
|
return;
|
|
1463
1463
|
}
|
|
1464
|
+
const { apiKey, headers } = authResult;
|
|
1464
1465
|
const pathEntries = this.sessionManager.getBranch();
|
|
1465
1466
|
const preparation = prepareCompaction(pathEntries, settings);
|
|
1466
1467
|
if (!preparation) {
|
|
1467
|
-
this._emit({
|
|
1468
|
+
this._emit({
|
|
1469
|
+
type: "compaction_end",
|
|
1470
|
+
reason,
|
|
1471
|
+
result: undefined,
|
|
1472
|
+
aborted: false,
|
|
1473
|
+
willRetry: false,
|
|
1474
|
+
});
|
|
1468
1475
|
return;
|
|
1469
1476
|
}
|
|
1470
1477
|
let extensionCompaction;
|
|
@@ -1478,7 +1485,13 @@ export class AgentSession {
|
|
|
1478
1485
|
signal: this._autoCompactionAbortController.signal,
|
|
1479
1486
|
}));
|
|
1480
1487
|
if (extensionResult?.cancel) {
|
|
1481
|
-
this._emit({
|
|
1488
|
+
this._emit({
|
|
1489
|
+
type: "compaction_end",
|
|
1490
|
+
reason,
|
|
1491
|
+
result: undefined,
|
|
1492
|
+
aborted: true,
|
|
1493
|
+
willRetry: false,
|
|
1494
|
+
});
|
|
1482
1495
|
return;
|
|
1483
1496
|
}
|
|
1484
1497
|
if (extensionResult?.compaction) {
|
|
@@ -1499,20 +1512,26 @@ export class AgentSession {
|
|
|
1499
1512
|
}
|
|
1500
1513
|
else {
|
|
1501
1514
|
// Generate compaction result
|
|
1502
|
-
const compactResult = await compact(preparation, this.model, apiKey, undefined, this._autoCompactionAbortController.signal);
|
|
1515
|
+
const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal);
|
|
1503
1516
|
summary = compactResult.summary;
|
|
1504
1517
|
firstKeptEntryId = compactResult.firstKeptEntryId;
|
|
1505
1518
|
tokensBefore = compactResult.tokensBefore;
|
|
1506
1519
|
details = compactResult.details;
|
|
1507
1520
|
}
|
|
1508
1521
|
if (this._autoCompactionAbortController.signal.aborted) {
|
|
1509
|
-
this._emit({
|
|
1522
|
+
this._emit({
|
|
1523
|
+
type: "compaction_end",
|
|
1524
|
+
reason,
|
|
1525
|
+
result: undefined,
|
|
1526
|
+
aborted: true,
|
|
1527
|
+
willRetry: false,
|
|
1528
|
+
});
|
|
1510
1529
|
return;
|
|
1511
1530
|
}
|
|
1512
1531
|
this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
|
|
1513
1532
|
const newEntries = this.sessionManager.getEntries();
|
|
1514
1533
|
const sessionContext = this.sessionManager.buildSessionContext();
|
|
1515
|
-
this.agent.
|
|
1534
|
+
this.agent.state.messages = sessionContext.messages;
|
|
1516
1535
|
// Get the saved compaction entry for the extension event
|
|
1517
1536
|
const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
|
|
1518
1537
|
if (this._extensionRunner && savedCompactionEntry) {
|
|
@@ -1528,12 +1547,12 @@ export class AgentSession {
|
|
|
1528
1547
|
tokensBefore,
|
|
1529
1548
|
details,
|
|
1530
1549
|
};
|
|
1531
|
-
this._emit({ type: "
|
|
1550
|
+
this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
|
|
1532
1551
|
if (willRetry) {
|
|
1533
1552
|
const messages = this.agent.state.messages;
|
|
1534
1553
|
const lastMsg = messages[messages.length - 1];
|
|
1535
1554
|
if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
|
|
1536
|
-
this.agent.
|
|
1555
|
+
this.agent.state.messages = messages.slice(0, -1);
|
|
1537
1556
|
}
|
|
1538
1557
|
setTimeout(() => {
|
|
1539
1558
|
this.agent.continue().catch(() => { });
|
|
@@ -1550,7 +1569,8 @@ export class AgentSession {
|
|
|
1550
1569
|
catch (error) {
|
|
1551
1570
|
const errorMessage = error instanceof Error ? error.message : "compaction failed";
|
|
1552
1571
|
this._emit({
|
|
1553
|
-
type: "
|
|
1572
|
+
type: "compaction_end",
|
|
1573
|
+
reason,
|
|
1554
1574
|
result: undefined,
|
|
1555
1575
|
aborted: false,
|
|
1556
1576
|
willRetry: false,
|
|
@@ -1588,8 +1608,8 @@ export class AgentSession {
|
|
|
1588
1608
|
}
|
|
1589
1609
|
if (this._extensionRunner) {
|
|
1590
1610
|
this._applyExtensionBindings(this._extensionRunner);
|
|
1591
|
-
await this._extensionRunner.emit(
|
|
1592
|
-
await this.extendResourcesFromExtensions("startup");
|
|
1611
|
+
await this._extensionRunner.emit(this._sessionStartEvent);
|
|
1612
|
+
await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
|
|
1593
1613
|
}
|
|
1594
1614
|
}
|
|
1595
1615
|
async extendResourcesFromExtensions(reason) {
|
|
@@ -1607,7 +1627,7 @@ export class AgentSession {
|
|
|
1607
1627
|
};
|
|
1608
1628
|
this._resourceLoader.extendResources(extensionPaths);
|
|
1609
1629
|
this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
|
|
1610
|
-
this.agent.
|
|
1630
|
+
this.agent.state.systemPrompt = this._baseSystemPrompt;
|
|
1611
1631
|
}
|
|
1612
1632
|
buildExtensionResourcePaths(entries) {
|
|
1613
1633
|
return entries.map((entry) => {
|
|
@@ -1649,7 +1669,7 @@ export class AgentSession {
|
|
|
1649
1669
|
if (!refreshedModel || refreshedModel === currentModel) {
|
|
1650
1670
|
return;
|
|
1651
1671
|
}
|
|
1652
|
-
this.agent.
|
|
1672
|
+
this.agent.state.model = refreshedModel;
|
|
1653
1673
|
}
|
|
1654
1674
|
_bindExtensionCore(runner) {
|
|
1655
1675
|
const getCommands = () => {
|
|
@@ -1710,8 +1730,7 @@ export class AgentSession {
|
|
|
1710
1730
|
refreshTools: () => this._refreshToolRegistry(),
|
|
1711
1731
|
getCommands,
|
|
1712
1732
|
setModel: async (model) => {
|
|
1713
|
-
|
|
1714
|
-
if (!key)
|
|
1733
|
+
if (!this.modelRegistry.hasConfiguredAuth(model))
|
|
1715
1734
|
return false;
|
|
1716
1735
|
await this.setModel(model);
|
|
1717
1736
|
return true;
|
|
@@ -1721,6 +1740,7 @@ export class AgentSession {
|
|
|
1721
1740
|
}, {
|
|
1722
1741
|
getModel: () => this.model,
|
|
1723
1742
|
isIdle: () => !this.isStreaming,
|
|
1743
|
+
getSignal: () => this.agent.signal,
|
|
1724
1744
|
abort: () => this.abort(),
|
|
1725
1745
|
hasPendingMessages: () => this.pendingMessageCount > 0,
|
|
1726
1746
|
shutdown: () => {
|
|
@@ -1860,7 +1880,7 @@ export class AgentSession {
|
|
|
1860
1880
|
async reload() {
|
|
1861
1881
|
const previousFlagValues = this._extensionRunner?.getFlagValues();
|
|
1862
1882
|
await this._extensionRunner?.emit({ type: "session_shutdown" });
|
|
1863
|
-
this.settingsManager.reload();
|
|
1883
|
+
await this.settingsManager.reload();
|
|
1864
1884
|
resetApiProviders();
|
|
1865
1885
|
await this._resourceLoader.reload();
|
|
1866
1886
|
this._buildRuntime({
|
|
@@ -1873,7 +1893,7 @@ export class AgentSession {
|
|
|
1873
1893
|
this._extensionShutdownHandler ||
|
|
1874
1894
|
this._extensionErrorListener;
|
|
1875
1895
|
if (this._extensionRunner && hasBindings) {
|
|
1876
|
-
await this._extensionRunner.emit({ type: "session_start" });
|
|
1896
|
+
await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
|
|
1877
1897
|
await this.extendResourcesFromExtensions("reload");
|
|
1878
1898
|
}
|
|
1879
1899
|
}
|
|
@@ -1892,8 +1912,8 @@ export class AgentSession {
|
|
|
1892
1912
|
if (isContextOverflow(message, contextWindow))
|
|
1893
1913
|
return false;
|
|
1894
1914
|
const err = message.errorMessage;
|
|
1895
|
-
// Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors, fetch failed, terminated, retry delay exceeded
|
|
1896
|
-
return /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|timed? out|timeout|terminated|retry delay/i.test(err);
|
|
1915
|
+
// Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors, fetch failed, request ended without sending chunks, terminated, retry delay exceeded
|
|
1916
|
+
return /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|timed? out|timeout|terminated|retry delay/i.test(err);
|
|
1897
1917
|
}
|
|
1898
1918
|
/**
|
|
1899
1919
|
* Handle retryable errors with exponential backoff.
|
|
@@ -1936,7 +1956,7 @@ export class AgentSession {
|
|
|
1936
1956
|
// Remove error message from agent state (keep in session for history)
|
|
1937
1957
|
const messages = this.agent.state.messages;
|
|
1938
1958
|
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
1939
|
-
this.agent.
|
|
1959
|
+
this.agent.state.messages = messages.slice(0, -1);
|
|
1940
1960
|
}
|
|
1941
1961
|
// Wait with exponential backoff (abortable)
|
|
1942
1962
|
this._retryAbortController = new AbortController();
|
|
@@ -1979,9 +1999,11 @@ export class AgentSession {
|
|
|
1979
1999
|
* Returns immediately if no retry is in progress.
|
|
1980
2000
|
*/
|
|
1981
2001
|
async waitForRetry() {
|
|
1982
|
-
if (this._retryPromise) {
|
|
1983
|
-
|
|
2002
|
+
if (!this._retryPromise) {
|
|
2003
|
+
return;
|
|
1984
2004
|
}
|
|
2005
|
+
await this._retryPromise;
|
|
2006
|
+
await this.agent.waitForIdle();
|
|
1985
2007
|
}
|
|
1986
2008
|
/** Whether auto-retry is currently in progress */
|
|
1987
2009
|
get isRetrying() {
|
|
@@ -2014,15 +2036,10 @@ export class AgentSession {
|
|
|
2014
2036
|
const prefix = this.settingsManager.getShellCommandPrefix();
|
|
2015
2037
|
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
|
|
2016
2038
|
try {
|
|
2017
|
-
const result = options?.operations
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
})
|
|
2022
|
-
: await executeBashCommand(resolvedCommand, {
|
|
2023
|
-
onChunk,
|
|
2024
|
-
signal: this._bashAbortController.signal,
|
|
2025
|
-
});
|
|
2039
|
+
const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations(), {
|
|
2040
|
+
onChunk,
|
|
2041
|
+
signal: this._bashAbortController.signal,
|
|
2042
|
+
});
|
|
2026
2043
|
this.recordBashResult(command, result, options);
|
|
2027
2044
|
return result;
|
|
2028
2045
|
}
|
|
@@ -2053,7 +2070,7 @@ export class AgentSession {
|
|
|
2053
2070
|
}
|
|
2054
2071
|
else {
|
|
2055
2072
|
// Add to agent state immediately
|
|
2056
|
-
this.agent.
|
|
2073
|
+
this.agent.state.messages.push(bashMessage);
|
|
2057
2074
|
// Save to session
|
|
2058
2075
|
this.sessionManager.appendMessage(bashMessage);
|
|
2059
2076
|
}
|
|
@@ -2081,7 +2098,7 @@ export class AgentSession {
|
|
|
2081
2098
|
return;
|
|
2082
2099
|
for (const bashMessage of this._pendingBashMessages) {
|
|
2083
2100
|
// Add to agent state
|
|
2084
|
-
this.agent.
|
|
2101
|
+
this.agent.state.messages.push(bashMessage);
|
|
2085
2102
|
// Save to session
|
|
2086
2103
|
this.sessionManager.appendMessage(bashMessage);
|
|
2087
2104
|
}
|
|
@@ -2090,130 +2107,12 @@ export class AgentSession {
|
|
|
2090
2107
|
// =========================================================================
|
|
2091
2108
|
// Session Management
|
|
2092
2109
|
// =========================================================================
|
|
2093
|
-
/**
|
|
2094
|
-
* Switch to a different session file.
|
|
2095
|
-
* Aborts current operation, loads messages, restores model/thinking.
|
|
2096
|
-
* Listeners are preserved and will continue receiving events.
|
|
2097
|
-
* @returns true if switch completed, false if cancelled by extension
|
|
2098
|
-
*/
|
|
2099
|
-
async switchSession(sessionPath) {
|
|
2100
|
-
const previousSessionFile = this.sessionManager.getSessionFile();
|
|
2101
|
-
// Emit session_before_switch event (can be cancelled)
|
|
2102
|
-
if (this._extensionRunner?.hasHandlers("session_before_switch")) {
|
|
2103
|
-
const result = (await this._extensionRunner.emit({
|
|
2104
|
-
type: "session_before_switch",
|
|
2105
|
-
reason: "resume",
|
|
2106
|
-
targetSessionFile: sessionPath,
|
|
2107
|
-
}));
|
|
2108
|
-
if (result?.cancel) {
|
|
2109
|
-
return false;
|
|
2110
|
-
}
|
|
2111
|
-
}
|
|
2112
|
-
this._disconnectFromAgent();
|
|
2113
|
-
await this.abort();
|
|
2114
|
-
this._steeringMessages = [];
|
|
2115
|
-
this._followUpMessages = [];
|
|
2116
|
-
this._pendingNextTurnMessages = [];
|
|
2117
|
-
// Set new session
|
|
2118
|
-
this.sessionManager.setSessionFile(sessionPath);
|
|
2119
|
-
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
2120
|
-
// Reload messages
|
|
2121
|
-
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2122
|
-
// Emit session_switch event to extensions
|
|
2123
|
-
if (this._extensionRunner) {
|
|
2124
|
-
await this._extensionRunner.emit({
|
|
2125
|
-
type: "session_switch",
|
|
2126
|
-
reason: "resume",
|
|
2127
|
-
previousSessionFile,
|
|
2128
|
-
});
|
|
2129
|
-
}
|
|
2130
|
-
// Emit session event to custom tools
|
|
2131
|
-
this.agent.replaceMessages(sessionContext.messages);
|
|
2132
|
-
// Restore model if saved
|
|
2133
|
-
if (sessionContext.model) {
|
|
2134
|
-
const previousModel = this.model;
|
|
2135
|
-
const availableModels = await this._modelRegistry.getAvailable();
|
|
2136
|
-
const match = availableModels.find((m) => m.provider === sessionContext.model.provider && m.id === sessionContext.model.modelId);
|
|
2137
|
-
if (match) {
|
|
2138
|
-
this.agent.setModel(match);
|
|
2139
|
-
await this._emitModelSelect(match, previousModel, "restore");
|
|
2140
|
-
}
|
|
2141
|
-
}
|
|
2142
|
-
const hasThinkingEntry = this.sessionManager.getBranch().some((entry) => entry.type === "thinking_level_change");
|
|
2143
|
-
const defaultThinkingLevel = this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
|
|
2144
|
-
if (hasThinkingEntry) {
|
|
2145
|
-
// Restore thinking level if saved (setThinkingLevel clamps to model capabilities)
|
|
2146
|
-
this.setThinkingLevel(sessionContext.thinkingLevel);
|
|
2147
|
-
}
|
|
2148
|
-
else {
|
|
2149
|
-
const availableLevels = this.getAvailableThinkingLevels();
|
|
2150
|
-
const effectiveLevel = availableLevels.includes(defaultThinkingLevel)
|
|
2151
|
-
? defaultThinkingLevel
|
|
2152
|
-
: this._clampThinkingLevel(defaultThinkingLevel, availableLevels);
|
|
2153
|
-
this.agent.setThinkingLevel(effectiveLevel);
|
|
2154
|
-
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
2155
|
-
}
|
|
2156
|
-
this._reconnectToAgent();
|
|
2157
|
-
return true;
|
|
2158
|
-
}
|
|
2159
2110
|
/**
|
|
2160
2111
|
* Set a display name for the current session.
|
|
2161
2112
|
*/
|
|
2162
2113
|
setSessionName(name) {
|
|
2163
2114
|
this.sessionManager.appendSessionInfo(name);
|
|
2164
2115
|
}
|
|
2165
|
-
/**
|
|
2166
|
-
* Create a fork from a specific entry.
|
|
2167
|
-
* Emits before_fork/fork session events to extensions.
|
|
2168
|
-
*
|
|
2169
|
-
* @param entryId ID of the entry to fork from
|
|
2170
|
-
* @returns Object with:
|
|
2171
|
-
* - selectedText: The text of the selected user message (for editor pre-fill)
|
|
2172
|
-
* - cancelled: True if an extension cancelled the fork
|
|
2173
|
-
*/
|
|
2174
|
-
async fork(entryId) {
|
|
2175
|
-
const previousSessionFile = this.sessionFile;
|
|
2176
|
-
const selectedEntry = this.sessionManager.getEntry(entryId);
|
|
2177
|
-
if (!selectedEntry || selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
|
|
2178
|
-
throw new Error("Invalid entry ID for forking");
|
|
2179
|
-
}
|
|
2180
|
-
const selectedText = this._extractUserMessageText(selectedEntry.message.content);
|
|
2181
|
-
let skipConversationRestore = false;
|
|
2182
|
-
// Emit session_before_fork event (can be cancelled)
|
|
2183
|
-
if (this._extensionRunner?.hasHandlers("session_before_fork")) {
|
|
2184
|
-
const result = (await this._extensionRunner.emit({
|
|
2185
|
-
type: "session_before_fork",
|
|
2186
|
-
entryId,
|
|
2187
|
-
}));
|
|
2188
|
-
if (result?.cancel) {
|
|
2189
|
-
return { selectedText, cancelled: true };
|
|
2190
|
-
}
|
|
2191
|
-
skipConversationRestore = result?.skipConversationRestore ?? false;
|
|
2192
|
-
}
|
|
2193
|
-
// Clear pending messages (bound to old session state)
|
|
2194
|
-
this._pendingNextTurnMessages = [];
|
|
2195
|
-
if (!selectedEntry.parentId) {
|
|
2196
|
-
this.sessionManager.newSession({ parentSession: previousSessionFile });
|
|
2197
|
-
}
|
|
2198
|
-
else {
|
|
2199
|
-
this.sessionManager.createBranchedSession(selectedEntry.parentId);
|
|
2200
|
-
}
|
|
2201
|
-
this.agent.sessionId = this.sessionManager.getSessionId();
|
|
2202
|
-
// Reload messages from entries (works for both file and in-memory mode)
|
|
2203
|
-
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2204
|
-
// Emit session_fork event to extensions (after fork completes)
|
|
2205
|
-
if (this._extensionRunner) {
|
|
2206
|
-
await this._extensionRunner.emit({
|
|
2207
|
-
type: "session_fork",
|
|
2208
|
-
previousSessionFile,
|
|
2209
|
-
});
|
|
2210
|
-
}
|
|
2211
|
-
// Emit session event to custom tools (with reason "fork")
|
|
2212
|
-
if (!skipConversationRestore) {
|
|
2213
|
-
this.agent.replaceMessages(sessionContext.messages);
|
|
2214
|
-
}
|
|
2215
|
-
return { selectedText, cancelled: false };
|
|
2216
|
-
}
|
|
2217
2116
|
// =========================================================================
|
|
2218
2117
|
// Tree Navigation
|
|
2219
2118
|
// =========================================================================
|
|
@@ -2292,14 +2191,12 @@ export class AgentSession {
|
|
|
2292
2191
|
let summaryDetails;
|
|
2293
2192
|
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
2294
2193
|
const model = this.model;
|
|
2295
|
-
const apiKey = await this.
|
|
2296
|
-
if (!apiKey) {
|
|
2297
|
-
throw new Error(`No API key for ${model.provider}`);
|
|
2298
|
-
}
|
|
2194
|
+
const { apiKey, headers } = await this._getRequiredRequestAuth(model);
|
|
2299
2195
|
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
2300
2196
|
const result = await generateBranchSummary(entriesToSummarize, {
|
|
2301
2197
|
model,
|
|
2302
2198
|
apiKey,
|
|
2199
|
+
headers,
|
|
2303
2200
|
signal: this._branchSummaryAbortController.signal,
|
|
2304
2201
|
customInstructions,
|
|
2305
2202
|
replaceInstructions,
|
|
@@ -2371,7 +2268,7 @@ export class AgentSession {
|
|
|
2371
2268
|
}
|
|
2372
2269
|
// Update agent state
|
|
2373
2270
|
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2374
|
-
this.agent.
|
|
2271
|
+
this.agent.state.messages = sessionContext.messages;
|
|
2375
2272
|
// Emit session_tree event
|
|
2376
2273
|
if (this._extensionRunner) {
|
|
2377
2274
|
await this._extensionRunner.emit({
|
|
@@ -2511,6 +2408,7 @@ export class AgentSession {
|
|
|
2511
2408
|
const toolRenderer = createToolHtmlRenderer({
|
|
2512
2409
|
getToolDefinition: (name) => this.getToolDefinition(name),
|
|
2513
2410
|
theme,
|
|
2411
|
+
cwd: this.sessionManager.getCwd(),
|
|
2514
2412
|
});
|
|
2515
2413
|
return await exportSessionToHtml(this.sessionManager, this.state, {
|
|
2516
2414
|
outputPath,
|
|
@@ -2549,29 +2447,6 @@ export class AgentSession {
|
|
|
2549
2447
|
writeFileSync(filePath, `${lines.join("\n")}\n`);
|
|
2550
2448
|
return filePath;
|
|
2551
2449
|
}
|
|
2552
|
-
/**
|
|
2553
|
-
* Import a JSONL session file.
|
|
2554
|
-
* Copies the file into the session directory and switches to it (like /resume).
|
|
2555
|
-
* @param inputPath Path to the JSONL file to import.
|
|
2556
|
-
* @returns true if the session was switched successfully.
|
|
2557
|
-
*/
|
|
2558
|
-
async importFromJsonl(inputPath) {
|
|
2559
|
-
const resolved = resolve(inputPath);
|
|
2560
|
-
if (!existsSync(resolved)) {
|
|
2561
|
-
throw new Error(`File not found: ${resolved}`);
|
|
2562
|
-
}
|
|
2563
|
-
// Copy into the session directory so we don't modify the original
|
|
2564
|
-
const sessionDir = this.sessionManager.getSessionDir();
|
|
2565
|
-
if (!existsSync(sessionDir)) {
|
|
2566
|
-
mkdirSync(sessionDir, { recursive: true });
|
|
2567
|
-
}
|
|
2568
|
-
const destPath = join(sessionDir, basename(resolved));
|
|
2569
|
-
// Avoid overwriting if source and destination are the same file
|
|
2570
|
-
if (resolve(destPath) !== resolved) {
|
|
2571
|
-
copyFileSync(resolved, destPath);
|
|
2572
|
-
}
|
|
2573
|
-
return this.switchSession(destPath);
|
|
2574
|
-
}
|
|
2575
2450
|
// =========================================================================
|
|
2576
2451
|
// Utilities
|
|
2577
2452
|
// =========================================================================
|