@zvada/agent-server 0.3.27 → 0.3.30

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.
Files changed (190) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +6 -4
  3. package/dist/core/agents/acp/account.js +111 -0
  4. package/dist/core/agents/acp/acp-agent.js +249 -158
  5. package/dist/core/agents/acp/adapter.js +103 -34
  6. package/dist/core/agents/acp/client.js +169 -42
  7. package/dist/core/agents/acp/known-agents.js +12 -5
  8. package/dist/core/agents/acp/mappings.js +84 -20
  9. package/dist/core/agents/acp/models.js +59 -0
  10. package/dist/core/agents/acp/profile.js +36 -0
  11. package/dist/core/agents/acp/prompts.js +248 -0
  12. package/dist/core/agents/acp/requests.js +4 -4
  13. package/dist/core/agents/claude-code/claude-agent.js +2 -12
  14. package/dist/core/agents/claude-code/login.js +4 -1
  15. package/dist/core/agents/claude-code/session.js +50 -18
  16. package/dist/core/agents/claude-code/spawn.js +0 -26
  17. package/dist/core/agents/claude-code/turn.js +6 -2
  18. package/dist/core/agents/codex-app-server/client.js +12 -13
  19. package/dist/core/agents/codex-app-server/login.js +4 -1
  20. package/dist/core/agents/gemini/failures.js +133 -0
  21. package/dist/core/agents/gemini/login.js +173 -0
  22. package/dist/core/agents/gemini/profile.js +138 -0
  23. package/dist/core/agents/gemini/tools.js +91 -0
  24. package/dist/core/agents/login.js +8 -6
  25. package/dist/core/agents/stderr-tail.js +5 -2
  26. package/dist/core/presets.js +13 -0
  27. package/dist/core/processes/native-processes.js +23 -1
  28. package/dist/core/provision/install-build.js +70 -26
  29. package/dist/core/provision/pins.js +5 -0
  30. package/dist/core/provision/provisioner.js +39 -16
  31. package/dist/core/provision/releases.js +39 -1
  32. package/dist/core/provision/tools.js +87 -28
  33. package/dist/operator/errors.js +2 -2
  34. package/dist/operator/operator.js +201 -90
  35. package/dist/operator/render.js +34 -28
  36. package/dist/operator/session-tools.js +2 -1
  37. package/dist/protocol/account.js +5 -1
  38. package/dist/protocol/auth.js +5 -1
  39. package/dist/protocol/config.js +4 -2
  40. package/dist/protocol/credentials.js +9 -1
  41. package/dist/protocol/harness.js +9 -1
  42. package/dist/protocol/part-input.js +2 -6
  43. package/dist/protocol/text-parts.js +10 -0
  44. package/dist/server/bin.js +22 -7
  45. package/dist/server/install.js +6 -4
  46. package/dist/types/core/agents/acp/account.d.ts +55 -0
  47. package/dist/types/core/agents/acp/account.d.ts.map +1 -0
  48. package/dist/types/core/agents/acp/acp-agent.d.ts +65 -36
  49. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  50. package/dist/types/core/agents/acp/adapter.d.ts +28 -3
  51. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  52. package/dist/types/core/agents/acp/client.d.ts +66 -4
  53. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  54. package/dist/types/core/agents/acp/known-agents.d.ts +4 -2
  55. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -1
  56. package/dist/types/core/agents/acp/mappings.d.ts +53 -7
  57. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  58. package/dist/types/core/agents/acp/models.d.ts +22 -0
  59. package/dist/types/core/agents/acp/models.d.ts.map +1 -0
  60. package/dist/types/core/agents/acp/profile.d.ts +97 -0
  61. package/dist/types/core/agents/acp/profile.d.ts.map +1 -0
  62. package/dist/types/core/agents/acp/prompts.d.ts +108 -0
  63. package/dist/types/core/agents/acp/prompts.d.ts.map +1 -0
  64. package/dist/types/core/agents/acp/requests.d.ts +7 -1
  65. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  66. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -2
  67. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  68. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  69. package/dist/types/core/agents/claude-code/options.d.ts +1 -1
  70. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  71. package/dist/types/core/agents/claude-code/session.d.ts +7 -6
  72. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  73. package/dist/types/core/agents/claude-code/spawn.d.ts +0 -8
  74. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -1
  75. package/dist/types/core/agents/claude-code/turn.d.ts +3 -2
  76. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  77. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  78. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  79. package/dist/types/core/agents/gemini/failures.d.ts +25 -0
  80. package/dist/types/core/agents/gemini/failures.d.ts.map +1 -0
  81. package/dist/types/core/agents/gemini/login.d.ts +28 -0
  82. package/dist/types/core/agents/gemini/login.d.ts.map +1 -0
  83. package/dist/types/core/agents/gemini/profile.d.ts +30 -0
  84. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -0
  85. package/dist/types/core/agents/gemini/tools.d.ts +18 -0
  86. package/dist/types/core/agents/gemini/tools.d.ts.map +1 -0
  87. package/dist/types/core/agents/login.d.ts +15 -5
  88. package/dist/types/core/agents/login.d.ts.map +1 -1
  89. package/dist/types/core/agents/stderr-tail.d.ts +1 -1
  90. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -1
  91. package/dist/types/core/presets.d.ts +2 -2
  92. package/dist/types/core/presets.d.ts.map +1 -1
  93. package/dist/types/core/processes/native-processes.d.ts +6 -0
  94. package/dist/types/core/processes/native-processes.d.ts.map +1 -1
  95. package/dist/types/core/provision/checksums.d.ts +7 -1
  96. package/dist/types/core/provision/checksums.d.ts.map +1 -1
  97. package/dist/types/core/provision/install-build.d.ts +32 -6
  98. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  99. package/dist/types/core/provision/pins.d.ts +4 -0
  100. package/dist/types/core/provision/pins.d.ts.map +1 -1
  101. package/dist/types/core/provision/provisioner.d.ts +18 -7
  102. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  103. package/dist/types/core/provision/releases.d.ts +2 -1
  104. package/dist/types/core/provision/releases.d.ts.map +1 -1
  105. package/dist/types/core/provision/tools.d.ts +36 -7
  106. package/dist/types/core/provision/tools.d.ts.map +1 -1
  107. package/dist/types/operator/errors.d.ts +5 -1
  108. package/dist/types/operator/errors.d.ts.map +1 -1
  109. package/dist/types/operator/operator.d.ts.map +1 -1
  110. package/dist/types/operator/render.d.ts +11 -6
  111. package/dist/types/operator/render.d.ts.map +1 -1
  112. package/dist/types/operator/session-tools.d.ts.map +1 -1
  113. package/dist/types/operator/types.d.ts +5 -4
  114. package/dist/types/operator/types.d.ts.map +1 -1
  115. package/dist/types/protocol/account.d.ts +4 -2
  116. package/dist/types/protocol/account.d.ts.map +1 -1
  117. package/dist/types/protocol/auth.d.ts +10 -7
  118. package/dist/types/protocol/auth.d.ts.map +1 -1
  119. package/dist/types/protocol/clis.d.ts +4 -3
  120. package/dist/types/protocol/clis.d.ts.map +1 -1
  121. package/dist/types/protocol/config.d.ts +6 -2
  122. package/dist/types/protocol/config.d.ts.map +1 -1
  123. package/dist/types/protocol/conversation.d.ts +3 -3
  124. package/dist/types/protocol/credentials.d.ts +8 -0
  125. package/dist/types/protocol/credentials.d.ts.map +1 -1
  126. package/dist/types/protocol/execution.d.ts +1 -1
  127. package/dist/types/protocol/harness.d.ts +5 -2
  128. package/dist/types/protocol/harness.d.ts.map +1 -1
  129. package/dist/types/protocol/lifecycle.d.ts +8 -8
  130. package/dist/types/protocol/models.d.ts +3 -0
  131. package/dist/types/protocol/models.d.ts.map +1 -1
  132. package/dist/types/protocol/part-input.d.ts.map +1 -1
  133. package/dist/types/protocol/text-parts.d.ts +10 -0
  134. package/dist/types/protocol/text-parts.d.ts.map +1 -0
  135. package/dist/types/protocol/wire-api.d.ts +39 -29
  136. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  137. package/dist/types/protocol/wire.d.ts +13 -10
  138. package/dist/types/protocol/wire.d.ts.map +1 -1
  139. package/dist/types/server/install.d.ts +2 -1
  140. package/dist/types/server/install.d.ts.map +1 -1
  141. package/docs/consuming.md +8 -1
  142. package/docs/deploy.md +17 -8
  143. package/docs/harnesses.md +173 -44
  144. package/package.json +1 -1
  145. package/src/core/agents/acp/account.ts +158 -0
  146. package/src/core/agents/acp/acp-agent.ts +290 -178
  147. package/src/core/agents/acp/adapter.ts +126 -35
  148. package/src/core/agents/acp/client.ts +196 -49
  149. package/src/core/agents/acp/known-agents.ts +14 -5
  150. package/src/core/agents/acp/mappings.ts +112 -21
  151. package/src/core/agents/acp/models.ts +72 -0
  152. package/src/core/agents/acp/profile.ts +133 -0
  153. package/src/core/agents/acp/prompts.ts +287 -0
  154. package/src/core/agents/acp/requests.ts +16 -9
  155. package/src/core/agents/claude-code/claude-agent.ts +2 -13
  156. package/src/core/agents/claude-code/login.ts +4 -1
  157. package/src/core/agents/claude-code/options.ts +1 -1
  158. package/src/core/agents/claude-code/session.ts +50 -16
  159. package/src/core/agents/claude-code/spawn.ts +0 -26
  160. package/src/core/agents/claude-code/turn.ts +7 -2
  161. package/src/core/agents/codex-app-server/client.ts +11 -18
  162. package/src/core/agents/codex-app-server/login.ts +4 -5
  163. package/src/core/agents/gemini/failures.ts +148 -0
  164. package/src/core/agents/gemini/login.ts +188 -0
  165. package/src/core/agents/gemini/profile.ts +163 -0
  166. package/src/core/agents/gemini/tools.ts +99 -0
  167. package/src/core/agents/login.ts +14 -8
  168. package/src/core/agents/stderr-tail.ts +5 -2
  169. package/src/core/presets.ts +15 -2
  170. package/src/core/processes/native-processes.ts +32 -1
  171. package/src/core/provision/checksums.ts +12 -2
  172. package/src/core/provision/install-build.ts +122 -55
  173. package/src/core/provision/pins.ts +5 -0
  174. package/src/core/provision/provisioner.ts +62 -27
  175. package/src/core/provision/releases.ts +47 -1
  176. package/src/core/provision/tools.ts +124 -31
  177. package/src/operator/errors.ts +5 -2
  178. package/src/operator/operator.ts +208 -91
  179. package/src/operator/render.ts +61 -33
  180. package/src/operator/session-tools.ts +2 -1
  181. package/src/operator/types.ts +5 -4
  182. package/src/protocol/account.ts +5 -2
  183. package/src/protocol/auth.ts +5 -1
  184. package/src/protocol/config.ts +4 -2
  185. package/src/protocol/credentials.ts +11 -2
  186. package/src/protocol/harness.ts +9 -1
  187. package/src/protocol/part-input.ts +2 -5
  188. package/src/protocol/text-parts.ts +10 -0
  189. package/src/server/bin.ts +20 -6
  190. package/src/server/install.ts +6 -3
