stitchkit 0.129.0 → 0.130.1

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 (163) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/agent-executor/acp/v1-connect.d.ts +87 -19
  3. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  4. package/dist/agent-executor/acp/v1-driver.d.ts +4 -2
  5. package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
  6. package/dist/agent-executor/acp/v1-handlers.d.ts +56 -0
  7. package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -0
  8. package/dist/agent-executor/acp/v1-map.d.ts +13 -2
  9. package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
  10. package/dist/agent-executor/acp/v1-permission.d.ts +44 -0
  11. package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -0
  12. package/dist/agent-executor/acp/v1-protocol.d.ts +63 -10
  13. package/dist/agent-executor/acp/v1-protocol.d.ts.map +1 -1
  14. package/dist/agent-executor/acp/v1-session.d.ts +34 -7
  15. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  16. package/dist/agent-executor/acp/v1-turn.d.ts +51 -13
  17. package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
  18. package/dist/agent-executor/claude/classify.d.ts +10 -0
  19. package/dist/agent-executor/claude/classify.d.ts.map +1 -1
  20. package/dist/agent-executor/claude/cli-driver.d.ts +4 -1
  21. package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
  22. package/dist/agent-executor/claude/events.d.ts +146 -0
  23. package/dist/agent-executor/claude/events.d.ts.map +1 -0
  24. package/dist/agent-executor/claude/limits.d.ts +7 -1
  25. package/dist/agent-executor/claude/limits.d.ts.map +1 -1
  26. package/dist/agent-executor/claude/protocol.d.ts +49 -9
  27. package/dist/agent-executor/claude/protocol.d.ts.map +1 -1
  28. package/dist/agent-executor/claude/session.d.ts +2 -0
  29. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  30. package/dist/agent-executor/claude-sdk/controls.d.ts +10 -1
  31. package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -1
  32. package/dist/agent-executor/claude-sdk/driver.d.ts +97 -3
  33. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  34. package/dist/agent-executor/claude-sdk/probe.d.ts +29 -0
  35. package/dist/agent-executor/claude-sdk/probe.d.ts.map +1 -0
  36. package/dist/agent-executor/claude-sdk/query-loop.d.ts +53 -5
  37. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
  38. package/dist/agent-executor/claude-sdk/query-options.d.ts +2 -0
  39. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -1
  40. package/dist/agent-executor/claude-sdk/session.d.ts +2 -3
  41. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  42. package/dist/agent-executor/claude-sdk/turn-usage.d.ts +81 -0
  43. package/dist/agent-executor/claude-sdk/turn-usage.d.ts.map +1 -0
  44. package/dist/agent-executor/codex/classify.d.ts +4 -0
  45. package/dist/agent-executor/codex/classify.d.ts.map +1 -1
  46. package/dist/agent-executor/codex/connect.d.ts +5 -2
  47. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  48. package/dist/agent-executor/codex/control-client.d.ts +206 -0
  49. package/dist/agent-executor/codex/control-client.d.ts.map +1 -0
  50. package/dist/agent-executor/codex/driver.d.ts +35 -5
  51. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  52. package/dist/agent-executor/codex/handlers.d.ts +52 -0
  53. package/dist/agent-executor/codex/handlers.d.ts.map +1 -0
  54. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  55. package/dist/agent-executor/codex/protocol.d.ts +128 -0
  56. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  57. package/dist/agent-executor/codex/request-answers.d.ts +101 -0
  58. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -0
  59. package/dist/agent-executor/codex/session-controls.d.ts +124 -61
  60. package/dist/agent-executor/codex/session-controls.d.ts.map +1 -1
  61. package/dist/agent-executor/codex/session.d.ts +10 -36
  62. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  63. package/dist/agent-executor/codex/shared-server.d.ts +31 -0
  64. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -0
  65. package/dist/agent-executor/codex/shared-thread.d.ts +46 -0
  66. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -0
  67. package/dist/agent-executor/codex/thread-controls.d.ts +144 -0
  68. package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -0
  69. package/dist/agent-executor/codex/thread-open.d.ts +66 -0
  70. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -0
  71. package/dist/agent-executor/codex/turn-input.d.ts +47 -0
  72. package/dist/agent-executor/codex/turn-input.d.ts.map +1 -0
  73. package/dist/agent-executor/contract.d.ts +77 -0
  74. package/dist/agent-executor/contract.d.ts.map +1 -1
  75. package/dist/agent-executor/engine.d.ts +6 -2
  76. package/dist/agent-executor/engine.d.ts.map +1 -1
  77. package/dist/agent-executor/executor-contract.d.ts +54 -0
  78. package/dist/agent-executor/executor-contract.d.ts.map +1 -1
  79. package/dist/agent-executor/handoff-schemas.d.ts +407 -0
  80. package/dist/agent-executor/handoff-schemas.d.ts.map +1 -0
  81. package/dist/agent-executor/handoff.d.ts +12 -0
  82. package/dist/agent-executor/handoff.d.ts.map +1 -0
  83. package/dist/agent-executor/hello.d.ts +72 -0
  84. package/dist/agent-executor/hello.d.ts.map +1 -1
  85. package/dist/agent-executor/image-input.d.ts +22 -0
  86. package/dist/agent-executor/image-input.d.ts.map +1 -1
  87. package/dist/agent-executor/projection.d.ts +2 -2
  88. package/dist/agent-executor/projection.d.ts.map +1 -1
  89. package/dist/agent-executor/session-primitives.d.ts +10 -1
  90. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  91. package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
  92. package/dist/agent-executor/testing/replay-driver.d.ts +41 -0
  93. package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -0
  94. package/dist/agent-executor/testing/replay-gate.d.ts +11 -0
  95. package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -0
  96. package/dist/agent-executor/testing/replay-runner.d.ts +27 -0
  97. package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -0
  98. package/dist/agent-executor/testing/replay-scenarios.d.ts +21 -0
  99. package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -0
  100. package/dist/agent-executor/testing/replay-transcript.d.ts +296 -0
  101. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -0
  102. package/dist/agent-executor/vocabulary.d.ts +135 -0
  103. package/dist/agent-executor/vocabulary.d.ts.map +1 -1
  104. package/dist/agent-runtime/branch-observations.d.ts +18 -18
  105. package/dist/agent-runtime/branch-provider.d.ts +2 -2
  106. package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
  107. package/dist/agent-runtime/sql-rows.d.ts +10 -10
  108. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
  109. package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
  110. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  111. package/dist/entrypoints/agent-executor/acp.d.ts +4 -1
  112. package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
  113. package/dist/entrypoints/agent-executor/acp.js +847 -214
  114. package/dist/entrypoints/agent-executor/claude-sdk.d.ts +5 -1
  115. package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
  116. package/dist/entrypoints/agent-executor/claude-sdk.js +713 -205
  117. package/dist/entrypoints/agent-executor/claude.js +44 -19
  118. package/dist/entrypoints/agent-executor/codex.d.ts +10 -2
  119. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  120. package/dist/entrypoints/agent-executor/codex.js +2269 -600
  121. package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
  122. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
  123. package/dist/entrypoints/agent-executor/testing.js +1002 -2
  124. package/dist/entrypoints/agent-executor.d.ts +4 -2
  125. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  126. package/dist/entrypoints/agent-executor.js +411 -23
  127. package/dist/entrypoints/agent-runtime.js +4 -23
  128. package/dist/entrypoints/tools/mcp.d.ts +1 -0
  129. package/dist/entrypoints/tools/mcp.d.ts.map +1 -1
  130. package/dist/entrypoints/tools/mcp.js +1 -1
  131. package/dist/entrypoints/tools/toolkit.js +1 -1
  132. package/dist/{index-wv2amqm4.js → index-2s8sy57y.js} +36 -103
  133. package/dist/{index-afb6z77w.js → index-dbp6xemn.js} +75 -7
  134. package/dist/{index-bjmj2q1z.js → index-jrn3prgm.js} +1 -1
  135. package/dist/index-kne9g2c5.js +30 -0
  136. package/dist/index-p1qmpq0p.js +1300 -0
  137. package/dist/{index-7jqn3b3g.js → index-v759mzed.js} +152 -2
  138. package/dist/{index-cbhxhma2.js → index-x5ayy5bn.js} +1 -0
  139. package/dist/index-y0a4gt1s.js +142 -0
  140. package/dist/tools/internal/rank-tools.d.ts +10 -0
  141. package/dist/tools/internal/rank-tools.d.ts.map +1 -0
  142. package/dist/tools/mcp/handler.d.ts +7 -3
  143. package/dist/tools/mcp/handler.d.ts.map +1 -1
  144. package/dist/tools/mcp/lazy-discovery.d.ts +47 -0
  145. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -0
  146. package/dist/tools/mcp/mount.d.ts +7 -0
  147. package/dist/tools/mcp/mount.d.ts.map +1 -1
  148. package/dist/tools/mcp/register.d.ts +2 -2
  149. package/dist/tools/mcp/register.d.ts.map +1 -1
  150. package/llms/agent-executor-acp.txt +7 -8
  151. package/llms/agent-executor-claude-sdk.txt +4 -2
  152. package/llms/agent-executor-codex.txt +8 -4
  153. package/llms/agent-executor-testing.txt +5 -1
  154. package/llms/agent-executor.txt +7 -6
  155. package/llms/stitchkit.txt +74 -74
  156. package/llms/tools-mcp.txt +3 -2
  157. package/llms/tools.txt +24 -0
  158. package/llms/{upgrading-0.128.0-0.129.0.txt → upgrading-0.128.0-0.130.0.txt} +30 -3
  159. package/llms/upgrading.txt +1 -1
  160. package/llms-full.txt +159 -97
  161. package/llms.txt +8 -8
  162. package/package.json +1 -1
  163. package/dist/index-y71zn1gw.js +0 -586
