@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,15 +1,18 @@
1
- import { AsyncQueue } from "../../../protocol/index.js";
1
+ import { AsyncQueue, clampThinkingLevel } from "../../../protocol/index.js";
2
2
  import { sharedNativeProcesses } from "../../processes/native-processes.js";
3
3
  import { onAbort, untilAborted } from "../../utils/deadline.js";
4
- import { McpUnavailableError, SessionResumeError } from "../../utils/errors.js";
4
+ import { InvalidRequestError, McpUnavailableError, SessionResumeError, } from "../../utils/errors.js";
5
5
  import { configFingerprint } from "../config-fingerprint.js";
6
6
  import { hostToolSessions, loopbackDirect, refuseHostName, } from "../host-tools.js";
7
7
  import { IDLE_TIMEOUT_MS, ProcessPool } from "../process-pool.js";
8
8
  import { SessionAgent } from "../session-agent.js";
9
+ import { AcpAccount, SESSION_REQUEST_TIMEOUT_MS, initialize, launchOf, startClient, } from "./account.js";
9
10
  import { CANCELLED_PROMPT_RESULT } from "./adapter.js";
10
- import { AcpClient } from "./client.js";
11
- import { permissionModeOf, toAcpMcpServers, toPromptBlocks, } from "./mappings.js";
12
- import { answerElicitation, answerPermission } from "./requests.js";
11
+ import { modeNames, refuseFiles, selectOf, selectableValues, toAcpMcpServers, toPromptBlocks, } from "./mappings.js";
12
+ import { defaultModel, listAcpModels } from "./models.js";
13
+ import { genericAcpProfile } from "./profile.js";
14
+ import { TurnPrompts } from "./prompts.js";
15
+ import { answerElicitation, answerPermission, } from "./requests.js";
13
16
  /**
14
17
  * What a session's agent process was started with, as one key: a change to
15
18
  * any of it starts another, which resumes the conversation where the agent
@@ -33,7 +36,12 @@ function canonicalServers(servers) {
33
36
  }
34
37
  function spawnKey(options, launch, takesDirectories, host) {
35
38
  return configFingerprint({
36
- launch: { command: launch.command, args: launch.args ?? [], env: launch.env ?? {} },
39
+ launch: {
40
+ command: launch.command,
41
+ args: launch.args ?? [],
42
+ env: launch.env ?? {},
43
+ fixedEnv: launch.fixedEnv ?? {},
44
+ },
37
45
  cwd: options.cwd,
38
46
  env: options.env,
39
47
  // @ref LLP 0018#acp — only what the agent is given
@@ -44,50 +52,12 @@ function spawnKey(options, launch, takesDirectories, host) {
44
52
  : undefined,
45
53
  });
46
54
  }
47
- const CAPABILITIES = {
48
- multiTurn: true,
49
- // A requested resume fails if the target agent cannot load saved sessions.
50
- sessionResume: true,
51
- // v1 has no portable model parameter. A requested model or thinking level
52
- // is applied only when the agent offers a `model` / `thought_level` config
53
- // option, so neither is promised here.
54
- modelSwitch: "unsupported",
55
- thinkingLevels: false,
56
- // The most an agent can take: its `initialize` decides, image data with its
57
- // `image` prompt capability and files beyond text with `embeddedContext`.
58
- images: true,
59
- files: ["text", "pdf", "binary"],
60
- mcpServers: true,
61
- permissionRequests: true,
62
- // The answer is an option id.
63
- rejectionMessages: false,
64
- ignoredSettings: [
65
- // ACP v1 has no system prompt: session/new takes the folder, the MCP
66
- // servers and the extra directories only (`resolveSession`).
67
- "systemPromptAppend",
68
- // A prompt runs until the agent ends it: ACP v1 has no turn limit.
69
- "maxTurns",
70
- // session/resume and session/load name a session, not a message in it.
71
- "resumeSessionAt",
72
- // The agent's credentials are its launch command's: the client gets the
73
- // launch, the folder and the env only (`AcpClientOptions`).
74
- "apiKey",
75
- // ACP v1 cannot ask an agent to run without its tools.
76
- "disableTools",
77
- ],
78
- };
79
- /** ACP protocol major version this harness speaks. */
80
- const PROTOCOL_VERSION = 1;
81
55
  /**
82
56
  * How long a cancelled prompt may take to end before the agent is ended,
83
57
  * unless `cancelGraceMs` says otherwise: an agent that can neither resume nor
84
58
  * load loses its conversation with it.
85
59
  */
