zidane 5.13.1 → 5.13.3
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/README.md +8 -2
- package/dist/{acp-CEE6C0m_.js → acp-BqIU2mo-.js} +109 -12
- package/dist/acp-BqIU2mo-.js.map +1 -0
- package/dist/acp-cli.js +164 -26
- package/dist/acp-cli.js.map +1 -1
- package/dist/acp.d.ts +41 -2
- package/dist/acp.d.ts.map +1 -1
- package/dist/acp.js +1 -1
- package/dist/chat.js +3 -2
- package/dist/chat.js.map +1 -1
- package/dist/eval.js +2 -2
- package/dist/{headless-Bz1SpTB-.js → headless-0O6HMNBQ.js} +5 -5
- package/dist/{headless-Bz1SpTB-.js.map → headless-0O6HMNBQ.js.map} +1 -1
- package/dist/headless.js +1 -1
- package/dist/index.js +6 -6
- package/dist/{messages-CGazSyTL.js → messages-DEsLGBB9.js} +2 -2
- package/dist/{messages-CGazSyTL.js.map → messages-DEsLGBB9.js.map} +1 -1
- package/dist/output/stream-json.js +1 -1
- package/dist/{presets-5IGiSsxm.js → presets-HDIxliiq.js} +2 -2
- package/dist/{presets-5IGiSsxm.js.map → presets-HDIxliiq.js.map} +1 -1
- package/dist/presets.js +1 -1
- package/dist/{providers-DMPAmUuY.js → providers-Cz-RNYZO.js} +2 -2
- package/dist/{providers-DMPAmUuY.js.map → providers-Cz-RNYZO.js.map} +1 -1
- package/dist/providers.js +2 -2
- package/dist/{session-B69BQSn1.js → session-BDWZZaYa.js} +2 -2
- package/dist/{session-B69BQSn1.js.map → session-BDWZZaYa.js.map} +1 -1
- package/dist/session.js +2 -2
- package/dist/{tools-CfS7rjuh.js → tools-DhzKzB1y.js} +2 -2
- package/dist/{tools-CfS7rjuh.js.map → tools-DhzKzB1y.js.map} +1 -1
- package/dist/tools.js +1 -1
- package/dist/{transcript-anchors-B_a1edre.js → transcript-anchors-Cq-8gx8u.js} +7 -1415
- package/dist/transcript-anchors-Cq-8gx8u.js.map +1 -0
- package/dist/tui.js +6 -5
- package/dist/tui.js.map +1 -1
- package/dist/xdg-zlSeVBhQ.js +1417 -0
- package/dist/xdg-zlSeVBhQ.js.map +1 -0
- package/docs/ACP.md +77 -1
- package/package.json +1 -1
- package/dist/acp-CEE6C0m_.js.map +0 -1
- package/dist/transcript-anchors-B_a1edre.js.map +0 -1
package/README.md
CHANGED
|
@@ -143,10 +143,16 @@ For `local` / `openai-compat`, `--base-url`, `--api-key-env`, `--headers-env`, `
|
|
|
143
143
|
Zidane ships an opt-in [Agent Client Protocol](https://agentclientprotocol.com) v1 adapter for editors and IDEs. Install the package and point your ACP client at:
|
|
144
144
|
|
|
145
145
|
```bash
|
|
146
|
-
zidane-acp --provider anthropic --model claude-sonnet-4-5
|
|
146
|
+
zidane-acp --provider anthropic --model claude-sonnet-4-5 --session-db ~/.zidane/acp-sessions.db
|
|
147
147
|
```
|
|
148
148
|
|
|
149
|
-
|
|
149
|
+
Expose a model picker to the client (e.g. Zed's dropdown) with `--models a,b` (one provider) or repeatable `--model-option provider:model[:label]` for cross-provider models — each resolves its own credentials lazily.
|
|
150
|
+
|
|
151
|
+
Use `--session-db` for clients like Zed that reopen ACP thread IDs across app restarts; otherwise old threads are unknown after the ACP server process exits.
|
|
152
|
+
|
|
153
|
+
Credentials come from Zidane's app credential store (`~/.zidane/credentials.json`) by default, so no API keys are needed in the editor config; explicit env vars still win. ACP doesn't let editors forward their own provider keys, so configure Zidane credentials once to keep secrets out of `settings.json`.
|
|
154
|
+
|
|
155
|
+
For Zed config, model selection, stdio framing details, session persistence, and in-process usage via `zidane/acp`, see [docs/ACP.md](./docs/ACP.md).
|
|
150
156
|
|
|
151
157
|
## Providers
|
|
152
158
|
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { I as defaultPromptMessage } from "./messages-DEsLGBB9.js";
|
|
2
|
+
import { d as createAgent } from "./tools-DhzKzB1y.js";
|
|
2
3
|
import { r as createProcessContext } from "./contexts-DHi8LPCp.js";
|
|
3
4
|
import { o as toolResultToText } from "./types-DxHDaqN7.js";
|
|
4
5
|
import { o as readStateKey, r as hashContent, s as resolveReadStateMap } from "./read-state-DH2IuQHX.js";
|
|
5
6
|
import { l as errorMessage } from "./errors-BpPfMo_4.js";
|
|
6
7
|
import { t as effectiveInputFromTurn } from "./stats-DAKBEKjc.js";
|
|
7
|
-
import { i as basic_default } from "./presets-
|
|
8
|
-
import { r as loadSession, t as createSession } from "./session-
|
|
8
|
+
import { i as basic_default } from "./presets-HDIxliiq.js";
|
|
9
|
+
import { r as loadSession, t as createSession } from "./session-BDWZZaYa.js";
|
|
9
10
|
import { resolve } from "node:path";
|
|
10
11
|
import { Buffer } from "node:buffer";
|
|
11
12
|
//#region src/acp/json-rpc.ts
|
|
@@ -633,6 +634,7 @@ function seedReadState(ctx, path, content, offset, limit) {
|
|
|
633
634
|
//#endregion
|
|
634
635
|
//#region src/acp/server.ts
|
|
635
636
|
const ACP_AGENT_VERSION = "1";
|
|
637
|
+
const MODEL_CONFIG_ID = "model";
|
|
636
638
|
const DEFAULT_PERMISSION_OPTIONS = [
|
|
637
639
|
{
|
|
638
640
|
optionId: "allow_once",
|
|
@@ -666,11 +668,49 @@ var AcpServerImpl = class {
|
|
|
666
668
|
modes;
|
|
667
669
|
defaultModeId;
|
|
668
670
|
defaultConfigOptions;
|
|
671
|
+
modelChoices;
|
|
672
|
+
defaultModelChoiceId;
|
|
673
|
+
builtProviders = /* @__PURE__ */ new Map();
|
|
669
674
|
constructor(options) {
|
|
670
675
|
this.options = options;
|
|
671
676
|
this.modes = defaultModes(options.modes);
|
|
672
677
|
this.defaultModeId = options.defaultModeId ?? this.modes[0]?.id ?? "build";
|
|
673
|
-
this.
|
|
678
|
+
this.modelChoices = options.models ?? [];
|
|
679
|
+
if (this.modelChoices.length === 0 && options.provider === void 0) throw new Error("AcpServerOptions requires either `provider` or `models`.");
|
|
680
|
+
this.defaultModelChoiceId = this.resolveDefaultModelChoiceId(options.defaultModelId);
|
|
681
|
+
this.defaultConfigOptions = this.buildDefaultConfigOptions(options.configOptions ?? []);
|
|
682
|
+
}
|
|
683
|
+
resolveDefaultModelChoiceId(requested) {
|
|
684
|
+
if (this.modelChoices.length === 0) return void 0;
|
|
685
|
+
if (requested !== void 0) {
|
|
686
|
+
if (!this.modelChoices.some((choice) => choice.id === requested)) throw new Error(`defaultModelId "${requested}" is not present in the models registry.`);
|
|
687
|
+
return requested;
|
|
688
|
+
}
|
|
689
|
+
return ((this.options.model ? this.modelChoices.find((choice) => choice.id === this.options.model || choice.model === this.options.model) : void 0) ?? this.modelChoices[0]).id;
|
|
690
|
+
}
|
|
691
|
+
buildDefaultConfigOptions(userConfig) {
|
|
692
|
+
if (this.modelChoices.length === 0) return userConfig;
|
|
693
|
+
return [{
|
|
694
|
+
id: MODEL_CONFIG_ID,
|
|
695
|
+
name: "Model",
|
|
696
|
+
type: "select",
|
|
697
|
+
category: "model",
|
|
698
|
+
currentValue: this.defaultModelChoiceId,
|
|
699
|
+
options: this.modelChoices.map((choice) => ({
|
|
700
|
+
value: choice.id,
|
|
701
|
+
name: choice.name ?? choice.model
|
|
702
|
+
}))
|
|
703
|
+
}, ...userConfig.filter((option) => option.id !== MODEL_CONFIG_ID)];
|
|
704
|
+
}
|
|
705
|
+
providerForChoiceId(id) {
|
|
706
|
+
const choice = this.modelChoices.find((candidate) => candidate.id === id);
|
|
707
|
+
if (!choice) throw new AcpProtocolError(-32602, `Unknown model: ${id}`);
|
|
708
|
+
let provider = this.builtProviders.get(id);
|
|
709
|
+
if (!provider) {
|
|
710
|
+
provider = typeof choice.provider === "function" ? choice.provider() : choice.provider;
|
|
711
|
+
this.builtProviders.set(id, provider);
|
|
712
|
+
}
|
|
713
|
+
return provider;
|
|
674
714
|
}
|
|
675
715
|
setPeer(peer) {
|
|
676
716
|
this.peer = peer;
|
|
@@ -870,7 +910,7 @@ var AcpServerImpl = class {
|
|
|
870
910
|
});
|
|
871
911
|
stats = await runtime.agent.run({
|
|
872
912
|
prompt: mapped.prompt,
|
|
873
|
-
...
|
|
913
|
+
...runtime.runModel ? { model: runtime.runModel } : {},
|
|
874
914
|
...this.options.system ? { system: this.options.system } : {},
|
|
875
915
|
signal: abortController.signal
|
|
876
916
|
});
|
|
@@ -908,7 +948,10 @@ var AcpServerImpl = class {
|
|
|
908
948
|
}
|
|
909
949
|
async setConfigOption(params) {
|
|
910
950
|
const runtime = this.requireSession(params.sessionId);
|
|
951
|
+
const isModelSwitch = this.modelChoices.length > 0 && params.configId === MODEL_CONFIG_ID;
|
|
952
|
+
if (isModelSwitch && runtime.inFlight) throw new AcpProtocolError(-32600, "Cannot switch model while a prompt is in flight.");
|
|
911
953
|
const configOptions = this.applyConfigSelection(runtime, params.configId, params.value);
|
|
954
|
+
if (isModelSwitch) this.selectModel(runtime, params.value);
|
|
912
955
|
runtime.config.set(params.configId, params.value);
|
|
913
956
|
await this.sessionUpdate(params.sessionId, {
|
|
914
957
|
sessionUpdate: "config_option_update",
|
|
@@ -916,6 +959,17 @@ var AcpServerImpl = class {
|
|
|
916
959
|
});
|
|
917
960
|
return { configOptions };
|
|
918
961
|
}
|
|
962
|
+
/**
|
|
963
|
+
* Rebind a live session to the provider + model of the selected registry
|
|
964
|
+
* choice. The agent is NOT rebuilt — only the router's delegate and the run
|
|
965
|
+
* model change — so execution handles and background tasks survive a switch.
|
|
966
|
+
*/
|
|
967
|
+
selectModel(runtime, choiceId) {
|
|
968
|
+
const choice = this.modelChoices.find((candidate) => candidate.id === choiceId);
|
|
969
|
+
if (!choice) throw new AcpProtocolError(-32602, `Unknown model: ${choiceId}`);
|
|
970
|
+
runtime.setProviderDelegate?.(this.providerForChoiceId(choice.id));
|
|
971
|
+
runtime.runModel = choice.model;
|
|
972
|
+
}
|
|
919
973
|
/** Reflect a `select` choice back into the advertised option set's `currentValue`. */
|
|
920
974
|
applyConfigSelection(runtime, configId, value) {
|
|
921
975
|
const option = runtime.configOptions.find((candidate) => candidate.id === configId);
|
|
@@ -942,7 +996,10 @@ var AcpServerImpl = class {
|
|
|
942
996
|
const mcpServers = acpMcpServersToZidane(params.mcpServers);
|
|
943
997
|
const session = await this.resolveSession(requestedSessionId, params.cwd, mustExist);
|
|
944
998
|
const execution = this.resolveExecution(params);
|
|
945
|
-
const
|
|
999
|
+
const initialChoiceId = this.defaultModelChoiceId;
|
|
1000
|
+
const router = initialChoiceId !== void 0 ? createProviderRouter(this.providerForChoiceId(initialChoiceId)) : void 0;
|
|
1001
|
+
const provider = router ? router.provider : this.resolveProvider();
|
|
1002
|
+
const runModel = initialChoiceId !== void 0 ? this.modelChoices.find((choice) => choice.id === initialChoiceId).model : this.options.model;
|
|
946
1003
|
const sessionId = session.id;
|
|
947
1004
|
const base = this.options.preset ?? basic_default;
|
|
948
1005
|
const agentOptions = this.options.agentOptions ?? {};
|
|
@@ -977,9 +1034,12 @@ var AcpServerImpl = class {
|
|
|
977
1034
|
session,
|
|
978
1035
|
execution,
|
|
979
1036
|
agent,
|
|
1037
|
+
provider,
|
|
980
1038
|
modeId: this.defaultModeId,
|
|
981
1039
|
configOptions: cloneConfigOptions(this.defaultConfigOptions),
|
|
982
|
-
config: /* @__PURE__ */ new Map()
|
|
1040
|
+
config: /* @__PURE__ */ new Map(),
|
|
1041
|
+
...runModel !== void 0 ? { runModel } : {},
|
|
1042
|
+
...router ? { setProviderDelegate: router.setDelegate } : {}
|
|
983
1043
|
};
|
|
984
1044
|
this.installHookAdapter(runtime);
|
|
985
1045
|
this.sessions.set(sessionId, runtime);
|
|
@@ -1019,7 +1079,10 @@ var AcpServerImpl = class {
|
|
|
1019
1079
|
return this.options.execution ?? createProcessContext({ cwd: params.cwd });
|
|
1020
1080
|
}
|
|
1021
1081
|
resolveProvider() {
|
|
1022
|
-
|
|
1082
|
+
if (this.defaultModelChoiceId !== void 0) return this.providerForChoiceId(this.defaultModelChoiceId);
|
|
1083
|
+
const provider = this.options.provider;
|
|
1084
|
+
if (provider === void 0) throw new AcpProtocolError(-32603, "No provider configured.");
|
|
1085
|
+
return typeof provider === "function" ? provider() : provider;
|
|
1023
1086
|
}
|
|
1024
1087
|
installHookAdapter(runtime) {
|
|
1025
1088
|
const seenTools = /* @__PURE__ */ new Set();
|
|
@@ -1129,7 +1192,7 @@ var AcpServerImpl = class {
|
|
|
1129
1192
|
});
|
|
1130
1193
|
});
|
|
1131
1194
|
runtime.agent.hooks.hook("turn:after", ({ usage, cumulativeUsage }) => {
|
|
1132
|
-
const size = this.resolveContextWindow();
|
|
1195
|
+
const size = this.resolveContextWindow(runtime);
|
|
1133
1196
|
if (size === void 0) return;
|
|
1134
1197
|
const used = effectiveInputFromTurn(usage);
|
|
1135
1198
|
if (used <= 0) return;
|
|
@@ -1142,11 +1205,11 @@ var AcpServerImpl = class {
|
|
|
1142
1205
|
});
|
|
1143
1206
|
});
|
|
1144
1207
|
}
|
|
1145
|
-
resolveContextWindow() {
|
|
1208
|
+
resolveContextWindow(runtime) {
|
|
1146
1209
|
if (typeof this.options.contextWindow === "number" && this.options.contextWindow > 0) return this.options.contextWindow;
|
|
1147
1210
|
const fromBehavior = this.options.behavior?.autoCompact;
|
|
1148
1211
|
if (fromBehavior && typeof fromBehavior === "object" && typeof fromBehavior.contextWindow === "number" && fromBehavior.contextWindow > 0) return fromBehavior.contextWindow;
|
|
1149
|
-
const meta =
|
|
1212
|
+
const meta = runtime.provider.meta;
|
|
1150
1213
|
if (typeof meta.contextWindow === "number" && meta.contextWindow > 0) return meta.contextWindow;
|
|
1151
1214
|
}
|
|
1152
1215
|
shouldRequestPermission(name, input) {
|
|
@@ -1201,6 +1264,40 @@ var AcpProtocolError = class extends Error {
|
|
|
1201
1264
|
this.name = "AcpProtocolError";
|
|
1202
1265
|
}
|
|
1203
1266
|
};
|
|
1267
|
+
/**
|
|
1268
|
+
* A provider that forwards every call to a swappable delegate. Lets a session
|
|
1269
|
+
* change its underlying provider (and thus credentials) on a model switch
|
|
1270
|
+
* without rebuilding the agent — the loop reads `formatTools` / message builders
|
|
1271
|
+
* / `meta` / `stream` fresh each run, and switches only happen between prompts.
|
|
1272
|
+
*/
|
|
1273
|
+
function createProviderRouter(initial) {
|
|
1274
|
+
let delegate = initial;
|
|
1275
|
+
return {
|
|
1276
|
+
provider: {
|
|
1277
|
+
get name() {
|
|
1278
|
+
return delegate.name;
|
|
1279
|
+
},
|
|
1280
|
+
get meta() {
|
|
1281
|
+
return delegate.meta;
|
|
1282
|
+
},
|
|
1283
|
+
formatTools: (tools) => delegate.formatTools(tools),
|
|
1284
|
+
userMessage: (content) => delegate.userMessage(content),
|
|
1285
|
+
assistantMessage: (content) => delegate.assistantMessage(content),
|
|
1286
|
+
toolResultsMessage: (results) => delegate.toolResultsMessage(results),
|
|
1287
|
+
stream: (options, callbacks) => delegate.stream(options, callbacks),
|
|
1288
|
+
promptMessage: (parts) => routePromptMessage(delegate, parts),
|
|
1289
|
+
classifyError: (err) => delegate.classifyError ? delegate.classifyError(err) : null,
|
|
1290
|
+
countTokens: (payload, signal) => delegate.countTokens ? delegate.countTokens(payload, signal) : Promise.resolve(null)
|
|
1291
|
+
},
|
|
1292
|
+
setDelegate: (next) => {
|
|
1293
|
+
delegate = next;
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
function routePromptMessage(delegate, parts) {
|
|
1298
|
+
if (delegate.promptMessage) return delegate.promptMessage(parts);
|
|
1299
|
+
return defaultPromptMessage(parts);
|
|
1300
|
+
}
|
|
1204
1301
|
function mergeTools(...sources) {
|
|
1205
1302
|
const out = {};
|
|
1206
1303
|
for (const source of sources) if (source) Object.assign(out, source);
|
|
@@ -1310,4 +1407,4 @@ function runAcpStdioServer(options) {
|
|
|
1310
1407
|
//#endregion
|
|
1311
1408
|
export { acpMcpServersToZidane as a, stopReasonFromRun as c, createJsonRpcConnection as d, wrapToolsForAcpClient as i, toolResultToAcpContent as l, AcpProtocolError as n, acpPromptToPromptParts as o, createAcpServer as r, sessionBlocksToAcp as s, runAcpStdioServer as t, JsonRpcRemoteError as u };
|
|
1312
1409
|
|
|
1313
|
-
//# sourceMappingURL=acp-
|
|
1410
|
+
//# sourceMappingURL=acp-BqIU2mo-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"acp-BqIU2mo-.js","names":["isObject","lastFinishReason","basic"],"sources":["../src/acp/json-rpc.ts","../src/acp/mapping.ts","../src/acp/client-tools.ts","../src/acp/server.ts","../src/acp/index.ts"],"sourcesContent":["import type { Readable, Writable } from 'node:stream'\nimport type { AcpPeer, JsonRpcFailure, JsonRpcId, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse } from './types'\nimport { Buffer } from 'node:buffer'\nimport { AcpErrorCode } from './types'\n\nexport interface JsonRpcConnectionOptions {\n input: Readable\n output: Writable\n onRequest: (message: JsonRpcRequest) => Promise<JsonRpcResponse | null | undefined> | JsonRpcResponse | null | undefined\n onNotification?: (message: JsonRpcMessage & { method: string, id?: undefined }) => void | Promise<void>\n framing?: 'content-length' | 'newline'\n onError?: (error: Error) => void\n}\n\nexport interface JsonRpcConnection extends AcpPeer {\n start: () => void\n close: () => void\n}\n\ninterface PendingRequest {\n resolve: (value: unknown) => void\n reject: (error: Error) => void\n}\n\nexport function createJsonRpcConnection(options: JsonRpcConnectionOptions): JsonRpcConnection {\n let nextId = 1\n let closed = false\n let buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0)\n const pending = new Map<JsonRpcId, PendingRequest>()\n\n const writeMessage = (message: JsonRpcMessage): void => {\n if (closed)\n return\n const json = JSON.stringify({ ...message, jsonrpc: '2.0' })\n // ACP stdio framing is newline-delimited JSON (NDJSON) and is the default.\n // `JSON.stringify` escapes any embedded newline, so a serialized message is\n // always a single line. LSP-style `Content-Length` framing is opt-in for\n // non-ACP transports only.\n if (options.framing === 'content-length') {\n const bytes = Buffer.byteLength(json)\n options.output.write(`Content-Length: ${bytes}\\r\\n\\r\\n${json}`)\n return\n }\n options.output.write(`${json}\\n`)\n }\n\n const handleParsed = async (message: unknown): Promise<void> => {\n if (!isObject(message)) {\n writeMessage(errorResponse(null, AcpErrorCode.InvalidRequest, 'Invalid JSON-RPC message.'))\n return\n }\n\n const msg = message as unknown as JsonRpcMessage\n if ('id' in msg && ('result' in msg || 'error' in msg)) {\n const request = pending.get(msg.id)\n if (!request)\n return\n pending.delete(msg.id)\n if ('error' in msg && msg.error) {\n request.reject(new JsonRpcRemoteError(msg.error.message, msg.error.code, msg.error.data))\n }\n else {\n request.resolve((msg as { result?: unknown }).result)\n }\n return\n }\n\n if (typeof (msg as { method?: unknown }).method !== 'string') {\n writeMessage(errorResponse(('id' in msg ? msg.id : null) ?? null, AcpErrorCode.InvalidRequest, 'Missing JSON-RPC method.'))\n return\n }\n\n if ('id' in msg) {\n try {\n const response = await options.onRequest(msg as JsonRpcRequest)\n if (response)\n writeMessage(response)\n }\n catch (err) {\n writeMessage(errorResponse(msg.id, AcpErrorCode.InternalError, err instanceof Error ? err.message : String(err)))\n }\n return\n }\n\n try {\n await options.onNotification?.(msg as JsonRpcMessage & { method: string, id?: undefined })\n }\n catch (err) {\n options.onError?.(err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n const onData = (chunk: Buffer | string): void => {\n buffer = Buffer.concat([buffer, typeof chunk === 'string' ? Buffer.from(chunk) : chunk])\n for (;;) {\n let parsed: { message: unknown, rest: Buffer<ArrayBufferLike> } | null\n try {\n parsed = readNextMessage(buffer)\n }\n catch (err) {\n buffer = Buffer.alloc(0)\n writeMessage(errorResponse(null, AcpErrorCode.ParseError, err instanceof Error ? err.message : String(err)))\n break\n }\n if (!parsed)\n break\n buffer = parsed.rest\n void handleParsed(parsed.message)\n }\n }\n\n const onError = (err: Error): void => {\n options.onError?.(err)\n }\n\n return {\n start() {\n options.input.on('data', onData)\n options.input.on('error', onError)\n },\n close() {\n closed = true\n options.input.off('data', onData)\n options.input.off('error', onError)\n for (const request of pending.values())\n request.reject(new Error('JSON-RPC connection closed.'))\n pending.clear()\n },\n sendNotification(method: string, params?: unknown) {\n writeMessage({ jsonrpc: '2.0', method, ...(params !== undefined ? { params } : {}) })\n },\n sendRequest(method: string, params?: unknown) {\n if (closed)\n return Promise.reject(new Error('JSON-RPC connection is closed.'))\n const id = nextId++\n writeMessage({ jsonrpc: '2.0', id, method, ...(params !== undefined ? { params } : {}) })\n return new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject })\n })\n },\n }\n}\n\nexport class JsonRpcRemoteError extends Error {\n constructor(message: string, readonly code: number, readonly data?: unknown) {\n super(message)\n this.name = 'JsonRpcRemoteError'\n }\n}\n\nexport function successResponse(id: JsonRpcId, result: unknown = {}): JsonRpcResponse {\n return { jsonrpc: '2.0', id, result }\n}\n\nexport function errorResponse(id: JsonRpcId, code: number, message: string, data?: unknown): JsonRpcFailure {\n return {\n jsonrpc: '2.0',\n id,\n error: {\n code,\n message,\n ...(data !== undefined ? { data } : {}),\n },\n }\n}\n\nfunction readNextMessage(input: Buffer<ArrayBufferLike>): { message: unknown, rest: Buffer<ArrayBufferLike> } | null {\n if (input.length === 0)\n return null\n\n const headerEnd = input.indexOf('\\r\\n\\r\\n')\n if (headerEnd >= 0) {\n const header = input.subarray(0, headerEnd).toString('utf8')\n const match = /^Content-Length:\\s*(\\d+)/im.exec(header)\n if (!match)\n return readLineMessage(input)\n const length = Number(match[1])\n const bodyStart = headerEnd + 4\n const bodyEnd = bodyStart + length\n if (input.length < bodyEnd)\n return null\n const body = input.subarray(bodyStart, bodyEnd).toString('utf8')\n return { message: JSON.parse(body), rest: input.subarray(bodyEnd) }\n }\n\n if (/^Content-Length:/i.test(input.subarray(0, Math.min(input.length, 32)).toString('utf8')))\n return null\n\n return readLineMessage(input)\n}\n\nfunction readLineMessage(input: Buffer<ArrayBufferLike>): { message: unknown, rest: Buffer<ArrayBufferLike> } | null {\n let rest = input\n // Skip blank lines: NDJSON streams may contain stray newlines (e.g. a keep-\n // alive or a trailing separator). Emitting an error for those would be wrong.\n for (;;) {\n const lineEnd = rest.indexOf('\\n')\n if (lineEnd < 0)\n return null\n const line = rest.subarray(0, lineEnd).toString('utf8').trim()\n rest = rest.subarray(lineEnd + 1)\n if (line.length === 0)\n continue\n return { message: JSON.parse(line), rest }\n }\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n","import type { McpServerConfig, PromptPart, SessionContentBlock, ToolResultContent, TurnFinishReason, TurnUsage } from '../types'\nimport type {\n AcpMcpServer,\n AcpPromptMapping,\n ContentBlock,\n Cost,\n EmbeddedResource,\n EmbeddedResourceResource,\n McpCapabilities,\n NewSessionResponse,\n PromptCapabilities,\n SessionMode,\n SessionModeState,\n StopReason,\n ToolCallContent,\n ToolKind,\n} from './types'\nimport { resolve } from 'node:path'\nimport { toolResultToText } from '../types'\n\nexport function acpMcpServersToZidane(servers: readonly AcpMcpServer[] | undefined): McpServerConfig[] {\n if (!servers)\n return []\n return servers.map((server): McpServerConfig => {\n if (server.type === 'http') {\n return {\n name: server.name,\n transport: 'streamable-http',\n url: server.url,\n headers: headersToRecord(server.headers),\n }\n }\n if (server.type === 'sse') {\n return {\n name: server.name,\n transport: 'sse',\n url: server.url,\n headers: headersToRecord(server.headers),\n }\n }\n const stdio = server as Extract<AcpMcpServer, { command: string }>\n return {\n name: server.name,\n transport: 'stdio',\n command: stdio.command,\n args: stdio.args ?? [],\n env: envToRecord(stdio.env),\n }\n })\n}\n\nexport function promptCapabilitiesForProvider(capabilities: { vision?: boolean, audio?: boolean } | undefined): PromptCapabilities {\n return {\n image: capabilities?.vision === true,\n audio: capabilities?.audio === true,\n embeddedContext: true,\n }\n}\n\nexport function mcpCapabilities(): McpCapabilities {\n return { http: true, sse: true }\n}\n\nexport function defaultModes(modes: readonly SessionMode[] | undefined): SessionMode[] {\n return modes && modes.length > 0\n ? [...modes]\n : [\n { id: 'build', name: 'Build', description: 'Full tool access for implementation work.' },\n { id: 'plan', name: 'Plan', description: 'Planning-oriented mode; hosts may narrow tools separately.' },\n ]\n}\n\nexport function makeModeState(modes: readonly SessionMode[], currentModeId: string): SessionModeState {\n return { currentModeId, availableModes: [...modes] }\n}\n\nexport function newSessionResponse(\n sessionId: string,\n modes: readonly SessionMode[],\n currentModeId: string,\n configOptions?: NewSessionResponse['configOptions'],\n): NewSessionResponse {\n return {\n sessionId,\n modes: makeModeState(modes, currentModeId),\n ...(configOptions && configOptions.length > 0 ? { configOptions } : {}),\n }\n}\n\nexport function acpPromptToPromptParts(prompt: readonly ContentBlock[]): AcpPromptMapping {\n const parts: PromptPart[] = []\n const warnings: string[] = []\n\n for (const block of prompt) {\n switch (block.type) {\n case 'text':\n parts.push({ type: 'text', text: block.text })\n break\n case 'image': {\n if (block.data) {\n parts.push({ type: 'image', mediaType: block.mimeType || 'image/png', data: block.data })\n }\n else {\n warnings.push(`Image resource linked instead of embedded: ${block.uri ?? 'unknown URI'}`)\n parts.push({ type: 'text', text: `[image resource: ${block.uri ?? 'unavailable'}]` })\n }\n break\n }\n case 'audio': {\n if (block.data) {\n parts.push({ type: 'audio', mediaType: block.mimeType || 'audio/mpeg', data: block.data })\n }\n else {\n warnings.push('Audio block omitted because it did not include embedded data.')\n parts.push({ type: 'text', text: '[audio resource omitted: no embedded data]' })\n }\n break\n }\n case 'resource_link':\n parts.push({ type: 'text', text: renderResourceLink(block) })\n break\n case 'resource':\n parts.push(resourceToPromptPart(block))\n break\n default:\n warnings.push('Unknown ACP content block converted to text.')\n parts.push({ type: 'text', text: JSON.stringify(block as Record<string, unknown>) })\n break\n }\n }\n\n return { prompt: parts, warnings }\n}\n\nexport function sessionBlocksToAcp(blocks: readonly SessionContentBlock[]): ContentBlock[] {\n const out: ContentBlock[] = []\n for (const block of blocks) {\n if (block.type === 'text' || block.type === 'thinking') {\n out.push({ type: 'text', text: block.text })\n }\n else if (block.type === 'image') {\n out.push(imageBlockToAcp(block.mediaType, 'data' in block ? block.data : undefined, 'ref' in block ? block.ref : undefined, block.name))\n }\n else if (block.type === 'audio') {\n if (block.data)\n out.push({ type: 'audio', mimeType: block.mediaType, data: block.data })\n }\n else if (block.type === 'document') {\n out.push(documentBlockToAcp(block.mediaType, 'data' in block ? block.data : undefined, 'ref' in block ? block.ref : undefined, block.encoding, block.name))\n }\n }\n return out\n}\n\nexport function toolResultToAcpContent(content: string | ToolResultContent[]): ToolCallContent[] {\n if (typeof content === 'string')\n return [{ type: 'content', content: { type: 'text', text: content } }]\n\n return content.map((block): ToolCallContent => {\n if (block.type === 'text')\n return { type: 'content', content: { type: 'text', text: block.text } }\n if (block.type === 'image') {\n return {\n type: 'content',\n content: imageBlockToAcp(block.mediaType, 'data' in block ? block.data : undefined, 'ref' in block ? block.ref : undefined, 'name' in block ? block.name : undefined),\n }\n }\n if (block.type === 'audio' && block.data)\n return { type: 'content', content: { type: 'audio', mimeType: block.mediaType, data: block.data } }\n if (block.type === 'document') {\n return {\n type: 'content',\n content: documentBlockToAcp(block.mediaType, 'data' in block ? block.data : undefined, 'ref' in block ? block.ref : undefined, block.encoding, 'name' in block ? block.name : undefined),\n }\n }\n return { type: 'content', content: { type: 'text', text: toolResultToText([block]) } }\n })\n}\n\n/**\n * Build a spec-valid ACP image block. `ImageContent` requires `data` +\n * `mimeType`; when we only have a reference (`ref`/uri) we fall back to a\n * `resource_link` (which requires `name` + `uri`) so we never emit an image\n * block missing its required `data`.\n */\nfunction imageBlockToAcp(mimeType: string, data: string | undefined, ref: string | undefined, name: string | undefined): ContentBlock {\n if (data)\n return { type: 'image', mimeType, data, ...(ref ? { uri: ref } : {}) }\n return { type: 'resource_link', uri: ref ?? acpSyntheticUri('image', name), name: name ?? 'image', mimeType }\n}\n\n/**\n * Build a spec-valid embedded `resource` (or a `resource_link` fallback for\n * reference-only documents). `EmbeddedResource.resource` requires a `uri`\n * plus either `text` (text payload) or `blob` (base64), so a synthetic URI is\n * minted when the source block has none.\n */\nfunction documentBlockToAcp(mimeType: string, data: string | undefined, ref: string | undefined, encoding: 'base64' | 'text' | undefined, name: string | undefined): ContentBlock {\n const uri = ref ?? acpSyntheticUri('document', name)\n if (typeof data !== 'string') {\n return { type: 'resource_link', uri, name: name ?? 'document', mimeType }\n }\n const resource: EmbeddedResourceResource = encoding === 'text'\n ? { uri, text: data, mimeType }\n : { uri, blob: data, mimeType }\n return { type: 'resource', resource }\n}\n\nfunction acpSyntheticUri(kind: string, name: string | undefined): string {\n const slug = (name ?? kind).replace(/[^\\w.-]+/g, '_')\n return `acp:///${kind}/${slug}`\n}\n\nexport function toolKindForName(name: string): ToolKind {\n if (name === 'read_file' || name === 'list_files')\n return 'read'\n if (name === 'write_file' || name === 'edit' || name === 'multi_edit')\n return 'edit'\n if (name === 'grep' || name === 'glob' || name === 'tool_search')\n return 'search'\n if (name === 'shell' || name === 'wait_task' || name === 'shell_kill')\n return 'execute'\n if (name === 'web_search' || name === 'fetch_url')\n return 'fetch'\n if (name === 'present_plan' || name === 'ask_user')\n return 'think'\n return 'other'\n}\n\nexport function stopReasonFromRun(input: { aborted: boolean, turnUsage?: TurnUsage[], maxTurnsReached?: boolean }): StopReason {\n if (input.aborted)\n return 'cancelled'\n if (input.maxTurnsReached)\n return 'max_turn_requests'\n const finish = lastFinishReason(input.turnUsage)\n switch (finish) {\n case 'length':\n return 'max_tokens'\n case 'content-filter':\n case 'error':\n return 'refusal'\n default:\n return 'end_turn'\n }\n}\n\nexport function usageCost(cost: number | undefined): Cost | null {\n if (typeof cost !== 'number' || !Number.isFinite(cost))\n return null\n return { amount: cost, currency: 'USD' }\n}\n\nexport function resolveAcpPath(cwd: string, path: string): string {\n return path.startsWith('/') ? path : resolve(cwd, path)\n}\n\nfunction lastFinishReason(turnUsage: TurnUsage[] | undefined): TurnFinishReason | undefined {\n for (let i = (turnUsage?.length ?? 0) - 1; i >= 0; i--) {\n const reason = turnUsage?.[i]?.finishReason\n if (reason)\n return reason\n }\n return undefined\n}\n\nfunction headersToRecord(headers: readonly { name: string, value: string }[] | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n for (const header of headers ?? [])\n out[header.name] = header.value\n return out\n}\n\nfunction envToRecord(env: readonly { name: string, value: string }[] | undefined): Record<string, string> {\n const out: Record<string, string> = {}\n for (const item of env ?? [])\n out[item.name] = item.value\n return out\n}\n\nfunction renderResourceLink(block: { uri: string, name?: string | null, title?: string | null, mimeType?: string | null }): string {\n const label = block.title ?? block.name ?? block.uri\n return block.mimeType\n ? `[resource: ${label}](${block.uri}) (${block.mimeType})`\n : `[resource: ${label}](${block.uri})`\n}\n\nfunction resourceToPromptPart(block: EmbeddedResource): PromptPart {\n const resource = block.resource\n const mediaType = resource.mimeType ?? 'text/plain'\n const name = nameFromUri(resource.uri)\n if ('text' in resource && typeof resource.text === 'string') {\n return {\n type: 'document',\n mediaType,\n data: resource.text,\n encoding: 'text',\n ...(name ? { name } : {}),\n }\n }\n if ('blob' in resource && typeof resource.blob === 'string') {\n return {\n type: 'document',\n mediaType,\n data: resource.blob,\n encoding: 'base64',\n ...(name ? { name } : {}),\n }\n }\n return { type: 'text', text: `[resource omitted: ${resource.uri}]` }\n}\n\nfunction nameFromUri(uri: string | undefined): string | undefined {\n if (!uri)\n return undefined\n const trimmed = uri.replace(/[/\\\\]+$/, '')\n const segment = trimmed.split(/[/\\\\]/).pop()\n return segment && segment.length > 0 ? segment : undefined\n}\n","import type { ToolContext, ToolDef } from '../tools'\nimport type { AcpClientCapabilities, AcpPeer, CreateTerminalRequest, TerminalOutputResponse } from './types'\nimport { Buffer } from 'node:buffer'\nimport { hashContent, readStateKey, resolveReadStateMap } from '../tools'\nimport { resolveAcpPath } from './mapping'\n\nexport interface AcpClientToolOptions {\n client: AcpPeer\n sessionId: string\n capabilities: AcpClientCapabilities\n useClientFileSystem?: boolean\n useClientTerminal?: boolean\n}\n\nexport function wrapToolsForAcpClient(tools: Record<string, ToolDef> | undefined, options: AcpClientToolOptions): Record<string, ToolDef> | undefined {\n if (!tools)\n return undefined\n\n const wrapped: Record<string, ToolDef> = { ...tools }\n const readFileEntry = findToolEntry(tools, 'read_file')\n const writeFileEntry = findToolEntry(tools, 'write_file')\n const shellEntry = findToolEntry(tools, 'shell')\n if (options.useClientFileSystem !== false && options.capabilities.fs?.readTextFile && readFileEntry)\n wrapped[readFileEntry.key] = wrapReadFile(readFileEntry.tool, options)\n if (options.useClientFileSystem !== false && options.capabilities.fs?.writeTextFile && writeFileEntry)\n wrapped[writeFileEntry.key] = wrapWriteFile(writeFileEntry.tool, options)\n if (options.useClientTerminal !== false && options.capabilities.terminal && shellEntry)\n wrapped[shellEntry.key] = wrapShell(shellEntry.tool, options)\n return wrapped\n}\n\nfunction findToolEntry(tools: Record<string, ToolDef>, canonicalName: string): { key: string, tool: ToolDef } | null {\n for (const [key, tool] of Object.entries(tools)) {\n if (key === canonicalName || tool.spec.name === canonicalName)\n return { key, tool }\n }\n return null\n}\n\nfunction wrapReadFile(base: ToolDef, options: AcpClientToolOptions): ToolDef {\n return {\n ...base,\n async execute(input, ctx) {\n const path = typeof input.path === 'string' ? input.path : ''\n if (!path)\n return 'Read error: missing path.'\n const absPath = resolveAcpPath(ctx.handle.cwd, path)\n const line = lineOrDefault(input.offset)\n const limit = positiveNumberOrNull(input.limit)\n const response = await options.client.sendRequest('fs/read_text_file', {\n sessionId: options.sessionId,\n path: absPath,\n line,\n ...(limit !== null ? { limit } : {}),\n }) as { content?: unknown }\n const content = typeof response.content === 'string' ? response.content : ''\n seedReadState(ctx, absPath, content, line ?? 1, limit ?? Number.POSITIVE_INFINITY)\n if (input.lineNumbers === false)\n return content\n return withLineNumbers(content, line ?? 1)\n },\n }\n}\n\nfunction wrapWriteFile(base: ToolDef, options: AcpClientToolOptions): ToolDef {\n return {\n ...base,\n async execute(input, ctx) {\n const path = typeof input.path === 'string' ? input.path : ''\n const content = typeof input.content === 'string' ? input.content : ''\n if (!path)\n return 'Write error: missing path.'\n const absPath = resolveAcpPath(ctx.handle.cwd, path)\n await options.client.sendRequest('fs/write_text_file', {\n sessionId: options.sessionId,\n path: absPath,\n content,\n })\n seedReadState(ctx, absPath, content, 0, Number.POSITIVE_INFINITY)\n ctx.reportOutcome?.('updated')\n return `Wrote ${absPath} (${Buffer.byteLength(content)} bytes).`\n },\n }\n}\n\nfunction wrapShell(base: ToolDef, options: AcpClientToolOptions): ToolDef {\n return {\n ...base,\n spec: withoutShellBackgroundInput(base.spec),\n async execute(input, ctx) {\n const command = typeof input.command === 'string' ? input.command : ''\n if (!command)\n return 'shell error: missing command.'\n if (input.run_in_background === true)\n return 'shell error: background mode is not supported through ACP terminal callbacks. Run the command in the foreground.'\n\n const request: CreateTerminalRequest = {\n sessionId: options.sessionId,\n command,\n cwd: ctx.handle.cwd,\n outputByteLimit: typeof input.maxOutputBytes === 'number' ? input.maxOutputBytes : null,\n }\n const created = await options.client.sendRequest('terminal/create', request) as { terminalId?: unknown }\n const terminalId = typeof created.terminalId === 'string' ? created.terminalId : ''\n if (!terminalId)\n return 'shell error: ACP client did not return a terminal id.'\n\n try {\n const exit = await options.client.sendRequest('terminal/wait_for_exit', {\n sessionId: options.sessionId,\n terminalId,\n }) as { exitCode?: number | null, signal?: string | null }\n const output = await options.client.sendRequest('terminal/output', {\n sessionId: options.sessionId,\n terminalId,\n }) as TerminalOutputResponse\n return formatTerminalOutput(output, exit)\n }\n finally {\n await options.client.sendRequest('terminal/release', {\n sessionId: options.sessionId,\n terminalId,\n }).catch(() => undefined)\n }\n },\n }\n}\n\nfunction formatTerminalOutput(output: TerminalOutputResponse, exit: { exitCode?: number | null, signal?: string | null }): string {\n const body = output.output || '(no output)'\n const code = exit.exitCode ?? output.exitStatus?.exitCode\n const signal = exit.signal ?? output.exitStatus?.signal\n const suffix = signal\n ? `\\n(signal ${signal})`\n : typeof code === 'number'\n ? `\\n(exit ${code})`\n : ''\n const truncated = output.truncated ? '\\n(output truncated by ACP client)' : ''\n return `${body}${truncated}${suffix}`\n}\n\nfunction withoutShellBackgroundInput(spec: ToolDef['spec']): ToolDef['spec'] {\n const properties = isRecord(spec.inputSchema.properties) ? spec.inputSchema.properties : undefined\n if (!properties || !Object.hasOwn(properties, 'run_in_background'))\n return spec\n\n const { run_in_background: _runInBackground, ...nextProperties } = properties\n const required = Array.isArray(spec.inputSchema.required)\n ? spec.inputSchema.required.filter(name => name !== 'run_in_background')\n : spec.inputSchema.required\n\n return {\n ...spec,\n description: spec.description\n .split('\\n')\n .filter(line =>\n !line.includes('run_in_background')\n && !line.includes('<task-notification>')\n && !line.includes('background task'),\n )\n .join('\\n'),\n inputSchema: {\n ...spec.inputSchema,\n properties: nextProperties,\n ...(required ? { required } : {}),\n },\n }\n}\n\nfunction withLineNumbers(content: string, start: number): string {\n return content\n .split('\\n')\n .map((line, index) => `${start + index}\\t${line}`)\n .join('\\n')\n}\n\nfunction lineOrDefault(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.trunc(value) : 1\n}\n\nfunction positiveNumberOrNull(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.trunc(value) : null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction seedReadState(ctx: ToolContext, path: string, content: string, offset: number, limit: number): void {\n const readState = resolveReadStateMap(ctx)\n if (!readState)\n return\n readState.set(readStateKey(ctx.handle.cwd, path), {\n contentHash: hashContent(content),\n offset,\n limit,\n maxBytes: Number.POSITIVE_INFINITY,\n mtimeMs: Date.now(),\n })\n}\n","import type { AgentOptions } from '../agent'\nimport type { Provider } from '../providers'\nimport type { Session } from '../session'\nimport type { ToolDef } from '../tools'\nimport type { AgentStats, McpServerConfig, PromptPart, TurnUsage } from '../types'\nimport type {\n AcpClientCapabilities,\n AcpModelChoice,\n AcpPeer,\n AcpServerOptions,\n AcpSessionRuntime,\n AuthenticateRequest,\n CancelNotification,\n DeleteSessionRequest,\n InitializeRequest,\n JsonRpcMessage,\n JsonRpcRequest,\n JsonRpcResponse,\n ListSessionsRequest,\n LoadSessionRequest,\n NewSessionRequest,\n PermissionOption,\n PromptRequest,\n PromptResponse,\n RequestPermissionOutcome,\n ResumeSessionRequest,\n SessionConfigOption,\n SessionInfo,\n SessionMode,\n SessionUpdate,\n SetSessionConfigOptionRequest,\n SetSessionModeRequest,\n ToolCallUpdate,\n} from './types'\nimport { createAgent } from '../agent'\nimport { createProcessContext } from '../contexts'\nimport { errorMessage } from '../errors'\nimport { basic } from '../presets'\nimport { defaultPromptMessage } from '../prompt'\nimport { createSession, loadSession } from '../session'\nimport { effectiveInputFromTurn } from '../stats'\nimport { wrapToolsForAcpClient } from './client-tools'\nimport { errorResponse, successResponse } from './json-rpc'\nimport {\n acpMcpServersToZidane,\n acpPromptToPromptParts,\n defaultModes,\n makeModeState,\n mcpCapabilities,\n newSessionResponse,\n promptCapabilitiesForProvider,\n sessionBlocksToAcp,\n stopReasonFromRun,\n toolKindForName,\n toolResultToAcpContent,\n usageCost,\n} from './mapping'\nimport { ACP_PROTOCOL_VERSION, AcpErrorCode } from './types'\n\nconst ACP_AGENT_VERSION = '1'\n\n// Reserved id for the auto-generated model selector config option. The registry\n// owns this id; a user-supplied config option with the same id is dropped.\nconst MODEL_CONFIG_ID = 'model'\n\nconst DEFAULT_PERMISSION_OPTIONS: PermissionOption[] = [\n { optionId: 'allow_once', name: 'Allow once', kind: 'allow_once' },\n { optionId: 'allow_always', name: 'Always allow', kind: 'allow_always' },\n { optionId: 'reject_once', name: 'Reject once', kind: 'reject_once' },\n { optionId: 'reject_always', name: 'Always reject', kind: 'reject_always' },\n]\n\nexport interface AcpServer {\n setPeer: (peer: AcpPeer) => void\n handleMessage: (message: JsonRpcMessage) => Promise<JsonRpcResponse | null>\n handleRequest: (method: string, params?: unknown) => Promise<unknown>\n notify: (method: string, params?: unknown) => Promise<void>\n close: () => Promise<void>\n}\n\nexport function createAcpServer(options: AcpServerOptions): AcpServer {\n return new AcpServerImpl(options)\n}\n\nclass AcpServerImpl implements AcpServer {\n private peer: AcpPeer | null = null\n private clientCapabilities: AcpClientCapabilities = {}\n private sessions = new Map<string, AcpSessionRuntime>()\n private modes: SessionMode[]\n private defaultModeId: string\n private defaultConfigOptions: SessionConfigOption[]\n private modelChoices: AcpModelChoice[]\n private defaultModelChoiceId: string | undefined\n // Provider instances memoized by choice id so a provider (and its\n // credentials) is constructed once and reused across sessions/switches.\n private builtProviders = new Map<string, Provider>()\n\n constructor(private readonly options: AcpServerOptions) {\n this.modes = defaultModes(options.modes)\n this.defaultModeId = options.defaultModeId ?? this.modes[0]?.id ?? 'build'\n this.modelChoices = options.models ?? []\n if (this.modelChoices.length === 0 && options.provider === undefined)\n throw new Error('AcpServerOptions requires either `provider` or `models`.')\n this.defaultModelChoiceId = this.resolveDefaultModelChoiceId(options.defaultModelId)\n this.defaultConfigOptions = this.buildDefaultConfigOptions(options.configOptions ?? [])\n }\n\n private resolveDefaultModelChoiceId(requested: string | undefined): string | undefined {\n if (this.modelChoices.length === 0)\n return undefined\n if (requested !== undefined) {\n if (!this.modelChoices.some(choice => choice.id === requested))\n throw new Error(`defaultModelId \"${requested}\" is not present in the models registry.`)\n return requested\n }\n // No explicit default: prefer a choice matching `options.model` (by id or\n // model string), else the first registered entry.\n const matched = this.options.model\n ? this.modelChoices.find(choice => choice.id === this.options.model || choice.model === this.options.model)\n : undefined\n return (matched ?? this.modelChoices[0]).id\n }\n\n private buildDefaultConfigOptions(userConfig: SessionConfigOption[]): SessionConfigOption[] {\n if (this.modelChoices.length === 0)\n return userConfig\n // Model selector first per ACP's option-ordering guidance. The registry\n // reserves the `model` id, so a colliding user option is dropped.\n const modelOption: SessionConfigOption = {\n id: MODEL_CONFIG_ID,\n name: 'Model',\n type: 'select',\n category: 'model',\n currentValue: this.defaultModelChoiceId!,\n options: this.modelChoices.map(choice => ({ value: choice.id, name: choice.name ?? choice.model })),\n }\n return [modelOption, ...userConfig.filter(option => option.id !== MODEL_CONFIG_ID)]\n }\n\n private providerForChoiceId(id: string): Provider {\n const choice = this.modelChoices.find(candidate => candidate.id === id)\n if (!choice)\n throw new AcpProtocolError(AcpErrorCode.InvalidParams, `Unknown model: ${id}`)\n let provider = this.builtProviders.get(id)\n if (!provider) {\n provider = typeof choice.provider === 'function' ? choice.provider() : choice.provider\n this.builtProviders.set(id, provider)\n }\n return provider\n }\n\n setPeer(peer: AcpPeer): void {\n this.peer = peer\n }\n\n async handleMessage(message: JsonRpcMessage): Promise<JsonRpcResponse | null> {\n if (!isObject(message) || typeof (message as { method?: unknown }).method !== 'string') {\n const id = 'id' in (message as object) ? (message as { id?: unknown }).id : null\n return errorResponse(normalizeId(id), AcpErrorCode.InvalidRequest, 'Invalid JSON-RPC request.')\n }\n\n if (!('id' in message)) {\n await this.handleNotification(message.method, (message as { params?: unknown }).params)\n return null\n }\n\n const request = message as JsonRpcRequest\n try {\n const result = await this.handleRequest(request.method, request.params)\n return successResponse(request.id, result)\n }\n catch (err) {\n const rpcError = toRpcError(err)\n return errorResponse(request.id, rpcError.code, rpcError.message, rpcError.data)\n }\n }\n\n async handleRequest(method: string, params?: unknown): Promise<unknown> {\n switch (method) {\n case 'initialize':\n return this.initialize(asObject<InitializeRequest>(params))\n case 'authenticate':\n return this.authenticate(asObject<AuthenticateRequest>(params))\n case 'logout':\n return this.logout()\n case 'session/new':\n return this.newSession(asObject<NewSessionRequest>(params))\n case 'session/load':\n return this.loadExistingSession(asObject<LoadSessionRequest>(params))\n case 'session/resume':\n return this.resumeSession(asObject<ResumeSessionRequest>(params))\n case 'session/list':\n return this.listSessions(asObject<ListSessionsRequest>(params))\n case 'session/delete':\n return this.deleteSession(asObject<DeleteSessionRequest>(params))\n case 'session/close':\n return this.closeSession(asObject<{ sessionId: string }>(params))\n case 'session/prompt':\n return this.prompt(asObject<PromptRequest>(params))\n case 'session/set_mode':\n return this.setMode(asObject<SetSessionModeRequest>(params))\n case 'session/set_config_option':\n return this.setConfigOption(asObject<SetSessionConfigOptionRequest>(params))\n default:\n throw new AcpProtocolError(AcpErrorCode.MethodNotFound, `Unknown ACP method: ${method}`)\n }\n }\n\n async notify(method: string, params?: unknown): Promise<void> {\n await this.peer?.sendNotification(method, params)\n }\n\n async close(): Promise<void> {\n const sessions = [...this.sessions.values()]\n this.sessions.clear()\n await Promise.allSettled(sessions.map(async (runtime) => {\n runtime.abortController?.abort(new Error('ACP server closing.'))\n await runtime.agent.destroy()\n }))\n }\n\n private async handleNotification(method: string, params?: unknown): Promise<void> {\n switch (method) {\n case 'session/cancel':\n this.cancel(asObject<CancelNotification>(params))\n break\n default:\n break\n }\n }\n\n private initialize(params: InitializeRequest): unknown {\n this.clientCapabilities = params.clientCapabilities ?? {}\n const provider = this.resolveProvider()\n return {\n // We currently speak ACP v1 only. Per ACP, return the requested version\n // only if supported; otherwise advertise the latest supported version.\n protocolVersion: params.protocolVersion === ACP_PROTOCOL_VERSION ? params.protocolVersion : ACP_PROTOCOL_VERSION,\n agentCapabilities: {\n loadSession: true,\n promptCapabilities: promptCapabilitiesForProvider(provider.meta.capabilities),\n mcpCapabilities: mcpCapabilities(),\n sessionCapabilities: {\n list: {},\n delete: {},\n resume: {},\n close: {},\n additionalDirectories: {},\n },\n auth: {\n ...(this.options.logout ? { logout: {} } : {}),\n },\n },\n agentInfo: this.options.agentInfo ?? { name: 'zidane', title: 'Zidane ACP', version: ACP_AGENT_VERSION },\n authMethods: this.options.authMethods ?? [],\n }\n }\n\n private async authenticate(params: AuthenticateRequest): Promise<unknown> {\n if (!this.options.authenticate)\n return {}\n return await this.options.authenticate(params)\n }\n\n private async logout(): Promise<unknown> {\n if (!this.options.logout)\n return {}\n return await this.options.logout()\n }\n\n private async newSession(params: NewSessionRequest): Promise<unknown> {\n const runtime = await this.createRuntime(params)\n this.deferAvailableCommands(runtime.sessionId)\n return newSessionResponse(runtime.sessionId, this.modes, runtime.modeId, runtime.configOptions)\n }\n\n private async loadExistingSession(params: LoadSessionRequest): Promise<unknown> {\n const runtime = await this.createRuntime(params, params.sessionId, true)\n // ACP `session/load` replays the full history through `session/update`\n // notifications BEFORE the response resolves; the response itself only\n // carries mode/config state (no inline `messages`).\n await this.replayHistory(runtime)\n this.deferAvailableCommands(runtime.sessionId)\n return this.sessionStateResponse(runtime)\n }\n\n private async resumeSession(params: ResumeSessionRequest): Promise<unknown> {\n const runtime = await this.createRuntime({\n cwd: params.cwd,\n additionalDirectories: params.additionalDirectories,\n mcpServers: params.mcpServers ?? [],\n }, params.sessionId, true)\n // `session/resume` does not replay history (unlike `session/load`); it only\n // reports current mode state.\n this.deferAvailableCommands(runtime.sessionId)\n return this.sessionStateResponse(runtime)\n }\n\n private sessionStateResponse(runtime: AcpSessionRuntime): { modes: ReturnType<typeof makeModeState>, configOptions?: SessionConfigOption[] } {\n return {\n modes: makeModeState(this.modes, runtime.modeId),\n ...(runtime.configOptions.length > 0 ? { configOptions: runtime.configOptions } : {}),\n }\n }\n\n private deferAvailableCommands(sessionId: string): void {\n if (!this.options.commands || this.options.commands.length === 0)\n return\n setTimeout(() => {\n void this.sessionUpdate(sessionId, {\n sessionUpdate: 'available_commands_update',\n availableCommands: this.options.commands!,\n })\n }, 0)\n }\n\n private async replayHistory(runtime: AcpSessionRuntime): Promise<void> {\n for (const turn of runtime.session.turns) {\n const blocks = sessionBlocksToAcp(turn.content)\n if (blocks.length === 0)\n continue\n const sessionUpdate = turn.role === 'assistant' ? 'agent_message_chunk' : 'user_message_chunk'\n for (const content of blocks)\n await this.sessionUpdate(runtime.sessionId, { sessionUpdate, content })\n }\n }\n\n private async listSessions(params: ListSessionsRequest): Promise<unknown> {\n const store = this.options.store\n if (!store) {\n return {\n sessions: [...this.sessions.values()]\n .filter(runtime => !params.cwd || runtime.cwd === params.cwd)\n .map(runtime => sessionInfo(runtime)),\n nextCursor: null,\n }\n }\n\n const ids = await store.list({ limit: 100, ...(params.cwd ? { projectRoot: params.cwd } : {}) })\n const sessions: SessionInfo[] = []\n for (const id of ids) {\n const loaded = await store.load(id)\n if (!loaded)\n continue\n // `SessionInfo.cwd` is required and must be absolute; fall back to the\n // requested filter cwd, then the live runtime cwd. Skip sessions we\n // cannot attribute to a working directory rather than emit an invalid one.\n const cwd = loaded.projectRoot ?? params.cwd ?? this.sessions.get(loaded.id)?.cwd\n if (!cwd)\n continue\n sessions.push({\n sessionId: loaded.id,\n cwd,\n title: typeof loaded.metadata.title === 'string' ? loaded.metadata.title : null,\n updatedAt: new Date(loaded.updatedAt).toISOString(),\n })\n }\n return { sessions, nextCursor: null }\n }\n\n private async deleteSession(params: DeleteSessionRequest): Promise<unknown> {\n const runtime = this.sessions.get(params.sessionId)\n if (runtime) {\n runtime.abortController?.abort(new Error('ACP session deleted.'))\n await runtime.agent.destroy()\n this.sessions.delete(params.sessionId)\n }\n await this.options.store?.delete(params.sessionId)\n return {}\n }\n\n private async closeSession(params: { sessionId: string }): Promise<unknown> {\n const runtime = this.requireSession(params.sessionId)\n runtime.abortController?.abort(new Error('ACP session closed.'))\n await runtime.agent.destroy()\n this.sessions.delete(params.sessionId)\n return {}\n }\n\n private async prompt(params: PromptRequest): Promise<PromptResponse> {\n const runtime = this.requireSession(params.sessionId)\n if (runtime.inFlight)\n throw new AcpProtocolError(AcpErrorCode.InvalidRequest, `Session ${params.sessionId} already has an in-flight prompt.`)\n\n const mapped = acpPromptToPromptParts(params.prompt)\n const abortController = new AbortController()\n runtime.abortController = abortController\n const run = async (): Promise<PromptResponse> => {\n let stats: AgentStats | undefined\n let aborted = false\n try {\n for (const warning of mapped.warnings) {\n await this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'agent_thought_chunk',\n content: { type: 'text', text: warning },\n })\n }\n stats = await runtime.agent.run({\n prompt: mapped.prompt,\n ...(runtime.runModel ? { model: runtime.runModel } : {}),\n ...(this.options.system ? { system: this.options.system } : {}),\n signal: abortController.signal,\n })\n }\n catch (err) {\n aborted = abortController.signal.aborted\n if (!aborted)\n throw err\n }\n finally {\n runtime.abortController = undefined\n runtime.inFlight = undefined\n }\n\n return {\n stopReason: stopReasonFromRun({\n aborted: aborted || abortController.signal.aborted,\n turnUsage: stats?.turnUsage,\n maxTurnsReached: stats ? reachedMaxTurns(stats, this.options.behavior) : false,\n }),\n }\n }\n\n const inFlight = run()\n runtime.inFlight = inFlight\n return await inFlight\n }\n\n private cancel(params: CancelNotification): void {\n const runtime = this.sessions.get(params.sessionId)\n runtime?.abortController?.abort(new Error('Cancelled by ACP client.'))\n runtime?.agent.abort()\n }\n\n private async setMode(params: SetSessionModeRequest): Promise<unknown> {\n const runtime = this.requireSession(params.sessionId)\n if (!this.modes.some(mode => mode.id === params.modeId))\n throw new AcpProtocolError(AcpErrorCode.InvalidParams, `Unknown mode: ${params.modeId}`)\n runtime.modeId = params.modeId\n await this.sessionUpdate(params.sessionId, {\n sessionUpdate: 'current_mode_update',\n currentModeId: params.modeId,\n })\n return {}\n }\n\n private async setConfigOption(params: SetSessionConfigOptionRequest): Promise<unknown> {\n const runtime = this.requireSession(params.sessionId)\n const isModelSwitch = this.modelChoices.length > 0 && params.configId === MODEL_CONFIG_ID\n // A model switch rebinds the agent's provider; refuse mid-prompt so we never\n // swap the provider out from under an in-flight stream.\n if (isModelSwitch && runtime.inFlight)\n throw new AcpProtocolError(AcpErrorCode.InvalidRequest, 'Cannot switch model while a prompt is in flight.')\n const configOptions = this.applyConfigSelection(runtime, params.configId, params.value)\n if (isModelSwitch)\n this.selectModel(runtime, params.value)\n runtime.config.set(params.configId, params.value)\n await this.sessionUpdate(params.sessionId, {\n sessionUpdate: 'config_option_update',\n configOptions,\n })\n return { configOptions }\n }\n\n /**\n * Rebind a live session to the provider + model of the selected registry\n * choice. The agent is NOT rebuilt — only the router's delegate and the run\n * model change — so execution handles and background tasks survive a switch.\n */\n private selectModel(runtime: AcpSessionRuntime, choiceId: string): void {\n const choice = this.modelChoices.find(candidate => candidate.id === choiceId)\n if (!choice)\n throw new AcpProtocolError(AcpErrorCode.InvalidParams, `Unknown model: ${choiceId}`)\n runtime.setProviderDelegate?.(this.providerForChoiceId(choice.id))\n runtime.runModel = choice.model\n }\n\n /** Reflect a `select` choice back into the advertised option set's `currentValue`. */\n private applyConfigSelection(runtime: AcpSessionRuntime, configId: string, value: string): SessionConfigOption[] {\n const option = runtime.configOptions.find(candidate => candidate.id === configId)\n if (!option)\n throw new AcpProtocolError(AcpErrorCode.InvalidParams, `Unknown config option: ${configId}`)\n if (!configOptionHasValue(option, value))\n throw new AcpProtocolError(AcpErrorCode.InvalidParams, `Invalid value for config option ${configId}: ${value}`)\n runtime.configOptions = runtime.configOptions.map(candidate =>\n candidate.id === configId ? { ...candidate, currentValue: value } : candidate,\n )\n return runtime.configOptions\n }\n\n private async createRuntime(params: NewSessionRequest | LoadSessionRequest | ResumeSessionRequest, requestedSessionId?: string, mustExist = false): Promise<AcpSessionRuntime> {\n if (requestedSessionId) {\n const existing = this.sessions.get(requestedSessionId)\n if (existing) {\n if (existing.cwd !== params.cwd)\n throw new AcpProtocolError(AcpErrorCode.InvalidParams, `Session ${requestedSessionId} belongs to cwd ${existing.cwd}, not ${params.cwd}.`)\n const nextAdditionalDirectories = params.additionalDirectories ?? existing.additionalDirectories\n const nextMcpServers = params.mcpServers === undefined\n ? existing.mcpServers\n : acpMcpServersToZidane(params.mcpServers)\n if (!sameStringArray(existing.additionalDirectories, nextAdditionalDirectories)) {\n throw new AcpProtocolError(\n AcpErrorCode.InvalidParams,\n `Session ${requestedSessionId} is already active with different additionalDirectories; close it before resuming with changed roots.`,\n )\n }\n if (!sameJson(existing.mcpServers, nextMcpServers)) {\n throw new AcpProtocolError(\n AcpErrorCode.InvalidParams,\n `Session ${requestedSessionId} is already active with different MCP servers; close it before resuming with changed MCP configuration.`,\n )\n }\n return existing\n }\n }\n\n const mcpServers = acpMcpServersToZidane(params.mcpServers)\n const session = await this.resolveSession(requestedSessionId, params.cwd, mustExist)\n const execution = this.resolveExecution(params)\n // In model-registry mode, bind the agent to a per-session router so a later\n // `session/set_config_option` can swap the provider WITHOUT rebuilding the\n // agent (a rebuild would destroy the execution handle + background tasks).\n const initialChoiceId = this.defaultModelChoiceId\n const router = initialChoiceId !== undefined\n ? createProviderRouter(this.providerForChoiceId(initialChoiceId))\n : undefined\n const provider = router ? router.provider : this.resolveProvider()\n const runModel = initialChoiceId !== undefined\n ? this.modelChoices.find(choice => choice.id === initialChoiceId)!.model\n : this.options.model\n const sessionId = session.id\n const base = this.options.preset ?? basic\n const agentOptions = this.options.agentOptions ?? {}\n const tools = mergeTools(base.tools, agentOptions.tools, this.options.tools)\n const wrappedTools = wrapToolsForAcpClient(tools, {\n client: this.requirePeer(),\n sessionId,\n capabilities: this.clientCapabilities,\n useClientFileSystem: this.options.useClientFileSystem,\n useClientTerminal: this.options.useClientTerminal,\n })\n const behavior = { ...base.behavior, ...agentOptions.behavior, ...this.options.behavior }\n const agent = createAgent({\n ...base,\n ...agentOptions,\n provider,\n execution,\n session,\n tools: wrappedTools,\n behavior,\n mcpServers: mergeMcpServers(base.mcpServers, agentOptions.mcpServers, this.options.agentOptions?.mcpServers, mcpServers),\n ...(this.options.system ? { system: this.options.system } : {}),\n })\n\n const runtime: AcpSessionRuntime = {\n sessionId,\n cwd: params.cwd,\n additionalDirectories: params.additionalDirectories ?? [],\n mcpServers,\n session,\n execution,\n agent,\n provider,\n modeId: this.defaultModeId,\n configOptions: cloneConfigOptions(this.defaultConfigOptions),\n config: new Map(),\n ...(runModel !== undefined ? { runModel } : {}),\n ...(router ? { setProviderDelegate: router.setDelegate } : {}),\n }\n this.installHookAdapter(runtime)\n this.sessions.set(sessionId, runtime)\n session.setMeta('acp.cwd', params.cwd)\n session.setMeta('acp.additionalDirectories', params.additionalDirectories ?? [])\n if (session.store)\n await session.save().catch(() => undefined)\n return runtime\n }\n\n private async resolveSession(sessionId: string | undefined, cwd: string, mustExist: boolean): Promise<Session> {\n const store = this.options.store\n if (sessionId && this.sessions.has(sessionId))\n return this.sessions.get(sessionId)!.session\n if (sessionId && store) {\n const existing = await loadSession(store, sessionId)\n if (existing)\n return existing\n if (mustExist)\n throw new AcpProtocolError(AcpErrorCode.ResourceNotFound, `Unknown session: ${sessionId}`)\n const created = await createSession({ id: sessionId, store, projectRoot: cwd, metadata: { title: 'ACP session' } })\n await created.save()\n return created\n }\n if (sessionId && mustExist)\n throw new AcpProtocolError(AcpErrorCode.ResourceNotFound, `Unknown session: ${sessionId}`)\n const created = await createSession({ ...(sessionId ? { id: sessionId } : {}), ...(store ? { store } : {}), projectRoot: cwd, metadata: { title: 'ACP session' } })\n if (store)\n await created.save()\n return created\n }\n\n private resolveExecution(params: NewSessionRequest | LoadSessionRequest | ResumeSessionRequest) {\n if (typeof this.options.execution === 'function')\n return this.options.execution(params)\n return this.options.execution ?? createProcessContext({ cwd: params.cwd })\n }\n\n private resolveProvider(): Provider {\n // Registry mode: the default choice's provider backs initialization-time\n // reads (e.g. prompt capabilities). Per-session routing is handled in\n // `createRuntime`/`selectModel`.\n if (this.defaultModelChoiceId !== undefined)\n return this.providerForChoiceId(this.defaultModelChoiceId)\n const provider = this.options.provider\n if (provider === undefined)\n throw new AcpProtocolError(AcpErrorCode.InternalError, 'No provider configured.')\n return typeof provider === 'function' ? provider() : provider\n }\n\n private installHookAdapter(runtime: AcpSessionRuntime): void {\n const seenTools = new Set<string>()\n\n runtime.agent.hooks.hook('stream:text', ({ delta, turnId }) => {\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'agent_message_chunk',\n messageId: turnId,\n content: { type: 'text', text: delta },\n })\n })\n runtime.agent.hooks.hook('stream:thinking', ({ delta, turnId }) => {\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'agent_thought_chunk',\n messageId: turnId,\n content: { type: 'text', text: delta },\n })\n })\n runtime.agent.hooks.hook('tool:gate', async (ctx) => {\n if (!this.shouldRequestPermission(ctx.name, ctx.input))\n return\n const key = permissionKey(ctx.name, ctx.input)\n const cached = runtime.config.get(key)\n if (cached === 'allow')\n return\n if (cached === 'reject') {\n ctx.block = true\n ctx.reason = 'Rejected by prior ACP permission decision.'\n return\n }\n const outcome = await this.requestPermission(runtime, {\n toolCallId: ctx.callId,\n title: ctx.name,\n kind: toolKindForName(ctx.name),\n status: 'pending',\n rawInput: ctx.input,\n })\n if (outcome.outcome === 'cancelled') {\n ctx.block = true\n ctx.reason = 'Cancelled by ACP client.'\n return\n }\n if (outcome.optionId === 'allow_always')\n runtime.config.set(key, 'allow')\n if (outcome.optionId === 'reject_always')\n runtime.config.set(key, 'reject')\n if (outcome.optionId.startsWith('reject')) {\n ctx.block = true\n ctx.reason = 'Rejected by ACP client.'\n }\n })\n runtime.agent.hooks.hook('tool:dispatched', (ctx) => {\n seenTools.add(ctx.callId)\n const status = ctx.outcome === 'gate-block' || ctx.outcome === 'invalid-input' || ctx.outcome === 'unknown' ? 'failed' : 'pending'\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'tool_call',\n toolCallId: ctx.callId,\n title: ctx.name,\n kind: toolKindForName(ctx.name),\n status,\n rawInput: ctx.input,\n ...(status === 'failed' ? { rawOutput: ctx.reason ?? ctx.outcome } : {}),\n })\n })\n runtime.agent.hooks.hook('tool:before', (ctx) => {\n if (!seenTools.has(ctx.callId)) {\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'tool_call',\n toolCallId: ctx.callId,\n title: ctx.name,\n kind: toolKindForName(ctx.name),\n status: 'in_progress',\n rawInput: ctx.input,\n })\n return\n }\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'tool_call_update',\n toolCallId: ctx.callId,\n status: 'in_progress',\n })\n })\n runtime.agent.hooks.hook('tool:after', (ctx) => {\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'tool_call_update',\n toolCallId: ctx.callId,\n status: 'completed',\n content: toolResultToAcpContent(ctx.result),\n rawOutput: ctx.result,\n })\n })\n runtime.agent.hooks.hook('tool:error', (ctx) => {\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'tool_call_update',\n toolCallId: ctx.callId,\n status: 'failed',\n rawOutput: errorMessage(ctx.error),\n })\n })\n runtime.agent.hooks.hook('tool:cancelled', (ctx) => {\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'tool_call_update',\n toolCallId: ctx.callId,\n status: 'failed',\n rawOutput: ctx.reason ?? 'cancelled',\n })\n })\n runtime.agent.hooks.hook('turn:after', ({ usage, cumulativeUsage }) => {\n // ACP `usage_update.used` is \"tokens currently in context\" and must track\n // `size`. Report the latest turn's effective input (input + cache read +\n // cache creation) — NOT the run-cumulative total, which would climb past\n // the window across turns. `cost` stays cumulative per the ACP spec.\n // Emit only when a window size is resolvable (never fabricate `size`) and\n // when occupancy is known (skip 0-token placeholder/aborted turns so we\n // don't reset the client's context meter).\n const size = this.resolveContextWindow(runtime)\n if (size === undefined)\n return\n const used = effectiveInputFromTurn(usage)\n if (used <= 0)\n return\n const cost = usageCost(cumulativeUsage.cost)\n void this.sessionUpdate(runtime.sessionId, {\n sessionUpdate: 'usage_update',\n used,\n size,\n ...(cost ? { cost } : {}),\n })\n })\n }\n\n private resolveContextWindow(runtime: AcpSessionRuntime): number | undefined {\n if (typeof this.options.contextWindow === 'number' && this.options.contextWindow > 0)\n return this.options.contextWindow\n const fromBehavior = this.options.behavior?.autoCompact\n if (fromBehavior && typeof fromBehavior === 'object' && typeof fromBehavior.contextWindow === 'number' && fromBehavior.contextWindow > 0)\n return fromBehavior.contextWindow\n // Read the session's CURRENT provider (router-aware) so usage `size` tracks\n // the selected model's window after a `session/set_config_option` switch.\n const meta = runtime.provider.meta as { contextWindow?: unknown }\n if (typeof meta.contextWindow === 'number' && meta.contextWindow > 0)\n return meta.contextWindow\n return undefined\n }\n\n private shouldRequestPermission(name: string, input: Record<string, unknown>): boolean {\n const policy = this.options.permission\n if (policy?.enabled !== true || !this.peer)\n return false\n if (policy.toolMatcher)\n return policy.toolMatcher(name, input)\n return name === 'shell' || name === 'write_file' || name === 'edit' || name === 'multi_edit'\n }\n\n private async requestPermission(runtime: AcpSessionRuntime, toolCall: ToolCallUpdate): Promise<RequestPermissionOutcome> {\n const peer = this.requirePeer()\n const request = peer.sendRequest('session/request_permission', {\n sessionId: runtime.sessionId,\n toolCall,\n options: this.options.permission?.options ?? DEFAULT_PERMISSION_OPTIONS,\n }) as Promise<{ outcome?: RequestPermissionOutcome }>\n const aborted = new Promise<{ outcome: RequestPermissionOutcome }>((resolve) => {\n const signal = runtime.abortController?.signal\n if (!signal)\n return\n if (signal.aborted) {\n resolve({ outcome: { outcome: 'cancelled' } })\n return\n }\n signal.addEventListener('abort', () => resolve({ outcome: { outcome: 'cancelled' } }), { once: true })\n })\n const response = await Promise.race([request, aborted])\n return response.outcome ?? { outcome: 'cancelled' }\n }\n\n private async sessionUpdate(sessionId: string, update: SessionUpdate): Promise<void> {\n await this.notify('session/update', { sessionId, update })\n }\n\n private requireSession(sessionId: string): AcpSessionRuntime {\n const runtime = this.sessions.get(sessionId)\n if (!runtime)\n throw new AcpProtocolError(AcpErrorCode.ResourceNotFound, `Unknown session: ${sessionId}`)\n return runtime\n }\n\n private requirePeer(): AcpPeer {\n if (!this.peer) {\n return {\n sendNotification: () => undefined,\n sendRequest: () => Promise.reject(new AcpProtocolError(AcpErrorCode.MethodNotFound, 'No ACP client peer is attached.')),\n }\n }\n return this.peer\n }\n}\n\nexport class AcpProtocolError extends Error {\n constructor(readonly code: number, message: string, readonly data?: unknown) {\n super(message)\n this.name = 'AcpProtocolError'\n }\n}\n\n/**\n * A provider that forwards every call to a swappable delegate. Lets a session\n * change its underlying provider (and thus credentials) on a model switch\n * without rebuilding the agent — the loop reads `formatTools` / message builders\n * / `meta` / `stream` fresh each run, and switches only happen between prompts.\n */\nfunction createProviderRouter(initial: Provider): { provider: Provider, setDelegate: (provider: Provider) => void } {\n let delegate = initial\n const provider: Provider = {\n get name() { return delegate.name },\n get meta() { return delegate.meta },\n formatTools: tools => delegate.formatTools(tools),\n userMessage: content => delegate.userMessage(content),\n assistantMessage: content => delegate.assistantMessage(content),\n toolResultsMessage: results => delegate.toolResultsMessage(results),\n stream: (options, callbacks) => delegate.stream(options, callbacks),\n promptMessage: parts => routePromptMessage(delegate, parts),\n classifyError: err => (delegate.classifyError ? delegate.classifyError(err) : null),\n countTokens: (payload, signal) => (delegate.countTokens ? delegate.countTokens(payload, signal) : Promise.resolve(null)),\n }\n return { provider, setDelegate: (next) => { delegate = next } }\n}\n\nfunction routePromptMessage(delegate: Provider, parts: PromptPart[]) {\n if (delegate.promptMessage)\n return delegate.promptMessage(parts)\n return defaultPromptMessage(parts)\n}\n\nfunction mergeTools(...sources: Array<Record<string, ToolDef> | undefined>): Record<string, ToolDef> | undefined {\n const out: Record<string, ToolDef> = {}\n for (const source of sources) {\n if (source)\n Object.assign(out, source)\n }\n return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction mergeMcpServers(...sources: Array<readonly McpServerConfig[] | undefined>): McpServerConfig[] {\n const byName = new Map<string, McpServerConfig>()\n for (const source of sources) {\n for (const server of source ?? [])\n byName.set(server.name, server)\n }\n return [...byName.values()]\n}\n\nfunction cloneConfigOptions(options: readonly SessionConfigOption[]): SessionConfigOption[] {\n return options.map(option => ({\n ...option,\n options: option.options.map(item => 'group' in item\n ? { ...item, options: item.options.map(child => ({ ...child })) }\n : { ...item }) as SessionConfigOption['options'],\n }))\n}\n\nfunction configOptionHasValue(option: SessionConfigOption, value: string): boolean {\n for (const item of option.options) {\n if ('group' in item) {\n if (item.options.some(child => child.value === value))\n return true\n }\n else if (item.value === value) {\n return true\n }\n }\n return false\n}\n\nfunction sameStringArray(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index])\n}\n\nfunction sameJson(left: unknown, right: unknown): boolean {\n return stableStringify(left) === stableStringify(right)\n}\n\nfunction asObject<T>(value: unknown): T {\n if (!isObject(value))\n throw new AcpProtocolError(AcpErrorCode.InvalidParams, 'Expected object parameters.')\n return value as T\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction normalizeId(id: unknown) {\n return typeof id === 'string' || typeof id === 'number' || id === null ? id : null\n}\n\nfunction toRpcError(err: unknown): { code: number, message: string, data?: unknown } {\n if (err instanceof AcpProtocolError)\n return { code: err.code, message: err.message, ...(err.data !== undefined ? { data: err.data } : {}) }\n return { code: AcpErrorCode.InternalError, message: err instanceof Error ? err.message : String(err) }\n}\n\nfunction sessionInfo(runtime: AcpSessionRuntime): SessionInfo {\n return {\n sessionId: runtime.sessionId,\n cwd: runtime.cwd,\n additionalDirectories: runtime.additionalDirectories,\n title: typeof runtime.session.metadata.title === 'string' ? runtime.session.metadata.title : null,\n updatedAt: new Date().toISOString(),\n }\n}\n\nfunction permissionKey(name: string, input: Record<string, unknown>): string {\n return `permission:${name}:${stableStringify(input)}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (!isObject(value))\n return JSON.stringify(value)\n const keys = Object.keys(value).sort()\n const out: Record<string, unknown> = {}\n for (const key of keys)\n out[key] = value[key]\n return JSON.stringify(out)\n}\n\nfunction reachedMaxTurns(stats: AgentStats, behavior: AgentOptions['behavior'] | undefined): boolean {\n const maxTurns = behavior?.maxTurns\n return typeof maxTurns === 'number' && stats.turns >= maxTurns && lastFinishReason(stats.turnUsage) !== 'length'\n}\n\nfunction lastFinishReason(turnUsage: TurnUsage[] | undefined) {\n for (let i = (turnUsage?.length ?? 0) - 1; i >= 0; i--) {\n const reason = turnUsage?.[i]?.finishReason\n if (reason)\n return reason\n }\n return undefined\n}\n","import type { Readable, Writable } from 'node:stream'\nimport type { AcpServerOptions } from './types'\nimport { createJsonRpcConnection } from './json-rpc'\nimport { createAcpServer } from './server'\n\nexport { wrapToolsForAcpClient } from './client-tools'\nexport type { AcpClientToolOptions } from './client-tools'\nexport { createJsonRpcConnection, JsonRpcRemoteError } from './json-rpc'\nexport type { JsonRpcConnection, JsonRpcConnectionOptions } from './json-rpc'\nexport { acpMcpServersToZidane, acpPromptToPromptParts, sessionBlocksToAcp, stopReasonFromRun, toolResultToAcpContent } from './mapping'\nexport { AcpProtocolError, createAcpServer } from './server'\nexport type { AcpServer } from './server'\nexport type * from './types'\n\nexport interface RunAcpStdioServerOptions extends AcpServerOptions {\n input?: Readable\n output?: Writable\n framing?: 'content-length' | 'newline'\n onError?: (error: Error) => void\n}\n\nexport function runAcpStdioServer(options: RunAcpStdioServerOptions) {\n const server = createAcpServer(options)\n const connection = createJsonRpcConnection({\n input: options.input ?? process.stdin,\n output: options.output ?? process.stdout,\n framing: options.framing,\n onError: options.onError,\n onRequest: message => server.handleMessage(message),\n onNotification: async (message) => {\n await server.handleMessage(message)\n },\n })\n server.setPeer(connection)\n connection.start()\n return {\n server,\n connection,\n async close() {\n connection.close()\n await server.close()\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,SAAgB,wBAAwB,SAAsD;CAC5F,IAAI,SAAS;CACb,IAAI,SAAS;CACb,IAAI,SAAkC,OAAO,MAAM,CAAC;CACpD,MAAM,0BAAU,IAAI,IAA+B;CAEnD,MAAM,gBAAgB,YAAkC;EACtD,IAAI,QACF;EACF,MAAM,OAAO,KAAK,UAAU;GAAE,GAAG;GAAS,SAAS;EAAM,CAAC;EAK1D,IAAI,QAAQ,YAAY,kBAAkB;GACxC,MAAM,QAAQ,OAAO,WAAW,IAAI;GACpC,QAAQ,OAAO,MAAM,mBAAmB,MAAM,UAAU,MAAM;GAC9D;EACF;EACA,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG;CAClC;CAEA,MAAM,eAAe,OAAO,YAAoC;EAC9D,IAAI,CAACA,WAAS,OAAO,GAAG;GACtB,aAAa,cAAc,MAAA,QAAmC,2BAA2B,CAAC;GAC1F;EACF;EAEA,MAAM,MAAM;EACZ,IAAI,QAAQ,QAAQ,YAAY,OAAO,WAAW,MAAM;GACtD,MAAM,UAAU,QAAQ,IAAI,IAAI,EAAE;GAClC,IAAI,CAAC,SACH;GACF,QAAQ,OAAO,IAAI,EAAE;GACrB,IAAI,WAAW,OAAO,IAAI,OACxB,QAAQ,OAAO,IAAI,mBAAmB,IAAI,MAAM,SAAS,IAAI,MAAM,MAAM,IAAI,MAAM,IAAI,CAAC;QAGxF,QAAQ,Q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