@dyyz1993/pi-coding-agent 0.70.6 → 0.74.4
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 +25 -26
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1042 -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 +21 -3
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +51 -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,23 @@ 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";
|
|
34
36
|
import { resolveModelAlias } from "./model-resolver.js";
|
|
35
37
|
import { expandPromptTemplate } from "./prompt-templates.js";
|
|
36
38
|
import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
|
|
@@ -60,8 +62,6 @@ export function parseSkillBlock(text) {
|
|
|
60
62
|
// ============================================================================
|
|
61
63
|
/** Standard thinking levels */
|
|
62
64
|
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
65
|
// ============================================================================
|
|
66
66
|
// AgentSession Class
|
|
67
67
|
// ============================================================================
|
|
@@ -97,7 +97,6 @@ export class AgentSession {
|
|
|
97
97
|
// Extension system
|
|
98
98
|
_extensionRunner;
|
|
99
99
|
_turnIndex = 0;
|
|
100
|
-
_toolCallVariables;
|
|
101
100
|
_resourceLoader;
|
|
102
101
|
_customTools;
|
|
103
102
|
_baseToolDefinitions = new Map();
|
|
@@ -117,6 +116,7 @@ export class AgentSession {
|
|
|
117
116
|
_backgroundTasks = new Set();
|
|
118
117
|
// Model registry for API key resolution
|
|
119
118
|
_modelRegistry;
|
|
119
|
+
_fileSnapshotManager = null;
|
|
120
120
|
_tierModels = {};
|
|
121
121
|
// Tool registry for extension getTools/setTools
|
|
122
122
|
_toolRegistry = new Map();
|
|
@@ -153,9 +153,28 @@ export class AgentSession {
|
|
|
153
153
|
get modelRegistry() {
|
|
154
154
|
return this._modelRegistry;
|
|
155
155
|
}
|
|
156
|
+
get fileSnapshotManager() {
|
|
157
|
+
return this._fileSnapshotManager;
|
|
158
|
+
}
|
|
159
|
+
_initFileSnapshotManager() {
|
|
160
|
+
try {
|
|
161
|
+
const storeRoot = join(getAgentDir(), "file-store");
|
|
162
|
+
const cwd = this._cwd;
|
|
163
|
+
const git = InternalGit.createForProject(storeRoot, cwd);
|
|
164
|
+
this._fileSnapshotManager = new FileSnapshotManager(git);
|
|
165
|
+
this._extensionRunner.setFileSnapshotManager(this._fileSnapshotManager);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
this._fileSnapshotManager = null;
|
|
169
|
+
this._extensionRunner.setFileSnapshotManager(null);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
156
172
|
async _getRequiredRequestAuth(model) {
|
|
157
173
|
const result = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
158
174
|
if (!result.ok) {
|
|
175
|
+
if (result.error.startsWith("No API key found")) {
|
|
176
|
+
throw new Error(formatNoApiKeyFoundMessage(model.provider));
|
|
177
|
+
}
|
|
159
178
|
throw new Error(result.error);
|
|
160
179
|
}
|
|
161
180
|
if (result.apiKey) {
|
|
@@ -167,8 +186,7 @@ export class AgentSession {
|
|
|
167
186
|
`Credentials may have expired or network is unavailable. ` +
|
|
168
187
|
`Run '/login ${model.provider}' to re-authenticate.`);
|
|
169
188
|
}
|
|
170
|
-
throw new Error(
|
|
171
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
|
|
189
|
+
throw new Error(formatNoApiKeyFoundMessage(model.provider));
|
|
172
190
|
}
|
|
173
191
|
/**
|
|
174
192
|
* Install tool hooks once on the Agent instance.
|
|
@@ -191,7 +209,6 @@ export class AgentSession {
|
|
|
191
209
|
toolName: toolCall.name,
|
|
192
210
|
toolCallId: toolCall.id,
|
|
193
211
|
input: args,
|
|
194
|
-
variables: this._toolCallVariables,
|
|
195
212
|
});
|
|
196
213
|
}
|
|
197
214
|
catch (err) {
|
|
@@ -303,21 +320,24 @@ export class AgentSession {
|
|
|
303
320
|
}
|
|
304
321
|
}
|
|
305
322
|
}
|
|
306
|
-
//
|
|
307
|
-
|
|
323
|
+
// Emit to extensions first
|
|
324
|
+
await this._emitExtensionEvent(event);
|
|
325
|
+
// Notify all listeners
|
|
326
|
+
this._emit(event);
|
|
327
|
+
// Handle session persistence
|
|
308
328
|
if (event.type === "message_end") {
|
|
309
|
-
|
|
329
|
+
// Check if this is a custom message from extensions
|
|
310
330
|
if (event.message.role === "custom") {
|
|
311
|
-
|
|
331
|
+
// Persist as CustomMessageEntry
|
|
332
|
+
this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
|
|
312
333
|
}
|
|
313
334
|
else if (event.message.role === "user" ||
|
|
314
335
|
event.message.role === "assistant" ||
|
|
315
336
|
event.message.role === "toolResult") {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
if (entryId) {
|
|
319
|
-
event.entryId = entryId;
|
|
337
|
+
// Regular LLM message - persist as SessionMessageEntry
|
|
338
|
+
this.sessionManager.appendMessage(event.message);
|
|
320
339
|
}
|
|
340
|
+
// Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
|
|
321
341
|
// Track assistant message for auto-compaction (checked on agent_end)
|
|
322
342
|
if (event.message.role === "assistant") {
|
|
323
343
|
this._lastAssistantMessage = event.message;
|
|
@@ -337,10 +357,6 @@ export class AgentSession {
|
|
|
337
357
|
}
|
|
338
358
|
}
|
|
339
359
|
}
|
|
340
|
-
// Emit to extensions first
|
|
341
|
-
await this._emitExtensionEvent(event);
|
|
342
|
-
// Notify all listeners
|
|
343
|
-
this._emit(event);
|
|
344
360
|
// Check auto-retry and auto-compaction after agent completes
|
|
345
361
|
if (event.type === "agent_end" && this._lastAssistantMessage) {
|
|
346
362
|
const msg = this._lastAssistantMessage;
|
|
@@ -384,6 +400,20 @@ export class AgentSession {
|
|
|
384
400
|
}
|
|
385
401
|
return undefined;
|
|
386
402
|
}
|
|
403
|
+
_replaceMessageInPlace(target, replacement) {
|
|
404
|
+
// Agent-core stores the finalized message object in its state before emitting message_end.
|
|
405
|
+
// SessionManager persistence happens later in _processAgentEvent() with event.message.
|
|
406
|
+
// Mutating this object in place keeps agent state, later turn/agent events, listeners,
|
|
407
|
+
// and the eventual SessionManager.appendMessage(event.message) persistence in sync.
|
|
408
|
+
if (target === replacement) {
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const targetRecord = target;
|
|
412
|
+
for (const key of Object.keys(targetRecord)) {
|
|
413
|
+
delete targetRecord[key];
|
|
414
|
+
}
|
|
415
|
+
Object.assign(targetRecord, replacement);
|
|
416
|
+
}
|
|
387
417
|
/** Emit extension events based on agent events */
|
|
388
418
|
async _emitExtensionEvent(event) {
|
|
389
419
|
if (event.type === "agent_start") {
|
|
@@ -430,9 +460,11 @@ export class AgentSession {
|
|
|
430
460
|
const extensionEvent = {
|
|
431
461
|
type: "message_end",
|
|
432
462
|
message: event.message,
|
|
433
|
-
entryId: event.entryId,
|
|
434
463
|
};
|
|
435
|
-
await this._extensionRunner.
|
|
464
|
+
const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
|
|
465
|
+
if (replacement) {
|
|
466
|
+
this._replaceMessageInPlace(event.message, replacement);
|
|
467
|
+
}
|
|
436
468
|
}
|
|
437
469
|
else if (event.type === "tool_execution_start") {
|
|
438
470
|
const extensionEvent = {
|
|
@@ -504,15 +536,10 @@ export class AgentSession {
|
|
|
504
536
|
* Call this when completely done with the session.
|
|
505
537
|
*/
|
|
506
538
|
dispose() {
|
|
507
|
-
this._extensionRunner.invalidate("This extension
|
|
508
|
-
this._sessionAbortController.abort();
|
|
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();
|
|
539
|
+
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().");
|
|
514
540
|
this._disconnectFromAgent();
|
|
515
541
|
this._eventListeners = [];
|
|
542
|
+
cleanupSessionResources(this.sessionId);
|
|
516
543
|
}
|
|
517
544
|
// =========================================================================
|
|
518
545
|
// Read-only State Access
|
|
@@ -530,25 +557,16 @@ export class AgentSession {
|
|
|
530
557
|
}
|
|
531
558
|
setTierModels(mapping) {
|
|
532
559
|
this._tierModels = { ...mapping };
|
|
560
|
+
this.sessionManager.appendTierModelsChange(mapping);
|
|
533
561
|
}
|
|
534
562
|
/** Current thinking level */
|
|
535
563
|
get thinkingLevel() {
|
|
536
564
|
return this.agent.state.thinkingLevel;
|
|
537
565
|
}
|
|
538
|
-
set toolCallVariables(vars) {
|
|
539
|
-
this._toolCallVariables = vars;
|
|
540
|
-
}
|
|
541
|
-
get toolCallVariables() {
|
|
542
|
-
return this._toolCallVariables;
|
|
543
|
-
}
|
|
544
566
|
/** Whether agent is currently streaming a response */
|
|
545
567
|
get isStreaming() {
|
|
546
568
|
return this.agent.state.isStreaming;
|
|
547
569
|
}
|
|
548
|
-
/** Signal that aborts on session shutdown */
|
|
549
|
-
get sessionSignal() {
|
|
550
|
-
return this._sessionAbortController.signal;
|
|
551
|
-
}
|
|
552
570
|
/** Current effective system prompt (includes any per-turn extension modifications) */
|
|
553
571
|
get systemPrompt() {
|
|
554
572
|
return this.agent.state.systemPrompt;
|
|
@@ -746,12 +764,11 @@ export class AgentSession {
|
|
|
746
764
|
if (!options?.streamingBehavior) {
|
|
747
765
|
throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
|
|
748
766
|
}
|
|
749
|
-
const { text: streamingText } = handleLargeInput(expandedText);
|
|
750
767
|
if (options.streamingBehavior === "followUp") {
|
|
751
|
-
await this._queueFollowUp(
|
|
768
|
+
await this._queueFollowUp(expandedText, currentImages);
|
|
752
769
|
}
|
|
753
770
|
else {
|
|
754
|
-
await this._queueSteer(
|
|
771
|
+
await this._queueSteer(expandedText, currentImages);
|
|
755
772
|
}
|
|
756
773
|
preflightResult?.(true);
|
|
757
774
|
return;
|
|
@@ -760,9 +777,7 @@ export class AgentSession {
|
|
|
760
777
|
this._flushPendingBashMessages();
|
|
761
778
|
// Validate model
|
|
762
779
|
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.");
|
|
780
|
+
throw new Error(formatNoModelSelectedMessage());
|
|
766
781
|
}
|
|
767
782
|
if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
|
|
768
783
|
const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
|
|
@@ -771,8 +786,7 @@ export class AgentSession {
|
|
|
771
786
|
`Credentials may have expired or network is unavailable. ` +
|
|
772
787
|
`Run '/login ${this.model.provider}' to re-authenticate.`);
|
|
773
788
|
}
|
|
774
|
-
throw new Error(
|
|
775
|
-
`Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`);
|
|
789
|
+
throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
|
|
776
790
|
}
|
|
777
791
|
// Check if we need to compact before sending (catches aborted responses)
|
|
778
792
|
const lastAssistant = this._findLastAssistantMessage();
|
|
@@ -781,10 +795,8 @@ export class AgentSession {
|
|
|
781
795
|
}
|
|
782
796
|
// Build messages array (custom message if any, then user message)
|
|
783
797
|
messages = [];
|
|
784
|
-
// Handle large input: save to temp file and replace with preview
|
|
785
|
-
const { text: finalText } = handleLargeInput(expandedText);
|
|
786
798
|
// Add user message
|
|
787
|
-
const userContent = [{ type: "text", text:
|
|
799
|
+
const userContent = [{ type: "text", text: expandedText }];
|
|
788
800
|
if (currentImages) {
|
|
789
801
|
userContent.push(...currentImages);
|
|
790
802
|
}
|
|
@@ -845,7 +857,7 @@ export class AgentSession {
|
|
|
845
857
|
if (!command)
|
|
846
858
|
return false;
|
|
847
859
|
// Get command context from extension runner (includes session control methods)
|
|
848
|
-
const ctx = this._extensionRunner.createCommandContext(
|
|
860
|
+
const ctx = this._extensionRunner.createCommandContext();
|
|
849
861
|
try {
|
|
850
862
|
await command.handler(args, ctx);
|
|
851
863
|
return true;
|
|
@@ -899,13 +911,14 @@ export class AgentSession {
|
|
|
899
911
|
* @throws Error if text is an extension command
|
|
900
912
|
*/
|
|
901
913
|
async steer(text, images) {
|
|
914
|
+
// Check for extension commands (cannot be queued)
|
|
902
915
|
if (text.startsWith("/")) {
|
|
903
916
|
this._throwIfExtensionCommand(text);
|
|
904
917
|
}
|
|
918
|
+
// Expand skill commands and prompt templates
|
|
905
919
|
let expandedText = this._expandSkillCommand(text);
|
|
906
920
|
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
907
|
-
|
|
908
|
-
await this._queueSteer(finalText, images);
|
|
921
|
+
await this._queueSteer(expandedText, images);
|
|
909
922
|
}
|
|
910
923
|
/**
|
|
911
924
|
* Queue a follow-up message to be processed after the agent finishes.
|
|
@@ -915,13 +928,14 @@ export class AgentSession {
|
|
|
915
928
|
* @throws Error if text is an extension command
|
|
916
929
|
*/
|
|
917
930
|
async followUp(text, images) {
|
|
931
|
+
// Check for extension commands (cannot be queued)
|
|
918
932
|
if (text.startsWith("/")) {
|
|
919
933
|
this._throwIfExtensionCommand(text);
|
|
920
934
|
}
|
|
935
|
+
// Expand skill commands and prompt templates
|
|
921
936
|
let expandedText = this._expandSkillCommand(text);
|
|
922
937
|
expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
|
|
923
|
-
|
|
924
|
-
await this._queueFollowUp(finalText, images);
|
|
938
|
+
await this._queueFollowUp(expandedText, images);
|
|
925
939
|
}
|
|
926
940
|
/**
|
|
927
941
|
* Internal: Queue a steering message (already expanded, no extension command check).
|
|
@@ -1074,6 +1088,10 @@ export class AgentSession {
|
|
|
1074
1088
|
get resourceLoader() {
|
|
1075
1089
|
return this._resourceLoader;
|
|
1076
1090
|
}
|
|
1091
|
+
/** Update the working directory for the session. */
|
|
1092
|
+
async setCwd(newCwd) {
|
|
1093
|
+
this._cwd = newCwd;
|
|
1094
|
+
}
|
|
1077
1095
|
/**
|
|
1078
1096
|
* Abort current operation and wait for agent to become idle.
|
|
1079
1097
|
*/
|
|
@@ -1181,13 +1199,20 @@ export class AgentSession {
|
|
|
1181
1199
|
const availableLevels = this.getAvailableThinkingLevels();
|
|
1182
1200
|
const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
|
|
1183
1201
|
// Only persist if actually changing
|
|
1184
|
-
const
|
|
1202
|
+
const previousLevel = this.agent.state.thinkingLevel;
|
|
1203
|
+
const isChanging = effectiveLevel !== previousLevel;
|
|
1185
1204
|
this.agent.state.thinkingLevel = effectiveLevel;
|
|
1186
1205
|
if (isChanging) {
|
|
1187
1206
|
this.sessionManager.appendThinkingLevelChange(effectiveLevel);
|
|
1188
1207
|
if (this.supportsThinking() || effectiveLevel !== "off") {
|
|
1189
1208
|
this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
|
|
1190
1209
|
}
|
|
1210
|
+
this._emit({ type: "thinking_level_changed", level: effectiveLevel });
|
|
1211
|
+
void this._extensionRunner.emit({
|
|
1212
|
+
type: "thinking_level_select",
|
|
1213
|
+
level: effectiveLevel,
|
|
1214
|
+
previousLevel,
|
|
1215
|
+
});
|
|
1191
1216
|
}
|
|
1192
1217
|
}
|
|
1193
1218
|
/**
|
|
@@ -1209,15 +1234,9 @@ export class AgentSession {
|
|
|
1209
1234
|
* The provider will clamp to what the specific model supports internally.
|
|
1210
1235
|
*/
|
|
1211
1236
|
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;
|
|
1237
|
+
if (!this.model)
|
|
1238
|
+
return THINKING_LEVELS;
|
|
1239
|
+
return getSupportedThinkingLevels(this.model);
|
|
1221
1240
|
}
|
|
1222
1241
|
/**
|
|
1223
1242
|
* Check if current model supports thinking/reasoning.
|
|
@@ -1234,24 +1253,8 @@ export class AgentSession {
|
|
|
1234
1253
|
}
|
|
1235
1254
|
return this.thinkingLevel;
|
|
1236
1255
|
}
|
|
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";
|
|
1256
|
+
_clampThinkingLevel(level, _availableLevels) {
|
|
1257
|
+
return this.model ? clampThinkingLevel(this.model, level) : "off";
|
|
1255
1258
|
}
|
|
1256
1259
|
// =========================================================================
|
|
1257
1260
|
// Queue Mode Management
|
|
@@ -1287,7 +1290,7 @@ export class AgentSession {
|
|
|
1287
1290
|
this._emit({ type: "compaction_start", reason: "manual" });
|
|
1288
1291
|
try {
|
|
1289
1292
|
if (!this.model) {
|
|
1290
|
-
throw new Error(
|
|
1293
|
+
throw new Error(formatNoModelSelectedMessage());
|
|
1291
1294
|
}
|
|
1292
1295
|
const { apiKey, headers } = await this._getRequiredRequestAuth(this.model);
|
|
1293
1296
|
const pathEntries = this.sessionManager.getBranch();
|
|
@@ -1597,11 +1600,6 @@ export class AgentSession {
|
|
|
1597
1600
|
tokensBefore,
|
|
1598
1601
|
details,
|
|
1599
1602
|
};
|
|
1600
|
-
let tokensAfter = 0;
|
|
1601
|
-
for (const msg of sessionContext.messages) {
|
|
1602
|
-
tokensAfter += estimateTokens(msg);
|
|
1603
|
-
}
|
|
1604
|
-
result.tokensAfter = tokensAfter;
|
|
1605
1603
|
this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
|
|
1606
1604
|
if (willRetry) {
|
|
1607
1605
|
const messages = this.agent.state.messages;
|
|
@@ -1663,13 +1661,10 @@ export class AgentSession {
|
|
|
1663
1661
|
}
|
|
1664
1662
|
if (bindings.registerChannel !== undefined) {
|
|
1665
1663
|
this._registerChannel = bindings.registerChannel;
|
|
1666
|
-
this._extensionRunner.flushPendingChannels(bindings.registerChannel);
|
|
1667
|
-
this._extensionRunner.updateRegisterChannel(bindings.registerChannel);
|
|
1668
1664
|
}
|
|
1669
1665
|
this._applyExtensionBindings(this._extensionRunner);
|
|
1670
1666
|
await this._extensionRunner.emit(this._sessionStartEvent);
|
|
1671
1667
|
await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
|
|
1672
|
-
await this._initMcpServers();
|
|
1673
1668
|
}
|
|
1674
1669
|
async extendResourcesFromExtensions(reason) {
|
|
1675
1670
|
if (!this._extensionRunner.hasHandlers("resources_discover")) {
|
|
@@ -1711,48 +1706,6 @@ export class AgentSession {
|
|
|
1711
1706
|
const name = base.replace(/\.(ts|js)$/, "");
|
|
1712
1707
|
return `extension:${name}`;
|
|
1713
1708
|
}
|
|
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
1709
|
_applyExtensionBindings(runner) {
|
|
1757
1710
|
runner.setUIContext(this._extensionUIContext);
|
|
1758
1711
|
runner.bindCommandContext(this._extensionCommandContextActions);
|
|
@@ -1860,7 +1813,7 @@ export class AgentSession {
|
|
|
1860
1813
|
}),
|
|
1861
1814
|
callLLM: (options) => this.callLLM(options),
|
|
1862
1815
|
callLLMStructured: (opts) => this.callLLMStructured(opts),
|
|
1863
|
-
forkAgent: (prompt,
|
|
1816
|
+
forkAgent: (prompt, opts) => this.forkAgent(prompt, opts),
|
|
1864
1817
|
background: (fn) => this.background(fn),
|
|
1865
1818
|
}, {
|
|
1866
1819
|
getModel: () => this.model,
|
|
@@ -1897,842 +1850,1036 @@ export class AgentSession {
|
|
|
1897
1850
|
},
|
|
1898
1851
|
});
|
|
1899
1852
|
}
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
const
|
|
1904
|
-
const
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1853
|
+
_refreshToolRegistry(options) {
|
|
1854
|
+
const previousRegistryNames = new Set(this._toolRegistry.keys());
|
|
1855
|
+
const previousActiveToolNames = this.getActiveToolNames();
|
|
1856
|
+
const allowedToolNames = this._allowedToolNames;
|
|
1857
|
+
const isAllowedTool = (name) => !allowedToolNames || allowedToolNames.has(name);
|
|
1858
|
+
const registeredTools = this._extensionRunner.getAllRegisteredTools();
|
|
1859
|
+
const allCustomTools = [
|
|
1860
|
+
...registeredTools,
|
|
1861
|
+
...this._customTools.map((definition) => ({
|
|
1862
|
+
definition,
|
|
1863
|
+
sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
|
|
1864
|
+
})),
|
|
1865
|
+
].filter((tool) => isAllowedTool(tool.definition.name));
|
|
1866
|
+
const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
|
|
1867
|
+
.filter(([name]) => isAllowedTool(name))
|
|
1868
|
+
.map(([name, definition]) => [
|
|
1869
|
+
name,
|
|
1870
|
+
{
|
|
1871
|
+
definition,
|
|
1872
|
+
sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
|
|
1873
|
+
},
|
|
1874
|
+
]));
|
|
1875
|
+
for (const tool of allCustomTools) {
|
|
1876
|
+
definitionRegistry.set(tool.definition.name, {
|
|
1877
|
+
definition: tool.definition,
|
|
1878
|
+
sourceInfo: tool.sourceInfo,
|
|
1879
|
+
});
|
|
1911
1880
|
}
|
|
1912
|
-
|
|
1913
|
-
|
|
1881
|
+
this._toolDefinitions = definitionRegistry;
|
|
1882
|
+
this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
|
|
1883
|
+
.map(({ definition }) => {
|
|
1884
|
+
const snippet = this._normalizePromptSnippet(definition.promptSnippet);
|
|
1885
|
+
return snippet ? [definition.name, snippet] : undefined;
|
|
1886
|
+
})
|
|
1887
|
+
.filter((entry) => entry !== undefined));
|
|
1888
|
+
this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
|
|
1889
|
+
.map(({ definition }) => {
|
|
1890
|
+
const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
|
|
1891
|
+
return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
|
|
1892
|
+
})
|
|
1893
|
+
.filter((entry) => entry !== undefined));
|
|
1894
|
+
const runner = this._extensionRunner;
|
|
1895
|
+
const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
|
|
1896
|
+
const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
|
|
1897
|
+
.filter((definition) => isAllowedTool(definition.name))
|
|
1898
|
+
.map((definition) => ({
|
|
1899
|
+
definition,
|
|
1900
|
+
sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
|
|
1901
|
+
})), runner);
|
|
1902
|
+
const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
|
|
1903
|
+
for (const tool of wrappedExtensionTools) {
|
|
1904
|
+
toolRegistry.set(tool.name, tool);
|
|
1914
1905
|
}
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1906
|
+
this._toolRegistry = toolRegistry;
|
|
1907
|
+
const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
|
|
1908
|
+
if (allowedToolNames) {
|
|
1909
|
+
for (const toolName of this._toolRegistry.keys()) {
|
|
1910
|
+
if (allowedToolNames.has(toolName)) {
|
|
1911
|
+
nextActiveToolNames.push(toolName);
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1918
1914
|
}
|
|
1919
|
-
if (
|
|
1920
|
-
const
|
|
1921
|
-
|
|
1915
|
+
else if (options?.includeAllExtensionTools) {
|
|
1916
|
+
for (const tool of wrappedExtensionTools) {
|
|
1917
|
+
nextActiveToolNames.push(tool.name);
|
|
1918
|
+
}
|
|
1922
1919
|
}
|
|
1923
|
-
if (
|
|
1924
|
-
|
|
1920
|
+
else if (!options?.activeToolNames) {
|
|
1921
|
+
for (const toolName of this._toolRegistry.keys()) {
|
|
1922
|
+
if (!previousRegistryNames.has(toolName)) {
|
|
1923
|
+
nextActiveToolNames.push(toolName);
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1925
1926
|
}
|
|
1926
|
-
|
|
1927
|
+
this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
|
|
1927
1928
|
}
|
|
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,
|
|
1929
|
+
_buildRuntime(options) {
|
|
1930
|
+
const autoResizeImages = this.settingsManager.getImageAutoResize();
|
|
1931
|
+
const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
|
|
1932
|
+
const shellPath = this.settingsManager.getShellPath();
|
|
1933
|
+
const baseToolDefinitions = this._baseToolsOverride
|
|
1934
|
+
? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
|
|
1935
|
+
name,
|
|
1936
|
+
createToolDefinitionFromAgentTool(tool),
|
|
1937
|
+
]))
|
|
1938
|
+
: createAllToolDefinitions(this._cwd, {
|
|
1939
|
+
read: { autoResizeImages },
|
|
1940
|
+
bash: { commandPrefix: shellCommandPrefix, shellPath },
|
|
1957
1941
|
});
|
|
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;
|
|
1942
|
+
this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
|
|
1943
|
+
const extensionsResult = this._resourceLoader.getExtensions();
|
|
1944
|
+
if (options.flagValues) {
|
|
1945
|
+
for (const [name, value] of options.flagValues) {
|
|
1946
|
+
extensionsResult.runtime.flagValues.set(name, value);
|
|
1973
1947
|
}
|
|
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
1948
|
}
|
|
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");
|
|
1949
|
+
this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry);
|
|
1950
|
+
if (this._extensionRunnerRef) {
|
|
1951
|
+
this._extensionRunnerRef.current = this._extensionRunner;
|
|
2004
1952
|
}
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
.join("\n");
|
|
2016
|
-
}
|
|
2017
|
-
}
|
|
2018
|
-
}
|
|
1953
|
+
this._bindExtensionCore(this._extensionRunner);
|
|
1954
|
+
this._applyExtensionBindings(this._extensionRunner);
|
|
1955
|
+
this._initFileSnapshotManager();
|
|
1956
|
+
const defaultActiveToolNames = this._baseToolsOverride
|
|
1957
|
+
? Object.keys(this._baseToolsOverride)
|
|
1958
|
+
: ["read", "bash", "edit", "write"];
|
|
1959
|
+
const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
|
|
1960
|
+
this._refreshToolRegistry({
|
|
1961
|
+
activeToolNames: baseActiveToolNames,
|
|
1962
|
+
includeAllExtensionTools: options.includeAllExtensionTools,
|
|
2019
1963
|
});
|
|
2020
|
-
try {
|
|
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;
|
|
2031
1964
|
}
|
|
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
|
-
}
|
|
1965
|
+
async reload() {
|
|
1966
|
+
const previousFlagValues = this._extensionRunner.getFlagValues();
|
|
1967
|
+
await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
|
|
1968
|
+
await this.settingsManager.reload();
|
|
1969
|
+
resetApiProviders();
|
|
1970
|
+
await this._resourceLoader.reload();
|
|
1971
|
+
this._buildRuntime({
|
|
1972
|
+
activeToolNames: this.getActiveToolNames(),
|
|
1973
|
+
flagValues: previousFlagValues,
|
|
1974
|
+
includeAllExtensionTools: true,
|
|
1975
|
+
});
|
|
1976
|
+
const hasBindings = this._extensionUIContext ||
|
|
1977
|
+
this._extensionCommandContextActions ||
|
|
1978
|
+
this._extensionShutdownHandler ||
|
|
1979
|
+
this._extensionErrorListener;
|
|
1980
|
+
if (hasBindings) {
|
|
1981
|
+
await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
|
|
1982
|
+
await this.extendResourcesFromExtensions("reload");
|
|
2092
1983
|
}
|
|
2093
|
-
throw lastError ?? new Error("callLLMStructured failed");
|
|
2094
1984
|
}
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
1985
|
+
// =========================================================================
|
|
1986
|
+
// Auto-Retry
|
|
1987
|
+
// =========================================================================
|
|
1988
|
+
/**
|
|
1989
|
+
* Check if an error is retryable (overloaded, rate limit, server errors).
|
|
1990
|
+
* Context overflow errors are NOT retryable (handled by compaction instead).
|
|
1991
|
+
*/
|
|
1992
|
+
_isRetryableError(message) {
|
|
1993
|
+
if (message.stopReason !== "error" || !message.errorMessage)
|
|
1994
|
+
return false;
|
|
1995
|
+
// Context overflow is handled by compaction, not retry
|
|
1996
|
+
const contextWindow = this.model?.contextWindow ?? 0;
|
|
1997
|
+
if (isContextOverflow(message, contextWindow))
|
|
1998
|
+
return false;
|
|
1999
|
+
const err = message.errorMessage;
|
|
2000
|
+
// 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
|
|
2001
|
+
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);
|
|
2002
|
+
}
|
|
2003
|
+
/**
|
|
2004
|
+
* Handle retryable errors with exponential backoff.
|
|
2005
|
+
* @returns true if retry was initiated, false if max retries exceeded or disabled
|
|
2006
|
+
*/
|
|
2007
|
+
async _handleRetryableError(message) {
|
|
2008
|
+
const settings = this.settingsManager.getRetrySettings();
|
|
2009
|
+
if (!settings.enabled) {
|
|
2010
|
+
this._resolveRetry();
|
|
2011
|
+
return false;
|
|
2102
2012
|
}
|
|
2103
|
-
|
|
2104
|
-
|
|
2013
|
+
// Retry promise is created synchronously in _handleAgentEvent for agent_end.
|
|
2014
|
+
// Keep a defensive fallback here in case a future refactor bypasses that path.
|
|
2015
|
+
if (!this._retryPromise) {
|
|
2016
|
+
this._retryPromise = new Promise((resolve) => {
|
|
2017
|
+
this._retryResolve = resolve;
|
|
2018
|
+
});
|
|
2105
2019
|
}
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2020
|
+
this._retryAttempt++;
|
|
2021
|
+
if (this._retryAttempt > settings.maxRetries) {
|
|
2022
|
+
// Max retries exceeded, emit final failure and reset
|
|
2023
|
+
this._emit({
|
|
2024
|
+
type: "auto_retry_end",
|
|
2025
|
+
success: false,
|
|
2026
|
+
attempt: this._retryAttempt - 1,
|
|
2027
|
+
finalError: message.errorMessage,
|
|
2028
|
+
});
|
|
2029
|
+
this._retryAttempt = 0;
|
|
2030
|
+
this._resolveRetry(); // Resolve so waitForRetry() completes
|
|
2031
|
+
return false;
|
|
2112
2032
|
}
|
|
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,
|
|
2033
|
+
const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
|
|
2034
|
+
this._emit({
|
|
2035
|
+
type: "auto_retry_start",
|
|
2036
|
+
attempt: this._retryAttempt,
|
|
2037
|
+
maxAttempts: settings.maxRetries,
|
|
2038
|
+
delayMs,
|
|
2039
|
+
errorMessage: message.errorMessage || "Unknown error",
|
|
2142
2040
|
});
|
|
2143
|
-
|
|
2144
|
-
const
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
opts.signal.addEventListener("abort", abortHandler, { once: true });
|
|
2041
|
+
// Remove error message from agent state (keep in session for history)
|
|
2042
|
+
const messages = this.agent.state.messages;
|
|
2043
|
+
if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
|
|
2044
|
+
this.agent.state.messages = messages.slice(0, -1);
|
|
2148
2045
|
}
|
|
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
|
-
});
|
|
2046
|
+
// Wait with exponential backoff (abortable)
|
|
2047
|
+
this._retryAbortController = new AbortController();
|
|
2184
2048
|
try {
|
|
2185
|
-
await
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2049
|
+
await sleep(delayMs, this._retryAbortController.signal);
|
|
2050
|
+
}
|
|
2051
|
+
catch {
|
|
2052
|
+
// Aborted during sleep - emit end event so UI can clean up
|
|
2053
|
+
const attempt = this._retryAttempt;
|
|
2054
|
+
this._retryAttempt = 0;
|
|
2055
|
+
this._retryAbortController = undefined;
|
|
2056
|
+
this._emit({
|
|
2057
|
+
type: "auto_retry_end",
|
|
2058
|
+
success: false,
|
|
2059
|
+
attempt,
|
|
2060
|
+
finalError: "Retry cancelled",
|
|
2189
2061
|
});
|
|
2062
|
+
this._resolveRetry();
|
|
2063
|
+
return false;
|
|
2064
|
+
}
|
|
2065
|
+
this._retryAbortController = undefined;
|
|
2066
|
+
// Retry via continue() - use setTimeout to break out of event handler chain
|
|
2067
|
+
setTimeout(() => {
|
|
2068
|
+
this.agent.continue().catch(() => {
|
|
2069
|
+
// Retry failed - will be caught by next agent_end
|
|
2070
|
+
});
|
|
2071
|
+
}, 0);
|
|
2072
|
+
return true;
|
|
2073
|
+
}
|
|
2074
|
+
/**
|
|
2075
|
+
* Cancel in-progress retry.
|
|
2076
|
+
*/
|
|
2077
|
+
abortRetry() {
|
|
2078
|
+
this._retryAbortController?.abort();
|
|
2079
|
+
// Note: _retryAttempt is reset in the catch block of _autoRetry
|
|
2080
|
+
this._resolveRetry();
|
|
2081
|
+
}
|
|
2082
|
+
/**
|
|
2083
|
+
* Wait for any in-progress retry to complete.
|
|
2084
|
+
* Returns immediately if no retry is in progress.
|
|
2085
|
+
*/
|
|
2086
|
+
async waitForRetry() {
|
|
2087
|
+
if (!this._retryPromise) {
|
|
2088
|
+
return;
|
|
2089
|
+
}
|
|
2090
|
+
await this._retryPromise;
|
|
2091
|
+
await this.agent.waitForIdle();
|
|
2092
|
+
}
|
|
2093
|
+
/** Whether auto-retry is currently in progress */
|
|
2094
|
+
get isRetrying() {
|
|
2095
|
+
return this._retryPromise !== undefined;
|
|
2096
|
+
}
|
|
2097
|
+
/** Whether auto-retry is enabled */
|
|
2098
|
+
get autoRetryEnabled() {
|
|
2099
|
+
return this.settingsManager.getRetryEnabled();
|
|
2100
|
+
}
|
|
2101
|
+
/**
|
|
2102
|
+
* Toggle auto-retry setting.
|
|
2103
|
+
*/
|
|
2104
|
+
setAutoRetryEnabled(enabled) {
|
|
2105
|
+
this.settingsManager.setRetryEnabled(enabled);
|
|
2106
|
+
}
|
|
2107
|
+
// =========================================================================
|
|
2108
|
+
// Bash Execution
|
|
2109
|
+
// =========================================================================
|
|
2110
|
+
/**
|
|
2111
|
+
* Execute a bash command.
|
|
2112
|
+
* Adds result to agent context and session.
|
|
2113
|
+
* @param command The bash command to execute
|
|
2114
|
+
* @param onChunk Optional streaming callback for output
|
|
2115
|
+
* @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
|
|
2116
|
+
* @param options.operations Custom BashOperations for remote execution
|
|
2117
|
+
*/
|
|
2118
|
+
async executeBash(command, onChunk, options) {
|
|
2119
|
+
this._bashAbortController = new AbortController();
|
|
2120
|
+
// Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
|
|
2121
|
+
const prefix = this.settingsManager.getShellCommandPrefix();
|
|
2122
|
+
const shellPath = this.settingsManager.getShellPath();
|
|
2123
|
+
const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
|
|
2124
|
+
try {
|
|
2125
|
+
const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
|
|
2126
|
+
onChunk,
|
|
2127
|
+
signal: this._bashAbortController.signal,
|
|
2128
|
+
});
|
|
2129
|
+
this.recordBashResult(command, result, options);
|
|
2130
|
+
return result;
|
|
2190
2131
|
}
|
|
2191
2132
|
finally {
|
|
2192
|
-
|
|
2193
|
-
if (abortHandler && opts.signal) {
|
|
2194
|
-
opts.signal.removeEventListener("abort", abortHandler);
|
|
2195
|
-
}
|
|
2133
|
+
this._bashAbortController = undefined;
|
|
2196
2134
|
}
|
|
2197
|
-
return { text: resultText, usage };
|
|
2198
2135
|
}
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2136
|
+
/**
|
|
2137
|
+
* Record a bash execution result in session history.
|
|
2138
|
+
* Used by executeBash and by extensions that handle bash execution themselves.
|
|
2139
|
+
*/
|
|
2140
|
+
recordBashResult(command, result, options) {
|
|
2141
|
+
const bashMessage = {
|
|
2142
|
+
role: "bashExecution",
|
|
2143
|
+
command,
|
|
2144
|
+
output: result.output,
|
|
2145
|
+
exitCode: result.exitCode,
|
|
2146
|
+
cancelled: result.cancelled,
|
|
2147
|
+
truncated: result.truncated,
|
|
2148
|
+
fullOutputPath: result.fullOutputPath,
|
|
2149
|
+
timestamp: Date.now(),
|
|
2150
|
+
excludeFromContext: options?.excludeFromContext,
|
|
2207
2151
|
};
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2152
|
+
// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
|
|
2153
|
+
if (this.isStreaming) {
|
|
2154
|
+
// Queue for later - will be flushed on agent_end
|
|
2155
|
+
this._pendingBashMessages.push(bashMessage);
|
|
2156
|
+
}
|
|
2157
|
+
else {
|
|
2158
|
+
// Add to agent state immediately
|
|
2159
|
+
this.agent.state.messages.push(bashMessage);
|
|
2160
|
+
// Save to session
|
|
2161
|
+
this.sessionManager.appendMessage(bashMessage);
|
|
2162
|
+
}
|
|
2211
2163
|
}
|
|
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
|
-
|
|
2164
|
+
/**
|
|
2165
|
+
* Cancel running bash command.
|
|
2166
|
+
*/
|
|
2167
|
+
abortBash() {
|
|
2168
|
+
this._bashAbortController?.abort();
|
|
2169
|
+
}
|
|
2170
|
+
/** Whether a bash command is currently running */
|
|
2171
|
+
get isBashRunning() {
|
|
2172
|
+
return this._bashAbortController !== undefined;
|
|
2173
|
+
}
|
|
2174
|
+
/** Whether there are pending bash messages waiting to be flushed */
|
|
2175
|
+
get hasPendingBashMessages() {
|
|
2176
|
+
return this._pendingBashMessages.length > 0;
|
|
2177
|
+
}
|
|
2178
|
+
/**
|
|
2179
|
+
* Flush pending bash messages to agent state and session.
|
|
2180
|
+
* Called after agent turn completes to maintain proper message ordering.
|
|
2181
|
+
*/
|
|
2182
|
+
_flushPendingBashMessages() {
|
|
2183
|
+
if (this._pendingBashMessages.length === 0)
|
|
2184
|
+
return;
|
|
2185
|
+
for (const bashMessage of this._pendingBashMessages) {
|
|
2186
|
+
// Add to agent state
|
|
2187
|
+
this.agent.state.messages.push(bashMessage);
|
|
2188
|
+
// Save to session
|
|
2189
|
+
this.sessionManager.appendMessage(bashMessage);
|
|
2190
|
+
}
|
|
2191
|
+
this._pendingBashMessages = [];
|
|
2192
|
+
}
|
|
2193
|
+
// =========================================================================
|
|
2194
|
+
// Session Management
|
|
2195
|
+
// =========================================================================
|
|
2196
|
+
/**
|
|
2197
|
+
* Set a display name for the current session.
|
|
2198
|
+
*/
|
|
2199
|
+
setSessionName(name) {
|
|
2200
|
+
this.sessionManager.appendSessionInfo(name);
|
|
2201
|
+
this._emit({ type: "session_info_changed", name: this.sessionManager.getSessionName() });
|
|
2202
|
+
}
|
|
2203
|
+
// =========================================================================
|
|
2204
|
+
// Tree Navigation
|
|
2205
|
+
// =========================================================================
|
|
2206
|
+
/**
|
|
2207
|
+
* Navigate to a different node in the session tree.
|
|
2208
|
+
* Unlike fork() which creates a new session file, this stays in the same file.
|
|
2209
|
+
*
|
|
2210
|
+
* @param targetId The entry ID to navigate to
|
|
2211
|
+
* @param options.summarize Whether user wants to summarize abandoned branch
|
|
2212
|
+
* @param options.customInstructions Custom instructions for summarizer
|
|
2213
|
+
* @param options.replaceInstructions If true, customInstructions replaces the default prompt
|
|
2214
|
+
* @param options.label Label to attach to the branch summary entry
|
|
2215
|
+
* @returns Result with editorText (if user message) and cancelled status
|
|
2216
|
+
*/
|
|
2217
|
+
async navigateTree(targetId, options = {}) {
|
|
2218
|
+
const oldLeafId = this.sessionManager.getLeafId();
|
|
2219
|
+
// No-op if already at target
|
|
2220
|
+
if (targetId === oldLeafId) {
|
|
2221
|
+
return { cancelled: false };
|
|
2222
|
+
}
|
|
2223
|
+
// Model required for summarization
|
|
2224
|
+
if (options.summarize && !this.model) {
|
|
2225
|
+
throw new Error("No model available for summarization");
|
|
2226
|
+
}
|
|
2227
|
+
const targetEntry = this.sessionManager.getEntry(targetId);
|
|
2228
|
+
if (!targetEntry) {
|
|
2229
|
+
throw new Error(`Entry ${targetId} not found`);
|
|
2230
|
+
}
|
|
2231
|
+
// Collect entries to summarize (from old leaf to common ancestor)
|
|
2232
|
+
const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
|
|
2233
|
+
// Prepare event data - mutable so extensions can override
|
|
2234
|
+
let customInstructions = options.customInstructions;
|
|
2235
|
+
let replaceInstructions = options.replaceInstructions;
|
|
2236
|
+
let label = options.label;
|
|
2237
|
+
const preparation = {
|
|
2238
|
+
targetId,
|
|
2239
|
+
oldLeafId,
|
|
2240
|
+
commonAncestorId,
|
|
2241
|
+
entriesToSummarize,
|
|
2242
|
+
userWantsSummary: options.summarize ?? false,
|
|
2243
|
+
customInstructions,
|
|
2244
|
+
replaceInstructions,
|
|
2245
|
+
label,
|
|
2246
|
+
skipFiles: options.skipFiles,
|
|
2247
|
+
};
|
|
2248
|
+
// Set up abort controller for summarization
|
|
2249
|
+
this._branchSummaryAbortController = new AbortController();
|
|
2250
|
+
try {
|
|
2251
|
+
let extensionSummary;
|
|
2252
|
+
let fromExtension = false;
|
|
2253
|
+
// Emit session_before_tree event
|
|
2254
|
+
if (this._extensionRunner.hasHandlers("session_before_tree")) {
|
|
2255
|
+
const result = (await this._extensionRunner.emit({
|
|
2256
|
+
type: "session_before_tree",
|
|
2257
|
+
preparation,
|
|
2258
|
+
signal: this._branchSummaryAbortController.signal,
|
|
2259
|
+
}));
|
|
2260
|
+
if (result?.cancel) {
|
|
2261
|
+
return { cancelled: true };
|
|
2262
|
+
}
|
|
2263
|
+
if (result?.summary && options.summarize) {
|
|
2264
|
+
extensionSummary = result.summary;
|
|
2265
|
+
fromExtension = true;
|
|
2266
|
+
}
|
|
2267
|
+
// Allow extensions to override instructions and label
|
|
2268
|
+
if (result?.customInstructions !== undefined) {
|
|
2269
|
+
customInstructions = result.customInstructions;
|
|
2270
|
+
}
|
|
2271
|
+
if (result?.replaceInstructions !== undefined) {
|
|
2272
|
+
replaceInstructions = result.replaceInstructions;
|
|
2273
|
+
}
|
|
2274
|
+
if (result?.label !== undefined) {
|
|
2275
|
+
label = result.label;
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
// Run default summarizer if needed
|
|
2279
|
+
let summaryText;
|
|
2280
|
+
let summaryDetails;
|
|
2281
|
+
if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
|
|
2282
|
+
const model = this.model;
|
|
2283
|
+
const { apiKey, headers } = await this._getRequiredRequestAuth(model);
|
|
2284
|
+
const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
|
|
2285
|
+
const result = await generateBranchSummary(entriesToSummarize, {
|
|
2286
|
+
model,
|
|
2287
|
+
apiKey,
|
|
2288
|
+
headers,
|
|
2289
|
+
signal: this._branchSummaryAbortController.signal,
|
|
2290
|
+
customInstructions,
|
|
2291
|
+
replaceInstructions,
|
|
2292
|
+
reserveTokens: branchSummarySettings.reserveTokens,
|
|
2293
|
+
});
|
|
2294
|
+
if (result.aborted) {
|
|
2295
|
+
return { cancelled: true, aborted: true };
|
|
2296
|
+
}
|
|
2297
|
+
if (result.error) {
|
|
2298
|
+
throw new Error(result.error);
|
|
2299
|
+
}
|
|
2300
|
+
summaryText = result.summary;
|
|
2301
|
+
summaryDetails = {
|
|
2302
|
+
readFiles: result.readFiles || [],
|
|
2303
|
+
modifiedFiles: result.modifiedFiles || [],
|
|
2304
|
+
};
|
|
2305
|
+
}
|
|
2306
|
+
else if (extensionSummary) {
|
|
2307
|
+
summaryText = extensionSummary.summary;
|
|
2308
|
+
summaryDetails = extensionSummary.details;
|
|
2309
|
+
}
|
|
2310
|
+
// Determine the new leaf position based on target type
|
|
2311
|
+
let newLeafId;
|
|
2312
|
+
let editorText;
|
|
2313
|
+
if (targetEntry.type === "message" && targetEntry.message.role === "user") {
|
|
2314
|
+
// User message: leaf = parent (null if root), text goes to editor
|
|
2315
|
+
newLeafId = targetEntry.parentId;
|
|
2316
|
+
editorText = this._extractUserMessageText(targetEntry.message.content);
|
|
2317
|
+
}
|
|
2318
|
+
else if (targetEntry.type === "custom_message") {
|
|
2319
|
+
// Custom message: leaf = parent (null if root), text goes to editor
|
|
2320
|
+
newLeafId = targetEntry.parentId;
|
|
2321
|
+
editorText =
|
|
2322
|
+
typeof targetEntry.content === "string"
|
|
2323
|
+
? targetEntry.content
|
|
2324
|
+
: targetEntry.content
|
|
2325
|
+
.filter((c) => c.type === "text")
|
|
2326
|
+
.map((c) => c.text)
|
|
2327
|
+
.join("");
|
|
2328
|
+
}
|
|
2329
|
+
else {
|
|
2330
|
+
// Non-user message: leaf = selected node
|
|
2331
|
+
newLeafId = targetId;
|
|
2332
|
+
}
|
|
2333
|
+
// Switch leaf (with or without summary)
|
|
2334
|
+
// Summary is attached at the navigation target position (newLeafId), not the old branch
|
|
2335
|
+
let summaryEntry;
|
|
2336
|
+
if (summaryText) {
|
|
2337
|
+
// Create summary at target position (can be null for root)
|
|
2338
|
+
const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
|
|
2339
|
+
summaryEntry = this.sessionManager.getEntry(summaryId);
|
|
2340
|
+
// Attach label to the summary entry
|
|
2341
|
+
if (label) {
|
|
2342
|
+
this.sessionManager.appendLabelChange(summaryId, label);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
else if (newLeafId === null) {
|
|
2346
|
+
// No summary, navigating to root - reset leaf
|
|
2347
|
+
this.sessionManager.resetLeaf();
|
|
2348
|
+
}
|
|
2349
|
+
else {
|
|
2350
|
+
// No summary, navigating to non-root
|
|
2351
|
+
this.sessionManager.branch(newLeafId);
|
|
2352
|
+
}
|
|
2353
|
+
// Attach label to target entry when not summarizing (no summary entry to label)
|
|
2354
|
+
if (label && !summaryText) {
|
|
2355
|
+
this.sessionManager.appendLabelChange(targetId, label);
|
|
2356
|
+
}
|
|
2357
|
+
// Update agent state
|
|
2358
|
+
const sessionContext = this.sessionManager.buildSessionContext();
|
|
2359
|
+
this.agent.state.messages = sessionContext.messages;
|
|
2360
|
+
// Emit session_tree event
|
|
2361
|
+
await this._extensionRunner.emit({
|
|
2362
|
+
type: "session_tree",
|
|
2363
|
+
newLeafId: this.sessionManager.getLeafId(),
|
|
2364
|
+
oldLeafId,
|
|
2365
|
+
summaryEntry,
|
|
2366
|
+
fromExtension: summaryText ? fromExtension : undefined,
|
|
2238
2367
|
});
|
|
2368
|
+
// Emit to custom tools
|
|
2369
|
+
return { editorText, cancelled: false, summaryEntry };
|
|
2239
2370
|
}
|
|
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);
|
|
2371
|
+
finally {
|
|
2372
|
+
this._branchSummaryAbortController = undefined;
|
|
2264
2373
|
}
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2374
|
+
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Get all user messages from session for fork selector.
|
|
2377
|
+
*/
|
|
2378
|
+
getUserMessagesForForking() {
|
|
2379
|
+
const entries = this.sessionManager.getEntries();
|
|
2380
|
+
const result = [];
|
|
2381
|
+
for (const entry of entries) {
|
|
2382
|
+
if (entry.type !== "message")
|
|
2383
|
+
continue;
|
|
2384
|
+
if (entry.message.role !== "user")
|
|
2385
|
+
continue;
|
|
2386
|
+
const text = this._extractUserMessageText(entry.message.content);
|
|
2387
|
+
if (text) {
|
|
2388
|
+
result.push({ entryId: entry.id, text });
|
|
2272
2389
|
}
|
|
2273
2390
|
}
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2391
|
+
return result;
|
|
2392
|
+
}
|
|
2393
|
+
_extractUserMessageText(content) {
|
|
2394
|
+
if (typeof content === "string")
|
|
2395
|
+
return content;
|
|
2396
|
+
if (Array.isArray(content)) {
|
|
2397
|
+
return content
|
|
2398
|
+
.filter((c) => c.type === "text")
|
|
2399
|
+
.map((c) => c.text)
|
|
2400
|
+
.join("");
|
|
2401
|
+
}
|
|
2402
|
+
return "";
|
|
2403
|
+
}
|
|
2404
|
+
/**
|
|
2405
|
+
* Get session statistics.
|
|
2406
|
+
*/
|
|
2407
|
+
getSessionStats() {
|
|
2408
|
+
const state = this.state;
|
|
2409
|
+
const userMessages = state.messages.filter((m) => m.role === "user").length;
|
|
2410
|
+
const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
|
|
2411
|
+
const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
|
|
2412
|
+
let toolCalls = 0;
|
|
2413
|
+
let totalInput = 0;
|
|
2414
|
+
let totalOutput = 0;
|
|
2415
|
+
let totalCacheRead = 0;
|
|
2416
|
+
let totalCacheWrite = 0;
|
|
2417
|
+
let totalCost = 0;
|
|
2418
|
+
for (const message of state.messages) {
|
|
2419
|
+
if (message.role === "assistant") {
|
|
2420
|
+
const assistantMsg = message;
|
|
2421
|
+
toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
|
|
2422
|
+
totalInput += assistantMsg.usage.input;
|
|
2423
|
+
totalOutput += assistantMsg.usage.output;
|
|
2424
|
+
totalCacheRead += assistantMsg.usage.cacheRead;
|
|
2425
|
+
totalCacheWrite += assistantMsg.usage.cacheWrite;
|
|
2426
|
+
totalCost += assistantMsg.usage.cost.total;
|
|
2277
2427
|
}
|
|
2278
2428
|
}
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2429
|
+
return {
|
|
2430
|
+
sessionFile: this.sessionFile,
|
|
2431
|
+
sessionId: this.sessionId,
|
|
2432
|
+
userMessages,
|
|
2433
|
+
assistantMessages,
|
|
2434
|
+
toolCalls,
|
|
2435
|
+
toolResults,
|
|
2436
|
+
totalMessages: state.messages.length,
|
|
2437
|
+
tokens: {
|
|
2438
|
+
input: totalInput,
|
|
2439
|
+
output: totalOutput,
|
|
2440
|
+
cacheRead: totalCacheRead,
|
|
2441
|
+
cacheWrite: totalCacheWrite,
|
|
2442
|
+
total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
|
|
2443
|
+
},
|
|
2444
|
+
cost: totalCost,
|
|
2445
|
+
contextUsage: this.getContextUsage(),
|
|
2446
|
+
};
|
|
2447
|
+
}
|
|
2448
|
+
getContextUsage() {
|
|
2449
|
+
const model = this.model;
|
|
2450
|
+
if (!model)
|
|
2451
|
+
return undefined;
|
|
2452
|
+
const contextWindow = model.contextWindow ?? 0;
|
|
2453
|
+
if (contextWindow <= 0)
|
|
2454
|
+
return undefined;
|
|
2455
|
+
// After compaction, the last assistant usage reflects pre-compaction context size.
|
|
2456
|
+
// We can only trust usage from an assistant that responded after the latest compaction.
|
|
2457
|
+
// If no such assistant exists, context token count is unknown until the next LLM response.
|
|
2458
|
+
const branchEntries = this.sessionManager.getBranch();
|
|
2459
|
+
const latestCompaction = getLatestCompactionEntry(branchEntries);
|
|
2460
|
+
if (latestCompaction) {
|
|
2461
|
+
// Check if there's a valid assistant usage after the compaction boundary
|
|
2462
|
+
const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
|
|
2463
|
+
let hasPostCompactionUsage = false;
|
|
2464
|
+
for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
|
|
2465
|
+
const entry = branchEntries[i];
|
|
2466
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
2467
|
+
const assistant = entry.message;
|
|
2468
|
+
if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
|
|
2469
|
+
const contextTokens = calculateContextTokens(assistant.usage);
|
|
2470
|
+
if (contextTokens > 0) {
|
|
2471
|
+
hasPostCompactionUsage = true;
|
|
2472
|
+
}
|
|
2473
|
+
break;
|
|
2474
|
+
}
|
|
2283
2475
|
}
|
|
2284
2476
|
}
|
|
2477
|
+
if (!hasPostCompactionUsage) {
|
|
2478
|
+
return { tokens: null, contextWindow, percent: null };
|
|
2479
|
+
}
|
|
2285
2480
|
}
|
|
2286
|
-
this.
|
|
2481
|
+
const estimate = estimateContextTokens(this.messages);
|
|
2482
|
+
const percent = (estimate.tokens / contextWindow) * 100;
|
|
2483
|
+
return {
|
|
2484
|
+
tokens: estimate.tokens,
|
|
2485
|
+
contextWindow,
|
|
2486
|
+
percent,
|
|
2487
|
+
};
|
|
2287
2488
|
}
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
:
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2489
|
+
/**
|
|
2490
|
+
* Export session to HTML.
|
|
2491
|
+
* @param outputPath Optional output path (defaults to session directory)
|
|
2492
|
+
* @returns Path to exported file
|
|
2493
|
+
*/
|
|
2494
|
+
async exportToHtml(outputPath) {
|
|
2495
|
+
const themeName = this.settingsManager.getTheme();
|
|
2496
|
+
// Create tool renderer if we have an extension runner (for custom tool HTML rendering)
|
|
2497
|
+
const toolRenderer = createToolHtmlRenderer({
|
|
2498
|
+
getToolDefinition: (name) => this.getToolDefinition(name),
|
|
2499
|
+
theme,
|
|
2500
|
+
cwd: this.sessionManager.getCwd(),
|
|
2501
|
+
});
|
|
2502
|
+
return await exportSessionToHtml(this.sessionManager, this.state, {
|
|
2503
|
+
outputPath,
|
|
2504
|
+
themeName,
|
|
2505
|
+
toolRenderer,
|
|
2506
|
+
});
|
|
2507
|
+
}
|
|
2508
|
+
/**
|
|
2509
|
+
* Export the current session branch to a JSONL file.
|
|
2510
|
+
* Writes the session header followed by all entries on the current branch path.
|
|
2511
|
+
* @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
|
|
2512
|
+
* @returns The resolved output file path.
|
|
2513
|
+
*/
|
|
2514
|
+
exportToJsonl(outputPath) {
|
|
2515
|
+
const filePath = resolve(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`);
|
|
2516
|
+
const dir = dirname(filePath);
|
|
2517
|
+
if (!existsSync(dir)) {
|
|
2518
|
+
mkdirSync(dir, { recursive: true });
|
|
2307
2519
|
}
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2520
|
+
const header = {
|
|
2521
|
+
type: "session",
|
|
2522
|
+
version: CURRENT_SESSION_VERSION,
|
|
2523
|
+
id: this.sessionManager.getSessionId(),
|
|
2524
|
+
timestamp: new Date().toISOString(),
|
|
2525
|
+
cwd: this.sessionManager.getCwd(),
|
|
2526
|
+
};
|
|
2527
|
+
const branchEntries = this.sessionManager.getBranch();
|
|
2528
|
+
const lines = [JSON.stringify(header)];
|
|
2529
|
+
// Re-chain parentIds to form a linear sequence
|
|
2530
|
+
let prevId = null;
|
|
2531
|
+
for (const entry of branchEntries) {
|
|
2532
|
+
const linear = { ...entry, parentId: prevId };
|
|
2533
|
+
lines.push(JSON.stringify(linear));
|
|
2534
|
+
prevId = entry.id;
|
|
2311
2535
|
}
|
|
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
|
-
});
|
|
2536
|
+
writeFileSync(filePath, `${lines.join("\n")}\n`);
|
|
2537
|
+
return filePath;
|
|
2322
2538
|
}
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2539
|
+
// =========================================================================
|
|
2540
|
+
// Utilities
|
|
2541
|
+
// =========================================================================
|
|
2542
|
+
/**
|
|
2543
|
+
* Get text content of last assistant message.
|
|
2544
|
+
* Useful for /copy command.
|
|
2545
|
+
* @returns Text content, or undefined if no assistant message exists
|
|
2546
|
+
*/
|
|
2547
|
+
getLastAssistantText() {
|
|
2548
|
+
const lastAssistant = this.messages
|
|
2549
|
+
.slice()
|
|
2550
|
+
.reverse()
|
|
2551
|
+
.find((m) => {
|
|
2552
|
+
if (m.role !== "assistant")
|
|
2553
|
+
return false;
|
|
2554
|
+
const msg = m;
|
|
2555
|
+
// Skip aborted messages with no content
|
|
2556
|
+
if (msg.stopReason === "aborted" && msg.content.length === 0)
|
|
2557
|
+
return false;
|
|
2558
|
+
return true;
|
|
2333
2559
|
});
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2560
|
+
if (!lastAssistant)
|
|
2561
|
+
return undefined;
|
|
2562
|
+
let text = "";
|
|
2563
|
+
for (const content of lastAssistant.content) {
|
|
2564
|
+
if (content.type === "text") {
|
|
2565
|
+
text += content.text;
|
|
2566
|
+
}
|
|
2341
2567
|
}
|
|
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
|
-
});
|
|
2568
|
+
return text.trim() || undefined;
|
|
2350
2569
|
}
|
|
2351
2570
|
// =========================================================================
|
|
2352
|
-
//
|
|
2571
|
+
// Extension System
|
|
2353
2572
|
// =========================================================================
|
|
2573
|
+
createReplacedSessionContext() {
|
|
2574
|
+
const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
|
|
2575
|
+
context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
|
|
2576
|
+
context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
|
|
2577
|
+
return context;
|
|
2578
|
+
}
|
|
2354
2579
|
/**
|
|
2355
|
-
* Check if
|
|
2356
|
-
* Context overflow errors are NOT retryable (handled by compaction instead).
|
|
2580
|
+
* Check if extensions have handlers for a specific event type.
|
|
2357
2581
|
*/
|
|
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);
|
|
2582
|
+
hasExtensionHandlers(eventType) {
|
|
2583
|
+
return this._extensionRunner.hasHandlers(eventType);
|
|
2368
2584
|
}
|
|
2369
2585
|
/**
|
|
2370
|
-
*
|
|
2371
|
-
* @returns true if retry was initiated, false if max retries exceeded or disabled
|
|
2586
|
+
* Get the extension runner (for setting UI context and error handlers).
|
|
2372
2587
|
*/
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
this._retryPromise = new Promise((resolve) => {
|
|
2383
|
-
this._retryResolve = resolve;
|
|
2384
|
-
});
|
|
2588
|
+
get extensionRunner() {
|
|
2589
|
+
return this._extensionRunner;
|
|
2590
|
+
}
|
|
2591
|
+
async _resolveOptionalModel(modelSpec) {
|
|
2592
|
+
if (modelSpec) {
|
|
2593
|
+
const aliasResolved = resolveModelAlias(modelSpec, this._tierModels);
|
|
2594
|
+
const resolved = aliasResolved ?? modelSpec;
|
|
2595
|
+
const available = await this._modelRegistry.getAvailable();
|
|
2596
|
+
return available.find((m) => m.id === resolved || `${m.provider}/${m.id}` === resolved);
|
|
2385
2597
|
}
|
|
2386
|
-
this.
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
});
|
|
2395
|
-
this._retryAttempt = 0;
|
|
2396
|
-
this._resolveRetry(); // Resolve so waitForRetry() completes
|
|
2397
|
-
return false;
|
|
2598
|
+
return this.model;
|
|
2599
|
+
}
|
|
2600
|
+
async callLLM(options) {
|
|
2601
|
+
const model = await this._resolveOptionalModel(options.model);
|
|
2602
|
+
if (!model)
|
|
2603
|
+
throw new Error("No model selected");
|
|
2604
|
+
const auth = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
2605
|
+
if (!auth?.ok) {
|
|
2606
|
+
throw new Error(auth?.error ?? `No API key configured for ${model.provider}`);
|
|
2398
2607
|
}
|
|
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);
|
|
2608
|
+
if (!auth.apiKey) {
|
|
2609
|
+
throw new Error(`No API key configured for ${model.provider}`);
|
|
2411
2610
|
}
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
try {
|
|
2415
|
-
await sleep(delayMs, this._retryAbortController.signal);
|
|
2611
|
+
if (options.signal?.aborted) {
|
|
2612
|
+
throw new Error("Aborted");
|
|
2416
2613
|
}
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2614
|
+
const messages = options.messages.map((m) => ({
|
|
2615
|
+
role: m.role,
|
|
2616
|
+
content: [{ type: "text", text: m.content }],
|
|
2617
|
+
timestamp: Date.now(),
|
|
2618
|
+
}));
|
|
2619
|
+
if (!options.tools || options.tools.length === 0) {
|
|
2620
|
+
const context = {
|
|
2621
|
+
systemPrompt: options.systemPrompt,
|
|
2622
|
+
messages,
|
|
2623
|
+
};
|
|
2624
|
+
const response = await complete(model, context, {
|
|
2625
|
+
apiKey: auth.apiKey,
|
|
2626
|
+
headers: auth.headers,
|
|
2627
|
+
maxTokens: options.maxTokens,
|
|
2628
|
+
signal: options.signal,
|
|
2427
2629
|
});
|
|
2428
|
-
|
|
2429
|
-
|
|
2630
|
+
return response.content
|
|
2631
|
+
.filter((c) => c.type === "text")
|
|
2632
|
+
.map((c) => c.text)
|
|
2633
|
+
.join("\n");
|
|
2430
2634
|
}
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2635
|
+
const toolInstances = options.tools
|
|
2636
|
+
.map((name) => {
|
|
2637
|
+
try {
|
|
2638
|
+
const registered = this._toolRegistry.get(name);
|
|
2639
|
+
if (registered)
|
|
2640
|
+
return registered;
|
|
2641
|
+
return createTool(name, this._cwd);
|
|
2642
|
+
}
|
|
2643
|
+
catch {
|
|
2644
|
+
return undefined;
|
|
2645
|
+
}
|
|
2646
|
+
})
|
|
2647
|
+
.filter((t) => t !== undefined);
|
|
2648
|
+
if (toolInstances.length === 0) {
|
|
2649
|
+
const context = {
|
|
2650
|
+
systemPrompt: options.systemPrompt,
|
|
2651
|
+
messages,
|
|
2652
|
+
};
|
|
2653
|
+
const response = await complete(model, context, {
|
|
2654
|
+
apiKey: auth.apiKey,
|
|
2655
|
+
headers: auth.headers,
|
|
2656
|
+
maxTokens: options.maxTokens,
|
|
2657
|
+
signal: options.signal,
|
|
2436
2658
|
});
|
|
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;
|
|
2659
|
+
return response.content
|
|
2660
|
+
.filter((c) => c.type === "text")
|
|
2661
|
+
.map((c) => c.text)
|
|
2662
|
+
.join("\n");
|
|
2455
2663
|
}
|
|
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;
|
|
2664
|
+
const agent = new Agent({
|
|
2665
|
+
getApiKey: () => auth.apiKey,
|
|
2666
|
+
initialState: {
|
|
2667
|
+
systemPrompt: options.systemPrompt ?? "",
|
|
2668
|
+
model,
|
|
2669
|
+
thinkingLevel: "off",
|
|
2670
|
+
tools: toolInstances,
|
|
2671
|
+
messages: [],
|
|
2672
|
+
},
|
|
2673
|
+
});
|
|
2674
|
+
if (options.signal?.aborted) {
|
|
2675
|
+
throw new Error("Aborted");
|
|
2676
|
+
}
|
|
2677
|
+
let resultText = "";
|
|
2678
|
+
const unsub = agent.subscribe((event) => {
|
|
2679
|
+
if (event.type === "message_end" && "message" in event) {
|
|
2680
|
+
const msg = event.message;
|
|
2681
|
+
if (msg.role === "assistant") {
|
|
2682
|
+
const content = msg.content;
|
|
2683
|
+
if (Array.isArray(content)) {
|
|
2684
|
+
resultText = content
|
|
2685
|
+
.filter((c) => c.type === "text")
|
|
2686
|
+
.map((c) => c.text)
|
|
2687
|
+
.join("\n");
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
});
|
|
2490
2692
|
try {
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2693
|
+
await agent.prompt({
|
|
2694
|
+
role: "user",
|
|
2695
|
+
content: [{ type: "text", text: options.messages[0]?.content ?? "" }],
|
|
2696
|
+
timestamp: Date.now(),
|
|
2494
2697
|
});
|
|
2495
|
-
this.recordBashResult(command, result, options);
|
|
2496
|
-
return result;
|
|
2497
2698
|
}
|
|
2498
2699
|
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);
|
|
2700
|
+
unsub();
|
|
2528
2701
|
}
|
|
2702
|
+
return resultText;
|
|
2529
2703
|
}
|
|
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
|
-
|
|
2704
|
+
async callLLMStructured(options) {
|
|
2705
|
+
const maxRetries = options.maxRetries ?? 0;
|
|
2706
|
+
let lastError;
|
|
2707
|
+
const schemaJson = JSON.stringify(options.schema);
|
|
2708
|
+
const structuredSystemPrompt = (options.systemPrompt ?? "") +
|
|
2709
|
+
`\n\nRespond with valid JSON matching this schema:\n${schemaJson}\n\nRespond with JSON only, no markdown.`;
|
|
2710
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
2711
|
+
const messages = attempt === 0
|
|
2712
|
+
? options.messages
|
|
2713
|
+
: [
|
|
2714
|
+
...options.messages,
|
|
2715
|
+
{ role: "assistant", content: lastError?.raw ?? "" },
|
|
2716
|
+
{
|
|
2717
|
+
role: "user",
|
|
2718
|
+
content: `Your previous response was invalid: ${lastError?.message}. Please respond with valid JSON matching the schema.`,
|
|
2719
|
+
},
|
|
2720
|
+
];
|
|
2721
|
+
const raw = await this.callLLM({
|
|
2722
|
+
...options,
|
|
2723
|
+
systemPrompt: structuredSystemPrompt,
|
|
2724
|
+
messages,
|
|
2725
|
+
});
|
|
2726
|
+
try {
|
|
2727
|
+
const cleaned = stripMarkdownCodeBlock(raw);
|
|
2728
|
+
const parsed = JSON.parse(cleaned);
|
|
2729
|
+
const check = Compile(options.schema);
|
|
2730
|
+
const coerced = Value.Convert(options.schema, parsed);
|
|
2731
|
+
if (!check.Check(coerced)) {
|
|
2732
|
+
const errors = check
|
|
2733
|
+
.Errors(coerced)
|
|
2734
|
+
.map((e) => `${e.instancePath}: ${e.message}`)
|
|
2735
|
+
.join("; ");
|
|
2736
|
+
const err = new Error(`Schema validation failed: ${errors}`);
|
|
2737
|
+
err.raw = raw;
|
|
2738
|
+
err.reason = "schema_validation";
|
|
2739
|
+
lastError = err;
|
|
2740
|
+
if (attempt >= maxRetries)
|
|
2741
|
+
throw err;
|
|
2742
|
+
continue;
|
|
2743
|
+
}
|
|
2744
|
+
return coerced;
|
|
2745
|
+
}
|
|
2746
|
+
catch (e) {
|
|
2747
|
+
if (e instanceof SyntaxError) {
|
|
2748
|
+
const err = new Error(`JSON parse failed: ${e.message}`);
|
|
2749
|
+
err.raw = raw;
|
|
2750
|
+
err.reason = "json_parse";
|
|
2751
|
+
lastError = err;
|
|
2752
|
+
if (attempt >= maxRetries)
|
|
2753
|
+
throw err;
|
|
2754
|
+
continue;
|
|
2755
|
+
}
|
|
2756
|
+
if (e.reason) {
|
|
2757
|
+
lastError = e;
|
|
2758
|
+
if (attempt >= maxRetries)
|
|
2759
|
+
throw lastError;
|
|
2760
|
+
continue;
|
|
2761
|
+
}
|
|
2762
|
+
throw e;
|
|
2763
|
+
}
|
|
2556
2764
|
}
|
|
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);
|
|
2765
|
+
throw lastError ?? new Error("callLLMStructured failed");
|
|
2567
2766
|
}
|
|
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 };
|
|
2767
|
+
async forkAgent(promptText, options) {
|
|
2768
|
+
const model = await this._resolveOptionalModel(options?.model);
|
|
2769
|
+
if (!model)
|
|
2770
|
+
throw new Error("No model selected");
|
|
2771
|
+
const auth = await this._modelRegistry.getApiKeyAndHeaders(model);
|
|
2772
|
+
if (!auth?.ok) {
|
|
2773
|
+
throw new Error("error" in auth ? auth.error : `No API key configured for ${model.provider}`);
|
|
2587
2774
|
}
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
throw new Error("No model available for summarization");
|
|
2775
|
+
if (!auth.apiKey) {
|
|
2776
|
+
throw new Error(`No API key configured for ${model.provider}`);
|
|
2591
2777
|
}
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2778
|
+
if (options?.signal?.aborted)
|
|
2779
|
+
throw new Error("Aborted");
|
|
2780
|
+
const opts = options ?? {};
|
|
2781
|
+
let toolNames = opts.tools ?? ["read", "grep", "find", "ls"];
|
|
2782
|
+
if (opts.bash === "deny") {
|
|
2783
|
+
toolNames = toolNames.filter((t) => t !== "bash");
|
|
2595
2784
|
}
|
|
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;
|
|
2785
|
+
const toolInstances = toolNames
|
|
2786
|
+
.map((name) => {
|
|
2787
|
+
try {
|
|
2788
|
+
const registered = this._toolRegistry.get(name);
|
|
2789
|
+
if (registered)
|
|
2790
|
+
return registered;
|
|
2791
|
+
return createTool(name, this._cwd);
|
|
2636
2792
|
}
|
|
2637
|
-
|
|
2638
|
-
|
|
2793
|
+
catch {
|
|
2794
|
+
return undefined;
|
|
2639
2795
|
}
|
|
2640
|
-
}
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2796
|
+
})
|
|
2797
|
+
.filter((t) => t !== undefined);
|
|
2798
|
+
const effectiveSystemPrompt = opts.inheritSystemPrompt
|
|
2799
|
+
? (this.agent.state.systemPrompt ?? opts.systemPrompt ?? "")
|
|
2800
|
+
: (opts.systemPrompt ?? "");
|
|
2801
|
+
const messages = opts.shareContext ? [...this.agent.state.messages] : [];
|
|
2802
|
+
const maxTurns = opts.maxTurns ?? 5;
|
|
2803
|
+
let turnCount = 0;
|
|
2804
|
+
const forkedAgent = new Agent({
|
|
2805
|
+
getApiKey: () => auth.apiKey,
|
|
2806
|
+
initialState: {
|
|
2807
|
+
systemPrompt: effectiveSystemPrompt,
|
|
2649
2808
|
model,
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2809
|
+
thinkingLevel: "off",
|
|
2810
|
+
tools: toolInstances,
|
|
2811
|
+
messages,
|
|
2812
|
+
},
|
|
2813
|
+
sessionId: opts.shareContext ? this.agent.sessionId : undefined,
|
|
2814
|
+
});
|
|
2815
|
+
let resultText = "";
|
|
2816
|
+
const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
2817
|
+
const abortHandler = opts.signal ? () => forkedAgent.abort() : undefined;
|
|
2818
|
+
if (abortHandler && opts.signal) {
|
|
2819
|
+
opts.signal.addEventListener("abort", abortHandler, { once: true });
|
|
2820
|
+
}
|
|
2821
|
+
const unsub = forkedAgent.subscribe((event) => {
|
|
2822
|
+
if (event.type === "turn_end") {
|
|
2823
|
+
turnCount++;
|
|
2824
|
+
if (turnCount >= maxTurns) {
|
|
2825
|
+
forkedAgent.abort();
|
|
2826
|
+
}
|
|
2660
2827
|
}
|
|
2661
|
-
if (
|
|
2662
|
-
|
|
2828
|
+
if (event.type === "message_end") {
|
|
2829
|
+
const msg = event.message;
|
|
2830
|
+
if (msg.role === "assistant") {
|
|
2831
|
+
const asst = msg;
|
|
2832
|
+
const content = asst.content;
|
|
2833
|
+
if (Array.isArray(content)) {
|
|
2834
|
+
resultText = content
|
|
2835
|
+
.filter((c) => c.type === "text")
|
|
2836
|
+
.map((c) => c.text)
|
|
2837
|
+
.join("\n");
|
|
2838
|
+
}
|
|
2839
|
+
if (asst.usage) {
|
|
2840
|
+
usage.input = asst.usage.input ?? 0;
|
|
2841
|
+
usage.output = asst.usage.output ?? 0;
|
|
2842
|
+
usage.cacheRead = asst.usage.cacheRead ?? 0;
|
|
2843
|
+
usage.cacheWrite = asst.usage.cacheWrite ?? 0;
|
|
2844
|
+
if (model.cost) {
|
|
2845
|
+
usage.cost =
|
|
2846
|
+
(usage.input * model.cost.input +
|
|
2847
|
+
usage.output * model.cost.output +
|
|
2848
|
+
usage.cacheRead * model.cost.cacheRead +
|
|
2849
|
+
usage.cacheWrite * model.cost.cacheWrite) /
|
|
2850
|
+
1_000_000;
|
|
2851
|
+
}
|
|
2852
|
+
}
|
|
2853
|
+
}
|
|
2663
2854
|
}
|
|
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;
|
|
2855
|
+
});
|
|
2856
|
+
try {
|
|
2857
|
+
await forkedAgent.prompt({
|
|
2858
|
+
role: "user",
|
|
2859
|
+
content: [{ type: "text", text: promptText }],
|
|
2860
|
+
timestamp: Date.now(),
|
|
2861
|
+
});
|
|
2696
2862
|
}
|
|
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);
|
|
2863
|
+
finally {
|
|
2864
|
+
unsub();
|
|
2865
|
+
if (abortHandler && opts.signal) {
|
|
2866
|
+
opts.signal.removeEventListener("abort", abortHandler);
|
|
2707
2867
|
}
|
|
2708
2868
|
}
|
|
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 };
|
|
2869
|
+
return { text: resultText, usage };
|
|
2870
|
+
}
|
|
2871
|
+
background(fn) {
|
|
2872
|
+
const controller = new AbortController();
|
|
2873
|
+
const promise = fn(controller.signal);
|
|
2874
|
+
const task = {
|
|
2875
|
+
id: randomUUID(),
|
|
2876
|
+
signal: controller.signal,
|
|
2877
|
+
promise: promise,
|
|
2878
|
+
cancel: () => controller.abort(),
|
|
2879
|
+
};
|
|
2880
|
+
this._backgroundTasks.add(task);
|
|
2881
|
+
promise.finally(() => this._backgroundTasks.delete(task));
|
|
2882
|
+
return task;
|
|
2736
2883
|
}
|
|
2737
2884
|
async previewRollback(targetId) {
|
|
2738
2885
|
const oldLeafId = this.sessionManager.getLeafId();
|
|
@@ -2761,226 +2908,5 @@ export class AgentSession {
|
|
|
2761
2908
|
deleted: [],
|
|
2762
2909
|
});
|
|
2763
2910
|
}
|
|
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
2911
|
}
|
|
2986
2912
|
//# sourceMappingURL=agent-session.js.map
|