@@ -1,21 +1,31 @@
1
1
  import type {
2
2
  InitializeResponse,
3
- PromptRequest,
4
3
  SessionConfigOption,
5
4
  SessionModeState,
6
5
  } from "@agentclientprotocol/sdk";
7
6
  import type {
8
7
  AgentCapabilities,
8
+ AgentHarness,
9
9
  AgentInput,
10
10
  McpServerConfig,
11
+ ModelDescriptor,
11
12
  PermissionMode,
12
13
  RunConfig,
13
14
  } from "../../../protocol/index.ts";
14
- import { AsyncQueue } from "../../../protocol/index.ts";
15
+ import { AsyncQueue, clampThinkingLevel } from "../../../protocol/index.ts";
15
16
  import { type NativeProcesses, sharedNativeProcesses } from "../../processes/native-processes.ts";
16
17
  import { onAbort, untilAborted } from "../../utils/deadline.ts";
17
- import { McpUnavailableError, SessionResumeError } from "../../utils/errors.ts";
18
- import type { AgentExecuteOptions, RawAgentEvent } from "../base.ts";
18
+ import {
19
+ InvalidRequestError,
20
+ McpUnavailableError,
21
+ SessionResumeError,
22
+ } from "../../utils/errors.ts";
23
+ import type {
24
+ AgentExecuteOptions,
25
+ AppliedExecution,
26
+ ListModelsOptions,
27
+ RawAgentEvent,
28
+ } from "../base.ts";
19
29
  import { configFingerprint } from "../config-fingerprint.ts";