@@ -1,9 +1,11 @@
1
1
  import"../../index-2rf33y2h.js";
2
2
  import {
3
+ ExecutorThreadDispositionSchema2,
4
+ ExecutorErrorKindSchema2,
3
5
  InteractionReplySchema2,
4
6
  engineProfile,
5
7
  engineEnvironment2
6
- } from "../../index-afb6z77w.js";
8
+ } from "../../index-dbp6xemn.js";
7
9
  import"../../index-09f7w2qq.js";
8
10
  import {
9
11
  NativeCommandError2
@@ -17,21 +19,26 @@ import {
17
19
  sessionAbort,
18
20
  stopConnection,
19
21
  withEphemeralConnection,
20
- DEFAULT_MAX_IMAGE_BYTES,
21
- validateImageOptions,
22
- bytesToBase64,
23
- resolveImageBytes,
22
+ safeJsonValue,
23
+ invokeSafely,
24
+ emitStartupPhase,
24
25
  holdEngineRequest,
25
26
  answerEngineRequest,
26
27
  drainEngineRequests,
27
28
  endEngineTurn,
28
29
  loseEngineTurn
29
- } from "../../index-wv2amqm4.js";
30
+ } from "../../index-2s8sy57y.js";
30
31
  import {
31
32
  JsonRpcError2,
32
33
  JSON_RPC_METHOD_NOT_FOUND2,
33
34
  createJsonRpcPeer2
34
35
  } from "../../index-1q0n6zek.js";
36
+ import {
37
+ DEFAULT_MAX_IMAGE_BYTES,
38
+ validateImageOptions,
39
+ bytesToBase64,
40
+ resolveImageBytes
41
+ } from "../../index-y0a4gt1s.js";
35
42
  import"../../index-pzhqydxb.js";
36
43
  import {
37
44
  spawnEngineProcess2
@@ -159,10 +166,73 @@ var acpFakeScenarios = {
159
166
  unknownRecord: () => steps(update({ sessionUpdate: "an_update_from_the_future" }), answer({ stopReason: "end_turn" })),
160
167
  crash: () => steps(chunk("dying "), { do: "crash" })
161
168
  };
169
+ // src/agent-executor/acp/v1-connect.ts
170
+ import { z as z2 } from "zod";
171
+
162
172
  // src/agent-executor/acp/v1-protocol.ts
163
173
  import { z } from "zod";
164
174
  var ACP_PROTOCOL_VERSION = 1;
165
- var CapabilitySchema = z.union([z.boolean(), z.looseObject({})]).optional();
175
+ var ACP_V1_AGENT_METHODS = z.enum([
176
+ "initialize",
177
+ "session/new",
178
+ "session/load",
179
+ "session/resume",
180
+ "session/list",
181
+ "session/close",
182
+ "session/delete",
183
+ "session/prompt",
184
+ "session/cancel",
185
+ "session/set_config_option",
186
+ "session/set_model"
187
+ ]).options;
188
+ var ACP_V1_CLIENT_METHODS = z.enum([
189
+ "session/update",
190
+ "session/request_permission"
191
+ ]).options;
192
+ var ACP_V1_UPDATE_KINDS = z.enum([
193
+ "user_message_chunk",
194
+ "agent_message_chunk",
195
+ "agent_thought_chunk",
196
+ "tool_call",
197
+ "tool_call_update",
198
+ "plan",
199
+ "plan_update",
200
+ "plan_removed",
201
+ "available_commands_update",
202
+ "current_mode_update",
203
+ "config_option_update",
204
+ "session_info_update",
205
+ "usage_update",
206
+ "compaction_update",
207
+ "compaction_summary_chunk"
208
+ ]).options;
209
+ var ACP_V1_PERMISSION_OPTION_KINDS = z.enum([
210
+ "allow_once",
211
+ "allow_always",
212
+ "reject_once",
213
+ "reject_always"
214
+ ]).options;
215
+ var ACP_V1_STOP_REASONS = z.enum([
216
+ "end_turn",
217
+ "max_tokens",
218
+ "max_turn_requests",
219
+ "refusal",
220
+ "cancelled"
221
+ ]).options;
222
+ var ACP_V1_USAGE_FIELDS = z.enum([
223
+ "inputTokens",
224
+ "outputTokens",
225
+ "cachedReadTokens",
226
+ "cachedWriteTokens",
227
+ "thoughtTokens",
228
+ "totalTokens"
229
+ ]).options;
230
+ var AcpClientInfoSchema = z.strictObject({
231
+ name: z.string().min(1),
232
+ version: z.string().min(1),
233
+ title: z.string().min(1).optional()
234
+ });
235
+ var CapabilitySchema = z.union([z.boolean(), z.looseObject({})]).nullish();
166
236
  var AcpInitializeResultSchema = z.looseObject({
167
237
  protocolVersion: z.int(),
168
238
  agentCapabilities: z.looseObject({
@@ -172,10 +242,15 @@ var AcpInitializeResultSchema = z.looseObject({
172
242
  resume: CapabilitySchema,
173
243
  load: CapabilitySchema,
174
244
  list: CapabilitySchema,
175
- close: CapabilitySchema
245
+ close: CapabilitySchema,
246
+ delete: CapabilitySchema
176
247
  }).optional()
177
248
  }).optional(),
178
- agentInfo: z.looseObject({ name: z.string().optional(), version: z.string().optional() }).optional(),
249
+ agentInfo: z.looseObject({
250
+ name: z.string().optional(),
251
+ title: z.string().nullish(),
252
+ version: z.string().optional()
253
+ }).nullish(),
179
254
  authMethods: z.array(z.looseObject({ id: z.string() })).optional()
180
255
  });
181
256
  var ChoiceSchema = z.looseObject({ value: z.string(), name: z.string().optional() });
@@ -259,13 +334,23 @@ var AcpUpdateNotificationSchema = z.looseObject({
259
334
  sessionId: z.string(),
260
335
  update: AcpSessionUpdateSchema
261
336
  });
337
+ var AcpPromptUsageSchema = z.looseObject({
338
+ inputTokens: z.int().nonnegative().nullish(),
339
+ outputTokens: z.int().nonnegative().nullish(),
340
+ cachedReadTokens: z.int().nonnegative().nullish(),
341
+ cachedWriteTokens: z.int().nonnegative().nullish(),
342
+ thoughtTokens: z.int().nonnegative().nullish(),
343
+ totalTokens: z.int().nonnegative().nullish()
344
+ });
262
345
  var AcpPromptResultSchema = z.looseObject({
263
346
  stopReason: z.string(),
264
- usage: z.looseObject({
265
- inputTokens: z.int().nonnegative().nullish(),
266
- outputTokens: z.int().nonnegative().nullish(),
267
- cachedReadTokens: z.int().nonnegative().nullish()
268
- }).nullish()
347
+ usage: AcpPromptUsageSchema.nullish()
348
+ });
349
+ var AcpPermissionOptionSchema = z.looseObject({
350
+ optionId: z.string(),
351
+ kind: z.string(),
352
+ name: z.string().optional(),
353
+ _meta: z.record(z.string(), z.json()).nullish()
269
354
  });
270
355
  var AcpPermissionRequestSchema = z.looseObject({
271
356
  sessionId: z.string(),
@@ -273,22 +358,57 @@ var AcpPermissionRequestSchema = z.looseObject({
273
358
  toolCallId: z.string(),
274
359
  title: z.string().nullish(),
275
360
  name: z.string().optional(),
361
+ kind: z.string().optional(),
276
362
  rawInput: z.json().optional(),
277
363
  args: z.json().optional()
278
364
  }),
279
- options: z.array(z.looseObject({ optionId: z.string(), kind: z.string() }))
365
+ options: z.array(AcpPermissionOptionSchema)
280
366
  });
281
367
 
282
368
  // src/agent-executor/acp/v1-connect.ts
283
369
  var DEFAULT_REQUEST_TIMEOUT_MS = 60000;
284
370
  var CLOSE_REQUEST_TIMEOUT_MS = 5000;
371
+ var MAX_PASSIVE_VERSION_LENGTH = 256;
372
+ var SessionMetaRecordSchema = z2.record(z2.string(), z2.json());
285
373
  function closeRequestTimeoutMs(config) {
286
374
  return Math.min(config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS, CLOSE_REQUEST_TIMEOUT_MS);
287
375
  }
376
+ function validateSessionMetaObject(meta) {
377
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) {
378
+ throw new TypeError("sessionMeta must be a plain JSON object");
379
+ }
380
+ return SessionMetaRecordSchema.parse(safeJsonValue(meta));
381
+ }
382
+ function resolveAcpSessionMeta(sessionMeta, initialized) {
383
+ if (sessionMeta === undefined)
384
+ return;
385
+ const resolved = typeof sessionMeta === "function" ? sessionMeta(initialized) : sessionMeta;
386
+ if (resolved === undefined)
387
+ return;
388
+ return validateSessionMetaObject(resolved);
389
+ }
288
390
  function assertAcpDriverOptions(config) {
289
391
  assertTimerMs("requestTimeoutMs", config.requestTimeoutMs);
290
392
  assertPositiveSafeInteger("maxFrameBytes", config.maxFrameBytes);
291
393
  assertPositiveSafeInteger("maxImageBytes", config.maxImageBytes);
394
+ if (config.probeMode !== undefined && config.probeMode !== "ephemeral-session" && config.probeMode !== "initialize-only" && config.probeMode !== "passive") {
395
+ throw new TypeError(`Invalid probeMode ${JSON.stringify(config.probeMode)}`);
396
+ }
397
+ if (config.passiveVersion !== undefined) {
398
+ const trimmed = config.passiveVersion.trim();
399
+ if (trimmed.length === 0 || trimmed.length > MAX_PASSIVE_VERSION_LENGTH) {
400
+ throw new TypeError(`passiveVersion must be a non-empty string up to ${MAX_PASSIVE_VERSION_LENGTH} characters`);
401
+ }
402
+ }
403
+ if (config.steerMode !== undefined && config.steerMode !== "none" && config.steerMode !== "prompt") {
404
+ throw new TypeError(`Invalid steerMode ${JSON.stringify(config.steerMode)}`);
405
+ }
406
+ if (config.clientInfo !== undefined) {
407
+ AcpClientInfoSchema.parse(config.clientInfo);
408
+ }
409
+ if (config.sessionMeta !== undefined && typeof config.sessionMeta !== "function") {
410
+ validateSessionMetaObject(config.sessionMeta);
411
+ }
292
412
  }
