@posthog/agent 1.30.0 → 2.0.1
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/LICENSE +1 -1
- package/README.md +221 -219
- package/dist/adapters/claude/conversion/tool-use-to-acp.d.ts +21 -0
- package/dist/adapters/claude/conversion/tool-use-to-acp.js +547 -0
- package/dist/adapters/claude/conversion/tool-use-to-acp.js.map +1 -0
- package/dist/adapters/claude/permissions/permission-options.d.ts +13 -0
- package/dist/adapters/claude/permissions/permission-options.js +117 -0
- package/dist/adapters/claude/permissions/permission-options.js.map +1 -0
- package/dist/adapters/claude/questions/utils.d.ts +132 -0
- package/dist/adapters/claude/questions/utils.js +63 -0
- package/dist/adapters/claude/questions/utils.js.map +1 -0
- package/dist/adapters/claude/tools.d.ts +18 -0
- package/dist/adapters/claude/tools.js +95 -0
- package/dist/adapters/claude/tools.js.map +1 -0
- package/dist/agent-DBQY1BfC.d.ts +123 -0
- package/dist/agent.d.ts +5 -0
- package/dist/agent.js +3656 -0
- package/dist/agent.js.map +1 -0
- package/dist/claude-cli/cli.js +3695 -2746
- package/dist/claude-cli/vendor/ripgrep/COPYING +3 -0
- package/dist/claude-cli/vendor/ripgrep/arm64-darwin/rg +0 -0
- package/dist/claude-cli/vendor/ripgrep/arm64-darwin/ripgrep.node +0 -0
- package/dist/claude-cli/vendor/ripgrep/arm64-linux/rg +0 -0
- package/dist/claude-cli/vendor/ripgrep/arm64-linux/ripgrep.node +0 -0
- package/dist/claude-cli/vendor/ripgrep/x64-darwin/rg +0 -0
- package/dist/claude-cli/vendor/ripgrep/x64-darwin/ripgrep.node +0 -0
- package/dist/claude-cli/vendor/ripgrep/x64-linux/rg +0 -0
- package/dist/claude-cli/vendor/ripgrep/x64-linux/ripgrep.node +0 -0
- package/dist/claude-cli/vendor/ripgrep/x64-win32/rg.exe +0 -0
- package/dist/claude-cli/vendor/ripgrep/x64-win32/ripgrep.node +0 -0
- package/dist/gateway-models.d.ts +24 -0
- package/dist/gateway-models.js +93 -0
- package/dist/gateway-models.js.map +1 -0
- package/dist/index.d.ts +172 -1203
- package/dist/index.js +3704 -6826
- package/dist/index.js.map +1 -1
- package/dist/logger-DDBiMOOD.d.ts +24 -0
- package/dist/posthog-api.d.ts +40 -0
- package/dist/posthog-api.js +175 -0
- package/dist/posthog-api.js.map +1 -0
- package/dist/server/agent-server.d.ts +41 -0
- package/dist/server/agent-server.js +4451 -0
- package/dist/server/agent-server.js.map +1 -0
- package/dist/server/bin.d.ts +1 -0
- package/dist/server/bin.js +4507 -0
- package/dist/server/bin.js.map +1 -0
- package/dist/types.d.ts +129 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -0
- package/package.json +66 -14
- package/src/acp-extensions.ts +93 -61
- package/src/adapters/acp-connection.ts +494 -0
- package/src/adapters/base-acp-agent.ts +150 -0
- package/src/adapters/claude/claude-agent.ts +596 -0
- package/src/adapters/claude/conversion/acp-to-sdk.ts +102 -0
- package/src/adapters/claude/conversion/sdk-to-acp.ts +571 -0
- package/src/adapters/claude/conversion/tool-use-to-acp.ts +618 -0
- package/src/adapters/claude/hooks.ts +64 -0
- package/src/adapters/claude/mcp/tool-metadata.ts +102 -0
- package/src/adapters/claude/permissions/permission-handlers.ts +433 -0
- package/src/adapters/claude/permissions/permission-options.ts +103 -0
- package/src/adapters/claude/plan/utils.ts +56 -0
- package/src/adapters/claude/questions/utils.ts +92 -0
- package/src/adapters/claude/session/commands.ts +38 -0
- package/src/adapters/claude/session/mcp-config.ts +37 -0
- package/src/adapters/claude/session/models.ts +12 -0
- package/src/adapters/claude/session/options.ts +236 -0
- package/src/adapters/claude/tool-meta.ts +143 -0
- package/src/adapters/claude/tools.ts +53 -611
- package/src/adapters/claude/types.ts +61 -0
- package/src/adapters/codex/spawn.ts +130 -0
- package/src/agent.ts +97 -734
- package/src/execution-mode.ts +43 -0
- package/src/gateway-models.ts +135 -0
- package/src/index.ts +79 -0
- package/src/otel-log-writer.test.ts +105 -0
- package/src/otel-log-writer.ts +94 -0
- package/src/posthog-api.ts +75 -235
- package/src/resume.ts +115 -0
- package/src/sagas/apply-snapshot-saga.test.ts +690 -0
- package/src/sagas/apply-snapshot-saga.ts +88 -0
- package/src/sagas/capture-tree-saga.test.ts +892 -0
- package/src/sagas/capture-tree-saga.ts +141 -0
- package/src/sagas/resume-saga.test.ts +558 -0
- package/src/sagas/resume-saga.ts +332 -0
- package/src/sagas/test-fixtures.ts +250 -0
- package/src/server/agent-server.test.ts +220 -0
- package/src/server/agent-server.ts +748 -0
- package/src/server/bin.ts +88 -0
- package/src/server/jwt.ts +65 -0
- package/src/server/schemas.ts +47 -0
- package/src/server/types.ts +13 -0
- package/src/server/utils/retry.test.ts +122 -0
- package/src/server/utils/retry.ts +61 -0
- package/src/server/utils/sse-parser.test.ts +93 -0
- package/src/server/utils/sse-parser.ts +46 -0
- package/src/session-log-writer.test.ts +140 -0
- package/src/session-log-writer.ts +137 -0
- package/src/test/assertions.ts +114 -0
- package/src/test/controllers/sse-controller.ts +107 -0
- package/src/test/fixtures/api.ts +111 -0
- package/src/test/fixtures/config.ts +33 -0
- package/src/test/fixtures/notifications.ts +92 -0
- package/src/test/mocks/claude-sdk.ts +251 -0
- package/src/test/mocks/msw-handlers.ts +48 -0
- package/src/test/setup.ts +114 -0
- package/src/test/wait.ts +41 -0
- package/src/tree-tracker.ts +173 -0
- package/src/types.ts +51 -154
- package/src/utils/acp-content.ts +58 -0
- package/src/utils/async-mutex.test.ts +104 -0
- package/src/utils/async-mutex.ts +31 -0
- package/src/utils/common.ts +15 -0
- package/src/utils/gateway.ts +9 -6
- package/src/utils/logger.ts +0 -30
- package/src/utils/streams.ts +220 -0
- package/CLAUDE.md +0 -331
- package/dist/templates/plan-template.md +0 -41
- package/src/adapters/claude/claude.ts +0 -1543
- package/src/adapters/claude/mcp-server.ts +0 -810
- package/src/adapters/claude/utils.ts +0 -267
- package/src/agents/execution.ts +0 -37
- package/src/agents/planning.ts +0 -60
- package/src/agents/research.ts +0 -160
- package/src/file-manager.ts +0 -306
- package/src/git-manager.ts +0 -577
- package/src/prompt-builder.ts +0 -499
- package/src/schemas.ts +0 -241
- package/src/session-store.ts +0 -259
- package/src/task-manager.ts +0 -163
- package/src/template-manager.ts +0 -236
- package/src/templates/plan-template.md +0 -41
- package/src/todo-manager.ts +0 -180
- package/src/tools/registry.ts +0 -129
- package/src/tools/types.ts +0 -127
- package/src/utils/tapped-stream.ts +0 -60
- package/src/workflow/config.ts +0 -53
- package/src/workflow/steps/build.ts +0 -135
- package/src/workflow/steps/finalize.ts +0 -241
- package/src/workflow/steps/plan.ts +0 -167
- package/src/workflow/steps/research.ts +0 -223
- package/src/workflow/types.ts +0 -62
- package/src/workflow/utils.ts +0 -53
- package/src/worktree-manager.ts +0 -928
|
@@ -1,1543 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The claude adapter has been based on the original claude-code-acp adapter,
|
|
3
|
-
* and could use some cleanup.
|
|
4
|
-
*
|
|
5
|
-
* https://github.com/zed-industries/claude-code-acp
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import * as fs from "node:fs";
|
|
9
|
-
import * as os from "node:os";
|
|
10
|
-
import * as path from "node:path";
|
|
11
|
-
import {
|
|
12
|
-
type Agent,
|
|
13
|
-
AgentSideConnection,
|
|
14
|
-
type AuthenticateRequest,
|
|
15
|
-
type AvailableCommand,
|
|
16
|
-
type CancelNotification,
|
|
17
|
-
type ClientCapabilities,
|
|
18
|
-
type InitializeRequest,
|
|
19
|
-
type InitializeResponse,
|
|
20
|
-
type LoadSessionRequest,
|
|
21
|
-
type LoadSessionResponse,
|
|
22
|
-
type NewSessionRequest,
|
|
23
|
-
type NewSessionResponse,
|
|
24
|
-
ndJsonStream,
|
|
25
|
-
type PromptRequest,
|
|
26
|
-
type PromptResponse,
|
|
27
|
-
type ReadTextFileRequest,
|
|
28
|
-
type ReadTextFileResponse,
|
|
29
|
-
RequestError,
|
|
30
|
-
type SessionModelState,
|
|
31
|
-
type SessionNotification,
|
|
32
|
-
type SetSessionModelRequest,
|
|
33
|
-
type SetSessionModeRequest,
|
|
34
|
-
type SetSessionModeResponse,
|
|
35
|
-
type TerminalHandle,
|
|
36
|
-
type TerminalOutputResponse,
|
|
37
|
-
type WriteTextFileRequest,
|
|
38
|
-
type WriteTextFileResponse,
|
|
39
|
-
} from "@agentclientprotocol/sdk";
|
|
40
|
-
import {
|
|
41
|
-
type CanUseTool,
|
|
42
|
-
type McpServerConfig,
|
|
43
|
-
type Options,
|
|
44
|
-
type PermissionMode,
|
|
45
|
-
type Query,
|
|
46
|
-
query,
|
|
47
|
-
type SDKPartialAssistantMessage,
|
|
48
|
-
type SDKUserMessage,
|
|
49
|
-
} from "@anthropic-ai/claude-agent-sdk";
|
|
50
|
-
import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";
|
|
51
|
-
import type {
|
|
52
|
-
BetaContentBlock,
|
|
53
|
-
BetaRawContentBlockDelta,
|
|
54
|
-
} from "@anthropic-ai/sdk/resources/beta.mjs";
|
|
55
|
-
import { v7 as uuidv7 } from "uuid";
|
|
56
|
-
import type {
|
|
57
|
-
SessionPersistenceConfig,
|
|
58
|
-
SessionStore,
|
|
59
|
-
} from "@/session-store.js";
|
|
60
|
-
import { Logger } from "@/utils/logger.js";
|
|
61
|
-
import { createTappedWritableStream } from "@/utils/tapped-stream.js";
|
|
62
|
-
import packageJson from "../../../package.json" with { type: "json" };
|
|
63
|
-
import { createMcpServer, EDIT_TOOL_NAMES, toolNames } from "./mcp-server.js";
|
|
64
|
-
import {
|
|
65
|
-
type ClaudePlanEntry,
|
|
66
|
-
createPostToolUseHook,
|
|
67
|
-
planEntries,
|
|
68
|
-
registerHookCallback,
|
|
69
|
-
toolInfoFromToolUse,
|
|
70
|
-
toolUpdateFromToolResult,
|
|
71
|
-
} from "./tools.js";
|
|
72
|
-
import {
|
|
73
|
-
createBidirectionalStreams,
|
|
74
|
-
Pushable,
|
|
75
|
-
type StreamPair,
|
|
76
|
-
unreachable,
|
|
77
|
-
} from "./utils.js";
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Clears the statsig cache to work around a claude-agent-sdk bug where cached
|
|
81
|
-
* tool definitions include input_examples which causes API errors.
|
|
82
|
-
* See: https://github.com/anthropics/claude-code/issues/11678
|
|
83
|
-
*/
|
|
84
|
-
function clearStatsigCache(): void {
|
|
85
|
-
const configDir =
|
|
86
|
-
process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
|
|
87
|
-
const statsigPath = path.join(configDir, "statsig");
|
|
88
|
-
|
|
89
|
-
try {
|
|
90
|
-
if (fs.existsSync(statsigPath)) {
|
|
91
|
-
fs.rmSync(statsigPath, { recursive: true, force: true });
|
|
92
|
-
}
|
|
93
|
-
} catch {
|
|
94
|
-
// Ignore errors - cache clearing is best-effort
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
type Session = {
|
|
99
|
-
query: Query;
|
|
100
|
-
input: Pushable<SDKUserMessage>;
|
|
101
|
-
cancelled: boolean;
|
|
102
|
-
permissionMode: PermissionMode;
|
|
103
|
-
notificationHistory: SessionNotification[];
|
|
104
|
-
sdkSessionId?: string;
|
|
105
|
-
};
|
|
106
|
-
|
|
107
|
-
type BackgroundTerminal =
|
|
108
|
-
| {
|
|
109
|
-
handle: TerminalHandle;
|
|
110
|
-
status: "started";
|
|
111
|
-
lastOutput: TerminalOutputResponse | null;
|
|
112
|
-
}
|
|
113
|
-
| {
|
|
114
|
-
status: "aborted" | "exited" | "killed" | "timedOut";
|
|
115
|
-
pendingOutput: TerminalOutputResponse;
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Extra metadata that can be given to Claude Code when creating a new session.
|
|
120
|
-
*/
|
|
121
|
-
export type NewSessionMeta = {
|
|
122
|
-
claudeCode?: {
|
|
123
|
-
/**
|
|
124
|
-
* Options forwarded to Claude Code when starting a new session.
|
|
125
|
-
* Those parameters will be ignored and managed by ACP:
|
|
126
|
-
* - cwd
|
|
127
|
-
* - includePartialMessages
|
|
128
|
-
* - allowDangerouslySkipPermissions
|
|
129
|
-
* - permissionMode
|
|
130
|
-
* - canUseTool
|
|
131
|
-
* - executable
|
|
132
|
-
* Those parameters will be used and updated to work with ACP:
|
|
133
|
-
* - hooks (merged with ACP's hooks)
|
|
134
|
-
* - mcpServers (merged with ACP's mcpServers)
|
|
135
|
-
*/
|
|
136
|
-
options?: Options;
|
|
137
|
-
};
|
|
138
|
-
/** Initial model to use for the session (e.g., 'claude-opus-4-5', 'gpt-5.1') */
|
|
139
|
-
model?: string;
|
|
140
|
-
};
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Extra metadata that the agent provides for each tool_call / tool_update update.
|
|
144
|
-
*/
|
|
145
|
-
export type ToolUpdateMeta = {
|
|
146
|
-
claudeCode?: {
|
|
147
|
-
/* The name of the tool that was used in Claude Code. */
|
|
148
|
-
toolName: string;
|
|
149
|
-
/* The structured output provided by Claude Code. */
|
|
150
|
-
toolResponse?: unknown;
|
|
151
|
-
};
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
type ToolUseCache = {
|
|
155
|
-
[key: string]: {
|
|
156
|
-
type: "tool_use" | "server_tool_use" | "mcp_tool_use";
|
|
157
|
-
id: string;
|
|
158
|
-
name: string;
|
|
159
|
-
input: any;
|
|
160
|
-
};
|
|
161
|
-
};
|
|
162
|
-
|
|
163
|
-
// Bypass Permissions doesn't work if we are a root/sudo user
|
|
164
|
-
const IS_ROOT = (process.geteuid?.() ?? process.getuid?.()) === 0;
|
|
165
|
-
|
|
166
|
-
// Implement the ACP Agent interface
|
|
167
|
-
export class ClaudeAcpAgent implements Agent {
|
|
168
|
-
sessions: {
|
|
169
|
-
[key: string]: Session;
|
|
170
|
-
};
|
|
171
|
-
client: AgentSideConnection;
|
|
172
|
-
toolUseCache: ToolUseCache;
|
|
173
|
-
fileContentCache: { [key: string]: string };
|
|
174
|
-
backgroundTerminals: { [key: string]: BackgroundTerminal } = {};
|
|
175
|
-
clientCapabilities?: ClientCapabilities;
|
|
176
|
-
logger: Logger = new Logger({ debug: true, prefix: "[ClaudeAcpAgent]" });
|
|
177
|
-
sessionStore?: SessionStore;
|
|
178
|
-
|
|
179
|
-
constructor(client: AgentSideConnection, sessionStore?: SessionStore) {
|
|
180
|
-
this.sessions = {};
|
|
181
|
-
this.client = client;
|
|
182
|
-
this.toolUseCache = {};
|
|
183
|
-
this.fileContentCache = {};
|
|
184
|
-
this.sessionStore = sessionStore;
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
createSession(
|
|
188
|
-
sessionId: string,
|
|
189
|
-
q: Query,
|
|
190
|
-
input: Pushable<SDKUserMessage>,
|
|
191
|
-
permissionMode: PermissionMode,
|
|
192
|
-
): Session {
|
|
193
|
-
const session: Session = {
|
|
194
|
-
query: q,
|
|
195
|
-
input,
|
|
196
|
-
cancelled: false,
|
|
197
|
-
permissionMode,
|
|
198
|
-
notificationHistory: [],
|
|
199
|
-
};
|
|
200
|
-
this.sessions[sessionId] = session;
|
|
201
|
-
return session;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
appendNotification(
|
|
205
|
-
sessionId: string,
|
|
206
|
-
notification: SessionNotification,
|
|
207
|
-
): void {
|
|
208
|
-
// In-memory only - S3 persistence is now automatic via tapped stream
|
|
209
|
-
this.sessions[sessionId]?.notificationHistory.push(notification);
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
async initialize(request: InitializeRequest): Promise<InitializeResponse> {
|
|
213
|
-
this.clientCapabilities = request.clientCapabilities;
|
|
214
|
-
|
|
215
|
-
// Default authMethod
|
|
216
|
-
const authMethod: any = {
|
|
217
|
-
description: "Run `claude /login` in the terminal",
|
|
218
|
-
name: "Log in with Claude Code",
|
|
219
|
-
id: "claude-login",
|
|
220
|
-
};
|
|
221
|
-
|
|
222
|
-
// If client supports terminal-auth capability, use that instead.
|
|
223
|
-
// if (request.clientCapabilities?._meta?.["terminal-auth"] === true) {
|
|
224
|
-
// const cliPath = fileURLToPath(import.meta.resolve("@anthropic-ai/claude-agent-sdk/cli.js"));
|
|
225
|
-
|
|
226
|
-
// authMethod._meta = {
|
|
227
|
-
// "terminal-auth": {
|
|
228
|
-
// command: "node",
|
|
229
|
-
// args: [cliPath, "/login"],
|
|
230
|
-
// label: "Claude Code Login",
|
|
231
|
-
// },
|
|
232
|
-
// };
|
|
233
|
-
// }
|
|
234
|
-
|
|
235
|
-
return {
|
|
236
|
-
protocolVersion: 1,
|
|
237
|
-
agentCapabilities: {
|
|
238
|
-
promptCapabilities: {
|
|
239
|
-
image: true,
|
|
240
|
-
embeddedContext: true,
|
|
241
|
-
},
|
|
242
|
-
mcpCapabilities: {
|
|
243
|
-
http: true,
|
|
244
|
-
sse: true,
|
|
245
|
-
},
|
|
246
|
-
loadSession: true,
|
|
247
|
-
_meta: {
|
|
248
|
-
posthog: {
|
|
249
|
-
resumeSession: true,
|
|
250
|
-
},
|
|
251
|
-
},
|
|
252
|
-
},
|
|
253
|
-
agentInfo: {
|
|
254
|
-
name: packageJson.name,
|
|
255
|
-
title: "Claude Code",
|
|
256
|
-
version: packageJson.version,
|
|
257
|
-
},
|
|
258
|
-
authMethods: [authMethod],
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
async newSession(params: NewSessionRequest): Promise<NewSessionResponse> {
|
|
262
|
-
if (
|
|
263
|
-
fs.existsSync(path.resolve(os.homedir(), ".claude.json.backup")) &&
|
|
264
|
-
!fs.existsSync(path.resolve(os.homedir(), ".claude.json"))
|
|
265
|
-
) {
|
|
266
|
-
throw RequestError.authRequired();
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// Allow caller to specify sessionId via _meta (e.g. taskRunId in our case)
|
|
270
|
-
const sessionId =
|
|
271
|
-
(params._meta as { sessionId?: string } | undefined)?.sessionId ||
|
|
272
|
-
uuidv7();
|
|
273
|
-
const input = new Pushable<SDKUserMessage>();
|
|
274
|
-
|
|
275
|
-
const mcpServers: Record<string, McpServerConfig> = {};
|
|
276
|
-
if (Array.isArray(params.mcpServers)) {
|
|
277
|
-
for (const server of params.mcpServers) {
|
|
278
|
-
if ("type" in server) {
|
|
279
|
-
mcpServers[server.name] = {
|
|
280
|
-
type: server.type,
|
|
281
|
-
url: server.url,
|
|
282
|
-
headers: server.headers
|
|
283
|
-
? Object.fromEntries(server.headers.map((e) => [e.name, e.value]))
|
|
284
|
-
: undefined,
|
|
285
|
-
};
|
|
286
|
-
} else {
|
|
287
|
-
mcpServers[server.name] = {
|
|
288
|
-
type: "stdio",
|
|
289
|
-
command: server.command,
|
|
290
|
-
args: server.args,
|
|
291
|
-
env: server.env
|
|
292
|
-
? Object.fromEntries(server.env.map((e) => [e.name, e.value]))
|
|
293
|
-
: undefined,
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// Only add the acp MCP server if built-in tools are not disabled
|
|
300
|
-
if (!params._meta?.disableBuiltInTools) {
|
|
301
|
-
const server = createMcpServer(this, sessionId, this.clientCapabilities);
|
|
302
|
-
mcpServers.acp = {
|
|
303
|
-
type: "sdk",
|
|
304
|
-
name: "acp",
|
|
305
|
-
instance: server,
|
|
306
|
-
};
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
let systemPrompt: Options["systemPrompt"] = {
|
|
310
|
-
type: "preset",
|
|
311
|
-
preset: "claude_code",
|
|
312
|
-
};
|
|
313
|
-
if (params._meta?.systemPrompt) {
|
|
314
|
-
const customPrompt = params._meta.systemPrompt;
|
|
315
|
-
if (typeof customPrompt === "string") {
|
|
316
|
-
systemPrompt = customPrompt;
|
|
317
|
-
} else if (
|
|
318
|
-
typeof customPrompt === "object" &&
|
|
319
|
-
"append" in customPrompt &&
|
|
320
|
-
typeof customPrompt.append === "string"
|
|
321
|
-
) {
|
|
322
|
-
systemPrompt.append = customPrompt.append;
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
const permissionMode = "default";
|
|
327
|
-
|
|
328
|
-
// Extract options from _meta if provided
|
|
329
|
-
const userProvidedOptions = (params._meta as NewSessionMeta | undefined)
|
|
330
|
-
?.claudeCode?.options;
|
|
331
|
-
|
|
332
|
-
const options: Options = {
|
|
333
|
-
systemPrompt,
|
|
334
|
-
settingSources: ["user", "project", "local"],
|
|
335
|
-
stderr: (err) => this.logger.error(err),
|
|
336
|
-
...userProvidedOptions,
|
|
337
|
-
// Override certain fields that must be controlled by ACP
|
|
338
|
-
cwd: params.cwd,
|
|
339
|
-
includePartialMessages: true,
|
|
340
|
-
mcpServers: { ...(userProvidedOptions?.mcpServers || {}), ...mcpServers },
|
|
341
|
-
// If we want bypassPermissions to be an option, we have to allow it here.
|
|
342
|
-
// But it doesn't work in root mode, so we only activate it if it will work.
|
|
343
|
-
allowDangerouslySkipPermissions: !IS_ROOT,
|
|
344
|
-
permissionMode,
|
|
345
|
-
canUseTool: this.canUseTool(sessionId),
|
|
346
|
-
// Use "node" to resolve via PATH where a symlink to Electron exists.
|
|
347
|
-
// This avoids launching the Electron binary directly from the app bundle,
|
|
348
|
-
// which can cause dock icons to appear on macOS even with ELECTRON_RUN_AS_NODE.
|
|
349
|
-
executable: "node",
|
|
350
|
-
// Prevent spawned Electron processes from showing in dock/tray.
|
|
351
|
-
// Must merge with process.env since SDK replaces rather than merges.
|
|
352
|
-
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
|
|
353
|
-
...(process.env.CLAUDE_CODE_EXECUTABLE && {
|
|
354
|
-
pathToClaudeCodeExecutable: process.env.CLAUDE_CODE_EXECUTABLE,
|
|
355
|
-
}),
|
|
356
|
-
hooks: {
|
|
357
|
-
...userProvidedOptions?.hooks,
|
|
358
|
-
PostToolUse: [
|
|
359
|
-
...(userProvidedOptions?.hooks?.PostToolUse || []),
|
|
360
|
-
{
|
|
361
|
-
hooks: [createPostToolUseHook(this.logger)],
|
|
362
|
-
},
|
|
363
|
-
],
|
|
364
|
-
},
|
|
365
|
-
};
|
|
366
|
-
|
|
367
|
-
const allowedTools = [];
|
|
368
|
-
const disallowedTools = [];
|
|
369
|
-
|
|
370
|
-
// Check if built-in tools should be disabled
|
|
371
|
-
const disableBuiltInTools = params._meta?.disableBuiltInTools === true;
|
|
372
|
-
|
|
373
|
-
if (!disableBuiltInTools) {
|
|
374
|
-
if (this.clientCapabilities?.fs?.readTextFile) {
|
|
375
|
-
allowedTools.push(toolNames.read);
|
|
376
|
-
disallowedTools.push("Read");
|
|
377
|
-
}
|
|
378
|
-
if (this.clientCapabilities?.fs?.writeTextFile) {
|
|
379
|
-
disallowedTools.push("Write", "Edit");
|
|
380
|
-
}
|
|
381
|
-
if (this.clientCapabilities?.terminal) {
|
|
382
|
-
allowedTools.push(toolNames.bashOutput, toolNames.killShell);
|
|
383
|
-
disallowedTools.push("Bash", "BashOutput", "KillShell");
|
|
384
|
-
}
|
|
385
|
-
} else {
|
|
386
|
-
// When built-in tools are disabled, explicitly disallow all of them
|
|
387
|
-
disallowedTools.push(
|
|
388
|
-
toolNames.read,
|
|
389
|
-
toolNames.write,
|
|
390
|
-
toolNames.edit,
|
|
391
|
-
toolNames.bash,
|
|
392
|
-
toolNames.bashOutput,
|
|
393
|
-
toolNames.killShell,
|
|
394
|
-
"Read",
|
|
395
|
-
"Write",
|
|
396
|
-
"Edit",
|
|
397
|
-
"Bash",
|
|
398
|
-
"BashOutput",
|
|
399
|
-
"KillShell",
|
|
400
|
-
"Glob",
|
|
401
|
-
"Grep",
|
|
402
|
-
"Task",
|
|
403
|
-
"TodoWrite",
|
|
404
|
-
"ExitPlanMode",
|
|
405
|
-
"WebSearch",
|
|
406
|
-
"WebFetch",
|
|
407
|
-
"AskUserQuestion",
|
|
408
|
-
"SlashCommand",
|
|
409
|
-
"Skill",
|
|
410
|
-
"NotebookEdit",
|
|
411
|
-
);
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
if (allowedTools.length > 0) {
|
|
415
|
-
options.allowedTools = allowedTools;
|
|
416
|
-
}
|
|
417
|
-
if (disallowedTools.length > 0) {
|
|
418
|
-
options.disallowedTools = disallowedTools;
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
// Handle abort controller from meta options
|
|
422
|
-
const abortController = userProvidedOptions?.abortController;
|
|
423
|
-
if (abortController?.signal.aborted) {
|
|
424
|
-
throw new Error("Cancelled");
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
// Clear statsig cache before creating query to avoid input_examples bug
|
|
428
|
-
clearStatsigCache();
|
|
429
|
-
|
|
430
|
-
const q = query({
|
|
431
|
-
prompt: input,
|
|
432
|
-
options,
|
|
433
|
-
});
|
|
434
|
-
|
|
435
|
-
this.createSession(sessionId, q, input, permissionMode);
|
|
436
|
-
|
|
437
|
-
// Register for S3 persistence if config provided
|
|
438
|
-
const persistence = params._meta?.persistence as
|
|
439
|
-
| SessionPersistenceConfig
|
|
440
|
-
| undefined;
|
|
441
|
-
if (persistence && this.sessionStore) {
|
|
442
|
-
this.sessionStore.register(sessionId, persistence);
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
const availableCommands = await getAvailableSlashCommands(q);
|
|
446
|
-
const models = await getAvailableModels(q);
|
|
447
|
-
|
|
448
|
-
// Set initial model if provided via _meta (must be after getAvailableModels which resets to default)
|
|
449
|
-
const requestedModel = (params._meta as NewSessionMeta | undefined)?.model;
|
|
450
|
-
if (requestedModel) {
|
|
451
|
-
try {
|
|
452
|
-
await q.setModel(requestedModel);
|
|
453
|
-
this.logger.info("Set initial model", { model: requestedModel });
|
|
454
|
-
} catch (err) {
|
|
455
|
-
this.logger.warn("Failed to set initial model, using default", {
|
|
456
|
-
requestedModel,
|
|
457
|
-
error: err,
|
|
458
|
-
});
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
// Needs to happen after we return the session
|
|
463
|
-
setTimeout(() => {
|
|
464
|
-
this.client.sessionUpdate({
|
|
465
|
-
sessionId,
|
|
466
|
-
update: {
|
|
467
|
-
sessionUpdate: "available_commands_update",
|
|
468
|
-
availableCommands,
|
|
469
|
-
},
|
|
470
|
-
});
|
|
471
|
-
}, 0);
|
|
472
|
-
|
|
473
|
-
const availableModes = [
|
|
474
|
-
{
|
|
475
|
-
id: "default",
|
|
476
|
-
name: "Always Ask",
|
|
477
|
-
description: "Prompts for permission on first use of each tool",
|
|
478
|
-
},
|
|
479
|
-
{
|
|
480
|
-
id: "acceptEdits",
|
|
481
|
-
name: "Accept Edits",
|
|
482
|
-
description:
|
|
483
|
-
"Automatically accepts file edit permissions for the session",
|
|
484
|
-
},
|
|
485
|
-
{
|
|
486
|
-
id: "plan",
|
|
487
|
-
name: "Plan Mode",
|
|
488
|
-
description:
|
|
489
|
-
"Claude can analyze but not modify files or execute commands",
|
|
490
|
-
},
|
|
491
|
-
];
|
|
492
|
-
// Only works in non-root mode
|
|
493
|
-
if (!IS_ROOT) {
|
|
494
|
-
availableModes.push({
|
|
495
|
-
id: "bypassPermissions",
|
|
496
|
-
name: "Bypass Permissions",
|
|
497
|
-
description: "Skips all permission prompts",
|
|
498
|
-
});
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
return {
|
|
502
|
-
sessionId,
|
|
503
|
-
models,
|
|
504
|
-
modes: {
|
|
505
|
-
currentModeId: permissionMode,
|
|
506
|
-
availableModes,
|
|
507
|
-
},
|
|
508
|
-
};
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
async authenticate(_params: AuthenticateRequest): Promise<void> {
|
|
512
|
-
throw new Error("Method not implemented.");
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
async prompt(params: PromptRequest): Promise<PromptResponse> {
|
|
516
|
-
if (!this.sessions[params.sessionId]) {
|
|
517
|
-
throw new Error("Session not found");
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
this.sessions[params.sessionId].cancelled = false;
|
|
521
|
-
|
|
522
|
-
const { query, input } = this.sessions[params.sessionId];
|
|
523
|
-
|
|
524
|
-
// Capture and store user message for replay
|
|
525
|
-
for (const chunk of params.prompt) {
|
|
526
|
-
const userNotification: SessionNotification = {
|
|
527
|
-
sessionId: params.sessionId,
|
|
528
|
-
update: {
|
|
529
|
-
sessionUpdate: "user_message_chunk",
|
|
530
|
-
content: chunk,
|
|
531
|
-
},
|
|
532
|
-
};
|
|
533
|
-
await this.client.sessionUpdate(userNotification);
|
|
534
|
-
this.appendNotification(params.sessionId, userNotification);
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
input.push(promptToClaude(params));
|
|
538
|
-
while (true) {
|
|
539
|
-
const { value: message, done } = await query.next();
|
|
540
|
-
if (done || !message) {
|
|
541
|
-
if (this.sessions[params.sessionId].cancelled) {
|
|
542
|
-
return { stopReason: "cancelled" };
|
|
543
|
-
}
|
|
544
|
-
break;
|
|
545
|
-
}
|
|
546
|
-
this.logger.debug("SDK message received", {
|
|
547
|
-
type: message.type,
|
|
548
|
-
subtype: (message as any).subtype,
|
|
549
|
-
});
|
|
550
|
-
|
|
551
|
-
switch (message.type) {
|
|
552
|
-
case "system":
|
|
553
|
-
switch (message.subtype) {
|
|
554
|
-
case "init":
|
|
555
|
-
// Capture SDK session ID and notify client for persistence
|
|
556
|
-
if (message.session_id) {
|
|
557
|
-
const session = this.sessions[params.sessionId];
|
|
558
|
-
if (session && !session.sdkSessionId) {
|
|
559
|
-
session.sdkSessionId = message.session_id;
|
|
560
|
-
this.client.extNotification("_posthog/sdk_session", {
|
|
561
|
-
sessionId: params.sessionId,
|
|
562
|
-
sdkSessionId: message.session_id,
|
|
563
|
-
});
|
|
564
|
-
}
|
|
565
|
-
}
|
|
566
|
-
break;
|
|
567
|
-
case "compact_boundary":
|
|
568
|
-
case "hook_response":
|
|
569
|
-
case "status":
|
|
570
|
-
// Todo: process via status api: https://docs.claude.com/en/docs/claude-code/hooks#hook-output
|
|
571
|
-
break;
|
|
572
|
-
default:
|
|
573
|
-
unreachable(message, this.logger);
|
|
574
|
-
break;
|
|
575
|
-
}
|
|
576
|
-
break;
|
|
577
|
-
case "result": {
|
|
578
|
-
if (this.sessions[params.sessionId].cancelled) {
|
|
579
|
-
return { stopReason: "cancelled" };
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
switch (message.subtype) {
|
|
583
|
-
case "success": {
|
|
584
|
-
if (message.result.includes("Please run /login")) {
|
|
585
|
-
throw RequestError.authRequired();
|
|
586
|
-
}
|
|
587
|
-
if (message.is_error) {
|
|
588
|
-
throw RequestError.internalError(undefined, message.result);
|
|
589
|
-
}
|
|
590
|
-
return { stopReason: "end_turn" };
|
|
591
|
-
}
|
|
592
|
-
case "error_during_execution":
|
|
593
|
-
if (message.is_error) {
|
|
594
|
-
throw RequestError.internalError(
|
|
595
|
-
undefined,
|
|
596
|
-
message.errors.join(", ") || message.subtype,
|
|
597
|
-
);
|
|
598
|
-
}
|
|
599
|
-
return { stopReason: "end_turn" };
|
|
600
|
-
case "error_max_budget_usd":
|
|
601
|
-
case "error_max_turns":
|
|
602
|
-
case "error_max_structured_output_retries":
|
|
603
|
-
if (message.is_error) {
|
|
604
|
-
throw RequestError.internalError(
|
|
605
|
-
undefined,
|
|
606
|
-
message.errors.join(", ") || message.subtype,
|
|
607
|
-
);
|
|
608
|
-
}
|
|
609
|
-
return { stopReason: "max_turn_requests" };
|
|
610
|
-
default:
|
|
611
|
-
unreachable(message, this.logger);
|
|
612
|
-
break;
|
|
613
|
-
}
|
|
614
|
-
break;
|
|
615
|
-
}
|
|
616
|
-
case "stream_event": {
|
|
617
|
-
this.logger.debug("Stream event", { eventType: message.event?.type });
|
|
618
|
-
for (const notification of streamEventToAcpNotifications(
|
|
619
|
-
message,
|
|
620
|
-
params.sessionId,
|
|
621
|
-
this.toolUseCache,
|
|
622
|
-
this.fileContentCache,
|
|
623
|
-
this.client,
|
|
624
|
-
this.logger,
|
|
625
|
-
)) {
|
|
626
|
-
await this.client.sessionUpdate(notification);
|
|
627
|
-
this.appendNotification(params.sessionId, notification);
|
|
628
|
-
}
|
|
629
|
-
break;
|
|
630
|
-
}
|
|
631
|
-
case "user":
|
|
632
|
-
case "assistant": {
|
|
633
|
-
if (this.sessions[params.sessionId].cancelled) {
|
|
634
|
-
break;
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
// Slash commands like /compact can generate invalid output... doesn't match
|
|
638
|
-
// their own docs: https://docs.anthropic.com/en/docs/claude-code/sdk/sdk-slash-commands#%2Fcompact-compact-conversation-history
|
|
639
|
-
if (
|
|
640
|
-
typeof message.message.content === "string" &&
|
|
641
|
-
message.message.content.includes("<local-command-stdout>")
|
|
642
|
-
) {
|
|
643
|
-
this.logger.info(message.message.content);
|
|
644
|
-
break;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
if (
|
|
648
|
-
typeof message.message.content === "string" &&
|
|
649
|
-
message.message.content.includes("<local-command-stderr>")
|
|
650
|
-
) {
|
|
651
|
-
this.logger.error(message.message.content);
|
|
652
|
-
break;
|
|
653
|
-
}
|
|
654
|
-
// Skip these user messages for now, since they seem to just be messages we don't want in the feed
|
|
655
|
-
if (
|
|
656
|
-
message.type === "user" &&
|
|
657
|
-
(typeof message.message.content === "string" ||
|
|
658
|
-
(Array.isArray(message.message.content) &&
|
|
659
|
-
message.message.content.length === 1 &&
|
|
660
|
-
message.message.content[0].type === "text"))
|
|
661
|
-
) {
|
|
662
|
-
break;
|
|
663
|
-
}
|
|
664
|
-
|
|
665
|
-
if (
|
|
666
|
-
message.type === "assistant" &&
|
|
667
|
-
message.message.model === "<synthetic>" &&
|
|
668
|
-
Array.isArray(message.message.content) &&
|
|
669
|
-
message.message.content.length === 1 &&
|
|
670
|
-
message.message.content[0].type === "text" &&
|
|
671
|
-
message.message.content[0].text.includes("Please run /login")
|
|
672
|
-
) {
|
|
673
|
-
throw RequestError.authRequired();
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
// Text/thinking is streamed via stream_event, so skip them here to avoid duplication.
|
|
677
|
-
const content = message.message.content;
|
|
678
|
-
const contentToProcess = Array.isArray(content)
|
|
679
|
-
? content.filter(
|
|
680
|
-
(block) => block.type !== "text" && block.type !== "thinking",
|
|
681
|
-
)
|
|
682
|
-
: content;
|
|
683
|
-
|
|
684
|
-
for (const notification of toAcpNotifications(
|
|
685
|
-
contentToProcess as typeof content,
|
|
686
|
-
message.message.role,
|
|
687
|
-
params.sessionId,
|
|
688
|
-
this.toolUseCache,
|
|
689
|
-
this.fileContentCache,
|
|
690
|
-
this.client,
|
|
691
|
-
this.logger,
|
|
692
|
-
)) {
|
|
693
|
-
await this.client.sessionUpdate(notification);
|
|
694
|
-
this.appendNotification(params.sessionId, notification);
|
|
695
|
-
}
|
|
696
|
-
break;
|
|
697
|
-
}
|
|
698
|
-
case "tool_progress":
|
|
699
|
-
break;
|
|
700
|
-
case "auth_status":
|
|
701
|
-
break;
|
|
702
|
-
default:
|
|
703
|
-
unreachable(message, this.logger);
|
|
704
|
-
break;
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
throw new Error("Session did not end in result");
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
async cancel(params: CancelNotification): Promise<void> {
|
|
711
|
-
if (!this.sessions[params.sessionId]) {
|
|
712
|
-
throw new Error("Session not found");
|
|
713
|
-
}
|
|
714
|
-
this.sessions[params.sessionId].cancelled = true;
|
|
715
|
-
await this.sessions[params.sessionId].query.interrupt();
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
async setSessionModel(params: SetSessionModelRequest) {
|
|
719
|
-
if (!this.sessions[params.sessionId]) {
|
|
720
|
-
throw new Error("Session not found");
|
|
721
|
-
}
|
|
722
|
-
await this.sessions[params.sessionId].query.setModel(params.modelId);
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
async setSessionMode(
|
|
726
|
-
params: SetSessionModeRequest,
|
|
727
|
-
): Promise<SetSessionModeResponse> {
|
|
728
|
-
if (!this.sessions[params.sessionId]) {
|
|
729
|
-
throw new Error("Session not found");
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
switch (params.modeId) {
|
|
733
|
-
case "default":
|
|
734
|
-
case "acceptEdits":
|
|
735
|
-
case "bypassPermissions":
|
|
736
|
-
case "plan":
|
|
737
|
-
this.sessions[params.sessionId].permissionMode = params.modeId;
|
|
738
|
-
try {
|
|
739
|
-
await this.sessions[params.sessionId].query.setPermissionMode(
|
|
740
|
-
params.modeId,
|
|
741
|
-
);
|
|
742
|
-
} catch (error) {
|
|
743
|
-
const errorMessage =
|
|
744
|
-
error instanceof Error && error.message
|
|
745
|
-
? error.message
|
|
746
|
-
: "Invalid Mode";
|
|
747
|
-
|
|
748
|
-
throw new Error(errorMessage);
|
|
749
|
-
}
|
|
750
|
-
return {};
|
|
751
|
-
default:
|
|
752
|
-
throw new Error("Invalid Mode");
|
|
753
|
-
}
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
async readTextFile(
|
|
757
|
-
params: ReadTextFileRequest,
|
|
758
|
-
): Promise<ReadTextFileResponse> {
|
|
759
|
-
const response = await this.client.readTextFile(params);
|
|
760
|
-
if (!params.limit && !params.line) {
|
|
761
|
-
this.fileContentCache[params.path] = response.content;
|
|
762
|
-
}
|
|
763
|
-
return response;
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
async writeTextFile(
|
|
767
|
-
params: WriteTextFileRequest,
|
|
768
|
-
): Promise<WriteTextFileResponse> {
|
|
769
|
-
const response = await this.client.writeTextFile(params);
|
|
770
|
-
this.fileContentCache[params.path] = params.content;
|
|
771
|
-
return response;
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
/**
|
|
775
|
-
* Load session delegates to resumeSession since we have no need to replay history.
|
|
776
|
-
* Client is responsible for fetching and rendering history from S3.
|
|
777
|
-
*/
|
|
778
|
-
async loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse> {
|
|
779
|
-
return this.resumeSession(params);
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
canUseTool(sessionId: string): CanUseTool {
|
|
783
|
-
return async (toolName, toolInput, { suggestions, toolUseID }) => {
|
|
784
|
-
const session = this.sessions[sessionId];
|
|
785
|
-
if (!session) {
|
|
786
|
-
return {
|
|
787
|
-
behavior: "deny",
|
|
788
|
-
message: "Session not found",
|
|
789
|
-
interrupt: true,
|
|
790
|
-
};
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
if (toolName === "ExitPlanMode") {
|
|
794
|
-
const response = await this.client.requestPermission({
|
|
795
|
-
options: [
|
|
796
|
-
{
|
|
797
|
-
kind: "allow_always",
|
|
798
|
-
name: "Yes, and auto-accept edits",
|
|
799
|
-
optionId: "acceptEdits",
|
|
800
|
-
},
|
|
801
|
-
{
|
|
802
|
-
kind: "allow_once",
|
|
803
|
-
name: "Yes, and manually approve edits",
|
|
804
|
-
optionId: "default",
|
|
805
|
-
},
|
|
806
|
-
{
|
|
807
|
-
kind: "reject_once",
|
|
808
|
-
name: "No, keep planning",
|
|
809
|
-
optionId: "plan",
|
|
810
|
-
},
|
|
811
|
-
],
|
|
812
|
-
sessionId,
|
|
813
|
-
toolCall: {
|
|
814
|
-
toolCallId: toolUseID,
|
|
815
|
-
rawInput: toolInput,
|
|
816
|
-
title: toolInfoFromToolUse(
|
|
817
|
-
{ name: toolName, input: toolInput },
|
|
818
|
-
this.fileContentCache,
|
|
819
|
-
this.logger,
|
|
820
|
-
).title,
|
|
821
|
-
},
|
|
822
|
-
});
|
|
823
|
-
|
|
824
|
-
if (
|
|
825
|
-
response.outcome?.outcome === "selected" &&
|
|
826
|
-
(response.outcome.optionId === "default" ||
|
|
827
|
-
response.outcome.optionId === "acceptEdits")
|
|
828
|
-
) {
|
|
829
|
-
session.permissionMode = response.outcome.optionId;
|
|
830
|
-
await this.client.sessionUpdate({
|
|
831
|
-
sessionId,
|
|
832
|
-
update: {
|
|
833
|
-
sessionUpdate: "current_mode_update",
|
|
834
|
-
currentModeId: response.outcome.optionId,
|
|
835
|
-
},
|
|
836
|
-
});
|
|
837
|
-
|
|
838
|
-
return {
|
|
839
|
-
behavior: "allow",
|
|
840
|
-
updatedInput: toolInput,
|
|
841
|
-
updatedPermissions: suggestions ?? [
|
|
842
|
-
{
|
|
843
|
-
type: "setMode",
|
|
844
|
-
mode: response.outcome.optionId,
|
|
845
|
-
destination: "session",
|
|
846
|
-
},
|
|
847
|
-
],
|
|
848
|
-
};
|
|
849
|
-
} else {
|
|
850
|
-
return {
|
|
851
|
-
behavior: "deny",
|
|
852
|
-
message: "User rejected request to exit plan mode.",
|
|
853
|
-
interrupt: true,
|
|
854
|
-
};
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
|
|
858
|
-
if (
|
|
859
|
-
session.permissionMode === "bypassPermissions" ||
|
|
860
|
-
(session.permissionMode === "acceptEdits" &&
|
|
861
|
-
EDIT_TOOL_NAMES.includes(toolName))
|
|
862
|
-
) {
|
|
863
|
-
return {
|
|
864
|
-
behavior: "allow",
|
|
865
|
-
updatedInput: toolInput,
|
|
866
|
-
updatedPermissions: suggestions ?? [
|
|
867
|
-
{
|
|
868
|
-
type: "addRules",
|
|
869
|
-
rules: [{ toolName }],
|
|
870
|
-
behavior: "allow",
|
|
871
|
-
destination: "session",
|
|
872
|
-
},
|
|
873
|
-
],
|
|
874
|
-
};
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
const response = await this.client.requestPermission({
|
|
878
|
-
options: [
|
|
879
|
-
{
|
|
880
|
-
kind: "allow_always",
|
|
881
|
-
name: "Always Allow",
|
|
882
|
-
optionId: "allow_always",
|
|
883
|
-
},
|
|
884
|
-
{ kind: "allow_once", name: "Allow", optionId: "allow" },
|
|
885
|
-
{ kind: "reject_once", name: "Reject", optionId: "reject" },
|
|
886
|
-
],
|
|
887
|
-
sessionId,
|
|
888
|
-
toolCall: {
|
|
889
|
-
toolCallId: toolUseID,
|
|
890
|
-
rawInput: toolInput,
|
|
891
|
-
title: toolInfoFromToolUse(
|
|
892
|
-
{ name: toolName, input: toolInput },
|
|
893
|
-
this.fileContentCache,
|
|
894
|
-
this.logger,
|
|
895
|
-
).title,
|
|
896
|
-
},
|
|
897
|
-
});
|
|
898
|
-
if (
|
|
899
|
-
response.outcome?.outcome === "selected" &&
|
|
900
|
-
(response.outcome.optionId === "allow" ||
|
|
901
|
-
response.outcome.optionId === "allow_always")
|
|
902
|
-
) {
|
|
903
|
-
// If Claude Code has suggestions, it will update their settings already
|
|
904
|
-
if (response.outcome.optionId === "allow_always") {
|
|
905
|
-
return {
|
|
906
|
-
behavior: "allow",
|
|
907
|
-
updatedInput: toolInput,
|
|
908
|
-
updatedPermissions: suggestions ?? [
|
|
909
|
-
{
|
|
910
|
-
type: "addRules",
|
|
911
|
-
rules: [{ toolName }],
|
|
912
|
-
behavior: "allow",
|
|
913
|
-
destination: "session",
|
|
914
|
-
},
|
|
915
|
-
],
|
|
916
|
-
};
|
|
917
|
-
}
|
|
918
|
-
return {
|
|
919
|
-
behavior: "allow",
|
|
920
|
-
updatedInput: toolInput,
|
|
921
|
-
};
|
|
922
|
-
} else {
|
|
923
|
-
return {
|
|
924
|
-
behavior: "deny",
|
|
925
|
-
message: "User refused permission to run tool",
|
|
926
|
-
interrupt: true,
|
|
927
|
-
};
|
|
928
|
-
}
|
|
929
|
-
};
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
/**
|
|
933
|
-
* Handle custom extension methods.
|
|
934
|
-
* Per ACP spec, extension methods start with underscore.
|
|
935
|
-
*/
|
|
936
|
-
async extMethod(
|
|
937
|
-
method: string,
|
|
938
|
-
params: Record<string, unknown>,
|
|
939
|
-
): Promise<Record<string, unknown>> {
|
|
940
|
-
if (method === "_posthog/session/resume") {
|
|
941
|
-
await this.resumeSession(params as unknown as LoadSessionRequest);
|
|
942
|
-
return {};
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
if (method === "session/setModel") {
|
|
946
|
-
const { sessionId, modelId } = params as {
|
|
947
|
-
sessionId: string;
|
|
948
|
-
modelId: string;
|
|
949
|
-
};
|
|
950
|
-
await this.setSessionModel({ sessionId, modelId });
|
|
951
|
-
return {};
|
|
952
|
-
}
|
|
953
|
-
|
|
954
|
-
throw RequestError.methodNotFound(method);
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
/**
|
|
958
|
-
* Resume a session without replaying history.
|
|
959
|
-
* Client is responsible for fetching and rendering history from S3.
|
|
960
|
-
* This basically implemetns the ACP session/resume RFD:
|
|
961
|
-
* https://agentclientprotocol.com/rfds/session-resume
|
|
962
|
-
*/
|
|
963
|
-
async resumeSession(
|
|
964
|
-
params: LoadSessionRequest,
|
|
965
|
-
): Promise<LoadSessionResponse> {
|
|
966
|
-
this.logger.info("[RESUME] Resuming session", { params });
|
|
967
|
-
const { sessionId } = params;
|
|
968
|
-
|
|
969
|
-
// Extract persistence config and SDK session ID from _meta
|
|
970
|
-
const persistence = params._meta?.persistence as
|
|
971
|
-
| SessionPersistenceConfig
|
|
972
|
-
| undefined;
|
|
973
|
-
const sdkSessionId = params._meta?.sdkSessionId as string | undefined;
|
|
974
|
-
|
|
975
|
-
if (!this.sessions[sessionId]) {
|
|
976
|
-
const input = new Pushable<SDKUserMessage>();
|
|
977
|
-
|
|
978
|
-
const mcpServers: Record<string, McpServerConfig> = {};
|
|
979
|
-
if (Array.isArray(params.mcpServers)) {
|
|
980
|
-
for (const server of params.mcpServers) {
|
|
981
|
-
if ("type" in server) {
|
|
982
|
-
mcpServers[server.name] = {
|
|
983
|
-
type: server.type,
|
|
984
|
-
url: server.url,
|
|
985
|
-
headers: server.headers
|
|
986
|
-
? Object.fromEntries(
|
|
987
|
-
server.headers.map((e) => [e.name, e.value]),
|
|
988
|
-
)
|
|
989
|
-
: undefined,
|
|
990
|
-
};
|
|
991
|
-
} else {
|
|
992
|
-
mcpServers[server.name] = {
|
|
993
|
-
type: "stdio",
|
|
994
|
-
command: server.command,
|
|
995
|
-
args: server.args,
|
|
996
|
-
env: server.env
|
|
997
|
-
? Object.fromEntries(server.env.map((e) => [e.name, e.value]))
|
|
998
|
-
: undefined,
|
|
999
|
-
};
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
|
|
1004
|
-
const server = createMcpServer(this, sessionId, this.clientCapabilities);
|
|
1005
|
-
mcpServers.acp = {
|
|
1006
|
-
type: "sdk",
|
|
1007
|
-
name: "acp",
|
|
1008
|
-
instance: server,
|
|
1009
|
-
};
|
|
1010
|
-
|
|
1011
|
-
const permissionMode = "default";
|
|
1012
|
-
|
|
1013
|
-
this.logger.info("Resuming session", {
|
|
1014
|
-
cwd: params.cwd,
|
|
1015
|
-
sdkSessionId,
|
|
1016
|
-
persistence,
|
|
1017
|
-
});
|
|
1018
|
-
const options: Options = {
|
|
1019
|
-
cwd: params.cwd,
|
|
1020
|
-
includePartialMessages: true,
|
|
1021
|
-
mcpServers,
|
|
1022
|
-
systemPrompt: { type: "preset", preset: "claude_code" },
|
|
1023
|
-
settingSources: ["user", "project", "local"],
|
|
1024
|
-
allowDangerouslySkipPermissions: !IS_ROOT,
|
|
1025
|
-
permissionMode,
|
|
1026
|
-
canUseTool: this.canUseTool(sessionId),
|
|
1027
|
-
stderr: (err) => this.logger.error(err),
|
|
1028
|
-
// Use "node" to resolve via PATH where a symlink to Electron exists.
|
|
1029
|
-
// This avoids launching the Electron binary directly from the app bundle,
|
|
1030
|
-
// which can cause dock icons to appear on macOS even with ELECTRON_RUN_AS_NODE.
|
|
1031
|
-
executable: "node",
|
|
1032
|
-
// Prevent spawned Electron processes from showing in dock/tray.
|
|
1033
|
-
// Must merge with process.env since SDK replaces rather than merges.
|
|
1034
|
-
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
|
|
1035
|
-
...(process.env.CLAUDE_CODE_EXECUTABLE && {
|
|
1036
|
-
pathToClaudeCodeExecutable: process.env.CLAUDE_CODE_EXECUTABLE,
|
|
1037
|
-
}),
|
|
1038
|
-
// Resume from SDK session if available
|
|
1039
|
-
...(sdkSessionId && { resume: sdkSessionId }),
|
|
1040
|
-
hooks: {
|
|
1041
|
-
PostToolUse: [
|
|
1042
|
-
{
|
|
1043
|
-
hooks: [createPostToolUseHook(this.logger)],
|
|
1044
|
-
},
|
|
1045
|
-
],
|
|
1046
|
-
},
|
|
1047
|
-
};
|
|
1048
|
-
|
|
1049
|
-
// Clear statsig cache before creating query to avoid input_examples bug
|
|
1050
|
-
clearStatsigCache();
|
|
1051
|
-
|
|
1052
|
-
const q = query({
|
|
1053
|
-
prompt: input,
|
|
1054
|
-
options,
|
|
1055
|
-
});
|
|
1056
|
-
|
|
1057
|
-
const availableCommands = await getAvailableSlashCommands(q);
|
|
1058
|
-
|
|
1059
|
-
const newSession = this.createSession(
|
|
1060
|
-
sessionId,
|
|
1061
|
-
q,
|
|
1062
|
-
input,
|
|
1063
|
-
permissionMode,
|
|
1064
|
-
);
|
|
1065
|
-
|
|
1066
|
-
// Store SDK session ID if resuming
|
|
1067
|
-
if (sdkSessionId) {
|
|
1068
|
-
newSession.sdkSessionId = sdkSessionId;
|
|
1069
|
-
}
|
|
1070
|
-
|
|
1071
|
-
// Register for future persistence
|
|
1072
|
-
if (persistence && this.sessionStore) {
|
|
1073
|
-
this.sessionStore.register(sessionId, persistence);
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
setTimeout(() => {
|
|
1077
|
-
this.client.sessionUpdate({
|
|
1078
|
-
sessionId,
|
|
1079
|
-
update: {
|
|
1080
|
-
sessionUpdate: "available_commands_update",
|
|
1081
|
-
availableCommands,
|
|
1082
|
-
},
|
|
1083
|
-
});
|
|
1084
|
-
}, 0);
|
|
1085
|
-
}
|
|
1086
|
-
|
|
1087
|
-
return {};
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
|
|
1091
|
-
async function getAvailableModels(query: Query): Promise<SessionModelState> {
|
|
1092
|
-
const models = await query.supportedModels();
|
|
1093
|
-
|
|
1094
|
-
// Query doesn't give us access to the currently selected model, so we just choose the first model in the list.
|
|
1095
|
-
const currentModel = models[0];
|
|
1096
|
-
await query.setModel(currentModel.value);
|
|
1097
|
-
|
|
1098
|
-
const availableModels = models.map((model) => ({
|
|
1099
|
-
modelId: model.value,
|
|
1100
|
-
name: model.displayName,
|
|
1101
|
-
description: model.description,
|
|
1102
|
-
}));
|
|
1103
|
-
|
|
1104
|
-
return {
|
|
1105
|
-
availableModels,
|
|
1106
|
-
currentModelId: currentModel.value,
|
|
1107
|
-
};
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
async function getAvailableSlashCommands(
|
|
1111
|
-
query: Query,
|
|
1112
|
-
): Promise<AvailableCommand[]> {
|
|
1113
|
-
const UNSUPPORTED_COMMANDS = [
|
|
1114
|
-
"context",
|
|
1115
|
-
"cost",
|
|
1116
|
-
"login",
|
|
1117
|
-
"logout",
|
|
1118
|
-
"output-style:new",
|
|
1119
|
-
"release-notes",
|
|
1120
|
-
"todos",
|
|
1121
|
-
];
|
|
1122
|
-
const commands = await query.supportedCommands();
|
|
1123
|
-
|
|
1124
|
-
return commands
|
|
1125
|
-
.map((command) => {
|
|
1126
|
-
const input = command.argumentHint
|
|
1127
|
-
? { hint: command.argumentHint }
|
|
1128
|
-
: null;
|
|
1129
|
-
let name = command.name;
|
|
1130
|
-
if (command.name.endsWith(" (MCP)")) {
|
|
1131
|
-
name = `mcp:${name.replace(" (MCP)", "")}`;
|
|
1132
|
-
}
|
|
1133
|
-
return {
|
|
1134
|
-
name,
|
|
1135
|
-
description: command.description || "",
|
|
1136
|
-
input,
|
|
1137
|
-
};
|
|
1138
|
-
})
|
|
1139
|
-
.filter(
|
|
1140
|
-
(command: AvailableCommand) =>
|
|
1141
|
-
!UNSUPPORTED_COMMANDS.includes(command.name),
|
|
1142
|
-
);
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
|
-
function formatUriAsLink(uri: string): string {
|
|
1146
|
-
try {
|
|
1147
|
-
if (uri.startsWith("file://")) {
|
|
1148
|
-
const path = uri.slice(7); // Remove "file://"
|
|
1149
|
-
const name = path.split("/").pop() || path;
|
|
1150
|
-
return `[@${name}](${uri})`;
|
|
1151
|
-
} else if (uri.startsWith("zed://")) {
|
|
1152
|
-
const parts = uri.split("/");
|
|
1153
|
-
const name = parts[parts.length - 1] || uri;
|
|
1154
|
-
return `[@${name}](${uri})`;
|
|
1155
|
-
}
|
|
1156
|
-
return uri;
|
|
1157
|
-
} catch {
|
|
1158
|
-
return uri;
|
|
1159
|
-
}
|
|
1160
|
-
}
|
|
1161
|
-
|
|
1162
|
-
export function promptToClaude(prompt: PromptRequest): SDKUserMessage {
|
|
1163
|
-
const content: any[] = [];
|
|
1164
|
-
const context: any[] = [];
|
|
1165
|
-
|
|
1166
|
-
for (const chunk of prompt.prompt) {
|
|
1167
|
-
switch (chunk.type) {
|
|
1168
|
-
case "text": {
|
|
1169
|
-
let text = chunk.text;
|
|
1170
|
-
// change /mcp:server:command args -> /server:command (MCP) args
|
|
1171
|
-
const mcpMatch = text.match(/^\/mcp:([^:\s]+):(\S+)(\s+.*)?$/);
|
|
1172
|
-
if (mcpMatch) {
|
|
1173
|
-
const [, server, command, args] = mcpMatch;
|
|
1174
|
-
text = `/${server}:${command} (MCP)${args || ""}`;
|
|
1175
|
-
}
|
|
1176
|
-
content.push({ type: "text", text });
|
|
1177
|
-
break;
|
|
1178
|
-
}
|
|
1179
|
-
case "resource_link": {
|
|
1180
|
-
const formattedUri = formatUriAsLink(chunk.uri);
|
|
1181
|
-
content.push({
|
|
1182
|
-
type: "text",
|
|
1183
|
-
text: formattedUri,
|
|
1184
|
-
});
|
|
1185
|
-
break;
|
|
1186
|
-
}
|
|
1187
|
-
case "resource": {
|
|
1188
|
-
if ("text" in chunk.resource) {
|
|
1189
|
-
const formattedUri = formatUriAsLink(chunk.resource.uri);
|
|
1190
|
-
content.push({
|
|
1191
|
-
type: "text",
|
|
1192
|
-
text: formattedUri,
|
|
1193
|
-
});
|
|
1194
|
-
context.push({
|
|
1195
|
-
type: "text",
|
|
1196
|
-
text: `\n<context ref="${chunk.resource.uri}">\n${chunk.resource.text}\n</context>`,
|
|
1197
|
-
});
|
|
1198
|
-
}
|
|
1199
|
-
// Ignore blob resources (unsupported)
|
|
1200
|
-
break;
|
|
1201
|
-
}
|
|
1202
|
-
case "image":
|
|
1203
|
-
if (chunk.data) {
|
|
1204
|
-
content.push({
|
|
1205
|
-
type: "image",
|
|
1206
|
-
source: {
|
|
1207
|
-
type: "base64",
|
|
1208
|
-
data: chunk.data,
|
|
1209
|
-
media_type: chunk.mimeType,
|
|
1210
|
-
},
|
|
1211
|
-
});
|
|
1212
|
-
} else if (chunk.uri?.startsWith("http")) {
|
|
1213
|
-
content.push({
|
|
1214
|
-
type: "image",
|
|
1215
|
-
source: {
|
|
1216
|
-
type: "url",
|
|
1217
|
-
url: chunk.uri,
|
|
1218
|
-
},
|
|
1219
|
-
});
|
|
1220
|
-
}
|
|
1221
|
-
break;
|
|
1222
|
-
// Ignore audio and other unsupported types
|
|
1223
|
-
default:
|
|
1224
|
-
break;
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
|
|
1228
|
-
content.push(...context);
|
|
1229
|
-
|
|
1230
|
-
return {
|
|
1231
|
-
type: "user",
|
|
1232
|
-
message: {
|
|
1233
|
-
role: "user",
|
|
1234
|
-
content: content,
|
|
1235
|
-
},
|
|
1236
|
-
session_id: prompt.sessionId,
|
|
1237
|
-
parent_tool_use_id: null,
|
|
1238
|
-
};
|
|
1239
|
-
}
|
|
1240
|
-
|
|
1241
|
-
/**
|
|
1242
|
-
* Convert an SDKAssistantMessage (Claude) to a SessionNotification (ACP).
|
|
1243
|
-
* Only handles text, image, and thinking chunks for now.
|
|
1244
|
-
*/
|
|
1245
|
-
export function toAcpNotifications(
|
|
1246
|
-
content:
|
|
1247
|
-
| string
|
|
1248
|
-
| ContentBlockParam[]
|
|
1249
|
-
| BetaContentBlock[]
|
|
1250
|
-
| BetaRawContentBlockDelta[],
|
|
1251
|
-
role: "assistant" | "user",
|
|
1252
|
-
sessionId: string,
|
|
1253
|
-
toolUseCache: ToolUseCache,
|
|
1254
|
-
fileContentCache: { [key: string]: string },
|
|
1255
|
-
client: AgentSideConnection,
|
|
1256
|
-
logger: Logger,
|
|
1257
|
-
): SessionNotification[] {
|
|
1258
|
-
if (typeof content === "string") {
|
|
1259
|
-
return [
|
|
1260
|
-
{
|
|
1261
|
-
sessionId,
|
|
1262
|
-
update: {
|
|
1263
|
-
sessionUpdate:
|
|
1264
|
-
role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
|
|
1265
|
-
content: {
|
|
1266
|
-
type: "text",
|
|
1267
|
-
text: content,
|
|
1268
|
-
},
|
|
1269
|
-
},
|
|
1270
|
-
},
|
|
1271
|
-
];
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
const output = [];
|
|
1275
|
-
// Only handle the first chunk for streaming; extend as needed for batching
|
|
1276
|
-
for (const chunk of content) {
|
|
1277
|
-
let update: SessionNotification["update"] | null = null;
|
|
1278
|
-
switch (chunk.type) {
|
|
1279
|
-
case "text":
|
|
1280
|
-
case "text_delta":
|
|
1281
|
-
update = {
|
|
1282
|
-
sessionUpdate:
|
|
1283
|
-
role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
|
|
1284
|
-
content: {
|
|
1285
|
-
type: "text",
|
|
1286
|
-
text: chunk.text,
|
|
1287
|
-
},
|
|
1288
|
-
};
|
|
1289
|
-
break;
|
|
1290
|
-
case "image":
|
|
1291
|
-
update = {
|
|
1292
|
-
sessionUpdate:
|
|
1293
|
-
role === "assistant" ? "agent_message_chunk" : "user_message_chunk",
|
|
1294
|
-
content: {
|
|
1295
|
-
type: "image",
|
|
1296
|
-
data: chunk.source.type === "base64" ? chunk.source.data : "",
|
|
1297
|
-
mimeType:
|
|
1298
|
-
chunk.source.type === "base64" ? chunk.source.media_type : "",
|
|
1299
|
-
uri: chunk.source.type === "url" ? chunk.source.url : undefined,
|
|
1300
|
-
},
|
|
1301
|
-
};
|
|
1302
|
-
break;
|
|
1303
|
-
case "thinking":
|
|
1304
|
-
case "thinking_delta":
|
|
1305
|
-
update = {
|
|
1306
|
-
sessionUpdate: "agent_thought_chunk",
|
|
1307
|
-
content: {
|
|
1308
|
-
type: "text",
|
|
1309
|
-
text: chunk.thinking,
|
|
1310
|
-
},
|
|
1311
|
-
};
|
|
1312
|
-
break;
|
|
1313
|
-
case "tool_use":
|
|
1314
|
-
case "server_tool_use":
|
|
1315
|
-
case "mcp_tool_use": {
|
|
1316
|
-
toolUseCache[chunk.id] = chunk;
|
|
1317
|
-
if (chunk.name === "TodoWrite") {
|
|
1318
|
-
// @ts-expect-error - sometimes input is empty object
|
|
1319
|
-
if (Array.isArray(chunk.input.todos)) {
|
|
1320
|
-
update = {
|
|
1321
|
-
sessionUpdate: "plan",
|
|
1322
|
-
entries: planEntries(chunk.input as { todos: ClaudePlanEntry[] }),
|
|
1323
|
-
};
|
|
1324
|
-
}
|
|
1325
|
-
} else {
|
|
1326
|
-
// Register hook callback to receive the structured output from the hook
|
|
1327
|
-
registerHookCallback(chunk.id, {
|
|
1328
|
-
onPostToolUseHook: async (toolUseId, _toolInput, toolResponse) => {
|
|
1329
|
-
const toolUse = toolUseCache[toolUseId];
|
|
1330
|
-
if (toolUse) {
|
|
1331
|
-
const update: SessionNotification["update"] = {
|
|
1332
|
-
_meta: {
|
|
1333
|
-
claudeCode: {
|
|
1334
|
-
toolResponse,
|
|
1335
|
-
toolName: toolUse.name,
|
|
1336
|
-
},
|
|
1337
|
-
} satisfies ToolUpdateMeta,
|
|
1338
|
-
toolCallId: toolUseId,
|
|
1339
|
-
sessionUpdate: "tool_call_update",
|
|
1340
|
-
};
|
|
1341
|
-
await client.sessionUpdate({
|
|
1342
|
-
sessionId,
|
|
1343
|
-
update,
|
|
1344
|
-
});
|
|
1345
|
-
} else {
|
|
1346
|
-
logger.error(
|
|
1347
|
-
`[claude-code-acp] Got a tool response for tool use that wasn't tracked: ${toolUseId}`,
|
|
1348
|
-
);
|
|
1349
|
-
}
|
|
1350
|
-
},
|
|
1351
|
-
});
|
|
1352
|
-
|
|
1353
|
-
let rawInput: Record<string, unknown> | undefined;
|
|
1354
|
-
try {
|
|
1355
|
-
rawInput = JSON.parse(JSON.stringify(chunk.input));
|
|
1356
|
-
} catch {
|
|
1357
|
-
// ignore if we can't turn it to JSON
|
|
1358
|
-
}
|
|
1359
|
-
update = {
|
|
1360
|
-
_meta: {
|
|
1361
|
-
claudeCode: {
|
|
1362
|
-
toolName: chunk.name,
|
|
1363
|
-
},
|
|
1364
|
-
} satisfies ToolUpdateMeta,
|
|
1365
|
-
toolCallId: chunk.id,
|
|
1366
|
-
sessionUpdate: "tool_call",
|
|
1367
|
-
rawInput,
|
|
1368
|
-
status: "pending",
|
|
1369
|
-
...toolInfoFromToolUse(chunk, fileContentCache, logger),
|
|
1370
|
-
};
|
|
1371
|
-
}
|
|
1372
|
-
break;
|
|
1373
|
-
}
|
|
1374
|
-
|
|
1375
|
-
case "tool_result":
|
|
1376
|
-
case "tool_search_tool_result":
|
|
1377
|
-
case "web_fetch_tool_result":
|
|
1378
|
-
case "web_search_tool_result":
|
|
1379
|
-
case "code_execution_tool_result":
|
|
1380
|
-
case "bash_code_execution_tool_result":
|
|
1381
|
-
case "text_editor_code_execution_tool_result":
|
|
1382
|
-
case "mcp_tool_result": {
|
|
1383
|
-
const toolUse = toolUseCache[chunk.tool_use_id];
|
|
1384
|
-
if (!toolUse) {
|
|
1385
|
-
logger.error(
|
|
1386
|
-
`[claude-code-acp] Got a tool result for tool use that wasn't tracked: ${chunk.tool_use_id}`,
|
|
1387
|
-
);
|
|
1388
|
-
break;
|
|
1389
|
-
}
|
|
1390
|
-
|
|
1391
|
-
if (toolUse.name !== "TodoWrite") {
|
|
1392
|
-
update = {
|
|
1393
|
-
_meta: {
|
|
1394
|
-
claudeCode: {
|
|
1395
|
-
toolName: toolUse.name,
|
|
1396
|
-
},
|
|
1397
|
-
} satisfies ToolUpdateMeta,
|
|
1398
|
-
toolCallId: chunk.tool_use_id,
|
|
1399
|
-
sessionUpdate: "tool_call_update",
|
|
1400
|
-
status:
|
|
1401
|
-
"is_error" in chunk && chunk.is_error ? "failed" : "completed",
|
|
1402
|
-
...toolUpdateFromToolResult(chunk, toolUseCache[chunk.tool_use_id]),
|
|
1403
|
-
};
|
|
1404
|
-
}
|
|
1405
|
-
break;
|
|
1406
|
-
}
|
|
1407
|
-
|
|
1408
|
-
case "document":
|
|
1409
|
-
case "search_result":
|
|
1410
|
-
case "redacted_thinking":
|
|
1411
|
-
case "input_json_delta":
|
|
1412
|
-
case "citations_delta":
|
|
1413
|
-
case "signature_delta":
|
|
1414
|
-
case "container_upload":
|
|
1415
|
-
break;
|
|
1416
|
-
|
|
1417
|
-
default:
|
|
1418
|
-
unreachable(chunk, logger);
|
|
1419
|
-
break;
|
|
1420
|
-
}
|
|
1421
|
-
if (update) {
|
|
1422
|
-
output.push({ sessionId, update });
|
|
1423
|
-
}
|
|
1424
|
-
}
|
|
1425
|
-
|
|
1426
|
-
return output;
|
|
1427
|
-
}
|
|
1428
|
-
|
|
1429
|
-
export function streamEventToAcpNotifications(
|
|
1430
|
-
message: SDKPartialAssistantMessage,
|
|
1431
|
-
sessionId: string,
|
|
1432
|
-
toolUseCache: ToolUseCache,
|
|
1433
|
-
fileContentCache: { [key: string]: string },
|
|
1434
|
-
client: AgentSideConnection,
|
|
1435
|
-
logger: Logger,
|
|
1436
|
-
): SessionNotification[] {
|
|
1437
|
-
const event = message.event;
|
|
1438
|
-
switch (event.type) {
|
|
1439
|
-
case "content_block_start":
|
|
1440
|
-
return toAcpNotifications(
|
|
1441
|
-
[event.content_block],
|
|
1442
|
-
"assistant",
|
|
1443
|
-
sessionId,
|
|
1444
|
-
toolUseCache,
|
|
1445
|
-
fileContentCache,
|
|
1446
|
-
client,
|
|
1447
|
-
logger,
|
|
1448
|
-
);
|
|
1449
|
-
case "content_block_delta":
|
|
1450
|
-
return toAcpNotifications(
|
|
1451
|
-
[event.delta],
|
|
1452
|
-
"assistant",
|
|
1453
|
-
sessionId,
|
|
1454
|
-
toolUseCache,
|
|
1455
|
-
fileContentCache,
|
|
1456
|
-
client,
|
|
1457
|
-
logger,
|
|
1458
|
-
);
|
|
1459
|
-
// No content
|
|
1460
|
-
case "message_start":
|
|
1461
|
-
case "message_delta":
|
|
1462
|
-
case "message_stop":
|
|
1463
|
-
case "content_block_stop":
|
|
1464
|
-
return [];
|
|
1465
|
-
|
|
1466
|
-
default:
|
|
1467
|
-
unreachable(event, logger);
|
|
1468
|
-
return [];
|
|
1469
|
-
}
|
|
1470
|
-
}
|
|
1471
|
-
|
|
1472
|
-
export type AcpConnectionConfig = {
|
|
1473
|
-
sessionStore?: SessionStore;
|
|
1474
|
-
sessionId?: string;
|
|
1475
|
-
taskId?: string;
|
|
1476
|
-
};
|
|
1477
|
-
|
|
1478
|
-
export type InProcessAcpConnection = {
|
|
1479
|
-
agentConnection: AgentSideConnection;
|
|
1480
|
-
clientStreams: StreamPair;
|
|
1481
|
-
};
|
|
1482
|
-
|
|
1483
|
-
export function createAcpConnection(
|
|
1484
|
-
config: AcpConnectionConfig = {},
|
|
1485
|
-
): InProcessAcpConnection {
|
|
1486
|
-
const logger = new Logger({ debug: true, prefix: "[AcpConnection]" });
|
|
1487
|
-
const streams = createBidirectionalStreams();
|
|
1488
|
-
|
|
1489
|
-
const { sessionStore } = config;
|
|
1490
|
-
|
|
1491
|
-
// Tap both streams for automatic persistence
|
|
1492
|
-
// All messages (bidirectional) will be persisted as they flow through
|
|
1493
|
-
let agentWritable = streams.agent.writable;
|
|
1494
|
-
let clientWritable = streams.client.writable;
|
|
1495
|
-
|
|
1496
|
-
if (config.sessionId && sessionStore) {
|
|
1497
|
-
// Register session for persistence BEFORE tapping streams
|
|
1498
|
-
// This ensures all messages from the start get persisted
|
|
1499
|
-
if (!sessionStore.isRegistered(config.sessionId)) {
|
|
1500
|
-
sessionStore.register(config.sessionId, {
|
|
1501
|
-
taskId: config.taskId ?? config.sessionId,
|
|
1502
|
-
runId: config.sessionId,
|
|
1503
|
-
logUrl: "", // Will be updated when we get the real logUrl
|
|
1504
|
-
});
|
|
1505
|
-
}
|
|
1506
|
-
|
|
1507
|
-
// Tap agent→client stream
|
|
1508
|
-
agentWritable = createTappedWritableStream(streams.agent.writable, {
|
|
1509
|
-
onMessage: (line) => {
|
|
1510
|
-
sessionStore.appendRawLine(config.sessionId!, line);
|
|
1511
|
-
},
|
|
1512
|
-
logger,
|
|
1513
|
-
});
|
|
1514
|
-
|
|
1515
|
-
// Tap client→agent stream
|
|
1516
|
-
clientWritable = createTappedWritableStream(streams.client.writable, {
|
|
1517
|
-
onMessage: (line) => {
|
|
1518
|
-
sessionStore.appendRawLine(config.sessionId!, line);
|
|
1519
|
-
},
|
|
1520
|
-
logger,
|
|
1521
|
-
});
|
|
1522
|
-
} else {
|
|
1523
|
-
logger.info("Tapped streams NOT enabled", {
|
|
1524
|
-
hasSessionId: !!config.sessionId,
|
|
1525
|
-
hasSessionStore: !!sessionStore,
|
|
1526
|
-
});
|
|
1527
|
-
}
|
|
1528
|
-
|
|
1529
|
-
const agentStream = ndJsonStream(agentWritable, streams.agent.readable);
|
|
1530
|
-
|
|
1531
|
-
const agentConnection = new AgentSideConnection(
|
|
1532
|
-
(client) => new ClaudeAcpAgent(client, sessionStore),
|
|
1533
|
-
agentStream,
|
|
1534
|
-
);
|
|
1535
|
-
|
|
1536
|
-
return {
|
|
1537
|
-
agentConnection,
|
|
1538
|
-
clientStreams: {
|
|
1539
|
-
readable: streams.client.readable,
|
|
1540
|
-
writable: clientWritable,
|
|
1541
|
-
},
|
|
1542
|
-
};
|
|
1543
|
-
}
|