stitchkit 0.129.0 → 0.130.0

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 (156) hide show
  1. package/CHANGELOG.md +26 -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 +2 -1
  47. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  48. package/dist/agent-executor/codex/control-client.d.ts +168 -0
  49. package/dist/agent-executor/codex/control-client.d.ts.map +1 -0
  50. package/dist/agent-executor/codex/driver.d.ts +22 -2
  51. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  52. package/dist/agent-executor/codex/handlers.d.ts +47 -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 +124 -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 +91 -51
  60. package/dist/agent-executor/codex/session-controls.d.ts.map +1 -1
  61. package/dist/agent-executor/codex/session.d.ts +34 -12
  62. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  63. package/dist/agent-executor/codex/shared-server.d.ts +29 -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 +128 -0
  68. package/dist/agent-executor/codex/thread-controls.d.ts.map +1 -0
  69. package/dist/agent-executor/codex/turn-input.d.ts +30 -0
  70. package/dist/agent-executor/codex/turn-input.d.ts.map +1 -0
  71. package/dist/agent-executor/contract.d.ts +77 -0
  72. package/dist/agent-executor/contract.d.ts.map +1 -1
  73. package/dist/agent-executor/engine.d.ts +6 -2
  74. package/dist/agent-executor/engine.d.ts.map +1 -1
  75. package/dist/agent-executor/executor-contract.d.ts +54 -0
  76. package/dist/agent-executor/executor-contract.d.ts.map +1 -1
  77. package/dist/agent-executor/handoff-schemas.d.ts +407 -0
  78. package/dist/agent-executor/handoff-schemas.d.ts.map +1 -0
  79. package/dist/agent-executor/handoff.d.ts +12 -0
  80. package/dist/agent-executor/handoff.d.ts.map +1 -0
  81. package/dist/agent-executor/hello.d.ts +72 -0
  82. package/dist/agent-executor/hello.d.ts.map +1 -1
  83. package/dist/agent-executor/image-input.d.ts +22 -0
  84. package/dist/agent-executor/image-input.d.ts.map +1 -1
  85. package/dist/agent-executor/projection.d.ts +2 -2
  86. package/dist/agent-executor/projection.d.ts.map +1 -1
  87. package/dist/agent-executor/session-primitives.d.ts +10 -1
  88. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  89. package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
  90. package/dist/agent-executor/testing/replay-driver.d.ts +41 -0
  91. package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -0
  92. package/dist/agent-executor/testing/replay-gate.d.ts +11 -0
  93. package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -0
  94. package/dist/agent-executor/testing/replay-runner.d.ts +27 -0
  95. package/dist/agent-executor/testing/replay-runner.d.ts.map +1 -0
  96. package/dist/agent-executor/testing/replay-scenarios.d.ts +21 -0
  97. package/dist/agent-executor/testing/replay-scenarios.d.ts.map +1 -0
  98. package/dist/agent-executor/testing/replay-transcript.d.ts +296 -0
  99. package/dist/agent-executor/testing/replay-transcript.d.ts.map +1 -0
  100. package/dist/agent-executor/vocabulary.d.ts +135 -0
  101. package/dist/agent-executor/vocabulary.d.ts.map +1 -1
  102. package/dist/agent-runtime/branch-provider.d.ts +2 -2
  103. package/dist/agent-runtime/deferred-tool-selection.d.ts.map +1 -1
  104. package/dist/entrypoints/agent-executor/acp.d.ts +4 -1
  105. package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
  106. package/dist/entrypoints/agent-executor/acp.js +847 -214
  107. package/dist/entrypoints/agent-executor/claude-sdk.d.ts +5 -1
  108. package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
  109. package/dist/entrypoints/agent-executor/claude-sdk.js +713 -205
  110. package/dist/entrypoints/agent-executor/claude.js +44 -19
  111. package/dist/entrypoints/agent-executor/codex.d.ts +9 -2
  112. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  113. package/dist/entrypoints/agent-executor/codex.js +1775 -359
  114. package/dist/entrypoints/agent-executor/testing.d.ts +4 -0
  115. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
  116. package/dist/entrypoints/agent-executor/testing.js +1002 -2
  117. package/dist/entrypoints/agent-executor.d.ts +4 -2
  118. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  119. package/dist/entrypoints/agent-executor.js +411 -23
  120. package/dist/entrypoints/agent-runtime.js +4 -23
  121. package/dist/entrypoints/tools/mcp.d.ts +1 -0
  122. package/dist/entrypoints/tools/mcp.d.ts.map +1 -1
  123. package/dist/entrypoints/tools/mcp.js +1 -1
  124. package/dist/entrypoints/tools/toolkit.js +1 -1
  125. package/dist/{index-wv2amqm4.js → index-2s8sy57y.js} +36 -103
  126. package/dist/{index-afb6z77w.js → index-dbp6xemn.js} +75 -7
  127. package/dist/{index-bjmj2q1z.js → index-jrn3prgm.js} +1 -1
  128. package/dist/index-kne9g2c5.js +30 -0
  129. package/dist/index-p1qmpq0p.js +1300 -0
  130. package/dist/{index-7jqn3b3g.js → index-v759mzed.js} +152 -2
  131. package/dist/{index-cbhxhma2.js → index-x5ayy5bn.js} +1 -0
  132. package/dist/index-y0a4gt1s.js +142 -0
  133. package/dist/tools/internal/rank-tools.d.ts +10 -0
  134. package/dist/tools/internal/rank-tools.d.ts.map +1 -0
  135. package/dist/tools/mcp/handler.d.ts +7 -3
  136. package/dist/tools/mcp/handler.d.ts.map +1 -1
  137. package/dist/tools/mcp/lazy-discovery.d.ts +47 -0
  138. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -0
  139. package/dist/tools/mcp/mount.d.ts +7 -0
  140. package/dist/tools/mcp/mount.d.ts.map +1 -1
  141. package/dist/tools/mcp/register.d.ts +2 -2
  142. package/dist/tools/mcp/register.d.ts.map +1 -1
  143. package/llms/agent-executor-acp.txt +7 -8
  144. package/llms/agent-executor-claude-sdk.txt +4 -2
  145. package/llms/agent-executor-codex.txt +8 -4
  146. package/llms/agent-executor-testing.txt +5 -1
  147. package/llms/agent-executor.txt +7 -6
  148. package/llms/stitchkit.txt +74 -74
  149. package/llms/tools-mcp.txt +3 -2
  150. package/llms/tools.txt +24 -0
  151. package/llms/{upgrading-0.128.0-0.129.0.txt → upgrading-0.128.0-0.130.0.txt} +30 -3
  152. package/llms/upgrading.txt +1 -1
  153. package/llms-full.txt +159 -97
  154. package/llms.txt +8 -8
  155. package/package.json +1 -1
  156. package/dist/index-y71zn1gw.js +0 -586
@@ -1,40 +1,50 @@
1
- import"../../index-2rf33y2h.js";
2
- import {
3
- InteractionReplySchema2,
4
- engineProfile,
5
- engineEnvironment2
6
- } from "../../index-afb6z77w.js";
7
1
  import"../../index-09f7w2qq.js";
8
2
  import"../../index-v59pxmf1.js";
9
3
  import"../../index-qa2jjb65.js";
10
4
  import"../../index-6kec3b14.js";