86
60
  const CANCEL_GRACE_MS = 10_000;
87
- /** Deadline for `initialize` on a freshly spawned agent (mirrors codex startup). */
88
- const INITIALIZE_TIMEOUT_MS = 15_000;
89
- /** Deadline for session lifecycle requests (`session/new`, `session/resume`). */
90
- const SESSION_REQUEST_TIMEOUT_MS = 30_000;
91
61
  /** A JSON-RPC error's `data` usually holds the cause its message only names. */
92
62
  function failureMessage(error) {
93
63
  if (!(error instanceof Error))
@@ -99,31 +69,73 @@ function failureMessage(error) {
99
69
  const detail = typeof data === "string" ? data : typeof nested === "string" ? nested : JSON.stringify(data);
100
70
  return `${error}: ${detail}`;
101
71
  }
102
- /** Every value a select option offers, whether listed flat or in groups. */
103
- function selectableValues(option) {
104
- return option.options.flatMap((entry) => "options" in entry ? entry.options.map((nested) => nested.value) : [entry.value]);
72
+ /** Set an option to `value` unless it holds it; the answer carries every option as it now stands. */
73
+ async function select(session, option, value) {
74
+ if (option.currentValue === value)
75
+ return;
76
+ const updated = await session.client.request("session/set_config_option", { sessionId: session.acpSessionId, configId: option.id, value }, SESSION_REQUEST_TIMEOUT_MS);
77
+ session.configOptions = updated.configOptions;
105
78
  }
106
79
  /**
107
- * ACP harness: drives any Agent Client Protocol v1 agent as a long-lived
108
- * subprocess (one per logical session, reused across turns). The launch
109
- * command comes from the operator's `resolveLaunch`; `initialize` negotiates
110
- * the protocol version and gates optional features (resume, images) on the
111
- * agent's advertised capabilities. The turn's stopReason arrives as the
80
+ * What the agent's options say the turn runs, where it has them: what it ran,
81
+ * not what was asked (a level the model lacks was fitted, or left alone).
82
+ */
83
+ function selected(session) {
84
+ const model = selectOf(session.configOptions, "model")?.currentValue;
85
+ const thinkingLevel = selectOf(session.configOptions, "thought_level")?.currentValue;
86
+ return { ...(model && { model }), ...(thinkingLevel && { thinkingLevel }) };
87
+ }
88
+ // @ref LLP 0016.000#an-acp-agents-profile — a profile reaches the agent only through its harness's registration
89
+ /**
90
+ * An ACP agent running a profile: drives an Agent Client Protocol v1 agent
91
+ * as a long-lived subprocess (one per logical session, reused across turns).
92
+ * What is one agent's own, its name, its launch command and where it departs
93
+ * from its `initialize`, is its profile; `initialize` negotiates the protocol
94
+ * version and gates optional features (resume, images) on the agent's
95
+ * advertised capabilities. The turn's stopReason arrives as the
112
96
  * `session/prompt` *response*, so `execute` re-injects it into the raw stream
113
- * as a synthetic `session/prompt_result` event for the adapter.
97
+ * as a synthetic `session/prompt_result` event for the adapter. Internal to
98
+ * the engine: a harness that is a profile constructs it in its registration
99
+ * (`geminiHarness`); `AcpAgent` is the `acp` harness.
114
100
  */
115
- export class AcpAgent extends SessionAgent {
101
+ export class ProfiledAcpAgent extends SessionAgent {
116
102
  agentOptions;
117
- harness = "acp";
118
- capabilities = CAPABILITIES;
103
+ harness;
104
+ capabilities;
105
+ login;
106
+ /** Present when its profile lists models: what the agent offers this login. */
107
+ listModels;
119
108
  /** Its CLIs start here: the runtime's, or this OS process's own when it was made without one. */
120
109
  processes;
110
+ profile;
121
111
  sessions;
122
112
  host;
123
- constructor(agentOptions) {
113
+ /** How its agents start: its profile's, on its processes. */
114
+ starts;
115
+ /** The agent with no turn: its account, for the login and the model list. */
116
+ account;
117
+ /** What each session's conversation was started with, when this agent started it (`newSession`). */
118
+ startedWith = new Map();
119
+ constructor(profile, agentOptions) {
124
120
  super({ cancelConfirmMs: agentOptions.cancelConfirmMs });
125
121
  this.agentOptions = agentOptions;
122
+ this.profile = profile;
123
+ this.harness = this.profile.harness;
124
+ this.capabilities = this.profile.capabilities;
126
125
  this.processes = agentOptions.processes ?? sharedNativeProcesses();
126
+ const { clientName, clientVersion, createClient } = agentOptions;
127
+ this.starts = {
128
+ profile: this.profile,
129
+ processes: this.processes,
130
+ clientName,
131
+ clientVersion,
132
+ createClient,
133
+ };
134
+ this.account = new AcpAccount(this.starts);
135
+ this.login = this.profile.login?.(this.account);
136
+ const models = this.profile.models;
137
+ if (models)
138
+ this.listModels = (listing) => listAcpModels(this.account, this.harness, (value) => models.offers(value), listing);
127
139
  this.host = hostToolSessions(agentOptions.hostTools, this.harness, {
128
140
  // @ref LLP 0018#acp — the engine's mode: the turn's, moved only by a plan the broker approved
129
141
  // The agent's own `current_mode_update` never raises it.
@@ -151,13 +163,10 @@ export class AcpAgent extends SessionAgent {
151
163
  }, { idleMs: agentOptions.idleTimeoutMs ?? IDLE_TIMEOUT_MS });
152
164
  }
153
165
  async resolveSession(options, signal) {
154
- signal.throwIfAborted();
155
166
  // A cancel ends the wait: the operator's resolution goes on for the next turn.
156
- const launch = await untilAborted(Promise.resolve(this.agentOptions.resolveLaunch()), signal);
157
- signal.throwIfAborted();
158
- if (!launch) {
159
- throw new Error("acp harness is not configured: resolveLaunch returned no agent launch command");
160
- }
167
+ const base = await launchOf(this.profile, signal);
168
+ const modeArgs = this.profile.modeArgs?.[options.permissionMode ?? "default"];
169
+ const launch = modeArgs ? { ...base, args: [...(base.args ?? []), ...modeArgs] } : base;
161
170
  const host = await untilAborted(Promise.resolve(this.host?.lease(options.sessionId, options.cwd)), signal);
162
171
  if (host)
163
172
  refuseHostName(options.mcpServers, host.source.name);
@@ -203,24 +212,26 @@ export class AcpAgent extends SessionAgent {
203
212
  */
204
213
  async spawn({ options, launch, host }, own, signal) {
205
214
  const resumeTarget = options.resumeSessionId;
206
- const clientOptions = {
215
+ const client = await startClient(this.starts, {
207
216
  launch,
208
217
  cwd: options.cwd,
209
218
  // @ref LLP 0018#acp — the bearer never travels through a proxy
210
- // In the client's own order: the engine's environment, the launch's, the turn's.
219
+ // In the client's own order: the engine's environment, the launch's, the turn's, the launch's fixed.
211
220
  env: this.host
212
221
  ? {
213
222
  ...options.env,
214
- ...loopbackDirect({ ...process.env, ...launch.env, ...options.env }),
223
+ ...loopbackDirect({
224
+ ...process.env,
225
+ ...launch.env,
226
+ ...options.env,
227
+ ...launch.fixedEnv,
228
+ }),
215
229
  }
216
230
  : options.env,
217
- clientName: this.agentOptions.clientName,
218
231
  sessionId: options.sessionId,
219
- processes: this.processes,
220
- };
221
- const client = this.agentOptions.createClient
222
- ? await this.agentOptions.createClient(clientOptions)
223
- : await AcpClient.create(clientOptions);
232
+ // What the agent asks gates the steers sent as prompts (`TurnPrompts`).
233
+ watchRequests: this.capabilities.steering === true,
234
+ });
224
235
  own(client);
225
236
  // Closed at once when the turn was cancelled meanwhile.
226
237
  const offAbort = onAbort(signal, () => client.close());
@@ -228,16 +239,7 @@ export class AcpAgent extends SessionAgent {
228
239
  let acpSessionId;
229
240
  try {
230
241
  signal.throwIfAborted();
231
- init = await client.request("initialize", {
232
- protocolVersion: PROTOCOL_VERSION,
233
- // The engine brokers the agent's requests for input, form or URL;
234
- // a turn whose client cannot answer declines them.
235
- clientCapabilities: { elicitation: { form: {}, url: {} } },
236
- clientInfo: {
237
- name: this.agentOptions.clientName ?? "agent-server",
238
- version: this.agentOptions.clientVersion ?? "0.0.0",
239
- },
240
- }, INITIALIZE_TIMEOUT_MS);
242
+ init = await initialize(client, this.starts);
241
243
  signal.throwIfAborted();
242
244
  const capabilities = init.agentCapabilities;
243
245
  const takesDirectories = Boolean(capabilities?.sessionCapabilities?.additionalDirectories);
@@ -246,7 +248,7 @@ export class AcpAgent extends SessionAgent {
246
248
  : capabilities?.loadSession
247
249
  ? "session/load"
248
250
  : undefined;
249
- const given = await this.serversFor(options, host, Boolean(capabilities?.mcpCapabilities?.http));
251
+ const given = await this.serversFor(options, host, this.profile.httpMcp || Boolean(capabilities?.mcpCapabilities?.http));
250
252
  const target = {
251
253
  cwd: options.cwd,
252
254
  mcpServers: toAcpMcpServers(given.servers),
@@ -275,14 +277,22 @@ export class AcpAgent extends SessionAgent {
275
277
  modes = resumed?.modes;
276
278
  }
277
279
  else {
278
- const created = await client.request("session/new", target, SESSION_REQUEST_TIMEOUT_MS);
280
+ const meta = this.profile.newSession?.meta(options);
281
+ const created = await client.request("session/new", { ...target, ...(meta && { _meta: meta }) }, SESSION_REQUEST_TIMEOUT_MS);
279
282
  acpSessionId = created.sessionId;
283
+ if (this.profile.newSession)
284
+ this.startedWith.set(options.sessionId, {
285
+ conversation: created.sessionId,
286
+ meta: configFingerprint(meta ?? {}),
287
+ });
280
288
  configOptions = created.configOptions;
281
289
  modes = created.modes;
282
290
  }
283
291
  signal.throwIfAborted();
284
292
  if (!acpSessionId)
285
293
  throw new Error("acp agent returned no session id");
294
+ // A session opens, new or resumed, on the account's default model.
295
+ const opened = selectOf(configOptions ?? [], "model");
286
296
  const session = {
287
297
  client,
288
298
  acpSessionId,
@@ -292,11 +302,17 @@ export class AcpAgent extends SessionAgent {
292
302
  resumable: resumeMethod !== undefined,
293
303
  configOptions: configOptions ?? [],
294
304
  ...(modes?.availableModes.length && { modes }),
305
+ ...(this.profile.models &&
306
+ opened && { defaultModel: defaultModel(opened, this.profile.models.offers) }),
295
307
  prompt: {
296
308
  image: Boolean(init.agentCapabilities?.promptCapabilities?.image),
297
309
  embeddedContext: Boolean(init.agentCapabilities?.promptCapabilities?.embeddedContext),
298
310
  },
311
+ servers: Object.keys(given.servers ?? {}),
299
312
  };
313
+ const tools = this.profile.tools;
314
+ if (tools)
315
+ session.describe = (call) => tools.describe(call, session.servers);
300
316
  client.setPermissionHandler((request) => answerPermission(session, request));
301
317
  client.setElicitationHandler((request) => answerElicitation(session, request));
302
318
  client.onSessionUpdate(({ sessionId, update }) => {
@@ -319,62 +335,99 @@ export class AcpAgent extends SessionAgent {
319
335
  }
320
336
  }
321
337
  /**
322
- * Select the requested model and thinking level through the agent's config
323
- * options. An agent without the option keeps its own default. A model the
324
- * agent does not offer fails the turn; thinking levels are a normalized
325
- * vocabulary an agent may not share, so an unmatched level is left alone.
326
- * Returns the settings it left alone.
338
+ * Select the requested model, then the thinking level, through the agent's
339
+ * config options; an agent without the option keeps its own default. A
340
+ * model the agent does not offer, or its profile does not take, fails the
341
+ * turn; a turn that names none on a profile that lists models runs the
342
+ * one its list marks default (`defaultModel`). The levels are the ones
343
+ * offered once the model is set, which are that model's, and the turn
344
+ * runs the nearest of them, as on Claude and Codex (`clampThinkingLevel`);
345
+ * a level that cannot be fitted is left alone. Returns the settings it
346
+ * left alone.
327
347
  */
328
348
  async applyConfig(session, options) {
329
- const requested = [
330
- ["model", options.model, "model"],
331
- ["thought_level", options.thinkingLevel, "thinkingLevel"],
332
- ];
333
349
  const left = [];
334
- for (const [category, value, field] of requested) {
335
- if (!value)
336
- continue;
337
- const option = session.configOptions.find((candidate) => candidate.category === category && candidate.type === "select");
338
- if (!option) {
339
- left.push(field);
340
- continue;
341
- }
342
- if (option.currentValue === value)
343
- continue;
344
- const offered = selectableValues(option);
345
- if (!offered.includes(value)) {
346
- if (category === "thought_level") {
347
- left.push(field);
348
- continue;
349
- }
350
- throw new Error(`invalid request: the ACP agent does not offer model '${value}' (available: ${offered.join(", ")})`);
350
+ const option = selectOf(session.configOptions, "model");
351
+ const offers = this.profile.models?.offers;
352
+ if (!option) {
353
+ if (options.model)
354
+ left.push("model");
355
+ }
356
+ else if (options.model || offers) {
357
+ const offered = selectableValues(option).filter((value) => offers?.(value) ?? true);
358
+ // @ref LLP 0016.000#an-acp-agents-model-and-thinking-level — a harness that lists its models runs only one of them
359
+ // The default the session opened on, while the agent still offers it.
360
+ const opened = session.defaultModel && offered.includes(session.defaultModel)
361
+ ? session.defaultModel
362
+ : undefined;
363
+ const model = options.model ?? opened ?? (offers && defaultModel(option, offers)) ?? option.currentValue;
364
+ if (!offered.includes(model)) {
365
+ throw new Error(`invalid request: the ${this.harness} harness does not offer model '${model}' (available: ${offered.join(", ") || "none"})`);
351
366
  }
352
- const updated = await session.client.request("session/set_config_option", { sessionId: session.acpSessionId, configId: option.id, value }, SESSION_REQUEST_TIMEOUT_MS);
353
- session.configOptions = updated.configOptions;
367
+ await select(session, option, model);
368
+ }
369
+ if (options.thinkingLevel) {
370
+ const option = selectOf(session.configOptions, "thought_level");
371
+ const level = option && clampThinkingLevel(options.thinkingLevel, selectableValues(option));
372
+ if (option && level !== undefined)
373
+ await select(session, option, level);
374
+ else
375
+ left.push("thinkingLevel");
354
376
  }
355
377
  return left;
356
378
  }
357
- // @ref LLP 0016.000#an-acp-agents-permission-mode — a permission mode reaches the agent, or is said not applied
379
+ // @ref LLP 0016.000#an-acp-agents-profile — what a conversation starts with it keeps
380
+ /**
381
+ * What a conversation keeps from its start (`newSession`), said not
382
+ * applied by a later turn that asks otherwise; what a conversation this
383
+ * agent did not start was given is unknown, and nothing is said.
384
+ */
385
+ keptFromStart(session, options) {
386
+ const kept = this.profile.newSession;
387
+ const started = this.startedWith.get(options.sessionId);
388
+ if (!kept || started?.conversation !== session.acpSessionId)
389
+ return [];
390
+ // Compared, not said of every later turn: a product sends the same config each turn, and that one is in effect.
391
+ return started.meta === configFingerprint(kept.meta(options) ?? {}) ? [] : [...kept.settings];
392
+ }
393
+ // @ref LLP 0016.000#an-acp-agents-permission-mode — never a turn in a mode the engine knows is not the one asked
358
394
  /**
359
395
  * Put the agent in the turn's permission mode (`default` when it names
360
- * none) through `session/set_mode`, by the agent's own id for it. Returns
361
- * whether the mode holds: false for one the agent offers none of, which
362
- * leaves the agent in its own. An agent that offers no modes runs as it
363
- * does, the engine answering what it asks by the mode (`autoDecide`); it
364
- * has no plan of its own to make, so `plan` does not hold there.
396
+ * none) through `session/set_mode`, by the agent's own id for it. An agent
397
+ * with no id for the mode is put in its `default`, never left in the mode
398
+ * an earlier turn left it in, and the engine answers what it asks by the
399
+ * turn's mode (`autoDecide`), as for an agent that offers no modes; neither
400
+ * has a plan of its own to make, so `plan` does not hold there. An agent
401
+ * with no `default` either stays where it is: in a mode the engine names
402
+ * and was not asked, the turn is refused; in one it cannot name, it runs,
403
+ * and the mode is said not applied. Returns whether the mode holds.
365
404
  */
366
405
  async applyMode(session, requested) {
367
406
  const modes = session.modes;
368
407
  if (!modes)
369
408
  return requested !== "plan";
370
- const target = modes.availableModes.find((mode) => permissionModeOf(mode.id) === requested);
371
- if (!target)
372
- return false;
373
- if (target.id !== modes.currentModeId) {
374
- await session.client.request("session/set_mode", { sessionId: session.acpSessionId, modeId: target.id }, SESSION_REQUEST_TIMEOUT_MS);
375
- session.modes = { ...modes, currentModeId: target.id };
409
+ const names = modeNames(this.profile.modeIds);
410
+ const offered = modes.availableModes.map(({ id }) => id);
411
+ const own = names.idOf(requested, offered);
412
+ const target = own ?? names.idOf("default", offered);
413
+ if (target === undefined) {
414
+ const current = names.modeOf(modes.currentModeId);
415
+ if (current === undefined)
416
+ return false;
417
+ if (current === requested)
418
+ return true;
419
+ throw new InvalidRequestError([
420
+ {
421
+ path: "permissionMode",
422
+ message: `the ${this.harness} harness cannot run a ${requested} turn: the agent is in ${current}, and offers no mode to move it to`,
423
+ },
424
+ ]);
376
425
  }
377
- return true;
426
+ if (target !== modes.currentModeId) {
427
+ await session.client.request("session/set_mode", { sessionId: session.acpSessionId, modeId: target }, SESSION_REQUEST_TIMEOUT_MS);
428
+ session.modes = { ...modes, currentModeId: target };
429
+ }
430
+ return own !== undefined || requested !== "plan";
378
431
  }
379
432
  async *executeTurn(input, options, controller) {
380
433
  const queue = new AsyncQueue();
@@ -383,6 +436,8 @@ export class AcpAgent extends SessionAgent {
383
436
  let session;
384
437
  try {
385
438
  controller.signal.throwIfAborted();
439
+ this.profile.admit?.(options);
440
+ refuseFiles(input, this.harness, this.capabilities.files);
386
441
  session = await this.resolveSession(options, controller.signal);
387
442
  const notApplied = await this.applyConfig(session, options);
388
443
  // Sent only to an agent that takes them (`resolveSession`).
@@ -390,8 +445,8 @@ export class AcpAgent extends SessionAgent {
390
445
  notApplied.push("additionalDirectories");
391
446
  if (!(await this.applyMode(session, options.permissionMode ?? "default")))
392
447
  notApplied.push("permissionMode");
393
- if (notApplied.length)
394
- options.onExecution?.({ notApplied });
448
+ notApplied.push(...this.keptFromStart(session, options));
449
+ options.onExecution?.({ ...selected(session), ...(notApplied.length && { notApplied }) });
395
450
  controller.signal.throwIfAborted();
396
451
  session.turn = {
397
452
  broker: options.onPermissionRequest,
@@ -403,30 +458,50 @@ export class AcpAgent extends SessionAgent {
403
458
  options.onNativeSession?.(session.acpSessionId, {
404
459
  resumed: session.acpSessionId === options.resumeSessionId,
405
460
  });
461
+ // What tells its calls' servers from their tools, for the adapter's tool rules.
462
+ if (this.profile.tools)
463
+ yield { method: "agentServer/mcpServers", params: { names: session.servers } };
406
464
  const { client, acpSessionId } = session;
407
- unsubscribe.push(client.onSessionUpdate((notification) => {
408
- if (notification.sessionId !== acpSessionId)
409
- return;
410
- queue.push({ method: "session/update", params: notification });
411
- }));
465
+ const takes = session.prompt;
412
466
  const finishCancelled = () => {
413
467
  queue.push(CANCELLED_PROMPT_RESULT);
414
468
  queue.end();
415
469
  };
416
- // Settles once the agent is no longer prompting: its prompt answered, or it exited.
417
- let promptEnded = () => { };
418
- const prompted = new Promise((resolve) => {
419
- promptEnded = () => resolve(true);
470
+ const prompts = new TurnPrompts({
471
+ send: (prompt) => client.request("session/prompt", { sessionId: acpSessionId, prompt }),
472
+ ...(client.asking && { asking: client.asking }),
473
+ signal: controller.signal,
474
+ ends: {
475
+ read: (steerId) => queue.push({ method: "agentServer/steerRead", params: { steerId } }),
476
+ ended: (result) => {
477
+ this.holdSteering(options);
478
+ queue.push({ method: "session/prompt_result", params: result });
479
+ queue.end();
480
+ },
481
+ failed: (error) => {
482
+ this.holdSteering(options);
483
+ if (controller.signal.aborted)
484
+ return finishCancelled();
485
+ queue.push({ method: "error", params: { message: failureMessage(error) } });
486
+ queue.end();
487
+ },
488
+ },
420
489
  });
421
- unsubscribe.push(client.onClose((error) => {
422
- promptEnded();
490
+ unsubscribe.push(client.onSessionUpdate((notification) => {
491
+ if (notification.sessionId !== acpSessionId)
492
+ return;
493
+ // A steer the agent took is read before what it says next.
494
+ prompts.update(notification.update);
495
+ queue.push({ method: "session/update", params: notification });
496
+ }), client.onClose((error) => {
497
+ prompts.close();
423
498
  if (controller.signal.aborted)
424
499
  finishCancelled();
425
500
  else
426
501
  queue.fail(error ?? new Error("acp agent exited mid-turn"));
427
502
  }));
428
503
  const cancelPrompt = () => {
429
- // ACP semantics: session/cancel makes the in-flight prompt resolve
504
+ // ACP semantics: session/cancel makes the in-flight prompts resolve
430
505
  // with stopReason=cancelled. Bound the wait for misbehaving agents.
431
506
  void client.notify("session/cancel", { sessionId: acpSessionId }).catch(() => { });
432
507
  cancelTimer = setTimeout(() => {
@@ -443,25 +518,17 @@ export class AcpAgent extends SessionAgent {
443
518
  }
444
519
  else {
445
520
  unsubscribe.push(onAbort(controller.signal, cancelPrompt));
446
- const prompt = {
447
- sessionId: acpSessionId,
448
- prompt: toPromptBlocks(input, session.prompt),
449
- };
450
- // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — confirmed only when the prompt ended
451
- this.cancelWith(options, () => prompted);
452
- client.request("session/prompt", prompt).then((response) => {
453
- promptEnded();
454
- queue.push({ method: "session/prompt_result", params: response });
455
- queue.end();
456
- }, (error) => {
457
- promptEnded();
458
- if (controller.signal.aborted) {
459
- finishCancelled();
460
- return;
461
- }
462
- queue.push({ method: "error", params: { message: failureMessage(error) } });
463
- queue.end();
464
- });
521
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — confirmed only when the prompts ended
522
+ this.cancelWith(options, () => prompts.settled.then(() => true));
523
+ prompts.start(toPromptBlocks(input, takes));
524
+ // @ref LLP 0016.000#an-acp-agent-steered-by-prompt — input during a turn is a prompt of its own
525
+ if (this.capabilities.steering)
526
+ await this.openSteering(options, (request) => {
527
+ if (!prompts.open || controller.signal.aborted)
528
+ return "no_active_turn";
529
+ prompts.steer(request.steerId, toPromptBlocks(request.input, takes));
530
+ return "steered";
531
+ });
465
532
  }
466
533
  for await (const event of queue) {
467
534
  yield event;
@@ -478,17 +545,31 @@ export class AcpAgent extends SessionAgent {
478
545
  for (const off of unsubscribe)
479
546
  off();
480
547
  if (session) {
548
+ // A turn that has ended asks nothing: what it left open is forgotten.
549
+ session.client.asking?.askNothing();
481
550
  session.turn = undefined;
482
551
  this.sessions.leave(options.sessionId, session);
483
552
  }
484
553
  }
485
554
  }
555
+ /** A steer's file of a kind the harness does not take is refused, as a turn's is. */
556
+ checkSteerInput(input) {
557
+ refuseFiles(input, this.harness, this.capabilities.files);
558
+ }
486
559
  async release(sessionId) {
487
560
  // The cancel aborts its turn at once; the agent is ended beside its
488
561
  // confirm window, not after it, and its exit is what confirms it.
489
562
  // An agent an eviction or a replacement ended earlier is waited for too.
490
563
  await Promise.all([super.release(sessionId), this.sessions.release(sessionId)]);
491
564
  this.host?.release(sessionId);
565
+ this.startedWith.delete(sessionId);
566
+ }
567
+ /**
568
+ * The agent's login changed (in `store`, or in every store): each session's
569
+ * next turn starts a new agent, which resumes its conversation.
570
+ */
571
+ loginChanged(store) {
572
+ this.sessions.loginChanged(store);
492
573
  }
493
574
  /** After a host resume, each session's next turn starts its agent again, on its conversation. */
494
575
  invalidateMcpConnections() {
@@ -500,3 +581,13 @@ export class AcpAgent extends SessionAgent {
500
581
  await this.host?.close();
501
582
  }
502
583
  }
584
+ /**
585
+ * The `acp` harness: any ACP v1 agent the operator launches
586
+ * (`resolveLaunch`), taken at its `initialize`'s word.
587
+ */
588
+ export class AcpAgent extends ProfiledAcpAgent {
589
+ constructor(options) {
590
+ const { resolveLaunch, ...shared } = options;
591
+ super(genericAcpProfile(resolveLaunch), shared);
592
+ }
593
+ }