293
413
  async function connectAcp(config, profile, cwd, signal, handlers = {}) {
294
414
  assertAcpDriverOptions(config);
@@ -300,6 +420,7 @@ async function connectAcp(config, profile, cwd, signal, handlers = {}) {
300
420
  ...handlers.onRequest && { onRequest: handlers.onRequest },
301
421
  ...handlers.onNotification && { onNotification: handlers.onNotification }
302
422
  });
423
+ emitStartupPhase(handlers.onStartupPhase, "spawning");
303
424
  const engine = spawnEngineProcess2({
304
425
  executable: config.executable,
305
426
  args: [...config.args ?? []],
@@ -310,8 +431,12 @@ async function connectAcp(config, profile, cwd, signal, handlers = {}) {
310
431
  });
311
432
  const reading = (async () => {
312
433
  try {
313
- for await (const line of engine.lines)
434
+ for await (const line of engine.lines) {
435
+ if (config.stdoutLineFilter !== undefined && !config.stdoutLineFilter(line)) {
436
+ continue;
437
+ }
314
438
  peer.receive(line);
439
+ }
315
440
  const ended = new Error(`The ACP agent ${config.executable} exited: ${engine.stderrTail().slice(-2000)}`);
316
441
  peer.close(ended);
317
442
  handlers.onEnd?.(ended);
@@ -327,15 +452,22 @@ async function connectAcp(config, profile, cwd, signal, handlers = {}) {
327
452
  }
328
453
  })();
329
454
  try {
330
- const initialized = AcpInitializeResultSchema.parse(await peer.request("initialize", {
455
+ emitStartupPhase(handlers.onStartupPhase, "initializing");
456
+ const clientInfo = config.clientInfo !== undefined ? AcpClientInfoSchema.parse(config.clientInfo) : undefined;
457
+ const rawInitialized = await peer.request("initialize", {
331
458
  protocolVersion: ACP_PROTOCOL_VERSION,
332
459
  clientCapabilities: {
333
460
  fs: { readTextFile: false, writeTextFile: false },
334
461
  terminal: false
335
- }
336
- }));
337
- if (initialized.protocolVersion !== ACP_PROTOCOL_VERSION) {
338
- throw new Error(`The ACP agent speaks protocol ${initialized.protocolVersion}; this driver speaks ${ACP_PROTOCOL_VERSION}`);
462
+ },
463
+ ...clientInfo !== undefined && { clientInfo }
464
+ });
465
+ if (typeof rawInitialized === "object" && rawInitialized !== null && !Array.isArray(rawInitialized) && "info" in rawInitialized) {
466
+ throw new Error(`The ACP agent speaks protocol v2 (initialize response has "info"); this driver speaks ACP v${ACP_PROTOCOL_VERSION}`);
467
+ }
468
+ const initialized = AcpInitializeResultSchema.parse(rawInitialized);
469
+ if (initialized.protocolVersion < ACP_PROTOCOL_VERSION) {
470
+ throw new Error(`The ACP agent speaks protocol ${initialized.protocolVersion}; this driver requires protocol >= ${ACP_PROTOCOL_VERSION}`);
339
471
  }
340
472
  return { engine, peer, reading, initialized };
341
473
  } catch (error) {
@@ -345,11 +477,11 @@ async function connectAcp(config, profile, cwd, signal, handlers = {}) {
345
477
  }
346
478
  function acpCan(connection, capability) {
347
479
  const value = connection.initialized.agentCapabilities?.sessionCapabilities?.[capability];
348
- return value !== undefined && value !== false;
480
+ return value !== undefined && value !== null && value !== false;
349
481
  }
350
482
 
351
483
  // src/agent-executor/acp/v1-map.ts
352
- import { z as z2 } from "zod";
484
+ import { z as z3 } from "zod";
353
485
  var ACP_AUTH_REQUIRED_CODE = -32000;
354
486
  var ACP_RATE_LIMIT_RE = /(?<![A-Za-z0-9])(?:rate[-_ ]?limit(?:ed|ing|s)?|quota|too many requests|429)(?![A-Za-z0-9])/i;
355
487
  var ACP_AUTH_RE = /(?<![A-Za-z0-9])(?:auth(?:enticat\w*|oriz\w*)?|login|log in|logged in|unauthori\w*|unauthenticat\w*|401)(?![A-Za-z0-9])/i;
@@ -369,7 +501,11 @@ var QUIET = new Set([
369
501
  "config_option_update",
370
502
  "session_info_update",
371
503
  "current_mode_update",
372
- "plan"
504
+ "plan",
505
+ "plan_update",
506
+ "plan_removed",
507
+ "compaction_update",
508
+ "compaction_summary_chunk"
373
509
  ]);
374
510
  function text(update) {
375
511
  const content = update.content;
@@ -435,7 +571,7 @@ function mapAcpUpdate(update, turnId, chunk, track) {
435
571
  callId,
436
572
  toolName,
437
573
  outcome: update.status === "completed" ? "success" : "error",
438
- ...output !== undefined && { output: z2.json().parse(output) }
574
+ ...output !== undefined && { output: z3.json().parse(output) }
439
575
  }
440
576
  ];
441
577
  }
@@ -472,6 +608,43 @@ function acpOutcome(stopReason, interruptRequested) {
472
608
  return "interrupted";
473
609
  return stopReason === "end_turn" ? "completed" : "failed";
474
610
  }
611
+ function normalizeAcpUsage(usage, options = {}) {
612
+ const cachedRead = usage.cachedReadTokens ?? undefined;
613
+ const inputTokens = usage.inputTokens != null ? options.usageInputIncludesCachedRead === false && cachedRead !== undefined ? usage.inputTokens + cachedRead : usage.inputTokens : undefined;
614
+ return {
615
+ ...inputTokens !== undefined && { inputTokens },
616
+ ...usage.outputTokens != null && { outputTokens: usage.outputTokens },
617
+ ...cachedRead !== undefined && { cachedInputTokens: cachedRead },
618
+ ...usage.cachedWriteTokens != null && {
619
+ cacheCreationInputTokens: usage.cachedWriteTokens
620
+ },
621
+ ...usage.thoughtTokens != null && { thinkingTokens: usage.thoughtTokens },
622
+ ...usage.totalTokens != null && { totalTokens: usage.totalTokens }
623
+ };
624
+ }
625
+ function sumOptionalCount(left, right) {
626
+ if (left === undefined && right === undefined)
627
+ return;
628
+ return (left ?? 0) + (right ?? 0);
629
+ }
630
+ function addAcpTokenUsage(total, next) {
631
+ if (total === undefined)
632
+ return next;
633
+ const inputTokens = sumOptionalCount(total.inputTokens, next.inputTokens);
634
+ const outputTokens = sumOptionalCount(total.outputTokens, next.outputTokens);
635
+ const cachedInputTokens = sumOptionalCount(total.cachedInputTokens, next.cachedInputTokens);
636
+ const cacheCreationInputTokens = sumOptionalCount(total.cacheCreationInputTokens, next.cacheCreationInputTokens);
637
+ const thinkingTokens = sumOptionalCount(total.thinkingTokens, next.thinkingTokens);
638
+ const totalTokens = sumOptionalCount(total.totalTokens, next.totalTokens);
639
+ return {
640
+ ...inputTokens !== undefined && { inputTokens },
641
+ ...outputTokens !== undefined && { outputTokens },
642
+ ...cachedInputTokens !== undefined && { cachedInputTokens },
643
+ ...cacheCreationInputTokens !== undefined && { cacheCreationInputTokens },
644
+ ...thinkingTokens !== undefined && { thinkingTokens },
645
+ ...totalTokens !== undefined && { totalTokens }
646
+ };
647
+ }
475
648
  async function acpPromptBlocks(parts, limits) {
476
649
  validateImageOptions(limits);
477
650
  for (const part of parts) {
@@ -508,50 +681,385 @@ async function acpPromptBlocks(parts, limits) {
508
681
  return blocks;
509
682
  }
510
683
 
511
- // src/agent-executor/acp/v1-turn.ts
684
+ // src/agent-executor/acp/v1-permission.ts
685
+ import { z as z4 } from "zod";
512
686
  var ACP_CANCELLED = { outcome: { outcome: "cancelled" } };
687
+ var AcpOptionSelectionInputSchema = z4.strictObject({
688
+ optionId: z4.string().min(1)
689
+ });
690
+ function isPlainJsonRecord(value) {
691
+ return typeof value === "object" && value !== null && !Array.isArray(value);
692
+ }
693
+ function buildAcpPermissionDeltaFields(asked) {
694
+ const callId = nonEmptyString(asked.toolCall.toolCallId);
695
+ const title = nonEmptyString(asked.toolCall.title);
696
+ const toolName = nonEmptyString(asked.toolCall.name) ?? title ?? "tool";
697
+ const toolInput = asked.toolCall.rawInput ?? asked.toolCall.args;
698
+ const options = asked.options.map((option) => ({
699
+ optionId: option.optionId,
700
+ kind: option.kind,
701
+ ...option.name !== undefined && { name: option.name },
702
+ ...option._meta !== undefined && option._meta !== null && { _meta: option._meta }
703
+ }));
704
+ let inputPayload;
705
+ if (isPlainJsonRecord(toolInput)) {
706
+ inputPayload = "options" in toolInput ? { ...toolInput, rawInput: toolInput, options } : { ...toolInput, options };
707
+ } else if (toolInput !== undefined) {
708
+ inputPayload = { rawInput: toolInput, options };
709
+ } else {
710
+ inputPayload = { options };
711
+ }
712
+ return {
713
+ ...callId !== undefined && { callId },
714
+ toolName,
715
+ input: safeJsonValue(inputPayload),
716
+ ...title !== undefined && { prompt: title }
717
+ };
718
+ }
719
+ function buildAcpPermissionAnswer(detail, rawReply) {
720
+ const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
721
+ if (reply.kind === "input") {
722
+ const selected = AcpOptionSelectionInputSchema.safeParse(reply.value);
723
+ if (!selected.success) {
724
+ throw new TypeError("An ACP input reply must carry { optionId: string } matching one of the offered options");
725
+ }
726
+ const option = detail.options.find((candidate) => candidate.optionId === selected.data.optionId);
727
+ if (option === undefined) {
728
+ throw new TypeError(`The ACP permission request offered no option with optionId ${JSON.stringify(selected.data.optionId)}`);
729
+ }
730
+ return { outcome: { outcome: "selected", optionId: option.optionId } };
731
+ }
732
+ if (reply.kind === "approve") {
733
+ if (reply.updatedInput !== undefined) {
734
+ throw new TypeError("The ACP driver does not support rewriting tool input (updatedInput)");
735
+ }
736
+ if (reply.scope === "session") {
737
+ const always = detail.options.find((candidate) => candidate.kind === "allow_always");
738
+ if (always === undefined) {
739
+ throw new TypeError("The ACP permission request offered no allow_always option for session-scoped approval");
740
+ }
741
+ return { outcome: { outcome: "selected", optionId: always.optionId } };
742
+ }
743
+ const option = detail.options.find((candidate) => candidate.kind === "allow_once") ?? detail.options.find((candidate) => candidate.kind.startsWith("allow"));
744
+ if (option === undefined)
745
+ throw new TypeError("The agent offered no allow option");
746
+ return { outcome: { outcome: "selected", optionId: option.optionId } };
747
+ }
748
+ if (reply.interrupt === true) {
749
+ throw new TypeError("The ACP driver does not support turn-cancelling approval denials; call interrupt() instead");
750
+ }
751
+ const option = detail.options.find((candidate) => candidate.kind === "reject_once") ?? detail.options.find((candidate) => candidate.kind.startsWith("reject"));
752
+ if (option === undefined)
753
+ throw new TypeError("The agent offered no reject option");
754
+ return { outcome: { outcome: "selected", optionId: option.optionId } };
755
+ }
756
+ function answerActiveAcpTurnRequest(turn, interactionId, rawReply) {
757
+ const waiting = turn.pending.get(interactionId);
758
+ if (waiting === undefined) {
759
+ throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
760
+ }
761
+ const answer = buildAcpPermissionAnswer(waiting.detail, rawReply);
762
+ answerEngineRequest(turn, interactionId, answer);
763
+ }
764
+ function answerAcpSessionRequest(input) {
765
+ if (input.turn?.pending.has(input.interactionId)) {
766
+ answerActiveAcpTurnRequest(input.turn, input.interactionId, input.reply);
767
+ return;
768
+ }
769
+ const external = input.externalPending.get(input.interactionId);
770
+ if (external === undefined || input.expectedEntry !== undefined && external !== input.expectedEntry) {
771
+ throw new TypeError(`Unknown interaction ${input.interactionId} for this ACP session`);
772
+ }
773
+ const answer = buildAcpPermissionAnswer(external.detail, input.reply);
774
+ input.externalPending.delete(input.interactionId);
775
+ external.resolve(answer);
776
+ }
777
+
778
+ // src/agent-executor/acp/v1-handlers.ts
779
+ var JSON_RPC_INTERNAL_ERROR = -32603;
780
+ var MAX_EXTERNAL_PENDING_REQUESTS = 256;
781
+ function normalizeTransformedUpdates(raw, transform) {
782
+ if (transform === undefined)
783
+ return [raw];
784
+ const result = transform(raw);
785
+ if (result === null || result === undefined)
786
+ return [];
787
+ if (Array.isArray(result)) {
788
+ return result.map((entry) => AcpSessionUpdateSchema.parse(entry));
789
+ }
790
+ return [AcpSessionUpdateSchema.parse(result)];
791
+ }
792
+ function handleAcpNotification(state, externalState, method, params) {
793
+ const turn = state.getTurn();
794
+ if (method !== "session/update") {
795
+ if (turn !== undefined) {
796
+ turn.chunk += 1;
797
+ offerTurnDelta(turn.channel, {
798
+ type: "error",
799
+ turnId: turn.state.turnId,
800
+ itemId: `unhandled:${method}:${turn.chunk}`,
801
+ raw: { source: "acp", type: method },
802
+ kind: "unhandled",
803
+ message: `ACP notification ${method} is not known to this driver`
804
+ });
805
+ }
806
+ return;
807
+ }
808
+ const parsed = AcpUpdateNotificationSchema.safeParse(params);
809
+ if (!parsed.success) {
810
+ if (turn !== undefined) {
811
+ turn.chunk += 1;
812
+ offerTurnDelta(turn.channel, {
813
+ type: "error",
814
+ turnId: turn.state.turnId,
815
+ itemId: `unhandled:session/update:${turn.chunk}`,
816
+ raw: { source: "acp", type: method },
817
+ kind: "unhandled",
818
+ message: `ACP update did not match schema: ${parsed.error.message}`
819
+ });
820
+ }
821
+ return;
822
+ }
823
+ let updates;
824
+ try {
825
+ updates = normalizeTransformedUpdates(parsed.data.update, state.transformUpdate);
826
+ } catch (error) {
827
+ if (turn !== undefined) {
828
+ turn.chunk += 1;
829
+ offerTurnDelta(turn.channel, {
830
+ type: "error",
831
+ turnId: turn.state.turnId,
832
+ itemId: `unhandled:session/update:${turn.chunk}`,
833
+ raw: { source: "acp", type: method },
834
+ kind: "unhandled",
835
+ message: `ACP transformUpdate failed: ${error instanceof Error ? error.message : String(error)}`
836
+ });
837
+ }
838
+ return;
839
+ }
840
+ const opened = state.isOpened();
841
+ for (const update of updates) {
842
+ state.onSessionMeta({
843
+ ...update.configOptions !== undefined && { configOptions: update.configOptions },
844
+ ...update.sessionUpdate === "session_info_update" && typeof update.title === "string" && { title: update.title },
845
+ ...update.availableCommands !== undefined && {
846
+ commands: update.availableCommands.map((command) => command.name)
847
+ }
848
+ });
849
+ let deltas = [];
850
+ if (turn !== undefined) {
851
+ turn.chunk += 1;
852
+ deltas = mapAcpUpdate(update, turn.state.turnId, turn.chunk, turn.track);
853
+ for (const delta of deltas)
854
+ offerTurnDelta(turn.channel, delta);
855
+ } else if (opened && state.onUpdate !== undefined) {
856
+ externalState.chunk += 1;
857
+ deltas = mapAcpUpdate(update, "external", externalState.chunk, externalState.track);
858
+ }
859
+ if (opened && state.onUpdate !== undefined) {
860
+ const event = {
861
+ sessionId: parsed.data.sessionId,
862
+ update,
863
+ duringActiveTurn: turn !== undefined,
864
+ deltas
865
+ };
866
+ invokeSafely(() => state.onUpdate?.(event));
867
+ }
868
+ }
869
+ }
870
+ function handleAcpRequest(state, method, params, id) {
871
+ const turn = state.getTurn();
872
+ if (method !== "session/request_permission") {
873
+ if (turn !== undefined) {
874
+ offerTurnDelta(turn.channel, {
875
+ type: "error",
876
+ turnId: turn.state.turnId,
877
+ itemId: `unhandled-request:${id}`,
878
+ raw: { source: "acp", type: method },
879
+ kind: "unhandled",
880
+ message: `ACP request ${method} is not known to this driver; refused`
881
+ });
882
+ }
883
+ throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
884
+ }
885
+ const interactionId = String(id);
886
+ if (turn !== undefined) {
887
+ const asked = AcpPermissionRequestSchema.parse(params);
888
+ const fields = buildAcpPermissionDeltaFields(asked);
889
+ return new Promise((resolve) => {
890
+ holdEngineRequest(turn, {
891
+ interactionId,
892
+ detail: { options: asked.options },
893
+ answeredBy: { source: "acp", type: method },
894
+ delta: () => ({
895
+ type: "request",
896
+ turnId: turn.state.turnId,
897
+ itemId: `request:${interactionId}`,
898
+ raw: { source: "acp", type: method },
899
+ interactionId,
900
+ kind: "approval",
901
+ ...fields
902
+ }),
903
+ refusal: ACP_CANCELLED,
904
+ resolve
905
+ });
906
+ });
907
+ }
908
+ const observer = state.onPermissionRequest;
909
+ if (observer === undefined || !state.isOpened()) {
910
+ throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
911
+ }
912
+ if (state.externalPending.size >= MAX_EXTERNAL_PENDING_REQUESTS) {
913
+ throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Too many pending external ACP permission requests (limit ${MAX_EXTERNAL_PENDING_REQUESTS})`);
914
+ }
915
+ if (state.externalPending.has(interactionId)) {
916
+ throw new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, `Duplicate pending external ACP permission request ${interactionId}`);
917
+ }
918
+ const asked = AcpPermissionRequestSchema.parse(params);
919
+ const delta = {
920
+ type: "request",
921
+ turnId: "external",
922
+ itemId: `request:${interactionId}`,
923
+ raw: { source: "acp", type: method },
924
+ interactionId,
925
+ kind: "approval",
926
+ ...buildAcpPermissionDeltaFields(asked)
927
+ };
928
+ return new Promise((resolve, reject) => {
929
+ const entry = { detail: { options: asked.options }, resolve };
930
+ state.externalPending.set(interactionId, entry);
931
+ const onObserverError = (error) => {
932
+ if (state.externalPending.get(interactionId) !== entry)
933
+ return;
934
+ state.externalPending.delete(interactionId);
935
+ if (error instanceof JsonRpcError2)
936
+ reject(error);
937
+ else
938
+ resolve(ACP_CANCELLED);
939
+ };
940
+ try {
941
+ const outcome = observer({
942
+ interactionId,
943
+ sessionId: asked.sessionId,
944
+ request: asked,
945
+ delta,
946
+ async respond(reply) {
947
+ answerAcpSessionRequest({
948
+ turn: undefined,
949
+ externalPending: state.externalPending,
950
+ expectedEntry: entry,
951
+ interactionId,
952
+ reply
953
+ });
954
+ }
955
+ });
956
+ if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
957
+ Promise.resolve(outcome).catch(onObserverError);
958
+ }
959
+ } catch (error) {
960
+ onObserverError(error);
961
+ }
962
+ });
963
+ }
964
+ function createAcpHandlers(state) {
965
+ const externalState = {
966
+ chunk: 0,
967
+ track: { segment: 0, toolNames: new Map }
968
+ };
969
+ return {
970
+ onNotification: (method, params) => handleAcpNotification(state, externalState, method, params),
971
+ onRequest: (method, params, id) => handleAcpRequest(state, method, params, id),
972
+ onEnd: state.onEnd
973
+ };
974
+ }
975
+
976
+ // src/agent-executor/acp/v1-turn.ts
977
+ import { z as z5 } from "zod";
978
+ var AcpPromptOutcomeOverrideSchema = z5.strictObject({
979
+ outcome: z5.literal("failed").optional(),
980
+ errorKind: ExecutorErrorKindSchema2,
981
+ message: z5.string().min(1),
982
+ threadDisposition: ExecutorThreadDispositionSchema2.optional()
983
+ });
513
984
  function newAcpTurn(turnId) {
514
985
  return {
515
986
  state: { turnId, interruptRequested: false },
516
987
  channel: createTurnDeltaChannel(),
517
988
  pending: new Map,
518
989
  chunk: 0,
519
- track: { segment: 0, toolNames: new Map }
990
+ track: { segment: 0, toolNames: new Map },
991
+ promptGeneration: 1,
992
+ accumulatedUsage: undefined,
993
+ settled: false
520
994
  };
521
995
  }
522
- function runAcpPrompt(peer, sessionId, prompt, turn, done) {
523
- peer.request("session/prompt", { sessionId, prompt: [...prompt] }, { timeoutMs: null }).then((result) => {
524
- const { stopReason, usage } = AcpPromptResultSchema.parse(result);
525
- const outcome = acpOutcome(stopReason, turn.state.interruptRequested);
526
- const raw = { source: "acp", type: `session/prompt/${stopReason}` };
996
+ function runAcpPrompt(input) {
997
+ const { peer, sessionId, prompt, turn, generation, checkOutcome, done } = input;
998
+ peer.request("session/prompt", { sessionId, prompt: [...prompt] }, { timeoutMs: null }).then(async (result) => {
999
+ if (turn.settled)
1000
+ return;
1001
+ const parsed = AcpPromptResultSchema.parse(result);
1002
+ if (parsed.usage !== undefined && parsed.usage !== null) {
1003
+ turn.accumulatedUsage = addAcpTokenUsage(turn.accumulatedUsage, normalizeAcpUsage(parsed.usage, {
1004
+ ...input.usageInputIncludesCachedRead !== undefined && {
1005
+ usageInputIncludesCachedRead: input.usageInputIncludesCachedRead
1006
+ }
1007
+ }));
1008
+ }
1009
+ if (generation !== turn.promptGeneration)
1010
+ return;
1011
+ const rawOverride = !turn.state.interruptRequested && checkOutcome !== undefined ? await checkOutcome(parsed) : undefined;
1012
+ if (turn.settled || generation !== turn.promptGeneration)
1013
+ return;
1014
+ const override = rawOverride !== undefined ? AcpPromptOutcomeOverrideSchema.parse(rawOverride) : undefined;
1015
+ const outcome = override !== undefined ? "failed" : acpOutcome(parsed.stopReason, turn.state.interruptRequested);
1016
+ const raw = { source: "acp", type: `session/prompt/${parsed.stopReason}` };
527
1017
  const last = [];
528
- if (usage !== undefined && usage !== null) {
1018
+ if (turn.accumulatedUsage !== undefined) {
529
1019
  last.push({
530
1020
  type: "usage",
531
1021
  turnId: turn.state.turnId,
532
1022
  itemId: "usage",
533
1023
  raw,
534
- ...usage.inputTokens != null && { inputTokens: usage.inputTokens },
535
- ...usage.outputTokens != null && { outputTokens: usage.outputTokens },
536
- ...usage.cachedReadTokens != null && {
537
- cachedInputTokens: usage.cachedReadTokens
538
- }
1024
+ ...turn.accumulatedUsage
539
1025
  });
540
1026
  }
541
- if (outcome === "failed") {
1027
+ if (override !== undefined) {
1028
+ last.push({
1029
+ type: "error",
1030
+ turnId: turn.state.turnId,
1031
+ itemId: "failure",
1032
+ raw,
1033
+ kind: override.errorKind,
1034
+ message: override.message
1035
+ });
1036
+ } else if (outcome === "failed") {
542
1037
  last.push({
543
1038
  type: "error",
544
1039
  turnId: turn.state.turnId,
545
1040
  itemId: "failure",
546
1041
  raw,
547
1042
  kind: "restartRecommended",
548
- message: `The ACP agent stopped: ${stopReason}`
1043
+ message: `The ACP agent stopped: ${parsed.stopReason}`
549
1044
  });
550
1045
  }
551
- last.push({ type: "turn-end", turnId: turn.state.turnId, itemId: "end", raw, outcome });
1046
+ last.push({
1047
+ type: "turn-end",
1048
+ turnId: turn.state.turnId,
1049
+ itemId: "end",
1050
+ raw,
1051
+ outcome,
1052
+ ...override?.threadDisposition !== undefined && {
1053
+ threadDisposition: override.threadDisposition
1054
+ }
1055
+ });
1056
+ turn.settled = true;
552
1057
  endEngineTurn(turn, () => ACP_CANCELLED, last);
553
1058
  done();
554
1059
  }).catch((error) => {
1060
+ if (turn.settled || generation !== turn.promptGeneration)
1061
+ return;
1062
+ turn.settled = true;
555
1063
  const kind = classifyAcpRpcRefusal(error);
556
1064
  if (kind !== undefined && error instanceof Error) {
557
1065
  const raw = { source: "acp", type: "session/prompt" };
@@ -587,21 +1095,109 @@ function acpTurnHandle(peer, sessionId, turn) {
587
1095
  drainEngineRequests(turn, () => ACP_CANCELLED);
588
1096
  },
589
1097
  async respond(interactionId, rawReply) {
590
- const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
591
- const waiting = turn.pending.get(interactionId);
592
- if (waiting === undefined)
593
- throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
594
- if (reply.kind === "input") {
595
- throw new TypeError("An ACP permission request is approved or denied, not answered with input");
1098
+ answerActiveAcpTurnRequest(turn, interactionId, rawReply);
1099
+ }
1100
+ };
1101
+ }
1102
+ function createAcpTurnControls(input) {
1103
+ let turnOpening = false;
1104
+ let steering = false;
1105
+ const releaseTurn = (turn) => {
1106
+ if (input.getTurn() === turn)
1107
+ input.setTurn(undefined);
1108
+ };
1109
+ return {
1110
+ async startTurn(turnInput) {
1111
+ input.ensureAlive();
1112
+ if (input.getTurn() !== undefined || turnOpening) {
1113
+ throw new Error("A turn is already running in this ACP session");
1114
+ }
1115
+ turnOpening = true;
1116
+ let prompt;
1117
+ let checkOutcome;
1118
+ try {
1119
+ prompt = await acpPromptBlocks(turnInput.input, input.limits);
1120
+ if (input.config.watchPromptOutcome !== undefined) {
1121
+ checkOutcome = await input.config.watchPromptOutcome({
1122
+ sessionId: input.sessionId,
1123
+ turnId: turnInput.turnId,
1124
+ generation: 1
1125
+ });
1126
+ }
1127
+ } finally {
1128
+ turnOpening = false;
596
1129
  }
597
- const wanted = reply.kind === "approve" ? "allow" : "reject";
598
- const { options } = waiting.detail;
599
- const option = options.find((candidate) => candidate.kind === `${wanted}_once`) ?? options.find((candidate) => candidate.kind.startsWith(wanted));
600
- if (option === undefined)
601
- throw new TypeError(`The agent offered no ${wanted} option`);
602
- answerEngineRequest(turn, interactionId, {
603
- outcome: { outcome: "selected", optionId: option.optionId }
1130
+ input.ensureAlive();
1131
+ const turn = newAcpTurn(turnInput.turnId);
1132
+ input.setTurn(turn);
1133
+ runAcpPrompt({
1134
+ peer: input.peer,
1135
+ sessionId: input.sessionId,
1136
+ prompt,
1137
+ turn,
1138
+ generation: 1,
1139
+ ...input.config.usageInputIncludesCachedRead !== undefined && {
1140
+ usageInputIncludesCachedRead: input.config.usageInputIncludesCachedRead
1141
+ },
1142
+ ...checkOutcome !== undefined && { checkOutcome },
1143
+ done: () => releaseTurn(turn)
604
1144
  });
1145
+ return acpTurnHandle(input.peer, input.sessionId, turn);
1146
+ },
1147
+ async steerTurn(steerInput) {
1148
+ if ((input.config.steerMode ?? "none") !== "prompt") {
1149
+ throw new TypeError('The ACP driver does not support steering unless steerMode is "prompt"');
1150
+ }
1151
+ input.ensureAlive();
1152
+ const turn = input.getTurn();
1153
+ if (turn === undefined || turn.settled) {
1154
+ throw new Error("Cannot steer turn: no ACP turn is currently running");
1155
+ }
1156
+ if (turn.state.interruptRequested) {
1157
+ throw new Error("Cannot steer turn: the active ACP turn was interrupted");
1158
+ }
1159
+ if (steering) {
1160
+ throw new Error("A steer request is already being dispatched for this ACP turn");
1161
+ }
1162
+ steering = true;
1163
+ let prompt;
1164
+ let checkOutcome;
1165
+ let nextGeneration;
1166
+ try {
1167
+ prompt = await acpPromptBlocks(steerInput.input, input.limits);
1168
+ input.ensureAlive();
1169
+ if (input.getTurn() !== turn || turn.settled || turn.state.interruptRequested) {
1170
+ throw new Error("Cannot steer turn: the active ACP turn ended before steering was sent");
1171
+ }
1172
+ nextGeneration = turn.promptGeneration + 1;
1173
+ if (input.config.watchPromptOutcome !== undefined) {
1174
+ checkOutcome = await input.config.watchPromptOutcome({
1175
+ sessionId: input.sessionId,
1176
+ turnId: turn.state.turnId,
1177
+ generation: nextGeneration
1178
+ });
1179
+ }
1180
+ input.ensureAlive();
1181
+ if (input.getTurn() !== turn || turn.settled || turn.state.interruptRequested) {
1182
+ throw new Error("Cannot steer turn: the active ACP turn ended before steering was sent");
1183
+ }
1184
+ turn.promptGeneration = nextGeneration;
1185
+ } finally {
1186
+ steering = false;
1187
+ }
1188
+ runAcpPrompt({
1189
+ peer: input.peer,
1190
+ sessionId: input.sessionId,
1191
+ prompt,
1192
+ turn,
1193
+ generation: nextGeneration,
1194
+ ...input.config.usageInputIncludesCachedRead !== undefined && {
1195
+ usageInputIncludesCachedRead: input.config.usageInputIncludesCachedRead
1196
+ },
1197
+ ...checkOutcome !== undefined && { checkOutcome },
1198
+ done: () => releaseTurn(turn)
1199
+ });
1200
+ return { turnId: turn.state.turnId };
605
1201
  }
606
1202
  };
607
1203
  }
@@ -621,103 +1217,45 @@ async function setOption(peer, sessionId, options, category, value) {
621
1217
  const answer = AcpSetConfigOptionResultSchema.parse(await peer.request("session/set_config_option", { sessionId, configId: option.id, value }));
622
1218
  return answer.configOptions ?? options;
623
1219
  }
624
- function createAcpHandlers(state) {
625
- return {
626
- onNotification(method, params) {
627
- const turn = state.getTurn();
628
- if (method !== "session/update") {
629
- if (turn !== undefined) {
630
- turn.chunk += 1;
631
- offerTurnDelta(turn.channel, {
632
- type: "error",
633
- turnId: turn.state.turnId,
634
- itemId: `unhandled:${method}:${turn.chunk}`,
635
- raw: { source: "acp", type: method },
636
- kind: "unhandled",
637
- message: `ACP notification ${method} is not known to this driver`
638
- });
639
- }
640
- return;
641
- }
642
- const parsed = AcpUpdateNotificationSchema.safeParse(params);
643
- if (!parsed.success) {
644
- if (turn !== undefined) {
645
- turn.chunk += 1;
646
- offerTurnDelta(turn.channel, {
647
- type: "error",
648
- turnId: turn.state.turnId,
649
- itemId: `unhandled:session/update:${turn.chunk}`,
650
- raw: { source: "acp", type: method },
651
- kind: "unhandled",
652
- message: `ACP update did not match schema: ${parsed.error.message}`
653
- });
654
- }
655
- return;
1220
+ async function applySessionSelections(input) {
1221
+ let options = input.configOptions;
1222
+ if (input.model !== undefined) {
1223
+ if (optionOf(options, "model") !== undefined) {
1224
+ options = await setOption(input.peer, input.sessionId, options, "model", input.model);
1225
+ } else if (input.models !== undefined && input.models !== null) {
1226
+ const available = input.models.availableModels?.map((entry) => entry.modelId) ?? [];
1227
+ if (available.length > 0 && !available.includes(input.model)) {
1228
+ throw new Error(`The ACP agent's model option has no value ${input.model} (offered: ${available.join(", ")})`);
656
1229
  }
657
- const { update } = parsed.data;
658
- state.onSessionMeta({
659
- ...update.configOptions !== undefined && { configOptions: update.configOptions },
660
- ...update.sessionUpdate === "session_info_update" && typeof update.title === "string" && { title: update.title },
661
- ...update.availableCommands !== undefined && {
662
- commands: update.availableCommands.map((command) => command.name)
663
- }
1230
+ await input.peer.request("session/set_model", {
1231
+ sessionId: input.sessionId,
1232
+ modelId: input.model
664
1233
  });
665
- if (turn === undefined)
666
- return;
667
- turn.chunk += 1;
668
- for (const delta of mapAcpUpdate(update, turn.state.turnId, turn.chunk, turn.track))
669
- offerTurnDelta(turn.channel, delta);
670
- },
671
- onRequest(method, params, id) {
672
- const turn = state.getTurn();
673
- if (method !== "session/request_permission" || turn === undefined) {
674
- if (turn !== undefined) {
675
- offerTurnDelta(turn.channel, {
676
- type: "error",
677
- turnId: turn.state.turnId,
678
- itemId: `unhandled-request:${id}`,
679
- raw: { source: "acp", type: method },
680
- kind: "unhandled",
681
- message: `ACP request ${method} is not known to this driver; refused`
682
- });
683
- }
684
- throw new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`);
685
- }
686
- const asked = AcpPermissionRequestSchema.parse(params);
687
- const interactionId = String(id);
688
- const toolInput = asked.toolCall.rawInput ?? asked.toolCall.args;
689
- const callId = nonEmptyString(asked.toolCall.toolCallId);
690
- const toolName = nonEmptyString(asked.toolCall.name) ?? nonEmptyString(asked.toolCall.title) ?? "tool";
691
- return new Promise((resolve) => {
692
- holdEngineRequest(turn, {
693
- interactionId,
694
- detail: { options: asked.options },
695
- answeredBy: { source: "acp", type: "session/request_permission" },
696
- delta: () => ({
697
- type: "request",
698
- turnId: turn.state.turnId,
699
- itemId: `request:${interactionId}`,
700
- raw: { source: "acp", type: method },
701
- interactionId,
702
- kind: "approval",
703
- ...callId !== undefined && { callId },
704
- toolName,
705
- ...toolInput !== undefined && { input: toolInput }
706
- }),
707
- refusal: ACP_CANCELLED,
708
- resolve
709
- });
710
- });
711
- },
712
- onEnd: state.onEnd
713
- };
1234
+ } else {
1235
+ throw new Error("The ACP agent offers no model option");
1236
+ }
1237
+ }
1238
+ if (input.thoughtLevel !== undefined) {
1239
+ options = await setOption(input.peer, input.sessionId, options, "thought_level", input.thoughtLevel);
1240
+ }
1241
+ if (input.mode !== undefined) {
1242
+ options = await setOption(input.peer, input.sessionId, options, "mode", input.mode);
1243
+ }
1244
+ return options;
1245
+ }
1246
+ function drainExternalPending(externalPending) {
1247
+ for (const [interactionId, pending] of [...externalPending]) {
1248
+ externalPending.delete(interactionId);
1249
+ pending.resolve(ACP_CANCELLED);
1250
+ }
714
1251
  }
715
1252
  async function openAcpSession(config, input) {
716
1253
  assertAcpDriverOptions(config);
717
1254
  const mcpServers = (config.mcpServers ?? []).map((server) => AcpMcpServerSchema.parse(server));
718
1255
  const linked = sessionAbort(input.signal);
1256
+ const externalPending = new Map;
719
1257
  let current;
720
- let turnOpening = false;
1258
+ let opened = false;
721
1259
  let closing = false;
722
1260
  let dead;
723
1261
  let configOptions = [];
@@ -725,62 +1263,117 @@ async function openAcpSession(config, input) {
725
1263
  let commands = [];
726
1264
  let connected;
727
1265
  try {
728
- connected = await connectAcp(config, input.profile, input.cwd, linked.signal, createAcpHandlers({
729
- getTurn: () => current,
730
- onSessionMeta(meta) {
731
- if (meta.configOptions !== undefined)
732
- configOptions = meta.configOptions;
733
- if (meta.title !== undefined)
734
- title = meta.title;
735
- if (meta.commands !== undefined)
736
- commands = meta.commands;
737
- },
738
- onEnd(error) {
739
- dead = error;
740
- const turn = current;
741
- current = undefined;
742
- loseEngineTurn(turn, () => ACP_CANCELLED, error);
743
- linked.abort();
744
- }
745
- }));
1266
+ connected = await connectAcp(config, input.profile, input.cwd, linked.signal, {
1267
+ ...createAcpHandlers({
1268
+ externalPending,
1269
+ isOpened: () => opened,
1270
+ getTurn: () => current,
1271
+ onSessionMeta(meta) {
1272
+ if (meta.configOptions !== undefined)
1273
+ configOptions = meta.configOptions;
1274
+ if (meta.title !== undefined)
1275
+ title = meta.title;
1276
+ if (meta.commands !== undefined)
1277
+ commands = meta.commands;
1278
+ },
1279
+ ...config.transformUpdate !== undefined && {
1280
+ transformUpdate: config.transformUpdate
1281
+ },
1282
+ ...config.onUpdate !== undefined && { onUpdate: config.onUpdate },
1283
+ ...config.onPermissionRequest !== undefined && {
1284
+ onPermissionRequest: config.onPermissionRequest
1285
+ },
1286
+ onEnd(error) {
1287
+ const shouldNotify = opened && !closing && input.signal?.aborted !== true;
1288
+ dead = error;
1289
+ const turn = current;
1290
+ current = undefined;
1291
+ externalPending.clear();
1292
+ if (turn !== undefined)
1293
+ turn.settled = true;
1294
+ loseEngineTurn(turn, () => ACP_CANCELLED, error);
1295
+ linked.abort();
1296
+ if (shouldNotify)
1297
+ invokeSafely(() => config.onDisconnect?.(error));
1298
+ }
1299
+ }),
1300
+ ...input.onStartupPhase !== undefined && { onStartupPhase: input.onStartupPhase }
1301
+ });
746
1302
  } catch (error) {
747
1303
  linked.release();
748
1304
  throw error;
749
1305
  }
750
1306
  const { peer, initialized } = connected;
1307
+ const ensureAlive = () => {
1308
+ if (closing)
1309
+ throw new Error("The ACP session is closing");
1310
+ if (dead !== undefined)
1311
+ throw dead;
1312
+ };
751
1313
  const stop = async (primary) => {
1314
+ closing = true;
1315
+ drainExternalPending(externalPending);
752
1316
  linked.abort();
753
- await stopConnection(connected, primary);
1317
+ try {
1318
+ await stopConnection(connected, primary);
1319
+ } finally {
1320
+ linked.release();
1321
+ }
754
1322
  };
755
1323
  try {
1324
+ const meta = resolveAcpSessionMeta(config.sessionMeta, initialized);
756
1325
  let sessionId;
1326
+ let sessionModels;
757
1327
  if (input.nativeThreadId === undefined) {
758
- const created = AcpNewSessionResultSchema.parse(await peer.request("session/new", { cwd: input.cwd, mcpServers }));
1328
+ const created = AcpNewSessionResultSchema.parse(await peer.request("session/new", {
1329
+ cwd: input.cwd,
1330
+ mcpServers,
1331
+ ...meta !== undefined && { _meta: meta }
1332
+ }));
759
1333
  sessionId = created.sessionId;
760
1334
  configOptions = created.configOptions ?? configOptions;
1335
+ sessionModels = created.models;
761
1336
  } else {
762
1337
  const method = acpCan(connected, "resume") ? "session/resume" : "session/load";
763
1338
  const reopened = AcpSessionStateSchema.parse(await peer.request(method, {
764
1339
  sessionId: input.nativeThreadId,
765
1340
  cwd: input.cwd,
766
- mcpServers
1341
+ mcpServers,
1342
+ ...meta !== undefined && { _meta: meta }
767
1343
  }) ?? {});
768
1344
  sessionId = input.nativeThreadId;
769
1345
  configOptions = reopened.configOptions ?? configOptions;
1346
+ sessionModels = reopened.models;
770
1347
  }
771
- for (const [category, value] of [
772
- ["model", config.model],
773
- ["thought_level", config.thoughtLevel],
774
- ["mode", config.mode]
775
- ]) {
776
- if (value !== undefined)
777
- configOptions = await setOption(peer, sessionId, configOptions, category, value);
778
- }
1348
+ const desiredModel = input.model ?? config.model;
1349
+ const desiredThoughtLevel = input.thoughtLevel ?? config.thoughtLevel;
1350
+ const desiredMode = input.mode ?? config.mode;
1351
+ configOptions = await applySessionSelections({
1352
+ peer,
1353
+ sessionId,
1354
+ configOptions,
1355
+ models: sessionModels,
1356
+ ...desiredModel !== undefined && { model: desiredModel },
1357
+ ...desiredThoughtLevel !== undefined && { thoughtLevel: desiredThoughtLevel },
1358
+ ...desiredMode !== undefined && { mode: desiredMode }
1359
+ });
779
1360
  const limits = {
780
1361
  images: initialized.agentCapabilities?.promptCapabilities?.image === true,
781
1362
  maxImageBytes: config.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES,
782
1363
  ...config.resolveFile && { resolveFile: config.resolveFile }
783
1364
  };
1365
+ const turnControls = createAcpTurnControls({
1366
+ config,
1367
+ peer,
1368
+ sessionId,
1369
+ limits,
1370
+ ensureAlive,
1371
+ getTurn: () => current,
1372
+ setTurn: (turn) => {
1373
+ current = turn;
1374
+ }
1375
+ });
1376
+ opened = true;
784
1377
  return {
785
1378
  nativeThreadId: sessionId,
786
1379
  approvalEnforcement: "agent-initiated",
@@ -794,41 +1387,18 @@ async function openAcpSession(config, input) {
794
1387
  return commands;
795
1388
  },
796
1389
  async setConfigOption(configId, value) {
797
- if (closing)
798
- throw new Error("The ACP session is closing");
799
- if (dead !== undefined)
800
- throw dead;
1390
+ ensureAlive();
801
1391
  configOptions = await setOption(peer, sessionId, configOptions, configId, value);
802
1392
  return configOptions;
803
1393
  },
804
- async startTurn(turnInput) {
805
- if (closing)
806
- throw new Error("The ACP session is closing");
807
- if (dead !== undefined)
808
- throw dead;
809
- if (current !== undefined || turnOpening)
810
- throw new Error("A turn is already running in this ACP session");
811
- turnOpening = true;
812
- let prompt;
813
- try {
814
- prompt = await acpPromptBlocks(turnInput.input, limits);
815
- } finally {
816
- turnOpening = false;
817
- }
818
- if (closing)
819
- throw new Error("The ACP session is closing");
820
- if (dead !== undefined)
821
- throw dead;
822
- const turn = newAcpTurn(turnInput.turnId);
823
- current = turn;
824
- runAcpPrompt(peer, sessionId, prompt, turn, () => {
825
- if (current === turn)
826
- current = undefined;
827
- });
828
- return acpTurnHandle(peer, sessionId, turn);
1394
+ async respond(interactionId, reply) {
1395
+ ensureAlive();
1396
+ answerAcpSessionRequest({ turn: current, externalPending, interactionId, reply });
829
1397
  },
1398
+ ...turnControls,
830
1399
  async close() {
831
1400
  closing = true;
1401
+ drainExternalPending(externalPending);
832
1402
  if (acpCan(connected, "close"))
833
1403
  await peer.request("session/close", { sessionId }, { timeoutMs: closeRequestTimeoutMs(config) }).catch(() => {
834
1404
  return;
@@ -846,13 +1416,22 @@ async function openAcpSession(config, input) {
846
1416
  function probe(config, profile, cwd, ask) {
847
1417
  return withEphemeralConnection((signal) => connectAcp(config, profile, cwd, signal), ask);
848
1418
  }
849
- async function probeModels(config, connection, cwd) {
850
- const session = AcpNewSessionResultSchema.parse(await connection.peer.request("session/new", { cwd, mcpServers: [] }));
1419
+ async function cleanupProbeSession(config, connection, sessionId) {
1420
+ const timeoutMs = closeRequestTimeoutMs(config);
851
1421
  if (acpCan(connection, "close")) {
852
- await connection.peer.request("session/close", { sessionId: session.sessionId }, { timeoutMs: closeRequestTimeoutMs(config) }).catch(() => {
1422
+ const closed = await connection.peer.request("session/close", { sessionId }, { timeoutMs }).then(() => true, () => false);
1423
+ if (closed)
1424
+ return;
1425
+ }
1426
+ if (acpCan(connection, "delete")) {
1427
+ await connection.peer.request("session/delete", { sessionId }, { timeoutMs }).catch(() => {
853
1428
  return;
854
1429
  });
855
1430
  }
1431
+ }
1432
+ async function probeModels(config, connection, cwd) {
1433
+ const session = AcpNewSessionResultSchema.parse(await connection.peer.request("session/new", { cwd, mcpServers: [] }));
1434
+ await cleanupProbeSession(config, connection, session.sessionId);
856
1435
  const option = session.configOptions?.find((candidate) => candidate.category === "model");
857
1436
  if (option !== undefined)
858
1437
  return acpOptionValues(option);
@@ -861,26 +1440,79 @@ async function probeModels(config, connection, cwd) {
861
1440
  function createAcpDriver(config) {
862
1441
  assertAcpDriverOptions(config);
863
1442
  const ambientHome = () => (config.ambient ?? process.env).HOME ?? "/";
1443
+ const probeMode = config.probeMode ?? "ephemeral-session";
1444
+ const capabilities = {
1445
+ runtimePolicyEnforcement: "client-boundary",
1446
+ sessionApproval: true,
1447
+ interruptOnDeny: false,
1448
+ updatedToolInput: false,
1449
+ structuredInput: true,
1450
+ steer: config.steerMode === "prompt",
1451
+ fork: false,
1452
+ revert: false,
1453
+ compact: false,
1454
+ injectItems: false,
1455
+ backgroundWorkOutlivesTurn: config.onUpdate !== undefined || config.onPermissionRequest !== undefined,
1456
+ multiThreadPerProcess: false,
1457
+ images: config.resolveFile !== undefined,
1458
+ planLimits: "none"
1459
+ };
864
1460
  return {
865
1461
  engine: "acp",
866
1462
  reconcile: "none",
1463
+ capabilities,
867
1464
  approvalEnforcement: "agent-initiated",
868
1465
  async info() {
869
- const profile = { profileId: "probe", engine: "acp", home: ambientHome() };
870
- const cwd = process.cwd();
871
- return probe(config, profile, cwd, async (connection) => ({
1466
+ if (probeMode === "passive") {
1467
+ return {
1468
+ engine: "acp",
1469
+ version: config.passiveVersion?.trim() || "unknown",
1470
+ reconcile: "none",
1471
+ models: { answer: "not-asked" },
1472
+ capabilities
1473
+ };
1474
+ }
1475
+ const profile = {
1476
+ profileId: "probe",
872
1477
  engine: "acp",
873
- version: connection.initialized.agentInfo?.version?.trim() || "unknown",
874
- reconcile: "none",
875
- models: await probeModels(config, connection, cwd).then((ids) => ({ answer: "listed", ids }), (error) => ({
876
- answer: "failed",
877
- error: (error instanceof Error ? error.message : String(error)) || "the model probe failed without a message"
878
- }))
879
- }));
1478
+ home: ambientHome()
1479
+ };
1480
+ const cwd = process.cwd();
1481
+ return probe(config, profile, cwd, async (connection) => {
1482
+ const version = connection.initialized.agentInfo?.version?.trim() || "unknown";
1483
+ if (probeMode === "initialize-only") {
1484
+ return {
1485
+ engine: "acp",
1486
+ version,
1487
+ reconcile: "none",
1488
+ models: { answer: "not-asked" },
1489
+ capabilities
1490
+ };
1491
+ }
1492
+ return {
1493
+ engine: "acp",
1494
+ version,
1495
+ reconcile: "none",
1496
+ models: await probeModels(config, connection, cwd).then((ids) => ({ answer: "listed", ids }), (error) => ({
1497
+ answer: "failed",
1498
+ error: (error instanceof Error ? error.message : String(error)) || "the model probe failed without a message"
1499
+ })),
1500
+ capabilities
1501
+ };
1502
+ });
880
1503
  },
881
1504
  async status(rawProfile) {
882
1505
  const profile = engineProfile("acp", rawProfile);
1506
+ if (probeMode === "passive") {
1507
+ return { login: { state: "unknown" }, effectiveCredential: "unknown" };
1508
+ }
883
1509
  try {
1510
+ if (probeMode === "initialize-only") {
1511
+ await probe(config, profile, process.cwd(), async () => {
1512
+ return;
1513
+ });
1514
+ return { login: { state: "unknown" }, effectiveCredential: "unknown" };
1515
+ }
884
1516
  await probe(config, profile, process.cwd(), (connection) => probeModels(config, connection, process.cwd()));
885
1517
  return { login: { state: "signed-in" }, effectiveCredential: "unknown" };
886
1518
  } catch (error) {
@@ -915,6 +1547,7 @@ function createAcpDriver(config) {
915
1547
  }
916
1548
  export {
917
1549
  ACP_PROTOCOL_VERSION,
1550
+ AcpClientInfoSchema,
918
1551
  AcpMcpServerSchema,
919
1552
  acpFakeScenarios,
920
1553
  createAcpDriver