5
+ import"../../index-2rf33y2h.js";
6
+ import {
7
+ ExecutorModelUsageSchema2,
8
+ PlanLimitsSchema2,
9
+ engineProfile,
10
+ engineEnvironment2
11
+ } from "../../index-dbp6xemn.js";
11
12
  import {
12
13
  nonEmptyString,
13
14
  createTurnDeltaChannel,
14
15
  offerTurnDelta,
15
16
  sessionAbort,
16
17
  safeJsonValue,
17
- validateImageOptions,
18
- imageTurnStarter,
18
+ invokeSafely,
19
+ emitStartupPhase,
19
20
  holdEngineRequest,
20
21
  answerEngineRequest,
21
22
  drainEngineRequests,
22
23
  endEngineTurn,
23
24
  loseEngineTurn
24
- } from "../../index-wv2amqm4.js";
25
+ } from "../../index-2s8sy57y.js";
25
26
  import {
27
+ ClaudeTaskUsageSchema2,
28
+ ClaudeRuntimeEventSchema2,
26
29
  claudeUserContent,
30
+ resolveClaudePermissionReply,
27
31
  newClaudeTurnState,
28
32
  classifyClaudeRecord,
33
+ claudeUsagePlanLimits,
29
34
  claudePlanWindows2,
30
35
  claudeTranscriptPath2,
31
36
  claudeTranscriptExists,
32
37
  findTranscriptInput
33
- } from "../../index-y71zn1gw.js";
38
+ } from "../../index-p1qmpq0p.js";
39
+ import {
40
+ validateImageOptions,
41
+ imageTurnStarter
42
+ } from "../../index-y0a4gt1s.js";
34
43
  import"../../index-pzhqydxb.js";
35
44
  import {
45
+ planLimitsReadFailed2,
36
46
  mergeRateLimitEvent2
37
- } from "../../index-bjmj2q1z.js";
47
+ } from "../../index-jrn3prgm.js";
38
48
  import {
39
49
  isPositiveSafeInteger
40
50
  } from "../../index-gr0kxymw.js";
@@ -46,172 +56,24 @@ import {
46
56
  abortReason,
47
57
  raceAbort
48
58
  } from "../../index-rptj3qnc.js";
