@dyyz1993/pi-coding-agent 0.70.6 → 0.74.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +266 -80
- package/README.md +48 -20
- package/dist/bun/cli.d.ts.map +1 -1
- package/dist/bun/cli.js +4 -2
- package/dist/bun/cli.js.map +1 -1
- package/dist/bun/restore-sandbox-env.d.ts +13 -0
- package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
- package/dist/bun/restore-sandbox-env.js +32 -0
- package/dist/bun/restore-sandbox-env.js.map +1 -0
- package/dist/cli/args.d.ts +2 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +34 -22
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/list-models.d.ts.map +1 -1
- package/dist/cli/list-models.js +2 -1
- package/dist/cli/list-models.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +9 -4
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +16 -8
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +238 -66
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +10 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +14 -0
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +2 -1
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +1 -0
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +37 -26
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1068 -1116
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-guidance.d.ts +5 -0
- package/dist/core/auth-guidance.d.ts.map +1 -0
- package/dist/core/auth-guidance.js +21 -0
- package/dist/core/auth-guidance.js.map +1 -0
- package/dist/core/auth-storage.d.ts +9 -0
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +20 -1
- 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 +9 -6
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +0 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
- package/dist/core/export-html/ansi-to-html.js +1 -1
- package/dist/core/export-html/ansi-to-html.js.map +1 -1
- package/dist/core/export-html/template.css +53 -4
- package/dist/core/export-html/template.js +84 -20
- package/dist/core/export-html/tool-renderer.d.ts +0 -6
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +15 -2
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts +0 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +49 -137
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +24 -20
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +128 -253
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +88 -60
- 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/file-store/file-snapshot-manager.d.ts +95 -0
- package/dist/core/file-store/file-snapshot-manager.d.ts.map +1 -0
- package/dist/core/file-store/file-snapshot-manager.js +508 -0
- package/dist/core/file-store/file-snapshot-manager.js.map +1 -0
- package/dist/core/file-store/index.d.ts +5 -0
- package/dist/core/file-store/index.d.ts.map +1 -0
- package/dist/core/file-store/index.js +3 -0
- package/dist/core/file-store/index.js.map +1 -0
- package/dist/core/messages.d.ts +10 -2
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +23 -6
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-registry.d.ts +19 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +97 -16
- 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 +24 -15
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/package-manager.d.ts +1 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +61 -35
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/provider-display-names.d.ts +2 -0
- package/dist/core/provider-display-names.d.ts.map +1 -0
- package/dist/core/provider-display-names.js +32 -0
- package/dist/core/provider-display-names.js.map +1 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +9 -21
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +9 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +39 -18
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +27 -17
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +133 -47
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +22 -3
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +54 -6
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +3 -8
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +4 -3
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/tools/bash.d.ts +0 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +155 -110
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +3 -2
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +4 -3
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +1 -1
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +50 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -0
- package/dist/core/tools/output-accumulator.js +178 -0
- package/dist/core/tools/output-accumulator.js.map +1 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +70 -13
- package/dist/core/tools/read.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +17 -39
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +3 -3
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +3 -1
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +1 -4
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +14 -56
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +5 -1
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +19 -4
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +1 -1
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +18 -6
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +93 -25
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +3 -7
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +5 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +53 -1
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +20 -4
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +423 -186
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +1 -1
- package/dist/modes/interactive/theme/light.json +1 -1
- package/dist/modes/print-mode.d.ts +3 -0
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +62 -19
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +80 -60
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +108 -93
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +106 -0
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +115 -0
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +238 -12
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/child-process.d.ts +1 -0
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +8 -0
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +2 -2
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +84 -45
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/paths.d.ts +9 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +31 -0
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/pi-user-agent.d.ts +2 -0
- package/dist/utils/pi-user-agent.d.ts.map +1 -0
- package/dist/utils/pi-user-agent.js +5 -0
- package/dist/utils/pi-user-agent.js.map +1 -0
- package/dist/utils/structured-output.d.ts +10 -0
- package/dist/utils/structured-output.d.ts.map +1 -0
- package/dist/utils/structured-output.js +57 -0
- package/dist/utils/structured-output.js.map +1 -0
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +6 -2
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/version-check.d.ts +14 -0
- package/dist/utils/version-check.d.ts.map +1 -0
- package/dist/utils/version-check.js +77 -0
- package/dist/utils/version-check.js.map +1 -0
- package/docs/compaction.md +14 -14
- package/docs/custom-provider.md +40 -31
- package/docs/development.md +1 -1
- package/docs/docs.json +148 -0
- package/docs/extensions.md +116 -56
- package/docs/index.md +70 -0
- package/docs/json.md +4 -4
- package/docs/models.md +150 -3
- package/docs/packages.md +10 -5
- package/docs/providers.md +62 -17
- package/docs/quickstart.md +142 -0
- package/docs/rollback-architecture.md +693 -0
- package/docs/rollback-test-cases.md +412 -0
- package/docs/rpc.md +1 -1
- package/docs/sdk.md +26 -26
- package/docs/{session.md → session-format.md} +6 -6
- package/docs/sessions.md +137 -0
- package/docs/settings.md +52 -9
- package/docs/termux.md +1 -1
- package/docs/themes.md +2 -2
- package/docs/tui.md +20 -20
- package/docs/usage.md +277 -0
- package/examples/extensions/README.md +2 -4
- package/examples/extensions/border-status-editor.ts +150 -0
- package/examples/extensions/commands.ts +2 -2
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/dynamic-resources/dynamic.json +1 -1
- package/examples/extensions/git-checkpoint.ts +1 -1
- package/examples/extensions/handoff.ts +49 -11
- package/examples/extensions/plan-mode/index.ts +1 -1
- package/examples/extensions/sandbox/package-lock.json +5 -5
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/subagent/agents.ts +126 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/README.md +2 -2
- package/package.json +7 -16
- package/docs/tree.md +0 -233
- package/examples/extensions/antigravity-image-gen.ts +0 -418
|
@@ -16,21 +16,24 @@ import { randomUUID } from "node:crypto";
|
|
|
16
16
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
17
17
|
import { basename, dirname, join, resolve } from "node:path";
|
|
18
18
|
import { Agent, } from "@dyyz1993/pi-agent-core";
|
|
19
|
-
import { complete, isContextOverflow, modelsAreEqual, resetApiProviders,
|
|
19
|
+
import { clampThinkingLevel, cleanupSessionResources, complete, getSupportedThinkingLevels, isContextOverflow, modelsAreEqual, resetApiProviders, } from "@dyyz1993/pi-ai";
|
|
20
20
|
import { Compile } from "typebox/compile";
|
|
21
21
|
import { Value } from "typebox/value";
|
|
22
|
-
import {
|
|
22
|
+
import { getAgentDir } from "../config.js";
|
|
23
23
|
import { theme } from "../modes/interactive/theme/theme.js";
|
|
24
24
|
import { stripFrontmatter } from "../utils/frontmatter.js";
|
|
25
25
|
import { sleep } from "../utils/sleep.js";
|
|
26
|
+
import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
|
|
26
27
|
import { executeBashWithOperations } from "./bash-executor.js";
|
|
27
|
-
import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens,
|
|
28
|
+
import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
|
|
28
29
|
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
|
|
29
30
|
import { exportSessionToHtml } from "./export-html/index.js";
|
|
30
31
|
import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
|
|
31
32
|
import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
|
|
32
33
|
import { emitSessionShutdownEvent } from "./extensions/runner.js";
|
|
33
|
-
import {
|
|
34
|
+
import { FileSnapshotManager } from "./file-store/file-snapshot-manager.js";
|
|
35
|
+
import { InternalGit } from "./file-store/internal-git.js";
|
|
36
|
+
import { McpManager } from "./mcp/mcp-manager.js";
|
|
34
37
|
import { resolveModelAlias } from "./model-resolver.js";
|
|
35
38
|
import { expandPromptTemplate } from "./prompt-templates.js";
|
|
36
39
|
import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
|
|
@@ -60,8 +63,6 @@ export function parseSkillBlock(text) {
|
|
|
60
63
|
// ============================================================================
|
|
61
64
|
/** Standard thinking levels */
|
|
62
65
|
const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
|
|
63
|
-
/** Thinking levels including xhigh (for supported models) */
|
|
64
|
-
const THINKING_LEVELS_WITH_XHIGH = ["off", "minimal", "low", "medium", "high", "xhigh"];
|
|
65
66
|
// ============================================================================
|
|
66
67
|
// AgentSession Class
|
|
67
68
|
// ============================================================================
|
|
@@ -97,7 +98,6 @@ export class AgentSession {
|
|
|
97
98
|
// Extension system
|
|
98
99
|
_extensionRunner;
|
|
99
100
|
_turnIndex = 0;
|
|
100
|
-
_toolCallVariables;
|
|
101
101
|
_resourceLoader;
|
|
102
102
|
_customTools;
|
|
103
103
|
_baseToolDefinitions = new Map();
|
|
@@ -117,6 +117,8 @@ export class AgentSession {
|
|
|
117
117
|
_backgroundTasks = new Set();
|
|
118
118
|
// Model registry for API key resolution
|
|
119
119
|
_modelRegistry;
|
|
120
|
+
_fileSnapshotManager = null;
|
|
121
|
+
_mcpManager;
|
|
120
122
|
_tierModels = {};
|
|
121
123
|
// Tool registry for extension getTools/setTools
|
|
122
124
|
_toolRegistry = new Map();
|
|
@@ -153,9 +155,50 @@ export class AgentSession {
|
|
|
153
155
|
get modelRegistry() {
|
|
154
156
|
return this._modelRegistry;
|
|
155
157
|
}
|
|
158
|
+
get fileSnapshotManager() {
|
|
159
|
+
return this._fileSnapshotManager;
|
|
160
|
+
}
|
|
161
|
+
_initFileSnapshotManager() {
|
|
162
|
+
try {
|
|
163
|
+
const storeRoot = join(getAgentDir(), "file-store");
|
|
164
|
+
const cwd = this._cwd;
|
|
165
|
+
const git = InternalGit.createForProject(storeRoot, cwd);
|
|
166
|
+
this._fileSnapshotManager = new FileSnapshotManager(git);
|
|
167
|
+
this._extensionRunner.setFileSnapshotManager(this._fileSnapshotManager);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
this._fileSnapshotManager = null;
|
|
171
|
+
this._extensionRunner.setFileSnapshotManager(null);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
_initMcpServers() {
|
|
175
|
+
const settings = this.settingsManager.getMergedSettings();
|
|
176
|
+
const servers = settings?.mcp?.servers;
|
|
177
|
+
if (!servers || Object.keys(servers).length === 0)
|
|
178
|
+
return;
|
|
179
|
+
this._mcpManager = new McpManager({
|
|
180
|
+
onConnectionChange: (conn) => {
|
|
181
|
+
this._emit({
|
|
182
|
+
type: "mcp_connection_change",
|
|
183
|
+
name: conn.name,
|
|
184
|
+
status: conn.status,
|
|
185
|
+
error: conn.error,
|
|
186
|
+
tools: conn.tools.map((t) => ({
|
|
187
|
+
originalName: t.originalName,
|
|
188
|
+
fullName: t.fullName,
|
|
189
|
+
description: t.description,
|
|
190
|
+
})),
|
|
191
|
+
});
|
|
192
|
+
},
|
|
193
|
+
});
|
|
194
|
+
this._mcpManager.connectAll(servers).catch(() => { });
|
|
195
|
+
}
|
|
156
196
|
async _getRequiredRequestAuth(model) {
|
|
157
197
|
const result = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
158
198
|
if (!result.ok) {
|
|
199
|
+
if (result.error.startsWith("No API key found")) {
|
|
200
|
+
throw new Error(formatNoApiKeyFoundMessage(model.provider));
|
|
201
|
+
}
|
|
159
202
|
throw new Error(result.error);
|
|
160
203
|
}
|
|
161
204
|
if (result.apiKey) {
|
|
@@ -167,8 +210,7 @@ export class AgentSession {
|
|
|
167
210
|
`Credentials may have expired or network is unavailable. ` +
|
|
168
211
|
`Run '/login ${model.provider}' to re-authenticate.`);
|
|
169
212
|
}
|
|
170
|
-
throw new Error(
|
|
171
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
|
|
213
|
+
throw new Error(formatNoApiKeyFoundMessage(model.provider));
|
|
172
214
|
}
|
|
173
215
|
/**
|
|
174
216
|
* Install tool hooks once on the Agent instance.
|
|
@@ -191,7 +233,6 @@ export class AgentSession {
|
|
|
191
233
|
toolName: toolCall.name,
|
|
192
234
|
toolCallId: toolCall.id,
|
|
193
235
|
input: args,
|
|
194
|
-
variables: this._toolCallVariables,
|
|
195
236
|
});
|
|
196
237
|
}
|
|
197
238
|
catch (err) {
|
|
@@ -303,21 +344,24 @@ export class AgentSession {
|
|
|
303
344
|
}
|
|
304
345
|
}
|
|
305
346
|
}
|
|
306
|
-
//
|
|
307
|
-
|
|
347
|
+
// Emit to extensions first
|
|
348
|
+
await this._emitExtensionEvent(event);
|
|
349
|
+
// Notify all listeners
|
|
350
|
+
this._emit(event);
|
|
351
|
+
// Handle session persistence
|
|
308
352
|
if (event.type === "message_end") {
|
|
309
|
-
|
|
353
|
+
// Check if this is a custom message from extensions
|
|
310
354
|
if (event.message.role === "custom") {
|
|
311
|
-
|
|
355
|
+
// Persist as CustomMessageEntry
|
|
356
|
+
this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
|
|
312
357
|
}
|
|
313
358
|
else if (event.message.role === "user" ||
|
|
314
359
|
event.message.role === "assistant" ||
|
|
315
360
|
event.message.role === "toolResult") {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
if (entryId) {
|
|
319
|
-
event.entryId = entryId;
|
|
361
|
+
// Regular LLM message - persist as SessionMessageEntry
|
|
362
|
+
this.sessionManager.appendMessage(event.message);
|
|
320
363
|
}
|
|
364
|
+
// Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
|
|
321
365
|
// Track assistant message for auto-compaction (checked on agent_end)
|
|
322
366
|
if (event.message.role === "assistant") {
|
|
323
367
|
this._lastAssistantMessage = event.message;
|
|
@@ -337,10 +381,6 @@ export class AgentSession {
|
|
|
337
381
|
}
|
|
338
382
|
}
|
|
339
383
|
}
|
|
340
|
-
// Emit to extensions first
|
|
341
|
-
await this._emitExtensionEvent(event);
|
|
342
|
-
// Notify all listeners
|
|
343
|
-
this._emit(event);
|
|
344
384
|
// Check auto-retry and auto-compaction after agent completes
|
|
345
385
|
if (event.type === "agent_end" && this._lastAssistantMessage) {
|
|
346
386
|
const msg = this._lastAssistantMessage;
|
|
@@ -384,6 +424,20 @@ export class AgentSession {
|
|
|
384
424
|
}
|
|
385
425
|
return undefined;
|
|
386
426
|
}
|
|
427
|
+
_replaceMessageInPlace(target, replacement) {
|
|
428
|
+
// Agent-core stores the finalized message object in its state before emitting message_end.
|
|
429
|
+
// SessionManager persistence happens later in _processAgentEvent() with event.message.
|
|
430
|
+
// Mutating this object in place keeps agent state, later turn/agent events, listeners,
|
|
431
|
+
// and the eventual SessionManager.appendMessage(event.message) persistence in sync.
|
|
432
|
+
if (target === replacement) {
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const targetRecord = target;
|
|
436
|
+
for (const key of Object.keys(targetRecord)) {
|
|
437
|
+
delete targetRecord[key];
|
|
438
|
+
}
|
|
439
|
+
Object.assign(targetRecord, replacement);
|
|
440
|
+
}
|
|
387
441
|
/** Emit extension events based on agent events */
|
|
388
442
|
async _emitExtensionEvent(event) {
|
|
389
443
|
if (event.type === "agent_start") {
|
|
@@ -430,9 +484,11 @@ export class AgentSession {
|
|
|
430
484
|
const extensionEvent = {
|
|
431
485
|
type: "message_end",
|
|
432
486
|
message: event.message,
|
|
433
|
-
entryId: event.entryId,
|
|
434
487
|
};
|
|
435
|
-
await this._extensionRunner.
|
|
488
|
+
const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
|
|
489
|
+
if (replacement) {
|
|
490
|
+
this._replaceMessageInPlace(event.message, replacement);
|
|
491
|
+
}
|
|
436
492
|
}
|
|
437
493
|
else if (event.type === "tool_execution_start") {
|
|
438
494
|
const extensionEvent = {
|
|
@@ -504,15 +560,11 @@ export class AgentSession {
|
|
|
504
560
|
* Call this when completely done with the session.
|
|
505
561
|
*/
|
|
506
562
|
dispose() {
|
|
507
|
-
this._extensionRunner.invalidate("This extension
|
|
508
|
-
this.
|
|
509
|
-
for (const task of this._backgroundTasks) {
|
|
510
|
-
task.cancel();
|
|
511
|
-
}
|
|
512
|
-
void Promise.allSettled([...this._backgroundTasks].map((t) => t.promise));
|
|
513
|
-
this._backgroundTasks.clear();
|
|
563
|
+
this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().");
|
|
564
|
+
this._mcpManager?.dispose().catch(() => { });
|
|
514
565
|
this._disconnectFromAgent();
|
|
515
566
|
this._eventListeners = [];
|
|
567
|
+
cleanupSessionResources(this.sessionId);
|
|
516
568
|
}
|
|
517
569
|
// =========================================================================
|
|
518
570
|
// Read-only State Access
|
|
@@ -530,25 +582,16 @@ export class AgentSession {
|
|
|
530
582
|
}
|
|
531
583
|
setTierModels(mapping) {
|
|
532
584
|
this._tierModels = { ...mapping };
|
|
585
|
+
this.sessionManager.appendTierModelsChange(mapping);
|
|
533
586
|
}
|
|
534
587
|
/** Current thinking level */
|
|
535
588
|
get thinkingLevel() {
|
|
536
589
|
return this.agent.state.thinkingLevel;
|
|
537
590
|
}
|
|
538
|
-
set toolCallVariables(vars) {
|
|
539
|
-
this._toolCallVariables = vars;
|
|
540
|
-
}
|
|
541
|
-
get toolCallVariables() {
|
|
542
|
-
return this._toolCallVariables;
|
|
543
|
-
}
|
|
544
591
|
/** Whether agent is currently streaming a response */
|
|
545
592
|
get isStreaming() {
|
|
546
593
|
return this.agent.state.isStreaming;
|
|
547
594
|
}
|
|
548
|
-
/** Signal that aborts on session shutdown */
|
|
549
|
-
get sessionSignal() {
|
|
550
|
-
return this._sessionAbortController.signal;
|
|
551
|
-
}
|
|
552
595
|
/** Current effective system prompt (includes any per-turn extension modifications) */
|
|
553
596
|
get systemPrompt() {
|
|
554
597
|
return this.agent.state.systemPrompt;
|
|
@@ -746,12 +789,11 @@ export class AgentSession {
|
|
|
746
789
|
if (!options?.streamingBehavior) {
|
|
747
790
|
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
748
791
|
}
|
|
749
|
-
const { text: streamingText } = handleLargeInput(expandedText);
|
|
750
792
|
if (options.streamingBehavior === "followUp") {
|
|
751
|
-
await this._queueFollowUp(
|
|
793
|
+
await this._queueFollowUp(expandedText, currentImages);
|
|
752
794
|
}
|
|
753
795
|
else {
|
|
754
|
-
await this._queueSteer(
|
|
796
|
+
await this._queueSteer(expandedText, currentImages);
|
|
755
797
|
}
|
|
756
798
|
preflightResult?.(true);
|
|
757
799
|
return;
|
|
@@ -760,9 +802,7 @@ export class AgentSession {
|
|
|
760
802
|
this._flushPendingBashMessages();
|
|
761
803
|
// Validate model
|
|
762
804
|
if (!this.model) {
|
|
763
|
-
throw new Error(
|
|
764
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}\n\n` +
|
|
765
|
-
"Then use /model to select a model.");
|
|
805
|
+
throw new Error(formatNoModelSelectedMessage());
|
|
766
806
|
}
|
|
767
807
|
if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
|
|
768
808
|
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
@@ -771,8 +811,7 @@ export class AgentSession {
|
|
|
771
811
|
`Credentials may have expired or network is unavailable. ` +
|
|
772
812
|
`Run '/login ${this.model.provider}' to re-authenticate.`);
|
|
773
813
|
}
|
|
774
|
-
throw new Error(
|
|
775
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
|
|
814
|
+
throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
|
|
776
815
|
}
|
|
777
816
|
// Check if we need to compact before sending (catches aborted responses)
|
|
778
817
|
const lastAssistant = this._findLastAssistantMessage();
|
|
@@ -781,10 +820,8 @@ export class AgentSession {
|
|
|
781
820
|
}
|
|
782
821
|
// Build messages array (custom message if any, then user message)
|
|
783
822
|
messages = [];
|
|
784
|
-
// Handle large input: save to temp file and replace with preview
|
|
785
|
-
const { text: finalText } = handleLargeInput(expandedText);
|
|
786
823
|
// Add user message
|
|
787
|
-
const userContent = [{ type: "text", text:
|
|
824
|
+
const userContent = [{ type: "text", text: expandedText }];
|
|
788
825
|
if (currentImages) {
|
|
789
826
|
userContent.push(...currentImages);
|
|
790
827
|
}
|
|
@@ -845,7 +882,7 @@ export class AgentSession {
|
|
|
845
882
|
if (!command)
|
|
846
883
|
return false;
|
|
847
884
|
// Get command context from extension runner (includes session control methods)
|
|
848
|
-
const ctx = this._extensionRunner.createCommandContext(
|
|
885
|
+
const ctx = this._extensionRunner.createCommandContext();
|
|
849
886
|
try {
|
|
850
887
|
await command.handler(args, ctx);
|
|
851
888
|
return true;
|
|
@@ -899,13 +936,14 @@ export class AgentSession {
|
|
|
899
936
|
* @throws Error if text is an extension command
|
|
900
937
|
*/
|
|
901
938
|
async steer(text, images) {
|
|
939
|
+
// Check for extension commands (cannot be queued)
|
|
902
940
|
if (text.startsWith("/")) {
|
|
903
941
|
this._throwIfExtensionCommand(text);
|
|
904
942
|
}
|
|
943
|
+
// Expand skill commands and prompt templates
|
|
905
944
|
let expandedText = this._expandSkillCommand(text);
|
|
906
945
|
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
907
|
-
|
|
908
|
-
await this._queueSteer(finalText, images);
|
|
946
|
+
await this._queueSteer(expandedText, images);
|
|
909
947
|
}
|
|
910
948
|
/**
|
|
911
949
|
* Queue a follow-up message to be processed after the agent finishes.
|
|
@@ -915,13 +953,14 @@ export class AgentSession {
|
|
|
915
953
|
* @throws Error if text is an extension command
|
|
916
954
|
*/
|
|
917
955
|
async followUp(text, images) {
|
|
956
|
+
// Check for extension commands (cannot be queued)
|
|
918
957
|
if (text.startsWith("/")) {
|
|
919
958
|
this._throwIfExtensionCommand(text);
|
|
920
959
|
}
|
|
960
|
+
// Expand skill commands and prompt templates
|
|
921
961
|
let expandedText = this._expandSkillCommand(text);
|
|
922
962
|
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
923
|
-
|
|
924
|
-
await this._queueFollowUp(finalText, images);
|
|
963
|
+
await this._queueFollowUp(expandedText, images);
|
|
925
964
|
}
|
|
926
965
|
/**
|
|
927
966
|
* Internal: Queue a steering message (already expanded, no extension command check).
|
|
@@ -1074,6 +1113,10 @@ export class AgentSession {
|
|
|
1074
1113
|
get resourceLoader() {
|
|
1075
1114
|
return this._resourceLoader;
|
|
1076
1115
|
}
|
|
1116
|
+
/** Update the working directory for the session. */
|
|
1117
|
+
async setCwd(newCwd) {
|
|
1118
|
+
this._cwd = newCwd;
|
|
1119
|
+
}
|
|
1077
1120
|
/**
|
|
1078
1121
|
* Abort current operation and wait for agent to become idle.
|
|
1079
1122
|
*/
|
|
@@ -1181,13 +1224,20 @@ export class AgentSession {
|
|
|
1181
1224
|
const availableLevels = this.getAvailableThinkingLevels();
|
|
1182
1225
|
const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
|
|
1183
1226
|
// Only persist if actually changing
|
|
1184
|
-
const
|
|
1227
|
+
const previousLevel = this.agent.state.thinkingLevel;
|
|
1228
|
+
const isChanging = effectiveLevel !== previousLevel;
|
|
1185
1229
|
this.agent.state.thinkingLevel = effectiveLevel;
|
|
1186
1230
|
if (isChanging) {
|
|
1187
1231
|
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
1188
1232
|
if (this.supportsThinking() || effectiveLevel !== "off") {
|
|
1189
1233
|
this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
|
|
1190
1234
|
}
|
|
1235
|
+
this._emit({ type: "thinking_level_changed", level: effectiveLevel });
|
|
1236
|
+
void this._extensionRunner.emit({
|
|
1237
|
+
type: "thinking_level_select",
|
|
1238
|
+
level: effectiveLevel,
|
|
1239
|
+
previousLevel,
|
|
1240
|
+
});
|
|
1191
1241
|
}
|
|
1192
1242
|
}
|
|
1193
1243
|
/**
|
|
@@ -1209,15 +1259,9 @@ export class AgentSession {
|
|
|
1209
1259
|
* The provider will clamp to what the specific model supports internally.
|
|
1210
1260
|
*/
|
|
1211
1261
|
getAvailableThinkingLevels() {
|
|
1212
|
-
if (!this.
|
|
1213
|
-
return
|
|
1214
|
-
return this.
|
|
1215
|
-
}
|
|
1216
|
-
/**
|
|
1217
|
-
* Check if current model supports xhigh thinking level.
|
|
1218
|
-
*/
|
|
1219
|
-
supportsXhighThinking() {
|
|
1220
|
-
return this.model ? supportsXhigh(this.model) : false;
|
|
1262
|
+
if (!this.model)
|
|
1263
|
+
return THINKING_LEVELS;
|
|
1264
|
+
return getSupportedThinkingLevels(this.model);
|
|
1221
1265
|
}
|
|
1222
1266
|
/**
|
|
1223
1267
|
* Check if current model supports thinking/reasoning.
|
|
@@ -1234,24 +1278,8 @@ export class AgentSession {
|
|
|
1234
1278
|
}
|
|
1235
1279
|
return this.thinkingLevel;
|
|
1236
1280
|
}
|
|
1237
|
-
_clampThinkingLevel(level,
|
|
1238
|
-
|
|
1239
|
-
const available = new Set(availableLevels);
|
|
1240
|
-
const requestedIndex = ordered.indexOf(level);
|
|
1241
|
-
if (requestedIndex === -1) {
|
|
1242
|
-
return availableLevels[0] ?? "off";
|
|
1243
|
-
}
|
|
1244
|
-
for (let i = requestedIndex; i < ordered.length; i++) {
|
|
1245
|
-
const candidate = ordered[i];
|
|
1246
|
-
if (available.has(candidate))
|
|
1247
|
-
return candidate;
|
|
1248
|
-
}
|
|
1249
|
-
for (let i = requestedIndex - 1; i >= 0; i--) {
|
|
1250
|
-
const candidate = ordered[i];
|
|
1251
|
-
if (available.has(candidate))
|
|
1252
|
-
return candidate;
|
|
1253
|
-
}
|
|
1254
|
-
return availableLevels[0] ?? "off";
|
|
1281
|
+
_clampThinkingLevel(level, _availableLevels) {
|
|
1282
|
+
return this.model ? clampThinkingLevel(this.model, level) : "off";
|
|
1255
1283
|
}
|
|
1256
1284
|
// =========================================================================
|
|
1257
1285
|
// Queue Mode Management
|
|
@@ -1287,7 +1315,7 @@ export class AgentSession {
|
|
|
1287
1315
|
this._emit({ type: "compaction_start", reason: "manual" });
|
|
1288
1316
|
try {
|
|
1289
1317
|
if (!this.model) {
|
|
1290
|
-
throw new Error(
|
|
1318
|
+
throw new Error(formatNoModelSelectedMessage());
|
|
1291
1319
|
}
|
|
1292
1320
|
const { apiKey, headers } = await this._getRequiredRequestAuth(this.model);
|
|
1293
1321
|
const pathEntries = this.sessionManager.getBranch();
|
|
@@ -1597,11 +1625,6 @@ export class AgentSession {
|
|
|
1597
1625
|
tokensBefore,
|
|
1598
1626
|
details,
|
|
1599
1627
|
};
|
|
1600
|
-
let tokensAfter = 0;
|
|
1601
|
-
for (const msg of sessionContext.messages) {
|
|
1602
|
-
tokensAfter += estimateTokens(msg);
|
|
1603
|
-
}
|
|
1604
|
-
result.tokensAfter = tokensAfter;
|
|
1605
1628
|
this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
|
|
1606
1629
|
if (willRetry) {
|
|
1607
1630
|
const messages = this.agent.state.messages;
|
|
@@ -1663,13 +1686,10 @@ export class AgentSession {
|
|
|
1663
1686
|
}
|
|
1664
1687
|
if (bindings.registerChannel !== undefined) {
|
|
1665
1688
|
this._registerChannel = bindings.registerChannel;
|
|
1666
|
-
this._extensionRunner.flushPendingChannels(bindings.registerChannel);
|
|
1667
|
-
this._extensionRunner.updateRegisterChannel(bindings.registerChannel);
|
|
1668
1689
|
}
|
|
1669
1690
|
this._applyExtensionBindings(this._extensionRunner);
|
|
1670
1691
|
await this._extensionRunner.emit(this._sessionStartEvent);
|
|
1671
1692
|
await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
|
|
1672
|
-
await this._initMcpServers();
|
|
1673
1693
|
}
|
|
1674
1694
|
async extendResourcesFromExtensions(reason) {
|
|
1675
1695
|
if (!this._extensionRunner.hasHandlers("resources_discover")) {
|
|
@@ -1711,48 +1731,6 @@ export class AgentSession {
|
|
|
1711
1731
|
const name = base.replace(/\.(ts|js)$/, "");
|
|
1712
1732
|
return `extension:${name}`;
|
|
1713
1733
|
}
|
|
1714
|
-
_mcpManager;
|
|
1715
|
-
_createMcpToolDef;
|
|
1716
|
-
async _initMcpServers() {
|
|
1717
|
-
const settings = this.settingsManager.getProjectSettings();
|
|
1718
|
-
const servers = settings?.mcp?.servers;
|
|
1719
|
-
if (!servers || Object.keys(servers).length === 0)
|
|
1720
|
-
return;
|
|
1721
|
-
const { McpManager } = await import("./mcp/mcp-manager.js");
|
|
1722
|
-
const { createMcpToolDefinition } = await import("./mcp/tool-converter.js");
|
|
1723
|
-
this._createMcpToolDef = createMcpToolDefinition;
|
|
1724
|
-
const mcpOptions = settings?.mcp?.options;
|
|
1725
|
-
const manager = new McpManager({
|
|
1726
|
-
...mcpOptions,
|
|
1727
|
-
onConnectionChange: () => {
|
|
1728
|
-
this._syncMcpTools();
|
|
1729
|
-
},
|
|
1730
|
-
});
|
|
1731
|
-
this._mcpManager = manager;
|
|
1732
|
-
try {
|
|
1733
|
-
await manager.connectAll(servers);
|
|
1734
|
-
this._syncMcpTools();
|
|
1735
|
-
}
|
|
1736
|
-
catch (e) {
|
|
1737
|
-
console.error("[mcp] Failed to initialize:", e);
|
|
1738
|
-
}
|
|
1739
|
-
this.sessionSignal.addEventListener("abort", () => {
|
|
1740
|
-
this._mcpManager?.dispose().catch(() => { });
|
|
1741
|
-
this._mcpManager = undefined;
|
|
1742
|
-
});
|
|
1743
|
-
}
|
|
1744
|
-
_syncMcpTools() {
|
|
1745
|
-
this._customTools = this._customTools.filter((t) => !t.name.startsWith("mcp__"));
|
|
1746
|
-
if (!this._createMcpToolDef || !this._mcpManager)
|
|
1747
|
-
return;
|
|
1748
|
-
const tools = this._mcpManager.getAllTools();
|
|
1749
|
-
for (const tool of tools) {
|
|
1750
|
-
this._customTools.push(this._createMcpToolDef(tool, this._mcpManager));
|
|
1751
|
-
}
|
|
1752
|
-
if (tools.length > 0) {
|
|
1753
|
-
this._refreshToolRegistry();
|
|
1754
|
-
}
|
|
1755
|
-
}
|
|
1756
1734
|
_applyExtensionBindings(runner) {
|
|
1757
1735
|
runner.setUIContext(this._extensionUIContext);
|
|
1758
1736
|
runner.bindCommandContext(this._extensionCommandContextActions);
|
|
@@ -1860,7 +1838,7 @@ export class AgentSession {
|
|
|
1860
1838
|
}),
|
|
1861
1839
|
callLLM: (options) => this.callLLM(options),
|
|
1862
1840
|
callLLMStructured: (opts) => this.callLLMStructured(opts),
|
|
1863
|
-
forkAgent: (prompt,
|
|
1841
|
+
forkAgent: (prompt, opts) => this.forkAgent(prompt, opts),
|
|
1864
1842
|
background: (fn) => this.background(fn),
|
|
1865
1843
|
}, {
|
|
1866
1844
|
getModel: () => this.model,
|
|
@@ -1897,842 +1875,1037 @@ export class AgentSession {
|
|
|
1897
1875
|
},
|
|
1898
1876
|
});
|
|
1899
1877
|
}
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
const
|
|
1904
|
-
const
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1878
|
+
_refreshToolRegistry(options) {
|
|
1879
|
+
const previousRegistryNames = new Set(this._toolRegistry.keys());
|
|
1880
|
+
const previousActiveToolNames = this.getActiveToolNames();
|
|
1881
|
+
const allowedToolNames = this._allowedToolNames;
|
|
1882
|
+
const isAllowedTool = (name) => !allowedToolNames || allowedToolNames.has(name);
|
|
1883
|
+
const registeredTools = this._extensionRunner.getAllRegisteredTools();
|
|
1884
|
+
const allCustomTools = [
|
|
1885
|
+
...registeredTools,
|
|
1886
|
+
...this._customTools.map((definition) => ({
|
|
1887
|
+
definition,
|
|
1888
|
+
sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
|
|
1889
|
+
})),
|
|
1890
|
+
].filter((tool) => isAllowedTool(tool.definition.name));
|
|
1891
|
+
const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
|
|
1892
|
+
.filter(([name]) => isAllowedTool(name))
|
|
1893
|
+
.map(([name, definition]) => [
|
|
1894
|
+
name,
|
|
1895
|
+
{
|
|
1896
|
+
definition,
|
|
1897
|
+
sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
|
|
1898
|
+
},
|
|
1899
|
+
]));
|
|
1900
|
+
for (const tool of allCustomTools) {
|
|
1901
|
+
definitionRegistry.set(tool.definition.name, {
|
|
1902
|
+
definition: tool.definition,
|
|
1903
|
+
sourceInfo: tool.sourceInfo,
|
|
1904
|
+
});
|
|
1911
1905
|
}
|
|
1912
|
-
|
|
1913
|
-
|
|
1906
|
+
this._toolDefinitions = definitionRegistry;
|
|
1907
|
+
this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
|
|
1908
|
+
.map(({ definition }) => {
|
|
1909
|
+
const snippet = this._normalizePromptSnippet(definition.promptSnippet);
|
|
1910
|
+
return snippet ? [definition.name, snippet] : undefined;
|
|
1911
|
+
})
|
|
1912
|
+
.filter((entry) => entry !== undefined));
|
|
1913
|
+
this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
|
|
1914
|
+
.map(({ definition }) => {
|
|
1915
|
+
const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
|
|
1916
|
+
return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
|
|
1917
|
+
})
|
|
1918
|
+
.filter((entry) => entry !== undefined));
|
|
1919
|
+
const runner = this._extensionRunner;
|
|
1920
|
+
const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
|
|
1921
|
+
const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
|
|
1922
|
+
.filter((definition) => isAllowedTool(definition.name))
|
|
1923
|
+
.map((definition) => ({
|
|
1924
|
+
definition,
|
|
1925
|
+
sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
|
|
1926
|
+
})), runner);
|
|
1927
|
+
const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
|
|
1928
|
+
for (const tool of wrappedExtensionTools) {
|
|
1929
|
+
toolRegistry.set(tool.name, tool);
|
|
1914
1930
|
}
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1931
|
+
this._toolRegistry = toolRegistry;
|
|
1932
|
+
const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
|
|
1933
|
+
if (allowedToolNames) {
|
|
1934
|
+
for (const toolName of this._toolRegistry.keys()) {
|
|
1935
|
+
if (allowedToolNames.has(toolName)) {
|
|
1936
|
+
nextActiveToolNames.push(toolName);
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1918
1939
|
}
|
|
1919
|
-
if (
|
|
1920
|
-
const
|
|
1921
|
-
|
|
1940
|
+
else if (options?.includeAllExtensionTools) {
|
|
1941
|
+
for (const tool of wrappedExtensionTools) {
|
|
1942
|
+
nextActiveToolNames.push(tool.name);
|
|
1943
|
+
}
|
|
1922
1944
|
}
|
|
1923
|
-
if (
|
|
1924
|
-
|
|
1945
|
+
else if (!options?.activeToolNames) {
|
|
1946
|
+
for (const toolName of this._toolRegistry.keys()) {
|
|
1947
|
+
if (!previousRegistryNames.has(toolName)) {
|
|
1948
|
+
nextActiveToolNames.push(toolName);
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1925
1951
|
}
|
|
1926
|
-
|
|
1952
|
+
this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
|
|
1927
1953
|
}
|
|
1928
|
-
|
|
1929
|
-
const
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
const
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
throw new Error("Aborted");
|
|
1941
|
-
}
|
|
1942
|
-
const messages = options.messages.map((m) => ({
|
|
1943
|
-
role: m.role,
|
|
1944
|
-
content: [{ type: "text", text: m.content }],
|
|
1945
|
-
timestamp: Date.now(),
|
|
1946
|
-
}));
|
|
1947
|
-
if (!options.tools || options.tools.length === 0) {
|
|
1948
|
-
const context = {
|
|
1949
|
-
systemPrompt: options.systemPrompt,
|
|
1950
|
-
messages,
|
|
1951
|
-
};
|
|
1952
|
-
const response = await complete(model, context, {
|
|
1953
|
-
apiKey: auth.apiKey,
|
|
1954
|
-
headers: auth.headers,
|
|
1955
|
-
maxTokens: options.maxTokens,
|
|
1956
|
-
signal: options.signal,
|
|
1954
|
+
_buildRuntime(options) {
|
|
1955
|
+
const autoResizeImages = this.settingsManager.getImageAutoResize();
|
|
1956
|
+
const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
|
|
1957
|
+
const shellPath = this.settingsManager.getShellPath();
|
|
1958
|
+
const baseToolDefinitions = this._baseToolsOverride
|
|
1959
|
+
? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
|
|
1960
|
+
name,
|
|
1961
|
+
createToolDefinitionFromAgentTool(tool),
|
|
1962
|
+
]))
|
|
1963
|
+
: createAllToolDefinitions(this._cwd, {
|
|
1964
|
+
read: { autoResizeImages },
|
|
1965
|
+
bash: { commandPrefix: shellCommandPrefix, shellPath },
|
|
1957
1966
|
});
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
const toolInstances = options.tools
|
|
1964
|
-
.map((name) => {
|
|
1965
|
-
try {
|
|
1966
|
-
const registered = this._toolRegistry.get(name);
|
|
1967
|
-
if (registered)
|
|
1968
|
-
return registered;
|
|
1969
|
-
return createTool(name, this._cwd);
|
|
1970
|
-
}
|
|
1971
|
-
catch {
|
|
1972
|
-
return undefined;
|
|
1967
|
+
this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
|
|
1968
|
+
const extensionsResult = this._resourceLoader.getExtensions();
|
|
1969
|
+
if (options.flagValues) {
|
|
1970
|
+
for (const [name, value] of options.flagValues) {
|
|
1971
|
+
extensionsResult.runtime.flagValues.set(name, value);
|
|
1973
1972
|
}
|
|
1974
|
-
})
|
|
1975
|
-
.filter((t) => t !== undefined);
|
|
1976
|
-
if (toolInstances.length === 0) {
|
|
1977
|
-
const context = {
|
|
1978
|
-
systemPrompt: options.systemPrompt,
|
|
1979
|
-
messages,
|
|
1980
|
-
};
|
|
1981
|
-
const response = await complete(model, context, {
|
|
1982
|
-
apiKey: auth.apiKey,
|
|
1983
|
-
headers: auth.headers,
|
|
1984
|
-
maxTokens: options.maxTokens,
|
|
1985
|
-
signal: options.signal,
|
|
1986
|
-
});
|
|
1987
|
-
return response.content
|
|
1988
|
-
.filter((c) => c.type === "text")
|
|
1989
|
-
.map((c) => c.text)
|
|
1990
|
-
.join("\n");
|
|
1991
1973
|
}
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
systemPrompt: options.systemPrompt ?? "",
|
|
1996
|
-
model,
|
|
1997
|
-
thinkingLevel: "off",
|
|
1998
|
-
tools: toolInstances,
|
|
1999
|
-
messages: [],
|
|
2000
|
-
},
|
|
2001
|
-
});
|
|
2002
|
-
if (options.signal?.aborted) {
|
|
2003
|
-
throw new Error("Aborted");
|
|
1974
|
+
this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry);
|
|
1975
|
+
if (this._extensionRunnerRef) {
|
|
1976
|
+
this._extensionRunnerRef.current = this._extensionRunner;
|
|
2004
1977
|
}
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
.join("\n");
|
|
2016
|
-
}
|
|
2017
|
-
}
|
|
2018
|
-
}
|
|
1978
|
+
this._bindExtensionCore(this._extensionRunner);
|
|
1979
|
+
this._applyExtensionBindings(this._extensionRunner);
|
|
1980
|
+
this._initFileSnapshotManager();
|
|
1981
|
+
const defaultActiveToolNames = this._baseToolsOverride
|
|
1982
|
+
? Object.keys(this._baseToolsOverride)
|
|
1983
|
+
: ["read", "bash", "edit", "write"];
|
|
1984
|
+
const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
|
|
1985
|
+
this._refreshToolRegistry({
|
|
1986
|
+
activeToolNames: baseActiveToolNames,
|
|
1987
|
+
includeAllExtensionTools: options.includeAllExtensionTools,
|
|
2019
1988
|
});
|
|
2020
|
-
|
|
2021
|
-
await agent.prompt({
|
|
2022
|
-
role: "user",
|
|
2023
|
-
content: [{ type: "text", text: options.messages[0]?.content ?? "" }],
|
|
2024
|
-
timestamp: Date.now(),
|
|
2025
|
-
});
|
|
2026
|
-
}
|
|
2027
|
-
finally {
|
|
2028
|
-
unsub();
|
|
2029
|
-
}
|
|
2030
|
-
return resultText;
|
|
1989
|
+
this._initMcpServers();
|
|
2031
1990
|
}
|
|
2032
|
-
async
|
|
2033
|
-
const
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
...options,
|
|
2051
|
-
systemPrompt: structuredSystemPrompt,
|
|
2052
|
-
messages,
|
|
2053
|
-
});
|
|
2054
|
-
try {
|
|
2055
|
-
const cleaned = stripMarkdownCodeBlock(raw);
|
|
2056
|
-
const parsed = JSON.parse(cleaned);
|
|
2057
|
-
const check = Compile(options.schema);
|
|
2058
|
-
const coerced = Value.Convert(options.schema, parsed);
|
|
2059
|
-
if (!check.Check(coerced)) {
|
|
2060
|
-
const errors = check
|
|
2061
|
-
.Errors(coerced)
|
|
2062
|
-
.map((e) => `${e.instancePath}: ${e.message}`)
|
|
2063
|
-
.join("; ");
|
|
2064
|
-
const err = new Error(`Schema validation failed: ${errors}`);
|
|
2065
|
-
err.raw = raw;
|
|
2066
|
-
err.reason = "schema_validation";
|
|
2067
|
-
lastError = err;
|
|
2068
|
-
if (attempt >= maxRetries)
|
|
2069
|
-
throw err;
|
|
2070
|
-
continue;
|
|
2071
|
-
}
|
|
2072
|
-
return coerced;
|
|
2073
|
-
}
|
|
2074
|
-
catch (e) {
|
|
2075
|
-
if (e instanceof SyntaxError) {
|
|
2076
|
-
const err = new Error(`JSON parse failed: ${e.message}`);
|
|
2077
|
-
err.raw = raw;
|
|
2078
|
-
err.reason = "json_parse";
|
|
2079
|
-
lastError = err;
|
|
2080
|
-
if (attempt >= maxRetries)
|
|
2081
|
-
throw err;
|
|
2082
|
-
continue;
|
|
2083
|
-
}
|
|
2084
|
-
if (e.reason) {
|
|
2085
|
-
lastError = e;
|
|
2086
|
-
if (attempt >= maxRetries)
|
|
2087
|
-
throw lastError;
|
|
2088
|
-
continue;
|
|
2089
|
-
}
|
|
2090
|
-
throw e;
|
|
2091
|
-
}
|
|
1991
|
+
async reload() {
|
|
1992
|
+
const previousFlagValues = this._extensionRunner.getFlagValues();
|
|
1993
|
+
await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
|
|
1994
|
+
await this.settingsManager.reload();
|
|
1995
|
+
resetApiProviders();
|
|
1996
|
+
await this._resourceLoader.reload();
|
|
1997
|
+
this._buildRuntime({
|
|
1998
|
+
activeToolNames: this.getActiveToolNames(),
|
|
1999
|
+
flagValues: previousFlagValues,
|
|
2000
|
+
includeAllExtensionTools: true,
|
|
2001
|
+
});
|
|
2002
|
+
const hasBindings = this._extensionUIContext ||
|
|
2003
|
+
this._extensionCommandContextActions ||
|
|
2004
|
+
this._extensionShutdownHandler ||
|
|
2005
|
+
this._extensionErrorListener;
|
|
2006
|
+
if (hasBindings) {
|
|
2007
|
+
await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
|
|
2008
|
+
await this.extendResourcesFromExtensions("reload");
|
|
2092
2009
|
}
|
|
2093
|
-
throw lastError ?? new Error("callLLMStructured failed");
|
|
2094
2010
|
}
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2011
|
+
// =========================================================================
|
|
2012
|
+
// Auto-Retry
|
|
2013
|
+
// =========================================================================
|
|
2014
|
+
/**
|
|
2015
|
+
* Check if an error is retryable (overloaded, rate limit, server errors).
|
|
2016
|
+
* Context overflow errors are NOT retryable (handled by compaction instead).
|
|
2017
|
+
*/
|
|
2018
|
+
_isRetryableError(message) {
|
|
2019
|
+
if (message.stopReason !== "error" || !message.errorMessage)
|
|
2020
|
+
return false;
|
|
2021
|
+
// Context overflow is handled by compaction, not retry
|
|
2022
|
+
const contextWindow = this.model?.contextWindow ?? 0;
|
|
2023
|
+
if (isContextOverflow(message, contextWindow))
|
|
2024
|
+
return false;
|
|
2025
|
+
const err = message.errorMessage;
|
|
2026
|
+
// Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors (including connection lost), WebSocket transport closes/errors, fetch failed, request ended without sending chunks, HTTP/2 closed before response, terminated, retry delay exceeded
|
|
2027
|
+
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|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|http2 request did not get a response|timed? out|timeout|terminated|retry delay/i.test(err);
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* Handle retryable errors with exponential backoff.
|
|
2031
|
+
* @returns true if retry was initiated, false if max retries exceeded or disabled
|
|
2032
|
+
*/
|
|
2033
|
+
async _handleRetryableError(message) {
|
|
2034
|
+
const settings = this.settingsManager.getRetrySettings();
|
|
2035
|
+
if (!settings.enabled) {
|
|
2036
|
+
this._resolveRetry();
|
|
2037
|
+
return false;
|
|
2102
2038
|
}
|
|
2103
|
-
|
|
2104
|
-
|
|
2039
|
+
// Retry promise is created synchronously in _handleAgentEvent for agent_end.
|
|
2040
|
+
// Keep a defensive fallback here in case a future refactor bypasses that path.
|
|
2041
|
+
if (!this._retryPromise) {
|
|
2042
|
+
this._retryPromise = new Promise((resolve) => {
|
|
2043
|
+
this._retryResolve = resolve;
|
|
2044
|
+
});
|
|
2105
2045
|
}
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2046
|
+
this._retryAttempt++;
|
|
2047
|
+
if (this._retryAttempt > settings.maxRetries) {
|
|
2048
|
+
// Max retries exceeded, emit final failure and reset
|
|
2049
|
+
this._emit({
|
|
2050
|
+
type: "auto_retry_end",
|
|
2051
|
+
success: false,
|
|
2052
|
+
attempt: this._retryAttempt - 1,
|
|
2053
|
+
finalError: message.errorMessage,
|
|
2054
|
+
});
|
|
2055
|
+
this._retryAttempt = 0;
|
|
2056
|
+
this._resolveRetry(); // Resolve so waitForRetry() completes
|
|
2057
|
+
return false;
|
|
2112
2058
|
}
|
|
2113
|
-
const
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
}
|
|
2121
|
-
catch {
|
|
2122
|
-
return undefined;
|
|
2123
|
-
}
|
|
2124
|
-
})
|
|
2125
|
-
.filter((t) => t !== undefined);
|
|
2126
|
-
const effectiveSystemPrompt = opts.inheritSystemPrompt
|
|
2127
|
-
? (this.agent.state.systemPrompt ?? opts.systemPrompt ?? "")
|
|
2128
|
-
: (opts.systemPrompt ?? "");
|
|
2129
|
-
const messages = opts.shareContext ? [...this.agent.state.messages] : [];
|
|
2130
|
-
const maxTurns = opts.maxTurns ?? 5;
|
|
2131
|
-
let turnCount = 0;
|
|
2132
|
-
const forkedAgent = new Agent({
|
|
2133
|
-
getApiKey: () => auth.apiKey,
|
|
2134
|
-
initialState: {
|
|
2135
|
-
systemPrompt: effectiveSystemPrompt,
|
|
2136
|
-
model,
|
|
2137
|
-
thinkingLevel: "off",
|
|
2138
|
-
tools: toolInstances,
|
|
2139
|
-
messages,
|
|
2140
|
-
},
|
|
2141
|
-
sessionId: opts.shareContext ? this.agent.sessionId : undefined,
|
|
2059
|
+
const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
|
|
2060
|
+
this._emit({
|
|
2061
|
+
type: "auto_retry_start",
|
|
2062
|
+
attempt: this._retryAttempt,
|
|
2063
|
+
maxAttempts: settings.maxRetries,
|
|
2064
|
+
delayMs,
|
|
2065
|
+
errorMessage: message.errorMessage || "Unknown error",
|
|
2142
2066
|
});
|
|
2143
|
-
|
|
2144
|
-
const
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
opts.signal.addEventListener("abort", abortHandler, { once: true });
|
|
2067
|
+
// Remove error message from agent state (keep in session for history)
|
|
2068
|
+
const messages = this.agent.state.messages;
|
|
2069
|
+
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
2070
|
+
this.agent.state.messages = messages.slice(0, -1);
|
|
2148
2071
|
}
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
turnCount++;
|
|
2152
|
-
if (turnCount >= maxTurns) {
|
|
2153
|
-
forkedAgent.abort();
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
if (event.type === "message_end") {
|
|
2157
|
-
const msg = event.message;
|
|
2158
|
-
if (msg.role === "assistant") {
|
|
2159
|
-
const asst = msg;
|
|
2160
|
-
const content = asst.content;
|
|
2161
|
-
if (Array.isArray(content)) {
|
|
2162
|
-
resultText = content
|
|
2163
|
-
.filter((c) => c.type === "text")
|
|
2164
|
-
.map((c) => c.text)
|
|
2165
|
-
.join("\n");
|
|
2166
|
-
}
|
|
2167
|
-
if (asst.usage) {
|
|
2168
|
-
usage.input = asst.usage.input ?? 0;
|
|
2169
|
-
usage.output = asst.usage.output ?? 0;
|
|
2170
|
-
usage.cacheRead = asst.usage.cacheRead ?? 0;
|
|
2171
|
-
usage.cacheWrite = asst.usage.cacheWrite ?? 0;
|
|
2172
|
-
if (model.cost) {
|
|
2173
|
-
usage.cost =
|
|
2174
|
-
(usage.input * model.cost.input +
|
|
2175
|
-
usage.output * model.cost.output +
|
|
2176
|
-
usage.cacheRead * model.cost.cacheRead +
|
|
2177
|
-
usage.cacheWrite * model.cost.cacheWrite) /
|
|
2178
|
-
1_000_000;
|
|
2179
|
-
}
|
|
2180
|
-
}
|
|
2181
|
-
}
|
|
2182
|
-
}
|
|
2183
|
-
});
|
|
2072
|
+
// Wait with exponential backoff (abortable)
|
|
2073
|
+
this._retryAbortController = new AbortController();
|
|
2184
2074
|
try {
|
|
2185
|
-
await
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2075
|
+
await sleep(delayMs, this._retryAbortController.signal);
|
|
2076
|
+
}
|
|
2077
|
+
catch {
|
|
2078
|
+
// Aborted during sleep - emit end event so UI can clean up
|
|
2079
|
+
const attempt = this._retryAttempt;
|
|
2080
|
+
this._retryAttempt = 0;
|
|
2081
|
+
this._retryAbortController = undefined;
|
|
2082
|
+
this._emit({
|
|
2083
|
+
type: "auto_retry_end",
|
|
2084
|
+
success: false,
|
|
2085
|
+
attempt,
|
|
2086
|
+
finalError: "Retry cancelled",
|
|
2189
2087
|
});
|
|
2088
|
+
this._resolveRetry();
|
|
2089
|
+
return false;
|
|
2090
|
+
}
|
|
2091
|
+
this._retryAbortController = undefined;
|
|
2092
|
+
// Retry via continue() - use setTimeout to break out of event handler chain
|
|
2093
|
+
setTimeout(() => {
|
|
2094
|
+
this.agent.continue().catch(() => {
|
|
2095
|
+
// Retry failed - will be caught by next agent_end
|
|
2096
|
+
});
|
|
2097
|
+
}, 0);
|
|
2098
|
+
return true;
|
|
2099
|
+
}
|
|
2100
|
+
/**
|
|
2101
|
+
* Cancel in-progress retry.
|
|
2102
|
+
*/
|
|
2103
|
+
abortRetry() {
|
|
2104
|
+
this._retryAbortController?.abort();
|
|
2105
|
+
// Note: _retryAttempt is reset in the catch block of _autoRetry
|
|
2106
|
+
this._resolveRetry();
|
|
2107
|
+
}
|
|
2108
|
+
/**
|
|
2109
|
+
* Wait for any in-progress retry to complete.
|
|
2110
|
+
* Returns immediately if no retry is in progress.
|
|
2111
|
+
*/
|
|
2112
|
+
async waitForRetry() {
|
|
2113
|
+
if (!this._retryPromise) {
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
await this._retryPromise;
|
|
2117
|
+
await this.agent.waitForIdle();
|
|
2118
|
+
}
|
|
2119
|
+
/** Whether auto-retry is currently in progress */
|
|
2120
|
+
get isRetrying() {
|
|
2121
|
+
return this._retryPromise !== undefined;
|
|
2122
|
+
}
|
|
2123
|
+
/** Whether auto-retry is enabled */
|
|
2124
|
+
get autoRetryEnabled() {
|
|
2125
|
+
return this.settingsManager.getRetryEnabled();
|
|
2126
|
+
}
|
|
2127
|
+
/**
|
|
2128
|
+
* Toggle auto-retry setting.
|
|
2129
|
+
*/
|
|
2130
|
+
setAutoRetryEnabled(enabled) {
|
|
2131
|
+
this.settingsManager.setRetryEnabled(enabled);
|
|
2132
|
+
}
|
|
2133
|
+
// =========================================================================
|
|
2134
|
+
// Bash Execution
|
|
2135
|
+
// =========================================================================
|
|
2136
|
+
/**
|
|
2137
|
+
* Execute a bash command.
|
|
2138
|
+
* Adds result to agent context and session.
|
|
2139
|
+
* @param command The bash command to execute
|
|
2140
|
+
* @param onChunk Optional streaming callback for output
|
|
2141
|
+
* @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
|
|
2142
|
+
* @param options.operations Custom BashOperations for remote execution
|
|
2143
|
+
*/
|
|
2144
|
+
async executeBash(command, onChunk, options) {
|
|
2145
|
+
this._bashAbortController = new AbortController();
|
|
2146
|
+
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
2147
|
+
const prefix = this.settingsManager.getShellCommandPrefix();
|
|
2148
|
+
const shellPath = this.settingsManager.getShellPath();
|
|
2149
|
+
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
|
|
2150
|
+
try {
|
|
2151
|
+
const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
|
|
2152
|
+
onChunk,
|
|
2153
|
+
signal: this._bashAbortController.signal,
|
|
2154
|
+
});
|
|
2155
|
+
this.recordBashResult(command, result, options);
|
|
2156
|
+
return result;
|
|
2190
2157
|
}
|
|
2191
2158
|
finally {
|
|
2192
|
-
|
|
2193
|
-
if (abortHandler && opts.signal) {
|
|
2194
|
-
opts.signal.removeEventListener("abort", abortHandler);
|
|
2195
|
-
}
|
|
2159
|
+
this._bashAbortController = undefined;
|
|
2196
2160
|
}
|
|
2197
|
-
return { text: resultText, usage };
|
|
2198
2161
|
}
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2162
|
+
/**
|
|
2163
|
+
* Record a bash execution result in session history.
|
|
2164
|
+
* Used by executeBash and by extensions that handle bash execution themselves.
|
|
2165
|
+
*/
|
|
2166
|
+
recordBashResult(command, result, options) {
|
|
2167
|
+
const bashMessage = {
|
|
2168
|
+
role: "bashExecution",
|
|
2169
|
+
command,
|
|
2170
|
+
output: result.output,
|
|
2171
|
+
exitCode: result.exitCode,
|
|
2172
|
+
cancelled: result.cancelled,
|
|
2173
|
+
truncated: result.truncated,
|
|
2174
|
+
fullOutputPath: result.fullOutputPath,
|
|
2175
|
+
timestamp: Date.now(),
|
|
2176
|
+
excludeFromContext: options?.excludeFromContext,
|
|
2207
2177
|
};
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2178
|
+
// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
|
|
2179
|
+
if (this.isStreaming) {
|
|
2180
|
+
// Queue for later - will be flushed on agent_end
|
|
2181
|
+
this._pendingBashMessages.push(bashMessage);
|
|
2182
|
+
}
|
|
2183
|
+
else {
|
|
2184
|
+
// Add to agent state immediately
|
|
2185
|
+
this.agent.state.messages.push(bashMessage);
|
|
2186
|
+
// Save to session
|
|
2187
|
+
this.sessionManager.appendMessage(bashMessage);
|
|
2188
|
+
}
|
|
2211
2189
|
}
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2190
|
+
/**
|
|
2191
|
+
* Cancel running bash command.
|
|
2192
|
+
*/
|
|
2193
|
+
abortBash() {
|
|
2194
|
+
this._bashAbortController?.abort();
|
|
2195
|
+
}
|
|
2196
|
+
/** Whether a bash command is currently running */
|
|
2197
|
+
get isBashRunning() {
|
|
2198
|
+
return this._bashAbortController !== undefined;
|
|
2199
|
+
}
|
|
2200
|
+
/** Whether there are pending bash messages waiting to be flushed */
|
|
2201
|
+
get hasPendingBashMessages() {
|
|
2202
|
+
return this._pendingBashMessages.length > 0;
|
|
2203
|
+
}
|
|
2204
|
+
/**
|
|
2205
|
+
* Flush pending bash messages to agent state and session.
|
|
2206
|
+
* Called after agent turn completes to maintain proper message ordering.
|
|
2207
|
+
*/
|
|
2208
|
+
_flushPendingBashMessages() {
|
|
2209
|
+
if (this._pendingBashMessages.length === 0)
|
|
2210
|
+
return;
|
|
2211
|
+
for (const bashMessage of this._pendingBashMessages) {
|
|
2212
|
+
// Add to agent state
|
|
2213
|
+
this.agent.state.messages.push(bashMessage);
|
|
2214
|
+
// Save to session
|
|
2215
|
+
this.sessionManager.appendMessage(bashMessage);
|
|
2216
|
+
}
|
|
2217
|
+
this._pendingBashMessages = [];
|
|
2218
|
+
}
|
|
2219
|
+
// =========================================================================
|
|
2220
|
+
// Session Management
|
|
2221
|
+
// =========================================================================
|
|
2222
|
+
/**
|
|
2223
|
+
* Set a display name for the current session.
|
|
2224
|
+
*/
|
|
2225
|
+
setSessionName(name) {
|
|
2226
|
+
this.sessionManager.appendSessionInfo(name);
|
|
2227
|
+
this._emit({ type: "session_info_changed", name: this.sessionManager.getSessionName() });
|
|
2228
|
+
}
|
|
2229
|
+
// =========================================================================
|
|
2230
|
+
// Tree Navigation
|
|
2231
|
+
// =========================================================================
|
|
2232
|
+
/**
|
|
2233
|
+
* Navigate to a different node in the session tree.
|
|
2234
|
+
* Unlike fork() which creates a new session file, this stays in the same file.
|
|
2235
|
+
*
|
|
2236
|
+
* @param targetId The entry ID to navigate to
|
|
2237
|
+
* @param options.summarize Whether user wants to summarize abandoned branch
|
|
2238
|
+
* @param options.customInstructions Custom instructions for summarizer
|
|
2239
|
+
* @param options.replaceInstructions If true, customInstructions replaces the default prompt
|
|
2240
|
+
* @param options.label Label to attach to the branch summary entry
|
|
2241
|
+
* @returns Result with editorText (if user message) and cancelled status
|
|
2242
|
+
*/
|
|
2243
|
+
async navigateTree(targetId, options = {}) {
|
|
2244
|
+
const oldLeafId = this.sessionManager.getLeafId();
|
|
2245
|
+
// No-op if already at target
|
|
2246
|
+
if (targetId === oldLeafId) {
|
|
2247
|
+
return { cancelled: false };
|
|
2248
|
+
}
|
|
2249
|
+
// Model required for summarization
|
|
2250
|
+
if (options.summarize && !this.model) {
|
|
2251
|
+
throw new Error("No model available for summarization");
|
|
2252
|
+
}
|
|
2253
|
+
const targetEntry = this.sessionManager.getEntry(targetId);
|
|
2254
|
+
if (!targetEntry) {
|
|
2255
|
+
throw new Error(`Entry ${targetId} not found`);
|
|
2256
|
+
}
|
|
2257
|
+
// Collect entries to summarize (from old leaf to common ancestor)
|
|
2258
|
+
const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
|
|
2259
|
+
// Prepare event data - mutable so extensions can override
|
|
2260
|
+
let customInstructions = options.customInstructions;
|
|
2261
|
+
let replaceInstructions = options.replaceInstructions;
|
|
2262
|
+
let label = options.label;
|
|
2263
|
+
const preparation = {
|
|
2264
|
+
targetId,
|
|
2265
|
+
oldLeafId,
|
|
2266
|
+
commonAncestorId,
|
|
2267
|
+
entriesToSummarize,
|
|
2268
|
+
userWantsSummary: options.summarize ?? false,
|
|
2269
|
+
customInstructions,
|
|
2270
|
+
replaceInstructions,
|
|
2271
|
+
label,
|
|
2272
|
+
skipFiles: options.skipFiles,
|
|
2273
|
+
};
|
|
2274
|
+
// Set up abort controller for summarization
|
|
2275
|
+
this._branchSummaryAbortController = new AbortController();
|
|
2276
|
+
try {
|
|
2277
|
+
let extensionSummary;
|
|
2278
|
+
let fromExtension = false;
|
|
2279
|
+
// Emit session_before_tree event
|
|
2280
|
+
if (this._extensionRunner.hasHandlers("session_before_tree")) {
|
|
2281
|
+
const result = (await this._extensionRunner.emit({
|
|
2282
|
+
type: "session_before_tree",
|
|
2283
|
+
preparation,
|
|
2284
|
+
signal: this._branchSummaryAbortController.signal,
|
|
2285
|
+
}));
|
|
2286
|
+
if (result?.cancel) {
|
|
2287
|
+
return { cancelled: true };
|
|
2288
|
+
}
|
|
2289
|
+
if (result?.summary && options.summarize) {
|
|
2290
|
+
extensionSummary = result.summary;
|
|
2291
|
+
fromExtension = true;
|
|
2292
|
+
}
|
|
2293
|
+
// Allow extensions to override instructions and label
|
|
2294
|
+
if (result?.customInstructions !== undefined) {
|
|
2295
|
+
customInstructions = result.customInstructions;
|
|
2296
|
+
}
|
|
2297
|
+
if (result?.replaceInstructions !== undefined) {
|
|
2298
|
+
replaceInstructions = result.replaceInstructions;
|
|
2299
|
+
}
|
|
2300
|
+
if (result?.label !== undefined) {
|
|
2301
|
+
label = result.label;
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
// Run default summarizer if needed
|
|
2305
|
+
let summaryText;
|
|
2306
|
+
let summaryDetails;
|
|
2307
|
+
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
2308
|
+
const model = this.model;
|
|
2309
|
+
const { apiKey, headers } = await this._getRequiredRequestAuth(model);
|
|
2310
|
+
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
2311
|
+
const result = await generateBranchSummary(entriesToSummarize, {
|
|
2312
|
+
model,
|
|
2313
|
+
apiKey,
|
|
2314
|
+
headers,
|
|
2315
|
+
signal: this._branchSummaryAbortController.signal,
|
|
2316
|
+
customInstructions,
|
|
2317
|
+
replaceInstructions,
|
|
2318
|
+
reserveTokens: branchSummarySettings.reserveTokens,
|
|
2319
|
+
});
|
|
2320
|
+
if (result.aborted) {
|
|
2321
|
+
return { cancelled: true, aborted: true };
|
|
2322
|
+
}
|
|
2323
|
+
if (result.error) {
|
|
2324
|
+
throw new Error(result.error);
|
|
2325
|
+
}
|
|
2326
|
+
summaryText = result.summary;
|
|
2327
|
+
summaryDetails = {
|
|
2328
|
+
readFiles: result.readFiles || [],
|
|
2329
|
+
modifiedFiles: result.modifiedFiles || [],
|
|
2330
|
+
};
|
|
2331
|
+
}
|
|
2332
|
+
else if (extensionSummary) {
|
|
2333
|
+
summaryText = extensionSummary.summary;
|
|
2334
|
+
summaryDetails = extensionSummary.details;
|
|
2335
|
+
}
|
|
2336
|
+
// Determine the new leaf position based on target type
|
|
2337
|
+
let newLeafId;
|
|
2338
|
+
let editorText;
|
|
2339
|
+
if (targetEntry.type === "message" && targetEntry.message.role === "user") {
|
|
2340
|
+
// User message: leaf = parent (null if root), text goes to editor
|
|
2341
|
+
newLeafId = targetEntry.parentId;
|
|
2342
|
+
editorText = this._extractUserMessageText(targetEntry.message.content);
|
|
2343
|
+
}
|
|
2344
|
+
else if (targetEntry.type === "custom_message") {
|
|
2345
|
+
// Custom message: leaf = parent (null if root), text goes to editor
|
|
2346
|
+
newLeafId = targetEntry.parentId;
|
|
2347
|
+
editorText =
|
|
2348
|
+
typeof targetEntry.content === "string"
|
|
2349
|
+
? targetEntry.content
|
|
2350
|
+
: targetEntry.content
|
|
2351
|
+
.filter((c) => c.type === "text")
|
|
2352
|
+
.map((c) => c.text)
|
|
2353
|
+
.join("");
|
|
2354
|
+
}
|
|
2355
|
+
else {
|
|
2356
|
+
// Non-user message: leaf = selected node
|
|
2357
|
+
newLeafId = targetId;
|
|
2358
|
+
}
|
|
2359
|
+
// Switch leaf (with or without summary)
|
|
2360
|
+
// Summary is attached at the navigation target position (newLeafId), not the old branch
|
|
2361
|
+
let summaryEntry;
|
|
2362
|
+
if (summaryText) {
|
|
2363
|
+
// Create summary at target position (can be null for root)
|
|
2364
|
+
const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
|
|
2365
|
+
summaryEntry = this.sessionManager.getEntry(summaryId);
|
|
2366
|
+
// Attach label to the summary entry
|
|
2367
|
+
if (label) {
|
|
2368
|
+
this.sessionManager.appendLabelChange(summaryId, label);
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
else if (newLeafId === null) {
|
|
2372
|
+
// No summary, navigating to root - reset leaf
|
|
2373
|
+
this.sessionManager.resetLeaf();
|
|
2374
|
+
}
|
|
2375
|
+
else {
|
|
2376
|
+
// No summary, navigating to non-root
|
|
2377
|
+
this.sessionManager.branch(newLeafId);
|
|
2378
|
+
}
|
|
2379
|
+
// Attach label to target entry when not summarizing (no summary entry to label)
|
|
2380
|
+
if (label && !summaryText) {
|
|
2381
|
+
this.sessionManager.appendLabelChange(targetId, label);
|
|
2382
|
+
}
|
|
2383
|
+
// Update agent state
|
|
2384
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2385
|
+
this.agent.state.messages = sessionContext.messages;
|
|
2386
|
+
// Emit session_tree event
|
|
2387
|
+
await this._extensionRunner.emit({
|
|
2388
|
+
type: "session_tree",
|
|
2389
|
+
newLeafId: this.sessionManager.getLeafId(),
|
|
2390
|
+
oldLeafId,
|
|
2391
|
+
summaryEntry,
|
|
2392
|
+
fromExtension: summaryText ? fromExtension : undefined,
|
|
2238
2393
|
});
|
|
2394
|
+
// Emit to custom tools
|
|
2395
|
+
return { editorText, cancelled: false, summaryEntry };
|
|
2239
2396
|
}
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
.map(({ definition }) => {
|
|
2243
|
-
const snippet = this._normalizePromptSnippet(definition.promptSnippet);
|
|
2244
|
-
return snippet ? [definition.name, snippet] : undefined;
|
|
2245
|
-
})
|
|
2246
|
-
.filter((entry) => entry !== undefined));
|
|
2247
|
-
this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
|
|
2248
|
-
.map(({ definition }) => {
|
|
2249
|
-
const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
|
|
2250
|
-
return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
|
|
2251
|
-
})
|
|
2252
|
-
.filter((entry) => entry !== undefined));
|
|
2253
|
-
const runner = this._extensionRunner;
|
|
2254
|
-
const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
|
|
2255
|
-
const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
|
|
2256
|
-
.filter((definition) => isAllowedTool(definition.name))
|
|
2257
|
-
.map((definition) => ({
|
|
2258
|
-
definition,
|
|
2259
|
-
sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
|
|
2260
|
-
})), runner);
|
|
2261
|
-
const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
|
|
2262
|
-
for (const tool of wrappedExtensionTools) {
|
|
2263
|
-
toolRegistry.set(tool.name, tool);
|
|
2397
|
+
finally {
|
|
2398
|
+
this._branchSummaryAbortController = undefined;
|
|
2264
2399
|
}
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* Get all user messages from session for fork selector.
|
|
2403
|
+
*/
|
|
2404
|
+
getUserMessagesForForking() {
|
|
2405
|
+
const entries = this.sessionManager.getEntries();
|
|
2406
|
+
const result = [];
|
|
2407
|
+
for (const entry of entries) {
|
|
2408
|
+
if (entry.type !== "message")
|
|
2409
|
+
continue;
|
|
2410
|
+
if (entry.message.role !== "user")
|
|
2411
|
+
continue;
|
|
2412
|
+
const text = this._extractUserMessageText(entry.message.content);
|
|
2413
|
+
if (text) {
|
|
2414
|
+
result.push({ entryId: entry.id, text });
|
|
2272
2415
|
}
|
|
2273
2416
|
}
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2417
|
+
return result;
|
|
2418
|
+
}
|
|
2419
|
+
_extractUserMessageText(content) {
|
|
2420
|
+
if (typeof content === "string")
|
|
2421
|
+
return content;
|
|
2422
|
+
if (Array.isArray(content)) {
|
|
2423
|
+
return content
|
|
2424
|
+
.filter((c) => c.type === "text")
|
|
2425
|
+
.map((c) => c.text)
|
|
2426
|
+
.join("");
|
|
2427
|
+
}
|
|
2428
|
+
return "";
|
|
2429
|
+
}
|
|
2430
|
+
/**
|
|
2431
|
+
* Get session statistics.
|
|
2432
|
+
*/
|
|
2433
|
+
getSessionStats() {
|
|
2434
|
+
const state = this.state;
|
|
2435
|
+
const userMessages = state.messages.filter((m) => m.role === "user").length;
|
|
2436
|
+
const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
|
|
2437
|
+
const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
|
|
2438
|
+
let toolCalls = 0;
|
|
2439
|
+
let totalInput = 0;
|
|
2440
|
+
let totalOutput = 0;
|
|
2441
|
+
let totalCacheRead = 0;
|
|
2442
|
+
let totalCacheWrite = 0;
|
|
2443
|
+
let totalCost = 0;
|
|
2444
|
+
for (const message of state.messages) {
|
|
2445
|
+
if (message.role === "assistant") {
|
|
2446
|
+
const assistantMsg = message;
|
|
2447
|
+
toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
|
|
2448
|
+
totalInput += assistantMsg.usage.input;
|
|
2449
|
+
totalOutput += assistantMsg.usage.output;
|
|
2450
|
+
totalCacheRead += assistantMsg.usage.cacheRead;
|
|
2451
|
+
totalCacheWrite += assistantMsg.usage.cacheWrite;
|
|
2452
|
+
totalCost += assistantMsg.usage.cost.total;
|
|
2277
2453
|
}
|
|
2278
2454
|
}
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2455
|
+
return {
|
|
2456
|
+
sessionFile: this.sessionFile,
|
|
2457
|
+
sessionId: this.sessionId,
|
|
2458
|
+
userMessages,
|
|
2459
|
+
assistantMessages,
|
|
2460
|
+
toolCalls,
|
|
2461
|
+
toolResults,
|
|
2462
|
+
totalMessages: state.messages.length,
|
|
2463
|
+
tokens: {
|
|
2464
|
+
input: totalInput,
|
|
2465
|
+
output: totalOutput,
|
|
2466
|
+
cacheRead: totalCacheRead,
|
|
2467
|
+
cacheWrite: totalCacheWrite,
|
|
2468
|
+
total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
|
|
2469
|
+
},
|
|
2470
|
+
cost: totalCost,
|
|
2471
|
+
contextUsage: this.getContextUsage(),
|
|
2472
|
+
};
|
|
2473
|
+
}
|
|
2474
|
+
getContextUsage() {
|
|
2475
|
+
const model = this.model;
|
|
2476
|
+
if (!model)
|
|
2477
|
+
return undefined;
|
|
2478
|
+
const contextWindow = model.contextWindow ?? 0;
|
|
2479
|
+
if (contextWindow <= 0)
|
|
2480
|
+
return undefined;
|
|
2481
|
+
// After compaction, the last assistant usage reflects pre-compaction context size.
|
|
2482
|
+
// We can only trust usage from an assistant that responded after the latest compaction.
|
|
2483
|
+
// If no such assistant exists, context token count is unknown until the next LLM response.
|
|
2484
|
+
const branchEntries = this.sessionManager.getBranch();
|
|
2485
|
+
const latestCompaction = getLatestCompactionEntry(branchEntries);
|
|
2486
|
+
if (latestCompaction) {
|
|
2487
|
+
// Check if there's a valid assistant usage after the compaction boundary
|
|
2488
|
+
const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
|
|
2489
|
+
let hasPostCompactionUsage = false;
|
|
2490
|
+
for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
|
|
2491
|
+
const entry = branchEntries[i];
|
|
2492
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
2493
|
+
const assistant = entry.message;
|
|
2494
|
+
if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
|
|
2495
|
+
const contextTokens = calculateContextTokens(assistant.usage);
|
|
2496
|
+
if (contextTokens > 0) {
|
|
2497
|
+
hasPostCompactionUsage = true;
|
|
2498
|
+
}
|
|
2499
|
+
break;
|
|
2500
|
+
}
|
|
2283
2501
|
}
|
|
2284
2502
|
}
|
|
2503
|
+
if (!hasPostCompactionUsage) {
|
|
2504
|
+
return { tokens: null, contextWindow, percent: null };
|
|
2505
|
+
}
|
|
2285
2506
|
}
|
|
2286
|
-
this.
|
|
2507
|
+
const estimate = estimateContextTokens(this.messages);
|
|
2508
|
+
const percent = (estimate.tokens / contextWindow) * 100;
|
|
2509
|
+
return {
|
|
2510
|
+
tokens: estimate.tokens,
|
|
2511
|
+
contextWindow,
|
|
2512
|
+
percent,
|
|
2513
|
+
};
|
|
2287
2514
|
}
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
:
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2515
|
+
/**
|
|
2516
|
+
* Export session to HTML.
|
|
2517
|
+
* @param outputPath Optional output path (defaults to session directory)
|
|
2518
|
+
* @returns Path to exported file
|
|
2519
|
+
*/
|
|
2520
|
+
async exportToHtml(outputPath) {
|
|
2521
|
+
const themeName = this.settingsManager.getTheme();
|
|
2522
|
+
// Create tool renderer if we have an extension runner (for custom tool HTML rendering)
|
|
2523
|
+
const toolRenderer = createToolHtmlRenderer({
|
|
2524
|
+
getToolDefinition: (name) => this.getToolDefinition(name),
|
|
2525
|
+
theme,
|
|
2526
|
+
cwd: this.sessionManager.getCwd(),
|
|
2527
|
+
});
|
|
2528
|
+
return await exportSessionToHtml(this.sessionManager, this.state, {
|
|
2529
|
+
outputPath,
|
|
2530
|
+
themeName,
|
|
2531
|
+
toolRenderer,
|
|
2532
|
+
});
|
|
2533
|
+
}
|
|
2534
|
+
/**
|
|
2535
|
+
* Export the current session branch to a JSONL file.
|
|
2536
|
+
* Writes the session header followed by all entries on the current branch path.
|
|
2537
|
+
* @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
|
|
2538
|
+
* @returns The resolved output file path.
|
|
2539
|
+
*/
|
|
2540
|
+
exportToJsonl(outputPath) {
|
|
2541
|
+
const filePath = resolve(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`);
|
|
2542
|
+
const dir = dirname(filePath);
|
|
2543
|
+
if (!existsSync(dir)) {
|
|
2544
|
+
mkdirSync(dir, { recursive: true });
|
|
2307
2545
|
}
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2546
|
+
const header = {
|
|
2547
|
+
type: "session",
|
|
2548
|
+
version: CURRENT_SESSION_VERSION,
|
|
2549
|
+
id: this.sessionManager.getSessionId(),
|
|
2550
|
+
timestamp: new Date().toISOString(),
|
|
2551
|
+
cwd: this.sessionManager.getCwd(),
|
|
2552
|
+
};
|
|
2553
|
+
const branchEntries = this.sessionManager.getBranch();
|
|
2554
|
+
const lines = [JSON.stringify(header)];
|
|
2555
|
+
// Re-chain parentIds to form a linear sequence
|
|
2556
|
+
let prevId = null;
|
|
2557
|
+
for (const entry of branchEntries) {
|
|
2558
|
+
const linear = { ...entry, parentId: prevId };
|
|
2559
|
+
lines.push(JSON.stringify(linear));
|
|
2560
|
+
prevId = entry.id;
|
|
2311
2561
|
}
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
const defaultActiveToolNames = this._baseToolsOverride
|
|
2315
|
-
? Object.keys(this._baseToolsOverride)
|
|
2316
|
-
: ["read", "bash", "edit", "write"];
|
|
2317
|
-
const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
|
|
2318
|
-
this._refreshToolRegistry({
|
|
2319
|
-
activeToolNames: baseActiveToolNames,
|
|
2320
|
-
includeAllExtensionTools: options.includeAllExtensionTools,
|
|
2321
|
-
});
|
|
2562
|
+
writeFileSync(filePath, `${lines.join("\n")}\n`);
|
|
2563
|
+
return filePath;
|
|
2322
2564
|
}
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2565
|
+
// =========================================================================
|
|
2566
|
+
// Utilities
|
|
2567
|
+
// =========================================================================
|
|
2568
|
+
/**
|
|
2569
|
+
* Get text content of last assistant message.
|
|
2570
|
+
* Useful for /copy command.
|
|
2571
|
+
* @returns Text content, or undefined if no assistant message exists
|
|
2572
|
+
*/
|
|
2573
|
+
getLastAssistantText() {
|
|
2574
|
+
const lastAssistant = this.messages
|
|
2575
|
+
.slice()
|
|
2576
|
+
.reverse()
|
|
2577
|
+
.find((m) => {
|
|
2578
|
+
if (m.role !== "assistant")
|
|
2579
|
+
return false;
|
|
2580
|
+
const msg = m;
|
|
2581
|
+
// Skip aborted messages with no content
|
|
2582
|
+
if (msg.stopReason === "aborted" && msg.content.length === 0)
|
|
2583
|
+
return false;
|
|
2584
|
+
return true;
|
|
2333
2585
|
});
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2586
|
+
if (!lastAssistant)
|
|
2587
|
+
return undefined;
|
|
2588
|
+
let text = "";
|
|
2589
|
+
for (const content of lastAssistant.content) {
|
|
2590
|
+
if (content.type === "text") {
|
|
2591
|
+
text += content.text;
|
|
2592
|
+
}
|
|
2341
2593
|
}
|
|
2342
|
-
|
|
2343
|
-
async setCwd(newCwd) {
|
|
2344
|
-
this._cwd = newCwd;
|
|
2345
|
-
this._buildRuntime({
|
|
2346
|
-
activeToolNames: this.getActiveToolNames(),
|
|
2347
|
-
flagValues: this._extensionRunner.getFlagValues(),
|
|
2348
|
-
includeAllExtensionTools: true,
|
|
2349
|
-
});
|
|
2594
|
+
return text.trim() || undefined;
|
|
2350
2595
|
}
|
|
2351
2596
|
// =========================================================================
|
|
2352
|
-
//
|
|
2597
|
+
// Extension System
|
|
2353
2598
|
// =========================================================================
|
|
2599
|
+
createReplacedSessionContext() {
|
|
2600
|
+
const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
|
|
2601
|
+
context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
|
|
2602
|
+
context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
|
|
2603
|
+
return context;
|
|
2604
|
+
}
|
|
2354
2605
|
/**
|
|
2355
|
-
* Check if
|
|
2356
|
-
* Context overflow errors are NOT retryable (handled by compaction instead).
|
|
2606
|
+
* Check if extensions have handlers for a specific event type.
|
|
2357
2607
|
*/
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
return false;
|
|
2361
|
-
// Context overflow is handled by compaction, not retry
|
|
2362
|
-
const contextWindow = this.model?.contextWindow ?? 0;
|
|
2363
|
-
if (isContextOverflow(message, contextWindow))
|
|
2364
|
-
return false;
|
|
2365
|
-
const err = message.errorMessage;
|
|
2366
|
-
// Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors (including connection lost), fetch failed, request ended without sending chunks, terminated, retry delay exceeded
|
|
2367
|
-
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|connection.?lost|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|timed? out|timeout|terminated|retry delay/i.test(err);
|
|
2608
|
+
hasExtensionHandlers(eventType) {
|
|
2609
|
+
return this._extensionRunner.hasHandlers(eventType);
|
|
2368
2610
|
}
|
|
2369
2611
|
/**
|
|
2370
|
-
*
|
|
2371
|
-
* @returns true if retry was initiated, false if max retries exceeded or disabled
|
|
2612
|
+
* Get the extension runner (for setting UI context and error handlers).
|
|
2372
2613
|
*/
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
this._retryPromise = new Promise((resolve) => {
|
|
2383
|
-
this._retryResolve = resolve;
|
|
2384
|
-
});
|
|
2614
|
+
get extensionRunner() {
|
|
2615
|
+
return this._extensionRunner;
|
|
2616
|
+
}
|
|
2617
|
+
async _resolveOptionalModel(modelSpec) {
|
|
2618
|
+
if (modelSpec) {
|
|
2619
|
+
const aliasResolved = resolveModelAlias(modelSpec, this._tierModels);
|
|
2620
|
+
const resolved = aliasResolved ?? modelSpec;
|
|
2621
|
+
const available = await this._modelRegistry.getAvailable();
|
|
2622
|
+
return available.find((m) => m.id === resolved || `${m.provider}/${m.id}` === resolved);
|
|
2385
2623
|
}
|
|
2386
|
-
this.
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
});
|
|
2395
|
-
this._retryAttempt = 0;
|
|
2396
|
-
this._resolveRetry(); // Resolve so waitForRetry() completes
|
|
2397
|
-
return false;
|
|
2624
|
+
return this.model;
|
|
2625
|
+
}
|
|
2626
|
+
async callLLM(options) {
|
|
2627
|
+
const model = await this._resolveOptionalModel(options.model);
|
|
2628
|
+
if (!model)
|
|
2629
|
+
throw new Error("No model selected");
|
|
2630
|
+
const auth = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
2631
|
+
if (!auth?.ok) {
|
|
2632
|
+
throw new Error(auth?.error ?? `No API key configured for ${model.provider}`);
|
|
2398
2633
|
}
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
type: "auto_retry_start",
|
|
2402
|
-
attempt: this._retryAttempt,
|
|
2403
|
-
maxAttempts: settings.maxRetries,
|
|
2404
|
-
delayMs,
|
|
2405
|
-
errorMessage: message.errorMessage || "Unknown error",
|
|
2406
|
-
});
|
|
2407
|
-
// Remove error message from agent state (keep in session for history)
|
|
2408
|
-
const messages = this.agent.state.messages;
|
|
2409
|
-
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
2410
|
-
this.agent.state.messages = messages.slice(0, -1);
|
|
2634
|
+
if (!auth.apiKey) {
|
|
2635
|
+
throw new Error(`No API key configured for ${model.provider}`);
|
|
2411
2636
|
}
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
try {
|
|
2415
|
-
await sleep(delayMs, this._retryAbortController.signal);
|
|
2637
|
+
if (options.signal?.aborted) {
|
|
2638
|
+
throw new Error("Aborted");
|
|
2416
2639
|
}
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2640
|
+
const messages = options.messages.map((m) => ({
|
|
2641
|
+
role: m.role,
|
|
2642
|
+
content: [{ type: "text", text: m.content }],
|
|
2643
|
+
timestamp: Date.now(),
|
|
2644
|
+
}));
|
|
2645
|
+
if (!options.tools || options.tools.length === 0) {
|
|
2646
|
+
const context = {
|
|
2647
|
+
systemPrompt: options.systemPrompt,
|
|
2648
|
+
messages,
|
|
2649
|
+
};
|
|
2650
|
+
const response = await complete(model, context, {
|
|
2651
|
+
apiKey: auth.apiKey,
|
|
2652
|
+
headers: auth.headers,
|
|
2653
|
+
maxTokens: options.maxTokens,
|
|
2654
|
+
signal: options.signal,
|
|
2427
2655
|
});
|
|
2428
|
-
|
|
2429
|
-
|
|
2656
|
+
return response.content
|
|
2657
|
+
.filter((c) => c.type === "text")
|
|
2658
|
+
.map((c) => c.text)
|
|
2659
|
+
.join("\n");
|
|
2430
2660
|
}
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2661
|
+
const toolInstances = options.tools
|
|
2662
|
+
.map((name) => {
|
|
2663
|
+
try {
|
|
2664
|
+
const registered = this._toolRegistry.get(name);
|
|
2665
|
+
if (registered)
|
|
2666
|
+
return registered;
|
|
2667
|
+
return createTool(name, this._cwd);
|
|
2668
|
+
}
|
|
2669
|
+
catch {
|
|
2670
|
+
return undefined;
|
|
2671
|
+
}
|
|
2672
|
+
})
|
|
2673
|
+
.filter((t) => t !== undefined);
|
|
2674
|
+
if (toolInstances.length === 0) {
|
|
2675
|
+
const context = {
|
|
2676
|
+
systemPrompt: options.systemPrompt,
|
|
2677
|
+
messages,
|
|
2678
|
+
};
|
|
2679
|
+
const response = await complete(model, context, {
|
|
2680
|
+
apiKey: auth.apiKey,
|
|
2681
|
+
headers: auth.headers,
|
|
2682
|
+
maxTokens: options.maxTokens,
|
|
2683
|
+
signal: options.signal,
|
|
2436
2684
|
});
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
* Cancel in-progress retry.
|
|
2442
|
-
*/
|
|
2443
|
-
abortRetry() {
|
|
2444
|
-
this._retryAbortController?.abort();
|
|
2445
|
-
// Note: _retryAttempt is reset in the catch block of _autoRetry
|
|
2446
|
-
this._resolveRetry();
|
|
2447
|
-
}
|
|
2448
|
-
/**
|
|
2449
|
-
* Wait for any in-progress retry to complete.
|
|
2450
|
-
* Returns immediately if no retry is in progress.
|
|
2451
|
-
*/
|
|
2452
|
-
async waitForRetry() {
|
|
2453
|
-
if (!this._retryPromise) {
|
|
2454
|
-
return;
|
|
2685
|
+
return response.content
|
|
2686
|
+
.filter((c) => c.type === "text")
|
|
2687
|
+
.map((c) => c.text)
|
|
2688
|
+
.join("\n");
|
|
2455
2689
|
}
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
async executeBash(command, onChunk, options) {
|
|
2485
|
-
this._bashAbortController = new AbortController();
|
|
2486
|
-
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
2487
|
-
const prefix = this.settingsManager.getShellCommandPrefix();
|
|
2488
|
-
const shellPath = this.settingsManager.getShellPath();
|
|
2489
|
-
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
|
|
2690
|
+
const agent = new Agent({
|
|
2691
|
+
getApiKey: () => auth.apiKey,
|
|
2692
|
+
initialState: {
|
|
2693
|
+
systemPrompt: options.systemPrompt ?? "",
|
|
2694
|
+
model,
|
|
2695
|
+
thinkingLevel: "off",
|
|
2696
|
+
tools: toolInstances,
|
|
2697
|
+
messages: [],
|
|
2698
|
+
},
|
|
2699
|
+
});
|
|
2700
|
+
if (options.signal?.aborted) {
|
|
2701
|
+
throw new Error("Aborted");
|
|
2702
|
+
}
|
|
2703
|
+
let resultText = "";
|
|
2704
|
+
const unsub = agent.subscribe((event) => {
|
|
2705
|
+
if (event.type === "message_end" && "message" in event) {
|
|
2706
|
+
const msg = event.message;
|
|
2707
|
+
if (msg.role === "assistant") {
|
|
2708
|
+
const content = msg.content;
|
|
2709
|
+
if (Array.isArray(content)) {
|
|
2710
|
+
resultText = content
|
|
2711
|
+
.filter((c) => c.type === "text")
|
|
2712
|
+
.map((c) => c.text)
|
|
2713
|
+
.join("\n");
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
});
|
|
2490
2718
|
try {
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2719
|
+
await agent.prompt({
|
|
2720
|
+
role: "user",
|
|
2721
|
+
content: [{ type: "text", text: options.messages[0]?.content ?? "" }],
|
|
2722
|
+
timestamp: Date.now(),
|
|
2494
2723
|
});
|
|
2495
|
-
this.recordBashResult(command, result, options);
|
|
2496
|
-
return result;
|
|
2497
2724
|
}
|
|
2498
2725
|
finally {
|
|
2499
|
-
|
|
2500
|
-
}
|
|
2501
|
-
}
|
|
2502
|
-
/**
|
|
2503
|
-
* Record a bash execution result in session history.
|
|
2504
|
-
* Used by executeBash and by extensions that handle bash execution themselves.
|
|
2505
|
-
*/
|
|
2506
|
-
recordBashResult(command, result, options) {
|
|
2507
|
-
const bashMessage = {
|
|
2508
|
-
role: "bashExecution",
|
|
2509
|
-
command,
|
|
2510
|
-
output: result.output,
|
|
2511
|
-
exitCode: result.exitCode,
|
|
2512
|
-
cancelled: result.cancelled,
|
|
2513
|
-
truncated: result.truncated,
|
|
2514
|
-
fullOutputPath: result.fullOutputPath,
|
|
2515
|
-
timestamp: Date.now(),
|
|
2516
|
-
excludeFromContext: options?.excludeFromContext,
|
|
2517
|
-
};
|
|
2518
|
-
// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
|
|
2519
|
-
if (this.isStreaming) {
|
|
2520
|
-
// Queue for later - will be flushed on agent_end
|
|
2521
|
-
this._pendingBashMessages.push(bashMessage);
|
|
2522
|
-
}
|
|
2523
|
-
else {
|
|
2524
|
-
// Add to agent state immediately
|
|
2525
|
-
this.agent.state.messages.push(bashMessage);
|
|
2526
|
-
// Save to session
|
|
2527
|
-
this.sessionManager.appendMessage(bashMessage);
|
|
2726
|
+
unsub();
|
|
2528
2727
|
}
|
|
2728
|
+
return resultText;
|
|
2529
2729
|
}
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2730
|
+
async callLLMStructured(options) {
|
|
2731
|
+
const maxRetries = options.maxRetries ?? 0;
|
|
2732
|
+
let lastError;
|
|
2733
|
+
const schemaJson = JSON.stringify(options.schema);
|
|
2734
|
+
const structuredSystemPrompt = (options.systemPrompt ?? "") +
|
|
2735
|
+
`\n\nRespond with valid JSON matching this schema:\n${schemaJson}\n\nRespond with JSON only, no markdown.`;
|
|
2736
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
2737
|
+
const messages = attempt === 0
|
|
2738
|
+
? options.messages
|
|
2739
|
+
: [
|
|
2740
|
+
...options.messages,
|
|
2741
|
+
{ role: "assistant", content: lastError?.raw ?? "" },
|
|
2742
|
+
{
|
|
2743
|
+
role: "user",
|
|
2744
|
+
content: `Your previous response was invalid: ${lastError?.message}. Please respond with valid JSON matching the schema.`,
|
|
2745
|
+
},
|
|
2746
|
+
];
|
|
2747
|
+
const raw = await this.callLLM({
|
|
2748
|
+
...options,
|
|
2749
|
+
systemPrompt: structuredSystemPrompt,
|
|
2750
|
+
messages,
|
|
2751
|
+
});
|
|
2752
|
+
try {
|
|
2753
|
+
const cleaned = stripMarkdownCodeBlock(raw);
|
|
2754
|
+
const parsed = JSON.parse(cleaned);
|
|
2755
|
+
const check = Compile(options.schema);
|
|
2756
|
+
const coerced = Value.Convert(options.schema, parsed);
|
|
2757
|
+
if (!check.Check(coerced)) {
|
|
2758
|
+
const errors = check
|
|
2759
|
+
.Errors(coerced)
|
|
2760
|
+
.map((e) => `${e.instancePath}: ${e.message}`)
|
|
2761
|
+
.join("; ");
|
|
2762
|
+
const err = new Error(`Schema validation failed: ${errors}`);
|
|
2763
|
+
err.raw = raw;
|
|
2764
|
+
err.reason = "schema_validation";
|
|
2765
|
+
lastError = err;
|
|
2766
|
+
if (attempt >= maxRetries)
|
|
2767
|
+
throw err;
|
|
2768
|
+
continue;
|
|
2769
|
+
}
|
|
2770
|
+
return coerced;
|
|
2771
|
+
}
|
|
2772
|
+
catch (e) {
|
|
2773
|
+
if (e instanceof SyntaxError) {
|
|
2774
|
+
const err = new Error(`JSON parse failed: ${e.message}`);
|
|
2775
|
+
err.raw = raw;
|
|
2776
|
+
err.reason = "json_parse";
|
|
2777
|
+
lastError = err;
|
|
2778
|
+
if (attempt >= maxRetries)
|
|
2779
|
+
throw err;
|
|
2780
|
+
continue;
|
|
2781
|
+
}
|
|
2782
|
+
if (e.reason) {
|
|
2783
|
+
lastError = e;
|
|
2784
|
+
if (attempt >= maxRetries)
|
|
2785
|
+
throw lastError;
|
|
2786
|
+
continue;
|
|
2787
|
+
}
|
|
2788
|
+
throw e;
|
|
2789
|
+
}
|
|
2556
2790
|
}
|
|
2557
|
-
|
|
2558
|
-
}
|
|
2559
|
-
// =========================================================================
|
|
2560
|
-
// Session Management
|
|
2561
|
-
// =========================================================================
|
|
2562
|
-
/**
|
|
2563
|
-
* Set a display name for the current session.
|
|
2564
|
-
*/
|
|
2565
|
-
setSessionName(name) {
|
|
2566
|
-
this.sessionManager.appendSessionInfo(name);
|
|
2791
|
+
throw lastError ?? new Error("callLLMStructured failed");
|
|
2567
2792
|
}
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
* @param targetId The entry ID to navigate to
|
|
2576
|
-
* @param options.summarize Whether user wants to summarize abandoned branch
|
|
2577
|
-
* @param options.customInstructions Custom instructions for summarizer
|
|
2578
|
-
* @param options.replaceInstructions If true, customInstructions replaces the default prompt
|
|
2579
|
-
* @param options.label Label to attach to the branch summary entry
|
|
2580
|
-
* @returns Result with editorText (if user message) and cancelled status
|
|
2581
|
-
*/
|
|
2582
|
-
async navigateTree(targetId, options = {}) {
|
|
2583
|
-
const oldLeafId = this.sessionManager.getLeafId();
|
|
2584
|
-
// No-op if already at target
|
|
2585
|
-
if (targetId === oldLeafId) {
|
|
2586
|
-
return { cancelled: false };
|
|
2793
|
+
async forkAgent(promptText, options) {
|
|
2794
|
+
const model = await this._resolveOptionalModel(options?.model);
|
|
2795
|
+
if (!model)
|
|
2796
|
+
throw new Error("No model selected");
|
|
2797
|
+
const auth = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
2798
|
+
if (!auth?.ok) {
|
|
2799
|
+
throw new Error("error" in auth ? auth.error : `No API key configured for ${model.provider}`);
|
|
2587
2800
|
}
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
throw new Error("No model available for summarization");
|
|
2801
|
+
if (!auth.apiKey) {
|
|
2802
|
+
throw new Error(`No API key configured for ${model.provider}`);
|
|
2591
2803
|
}
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2804
|
+
if (options?.signal?.aborted)
|
|
2805
|
+
throw new Error("Aborted");
|
|
2806
|
+
const opts = options ?? {};
|
|
2807
|
+
let toolNames = opts.tools ?? ["read", "grep", "find", "ls"];
|
|
2808
|
+
if (opts.bash === "deny") {
|
|
2809
|
+
toolNames = toolNames.filter((t) => t !== "bash");
|
|
2595
2810
|
}
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
targetId,
|
|
2604
|
-
oldLeafId,
|
|
2605
|
-
commonAncestorId,
|
|
2606
|
-
entriesToSummarize,
|
|
2607
|
-
userWantsSummary: options.summarize ?? false,
|
|
2608
|
-
customInstructions,
|
|
2609
|
-
replaceInstructions,
|
|
2610
|
-
label,
|
|
2611
|
-
};
|
|
2612
|
-
// Set up abort controller for summarization
|
|
2613
|
-
this._branchSummaryAbortController = new AbortController();
|
|
2614
|
-
let extensionSummary;
|
|
2615
|
-
let fromExtension = false;
|
|
2616
|
-
// Emit session_before_tree event
|
|
2617
|
-
if (this._extensionRunner.hasHandlers("session_before_tree")) {
|
|
2618
|
-
const result = (await this._extensionRunner.emit({
|
|
2619
|
-
type: "session_before_tree",
|
|
2620
|
-
preparation,
|
|
2621
|
-
signal: this._branchSummaryAbortController.signal,
|
|
2622
|
-
}));
|
|
2623
|
-
if (result?.cancel) {
|
|
2624
|
-
return { cancelled: true };
|
|
2625
|
-
}
|
|
2626
|
-
if (result?.summary && options.summarize) {
|
|
2627
|
-
extensionSummary = result.summary;
|
|
2628
|
-
fromExtension = true;
|
|
2629
|
-
}
|
|
2630
|
-
// Allow extensions to override instructions and label
|
|
2631
|
-
if (result?.customInstructions !== undefined) {
|
|
2632
|
-
customInstructions = result.customInstructions;
|
|
2633
|
-
}
|
|
2634
|
-
if (result?.replaceInstructions !== undefined) {
|
|
2635
|
-
replaceInstructions = result.replaceInstructions;
|
|
2811
|
+
const toolInstances = toolNames
|
|
2812
|
+
.map((name) => {
|
|
2813
|
+
try {
|
|
2814
|
+
const registered = this._toolRegistry.get(name);
|
|
2815
|
+
if (registered)
|
|
2816
|
+
return registered;
|
|
2817
|
+
return createTool(name, this._cwd);
|
|
2636
2818
|
}
|
|
2637
|
-
|
|
2638
|
-
|
|
2819
|
+
catch {
|
|
2820
|
+
return undefined;
|
|
2639
2821
|
}
|
|
2640
|
-
}
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2822
|
+
})
|
|
2823
|
+
.filter((t) => t !== undefined);
|
|
2824
|
+
const effectiveSystemPrompt = opts.inheritSystemPrompt
|
|
2825
|
+
? (this.agent.state.systemPrompt ?? opts.systemPrompt ?? "")
|
|
2826
|
+
: (opts.systemPrompt ?? "");
|
|
2827
|
+
const messages = opts.shareContext ? [...this.agent.state.messages] : [];
|
|
2828
|
+
const maxTurns = opts.maxTurns ?? 5;
|
|
2829
|
+
let turnCount = 0;
|
|
2830
|
+
const forkedAgent = new Agent({
|
|
2831
|
+
getApiKey: () => auth.apiKey,
|
|
2832
|
+
initialState: {
|
|
2833
|
+
systemPrompt: effectiveSystemPrompt,
|
|
2649
2834
|
model,
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2835
|
+
thinkingLevel: "off",
|
|
2836
|
+
tools: toolInstances,
|
|
2837
|
+
messages,
|
|
2838
|
+
},
|
|
2839
|
+
sessionId: opts.shareContext ? this.agent.sessionId : undefined,
|
|
2840
|
+
});
|
|
2841
|
+
let resultText = "";
|
|
2842
|
+
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
2843
|
+
const abortHandler = opts.signal ? () => forkedAgent.abort() : undefined;
|
|
2844
|
+
if (abortHandler && opts.signal) {
|
|
2845
|
+
opts.signal.addEventListener("abort", abortHandler, { once: true });
|
|
2846
|
+
}
|
|
2847
|
+
const unsub = forkedAgent.subscribe((event) => {
|
|
2848
|
+
if (event.type === "turn_end") {
|
|
2849
|
+
turnCount++;
|
|
2850
|
+
if (turnCount >= maxTurns) {
|
|
2851
|
+
forkedAgent.abort();
|
|
2852
|
+
}
|
|
2660
2853
|
}
|
|
2661
|
-
if (
|
|
2662
|
-
|
|
2854
|
+
if (event.type === "message_end") {
|
|
2855
|
+
const msg = event.message;
|
|
2856
|
+
if (msg.role === "assistant") {
|
|
2857
|
+
const asst = msg;
|
|
2858
|
+
const content = asst.content;
|
|
2859
|
+
if (Array.isArray(content)) {
|
|
2860
|
+
resultText = content
|
|
2861
|
+
.filter((c) => c.type === "text")
|
|
2862
|
+
.map((c) => c.text)
|
|
2863
|
+
.join("\n");
|
|
2864
|
+
}
|
|
2865
|
+
if (asst.usage) {
|
|
2866
|
+
usage.input = asst.usage.input ?? 0;
|
|
2867
|
+
usage.output = asst.usage.output ?? 0;
|
|
2868
|
+
usage.cacheRead = asst.usage.cacheRead ?? 0;
|
|
2869
|
+
usage.cacheWrite = asst.usage.cacheWrite ?? 0;
|
|
2870
|
+
if (model.cost) {
|
|
2871
|
+
usage.cost =
|
|
2872
|
+
(usage.input * model.cost.input +
|
|
2873
|
+
usage.output * model.cost.output +
|
|
2874
|
+
usage.cacheRead * model.cost.cacheRead +
|
|
2875
|
+
usage.cacheWrite * model.cost.cacheWrite) /
|
|
2876
|
+
1_000_000;
|
|
2877
|
+
}
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2663
2880
|
}
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
summaryText = extensionSummary.summary;
|
|
2672
|
-
summaryDetails = extensionSummary.details;
|
|
2673
|
-
}
|
|
2674
|
-
// Determine the new leaf position based on target type
|
|
2675
|
-
let newLeafId;
|
|
2676
|
-
let editorText;
|
|
2677
|
-
if (targetEntry.type === "message" && targetEntry.message.role === "user") {
|
|
2678
|
-
// User message: leaf = parent (null if root), text goes to editor
|
|
2679
|
-
newLeafId = targetEntry.parentId;
|
|
2680
|
-
editorText = this._extractUserMessageText(targetEntry.message.content);
|
|
2681
|
-
}
|
|
2682
|
-
else if (targetEntry.type === "custom_message") {
|
|
2683
|
-
// Custom message: leaf = parent (null if root), text goes to editor
|
|
2684
|
-
newLeafId = targetEntry.parentId;
|
|
2685
|
-
editorText =
|
|
2686
|
-
typeof targetEntry.content === "string"
|
|
2687
|
-
? targetEntry.content
|
|
2688
|
-
: targetEntry.content
|
|
2689
|
-
.filter((c) => c.type === "text")
|
|
2690
|
-
.map((c) => c.text)
|
|
2691
|
-
.join("");
|
|
2692
|
-
}
|
|
2693
|
-
else {
|
|
2694
|
-
// Non-user message: leaf = selected node
|
|
2695
|
-
newLeafId = targetId;
|
|
2881
|
+
});
|
|
2882
|
+
try {
|
|
2883
|
+
await forkedAgent.prompt({
|
|
2884
|
+
role: "user",
|
|
2885
|
+
content: [{ type: "text", text: promptText }],
|
|
2886
|
+
timestamp: Date.now(),
|
|
2887
|
+
});
|
|
2696
2888
|
}
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
// Create summary at target position (can be null for root)
|
|
2702
|
-
const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
|
|
2703
|
-
summaryEntry = this.sessionManager.getEntry(summaryId);
|
|
2704
|
-
// Attach label to the summary entry
|
|
2705
|
-
if (label) {
|
|
2706
|
-
this.sessionManager.appendLabelChange(summaryId, label);
|
|
2889
|
+
finally {
|
|
2890
|
+
unsub();
|
|
2891
|
+
if (abortHandler && opts.signal) {
|
|
2892
|
+
opts.signal.removeEventListener("abort", abortHandler);
|
|
2707
2893
|
}
|
|
2708
2894
|
}
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
this.agent.state.messages = sessionContext.messages;
|
|
2724
|
-
// Emit session_tree event
|
|
2725
|
-
await this._extensionRunner.emit({
|
|
2726
|
-
type: "session_tree",
|
|
2727
|
-
newLeafId: this.sessionManager.getLeafId(),
|
|
2728
|
-
oldLeafId,
|
|
2729
|
-
summaryEntry,
|
|
2730
|
-
fromExtension: summaryText ? fromExtension : undefined,
|
|
2731
|
-
skipFiles: options.skipFiles,
|
|
2732
|
-
});
|
|
2733
|
-
// Emit to custom tools
|
|
2734
|
-
this._branchSummaryAbortController = undefined;
|
|
2735
|
-
return { editorText, cancelled: false, summaryEntry };
|
|
2895
|
+
return { text: resultText, usage };
|
|
2896
|
+
}
|
|
2897
|
+
background(fn) {
|
|
2898
|
+
const controller = new AbortController();
|
|
2899
|
+
const promise = fn(controller.signal);
|
|
2900
|
+
const task = {
|
|
2901
|
+
id: randomUUID(),
|
|
2902
|
+
signal: controller.signal,
|
|
2903
|
+
promise: promise,
|
|
2904
|
+
cancel: () => controller.abort(),
|
|
2905
|
+
};
|
|
2906
|
+
this._backgroundTasks.add(task);
|
|
2907
|
+
promise.finally(() => this._backgroundTasks.delete(task));
|
|
2908
|
+
return task;
|
|
2736
2909
|
}
|
|
2737
2910
|
async previewRollback(targetId) {
|
|
2738
2911
|
const oldLeafId = this.sessionManager.getLeafId();
|
|
@@ -2761,226 +2934,5 @@ export class AgentSession {
|
|
|
2761
2934
|
deleted: [],
|
|
2762
2935
|
});
|
|
2763
2936
|
}
|
|
2764
|
-
/**
|
|
2765
|
-
* Get all user messages from session for fork selector.
|
|
2766
|
-
*/
|
|
2767
|
-
getUserMessagesForForking() {
|
|
2768
|
-
const entries = this.sessionManager.getEntries();
|
|
2769
|
-
const result = [];
|
|
2770
|
-
for (const entry of entries) {
|
|
2771
|
-
if (entry.type !== "message")
|
|
2772
|
-
continue;
|
|
2773
|
-
if (entry.message.role !== "user")
|
|
2774
|
-
continue;
|
|
2775
|
-
const text = this._extractUserMessageText(entry.message.content);
|
|
2776
|
-
if (text) {
|
|
2777
|
-
result.push({ entryId: entry.id, text });
|
|
2778
|
-
}
|
|
2779
|
-
}
|
|
2780
|
-
return result;
|
|
2781
|
-
}
|
|
2782
|
-
_extractUserMessageText(content) {
|
|
2783
|
-
if (typeof content === "string")
|
|
2784
|
-
return content;
|
|
2785
|
-
if (Array.isArray(content)) {
|
|
2786
|
-
return content
|
|
2787
|
-
.filter((c) => c.type === "text")
|
|
2788
|
-
.map((c) => c.text)
|
|
2789
|
-
.join("");
|
|
2790
|
-
}
|
|
2791
|
-
return "";
|
|
2792
|
-
}
|
|
2793
|
-
/**
|
|
2794
|
-
* Get session statistics.
|
|
2795
|
-
*/
|
|
2796
|
-
getSessionStats() {
|
|
2797
|
-
const state = this.state;
|
|
2798
|
-
const userMessages = state.messages.filter((m) => m.role === "user").length;
|
|
2799
|
-
const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
|
|
2800
|
-
const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
|
|
2801
|
-
let toolCalls = 0;
|
|
2802
|
-
let totalInput = 0;
|
|
2803
|
-
let totalOutput = 0;
|
|
2804
|
-
let totalCacheRead = 0;
|
|
2805
|
-
let totalCacheWrite = 0;
|
|
2806
|
-
let totalCost = 0;
|
|
2807
|
-
for (const message of state.messages) {
|
|
2808
|
-
if (message.role === "assistant") {
|
|
2809
|
-
const assistantMsg = message;
|
|
2810
|
-
toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
|
|
2811
|
-
totalInput += assistantMsg.usage.input;
|
|
2812
|
-
totalOutput += assistantMsg.usage.output;
|
|
2813
|
-
totalCacheRead += assistantMsg.usage.cacheRead;
|
|
2814
|
-
totalCacheWrite += assistantMsg.usage.cacheWrite;
|
|
2815
|
-
totalCost += assistantMsg.usage.cost.total;
|
|
2816
|
-
}
|
|
2817
|
-
}
|
|
2818
|
-
return {
|
|
2819
|
-
sessionFile: this.sessionFile,
|
|
2820
|
-
sessionId: this.sessionId,
|
|
2821
|
-
userMessages,
|
|
2822
|
-
assistantMessages,
|
|
2823
|
-
toolCalls,
|
|
2824
|
-
toolResults,
|
|
2825
|
-
totalMessages: state.messages.length,
|
|
2826
|
-
tokens: {
|
|
2827
|
-
input: totalInput,
|
|
2828
|
-
output: totalOutput,
|
|
2829
|
-
cacheRead: totalCacheRead,
|
|
2830
|
-
cacheWrite: totalCacheWrite,
|
|
2831
|
-
total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
|
|
2832
|
-
},
|
|
2833
|
-
cost: totalCost,
|
|
2834
|
-
contextUsage: this.getContextUsage(),
|
|
2835
|
-
};
|
|
2836
|
-
}
|
|
2837
|
-
getContextUsage() {
|
|
2838
|
-
const model = this.model;
|
|
2839
|
-
if (!model)
|
|
2840
|
-
return undefined;
|
|
2841
|
-
const contextWindow = model.contextWindow ?? 0;
|
|
2842
|
-
if (contextWindow <= 0)
|
|
2843
|
-
return undefined;
|
|
2844
|
-
const branchEntries = this.sessionManager.getBranch();
|
|
2845
|
-
const latestCompaction = getLatestCompactionEntry(branchEntries);
|
|
2846
|
-
if (latestCompaction) {
|
|
2847
|
-
const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
|
|
2848
|
-
for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
|
|
2849
|
-
const entry = branchEntries[i];
|
|
2850
|
-
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
2851
|
-
const assistant = entry.message;
|
|
2852
|
-
if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
|
|
2853
|
-
const contextTokens = calculateContextTokens(assistant.usage);
|
|
2854
|
-
if (contextTokens > 0) {
|
|
2855
|
-
const percent = (contextTokens / contextWindow) * 100;
|
|
2856
|
-
return { tokens: contextTokens, contextWindow, percent };
|
|
2857
|
-
}
|
|
2858
|
-
}
|
|
2859
|
-
break;
|
|
2860
|
-
}
|
|
2861
|
-
}
|
|
2862
|
-
}
|
|
2863
|
-
const estimate = estimateContextTokens(this.messages);
|
|
2864
|
-
if (latestCompaction && estimate.lastUsageIndex !== null) {
|
|
2865
|
-
const usageMsg = this.messages[estimate.lastUsageIndex];
|
|
2866
|
-
if (usageMsg?.role === "assistant" &&
|
|
2867
|
-
usageMsg.timestamp <= new Date(latestCompaction.timestamp).getTime()) {
|
|
2868
|
-
let estimated = 0;
|
|
2869
|
-
for (const message of this.messages) {
|
|
2870
|
-
estimated += estimateTokens(message);
|
|
2871
|
-
}
|
|
2872
|
-
const fallbackPercent = contextWindow > 0 ? (estimated / contextWindow) * 100 : 0;
|
|
2873
|
-
return { tokens: estimated, contextWindow, percent: fallbackPercent };
|
|
2874
|
-
}
|
|
2875
|
-
}
|
|
2876
|
-
const percent = contextWindow > 0 ? (estimate.tokens / contextWindow) * 100 : 0;
|
|
2877
|
-
return {
|
|
2878
|
-
tokens: estimate.tokens,
|
|
2879
|
-
contextWindow,
|
|
2880
|
-
percent,
|
|
2881
|
-
};
|
|
2882
|
-
}
|
|
2883
|
-
/**
|
|
2884
|
-
* Export session to HTML.
|
|
2885
|
-
* @param outputPath Optional output path (defaults to session directory)
|
|
2886
|
-
* @returns Path to exported file
|
|
2887
|
-
*/
|
|
2888
|
-
async exportToHtml(outputPath) {
|
|
2889
|
-
const themeName = this.settingsManager.getTheme();
|
|
2890
|
-
// Create tool renderer if we have an extension runner (for custom tool HTML rendering)
|
|
2891
|
-
const toolRenderer = createToolHtmlRenderer({
|
|
2892
|
-
getToolDefinition: (name) => this.getToolDefinition(name),
|
|
2893
|
-
theme,
|
|
2894
|
-
cwd: this.sessionManager.getCwd(),
|
|
2895
|
-
});
|
|
2896
|
-
return await exportSessionToHtml(this.sessionManager, this.state, {
|
|
2897
|
-
outputPath,
|
|
2898
|
-
themeName,
|
|
2899
|
-
toolRenderer,
|
|
2900
|
-
});
|
|
2901
|
-
}
|
|
2902
|
-
/**
|
|
2903
|
-
* Export the current session branch to a JSONL file.
|
|
2904
|
-
* Writes the session header followed by all entries on the current branch path.
|
|
2905
|
-
* @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
|
|
2906
|
-
* @returns The resolved output file path.
|
|
2907
|
-
*/
|
|
2908
|
-
exportToJsonl(outputPath) {
|
|
2909
|
-
const filePath = resolve(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`);
|
|
2910
|
-
const dir = dirname(filePath);
|
|
2911
|
-
if (!existsSync(dir)) {
|
|
2912
|
-
mkdirSync(dir, { recursive: true });
|
|
2913
|
-
}
|
|
2914
|
-
const header = {
|
|
2915
|
-
type: "session",
|
|
2916
|
-
version: CURRENT_SESSION_VERSION,
|
|
2917
|
-
id: this.sessionManager.getSessionId(),
|
|
2918
|
-
timestamp: new Date().toISOString(),
|
|
2919
|
-
cwd: this.sessionManager.getCwd(),
|
|
2920
|
-
};
|
|
2921
|
-
const branchEntries = this.sessionManager.getBranch();
|
|
2922
|
-
const lines = [JSON.stringify(header)];
|
|
2923
|
-
// Re-chain parentIds to form a linear sequence
|
|
2924
|
-
let prevId = null;
|
|
2925
|
-
for (const entry of branchEntries) {
|
|
2926
|
-
const linear = { ...entry, parentId: prevId };
|
|
2927
|
-
lines.push(JSON.stringify(linear));
|
|
2928
|
-
prevId = entry.id;
|
|
2929
|
-
}
|
|
2930
|
-
writeFileSync(filePath, `${lines.join("\n")}\n`);
|
|
2931
|
-
return filePath;
|
|
2932
|
-
}
|
|
2933
|
-
// =========================================================================
|
|
2934
|
-
// Utilities
|
|
2935
|
-
// =========================================================================
|
|
2936
|
-
/**
|
|
2937
|
-
* Get text content of last assistant message.
|
|
2938
|
-
* Useful for /copy command.
|
|
2939
|
-
* @returns Text content, or undefined if no assistant message exists
|
|
2940
|
-
*/
|
|
2941
|
-
getLastAssistantText() {
|
|
2942
|
-
const lastAssistant = this.messages
|
|
2943
|
-
.slice()
|
|
2944
|
-
.reverse()
|
|
2945
|
-
.find((m) => {
|
|
2946
|
-
if (m.role !== "assistant")
|
|
2947
|
-
return false;
|
|
2948
|
-
const msg = m;
|
|
2949
|
-
// Skip aborted messages with no content
|
|
2950
|
-
if (msg.stopReason === "aborted" && msg.content.length === 0)
|
|
2951
|
-
return false;
|
|
2952
|
-
return true;
|
|
2953
|
-
});
|
|
2954
|
-
if (!lastAssistant)
|
|
2955
|
-
return undefined;
|
|
2956
|
-
let text = "";
|
|
2957
|
-
for (const content of lastAssistant.content) {
|
|
2958
|
-
if (content.type === "text") {
|
|
2959
|
-
text += content.text;
|
|
2960
|
-
}
|
|
2961
|
-
}
|
|
2962
|
-
return text.trim() || undefined;
|
|
2963
|
-
}
|
|
2964
|
-
// =========================================================================
|
|
2965
|
-
// Extension System
|
|
2966
|
-
// =========================================================================
|
|
2967
|
-
createReplacedSessionContext() {
|
|
2968
|
-
const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
|
|
2969
|
-
context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
|
|
2970
|
-
context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
|
|
2971
|
-
return context;
|
|
2972
|
-
}
|
|
2973
|
-
/**
|
|
2974
|
-
* Check if extensions have handlers for a specific event type.
|
|
2975
|
-
*/
|
|
2976
|
-
hasExtensionHandlers(eventType) {
|
|
2977
|
-
return this._extensionRunner.hasHandlers(eventType);
|
|
2978
|
-
}
|
|
2979
|
-
/**
|
|
2980
|
-
* Get the extension runner (for setting UI context and error handlers).
|
|
2981
|
-
*/
|
|
2982
|
-
get extensionRunner() {
|
|
2983
|
-
return this._extensionRunner;
|
|
2984
|
-
}
|
|
2985
2937
|
}
|
|
2986
2938
|
//# sourceMappingURL=agent-session.js.map
|