@zvada/agent-server 0.3.26 → 0.3.28

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 (262) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +7 -5
  3. package/dist/client/client.js +27 -11
  4. package/dist/client/connection.js +35 -3
  5. package/dist/core/agents/acp/account.js +111 -0
  6. package/dist/core/agents/acp/acp-agent.js +247 -158
  7. package/dist/core/agents/acp/adapter.js +103 -34
  8. package/dist/core/agents/acp/client.js +169 -42
  9. package/dist/core/agents/acp/known-agents.js +12 -5
  10. package/dist/core/agents/acp/mappings.js +84 -20
  11. package/dist/core/agents/acp/models.js +59 -0
  12. package/dist/core/agents/acp/profile.js +36 -0
  13. package/dist/core/agents/acp/prompts.js +248 -0
  14. package/dist/core/agents/acp/requests.js +4 -4
  15. package/dist/core/agents/claude-code/approvals.js +1 -1
  16. package/dist/core/agents/claude-code/login.js +4 -1
  17. package/dist/core/agents/claude-code/session.js +38 -10
  18. package/dist/core/agents/claude-code/spawn.js +0 -26
  19. package/dist/core/agents/codex-app-server/client.js +12 -13
  20. package/dist/core/agents/codex-app-server/login.js +4 -1
  21. package/dist/core/agents/codex-app-server/plan-approval.js +1 -1
  22. package/dist/core/agents/gemini/failures.js +133 -0
  23. package/dist/core/agents/gemini/login.js +173 -0
  24. package/dist/core/agents/gemini/profile.js +137 -0
  25. package/dist/core/agents/gemini/tools.js +91 -0
  26. package/dist/core/agents/login.js +8 -6
  27. package/dist/core/agents/scripted/scripted-agent.js +30 -3
  28. package/dist/core/agents/stderr-tail.js +5 -2
  29. package/dist/core/presets.js +17 -1
  30. package/dist/core/processes/native-processes.js +23 -1
  31. package/dist/core/provision/install-build.js +70 -26
  32. package/dist/core/provision/pins.js +5 -0
  33. package/dist/core/provision/provisioner.js +39 -16
  34. package/dist/core/provision/releases.js +39 -1
  35. package/dist/core/provision/tools.js +87 -28
  36. package/dist/core/runtime/agent-runtime.js +15 -5
  37. package/dist/core/runtime/event-processor.js +13 -8
  38. package/dist/core/runtime/origin-line.js +42 -0
  39. package/dist/core/runtime/request-broker.js +2 -1
  40. package/dist/core/runtime/steering.js +4 -3
  41. package/dist/core/runtime/turn.js +6 -4
  42. package/dist/operator/errors.js +97 -0
  43. package/dist/operator/index.js +10 -5
  44. package/dist/operator/mcp.js +7 -12
  45. package/dist/operator/operator.js +1431 -378
  46. package/dist/operator/refs.js +59 -0
  47. package/dist/operator/render.js +199 -94
  48. package/dist/operator/session-tools.js +88 -0
  49. package/dist/operator/types.js +30 -0
  50. package/dist/operator/view.js +82 -27
  51. package/dist/protocol/account.js +5 -1
  52. package/dist/protocol/auth.js +5 -1
  53. package/dist/protocol/config.js +12 -5
  54. package/dist/protocol/conversation.js +3 -0
  55. package/dist/protocol/credentials.js +9 -1
  56. package/dist/protocol/harness.js +9 -1
  57. package/dist/protocol/history.js +2 -1
  58. package/dist/protocol/index.js +1 -0
  59. package/dist/protocol/lifecycle.js +19 -0
  60. package/dist/protocol/origin.js +39 -0
  61. package/dist/protocol/reduce.js +2 -0
  62. package/dist/protocol/wire.js +17 -0
  63. package/dist/server/bin.js +22 -7
  64. package/dist/server/install.js +6 -4
  65. package/dist/server/routes.js +15 -5
  66. package/dist/types/client/client.d.ts.map +1 -1
  67. package/dist/types/client/connection.d.ts +14 -2
  68. package/dist/types/client/connection.d.ts.map +1 -1
  69. package/dist/types/client/turns.d.ts +2 -2
  70. package/dist/types/client/turns.d.ts.map +1 -1
  71. package/dist/types/core/agents/acp/account.d.ts +55 -0
  72. package/dist/types/core/agents/acp/account.d.ts.map +1 -0
  73. package/dist/types/core/agents/acp/acp-agent.d.ts +65 -36
  74. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  75. package/dist/types/core/agents/acp/adapter.d.ts +28 -3
  76. package/dist/types/core/agents/acp/adapter.d.ts.map +1 -1
  77. package/dist/types/core/agents/acp/client.d.ts +66 -4
  78. package/dist/types/core/agents/acp/client.d.ts.map +1 -1
  79. package/dist/types/core/agents/acp/known-agents.d.ts +4 -2
  80. package/dist/types/core/agents/acp/known-agents.d.ts.map +1 -1
  81. package/dist/types/core/agents/acp/mappings.d.ts +53 -7
  82. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  83. package/dist/types/core/agents/acp/models.d.ts +22 -0
  84. package/dist/types/core/agents/acp/models.d.ts.map +1 -0
  85. package/dist/types/core/agents/acp/profile.d.ts +92 -0
  86. package/dist/types/core/agents/acp/profile.d.ts.map +1 -0
  87. package/dist/types/core/agents/acp/prompts.d.ts +108 -0
  88. package/dist/types/core/agents/acp/prompts.d.ts.map +1 -0
  89. package/dist/types/core/agents/acp/requests.d.ts +7 -1
  90. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  91. package/dist/types/core/agents/base.d.ts +2 -0
  92. package/dist/types/core/agents/base.d.ts.map +1 -1
  93. package/dist/types/core/agents/claude-code/login.d.ts.map +1 -1
  94. package/dist/types/core/agents/claude-code/session.d.ts +3 -0
  95. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  96. package/dist/types/core/agents/claude-code/spawn.d.ts +0 -8
  97. package/dist/types/core/agents/claude-code/spawn.d.ts.map +1 -1
  98. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  99. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  100. package/dist/types/core/agents/gemini/failures.d.ts +25 -0
  101. package/dist/types/core/agents/gemini/failures.d.ts.map +1 -0
  102. package/dist/types/core/agents/gemini/login.d.ts +28 -0
  103. package/dist/types/core/agents/gemini/login.d.ts.map +1 -0
  104. package/dist/types/core/agents/gemini/profile.d.ts +30 -0
  105. package/dist/types/core/agents/gemini/profile.d.ts.map +1 -0
  106. package/dist/types/core/agents/gemini/tools.d.ts +18 -0
  107. package/dist/types/core/agents/gemini/tools.d.ts.map +1 -0
  108. package/dist/types/core/agents/login.d.ts +15 -5
  109. package/dist/types/core/agents/login.d.ts.map +1 -1
  110. package/dist/types/core/agents/scripted/scripted-agent.d.ts +14 -1
  111. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  112. package/dist/types/core/agents/stderr-tail.d.ts +1 -1
  113. package/dist/types/core/agents/stderr-tail.d.ts.map +1 -1
  114. package/dist/types/core/presets.d.ts +2 -2
  115. package/dist/types/core/presets.d.ts.map +1 -1
  116. package/dist/types/core/processes/native-processes.d.ts +6 -0
  117. package/dist/types/core/processes/native-processes.d.ts.map +1 -1
  118. package/dist/types/core/provision/checksums.d.ts +7 -1
  119. package/dist/types/core/provision/checksums.d.ts.map +1 -1
  120. package/dist/types/core/provision/install-build.d.ts +32 -6
  121. package/dist/types/core/provision/install-build.d.ts.map +1 -1
  122. package/dist/types/core/provision/pins.d.ts +4 -0
  123. package/dist/types/core/provision/pins.d.ts.map +1 -1
  124. package/dist/types/core/provision/provisioner.d.ts +18 -7
  125. package/dist/types/core/provision/provisioner.d.ts.map +1 -1
  126. package/dist/types/core/provision/releases.d.ts +2 -1
  127. package/dist/types/core/provision/releases.d.ts.map +1 -1
  128. package/dist/types/core/provision/tools.d.ts +36 -7
  129. package/dist/types/core/provision/tools.d.ts.map +1 -1
  130. package/dist/types/core/runtime/agent-runtime.d.ts +4 -2
  131. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  132. package/dist/types/core/runtime/event-processor.d.ts +2 -2
  133. package/dist/types/core/runtime/event-processor.d.ts.map +1 -1
  134. package/dist/types/core/runtime/origin-line.d.ts +15 -0
  135. package/dist/types/core/runtime/origin-line.d.ts.map +1 -0
  136. package/dist/types/core/runtime/request-broker.d.ts +1 -1
  137. package/dist/types/core/runtime/request-broker.d.ts.map +1 -1
  138. package/dist/types/core/runtime/steering.d.ts +7 -4
  139. package/dist/types/core/runtime/steering.d.ts.map +1 -1
  140. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  141. package/dist/types/operator/errors.d.ts +87 -0
  142. package/dist/types/operator/errors.d.ts.map +1 -0
  143. package/dist/types/operator/index.d.ts +10 -5
  144. package/dist/types/operator/index.d.ts.map +1 -1
  145. package/dist/types/operator/mcp.d.ts +1 -1
  146. package/dist/types/operator/mcp.d.ts.map +1 -1
  147. package/dist/types/operator/operator.d.ts +15 -197
  148. package/dist/types/operator/operator.d.ts.map +1 -1
  149. package/dist/types/operator/refs.d.ts +25 -0
  150. package/dist/types/operator/refs.d.ts.map +1 -0
  151. package/dist/types/operator/render.d.ts +67 -22
  152. package/dist/types/operator/render.d.ts.map +1 -1
  153. package/dist/types/operator/session-tools.d.ts +61 -0
  154. package/dist/types/operator/session-tools.d.ts.map +1 -0
  155. package/dist/types/operator/types.d.ts +442 -0
  156. package/dist/types/operator/types.d.ts.map +1 -0
  157. package/dist/types/operator/view.d.ts +19 -29
  158. package/dist/types/operator/view.d.ts.map +1 -1
  159. package/dist/types/protocol/account.d.ts +4 -2
  160. package/dist/types/protocol/account.d.ts.map +1 -1
  161. package/dist/types/protocol/auth.d.ts +10 -7
  162. package/dist/types/protocol/auth.d.ts.map +1 -1
  163. package/dist/types/protocol/clis.d.ts +4 -3
  164. package/dist/types/protocol/clis.d.ts.map +1 -1
  165. package/dist/types/protocol/config.d.ts +22 -5
  166. package/dist/types/protocol/config.d.ts.map +1 -1
  167. package/dist/types/protocol/conversation.d.ts +47 -6
  168. package/dist/types/protocol/conversation.d.ts.map +1 -1
  169. package/dist/types/protocol/credentials.d.ts +8 -0
  170. package/dist/types/protocol/credentials.d.ts.map +1 -1
  171. package/dist/types/protocol/execution.d.ts +1 -1
  172. package/dist/types/protocol/harness.d.ts +5 -2
  173. package/dist/types/protocol/harness.d.ts.map +1 -1
  174. package/dist/types/protocol/history.d.ts +1 -1
  175. package/dist/types/protocol/history.d.ts.map +1 -1
  176. package/dist/types/protocol/index.d.ts +1 -0
  177. package/dist/types/protocol/index.d.ts.map +1 -1
  178. package/dist/types/protocol/lifecycle.d.ts +48 -10
  179. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  180. package/dist/types/protocol/models.d.ts +3 -0
  181. package/dist/types/protocol/models.d.ts.map +1 -1
  182. package/dist/types/protocol/origin.d.ts +49 -0
  183. package/dist/types/protocol/origin.d.ts.map +1 -0
  184. package/dist/types/protocol/reduce.d.ts.map +1 -1
  185. package/dist/types/protocol/wire-api.d.ts +78 -30
  186. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  187. package/dist/types/protocol/wire.d.ts +78 -12
  188. package/dist/types/protocol/wire.d.ts.map +1 -1
  189. package/dist/types/server/install.d.ts +2 -1
  190. package/dist/types/server/install.d.ts.map +1 -1
  191. package/dist/types/server/routes.d.ts.map +1 -1
  192. package/docs/consuming.md +62 -121
  193. package/docs/deploy.md +17 -8
  194. package/docs/harnesses.md +166 -44
  195. package/docs/sync-history.md +2 -1
  196. package/package.json +1 -1
  197. package/src/client/client.ts +36 -9
  198. package/src/client/connection.ts +31 -1
  199. package/src/client/turns.ts +2 -1
  200. package/src/core/agents/acp/account.ts +158 -0
  201. package/src/core/agents/acp/acp-agent.ts +288 -178
  202. package/src/core/agents/acp/adapter.ts +126 -35
  203. package/src/core/agents/acp/client.ts +196 -49
  204. package/src/core/agents/acp/known-agents.ts +14 -5
  205. package/src/core/agents/acp/mappings.ts +112 -21
  206. package/src/core/agents/acp/models.ts +72 -0
  207. package/src/core/agents/acp/profile.ts +127 -0
  208. package/src/core/agents/acp/prompts.ts +287 -0
  209. package/src/core/agents/acp/requests.ts +16 -9
  210. package/src/core/agents/base.ts +2 -0
  211. package/src/core/agents/claude-code/approvals.ts +2 -2
  212. package/src/core/agents/claude-code/login.ts +4 -1
  213. package/src/core/agents/claude-code/session.ts +38 -8
  214. package/src/core/agents/claude-code/spawn.ts +0 -26
  215. package/src/core/agents/codex-app-server/client.ts +11 -18
  216. package/src/core/agents/codex-app-server/login.ts +4 -5
  217. package/src/core/agents/codex-app-server/plan-approval.ts +1 -1
  218. package/src/core/agents/gemini/failures.ts +148 -0
  219. package/src/core/agents/gemini/login.ts +188 -0
  220. package/src/core/agents/gemini/profile.ts +162 -0
  221. package/src/core/agents/gemini/tools.ts +99 -0
  222. package/src/core/agents/login.ts +14 -8
  223. package/src/core/agents/scripted/scripted-agent.ts +42 -3
  224. package/src/core/agents/stderr-tail.ts +5 -2
  225. package/src/core/presets.ts +19 -3
  226. package/src/core/processes/native-processes.ts +32 -1
  227. package/src/core/provision/checksums.ts +12 -2
  228. package/src/core/provision/install-build.ts +122 -55
  229. package/src/core/provision/pins.ts +5 -0
  230. package/src/core/provision/provisioner.ts +62 -27
  231. package/src/core/provision/releases.ts +47 -1
  232. package/src/core/provision/tools.ts +124 -31
  233. package/src/core/runtime/agent-runtime.ts +31 -7
  234. package/src/core/runtime/event-processor.ts +13 -6
  235. package/src/core/runtime/origin-line.ts +43 -0
  236. package/src/core/runtime/request-broker.ts +2 -0
  237. package/src/core/runtime/steering.ts +8 -4
  238. package/src/core/runtime/turn.ts +11 -4
  239. package/src/operator/errors.ts +221 -0
  240. package/src/operator/index.ts +18 -23
  241. package/src/operator/mcp.ts +7 -16
  242. package/src/operator/operator.ts +1684 -610
  243. package/src/operator/refs.ts +75 -0
  244. package/src/operator/render.ts +260 -118
  245. package/src/operator/session-tools.ts +127 -0
  246. package/src/operator/types.ts +506 -0
  247. package/src/operator/view.ts +93 -42
  248. package/src/protocol/account.ts +5 -2
  249. package/src/protocol/auth.ts +5 -1
  250. package/src/protocol/config.ts +14 -6
  251. package/src/protocol/conversation.ts +3 -0
  252. package/src/protocol/credentials.ts +11 -2
  253. package/src/protocol/harness.ts +9 -1
  254. package/src/protocol/history.ts +2 -1
  255. package/src/protocol/index.ts +1 -0
  256. package/src/protocol/lifecycle.ts +21 -0
  257. package/src/protocol/origin.ts +47 -0
  258. package/src/protocol/reduce.ts +4 -0
  259. package/src/protocol/wire.ts +18 -0
  260. package/src/server/bin.ts +20 -6
  261. package/src/server/install.ts +6 -3
  262. package/src/server/routes.ts +16 -5