49
-
50
- // src/agent-executor/claude-sdk/query-options.ts
51
- import { spawn } from "node:child_process";
52
- import { StringDecoder } from "node:string_decoder";
53
- var DEFAULT_DELEGATION_TIMEOUT_MS = 30000;
54
- var FLAG_SETTINGS_REPLAY_TIMEOUT_MS = 30000;
55
- function validateClaudeSdkConfig(config) {
56
- validateImageOptions(config);
57
- if (config.supportedDialogKinds !== undefined && config.supportedDialogKinds.length > 0 && config.onUserDialog === undefined) {
58
- throw new TypeError("ClaudeSdkDriverConfig.supportedDialogKinds requires onUserDialog when non-empty");
59
- }
60
- if (config.verifyDelegation?.timeoutMs !== undefined) {
61
- assertTimerMs("verifyDelegation.timeoutMs", config.verifyDelegation.timeoutMs);
62
- }
63
- }
64
- function hasDelegationVerification(check) {
65
- return check?.requireHooksApplied === true || check?.requireNoMcpServers === true;
66
- }
67
- function readPositivePid(spawned) {
68
- if (typeof spawned !== "object" || spawned === null)
69
- return;
70
- const raw = Reflect.get(spawned, "pid");
71
- return isPositiveSafeInteger(raw) ? raw : undefined;
72
- }
73
- function createDefaultSpawner(stderrCallback) {
74
- return (opts) => {
75
- const child = spawn(opts.command, opts.args, {
76
- cwd: opts.cwd,
77
- env: opts.env,
78
- signal: opts.signal,
79
- stdio: ["pipe", "pipe", "pipe"],
80
- shell: false,
81
- windowsHide: true
82
- });
83
- if (child.stderr !== null) {
84
- const decoder = new StringDecoder("utf8");
85
- const emit = (text) => {
86
- if (text.length === 0 || stderrCallback === undefined)
87
- return;
88
- try {
89
- stderrCallback(text);
90
- } catch {}
91
- };
92
- child.stderr.on("error", () => {
93
- return;
94
- });
95
- child.stderr.on("data", (chunk) => {
96
- emit(typeof chunk === "string" ? chunk : decoder.write(chunk));
97
- });
98
- child.stderr.on("end", () => {
99
- emit(decoder.end());
100
- });
101
- }
102
- return child;
103
- };
104
- }
105
- function buildSpawnHook(config, recordPid, onPidExit) {
106
- if (config.spawnClaudeCodeProcess === undefined && config.onProviderPid === undefined) {
107
- return;
108
- }
109
- const baseSpawner = config.spawnClaudeCodeProcess ?? createDefaultSpawner(config.stderr);
110
- return (spawnOpts) => {
111
- const proc = baseSpawner(spawnOpts);
112
- const pid = readPositivePid(proc);
113
- recordPid(pid);
114
- if (pid !== undefined && typeof proc.once === "function") {
115
- proc.once("exit", () => onPidExit(pid));
116
- }
117
- if (pid !== undefined && config.onProviderPid !== undefined) {
118
- try {
119
- config.onProviderPid(pid);
120
- } catch (error) {
121
- try {
122
- proc.kill("SIGTERM");
123
- } catch {}
124
- recordPid(undefined);
125
- throw error;
126
- }
127
- }
128
- return proc;
129
- };
130
- }
131
- function buildClaudeSdkQueryOptions(input) {
132
- const { config } = input;
133
- const spawnHook = buildSpawnHook(config, input.recordPid, input.onPidExit);
59
+ // src/agent-executor/claude-sdk/controls.ts
60
+ function unpublishedClaudeSdkUsageRead(now = new Date) {
134
61
  return {
135
- cwd: input.cwd,
136
- env: input.env,
137
- includePartialMessages: true,
138
- permissionMode: input.activePermissionMode,
139
- canUseTool: input.canUseTool,
140
- ...input.activeModel !== undefined && { model: input.activeModel },
141
- ...config.allowDangerouslySkipPermissions !== undefined && {
142
- allowDangerouslySkipPermissions: config.allowDangerouslySkipPermissions
143
- },
144
- ...config.pathToClaudeCodeExecutable !== undefined && {
145
- pathToClaudeCodeExecutable: config.pathToClaudeCodeExecutable
146
- },
147
- ...config.systemPrompt !== undefined && { systemPrompt: config.systemPrompt },
148
- ...config.settingSources !== undefined && { settingSources: config.settingSources },
149
- ...config.enableFileCheckpointing !== undefined && {
150
- enableFileCheckpointing: config.enableFileCheckpointing
151
- },
152
- ...config.supportedDialogKinds !== undefined && {
153
- supportedDialogKinds: [...config.supportedDialogKinds]
154
- },
155
- ...config.onUserDialog !== undefined && { onUserDialog: config.onUserDialog },
156
- ...config.hooks !== undefined && { hooks: config.hooks },
157
- ...config.tools !== undefined && { tools: config.tools },
158
- ...config.allowedTools !== undefined && { allowedTools: config.allowedTools },
159
- ...config.disallowedTools !== undefined && { disallowedTools: config.disallowedTools },
160
- ...config.mcpServers !== undefined && { mcpServers: config.mcpServers },
161
- ...config.mcpServersDelivery !== undefined && {
162
- mcpServersDelivery: config.mcpServersDelivery
163
- },
164
- ...config.strictMcpConfig !== undefined && { strictMcpConfig: config.strictMcpConfig },
165
- ...config.plugins !== undefined && { plugins: config.plugins },
166
- ...config.agents !== undefined && { agents: config.agents },
167
- ...config.extraArgs !== undefined && { extraArgs: config.extraArgs },
168
- ...config.stderr !== undefined && { stderr: config.stderr },
169
- ...spawnHook !== undefined && { spawnClaudeCodeProcess: spawnHook },
170
- ...input.resume ? { resume: input.sessionId } : { sessionId: input.sessionId }
62
+ supported: false,
63
+ planLimits: PlanLimitsSchema2.parse({
64
+ answer: "unpublished",
65
+ windows: [],
66
+ observedAt: now.toISOString()
67
+ })
171
68
  };
172
69
  }
173
- async function verifyClaudeSdkDelegation(query, check, signal) {
174
- const timeoutMs = check.timeoutMs ?? DEFAULT_DELEGATION_TIMEOUT_MS;
175
- await withSignalDeadline(timeoutMs, signal, () => new Error(`Claude SDK delegation verification timed out after ${timeoutMs} ms`), async (deadlineSignal) => {
176
- if (check.requireHooksApplied === true) {
177
- if (typeof query.initializationResult !== "function") {
178
- throw new Error("Claude SDK delegation verification requires query.initializationResult()");
179
- }
180
- const initialized = await raceAbort(query.initializationResult(), deadlineSignal);
181
- if (typeof initialized !== "object" || initialized === null || Reflect.get(initialized, "hooks_applied") !== true) {
182
- throw new Error("Claude SDK did not acknowledge delegation hooks (initializationResult().hooks_applied !== true)");
183
- }
184
- }
185
- if (check.requireNoMcpServers === true) {
186
- if (typeof query.mcpServerStatus !== "function") {
187
- throw new Error("Claude SDK delegation verification requires query.mcpServerStatus()");
188
- }
189
- const servers = await raceAbort(query.mcpServerStatus(), deadlineSignal);
190
- if (!Array.isArray(servers)) {
191
- throw new Error("Claude SDK delegation verification refused non-array mcpServerStatus() response");
192
- }
193
- if (servers.length > 0) {
194
- throw new Error(`Claude SDK exposed ${servers.length} MCP server(s) under delegated policy`);
195
- }
196
- }
197
- });
198
- }
199
- async function replayClaudeSdkFlagSettings(query, overlay, signal) {
200
- if (typeof query.applyFlagSettings !== "function") {
201
- throw new Error("Claude SDK cannot replay flag settings on restart: query does not support applyFlagSettings()");
70
+ function normalizeClaudeSdkUsageRead(raw, recordPlanLimits, now = new Date) {
71
+ const planLimits = claudeUsagePlanLimits(raw, now);
72
+ if (planLimits.answer === "known" || planLimits.answer === "no-plan-limit") {
73
+ recordPlanLimits?.(planLimits);
202
74
  }
203
- const applySettings = query.applyFlagSettings.bind(query);
204
- await withSignalDeadline(FLAG_SETTINGS_REPLAY_TIMEOUT_MS, signal, () => new Error(`Claude SDK flag settings replay timed out after ${FLAG_SETTINGS_REPLAY_TIMEOUT_MS} ms`), (replaySignal) => raceAbort(applySettings(overlay), replaySignal).catch((error) => {
205
- if (replaySignal.aborted)
206
- throw abortReason(replaySignal);
207
- throw error;
208
- }));
75
+ return { supported: true, planLimits, raw };
209
76
  }
210
-
211
- // src/agent-executor/claude-sdk/session.ts
212
- import { randomUUID as randomUUID2 } from "node:crypto";
213
-
214
- // src/agent-executor/claude-sdk/controls.ts
215
77
  function requireMethod(query, name) {
216
78
  const fn = query[name];
217
79
  if (typeof fn !== "function") {
@@ -265,10 +127,33 @@ function createClaudeSdkControls(host) {
265
127
  const query = await activeQuery();
266
128
  return guarded(requireMethod(query, "getContextUsage").call(query, opts));
267
129
  },
130
+ async readUsage(opts) {
131
+ const query = await activeQuery();
132
+ const fn = query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET;
133
+ if (typeof fn !== "function") {
134
+ return unpublishedClaudeSdkUsageRead();
135
+ }
136
+ let raw;
137
+ try {
138
+ raw = await guarded(fn.call(query, opts));
139
+ } catch (error) {
140
+ if (!host.isClosed() && !host.signal.aborted) {
141
+ host.recordPlanLimitsFailure(error);
142
+ }
143
+ throw error;
144
+ }
145
+ if (host.isClosed())
146
+ throw new Error("The Claude SDK session is closed");
147
+ return normalizeClaudeSdkUsageRead(raw, host.recordPlanLimits);
148
+ },
268
149
  async mcpServerStatus() {
269
150
  const query = await activeQuery();
270
151
  return guarded(requireMethod(query, "mcpServerStatus").call(query));
271
152
  },
153
+ async setMcpServers(servers) {
154
+ const query = await activeQuery();
155
+ return guarded(requireMethod(query, "setMcpServers").call(query, servers));
156
+ },
272
157
  async toggleMcpServer(serverName, enabled) {
273
158
  const query = await activeQuery();
274
159
  await guarded(requireMethod(query, "toggleMcpServer").call(query, serverName, enabled));
@@ -277,6 +162,20 @@ function createClaudeSdkControls(host) {
277
162
  const query = await activeQuery();
278
163
  await guarded(requireMethod(query, "reconnectMcpServer").call(query, serverName));
279
164
  },
165
+ async stopTask(taskId) {
166
+ if (typeof taskId !== "string" || taskId.trim().length === 0) {
167
+ throw new TypeError("Claude SDK stopTask requires a non-empty taskId");
168
+ }
169
+ const query = await activeQuery();
170
+ await guarded(requireMethod(query, "stopTask").call(query, taskId));
171
+ },
172
+ async backgroundTasks(toolUseId) {
173
+ if (toolUseId !== undefined && (typeof toolUseId !== "string" || toolUseId.trim().length === 0)) {
174
+ throw new TypeError("Claude SDK backgroundTasks toolUseId must be a non-empty string when provided");
175
+ }
176
+ const query = await activeQuery();
177
+ return guarded(requireMethod(query, "backgroundTasks").call(query, toolUseId));
178
+ },
280
179
  async rewindFiles(userMessageId, options) {
281
180
  const query = await activeQuery();
282
181
  return guarded(requireMethod(query, "rewindFiles").call(query, userMessageId, options));
@@ -286,6 +185,160 @@ function createClaudeSdkControls(host) {
286
185
 
287
186
  // src/agent-executor/claude-sdk/query-loop.ts
288
187
  import { randomUUID } from "node:crypto";
188
+
189
+ // src/agent-executor/claude-sdk/turn-usage.ts
190
+ import { z } from "zod";
191
+ var MAX_MODEL_USAGE_ENTRIES = 64;
192
+ var ClaudeSdkTokenPairSchema = z.strictObject({
193
+ inputTokens: z.int().nonnegative(),
194
+ outputTokens: z.int().nonnegative()
195
+ });
196
+ var ClaudeSdkTurnUsageSchema = z.strictObject({
197
+ turnId: z.string().min(1),
198
+ primaryModel: z.string().min(1).max(256).optional(),
199
+ modelUsageDelta: z.record(z.string().min(1).max(256), ExecutorModelUsageSchema2).refine((entries) => Object.keys(entries).length <= MAX_MODEL_USAGE_ENTRIES, `modelUsageDelta must carry at most ${MAX_MODEL_USAGE_ENTRIES} models`).optional(),
200
+ otherUsage: ClaudeSdkTokenPairSchema.optional(),
201
+ cumulativeModelUsage: z.record(z.string().min(1).max(256), ExecutorModelUsageSchema2).refine((entries) => Object.keys(entries).length <= MAX_MODEL_USAGE_ENTRIES, `cumulativeModelUsage must carry at most ${MAX_MODEL_USAGE_ENTRIES} models`).optional()
202
+ });
203
+ function diffOptionalCounter(before, after, isNewModel) {
204
+ if (isNewModel)
205
+ return { ok: true, value: after };
206
+ if (before === undefined) {
207
+ return { ok: true, value: undefined };
208
+ }
209
+ if (after === undefined || after < before)
210
+ return { ok: false, value: undefined };
211
+ return { ok: true, value: after - before };
212
+ }
213
+ function diffModelRow(before, after) {
214
+ const isNewModel = before === undefined;
215
+ const baseInput = isNewModel ? 0 : before.inputTokens;
216
+ const baseOutput = isNewModel ? 0 : before.outputTokens;
217
+ if (after.inputTokens < baseInput || after.outputTokens < baseOutput)
218
+ return;
219
+ const cacheRead = diffOptionalCounter(before?.cacheReadInputTokens, after.cacheReadInputTokens, isNewModel);
220
+ const cacheCreate = diffOptionalCounter(before?.cacheCreationInputTokens, after.cacheCreationInputTokens, isNewModel);
221
+ const thinking = diffOptionalCounter(before?.thinkingTokens, after.thinkingTokens, isNewModel);
222
+ const cache5m = diffOptionalCounter(before?.cacheCreationEphemeral5mInputTokens, after.cacheCreationEphemeral5mInputTokens, isNewModel);
223
+ const cache1h = diffOptionalCounter(before?.cacheCreationEphemeral1hInputTokens, after.cacheCreationEphemeral1hInputTokens, isNewModel);
224
+ const webSearch = diffOptionalCounter(before?.webSearchRequests, after.webSearchRequests, isNewModel);
225
+ const cost = diffOptionalCounter(before?.costUsd, after.costUsd, isNewModel);
226
+ if (!cacheRead.ok || !cacheCreate.ok || !thinking.ok || !cache5m.ok || !cache1h.ok || !webSearch.ok || !cost.ok) {
227
+ return;
228
+ }
229
+ const inputDelta = after.inputTokens - baseInput;
230
+ const outputDelta = after.outputTokens - baseOutput;
231
+ const missingCacheBaseline = !isNewModel && before.cacheReadInputTokens === undefined && after.cacheReadInputTokens !== undefined || !isNewModel && before.cacheCreationInputTokens === undefined && after.cacheCreationInputTokens !== undefined;
232
+ const ledgerInput = missingCacheBaseline ? undefined : inputDelta + (cacheRead.value ?? 0) + (cacheCreate.value ?? 0);
233
+ return {
234
+ ledgerInput,
235
+ row: {
236
+ inputTokens: inputDelta,
237
+ outputTokens: outputDelta,
238
+ ...cacheRead.value !== undefined && { cacheReadInputTokens: cacheRead.value },
239
+ ...cacheCreate.value !== undefined && { cacheCreationInputTokens: cacheCreate.value },
240
+ ...thinking.value !== undefined && { thinkingTokens: thinking.value },
241
+ ...cache5m.value !== undefined && {
242
+ cacheCreationEphemeral5mInputTokens: cache5m.value
243
+ },
244
+ ...cache1h.value !== undefined && {
245
+ cacheCreationEphemeral1hInputTokens: cache1h.value
246
+ },
247
+ ...webSearch.value !== undefined && { webSearchRequests: webSearch.value },
248
+ ...cost.value !== undefined && { costUsd: cost.value },
249
+ ...after.contextWindow !== undefined && { contextWindow: after.contextWindow },
250
+ ...after.maxOutputTokens !== undefined && { maxOutputTokens: after.maxOutputTokens },
251
+ ...after.canonicalModel !== undefined && { canonicalModel: after.canonicalModel },
252
+ ...after.provider !== undefined && { provider: after.provider },
253
+ ...after.costBasis !== undefined && { costBasis: after.costBasis }
254
+ }
255
+ };
256
+ }
257
+ function computeDeltaMap(baseline, current) {
258
+ for (const model of baseline.keys()) {
259
+ if (!Object.hasOwn(current, model))
260
+ return;
261
+ }
262
+ const deltaEntries = new Map;
263
+ let totalLedgerInput = 0;
264
+ let totalLedgerOutput = 0;
265
+ let hasCompleteLedgerInput = true;
266
+ for (const [model, after] of Object.entries(current)) {
267
+ const diff = diffModelRow(baseline.get(model), after);
268
+ if (diff === undefined)
269
+ return;
270
+ deltaEntries.set(model, diff.row);
271
+ if (diff.ledgerInput === undefined)
272
+ hasCompleteLedgerInput = false;
273
+ else
274
+ totalLedgerInput += diff.ledgerInput;
275
+ totalLedgerOutput += diff.row.outputTokens;
276
+ }
277
+ return {
278
+ modelUsageDelta: Object.fromEntries(deltaEntries),
279
+ ledgerTotals: hasCompleteLedgerInput ? { inputTokens: totalLedgerInput, outputTokens: totalLedgerOutput } : undefined
280
+ };
281
+ }
282
+ function computeOtherUsage(ledgerTotals, usageDelta) {
283
+ if (ledgerTotals === undefined || usageDelta === undefined)
284
+ return;
285
+ if (usageDelta.inputTokens === undefined || usageDelta.outputTokens === undefined) {
286
+ return;
287
+ }
288
+ const mainInput = usageDelta.inputTokens + (usageDelta.cachedInputTokens ?? 0) + (usageDelta.cacheCreationInputTokens ?? 0);
289
+ const mainOutput = usageDelta.outputTokens;
290
+ if (ledgerTotals.inputTokens < mainInput || ledgerTotals.outputTokens < mainOutput) {
291
+ return;
292
+ }
293
+ return {
294
+ inputTokens: ledgerTotals.inputTokens - mainInput,
295
+ outputTokens: ledgerTotals.outputTokens - mainOutput
296
+ };
297
+ }
298
+ function createClaudeSdkTurnUsageTracker() {
299
+ let baseline = new Map;
300
+ return {
301
+ recordTurn({ turnId, primaryModel, usageDelta }) {
302
+ const cumulative = usageDelta?.modelUsage;
303
+ if (cumulative === undefined || Object.keys(cumulative).length === 0) {
304
+ baseline = undefined;
305
+ return {
306
+ turnId,
307
+ ...primaryModel !== undefined && { primaryModel }
308
+ };
309
+ }
310
+ const nextSnapshot = new Map(Object.entries(cumulative));
311
+ if (baseline === undefined) {
312
+ baseline = nextSnapshot;
313
+ return {
314
+ turnId,
315
+ ...primaryModel !== undefined && { primaryModel },
316
+ cumulativeModelUsage: cumulative
317
+ };
318
+ }
319
+ const computed = computeDeltaMap(baseline, cumulative);
320
+ if (computed === undefined) {
321
+ baseline = undefined;
322
+ return {
323
+ turnId,
324
+ ...primaryModel !== undefined && { primaryModel },
325
+ cumulativeModelUsage: cumulative
326
+ };
327
+ }
328
+ baseline = nextSnapshot;
329
+ const otherUsage = computeOtherUsage(computed.ledgerTotals, usageDelta);
330
+ return {
331
+ turnId,
332
+ ...primaryModel !== undefined && { primaryModel },
333
+ modelUsageDelta: computed.modelUsageDelta,
334
+ ...otherUsage !== undefined && { otherUsage },
335
+ cumulativeModelUsage: cumulative
336
+ };
337
+ }
338
+ };
339
+ }
340
+
341
+ // src/agent-executor/claude-sdk/query-loop.ts
289
342
  var SDK_ANSWER = { source: "claude-sdk", type: "PermissionResult" };
290
343
  var stoppedPermission = (message) => () => ({
291
344
  behavior: "deny",
@@ -293,14 +346,7 @@ var stoppedPermission = (message) => () => ({
293
346
  interrupt: true
294
347
  });
295
348
  function closeQuerySafely(query) {
296
- try {
297
- const closing = query?.close?.();
298
- if (typeof closing === "object" && closing !== null && "then" in closing && typeof closing.then === "function") {
299
- Promise.resolve(closing).catch(() => {
300
- return;
301
- });
302
- }
303
- } catch {}
349
+ invokeSafely(() => query?.close?.());
304
350
  }
305
351
  function pushablePrompt() {
306
352
  const queue = [];
@@ -352,26 +398,69 @@ function createSdkCanUseTool(state) {
352
398
  });
353
399
  };
354
400
  const callId = nonEmptyString(options.toolUseID);
401
+ const rawToolName = nonEmptyString(toolName);
402
+ let safeInputSnapshot;
355
403
  holdEngineRequest(turn, {
356
404
  interactionId,
357
- detail: { input: toolInput },
405
+ detail: {
406
+ input: toolInput,
407
+ toolName: rawToolName,
408
+ suppressSessionRule: options.suppressAlwaysAllowRule === true
409
+ },
358
410
  answeredBy: SDK_ANSWER,
359
- delta: () => ({
360
- type: "request",
361
- turnId: turn.state.turnId,
362
- itemId: `request:${interactionId}`,
363
- raw: { source: "claude-sdk", type: "canUseTool" },
364
- interactionId,
365
- kind: "approval",
366
- toolName: nonEmptyString(toolName) ?? "tool",
367
- ...callId !== undefined && { callId },
368
- input: safeJsonValue(toolInput)
369
- }),
411
+ delta: () => {
412
+ const safeInput = safeJsonValue(toolInput);
413
+ if (typeof safeInput === "object" && safeInput !== null && !Array.isArray(safeInput)) {
414
+ safeInputSnapshot = safeInput;
415
+ }
416
+ return {
417
+ type: "request",
418
+ turnId: turn.state.turnId,
419
+ itemId: `request:${interactionId}`,
420
+ raw: { source: "claude-sdk", type: "canUseTool" },
421
+ interactionId,
422
+ kind: "approval",
423
+ toolName: rawToolName ?? "tool",
424
+ ...callId !== undefined && { callId },
425
+ input: safeInput
426
+ };
427
+ },
370
428
  refusal: { behavior: "deny", message: "The turn was interrupted", interrupt: true },
371
429
  resolve: finish
372
430
  });
373
- if (turn.pending.has(interactionId))
431
+ if (turn.pending.has(interactionId)) {
374
432
  options.signal.addEventListener("abort", onToolAbort, { once: true });
433
+ if (state.onPermissionRequest !== undefined) {
434
+ const meta = {
435
+ turnId: turn.state.turnId,
436
+ interactionId,
437
+ toolName,
438
+ input: safeInputSnapshot ?? {},
439
+ toolUseID: options.toolUseID,
440
+ ...options.requestId !== undefined && { requestId: options.requestId },
441
+ ...options.decisionReason !== undefined && {
442
+ decisionReason: options.decisionReason
443
+ },
444
+ ...options.blockedPath !== undefined && { blockedPath: options.blockedPath },
445
+ ...options.title !== undefined && { title: options.title },
446
+ ...options.displayName !== undefined && { displayName: options.displayName },
447
+ ...options.description !== undefined && { description: options.description },
448
+ ...options.suggestions !== undefined && {
449
+ suggestions: [...options.suggestions]
450
+ },
451
+ ...options.agentID !== undefined && { agentID: options.agentID },
452
+ ...options.mcpServer !== undefined && { mcpServer: { ...options.mcpServer } },
453
+ ...options.defaultToNo !== undefined && { defaultToNo: options.defaultToNo },
454
+ ...options.suppressAlwaysAllowRule !== undefined && {
455
+ suppressAlwaysAllowRule: options.suppressAlwaysAllowRule
456
+ },
457
+ ...options.matchedAskRule !== undefined && {
458
+ matchedAskRule: { ...options.matchedAskRule }
459
+ }
460
+ };
461
+ invokeSafely(() => state.onPermissionRequest?.(meta));
462
+ }
463
+ }
375
464
  });
376
465
  }
377
466
  function sdkTurnHandle(turn, query) {
@@ -383,47 +472,365 @@ function sdkTurnHandle(turn, query) {
383
472
  await query.interrupt();
384
473
  },
385
474
  async respond(interactionId, rawReply) {
386
- const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
387
475
  const waiting = turn.pending.get(interactionId);
388
- if (waiting === undefined)
476
+ if (waiting === undefined) {
389
477
  throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
390
- if (reply.kind === "input") {
391
- throw new TypeError("A Claude permission request is approved or denied, not answered with input");
392
478
  }
393
- answerEngineRequest(turn, interactionId, reply.kind === "approve" ? { behavior: "allow", updatedInput: waiting.detail.input } : { behavior: "deny", message: reply.message });
479
+ const decision = resolveClaudePermissionReply(waiting.detail, rawReply);
480
+ if (decision.behavior === "allow") {
481
+ answerEngineRequest(turn, interactionId, {
482
+ behavior: "allow",
483
+ updatedInput: decision.input,
484
+ ...decision.updatedPermissions !== undefined && {
485
+ updatedPermissions: decision.updatedPermissions.map((rule) => ({
486
+ type: rule.type,
487
+ rules: rule.rules.map((entry) => ({ toolName: entry.toolName })),
488
+ behavior: rule.behavior,
489
+ destination: rule.destination
490
+ }))
491
+ }
492
+ });
493
+ return;
494
+ }
495
+ answerEngineRequest(turn, interactionId, decision);
394
496
  }
395
497
  };
396
498
  }
397
499
  function runSdkQueryLoop(input) {
500
+ const turnUsageTracker = createClaudeSdkTurnUsageTracker();
501
+ let sessionModel;
398
502
  (async () => {
399
503
  try {
400
504
  for await (const record of input.handle.query) {
401
505
  const turn = input.getTurn();
402
506
  const verdict = classifyClaudeRecord(record, turn?.state ?? newClaudeTurnState("between-turns"));
403
- if (verdict.kind === "limits") {
507
+ if (verdict.kind === "session") {
508
+ if (verdict.model !== undefined)
509
+ sessionModel = verdict.model;
510
+ } else if (verdict.kind === "limits") {
404
511
  input.limits.set(input.profileId, mergeRateLimitEvent2({
405
512
  previous: input.limits.get(input.profileId),
406
513
  windows: claudePlanWindows2(verdict.info),
407
514
  now: new Date
408
515
  }));
516
+ } else if (verdict.kind === "event") {
517
+ if (input.onEvent !== undefined) {
518
+ invokeSafely(() => input.onEvent?.(verdict.event));
519
+ }
409
520
  } else if (verdict.kind === "deltas") {
410
521
  for (const delta of verdict.deltas)
411
522
  offerTurnDelta(turn?.channel, delta);
412
523
  } else if (verdict.kind === "end") {
524
+ const usageDelta = verdict.deltas.find((delta) => delta.type === "usage");
525
+ const primaryModel = turn?.state.primaryModel ?? sessionModel;
526
+ const summary = turnUsageTracker.recordTurn({
527
+ turnId: turn?.state.turnId ?? "between-turns",
528
+ ...primaryModel !== undefined && { primaryModel },
529
+ ...usageDelta?.type === "usage" && { usageDelta }
530
+ });
531
+ if (turn !== undefined && input.onTurnUsage !== undefined) {
532
+ invokeSafely(() => input.onTurnUsage?.(summary));
533
+ }
413
534
  endEngineTurn(turn, stoppedPermission("The turn ended"), verdict.deltas);
414
535
  input.clearTurn();
415
536
  } else if (verdict.kind === "unhandled") {
416
537
  offerTurnDelta(turn?.channel, verdict.delta);
417
538
  }
418
539
  }
419
- throw new Error("The Agent SDK query ended during the turn");
540
+ throw new Error(input.getTurn() !== undefined ? "The Agent SDK query ended during the turn" : "The Agent SDK query ended while idle");
420
541
  } catch (error) {
421
542
  input.onExit(input.handle, error);
422
543
  }
423
544
  })();
424
545
  }
425
546
 
547
+ // src/agent-executor/claude-sdk/probe.ts
548
+ var DEFAULT_PROBE_TIMEOUT_MS = 30000;
549
+ function createNeverYieldingPrompt(signal) {
550
+ return {
551
+ [Symbol.asyncIterator]() {
552
+ return {
553
+ next() {
554
+ if (signal.aborted) {
555
+ return Promise.resolve({ value: undefined, done: true });
556
+ }
557
+ return new Promise((resolve) => {
558
+ signal.addEventListener("abort", () => resolve({ value: undefined, done: true }), {
559
+ once: true
560
+ });
561
+ });
562
+ },
563
+ return() {
564
+ return Promise.resolve({ value: undefined, done: true });
565
+ }
566
+ };
567
+ }
568
+ };
569
+ }
570
+ function buildProbeOptions(input) {
571
+ const { config } = input;
572
+ return {
573
+ cwd: input.cwd,
574
+ env: input.env,
575
+ abortController: input.abortController,
576
+ persistSession: false,
577
+ settings: { disableAllHooks: true },
578
+ strictMcpConfig: true,
579
+ mcpServers: {},
580
+ allowedTools: [],
581
+ canUseTool: async () => ({
582
+ behavior: "deny",
583
+ message: "Capability probe does not execute tools",
584
+ interrupt: true
585
+ }),
586
+ ...config.pathToClaudeCodeExecutable !== undefined && {
587
+ pathToClaudeCodeExecutable: config.pathToClaudeCodeExecutable
588
+ },
589
+ ...config.settingSources !== undefined && { settingSources: config.settingSources },
590
+ ...config.extraArgs !== undefined && { extraArgs: config.extraArgs },
591
+ ...config.stderr !== undefined && { stderr: config.stderr },
592
+ ...config.spawnClaudeCodeProcess !== undefined && {
593
+ spawnClaudeCodeProcess: config.spawnClaudeCodeProcess
594
+ }
595
+ };
596
+ }
597
+ async function probeClaudeSdkCapabilities(config, limits, input) {
598
+ const profile = engineProfile("claude-sdk", input.profile);
599
+ if (input.timeoutMs !== undefined) {
600
+ assertTimerMs("timeoutMs", input.timeoutMs);
601
+ }
602
+ input.signal?.throwIfAborted();
603
+ const timeoutMs = input.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
604
+ const ambient = config.ambient ?? process.env;
605
+ const env = engineEnvironment2(profile, ambient);
606
+ return withSignalDeadline(timeoutMs, input.signal, () => new Error(`Claude SDK capability probe timed out after ${timeoutMs} ms`), async (deadlineSignal) => {
607
+ const probeAbort = new AbortController;
608
+ const onDeadlineAbort = () => probeAbort.abort(deadlineSignal.reason);
609
+ if (deadlineSignal.aborted) {
610
+ onDeadlineAbort();
611
+ } else {
612
+ deadlineSignal.addEventListener("abort", onDeadlineAbort, { once: true });
613
+ }
614
+ let query;
615
+ try {
616
+ query = config.query({
617
+ prompt: createNeverYieldingPrompt(probeAbort.signal),
618
+ options: buildProbeOptions({
619
+ config,
620
+ cwd: input.cwd,
621
+ env,
622
+ abortController: probeAbort
623
+ })
624
+ });
625
+ const initFn = query.initializationResult;
626
+ const modelsFn = query.supportedModels;
627
+ const commandsFn = query.supportedCommands;
628
+ const accountFn = query.accountInfo;
629
+ if (typeof initFn !== "function" && typeof modelsFn !== "function" && typeof commandsFn !== "function" && typeof accountFn !== "function") {
630
+ throw new Error("The configured Claude SDK query does not expose capability probe RPCs");
631
+ }
632
+ const initializationResult = typeof initFn === "function" ? await raceAbort(initFn.call(query), deadlineSignal) : undefined;
633
+ const usageFn = input.includeUsage === true ? query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET : undefined;
634
+ const [models, commands, account, rawUsage] = await Promise.all([
635
+ typeof modelsFn === "function" ? raceAbort(modelsFn.call(query), deadlineSignal) : Promise.resolve(initializationResult?.models),
636
+ typeof commandsFn === "function" ? raceAbort(commandsFn.call(query), deadlineSignal) : Promise.resolve(initializationResult?.commands),
637
+ typeof accountFn === "function" ? raceAbort(accountFn.call(query), deadlineSignal) : Promise.resolve(initializationResult?.account),
638
+ typeof usageFn === "function" ? raceAbort(usageFn.call(query, { skipBehaviors: true }), deadlineSignal) : Promise.resolve(undefined)
639
+ ]);
640
+ let usage;
641
+ if (input.includeUsage === true) {
642
+ usage = typeof usageFn === "function" && rawUsage !== undefined ? normalizeClaudeSdkUsageRead(rawUsage, (planLimits) => {
643
+ limits.set(profile.profileId, planLimits);
644
+ }) : unpublishedClaudeSdkUsageRead();
645
+ }
646
+ return {
647
+ ...initializationResult !== undefined && { initializationResult },
648
+ ...models !== undefined && { models },
649
+ ...commands !== undefined && { commands },
650
+ ...account !== undefined && { account },
651
+ ...usage !== undefined && { usage }
652
+ };
653
+ } finally {
654
+ deadlineSignal.removeEventListener("abort", onDeadlineAbort);
655
+ if (!probeAbort.signal.aborted)
656
+ probeAbort.abort();
657
+ closeQuerySafely(query);
658
+ }
659
+ });
660
+ }
661
+
662
+ // src/agent-executor/claude-sdk/query-options.ts
663
+ import { spawn } from "node:child_process";
664
+ import { StringDecoder } from "node:string_decoder";
665
+ var DEFAULT_DELEGATION_TIMEOUT_MS = 30000;
666
+ var FLAG_SETTINGS_REPLAY_TIMEOUT_MS = 30000;
667
+ function validateClaudeSdkConfig(config) {
668
+ validateImageOptions(config);
669
+ if (config.supportedDialogKinds !== undefined && config.supportedDialogKinds.length > 0 && config.onUserDialog === undefined) {
670
+ throw new TypeError("ClaudeSdkDriverConfig.supportedDialogKinds requires onUserDialog when non-empty");
671
+ }
672
+ if (config.verifyDelegation?.timeoutMs !== undefined) {
673
+ assertTimerMs("verifyDelegation.timeoutMs", config.verifyDelegation.timeoutMs);
674
+ }
675
+ }
676
+ function hasDelegationVerification(check) {
677
+ return check?.requireHooksApplied === true || check?.requireNoMcpServers === true;
678
+ }
679
+ function readPositivePid(spawned) {
680
+ if (typeof spawned !== "object" || spawned === null)
681
+ return;
682
+ const raw = Reflect.get(spawned, "pid");
683
+ return isPositiveSafeInteger(raw) ? raw : undefined;
684
+ }
685
+ function createDefaultSpawner(stderrCallback) {
686
+ return (opts) => {
687
+ const child = spawn(opts.command, opts.args, {
688
+ cwd: opts.cwd,
689
+ env: opts.env,
690
+ signal: opts.signal,
691
+ stdio: ["pipe", "pipe", "pipe"],
692
+ shell: false,
693
+ windowsHide: true
694
+ });
695
+ if (child.stderr !== null) {
696
+ const decoder = new StringDecoder("utf8");
697
+ const emit = (text) => {
698
+ if (text.length === 0 || stderrCallback === undefined)
699
+ return;
700
+ try {
701
+ stderrCallback(text);
702
+ } catch {}
703
+ };
704
+ child.stderr.on("error", () => {
705
+ return;
706
+ });
707
+ child.stderr.on("data", (chunk) => {
708
+ emit(typeof chunk === "string" ? chunk : decoder.write(chunk));
709
+ });
710
+ child.stderr.on("end", () => {
711
+ emit(decoder.end());
712
+ });
713
+ }
714
+ return child;
715
+ };
716
+ }
717
+ function buildSpawnHook(config, recordPid, onPidExit) {
718
+ if (config.spawnClaudeCodeProcess === undefined && config.onProviderPid === undefined) {
719
+ return;
720
+ }
721
+ const baseSpawner = config.spawnClaudeCodeProcess ?? createDefaultSpawner(config.stderr);
722
+ return (spawnOpts) => {
723
+ const proc = baseSpawner(spawnOpts);
724
+ const pid = readPositivePid(proc);
725
+ recordPid(pid);
726
+ if (pid !== undefined && typeof proc.once === "function") {
727
+ proc.once("exit", () => onPidExit(pid));
728
+ }
729
+ if (pid !== undefined && config.onProviderPid !== undefined) {
730
+ try {
731
+ config.onProviderPid(pid);
732
+ } catch (error) {
733
+ try {
734
+ proc.kill("SIGTERM");
735
+ } catch {}
736
+ recordPid(undefined);
737
+ throw error;
738
+ }
739
+ }
740
+ return proc;
741
+ };
742
+ }
743
+ function buildClaudeSdkQueryOptions(input) {
744
+ const { config } = input;
745
+ const spawnHook = buildSpawnHook(config, input.recordPid, input.onPidExit);
746
+ return {
747
+ cwd: input.cwd,
748
+ env: input.env,
749
+ includePartialMessages: true,
750
+ permissionMode: input.activePermissionMode,
751
+ canUseTool: input.canUseTool,
752
+ ...input.activeModel !== undefined && { model: input.activeModel },
753
+ ...config.allowDangerouslySkipPermissions !== undefined && {
754
+ allowDangerouslySkipPermissions: config.allowDangerouslySkipPermissions
755
+ },
756
+ ...config.pathToClaudeCodeExecutable !== undefined && {
757
+ pathToClaudeCodeExecutable: config.pathToClaudeCodeExecutable
758
+ },
759
+ ...config.systemPrompt !== undefined && { systemPrompt: config.systemPrompt },
760
+ ...config.settingSources !== undefined && { settingSources: config.settingSources },
761
+ ...config.enableFileCheckpointing !== undefined && {
762
+ enableFileCheckpointing: config.enableFileCheckpointing
763
+ },
764
+ ...config.supportedDialogKinds !== undefined && {
765
+ supportedDialogKinds: [...config.supportedDialogKinds]
766
+ },
767
+ ...config.onUserDialog !== undefined && { onUserDialog: config.onUserDialog },
768
+ ...config.onElicitation !== undefined && { onElicitation: config.onElicitation },
769
+ ...config.hooks !== undefined && { hooks: config.hooks },
770
+ ...config.tools !== undefined && { tools: config.tools },
771
+ ...config.allowedTools !== undefined && { allowedTools: config.allowedTools },
772
+ ...config.disallowedTools !== undefined && { disallowedTools: config.disallowedTools },
773
+ ...config.mcpServers !== undefined && { mcpServers: config.mcpServers },
774
+ ...config.mcpServersDelivery !== undefined && {
775
+ mcpServersDelivery: config.mcpServersDelivery
776
+ },
777
+ ...config.strictMcpConfig !== undefined && { strictMcpConfig: config.strictMcpConfig },
778
+ ...config.plugins !== undefined && { plugins: config.plugins },
779
+ ...config.agents !== undefined && { agents: config.agents },
780
+ ...config.extraArgs !== undefined && { extraArgs: config.extraArgs },
781
+ ...config.stderr !== undefined && { stderr: config.stderr },
782
+ ...spawnHook !== undefined && { spawnClaudeCodeProcess: spawnHook },
783
+ ...input.resume ? {
784
+ resume: input.sessionId,
785
+ ...input.resumeSessionAt !== undefined && {
786
+ resumeSessionAt: input.resumeSessionAt
787
+ },
788
+ ...input.resumeDropsTurn !== undefined && {
789
+ resumeDropsTurn: input.resumeDropsTurn
790
+ }
791
+ } : { sessionId: input.sessionId }
792
+ };
793
+ }
794
+ async function verifyClaudeSdkDelegation(query, check, signal) {
795
+ const timeoutMs = check.timeoutMs ?? DEFAULT_DELEGATION_TIMEOUT_MS;
796
+ await withSignalDeadline(timeoutMs, signal, () => new Error(`Claude SDK delegation verification timed out after ${timeoutMs} ms`), async (deadlineSignal) => {
797
+ if (check.requireHooksApplied === true) {
798
+ if (typeof query.initializationResult !== "function") {
799
+ throw new Error("Claude SDK delegation verification requires query.initializationResult()");
800
+ }
801
+ const initialized = await raceAbort(query.initializationResult(), deadlineSignal);
802
+ if (typeof initialized !== "object" || initialized === null || Reflect.get(initialized, "hooks_applied") !== true) {
803
+ throw new Error("Claude SDK did not acknowledge delegation hooks (initializationResult().hooks_applied !== true)");
804
+ }
805
+ }
806
+ if (check.requireNoMcpServers === true) {
807
+ if (typeof query.mcpServerStatus !== "function") {
808
+ throw new Error("Claude SDK delegation verification requires query.mcpServerStatus()");
809
+ }
810
+ const servers = await raceAbort(query.mcpServerStatus(), deadlineSignal);
811
+ if (!Array.isArray(servers)) {
812
+ throw new Error("Claude SDK delegation verification refused non-array mcpServerStatus() response");
813
+ }
814
+ if (servers.length > 0) {
815
+ throw new Error(`Claude SDK exposed ${servers.length} MCP server(s) under delegated policy`);
816
+ }
817
+ }
818
+ });
819
+ }
820
+ async function replayClaudeSdkFlagSettings(query, overlay, signal) {
821
+ if (typeof query.applyFlagSettings !== "function") {
822
+ throw new Error("Claude SDK cannot replay flag settings on restart: query does not support applyFlagSettings()");
823
+ }
824
+ const applySettings = query.applyFlagSettings.bind(query);
825
+ await withSignalDeadline(FLAG_SETTINGS_REPLAY_TIMEOUT_MS, signal, () => new Error(`Claude SDK flag settings replay timed out after ${FLAG_SETTINGS_REPLAY_TIMEOUT_MS} ms`), (replaySignal) => raceAbort(applySettings(overlay), replaySignal).catch((error) => {
826
+ if (replaySignal.aborted)
827
+ throw abortReason(replaySignal);
828
+ throw error;
829
+ }));
830
+ }
831
+
426
832
  // src/agent-executor/claude-sdk/session.ts
833
+ import { randomUUID as randomUUID2 } from "node:crypto";
427
834
  function isUuid(value) {
428
835
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
429
836
  }
@@ -485,6 +892,7 @@ async function launchSingleSdkQuery(input) {
485
892
  if (input.isClosed())
486
893
  throw new Error("The Claude SDK session is closed");
487
894
  input.signal.throwIfAborted();
895
+ emitStartupPhase(input.onStartupPhase, "spawning");
488
896
  const pushed = pushablePrompt();
489
897
  let query;
490
898
  try {
@@ -497,6 +905,12 @@ async function launchSingleSdkQuery(input) {
497
905
  canUseTool: input.canUseTool,
498
906
  sessionId: input.sessionId,
499
907
  resume: input.resume,
908
+ ...input.resumeSessionAt !== undefined && {
909
+ resumeSessionAt: input.resumeSessionAt
910
+ },
911
+ ...input.resumeDropsTurn !== undefined && {
912
+ resumeDropsTurn: input.resumeDropsTurn
913
+ },
500
914
  activeModel: input.activeModel,
501
915
  activePermissionMode: input.activePermissionMode,
502
916
  recordPid: input.recordPid,
@@ -530,6 +944,10 @@ async function launchSingleSdkQuery(input) {
530
944
  limits: input.limits,
531
945
  getTurn: input.getTurn,
532
946
  clearTurn: input.clearTurn,
947
+ ...input.config.onEvent !== undefined && { onEvent: input.config.onEvent },
948
+ ...input.config.onTurnUsage !== undefined && {
949
+ onTurnUsage: input.config.onTurnUsage
950
+ },
533
951
  onExit: input.onExit
534
952
  });
535
953
  },
@@ -538,6 +956,7 @@ async function launchSingleSdkQuery(input) {
538
956
  input.setInFlightClose(closeHandle);
539
957
  try {
540
958
  if (hasDelegationVerification(input.config.verifyDelegation)) {
959
+ emitStartupPhase(input.onStartupPhase, "verifying");
541
960
  await verifyClaudeSdkDelegation(query, input.config.verifyDelegation, input.signal);
542
961
  }
543
962
  if (input.flagSettingsOverlay !== undefined) {
@@ -555,15 +974,56 @@ async function launchSingleSdkQuery(input) {
555
974
  input.setInFlightClose(undefined);
556
975
  return handle;
557
976
  }
977
+ function notifyQueryExit(callback, error, context) {
978
+ if (callback === undefined)
979
+ return;
980
+ invokeSafely(() => callback(error, context));
981
+ }
982
+ function validateClaudeSdkOpenInput(input) {
983
+ const hasNativeThreadId = typeof input.nativeThreadId === "string" && input.nativeThreadId.trim().length > 0;
984
+ if (input.resumeSessionAt !== undefined) {
985
+ if (typeof input.resumeSessionAt !== "string" || input.resumeSessionAt.trim().length === 0) {
986
+ throw new TypeError("Claude SDK open() requires a non-empty resumeSessionAt UUID when provided");
987
+ }
988
+ if (!hasNativeThreadId) {
989
+ throw new TypeError("Claude SDK open() requires nativeThreadId when resumeSessionAt is provided");
990
+ }
991
+ }
992
+ if (input.resumeDropsTurn !== undefined) {
993
+ if (typeof input.resumeDropsTurn !== "string" || input.resumeDropsTurn.trim().length === 0) {
994
+ throw new TypeError("Claude SDK open() requires a non-empty resumeDropsTurn prompt UUID when provided");
995
+ }
996
+ if (!hasNativeThreadId) {
997
+ throw new TypeError("Claude SDK open() requires nativeThreadId when resumeDropsTurn is provided");
998
+ }
999
+ if (input.resumeSessionAt === undefined) {
1000
+ throw new TypeError("Claude SDK open() requires resumeSessionAt when resumeDropsTurn is provided");
1001
+ }
1002
+ }
1003
+ }
1004
+ function recordSdkPlanLimitsFailure(limits, profileId, error) {
1005
+ const rawMessage = error instanceof Error ? error.message : String(error);
1006
+ const boundedMessage = rawMessage.trim().length > 0 ? rawMessage.slice(0, 4096) : "Plan limits read failed";
1007
+ limits.set(profileId, planLimitsReadFailed2({
1008
+ previous: limits.get(profileId),
1009
+ error: boundedMessage,
1010
+ now: new Date
1011
+ }));
1012
+ }
558
1013
  async function openClaudeSdkSession(config, limits, input) {
1014
+ validateClaudeSdkOpenInput(input);
559
1015
  const ambient = config.ambient ?? process.env;
560
1016
  const profile = engineProfile("claude-sdk", input.profile);
561
1017
  input.signal?.throwIfAborted();
562
1018
  const sessionId = input.nativeThreadId ?? randomUUID2();
563
1019
  const transcript = claudeTranscriptPath2({ home: profile.home, cwd: input.cwd, sessionId });
564
- let resume = input.nativeThreadId !== undefined && await claudeTranscriptExists(transcript);
1020
+ const transcriptExists = input.nativeThreadId !== undefined && await claudeTranscriptExists(transcript);
1021
+ let resume = transcriptExists || input.resumeSessionAt !== undefined;
1022
+ let pendingResumeSessionAt = input.resumeSessionAt;
1023
+ let pendingResumeDropsTurn = input.resumeDropsTurn;
565
1024
  let current;
566
1025
  let startingTurn = false;
1026
+ let opened = false;
567
1027
  let closed = false;
568
1028
  let providerPid;
569
1029
  let activeModel = config.model;
@@ -593,7 +1053,10 @@ async function openClaudeSdkSession(config, limits, input) {
593
1053
  });
594
1054
  const canUseTool = createSdkCanUseTool({
595
1055
  getTurn: () => current,
596
- isClosed: () => closed
1056
+ isClosed: () => closed,
1057
+ ...config.onPermissionRequest !== undefined && {
1058
+ onPermissionRequest: config.onPermissionRequest
1059
+ }
597
1060
  });
598
1061
  const ensureQuery = async (startLoopImmediately) => {
599
1062
  if (closed)
@@ -612,6 +1075,12 @@ async function openClaudeSdkSession(config, limits, input) {
612
1075
  limits,
613
1076
  sessionId,
614
1077
  resume,
1078
+ ...pendingResumeSessionAt !== undefined && {
1079
+ resumeSessionAt: pendingResumeSessionAt
1080
+ },
1081
+ ...pendingResumeDropsTurn !== undefined && {
1082
+ resumeDropsTurn: pendingResumeDropsTurn
1083
+ },
615
1084
  activeModel,
616
1085
  activePermissionMode,
617
1086
  flagSettingsOverlay,
@@ -632,9 +1101,12 @@ async function openClaudeSdkSession(config, limits, input) {
632
1101
  if (providerPid === exitedPid)
633
1102
  providerPid = undefined;
634
1103
  },
1104
+ ...input.onStartupPhase !== undefined && { onStartupPhase: input.onStartupPhase },
635
1105
  onExit: (exited, error) => {
636
1106
  const ownsSession = running === exited;
1107
+ const shouldNotify = ownsSession && opened && !closed && !linked.signal.aborted;
637
1108
  const turn = ownsSession ? current : undefined;
1109
+ const duringTurn = turn !== undefined;
638
1110
  if (ownsSession) {
639
1111
  running = undefined;
640
1112
  current = undefined;
@@ -642,6 +1114,12 @@ async function openClaudeSdkSession(config, limits, input) {
642
1114
  }
643
1115
  loseEngineTurn(turn, stoppedPermission("The Claude SDK query ended"), error);
644
1116
  exited.close();
1117
+ if (shouldNotify) {
1118
+ notifyQueryExit(config.onQueryExit, error, {
1119
+ duringTurn,
1120
+ nativeThreadId: sessionId
1121
+ });
1122
+ }
645
1123
  }
646
1124
  }).then((handle) => {
647
1125
  running = handle;
@@ -682,6 +1160,8 @@ async function openClaudeSdkSession(config, limits, input) {
682
1160
  },
683
1161
  markResumable: () => {
684
1162
  resume = true;
1163
+ pendingResumeSessionAt = undefined;
1164
+ pendingResumeDropsTurn = undefined;
685
1165
  },
686
1166
  ensureQuery
687
1167
  });
@@ -697,8 +1177,13 @@ async function openClaudeSdkSession(config, limits, input) {
697
1177
  },
698
1178
  recordFlagSettings: (settings) => {
699
1179
  flagSettingsOverlay = { ...flagSettingsOverlay, ...settings };
700
- }
1180
+ },
1181
+ recordPlanLimits: (next) => {
1182
+ limits.set(profile.profileId, next);
1183
+ },
1184
+ recordPlanLimitsFailure: (error) => recordSdkPlanLimitsFailure(limits, profile.profileId, error)
701
1185
  });
1186
+ opened = true;
702
1187
  return {
703
1188
  nativeThreadId: sessionId,
704
1189
  get providerPid() {
@@ -718,15 +1203,33 @@ async function openClaudeSdkSession(config, limits, input) {
718
1203
  function createClaudeSdkDriver(config) {
719
1204
  validateClaudeSdkConfig(config);
720
1205
  const limits = new Map;
1206
+ const capabilities = {
1207
+ runtimePolicyEnforcement: "native",
1208
+ sessionApproval: true,
1209
+ interruptOnDeny: true,
1210
+ updatedToolInput: true,
1211
+ structuredInput: false,
1212
+ steer: false,
1213
+ fork: config.forkSession !== undefined,
1214
+ revert: false,
1215
+ compact: false,
1216
+ injectItems: false,
1217
+ backgroundWorkOutlivesTurn: config.onEvent !== undefined,
1218
+ multiThreadPerProcess: false,
1219
+ images: config.resolveFile !== undefined,
1220
+ planLimits: "pull"
1221
+ };
721
1222
  return {
722
1223
  engine: "claude-sdk",
723
1224
  reconcile: "client-id",
1225
+ capabilities,
724
1226
  async info() {
725
1227
  return {
726
1228
  engine: "claude-sdk",
727
1229
  version: config.sdkVersion,
728
1230
  reconcile: "client-id",
729
- models: { answer: "not-asked" }
1231
+ models: { answer: "not-asked" },
1232
+ capabilities
730
1233
  };
731
1234
  },
732
1235
  async status(rawProfile) {
@@ -748,9 +1251,14 @@ function createClaudeSdkDriver(config) {
748
1251
  throw new Error("Claude SDK driver was not configured with forkSession");
749
1252
  }
750
1253
  return config.forkSession(sessionId, options);
751
- }
1254
+ },
1255
+ probeCapabilities: (input) => probeClaudeSdkCapabilities(config, limits, input)
752
1256
  };
753
1257
  }
754
1258
  export {
1259
+ ClaudeRuntimeEventSchema2 as ClaudeRuntimeEventSchema,
1260
+ ClaudeSdkTokenPairSchema,
1261
+ ClaudeSdkTurnUsageSchema,
1262
+ ClaudeTaskUsageSchema2 as ClaudeTaskUsageSchema,
755
1263
  createClaudeSdkDriver
756
1264
  };