@e2e-dev/acp 0.0.0-stage → 0.1.0-nightly-20261030152130

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/dist/mcp.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Serves the step tools to the agent as one MCP server over streamable HTTP
3
+ * on 127.0.0.1. An ACP agent takes tools only as MCP servers, and a stdio
4
+ * server would run in another process, away from the step's context; over
5
+ * HTTP every call runs here, in the test worker. The port is ephemeral and
6
+ * the path random per session, so nothing else on the machine guesses it.
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import { createServer } from 'node:http';
10
+ import { Readable } from 'node:stream';
11
+ import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
12
+ /** The MCP server name the agent sees. Distinct from `e2e mcp`'s `e2e`, so a permission request naming it is about these tools. */
13
+ export const MCP_SERVER_NAME = 'e2e_step';
14
+ /** Starts the tool server on an ephemeral 127.0.0.1 port. */
15
+ export async function serveTools(tools) {
16
+ const route = `/${randomUUID()}/mcp`;
17
+ const handler = createMcpHandler(() => {
18
+ const server = new McpServer({ name: MCP_SERVER_NAME, version: '1' }, { capabilities: { tools: {} } });
19
+ for (const tool of tools) {
20
+ server.registerTool(tool.name, {
21
+ description: tool.description,
22
+ inputSchema: tool.inputSchema,
23
+ annotations: { readOnlyHint: tool.readOnly, openWorldHint: false },
24
+ }, async (args) => {
25
+ const result = await tool.run(args);
26
+ return {
27
+ content: [
28
+ { type: 'text', text: result.text },
29
+ ...(result.image === undefined ? [] : [{ type: 'image', ...result.image }]),
30
+ ],
31
+ ...(result.isError === true ? { isError: true } : {}),
32
+ };
33
+ });
34
+ }
35
+ return server;
36
+ });
37
+ const http = createServer((request, response) => {
38
+ if (request.url !== route) {
39
+ response.writeHead(404).end();
40
+ return;
41
+ }
42
+ void forward(handler.fetch, request, response);
43
+ });
44
+ await new Promise((resolve, reject) => {
45
+ http.once('error', reject);
46
+ http.listen(0, '127.0.0.1', resolve);
47
+ });
48
+ const { port } = http.address();
49
+ return {
50
+ url: `http://127.0.0.1:${port}${route}`,
51
+ close: async () => {
52
+ await handler.close();
53
+ http.closeAllConnections();
54
+ await new Promise((resolve) => http.close(() => resolve()));
55
+ },
56
+ };
57
+ }
58
+ /** Hands one Node request to the web-standard handler and streams its response back. */
59
+ async function forward(fetch, incoming, outgoing) {
60
+ try {
61
+ const headers = new Headers();
62
+ for (const [key, value] of Object.entries(incoming.headers)) {
63
+ if (typeof value === 'string')
64
+ headers.set(key, value);
65
+ else if (Array.isArray(value))
66
+ for (const item of value)
67
+ headers.append(key, item);
68
+ }
69
+ const method = incoming.method ?? 'GET';
70
+ const body = method === 'GET' || method === 'HEAD' ? undefined : await readAll(incoming);
71
+ const response = await fetch(new Request(`http://127.0.0.1${incoming.url ?? '/'}`, { method, headers, ...(body === undefined ? {} : { body }) }));
72
+ outgoing.writeHead(response.status, Object.fromEntries(response.headers));
73
+ if (response.body === null)
74
+ outgoing.end();
75
+ else
76
+ Readable.fromWeb(response.body).pipe(outgoing);
77
+ }
78
+ catch (error) {
79
+ if (!outgoing.headersSent)
80
+ outgoing.writeHead(500);
81
+ outgoing.end(error instanceof Error ? error.message : String(error));
82
+ }
83
+ }
84
+ async function readAll(stream) {
85
+ const chunks = [];
86
+ for await (const chunk of stream)
87
+ chunks.push(chunk);
88
+ return new Uint8Array(Buffer.concat(chunks));
89
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * How to start each agent with e2e's step tools as its only tools. ACP lets
3
+ * a client add tools but not take the agent's own away, so each preset turns
4
+ * them off the way its agent allows. The adapter runs from the install found
5
+ * from the working directory up, never fetched by name at run time.
6
+ */
7
+ import { type AgentLaunch } from './session.ts';
8
+ import type { AcpAgentOptions } from './types.ts';
9
+ /** Claude Code with no built-in tools, no user or project settings or MCP servers, and no saved session. */
10
+ export declare function claudeCodeLaunch(options: AcpAgentOptions): () => Promise<AgentLaunch>;
11
+ /**
12
+ * Codex in its read-only mode with no shell, web search, apps, plugins,
13
+ * browser or computer use, and the user's own MCP servers turned off by
14
+ * name, as `codex mcp list` reports them. The adapter merges this over the
15
+ * user's Codex config for its sessions only. Codex may still start a
16
+ * subagent, which fails the step like any tool of its own.
17
+ */
18
+ export declare function codexLaunch(options: AcpAgentOptions): () => Promise<AgentLaunch>;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * How to start each agent with e2e's step tools as its only tools. ACP lets
3
+ * a client add tools but not take the agent's own away, so each preset turns
4
+ * them off the way its agent allows. The adapter runs from the install found
5
+ * from the working directory up, never fetched by name at run time.
6
+ */
7
+ import { execFile } from 'node:child_process';
8
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
9
+ import { createRequire } from 'node:module';
10
+ import { dirname, join, parse } from 'node:path';
11
+ import { promisify } from 'node:util';
12
+ import { ConfigurationError } from 'e2e/engine';
13
+ import { z } from 'zod';
14
+ import { withoutSecrets } from './session.js';
15
+ const execFileAsync = promisify(execFile);
16
+ /** What `codex mcp list --json` prints, as far as the preset reads it. */
17
+ const CodexServerList = z.array(z.object({ name: z.string() }));
18
+ /** The `bin` field of a package manifest. */
19
+ const PackageBin = z.object({ bin: z.union([z.string(), z.record(z.string(), z.string())]).optional() });
20
+ /** Claude Code with no built-in tools, no user or project settings or MCP servers, and no saved session. */
21
+ export function claudeCodeLaunch(options) {
22
+ const bin = adapterBin('@agentclientprotocol/claude-agent-acp', 'claude-agent-acp');
23
+ const launch = {
24
+ command: process.execPath,
25
+ args: [bin],
26
+ // The adapter starts on ANTHROPIC_MODEL ahead of the user's own settings, whose model may not start outside their CLI.
27
+ env: { ...(options.model === undefined ? {} : { ANTHROPIC_MODEL: options.model }), ...options.env },
28
+ model: options.model,
29
+ sessionMeta: {
30
+ claudeCode: {
31
+ options: {
32
+ tools: [],
33
+ settingSources: [],
34
+ strictMcpConfig: true,
35
+ persistSession: false,
36
+ allowDangerouslySkipPermissions: false,
37
+ },
38
+ },
39
+ },
40
+ signIn: 'run `claude` and log in, or set ANTHROPIC_API_KEY',
41
+ };
42
+ return async () => launch;
43
+ }
44
+ /**
45
+ * Codex in its read-only mode with no shell, web search, apps, plugins,
46
+ * browser or computer use, and the user's own MCP servers turned off by
47
+ * name, as `codex mcp list` reports them. The adapter merges this over the
48
+ * user's Codex config for its sessions only. Codex may still start a
49
+ * subagent, which fails the step like any tool of its own.
50
+ */
51
+ export function codexLaunch(options) {
52
+ const pkg = adapterPackage('@agentclientprotocol/codex-acp');
53
+ const bin = binOf(pkg, 'codex-acp');
54
+ let launch;
55
+ return () => {
56
+ launch ??= codexServers(pkg, options.env).then((servers) => ({
57
+ command: process.execPath,
58
+ args: [bin],
59
+ env: { ...options.env, CODEX_CONFIG: JSON.stringify(codexConfig(servers)) },
60
+ model: options.model,
61
+ mode: 'read-only',
62
+ signIn: 'run `codex login`',
63
+ }));
64
+ launch.catch(() => {
65
+ launch = undefined;
66
+ });
67
+ return launch;
68
+ };
69
+ }
70
+ /** The Codex features that give the agent a tool of its own. */
71
+ const CODEX_FEATURES_OFF = [
72
+ 'apps',
73
+ 'browser_use',
74
+ 'browser_use_external',
75
+ 'computer_use',
76
+ 'goals',
77
+ 'image_generation',
78
+ 'multi_agent',
79
+ 'multi_agent_v2',
80
+ 'plugins',
81
+ 'shell_tool',
82
+ 'skill_search',
83
+ 'tool_suggest',
84
+ 'unified_exec',
85
+ 'view_image',
86
+ ];
87
+ function codexConfig(servers) {
88
+ return {
89
+ web_search: 'disabled',
90
+ features: Object.fromEntries(CODEX_FEATURES_OFF.map((feature) => [feature, false])),
91
+ mcp_servers: Object.fromEntries(servers.map((name) => [name, { enabled: false }])),
92
+ };
93
+ }
94
+ /** The MCP servers the user's Codex config declares, from the Codex the adapter runs. */
95
+ async function codexServers(adapter, env) {
96
+ const codexPath = env?.['CODEX_PATH'] ?? process.env['CODEX_PATH'];
97
+ const [command, args] = codexPath === undefined
98
+ ? [process.execPath, [createRequire(join(adapter, 'package.json')).resolve('@openai/codex/bin/codex.js')]]
99
+ : [codexPath, []];
100
+ try {
101
+ const { stdout } = await execFileAsync(command, [...args, 'mcp', 'list', '--json'], {
102
+ env: withoutSecrets({ ...process.env, ...env }),
103
+ timeout: 30_000,
104
+ });
105
+ return CodexServerList.parse(JSON.parse(stdout)).map((server) => server.name);
106
+ }
107
+ catch (error) {
108
+ throw new Error(`could not list your Codex MCP servers to turn them off: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
109
+ }
110
+ }
111
+ /**
112
+ * The directory of an adapter package installed in the project, found the
113
+ * way Node finds a dependency, with links resolved: pnpm links a package
114
+ * into the project, and its own dependencies resolve only from where it is.
115
+ */
116
+ function adapterPackage(name) {
117
+ for (let directory = process.cwd();; directory = dirname(directory)) {
118
+ const candidate = join(directory, 'node_modules', name);
119
+ if (existsSync(join(candidate, 'package.json')))
120
+ return realpathSync(candidate);
121
+ if (directory === parse(directory).root)
122
+ break;
123
+ }
124
+ throw new ConfigurationError('INVALID_CONFIG', `${name} is not installed in ${process.cwd()} or a directory above it: npm install -D ${name}, and run e2e from that project`);
125
+ }
126
+ function adapterBin(name, bin) {
127
+ return binOf(adapterPackage(name), bin);
128
+ }
129
+ function binOf(pkg, bin) {
130
+ const manifest = PackageBin.safeParse(JSON.parse(readFileSync(join(pkg, 'package.json'), 'utf8')));
131
+ const declared = manifest.success ? manifest.data.bin : undefined;
132
+ const path = typeof declared === 'string' ? declared : declared?.[bin];
133
+ if (path === undefined)
134
+ throw new ConfigurationError('INVALID_CONFIG', `${pkg} has no ${bin} command`);
135
+ return join(pkg, path);
136
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * One ACP agent process and one session in it.
3
+ *
4
+ * The agent process starts in the project directory, so a command installed
5
+ * there resolves, and gets `initialize` and one `session/new` in an empty
6
+ * temporary directory with the step tools as its only MCP server. The
7
+ * client advertises no file system or terminal capability, and answers
8
+ * permission requests itself: calls of the step tools are allowed, anything
9
+ * else is rejected. Each `prompt` is one `session/prompt` and resolves when
10
+ * the agent's turn ends.
11
+ */
12
+ import { type Usage } from '@agentclientprotocol/sdk';
13
+ import { type ServedTool } from './mcp.ts';
14
+ /** How to start one agent and what its session gets. */
15
+ export interface AgentLaunch {
16
+ readonly command: string;
17
+ readonly args: readonly string[];
18
+ readonly env?: Readonly<Record<string, string>> | undefined;
19
+ readonly model?: string | undefined;
20
+ readonly mode?: string | undefined;
21
+ readonly sessionMeta?: Readonly<Record<string, unknown>> | undefined;
22
+ /** How the user signs the agent in, for a session it refuses until they do. */
23
+ readonly signIn?: string | undefined;
24
+ }
25
+ /** What one prompt turn reported. */
26
+ export interface TurnReport {
27
+ readonly startedAt: string;
28
+ readonly durationMs: number;
29
+ readonly stopReason: string;
30
+ readonly usage?: Usage;
31
+ /** The turn's cost in USD, when the agent reports a session cost. */
32
+ readonly costUsd?: number;
33
+ /** The agent's text replies during the turn. */
34
+ readonly text: string;
35
+ /** Tool calls of the agent's own that asked permission and were rejected. */
36
+ readonly rejected: readonly string[];
37
+ /** Tool calls of the agent's own that ran without asking. */
38
+ readonly ran: readonly string[];
39
+ }
40
+ /** A running agent session. */
41
+ export interface AcpSession {
42
+ prompt(text: string): Promise<TurnReport>;
43
+ /** Cancels the turn in flight, if any. */
44
+ cancel(): void;
45
+ close(): void;
46
+ /** The model the session runs, when the agent names it. */
47
+ readonly modelId: string | undefined;
48
+ readonly agentName: string | undefined;
49
+ }
50
+ /**
51
+ * Starts the agent, initializes it, and opens a session with the tools.
52
+ * Aborting `signal` before the session is open stops the agent and the tool
53
+ * server and rejects. `onOwnTool` hears of every tool of the agent's own
54
+ * that runs without asking, as soon as it starts or finishes.
55
+ */
56
+ export declare function startSession(launch: AgentLaunch, tools: readonly ServedTool[], signal: AbortSignal, onOwnTool?: (title: string) => void): Promise<AcpSession>;
57
+ /** The agent's environment without the variables e2e reads secrets from, wherever they came from. */
58
+ export declare function withoutSecrets(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
@@ -0,0 +1,287 @@
1
+ /**
2
+ * One ACP agent process and one session in it.
3
+ *
4
+ * The agent process starts in the project directory, so a command installed
5
+ * there resolves, and gets `initialize` and one `session/new` in an empty
6
+ * temporary directory with the step tools as its only MCP server. The
7
+ * client advertises no file system or terminal capability, and answers
8
+ * permission requests itself: calls of the step tools are allowed, anything
9
+ * else is rejected. Each `prompt` is one `session/prompt` and resolves when
10
+ * the agent's turn ends.
11
+ */
12
+ import { spawn } from 'node:child_process';
13
+ import { mkdtempSync, rmSync } from 'node:fs';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import { Readable, Writable } from 'node:stream';
17
+ import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION, } from '@agentclientprotocol/sdk';
18
+ import { ConfigurationError } from 'e2e/engine';
19
+ import { MCP_SERVER_NAME, serveTools } from './mcp.js';
20
+ /** Tool kinds an agent uses for its own tools and subagents; never a call of ours without an adapter's mark. */
21
+ const BUILT_IN_KINDS = new Set(['read', 'edit', 'delete', 'move', 'search', 'execute', 'fetch', 'think', 'switch_mode']);
22
+ /** ACP's error code for a request the agent refuses until the user signs in. */
23
+ const AUTH_REQUIRED = -32000;
24
+ /** Variables e2e reads secret and credential values from: the agent never needs them. Any case, since Windows reads names that way. */
25
+ const SECRET_VARIABLE = /^E2E_(?:SECRET|USER)_/i;
26
+ /**
27
+ * Starts the agent, initializes it, and opens a session with the tools.
28
+ * Aborting `signal` before the session is open stops the agent and the tool
29
+ * server and rejects. `onOwnTool` hears of every tool of the agent's own
30
+ * that runs without asking, as soon as it starts or finishes.
31
+ */
32
+ export async function startSession(launch, tools, signal, onOwnTool = () => undefined) {
33
+ signal.throwIfAborted();
34
+ const cwd = mkdtempSync(join(tmpdir(), 'e2e-acp-'));
35
+ let server;
36
+ // Started before anything can fail, so teardown can close it even when the startup race is lost while it binds.
37
+ const serving = serveTools(tools);
38
+ serving.catch(() => undefined);
39
+ const child = spawn(launch.command, [...launch.args], {
40
+ stdio: ['pipe', 'pipe', 'pipe'],
41
+ env: withoutSecrets({ ...process.env, ...launch.env }),
42
+ });
43
+ let stderr = '';
44
+ child.stderr.on('data', (data) => {
45
+ stderr = (stderr + data.toString()).slice(-2000);
46
+ });
47
+ // A dead agent must not take the test worker down with a pipe error.
48
+ child.stdin.on('error', () => undefined);
49
+ const exited = new Promise((_, reject) => {
50
+ child.on('error', (error) => reject(new Error(`could not start ${launch.command}: ${error.message}`)));
51
+ child.on('exit', (code, exitSignal) => reject(new Error(`the agent exited (${exitSignal ?? `code ${code}`})${stderr === '' ? '' : `: ${lastLine(stderr)}`}`)));
52
+ });
53
+ exited.catch(() => undefined);
54
+ let onAbort;
55
+ const aborted = new Promise((_, reject) => {
56
+ onAbort = () => reject(new Error('the step ended while the agent was starting'));
57
+ signal.addEventListener('abort', onAbort, { once: true });
58
+ });
59
+ aborted.catch(() => undefined);
60
+ /** Ends a startup step early when the agent exits or the attempt ends. */
61
+ const startup = (step) => Promise.race([exited, aborted, step]);
62
+ const ours = new Set(tools.map((tool) => tool.name));
63
+ const calls = new Map();
64
+ const turn = { cost: undefined, text: '', own: { allowed: new Set(), rejected: new Map(), ran: new Map() } };
65
+ const client = {
66
+ requestPermission: (params) => answerPermission(params, ours, calls, turn.own),
67
+ sessionUpdate: (params) => observe(params, ours, calls, turn, onOwnTool),
68
+ };
69
+ const connection = new ClientSideConnection(() => client, ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout)));
70
+ const teardown = () => {
71
+ child.stdin.end();
72
+ child.kill('SIGTERM');
73
+ setTimeout(() => {
74
+ if (child.exitCode === null && child.signalCode === null)
75
+ child.kill('SIGKILL');
76
+ }, 3_000).unref();
77
+ void serving.then((started) => started.close(), () => undefined);
78
+ rmSync(cwd, { recursive: true, force: true });
79
+ };
80
+ let initialize;
81
+ let sessionId;
82
+ let modelId;
83
+ try {
84
+ server = await startup(serving);
85
+ initialize = await startup(connection.initialize({
86
+ protocolVersion: PROTOCOL_VERSION,
87
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
88
+ clientInfo: { name: 'e2e', version: '1' },
89
+ }));
90
+ if (initialize.agentCapabilities?.mcpCapabilities?.http !== true) {
91
+ throw new ConfigurationError('INVALID_CONFIG', `${launch.command} does not accept MCP servers over HTTP, which the step tools need`);
92
+ }
93
+ const session = await startup(connection.newSession({
94
+ cwd,
95
+ mcpServers: [{ type: 'http', name: MCP_SERVER_NAME, url: server.url, headers: [] }],
96
+ ...(launch.sessionMeta === undefined ? {} : { _meta: { ...launch.sessionMeta } }),
97
+ }));
98
+ sessionId = session.sessionId;
99
+ const modelOption = session.configOptions?.find((option) => option.category === 'model' || option.id === 'model');
100
+ if (launch.model !== undefined) {
101
+ const offered = modelOption === undefined ? [] : selectValues(modelOption);
102
+ if (modelOption === undefined || !offered.includes(launch.model)) {
103
+ throw new ConfigurationError('INVALID_CONFIG', `the agent does not offer model ${launch.model}${offered.length === 0 ? '' : `; it offers ${offered.join(', ')}`}`);
104
+ }
105
+ await startup(connection.setSessionConfigOption({ sessionId, configId: modelOption.id, value: launch.model }));
106
+ modelId = launch.model;
107
+ }
108
+ else if (modelOption?.type === 'select') {
109
+ modelId = String(modelOption.currentValue);
110
+ }
111
+ if (launch.mode !== undefined)
112
+ await startup(selectMode(connection, session, launch.mode));
113
+ }
114
+ catch (error) {
115
+ teardown();
116
+ if (isAuthRequired(error)) {
117
+ throw new Error(`the agent is not signed in${launch.signIn === undefined ? '' : `: ${launch.signIn}`}`, { cause: error });
118
+ }
119
+ throw withDetails(error);
120
+ }
121
+ finally {
122
+ if (onAbort !== undefined)
123
+ signal.removeEventListener('abort', onAbort);
124
+ }
125
+ let closed = false;
126
+ return {
127
+ modelId,
128
+ agentName: initialize.agentInfo?.name,
129
+ async prompt(text) {
130
+ turn.text = '';
131
+ turn.own = { allowed: new Set(), rejected: new Map(), ran: new Map() };
132
+ const costBefore = turn.cost;
133
+ const started = Date.now();
134
+ const response = await Promise.race([connection.prompt({ sessionId, prompt: [{ type: 'text', text }] }), exited]).catch((error) => {
135
+ throw withDetails(error);
136
+ });
137
+ const costUsd = turn.cost === undefined ? undefined : turn.cost - (costBefore ?? 0);
138
+ return {
139
+ startedAt: new Date(started).toISOString(),
140
+ durationMs: Date.now() - started,
141
+ stopReason: response.stopReason,
142
+ ...(response.usage == null ? {} : { usage: response.usage }),
143
+ ...(costUsd === undefined ? {} : { costUsd }),
144
+ text: turn.text,
145
+ rejected: [...turn.own.rejected.values()],
146
+ ran: [...turn.own.ran.values()],
147
+ };
148
+ },
149
+ cancel() {
150
+ void connection.cancel({ sessionId }).catch(() => undefined);
151
+ },
152
+ close() {
153
+ if (closed)
154
+ return;
155
+ closed = true;
156
+ // Synchronous to the end, so a worker exiting right after the attempt still stops the agent.
157
+ if (initialize.agentCapabilities?.sessionCapabilities?.close != null) {
158
+ void connection.closeSession({ sessionId }).catch(() => undefined);
159
+ }
160
+ teardown();
161
+ },
162
+ };
163
+ }
164
+ /** The agent's environment without the variables e2e reads secrets from, wherever they came from. */
165
+ export function withoutSecrets(env) {
166
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !SECRET_VARIABLE.test(name)));
167
+ }
168
+ /** `error` with what the agent said about it beyond its message appended, if anything. */
169
+ function withDetails(error) {
170
+ const details = detailsOf(error);
171
+ return details === undefined ? error : new Error(`${error instanceof Error ? error.message : String(error)}: ${details}`, { cause: error });
172
+ }
173
+ /** What an agent said about a refused request beyond its message: the Claude adapter's `data.details`, the Codex adapter's `data.message`. */
174
+ function detailsOf(error) {
175
+ const data = typeof error === 'object' && error !== null ? error.data : undefined;
176
+ const fields = typeof data === 'object' && data !== null ? data : undefined;
177
+ const details = fields === undefined ? data : (fields.details ?? fields.message);
178
+ return typeof details === 'string' && details !== '' ? details : undefined;
179
+ }
180
+ function isAuthRequired(error) {
181
+ return typeof error === 'object' && error !== null && error.code === AUTH_REQUIRED;
182
+ }
183
+ async function selectMode(connection, session, mode) {
184
+ const option = session.configOptions?.find((entry) => entry.category === 'mode');
185
+ if (option !== undefined && selectValues(option).includes(mode)) {
186
+ await connection.setSessionConfigOption({ sessionId: session.sessionId, configId: option.id, value: mode });
187
+ }
188
+ else if (session.modes?.availableModes.some((entry) => entry.id === mode) === true) {
189
+ await connection.setSessionMode({ sessionId: session.sessionId, modeId: mode });
190
+ }
191
+ else {
192
+ throw new ConfigurationError('INVALID_CONFIG', `the agent has no mode ${mode}`);
193
+ }
194
+ }
195
+ /** The values of a select config option, groups flattened. */
196
+ function selectValues(option) {
197
+ if (option.type !== 'select')
198
+ return [];
199
+ return option.options.flatMap((entry) => ('group' in entry ? entry.options.map((inner) => inner.value) : [entry.value]));
200
+ }
201
+ function observe({ update }, ours, calls, turn, onOwnTool) {
202
+ switch (update.sessionUpdate) {
203
+ case 'tool_call':
204
+ case 'tool_call_update': {
205
+ const { sessionUpdate: _, ...fields } = update;
206
+ const call = { ...calls.get(update.toolCallId), ...defined(fields) };
207
+ calls.set(update.toolCallId, call);
208
+ // A call of the agent's own that started or finished without a permission we rejected ran without asking:
209
+ // caught when it starts, so a long one cannot feed what it read to the step tools before it ends.
210
+ const started = call.status === 'in_progress' || call.status === 'completed' || call.status === 'failed';
211
+ const { allowed, rejected, ran: already } = turn.own;
212
+ const ran = started && !allowed.has(update.toolCallId) && !rejected.has(update.toolCallId) && !already.has(update.toolCallId);
213
+ if (ran && !isOurs(call, undefined, ours)) {
214
+ const title = titleOf(call);
215
+ turn.own.ran.set(update.toolCallId, title);
216
+ onOwnTool(title);
217
+ }
218
+ break;
219
+ }
220
+ case 'agent_message_chunk':
221
+ if (update.content.type === 'text')
222
+ turn.text += update.content.text;
223
+ break;
224
+ case 'usage_update':
225
+ if (update.cost != null && update.cost.currency === 'USD')
226
+ turn.cost = update.cost.amount;
227
+ break;
228
+ default:
229
+ break;
230
+ }
231
+ }
232
+ /** Allows calls of the step tools; rejects everything else. */
233
+ function answerPermission(params, ours, calls, own) {
234
+ const toolCall = { ...calls.get(params.toolCall.toolCallId), ...defined(params.toolCall) };
235
+ const allowed = isOurs(toolCall, params['_meta'] ?? undefined, ours);
236
+ // Remembered, since the call's later updates may not carry what the request named it by.
237
+ if (allowed)
238
+ own.allowed.add(params.toolCall.toolCallId);
239
+ else
240
+ own.rejected.set(params.toolCall.toolCallId, titleOf(toolCall));
241
+ const kinds = allowed ? ['allow_once', 'allow_always'] : ['reject_once', 'reject_always'];
242
+ const option = kinds.map((kind) => params.options.find((entry) => entry.kind === kind)).find((entry) => entry !== undefined);
243
+ return option === undefined ? { outcome: { outcome: 'cancelled' } } : { outcome: { outcome: 'selected', optionId: option.optionId } };
244
+ }
245
+ /**
246
+ * Whether a tool call is one of ours. ACP has no standard field for the MCP
247
+ * server behind a call, so this reads what the adapters fill in, never text
248
+ * the agent wrote: the Claude adapter's `_meta.claudeCode.toolName`; the
249
+ * server and tool of a call the Codex adapter marks as an MCP call; and
250
+ * otherwise, for a call of no built-in kind, a raw input that is just a
251
+ * server, a tool, and its arguments. Anything else is not ours.
252
+ */
253
+ function isOurs(toolCall, requestMeta, ours) {
254
+ const meta = (toolCall['_meta'] ?? {});
255
+ if (meta.claudeCode !== undefined) {
256
+ const name = meta.claudeCode.toolName;
257
+ const prefix = `mcp__${MCP_SERVER_NAME}__`;
258
+ return typeof name === 'string' && name.startsWith(prefix) && ours.has(name.slice(prefix.length));
259
+ }
260
+ if (meta.is_mcp_tool_call === true || requestMeta?.['is_mcp_tool_approval'] === true)
261
+ return mcpCallOf(toolCall.rawInput, ours);
262
+ if (toolCall.kind != null && BUILT_IN_KINDS.has(toolCall.kind))
263
+ return false;
264
+ return mcpCallOf(toolCall.rawInput, ours);
265
+ }
266
+ function titleOf(call) {
267
+ return call.title ?? call.kind ?? 'tool';
268
+ }
269
+ /** Whether a raw input is an MCP call of one of our tools: our server, the tool's name, and its arguments, nothing else. */
270
+ function mcpCallOf(rawInput, ours) {
271
+ if (typeof rawInput !== 'object' || rawInput === null || Array.isArray(rawInput))
272
+ return false;
273
+ const fields = rawInput;
274
+ if (!Object.keys(fields).every((key) => MCP_CALL_FIELDS.has(key)))
275
+ return false;
276
+ const server = fields['server'] ?? fields['serverName'] ?? fields['server_name'];
277
+ const tool = fields['tool'] ?? fields['toolName'] ?? fields['tool_name'];
278
+ return server === MCP_SERVER_NAME && typeof tool === 'string' && ours.has(tool);
279
+ }
280
+ /** The fields of an MCP call's raw input as adapters report it. */
281
+ const MCP_CALL_FIELDS = new Set(['server', 'serverName', 'server_name', 'tool', 'toolName', 'tool_name', 'arguments', 'args', 'input']);
282
+ function defined(value) {
283
+ return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== undefined && field !== null));
284
+ }
285
+ function lastLine(text) {
286
+ return text.trim().split('\n').at(-1) ?? '';
287
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The tools a session offers: the built-in agent's action tools
3
+ * (`createGrammarTools` from `e2e/agent`) and its `complete_step`
4
+ * (`createVerdictTool`). An ACP session lists its tools once, while e2e
5
+ * builds them per step, so the session lists them from its first step and
6
+ * each call runs the active step's own tool of that name. Every action goes
7
+ * through `ctx.actions`, where the runner authorizes, counts, and records
8
+ * it, so steps replay from the cache as the built-in agent's do.
9
+ */
10
+ import type { StepExecutorContext, StepVerdict } from 'e2e';
11
+ import { type VerdictTool } from 'e2e/agent';
12
+ import type { ServedTool } from './mcp.ts';
13
+ /** One tool as `e2e/agent` builds it: an AI SDK tool. */
14
+ interface AgentTool {
15
+ readonly description?: string;
16
+ readonly inputSchema: unknown;
17
+ readonly execute?: (input: unknown, options: {
18
+ toolCallId: string;
19
+ messages: [];
20
+ }) => unknown;
21
+ }
22
+ type AgentTools = Readonly<Record<string, AgentTool>>;
23
+ /** The step a session serves now. */
24
+ export interface ActiveStep {
25
+ readonly ctx: StepExecutorContext;
26
+ /** The step's `complete_step`, which holds its verdict once the agent concludes. */
27
+ readonly conclusion: VerdictTool;
28
+ /** A runtime error a tool hit; the turn is cancelled and `runStep` rethrows it. */
29
+ halted: unknown;
30
+ /** A tool of the agent's own that ran without asking; the turn is cancelled and the step fails. */
31
+ denied: string | undefined;
32
+ /** Tool names in call order, for the transcript. */
33
+ readonly calls: string[];
34
+ /** The step's own action tools, built on its first look. */
35
+ tools?: AgentTools;
36
+ }
37
+ /** The step a session starts serving, with nothing concluded yet. */
38
+ export declare function activeStep(ctx: StepExecutorContext): ActiveStep;
39
+ /** The verdict the agent concluded the step with, if it did. */
40
+ export declare function verdictOf(active: ActiveStep): StepVerdict | undefined;
41
+ /** Where the tools find the active step, and how a tool ends the turn early. */
42
+ export interface StepSlot {
43
+ active: ActiveStep | undefined;
44
+ /** Called when a tool hit a runtime error: cancels the agent's turn. */
45
+ halt(): void;
46
+ }
47
+ /** The step's first screen, whole: the first look of its action tools, which later results report changes against. */
48
+ export declare function openingScreen(active: ActiveStep): Promise<string>;
49
+ /** The listed tools the active step does not offer, by the reason it would give. */
50
+ export declare function missingTools(active: ActiveStep, listed: readonly ServedTool[]): string[];
51
+ /** The session's tools, listed from its first step. */
52
+ export declare function stepTools(slot: StepSlot, first: StepExecutorContext): ServedTool[];
53
+ export {};