@@ -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,8 @@ 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 launch = await launchOf(this.profile, signal);
161
168
  const host = await untilAborted(Promise.resolve(this.host?.lease(options.sessionId, options.cwd)), signal);
162
169
  if (host)
163
170
  refuseHostName(options.mcpServers, host.source.name);
@@ -203,24 +210,26 @@ export class AcpAgent extends SessionAgent {
203
210
  */
204
211
  async spawn({ options, launch, host }, own, signal) {
205
212
  const resumeTarget = options.resumeSessionId;
206
- const clientOptions = {
213
+ const client = await startClient(this.starts, {
207
214
  launch,
208
215
  cwd: options.cwd,
209
216
  // @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.
217
+ // In the client's own order: the engine's environment, the launch's, the turn's, the launch's fixed.
211
218
  env: this.host
212
219
  ? {
213
220
  ...options.env,
214
- ...loopbackDirect({ ...process.env, ...launch.env, ...options.env }),
221
+ ...loopbackDirect({
222
+ ...process.env,
223
+ ...launch.env,
224
+ ...options.env,
225
+ ...launch.fixedEnv,
226
+ }),
215
227
  }
216
228
  : options.env,
217
- clientName: this.agentOptions.clientName,
218
229
  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);
230
+ // What the agent asks gates the steers sent as prompts (`TurnPrompts`).
231
+ watchRequests: this.capabilities.steering === true,
232
+ });
224
233
  own(client);
225
234
  // Closed at once when the turn was cancelled meanwhile.
226
235
  const offAbort = onAbort(signal, () => client.close());
@@ -228,16 +237,7 @@ export class AcpAgent extends SessionAgent {
228
237
  let acpSessionId;
229
238
  try {
230
239
  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);
240
+ init = await initialize(client, this.starts);
241
241
  signal.throwIfAborted();
242
242
  const capabilities = init.agentCapabilities;
243
243
  const takesDirectories = Boolean(capabilities?.sessionCapabilities?.additionalDirectories);
@@ -246,7 +246,7 @@ export class AcpAgent extends SessionAgent {
246
246
  : capabilities?.loadSession
247
247
  ? "session/load"
248
248
  : undefined;
249
- const given = await this.serversFor(options, host, Boolean(capabilities?.mcpCapabilities?.http));
249
+ const given = await this.serversFor(options, host, this.profile.httpMcp || Boolean(capabilities?.mcpCapabilities?.http));
250
250
  const target = {
251
251
  cwd: options.cwd,
252
252
  mcpServers: toAcpMcpServers(given.servers),
@@ -275,14 +275,22 @@ export class AcpAgent extends SessionAgent {
275
275
  modes = resumed?.modes;
276
276
  }
277
277
  else {
278
- const created = await client.request("session/new", target, SESSION_REQUEST_TIMEOUT_MS);
278
+ const meta = this.profile.newSession?.meta(options);
279
+ const created = await client.request("session/new", { ...target, ...(meta && { _meta: meta }) }, SESSION_REQUEST_TIMEOUT_MS);
279
280
  acpSessionId = created.sessionId;
281
+ if (this.profile.newSession)
282
+ this.startedWith.set(options.sessionId, {
283
+ conversation: created.sessionId,
284
+ meta: configFingerprint(meta ?? {}),
285
+ });
280
286
  configOptions = created.configOptions;
281
287
  modes = created.modes;
282
288
  }
283
289
  signal.throwIfAborted();
284
290
  if (!acpSessionId)
285
291
  throw new Error("acp agent returned no session id");
292
+ // A session opens, new or resumed, on the account's default model.
293
+ const opened = selectOf(configOptions ?? [], "model");
286
294
  const session = {
287
295
  client,
288
296
  acpSessionId,
@@ -292,11 +300,17 @@ export class AcpAgent extends SessionAgent {
292
300
  resumable: resumeMethod !== undefined,
293
301
  configOptions: configOptions ?? [],
294
302
  ...(modes?.availableModes.length && { modes }),
303
+ ...(this.profile.models &&
304
+ opened && { defaultModel: defaultModel(opened, this.profile.models.offers) }),
295
305
  prompt: {
296
306
  image: Boolean(init.agentCapabilities?.promptCapabilities?.image),
297
307
  embeddedContext: Boolean(init.agentCapabilities?.promptCapabilities?.embeddedContext),
298
308
  },
309
+ servers: Object.keys(given.servers ?? {}),
299
310
  };
311
+ const tools = this.profile.tools;
312
+ if (tools)
313
+ session.describe = (call) => tools.describe(call, session.servers);
300
314
  client.setPermissionHandler((request) => answerPermission(session, request));
301
315
  client.setElicitationHandler((request) => answerElicitation(session, request));
302
316
  client.onSessionUpdate(({ sessionId, update }) => {
@@ -319,62 +333,99 @@ export class AcpAgent extends SessionAgent {
319
333
  }
320
334
  }
321
335
  /**
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.
336
+ * Select the requested model, then the thinking level, through the agent's
337
+ * config options; an agent without the option keeps its own default. A
338
+ * model the agent does not offer, or its profile does not take, fails the
339
+ * turn; a turn that names none on a profile that lists models runs the
340
+ * one its list marks default (`defaultModel`). The levels are the ones
341
+ * offered once the model is set, which are that model's, and the turn
342
+ * runs the nearest of them, as on Claude and Codex (`clampThinkingLevel`);
343
+ * a level that cannot be fitted is left alone. Returns the settings it
344
+ * left alone.
327
345
  */
328
346
  async applyConfig(session, options) {
329
- const requested = [
330
- ["model", options.model, "model"],
331
- ["thought_level", options.thinkingLevel, "thinkingLevel"],
332
- ];
333
347
  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(", ")})`);
348
+ const option = selectOf(session.configOptions, "model");
349
+ const offers = this.profile.models?.offers;
350
+ if (!option) {
351
+ if (options.model)
352
+ left.push("model");
353
+ }
354
+ else if (options.model || offers) {
355
+ const offered = selectableValues(option).filter((value) => offers?.(value) ?? true);
356
+ // @ref LLP 0016.000#an-acp-agents-model-and-thinking-level — a harness that lists its models runs only one of them
357
+ // The default the session opened on, while the agent still offers it.
358
+ const opened = session.defaultModel && offered.includes(session.defaultModel)
359
+ ? session.defaultModel
360
+ : undefined;
361
+ const model = options.model ?? opened ?? (offers && defaultModel(option, offers)) ?? option.currentValue;
362
+ if (!offered.includes(model)) {
363
+ throw new Error(`invalid request: the ${this.harness} harness does not offer model '${model}' (available: ${offered.join(", ") || "none"})`);
351
364
  }
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;
365
+ await select(session, option, model);
366
+ }
367
+ if (options.thinkingLevel) {
368
+ const option = selectOf(session.configOptions, "thought_level");
369
+ const level = option && clampThinkingLevel(options.thinkingLevel, selectableValues(option));
370
+ if (option && level !== undefined)
371
+ await select(session, option, level);
372
+ else
373
+ left.push("thinkingLevel");
354
374
  }
355
375
  return left;
356
376
  }
357
- // @ref LLP 0016.000#an-acp-agents-permission-mode — a permission mode reaches the agent, or is said not applied
377
+ // @ref LLP 0016.000#an-acp-agents-profile — what a conversation starts with it keeps
378
+ /**
379
+ * What a conversation keeps from its start (`newSession`), said not
380
+ * applied by a later turn that asks otherwise; what a conversation this
381
+ * agent did not start was given is unknown, and nothing is said.
382
+ */
383
+ keptFromStart(session, options) {
384
+ const kept = this.profile.newSession;
385
+ const started = this.startedWith.get(options.sessionId);
386
+ if (!kept || started?.conversation !== session.acpSessionId)
387
+ return [];
388
+ // Compared, not said of every later turn: a product sends the same config each turn, and that one is in effect.
389
+ return started.meta === configFingerprint(kept.meta(options) ?? {}) ? [] : [...kept.settings];
390
+ }
391
+ // @ref LLP 0016.000#an-acp-agents-permission-mode — never a turn in a mode the engine knows is not the one asked
358
392
  /**
359
393
  * 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.
394
+ * none) through `session/set_mode`, by the agent's own id for it. An agent
395
+ * with no id for the mode is put in its `default`, never left in the mode
396
+ * an earlier turn left it in, and the engine answers what it asks by the
397
+ * turn's mode (`autoDecide`), as for an agent that offers no modes; neither
398
+ * has a plan of its own to make, so `plan` does not hold there. An agent
399
+ * with no `default` either stays where it is: in a mode the engine names
400
+ * and was not asked, the turn is refused; in one it cannot name, it runs,
401
+ * and the mode is said not applied. Returns whether the mode holds.
365
402
  */
366
403
  async applyMode(session, requested) {
367
404
  const modes = session.modes;
368
405
  if (!modes)
369
406
  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 };
407
+ const names = modeNames(this.profile.modeIds);
408
+ const offered = modes.availableModes.map(({ id }) => id);
409
+ const own = names.idOf(requested, offered);
410
+ const target = own ?? names.idOf("default", offered);
411
+ if (target === undefined) {
412
+ const current = names.modeOf(modes.currentModeId);
413
+ if (current === undefined)
414
+ return false;
415
+ if (current === requested)
416
+ return true;
417
+ throw new InvalidRequestError([
418
+ {
419
+ path: "permissionMode",
420
+ message: `the ${this.harness} harness cannot run a ${requested} turn: the agent is in ${current}, and offers no mode to move it to`,
421
+ },
422
+ ]);
376
423
  }
377
- return true;
424
+ if (target !== modes.currentModeId) {
425
+ await session.client.request("session/set_mode", { sessionId: session.acpSessionId, modeId: target }, SESSION_REQUEST_TIMEOUT_MS);
426
+ session.modes = { ...modes, currentModeId: target };
427
+ }
428
+ return own !== undefined || requested !== "plan";
378
429
  }
379
430
  async *executeTurn(input, options, controller) {
380
431
  const queue = new AsyncQueue();
@@ -383,6 +434,8 @@ export class AcpAgent extends SessionAgent {
383
434
  let session;
384
435
  try {
385
436
  controller.signal.throwIfAborted();
437
+ this.profile.admit?.(options);
438
+ refuseFiles(input, this.harness, this.capabilities.files);
386
439
  session = await this.resolveSession(options, controller.signal);
387
440
  const notApplied = await this.applyConfig(session, options);
388
441
  // Sent only to an agent that takes them (`resolveSession`).
@@ -390,8 +443,8 @@ export class AcpAgent extends SessionAgent {
390
443
  notApplied.push("additionalDirectories");
391
444
  if (!(await this.applyMode(session, options.permissionMode ?? "default")))
392
445
  notApplied.push("permissionMode");
393
- if (notApplied.length)
394
- options.onExecution?.({ notApplied });
446
+ notApplied.push(...this.keptFromStart(session, options));
447
+ options.onExecution?.({ ...selected(session), ...(notApplied.length && { notApplied }) });
395
448
  controller.signal.throwIfAborted();
396
449
  session.turn = {
397
450
  broker: options.onPermissionRequest,
@@ -403,30 +456,50 @@ export class AcpAgent extends SessionAgent {
403
456
  options.onNativeSession?.(session.acpSessionId, {
404
457
  resumed: session.acpSessionId === options.resumeSessionId,
405
458
  });
459
+ // What tells its calls' servers from their tools, for the adapter's tool rules.
460
+ if (this.profile.tools)
461
+ yield { method: "agentServer/mcpServers", params: { names: session.servers } };
406
462
  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
- }));
463
+ const takes = session.prompt;
412
464
  const finishCancelled = () => {
413
465
  queue.push(CANCELLED_PROMPT_RESULT);
414
466
  queue.end();
415
467
  };
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);
468
+ const prompts = new TurnPrompts({
469
+ send: (prompt) => client.request("session/prompt", { sessionId: acpSessionId, prompt }),
470
+ ...(client.asking && { asking: client.asking }),
471
+ signal: controller.signal,
472
+ ends: {
473
+ read: (steerId) => queue.push({ method: "agentServer/steerRead", params: { steerId } }),
474
+ ended: (result) => {
475
+ this.holdSteering(options);
476
+ queue.push({ method: "session/prompt_result", params: result });
477
+ queue.end();
478
+ },
479
+ failed: (error) => {
480
+ this.holdSteering(options);
481
+ if (controller.signal.aborted)
482
+ return finishCancelled();
483
+ queue.push({ method: "error", params: { message: failureMessage(error) } });
484
+ queue.end();
485
+ },
486
+ },
420
487
  });
421
- unsubscribe.push(client.onClose((error) => {
422
- promptEnded();
488
+ unsubscribe.push(client.onSessionUpdate((notification) => {
489
+ if (notification.sessionId !== acpSessionId)
490
+ return;
491
+ // A steer the agent took is read before what it says next.
492
+ prompts.update(notification.update);
493
+ queue.push({ method: "session/update", params: notification });
494
+ }), client.onClose((error) => {
495
+ prompts.close();
423
496
  if (controller.signal.aborted)
424
497
  finishCancelled();
425
498
  else
426
499
  queue.fail(error ?? new Error("acp agent exited mid-turn"));
427
500
  }));
428
501
  const cancelPrompt = () => {
429
- // ACP semantics: session/cancel makes the in-flight prompt resolve
502
+ // ACP semantics: session/cancel makes the in-flight prompts resolve
430
503
  // with stopReason=cancelled. Bound the wait for misbehaving agents.
431
504
  void client.notify("session/cancel", { sessionId: acpSessionId }).catch(() => { });
432
505
  cancelTimer = setTimeout(() => {
@@ -443,25 +516,17 @@ export class AcpAgent extends SessionAgent {
443
516
  }
444
517
  else {
445
518
  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
- });
519
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — confirmed only when the prompts ended
520
+ this.cancelWith(options, () => prompts.settled.then(() => true));
521
+ prompts.start(toPromptBlocks(input, takes));
522
+ // @ref LLP 0016.000#an-acp-agent-steered-by-prompt — input during a turn is a prompt of its own
523
+ if (this.capabilities.steering)
524
+ await this.openSteering(options, (request) => {
525
+ if (!prompts.open || controller.signal.aborted)
526
+ return "no_active_turn";
527
+ prompts.steer(request.steerId, toPromptBlocks(request.input, takes));
528
+ return "steered";
529
+ });
465
530
  }
466
531
  for await (const event of queue) {
467
532
  yield event;
@@ -478,17 +543,31 @@ export class AcpAgent extends SessionAgent {
478
543
  for (const off of unsubscribe)
479
544
  off();
480
545
  if (session) {
546
+ // A turn that has ended asks nothing: what it left open is forgotten.
547
+ session.client.asking?.askNothing();
481
548
  session.turn = undefined;
482
549
  this.sessions.leave(options.sessionId, session);
483
550
  }
484
551
  }
485
552
  }
553
+ /** A steer's file of a kind the harness does not take is refused, as a turn's is. */
554
+ checkSteerInput(input) {
555
+ refuseFiles(input, this.harness, this.capabilities.files);
556
+ }
486
557
  async release(sessionId) {
487
558
  // The cancel aborts its turn at once; the agent is ended beside its
488
559
  // confirm window, not after it, and its exit is what confirms it.
489
560
  // An agent an eviction or a replacement ended earlier is waited for too.
490
561
  await Promise.all([super.release(sessionId), this.sessions.release(sessionId)]);
491
562
  this.host?.release(sessionId);
563
+ this.startedWith.delete(sessionId);
564
+ }
565
+ /**
566
+ * The agent's login changed (in `store`, or in every store): each session's
567
+ * next turn starts a new agent, which resumes its conversation.
568
+ */
569
+ loginChanged(store) {
570
+ this.sessions.loginChanged(store);
492
571
  }
493
572
  /** After a host resume, each session's next turn starts its agent again, on its conversation. */
494
573
  invalidateMcpConnections() {
@@ -500,3 +579,13 @@ export class AcpAgent extends SessionAgent {
500
579
  await this.host?.close();
501
580
  }
502
581
  }
582
+ /**
583
+ * The `acp` harness: any ACP v1 agent the operator launches
584
+ * (`resolveLaunch`), taken at its `initialize`'s word.
585
+ */
586
+ export class AcpAgent extends ProfiledAcpAgent {
587
+ constructor(options) {
588
+ const { resolveLaunch, ...shared } = options;
589
+ super(genericAcpProfile(resolveLaunch), shared);
590
+ }
591
+ }