20
30
  import {
21
31
  type HostLease,
@@ -25,17 +35,38 @@ import {
25
35
  loopbackDirect,
26
36
  refuseHostName,
27
37
  } from "../host-tools.ts";
38
+ import type { CliLogin } from "../login.ts";
28
39
  import { IDLE_TIMEOUT_MS, ProcessPool } from "../process-pool.ts";
29
40
  import { SessionAgent } from "../session-agent.ts";
41
+ import {
42
+ AcpAccount,
43
+ type AcpStart,
44
+ SESSION_REQUEST_TIMEOUT_MS,
45
+ initialize,
46
+ launchOf,
47
+ startClient,
48
+ } from "./account.ts";
30
49
  import { type AcpRawEvent, CANCELLED_PROMPT_RESULT } from "./adapter.ts";
31
- import { AcpClient, type AcpClientOptions, type AcpLaunch } from "./client.ts";
50
+ import type { AcpClient, AcpClientOptions, AcpLaunch } from "./client.ts";
32
51
  import {
33
52
  type AcpPromptCapabilities,
34
- permissionModeOf,
53
+ type SelectOption,
54
+ modeNames,
55
+ refuseFiles,
56
+ selectOf,
57
+ selectableValues,
35
58
  toAcpMcpServers,
36
59
  toPromptBlocks,
37
60
  } from "./mappings.ts";
38
- import { type TurnScope, answerElicitation, answerPermission } from "./requests.ts";
61
+ import { defaultModel, listAcpModels } from "./models.ts";
62
+ import { type AcpProfile, genericAcpProfile } from "./profile.ts";
63
+ import { TurnPrompts } from "./prompts.ts";
64
+ import {
65
+ type RequestScope,
66
+ type TurnScope,
67
+ answerElicitation,
68
+ answerPermission,
69
+ } from "./requests.ts";
39
70
 
40
71
  /**
41
72
  * What a session's agent process was started with, as one key: a change to
@@ -69,7 +100,12 @@ function spawnKey(
69
100
  host: string | undefined,
70
101
  ): string {
71
102
  return configFingerprint({
72
- launch: { command: launch.command, args: launch.args ?? [], env: launch.env ?? {} },
103
+ launch: {
104
+ command: launch.command,
105
+ args: launch.args ?? [],
106
+ env: launch.env ?? {},
107
+ fixedEnv: launch.fixedEnv ?? {},
108
+ },
73
109
  cwd: options.cwd,
74
110
  env: options.env,
75
111
  // @ref LLP 0018#acp — only what the agent is given
@@ -81,42 +117,6 @@ function spawnKey(
81
117
  });
82
118
  }
83
119
 
84
- const CAPABILITIES: AgentCapabilities = {
85
- multiTurn: true,
86
- // A requested resume fails if the target agent cannot load saved sessions.
87
- sessionResume: true,
88
- // v1 has no portable model parameter. A requested model or thinking level
89
- // is applied only when the agent offers a `model` / `thought_level` config
90
- // option, so neither is promised here.
91
- modelSwitch: "unsupported",
92
- thinkingLevels: false,
93
- // The most an agent can take: its `initialize` decides, image data with its
94
- // `image` prompt capability and files beyond text with `embeddedContext`.
95
- images: true,
96
- files: ["text", "pdf", "binary"],
97
- mcpServers: true,
98
- permissionRequests: true,
99
- // The answer is an option id.
100
- rejectionMessages: false,
101
- ignoredSettings: [
102
- // ACP v1 has no system prompt: session/new takes the folder, the MCP
103
- // servers and the extra directories only (`resolveSession`).
104
- "systemPromptAppend",
105
- // A prompt runs until the agent ends it: ACP v1 has no turn limit.
106
- "maxTurns",
107
- // session/resume and session/load name a session, not a message in it.
108
- "resumeSessionAt",
109
- // The agent's credentials are its launch command's: the client gets the
110
- // launch, the folder and the env only (`AcpClientOptions`).
111
- "apiKey",
112
- // ACP v1 cannot ask an agent to run without its tools.
113
- "disableTools",
114
- ] satisfies Array<keyof RunConfig>,
115
- };
116
-
117
- /** ACP protocol major version this harness speaks. */
118
- const PROTOCOL_VERSION = 1;
119
-
120
120
  /**
121
121
  * How long a cancelled prompt may take to end before the agent is ended,
122
122
  * unless `cancelGraceMs` says otherwise: an agent that can neither resume nor
@@ -124,12 +124,6 @@ const PROTOCOL_VERSION = 1;
124
124
  */
125
125
  const CANCEL_GRACE_MS = 10_000;
126
126
 
127
- /** Deadline for `initialize` on a freshly spawned agent (mirrors codex startup). */
128
- const INITIALIZE_TIMEOUT_MS = 15_000;
129
-
130
- /** Deadline for session lifecycle requests (`session/new`, `session/resume`). */
131
- const SESSION_REQUEST_TIMEOUT_MS = 30_000;
132
-
133
127
  export interface AcpAgentOptions {
134
128
  /**
135
129
  * Resolve the ACP agent subprocess to launch. Operator-level only — never
@@ -171,7 +165,7 @@ export interface AcpAgentOptions {
171
165
  hostTools?: HostTools;
172
166
  }
173
167
 
174
- interface AcpSession {
168
+ interface AcpSession extends RequestScope {
175
169
  client: AcpClient;
176
170
  acpSessionId: string;
177
171
  /** What its agent process was started with (`spawnKey`). */
@@ -186,8 +180,12 @@ interface AcpSession {
186
180
  configOptions: SessionConfigOption[];
187
181
  /** The agent's modes, kept current by `current_mode_update`; absent when it offers none. */
188
182
  modes?: SessionModeState;
183
+ /** For a profile that lists models: the one a turn naming none runs, as the session opened on it. */
184
+ defaultModel?: string;
189
185
  /** From `initialize`: what the agent's prompts accept beyond text and links. */
190
186
  prompt: AcpPromptCapabilities;
187
+ /** The MCP servers the agent was given, by name: what tells a call's server from its tool. */
188
+ servers: string[];
191
189
  turn?: TurnScope;
192
190
  }
193
191
 
@@ -210,33 +208,81 @@ function failureMessage(error: unknown): string {
210
208
  return `${error}: ${detail}`;
211
209
  }
212
210
 
213
- /** Every value a select option offers, whether listed flat or in groups. */
214
- function selectableValues(option: SessionConfigOption & { type: "select" }): string[] {
215
- return option.options.flatMap((entry) =>
216
- "options" in entry ? entry.options.map((nested) => nested.value) : [entry.value],
211
+ /** Set an option to `value` unless it holds it; the answer carries every option as it now stands. */
212
+ async function select(session: AcpSession, option: SelectOption, value: string): Promise<void> {
213
+ if (option.currentValue === value) return;
214
+ const updated = await session.client.request(
215
+ "session/set_config_option",
216
+ { sessionId: session.acpSessionId, configId: option.id, value },
217
+ SESSION_REQUEST_TIMEOUT_MS,
217
218
  );
219
+ session.configOptions = updated.configOptions;
218
220
  }
219
221
 
220
222
  /**
221
- * ACP harness: drives any Agent Client Protocol v1 agent as a long-lived
222
- * subprocess (one per logical session, reused across turns). The launch
223
- * command comes from the operator's `resolveLaunch`; `initialize` negotiates
224
- * the protocol version and gates optional features (resume, images) on the
225
- * agent's advertised capabilities. The turn's stopReason arrives as the
223
+ * What the agent's options say the turn runs, where it has them: what it ran,
224
+ * not what was asked (a level the model lacks was fitted, or left alone).
225
+ */
226
+ function selected(session: AcpSession): AppliedExecution {
227
+ const model = selectOf(session.configOptions, "model")?.currentValue;
228
+ const thinkingLevel = selectOf(session.configOptions, "thought_level")?.currentValue;
229
+ return { ...(model && { model }), ...(thinkingLevel && { thinkingLevel }) };
230
+ }
231
+
232
+ // @ref LLP 0016.000#an-acp-agents-profile — a profile reaches the agent only through its harness's registration
233
+ /**
234
+ * An ACP agent running a profile: drives an Agent Client Protocol v1 agent
235
+ * as a long-lived subprocess (one per logical session, reused across turns).
236
+ * What is one agent's own, its name, its launch command and where it departs
237
+ * from its `initialize`, is its profile; `initialize` negotiates the protocol
238
+ * version and gates optional features (resume, images) on the agent's
239
+ * advertised capabilities. The turn's stopReason arrives as the
226
240
  * `session/prompt` *response*, so `execute` re-injects it into the raw stream
227
- * as a synthetic `session/prompt_result` event for the adapter.
241
+ * as a synthetic `session/prompt_result` event for the adapter. Internal to
242
+ * the engine: a harness that is a profile constructs it in its registration
243
+ * (`geminiHarness`); `AcpAgent` is the `acp` harness.
228
244
  */
229
- export class AcpAgent extends SessionAgent {
230
- readonly harness = "acp" as const;
231
- readonly capabilities = CAPABILITIES;
245
+ export class ProfiledAcpAgent extends SessionAgent {
246
+ readonly harness: AgentHarness;
247
+ readonly capabilities: AgentCapabilities;
248
+ readonly login?: CliLogin;
249
+ /** Present when its profile lists models: what the agent offers this login. */
250
+ readonly listModels?: (options: ListModelsOptions) => Promise<ModelDescriptor[]>;
232
251
  /** Its CLIs start here: the runtime's, or this OS process's own when it was made without one. */
233
252
  readonly processes: NativeProcesses;
253
+ private readonly profile: AcpProfile;
234
254
  private readonly sessions: ProcessPool<AcpSession, AcpPoolTurn>;
235
255
  private readonly host?: HostToolSessions;
256
+ /** How its agents start: its profile's, on its processes. */
257
+ private readonly starts: AcpStart;
258
+ /** The agent with no turn: its account, for the login and the model list. */
259
+ private readonly account: AcpAccount;
260
+ /** What each session's conversation was started with, when this agent started it (`newSession`). */
261
+ private readonly startedWith = new Map<string, { conversation: string; meta: string }>();
236
262
 
237
- constructor(private readonly agentOptions: AcpAgentOptions) {
263
+ constructor(
264
+ profile: AcpProfile,
265
+ private readonly agentOptions: Omit<AcpAgentOptions, "resolveLaunch">,
266
+ ) {
238
267
  super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
268
+ this.profile = profile;
269
+ this.harness = this.profile.harness;
270
+ this.capabilities = this.profile.capabilities;
239
271
  this.processes = agentOptions.processes ?? sharedNativeProcesses();
272
+ const { clientName, clientVersion, createClient } = agentOptions;
273
+ this.starts = {
274
+ profile: this.profile,
275
+ processes: this.processes,
276
+ clientName,
277
+ clientVersion,
278
+ createClient,
279
+ };
280
+ this.account = new AcpAccount(this.starts);
281
+ this.login = this.profile.login?.(this.account);
282
+ const models = this.profile.models;
283
+ if (models)
284
+ this.listModels = (listing) =>
285
+ listAcpModels(this.account, this.harness, (value) => models.offers(value), listing);
240
286
  this.host = hostToolSessions(agentOptions.hostTools, this.harness, {
241
287
  // @ref LLP 0018#acp — the engine's mode: the turn's, moved only by a plan the broker approved
242
288
  // The agent's own `current_mode_update` never raises it.
@@ -272,15 +318,10 @@ export class AcpAgent extends SessionAgent {
272
318
  options: AgentExecuteOptions,
273
319
  signal: AbortSignal,
274
320
  ): Promise<AcpSession> {
275
- signal.throwIfAborted();
276
321
  // A cancel ends the wait: the operator's resolution goes on for the next turn.
277
- const launch = await untilAborted(Promise.resolve(this.agentOptions.resolveLaunch()), signal);
278
- signal.throwIfAborted();
279
- if (!launch) {
280
- throw new Error(
281
- "acp harness is not configured: resolveLaunch returned no agent launch command",
282
- );
283
- }
322
+ const base = await launchOf(this.profile, signal);
323
+ const modeArgs = this.profile.modeArgs?.[options.permissionMode ?? "default"];
324
+ const launch = modeArgs ? { ...base, args: [...(base.args ?? []), ...modeArgs] } : base;
284
325
 
285
326
  const host = await untilAborted(
286
327
  Promise.resolve(this.host?.lease(options.sessionId, options.cwd)),
@@ -337,24 +378,26 @@ export class AcpAgent extends SessionAgent {
337
378
  signal: AbortSignal,
338
379
  ): Promise<AcpSession> {
339
380
  const resumeTarget = options.resumeSessionId;
340
- const clientOptions: AcpClientOptions = {
381
+ const client = await startClient(this.starts, {
341
382
  launch,
342
383
  cwd: options.cwd,
343
384
  // @ref LLP 0018#acp — the bearer never travels through a proxy
344
- // In the client's own order: the engine's environment, the launch's, the turn's.
385
+ // In the client's own order: the engine's environment, the launch's, the turn's, the launch's fixed.
345
386
  env: this.host
346
387
  ? {
347
388
  ...options.env,
348
- ...loopbackDirect({ ...process.env, ...launch.env, ...options.env }),
389
+ ...loopbackDirect({
390
+ ...process.env,
391
+ ...launch.env,
392
+ ...options.env,
393
+ ...launch.fixedEnv,
394
+ }),
349
395
  }
350
396
  : options.env,
351
- clientName: this.agentOptions.clientName,
352
397
  sessionId: options.sessionId,
353
- processes: this.processes,
354
- };
355
- const client = this.agentOptions.createClient
356
- ? await this.agentOptions.createClient(clientOptions)
357
- : await AcpClient.create(clientOptions);
398
+ // What the agent asks gates the steers sent as prompts (`TurnPrompts`).
399
+ watchRequests: this.capabilities.steering === true,
400
+ });
358
401
  own(client);
359
402
  // Closed at once when the turn was cancelled meanwhile.
360
403
  const offAbort = onAbort(signal, () => client.close());
@@ -362,20 +405,7 @@ export class AcpAgent extends SessionAgent {
362
405
  let acpSessionId: string | undefined;
363
406
  try {
364
407
  signal.throwIfAborted();
365
- init = await client.request(
366
- "initialize",
367
- {
368
- protocolVersion: PROTOCOL_VERSION,
369
- // The engine brokers the agent's requests for input, form or URL;
370
- // a turn whose client cannot answer declines them.
371
- clientCapabilities: { elicitation: { form: {}, url: {} } },
372
- clientInfo: {
373
- name: this.agentOptions.clientName ?? "agent-server",
374
- version: this.agentOptions.clientVersion ?? "0.0.0",
375
- },
376
- },
377
- INITIALIZE_TIMEOUT_MS,
378
- );
408
+ init = await initialize(client, this.starts);
379
409
  signal.throwIfAborted();
380
410
  const capabilities = init.agentCapabilities;
381
411
  const takesDirectories = Boolean(capabilities?.sessionCapabilities?.additionalDirectories);
@@ -387,7 +417,7 @@ export class AcpAgent extends SessionAgent {
387
417
  const given = await this.serversFor(
388
418
  options,
389
419
  host,
390
- Boolean(capabilities?.mcpCapabilities?.http),
420
+ this.profile.httpMcp || Boolean(capabilities?.mcpCapabilities?.http),
391
421
  );
392
422
  const target = {
393
423
  cwd: options.cwd,
@@ -423,14 +453,26 @@ export class AcpAgent extends SessionAgent {
423
453
  configOptions = resumed?.configOptions;
424
454
  modes = resumed?.modes;
425
455
  } else {
426
- const created = await client.request("session/new", target, SESSION_REQUEST_TIMEOUT_MS);
456
+ const meta = this.profile.newSession?.meta(options);
457
+ const created = await client.request(
458
+ "session/new",
459
+ { ...target, ...(meta && { _meta: meta }) },
460
+ SESSION_REQUEST_TIMEOUT_MS,
461
+ );
427
462
  acpSessionId = created.sessionId;
463
+ if (this.profile.newSession)
464
+ this.startedWith.set(options.sessionId, {
465
+ conversation: created.sessionId,
466
+ meta: configFingerprint(meta ?? {}),
467
+ });
428
468
  configOptions = created.configOptions;
429
469
  modes = created.modes;
430
470
  }
431
471
  signal.throwIfAborted();
432
472
  if (!acpSessionId) throw new Error("acp agent returned no session id");
433
473
 
474
+ // A session opens, new or resumed, on the account's default model.
475
+ const opened = selectOf(configOptions ?? [], "model");
434
476
  const session: AcpSession = {
435
477
  client,
436
478
  acpSessionId,
@@ -440,11 +482,16 @@ export class AcpAgent extends SessionAgent {
440
482
  resumable: resumeMethod !== undefined,
441
483
  configOptions: configOptions ?? [],
442
484
  ...(modes?.availableModes.length && { modes }),
485
+ ...(this.profile.models &&
486
+ opened && { defaultModel: defaultModel(opened, this.profile.models.offers) }),
443
487
  prompt: {
444
488
  image: Boolean(init.agentCapabilities?.promptCapabilities?.image),
445
489
  embeddedContext: Boolean(init.agentCapabilities?.promptCapabilities?.embeddedContext),
446
490
  },
491
+ servers: Object.keys(given.servers ?? {}),
447
492
  };
493
+ const tools = this.profile.tools;
494
+ if (tools) session.describe = (call) => tools.describe(call, session.servers);
448
495
  client.setPermissionHandler((request) => answerPermission(session, request));
449
496
  client.setElicitationHandler((request) => answerElicitation(session, request));
450
497
  client.onSessionUpdate(({ sessionId, update }) => {
@@ -465,75 +512,104 @@ export class AcpAgent extends SessionAgent {
465
512
  }
466
513
 
467
514
  /**
468
- * Select the requested model and thinking level through the agent's config
469
- * options. An agent without the option keeps its own default. A model the
470
- * agent does not offer fails the turn; thinking levels are a normalized
471
- * vocabulary an agent may not share, so an unmatched level is left alone.
472
- * Returns the settings it left alone.
515
+ * Select the requested model, then the thinking level, through the agent's
516
+ * config options; an agent without the option keeps its own default. A
517
+ * model the agent does not offer, or its profile does not take, fails the
518
+ * turn; a turn that names none on a profile that lists models runs the
519
+ * one its list marks default (`defaultModel`). The levels are the ones
520
+ * offered once the model is set, which are that model's, and the turn
521
+ * runs the nearest of them, as on Claude and Codex (`clampThinkingLevel`);
522
+ * a level that cannot be fitted is left alone. Returns the settings it
523
+ * left alone.
473
524
  */
474
525
  private async applyConfig(
475
526
  session: AcpSession,
476
527
  options: AgentExecuteOptions,
477
528
  ): Promise<Array<keyof RunConfig>> {
478
- const requested = [
479
- ["model", options.model, "model"],
480
- ["thought_level", options.thinkingLevel, "thinkingLevel"],
481
- ] as const;
482
529
  const left: Array<keyof RunConfig> = [];
483
- for (const [category, value, field] of requested) {
484
- if (!value) continue;
485
- const option = session.configOptions.find(
486
- (candidate): candidate is SessionConfigOption & { type: "select" } =>
487
- candidate.category === category && candidate.type === "select",
488
- );
489
- if (!option) {
490
- left.push(field);
491
- continue;
492
- }
493
- if (option.currentValue === value) continue;
494
- const offered = selectableValues(option);
495
- if (!offered.includes(value)) {
496
- if (category === "thought_level") {
497
- left.push(field);
498
- continue;
499
- }
530
+ const option = selectOf(session.configOptions, "model");
531
+ const offers = this.profile.models?.offers;
532
+ if (!option) {
533
+ if (options.model) left.push("model");
534
+ } else if (options.model || offers) {
535
+ const offered = selectableValues(option).filter((value) => offers?.(value) ?? true);
536
+ // @ref LLP 0016.000#an-acp-agents-model-and-thinking-level — a harness that lists its models runs only one of them
537
+ // The default the session opened on, while the agent still offers it.
538
+ const opened =
539
+ session.defaultModel && offered.includes(session.defaultModel)
540
+ ? session.defaultModel
541
+ : undefined;
542
+ const model =
543
+ options.model ?? opened ?? (offers && defaultModel(option, offers)) ?? option.currentValue;
544
+ if (!offered.includes(model)) {
500
545
  throw new Error(
501
- `invalid request: the ACP agent does not offer model '${value}' (available: ${offered.join(", ")})`,
546
+ `invalid request: the ${this.harness} harness does not offer model '${model}' (available: ${offered.join(", ") || "none"})`,
502
547
  );
503
548
  }
504
- const updated = await session.client.request(
505
- "session/set_config_option",
506
- { sessionId: session.acpSessionId, configId: option.id, value },
507
- SESSION_REQUEST_TIMEOUT_MS,
508
- );
509
- session.configOptions = updated.configOptions;
549
+ await select(session, option, model);
550
+ }
551
+ if (options.thinkingLevel) {
552
+ const option = selectOf(session.configOptions, "thought_level");
553
+ const level = option && clampThinkingLevel(options.thinkingLevel, selectableValues(option));
554
+ if (option && level !== undefined) await select(session, option, level);
555
+ else left.push("thinkingLevel");
510
556
  }
511
557
  return left;
512
558
  }
513
559
 
514
- // @ref LLP 0016.000#an-acp-agents-permission-mode — a permission mode reaches the agent, or is said not applied
560
+ // @ref LLP 0016.000#an-acp-agents-profile — what a conversation starts with it keeps
561
+ /**
562
+ * What a conversation keeps from its start (`newSession`), said not
563
+ * applied by a later turn that asks otherwise; what a conversation this
564
+ * agent did not start was given is unknown, and nothing is said.
565
+ */
566
+ private keptFromStart(session: AcpSession, options: AgentExecuteOptions): Array<keyof RunConfig> {
567
+ const kept = this.profile.newSession;
568
+ const started = this.startedWith.get(options.sessionId);
569
+ if (!kept || started?.conversation !== session.acpSessionId) return [];
570
+ // Compared, not said of every later turn: a product sends the same config each turn, and that one is in effect.
571
+ return started.meta === configFingerprint(kept.meta(options) ?? {}) ? [] : [...kept.settings];
572
+ }
573
+
574
+ // @ref LLP 0016.000#an-acp-agents-permission-mode — never a turn in a mode the engine knows is not the one asked
515
575
  /**
516
576
  * Put the agent in the turn's permission mode (`default` when it names
517
- * none) through `session/set_mode`, by the agent's own id for it. Returns
518
- * whether the mode holds: false for one the agent offers none of, which
519
- * leaves the agent in its own. An agent that offers no modes runs as it
520
- * does, the engine answering what it asks by the mode (`autoDecide`); it
521
- * has no plan of its own to make, so `plan` does not hold there.
577
+ * none) through `session/set_mode`, by the agent's own id for it. An agent
578
+ * with no id for the mode is put in its `default`, never left in the mode
579
+ * an earlier turn left it in, and the engine answers what it asks by the
580
+ * turn's mode (`autoDecide`), as for an agent that offers no modes; neither
581
+ * has a plan of its own to make, so `plan` does not hold there. An agent
582
+ * with no `default` either stays where it is: in a mode the engine names
583
+ * and was not asked, the turn is refused; in one it cannot name, it runs,
584
+ * and the mode is said not applied. Returns whether the mode holds.
522
585
  */
523
586
  private async applyMode(session: AcpSession, requested: PermissionMode): Promise<boolean> {
524
587
  const modes = session.modes;
525
588
  if (!modes) return requested !== "plan";
526
- const target = modes.availableModes.find((mode) => permissionModeOf(mode.id) === requested);
527
- if (!target) return false;
528
- if (target.id !== modes.currentModeId) {
589
+ const names = modeNames(this.profile.modeIds);
590
+ const offered = modes.availableModes.map(({ id }) => id);
591
+ const own = names.idOf(requested, offered);
592
+ const target = own ?? names.idOf("default", offered);
593
+ if (target === undefined) {
594
+ const current = names.modeOf(modes.currentModeId);
595
+ if (current === undefined) return false;
596
+ if (current === requested) return true;
597
+ throw new InvalidRequestError([
598
+ {
599
+ path: "permissionMode",
600
+ message: `the ${this.harness} harness cannot run a ${requested} turn: the agent is in ${current}, and offers no mode to move it to`,
601
+ },
602
+ ]);
603
+ }
604
+ if (target !== modes.currentModeId) {
529
605
  await session.client.request(
530
606
  "session/set_mode",
531
- { sessionId: session.acpSessionId, modeId: target.id },
607
+ { sessionId: session.acpSessionId, modeId: target },
532
608
  SESSION_REQUEST_TIMEOUT_MS,
533
609
  );
534
- session.modes = { ...modes, currentModeId: target.id };
610
+ session.modes = { ...modes, currentModeId: target };
535
611
  }
536
- return true;
612
+ return own !== undefined || requested !== "plan";
537
613
  }
538
614
 
539
615
  protected override async *executeTurn(
@@ -547,6 +623,8 @@ export class AcpAgent extends SessionAgent {
547
623
  let session: AcpSession | undefined;
548
624
  try {
549
625
  controller.signal.throwIfAborted();
626
+ this.profile.admit?.(options);
627
+ refuseFiles(input, this.harness, this.capabilities.files);
550
628
  session = await this.resolveSession(options, controller.signal);
551
629
  const notApplied = await this.applyConfig(session, options);
552
630
  // Sent only to an agent that takes them (`resolveSession`).
@@ -554,7 +632,8 @@ export class AcpAgent extends SessionAgent {
554
632
  notApplied.push("additionalDirectories");
555
633
  if (!(await this.applyMode(session, options.permissionMode ?? "default")))
556
634
  notApplied.push("permissionMode");
557
- if (notApplied.length) options.onExecution?.({ notApplied });
635
+ notApplied.push(...this.keptFromStart(session, options));
636
+ options.onExecution?.({ ...selected(session), ...(notApplied.length && { notApplied }) });
558
637
  controller.signal.throwIfAborted();
559
638
  session.turn = {
560
639
  broker: options.onPermissionRequest,
@@ -566,33 +645,51 @@ export class AcpAgent extends SessionAgent {
566
645
  options.onNativeSession?.(session.acpSessionId, {
567
646
  resumed: session.acpSessionId === options.resumeSessionId,
568
647
  });
648
+ // What tells its calls' servers from their tools, for the adapter's tool rules.
649
+ if (this.profile.tools)
650
+ yield { method: "agentServer/mcpServers", params: { names: session.servers } };
569
651
  const { client, acpSessionId } = session;
652
+ const takes = session.prompt;
570
653
 
571
- unsubscribe.push(
572
- client.onSessionUpdate((notification) => {
573
- if (notification.sessionId !== acpSessionId) return;
574
- queue.push({ method: "session/update", params: notification });
575
- }),
576
- );
577
654
  const finishCancelled = () => {
578
655
  queue.push(CANCELLED_PROMPT_RESULT);
579
656
  queue.end();
580
657
  };
581
- // Settles once the agent is no longer prompting: its prompt answered, or it exited.
582
- let promptEnded = () => {};
583
- const prompted = new Promise<boolean>((resolve) => {
584
- promptEnded = () => resolve(true);
658
+ const prompts = new TurnPrompts({
659
+ send: (prompt) => client.request("session/prompt", { sessionId: acpSessionId, prompt }),
660
+ ...(client.asking && { asking: client.asking }),
661
+ signal: controller.signal,
662
+ ends: {
663
+ read: (steerId) => queue.push({ method: "agentServer/steerRead", params: { steerId } }),
664
+ ended: (result) => {
665
+ this.holdSteering(options);
666
+ queue.push({ method: "session/prompt_result", params: result });
667
+ queue.end();
668
+ },
669
+ failed: (error) => {
670
+ this.holdSteering(options);
671
+ if (controller.signal.aborted) return finishCancelled();
672
+ queue.push({ method: "error", params: { message: failureMessage(error) } });
673
+ queue.end();
674
+ },
675
+ },
585
676
  });
586
677
  unsubscribe.push(
678
+ client.onSessionUpdate((notification) => {
679
+ if (notification.sessionId !== acpSessionId) return;
680
+ // A steer the agent took is read before what it says next.
681
+ prompts.update(notification.update);
682
+ queue.push({ method: "session/update", params: notification });
683
+ }),
587
684
  client.onClose((error) => {
588
- promptEnded();
685
+ prompts.close();
589
686
  if (controller.signal.aborted) finishCancelled();
590
687
  else queue.fail(error ?? new Error("acp agent exited mid-turn"));
591
688
  }),
592
689
  );
593
690
 
594
691
  const cancelPrompt = () => {
595
- // ACP semantics: session/cancel makes the in-flight prompt resolve
692
+ // ACP semantics: session/cancel makes the in-flight prompts resolve
596
693
  // with stopReason=cancelled. Bound the wait for misbehaving agents.
597
694
  void client.notify("session/cancel", { sessionId: acpSessionId }).catch(() => {});
598
695
  cancelTimer = setTimeout(() => {
@@ -609,28 +706,16 @@ export class AcpAgent extends SessionAgent {
609
706
  finishCancelled();
610
707
  } else {
611
708
  unsubscribe.push(onAbort(controller.signal, cancelPrompt));
612
- const prompt: PromptRequest = {
613
- sessionId: acpSessionId,
614
- prompt: toPromptBlocks(input, session.prompt),
615
- };
616
- // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — confirmed only when the prompt ended
617
- this.cancelWith(options, () => prompted);
618
- client.request("session/prompt", prompt).then(
619
- (response) => {
620
- promptEnded();
621
- queue.push({ method: "session/prompt_result", params: response });
622
- queue.end();
623
- },
624
- (error: unknown) => {
625
- promptEnded();
626
- if (controller.signal.aborted) {
627
- finishCancelled();
628
- return;
629
- }
630
- queue.push({ method: "error", params: { message: failureMessage(error) } });
631
- queue.end();
632
- },
633
- );
709
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — confirmed only when the prompts ended
710
+ this.cancelWith(options, () => prompts.settled.then(() => true));
711
+ prompts.start(toPromptBlocks(input, takes));
712
+ // @ref LLP 0016.000#an-acp-agent-steered-by-prompt — input during a turn is a prompt of its own
713
+ if (this.capabilities.steering)
714
+ await this.openSteering(options, (request) => {
715
+ if (!prompts.open || controller.signal.aborted) return "no_active_turn";
716
+ prompts.steer(request.steerId, toPromptBlocks(request.input, takes));
717
+ return "steered";
718
+ });
634
719
  }
635
720
 
636
721
  for await (const event of queue) {
@@ -643,18 +728,34 @@ export class AcpAgent extends SessionAgent {
643
728
  if (cancelTimer) clearTimeout(cancelTimer);
644
729
  for (const off of unsubscribe) off();
645
730
  if (session) {
731
+ // A turn that has ended asks nothing: what it left open is forgotten.
732
+ session.client.asking?.askNothing();
646
733
  session.turn = undefined;
647
734
  this.sessions.leave(options.sessionId, session);
648
735
  }
649
736
  }
650
737
  }
651
738
 
739
+ /** A steer's file of a kind the harness does not take is refused, as a turn's is. */
740
+ protected override checkSteerInput(input: AgentInput): void {
741
+ refuseFiles(input, this.harness, this.capabilities.files);
742
+ }
743
+
652
744
  override async release(sessionId: string): Promise<void> {
653
745
  // The cancel aborts its turn at once; the agent is ended beside its
654
746
  // confirm window, not after it, and its exit is what confirms it.
655
747
  // An agent an eviction or a replacement ended earlier is waited for too.
656
748
  await Promise.all([super.release(sessionId), this.sessions.release(sessionId)]);
657
749
  this.host?.release(sessionId);
750
+ this.startedWith.delete(sessionId);
751
+ }
752
+
753
+ /**
754
+ * The agent's login changed (in `store`, or in every store): each session's
755
+ * next turn starts a new agent, which resumes its conversation.
756
+ */
757
+ loginChanged(store?: string): void {
758
+ this.sessions.loginChanged(store);
658
759
  }
659
760
 
660
761
  /** After a host resume, each session's next turn starts its agent again, on its conversation. */
@@ -668,3 +769,14 @@ export class AcpAgent extends SessionAgent {
668
769
  await this.host?.close();
669
770
  }
670
771
  }
772
+
773
+ /**
774
+ * The `acp` harness: any ACP v1 agent the operator launches
775
+ * (`resolveLaunch`), taken at its `initialize`'s word.
776
+ */
777
+ export class AcpAgent extends ProfiledAcpAgent {
778
+ constructor(options: AcpAgentOptions) {
779
+ const { resolveLaunch, ...shared } = options;
780
+ super(genericAcpProfile(resolveLaunch), shared);
781
+ }
782
+ }