stitchkit 0.128.0 → 0.129.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 (162) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/agent-executor/claude/transcript.d.ts +2 -2
  3. package/dist/agent-executor/claude/transcript.d.ts.map +1 -1
  4. package/dist/agent-executor/claude-sdk/controls.d.ts +19 -0
  5. package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -0
  6. package/dist/agent-executor/claude-sdk/driver.d.ts +114 -4
  7. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  8. package/dist/agent-executor/claude-sdk/query-loop.d.ts +46 -0
  9. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -0
  10. package/dist/agent-executor/claude-sdk/query-options.d.ts +27 -0
  11. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -0
  12. package/dist/agent-executor/claude-sdk/session.d.ts +6 -5
  13. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  14. package/dist/agent-executor/codex/classify.d.ts.map +1 -1
  15. package/dist/agent-executor/codex/connect.d.ts +45 -0
  16. package/dist/agent-executor/codex/connect.d.ts.map +1 -0
  17. package/dist/agent-executor/codex/driver.d.ts +51 -10
  18. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  19. package/dist/agent-executor/codex/limits.d.ts +11 -2
  20. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  21. package/dist/agent-executor/codex/protocol.d.ts +49 -4
  22. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  23. package/dist/agent-executor/codex/session-controls.d.ts +155 -0
  24. package/dist/agent-executor/codex/session-controls.d.ts.map +1 -0
  25. package/dist/agent-executor/codex/session.d.ts +27 -31
  26. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  27. package/dist/agent-executor/codex/unix-socket-target.d.ts +26 -0
  28. package/dist/agent-executor/codex/unix-socket-target.d.ts.map +1 -0
  29. package/dist/agent-executor/codex/unix-socket.d.ts +26 -0
  30. package/dist/agent-executor/codex/unix-socket.d.ts.map +1 -0
  31. package/dist/agent-executor/codex/ws-frame.d.ts +15 -0
  32. package/dist/agent-executor/codex/ws-frame.d.ts.map +1 -0
  33. package/dist/agent-executor/contract.d.ts +2 -0
  34. package/dist/agent-executor/contract.d.ts.map +1 -1
  35. package/dist/agent-executor/engine-process.d.ts +9 -0
  36. package/dist/agent-executor/engine-process.d.ts.map +1 -1
  37. package/dist/agent-executor/hello.d.ts +8 -0
  38. package/dist/agent-executor/hello.d.ts.map +1 -1
  39. package/dist/agent-runtime/branch-observations.d.ts +5 -5
  40. package/dist/agent-runtime/branch-provider.d.ts +2 -2
  41. package/dist/agent-runtime/sql-rows.d.ts +10 -10
  42. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  43. package/dist/entrypoints/agent-executor/acp.js +7 -7
  44. package/dist/entrypoints/agent-executor/claude-sdk.d.ts +1 -1
  45. package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
  46. package/dist/entrypoints/agent-executor/claude-sdk.js +532 -101
  47. package/dist/entrypoints/agent-executor/claude.js +8 -8
  48. package/dist/entrypoints/agent-executor/codex.d.ts +4 -0
  49. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  50. package/dist/entrypoints/agent-executor/codex.js +1491 -228
  51. package/dist/entrypoints/agent-executor.js +7 -7
  52. package/dist/entrypoints/agent-runtime/browser.js +1 -1
  53. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  54. package/dist/entrypoints/agent-runtime/harness.js +8 -8
  55. package/dist/entrypoints/agent-runtime/openrouter.js +2 -2
  56. package/dist/entrypoints/agent-runtime/postgres.js +6 -6
  57. package/dist/entrypoints/agent-runtime/realtime.js +4 -4
  58. package/dist/entrypoints/agent-runtime/sandbox.js +5 -5
  59. package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
  60. package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
  61. package/dist/entrypoints/agent-runtime/testing.js +5 -5
  62. package/dist/entrypoints/agent-runtime.js +17 -17
  63. package/dist/entrypoints/application/directory-inbox.js +2 -2
  64. package/dist/entrypoints/application/opentelemetry.js +2 -2
  65. package/dist/entrypoints/application.js +2 -2
  66. package/dist/entrypoints/cli/publish.js +3 -3
  67. package/dist/entrypoints/cli.js +8 -8
  68. package/dist/entrypoints/contract.js +2 -2
  69. package/dist/entrypoints/files/packaging.js +2 -2
  70. package/dist/entrypoints/files.js +7 -7
  71. package/dist/entrypoints/handler.js +4 -4
  72. package/dist/entrypoints/http.js +5 -5
  73. package/dist/entrypoints/index.js +7 -7
  74. package/dist/entrypoints/node.js +5 -5
  75. package/dist/entrypoints/observability.js +4 -4
  76. package/dist/entrypoints/primitives.js +2 -2
  77. package/dist/entrypoints/process.js +5 -5
  78. package/dist/entrypoints/react.js +1 -1
  79. package/dist/entrypoints/remote.js +2 -2
  80. package/dist/entrypoints/server.js +6 -6
  81. package/dist/entrypoints/service-host/macos.js +5 -5
  82. package/dist/entrypoints/service-host.js +7 -7
  83. package/dist/entrypoints/spend.js +1 -1
  84. package/dist/entrypoints/sync/postgres.js +1 -1
  85. package/dist/entrypoints/sync.js +2 -2
  86. package/dist/entrypoints/telegram.js +2 -2
  87. package/dist/entrypoints/testing.js +5 -5
  88. package/dist/entrypoints/tools/agent.js +5 -5
  89. package/dist/entrypoints/tools/connections.js +2 -2
  90. package/dist/entrypoints/tools/invoker.js +4 -4
  91. package/dist/entrypoints/tools/mcp.js +5 -5
  92. package/dist/entrypoints/tools/toolkit.js +8 -8
  93. package/dist/entrypoints/tools.js +12 -12
  94. package/dist/entrypoints/tracking/contract.js +1 -1
  95. package/dist/entrypoints/xlsx.js +1 -1
  96. package/dist/{index-prf6ayhf.js → index-13wmzpa6.js} +1 -1
  97. package/dist/{index-n7f89hjw.js → index-17qgm6xe.js} +3 -3
  98. package/dist/{index-wv8dqy7q.js → index-205456mf.js} +1 -1
  99. package/dist/{index-pwskmywy.js → index-21cfxc4z.js} +1 -1
  100. package/dist/{index-d4svrknj.js → index-39c2hj6h.js} +2 -2
  101. package/dist/{index-sfzfd2m2.js → index-39rmc00v.js} +1 -1
  102. package/dist/{index-ky3ardqn.js → index-3fym4j8n.js} +1 -1
  103. package/dist/{index-c5gp2gh6.js → index-5tdc0q43.js} +1 -1
  104. package/dist/{index-3ypvpkwr.js → index-669374qc.js} +1 -1
  105. package/dist/{index-m18xm96h.js → index-7jqn3b3g.js} +4 -4
  106. package/dist/{index-5jyjb4s0.js → index-80acsm27.js} +1 -1
  107. package/dist/{index-xmr47znh.js → index-827bgv33.js} +1 -1
  108. package/dist/{index-v1mxss62.js → index-93n6jwy0.js} +3 -3
  109. package/dist/{index-d54npte7.js → index-9kpxz49v.js} +2 -2
  110. package/dist/{index-xv9jb84s.js → index-9sfhje6y.js} +3 -3
  111. package/dist/{index-bh4pmtr9.js → index-afb6z77w.js} +3 -1
  112. package/dist/{index-9y0afd5f.js → index-apf5g7y9.js} +1 -1
  113. package/dist/{index-4qvyhn23.js → index-bjmj2q1z.js} +1 -1
  114. package/dist/{index-g3e57qj6.js → index-dcsxj68j.js} +2 -2
  115. package/dist/{index-waa6t4zx.js → index-dnzxxf8a.js} +1 -1
  116. package/dist/{index-gf92hc87.js → index-fgahdc7s.js} +2 -2
  117. package/dist/{index-kzavdze2.js → index-gr0kxymw.js} +5 -1
  118. package/dist/{index-e06z0tkb.js → index-gya4hwh3.js} +2 -2
  119. package/dist/{index-gzny6zsw.js → index-hab790s6.js} +5 -5
  120. package/dist/{index-bz3gn6cs.js → index-j0ef04jw.js} +2 -2
  121. package/dist/{index-rhb33thr.js → index-jcge9tx3.js} +1 -1
  122. package/dist/{index-pn5b11ce.js → index-mkfhpk11.js} +1 -1
  123. package/dist/{index-1qwrczr1.js → index-mttkdm5a.js} +1 -1
  124. package/dist/{index-rxnyygke.js → index-n3bm7zqq.js} +1 -1
  125. package/dist/{index-6wp4dn9d.js → index-p06z7g7w.js} +3 -3
  126. package/dist/{index-kt6dh1n6.js → index-p16q492v.js} +1 -1
  127. package/dist/{index-t7wa7k12.js → index-pp97q86a.js} +1 -1
  128. package/dist/{index-39n02e0q.js → index-psye60qn.js} +1 -1
  129. package/dist/{index-5ptwb6ka.js → index-pzhqydxb.js} +1 -1
  130. package/dist/{index-7kfcb576.js → index-qa2jjb65.js} +1 -1
  131. package/dist/{index-rzeezh79.js → index-qhjmmsm2.js} +2 -2
  132. package/dist/{index-7grgs8cx.js → index-qpzyahe3.js} +2 -2
  133. package/dist/{index-jfecdk1e.js → index-r97ppg0g.js} +2 -2
  134. package/dist/{index-bmaz3jzy.js → index-rjs94dny.js} +1 -1
  135. package/dist/{index-5v5vg85s.js → index-rxh3qy4x.js} +32 -5
  136. package/dist/{index-en8e5zsj.js → index-ryxb427v.js} +1 -1
  137. package/dist/{index-y065r8g5.js → index-sd4e5x5j.js} +7 -7
  138. package/dist/{index-g56ht6qf.js → index-t3qcac2a.js} +1 -1
  139. package/dist/{index-13dnv6d0.js → index-wv2amqm4.js} +4 -4
  140. package/dist/{index-4j8efqr3.js → index-x2fb37t0.js} +2 -2
  141. package/dist/{index-0gqs8ght.js → index-y71zn1gw.js} +32 -4
  142. package/dist/{index-wavv538x.js → index-ybdq8kk2.js} +3 -3
  143. package/dist/{index-4gk6k3zc.js → index-ycr4pk0z.js} +1 -1
  144. package/dist/{index-0tyt97nk.js → index-yrr3n391.js} +1 -1
  145. package/dist/{index-v37b2cd6.js → index-z20pdxeb.js} +2 -2
  146. package/dist/{index-8x22nprv.js → index-z9d74jmb.js} +3 -3
  147. package/dist/{index-3tnwtz38.js → index-zhshhxew.js} +1 -1
  148. package/dist/{index-hj1zq7mh.js → index-znd1b57f.js} +3 -3
  149. package/dist/internal/positive-integer.d.ts +2 -0
  150. package/dist/internal/positive-integer.d.ts.map +1 -1
  151. package/dist/internal/unix-socket.d.ts +7 -0
  152. package/dist/internal/unix-socket.d.ts.map +1 -1
  153. package/llms/agent-executor-claude-sdk.txt +13 -10
  154. package/llms/agent-executor-claude.txt +1 -1
  155. package/llms/agent-executor-codex.txt +9 -3
  156. package/llms/agent-executor.txt +2 -2
  157. package/llms/stitchkit.txt +74 -74
  158. package/llms/{upgrading-0.128.0.txt → upgrading-0.128.0-0.129.0.txt} +31 -3
  159. package/llms/upgrading.txt +1 -1
  160. package/llms-full.txt +127 -90
  161. package/llms.txt +6 -6
  162. package/package.json +1 -1
@@ -3,10 +3,10 @@ import {
3
3
  InteractionReplySchema2,
4
4
  engineProfile,
5
5
  engineEnvironment2
6
- } from "../../index-bh4pmtr9.js";
6
+ } from "../../index-afb6z77w.js";
7
7
  import"../../index-09f7w2qq.js";
8
8
  import"../../index-v59pxmf1.js";
9
- import"../../index-7kfcb576.js";
9
+ import"../../index-qa2jjb65.js";
10
10
  import"../../index-6kec3b14.js";
11
11
  import {
12
12
  nonEmptyString,
@@ -21,7 +21,7 @@ import {
21
21
  drainEngineRequests,
22
22
  endEngineTurn,
23
23
  loseEngineTurn
24
- } from "../../index-13dnv6d0.js";
24
+ } from "../../index-wv2amqm4.js";
25
25
  import {
26
26
  claudeUserContent,
27
27
  newClaudeTurnState,
@@ -30,20 +30,262 @@ import {
30
30
  claudeTranscriptPath2,
31
31
  claudeTranscriptExists,
32
32
  findTranscriptInput
33
- } from "../../index-0gqs8ght.js";
34
- import"../../index-5ptwb6ka.js";
33
+ } from "../../index-y71zn1gw.js";
34
+ import"../../index-pzhqydxb.js";
35
35
  import {
36
36
  mergeRateLimitEvent2
37
- } from "../../index-4qvyhn23.js";
37
+ } from "../../index-bjmj2q1z.js";
38
38
  import {
39
- abortReason
39
+ isPositiveSafeInteger
40
+ } from "../../index-gr0kxymw.js";
41
+ import {
42
+ assertTimerMs,
43
+ withSignalDeadline
44
+ } from "../../index-agy5fqgf.js";
45
+ import {
46
+ abortReason,
47
+ raceAbort
40
48
  } from "../../index-rptj3qnc.js";
41
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);
134
+ 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 }
171
+ };
172
+ }
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()");
202
+ }
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
+ }));
209
+ }
210
+
42
211
  // src/agent-executor/claude-sdk/session.ts
43
- import { randomUUID } from "node:crypto";
44
- function isUuid(value) {
45
- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
212
+ import { randomUUID as randomUUID2 } from "node:crypto";
213
+
214
+ // src/agent-executor/claude-sdk/controls.ts
215
+ function requireMethod(query, name) {
216
+ const fn = query[name];
217
+ if (typeof fn !== "function") {
218
+ throw new Error(`The configured Claude SDK query does not support ${String(name)}()`);
219
+ }
220
+ return fn;
221
+ }
222
+ function createClaudeSdkControls(host) {
223
+ const activeQuery = async () => {
224
+ if (host.isClosed())
225
+ throw new Error("The Claude SDK session is closed");
226
+ const active = await raceAbort(host.ensureQuery(), host.signal);
227
+ if (host.isClosed())
228
+ throw new Error("The Claude SDK session is closed");
229
+ return active.query;
230
+ };
231
+ const guarded = (promise) => raceAbort(promise, host.signal);
232
+ return {
233
+ async setModel(model) {
234
+ const query = await activeQuery();
235
+ await guarded(requireMethod(query, "setModel").call(query, model));
236
+ host.setActiveModel(model);
237
+ },
238
+ async setPermissionMode(mode) {
239
+ const query = await activeQuery();
240
+ await guarded(requireMethod(query, "setPermissionMode").call(query, mode));
241
+ host.setActivePermissionMode(mode);
242
+ },
243
+ async applyFlagSettings(settings) {
244
+ const query = await activeQuery();
245
+ await guarded(requireMethod(query, "applyFlagSettings").call(query, settings));
246
+ host.recordFlagSettings(settings);
247
+ },
248
+ async initializationResult() {
249
+ const query = await activeQuery();
250
+ return guarded(requireMethod(query, "initializationResult").call(query));
251
+ },
252
+ async supportedModels() {
253
+ const query = await activeQuery();
254
+ return guarded(requireMethod(query, "supportedModels").call(query));
255
+ },
256
+ async supportedCommands() {
257
+ const query = await activeQuery();
258
+ return guarded(requireMethod(query, "supportedCommands").call(query));
259
+ },
260
+ async accountInfo() {
261
+ const query = await activeQuery();
262
+ return guarded(requireMethod(query, "accountInfo").call(query));
263
+ },
264
+ async getContextUsage(opts) {
265
+ const query = await activeQuery();
266
+ return guarded(requireMethod(query, "getContextUsage").call(query, opts));
267
+ },
268
+ async mcpServerStatus() {
269
+ const query = await activeQuery();
270
+ return guarded(requireMethod(query, "mcpServerStatus").call(query));
271
+ },
272
+ async toggleMcpServer(serverName, enabled) {
273
+ const query = await activeQuery();
274
+ await guarded(requireMethod(query, "toggleMcpServer").call(query, serverName, enabled));
275
+ },
276
+ async reconnectMcpServer(serverName) {
277
+ const query = await activeQuery();
278
+ await guarded(requireMethod(query, "reconnectMcpServer").call(query, serverName));
279
+ },
280
+ async rewindFiles(userMessageId, options) {
281
+ const query = await activeQuery();
282
+ return guarded(requireMethod(query, "rewindFiles").call(query, userMessageId, options));
283
+ }
284
+ };
46
285
  }
286
+
287
+ // src/agent-executor/claude-sdk/query-loop.ts
288
+ import { randomUUID } from "node:crypto";
47
289
  var SDK_ANSWER = { source: "claude-sdk", type: "PermissionResult" };
48
290
  var stoppedPermission = (message) => () => ({
49
291
  behavior: "deny",
@@ -152,23 +394,195 @@ function sdkTurnHandle(turn, query) {
152
394
  }
153
395
  };
154
396
  }
397
+ function runSdkQueryLoop(input) {
398
+ (async () => {
399
+ try {
400
+ for await (const record of input.handle.query) {
401
+ const turn = input.getTurn();
402
+ const verdict = classifyClaudeRecord(record, turn?.state ?? newClaudeTurnState("between-turns"));
403
+ if (verdict.kind === "limits") {
404
+ input.limits.set(input.profileId, mergeRateLimitEvent2({
405
+ previous: input.limits.get(input.profileId),
406
+ windows: claudePlanWindows2(verdict.info),
407
+ now: new Date
408
+ }));
409
+ } else if (verdict.kind === "deltas") {
410
+ for (const delta of verdict.deltas)
411
+ offerTurnDelta(turn?.channel, delta);
412
+ } else if (verdict.kind === "end") {
413
+ endEngineTurn(turn, stoppedPermission("The turn ended"), verdict.deltas);
414
+ input.clearTurn();
415
+ } else if (verdict.kind === "unhandled") {
416
+ offerTurnDelta(turn?.channel, verdict.delta);
417
+ }
418
+ }
419
+ throw new Error("The Agent SDK query ended during the turn");
420
+ } catch (error) {
421
+ input.onExit(input.handle, error);
422
+ }
423
+ })();
424
+ }
425
+
426
+ // src/agent-executor/claude-sdk/session.ts
427
+ function isUuid(value) {
428
+ 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
+ }
430
+ function createSdkStartTurn(input) {
431
+ return imageTurnStarter({
432
+ driverLabel: "The Agent SDK driver",
433
+ busyMessage: "A turn is already running in this Claude session",
434
+ imageOptions: input.config,
435
+ signal: input.signal,
436
+ check(turnInput) {
437
+ if (input.isClosed())
438
+ throw new Error("The Claude SDK session is closed");
439
+ if (input.getTurn() !== undefined || input.isStarting())
440
+ throw new Error("A turn is already running in this Claude session");
441
+ if (!isUuid(turnInput.clientId))
442
+ throw new TypeError("The Agent SDK driver needs a UUID client id");
443
+ },
444
+ async dispatch(turnInput, parts) {
445
+ const clientId = turnInput.clientId;
446
+ if (!isUuid(clientId))
447
+ throw new TypeError("The Agent SDK driver needs a UUID client id");
448
+ input.setStarting(true);
449
+ let active;
450
+ try {
451
+ active = await input.ensureQuery(false);
452
+ } finally {
453
+ input.setStarting(false);
454
+ }
455
+ if (input.isClosed())
456
+ throw new Error("The Claude SDK session is closed");
457
+ if (input.getTurn() !== undefined)
458
+ throw new Error("A turn is already running in this Claude session");
459
+ const turn = {
460
+ state: newClaudeTurnState(turnInput.turnId),
461
+ channel: createTurnDeltaChannel(),
462
+ pending: new Map
463
+ };
464
+ input.setTurn(turn);
465
+ try {
466
+ active.send({
467
+ type: "user",
468
+ message: { role: "user", content: claudeUserContent(parts) },
469
+ parent_tool_use_id: null,
470
+ uuid: clientId,
471
+ session_id: input.sessionId
472
+ });
473
+ input.markResumable();
474
+ active.startLoop();
475
+ return sdkTurnHandle(turn, active.query);
476
+ } catch (error) {
477
+ if (input.getTurn() === turn)
478
+ input.setTurn(undefined);
479
+ throw error;
480
+ }
481
+ }
482
+ });
483
+ }
484
+ async function launchSingleSdkQuery(input) {
485
+ if (input.isClosed())
486
+ throw new Error("The Claude SDK session is closed");
487
+ input.signal.throwIfAborted();
488
+ const pushed = pushablePrompt();
489
+ let query;
490
+ try {
491
+ query = input.config.query({
492
+ prompt: pushed.prompt,
493
+ options: buildClaudeSdkQueryOptions({
494
+ config: input.config,
495
+ cwd: input.cwd,
496
+ env: input.env,
497
+ canUseTool: input.canUseTool,
498
+ sessionId: input.sessionId,
499
+ resume: input.resume,
500
+ activeModel: input.activeModel,
501
+ activePermissionMode: input.activePermissionMode,
502
+ recordPid: input.recordPid,
503
+ onPidExit: input.onPidExit
504
+ })
505
+ });
506
+ } catch (error) {
507
+ input.recordPid(undefined);
508
+ pushed.end();
509
+ throw error;
510
+ }
511
+ let closedOnce = false;
512
+ let loopStarted = false;
513
+ const closeHandle = () => {
514
+ if (closedOnce)
515
+ return;
516
+ closedOnce = true;
517
+ pushed.end();
518
+ closeQuerySafely(query);
519
+ };
520
+ const handle = {
521
+ query,
522
+ send: pushed.send,
523
+ startLoop() {
524
+ if (loopStarted || closedOnce)
525
+ return;
526
+ loopStarted = true;
527
+ runSdkQueryLoop({
528
+ handle,
529
+ profileId: input.profileId,
530
+ limits: input.limits,
531
+ getTurn: input.getTurn,
532
+ clearTurn: input.clearTurn,
533
+ onExit: input.onExit
534
+ });
535
+ },
536
+ close: closeHandle
537
+ };
538
+ input.setInFlightClose(closeHandle);
539
+ try {
540
+ if (hasDelegationVerification(input.config.verifyDelegation)) {
541
+ await verifyClaudeSdkDelegation(query, input.config.verifyDelegation, input.signal);
542
+ }
543
+ if (input.flagSettingsOverlay !== undefined) {
544
+ await replayClaudeSdkFlagSettings(query, input.flagSettingsOverlay, input.signal);
545
+ }
546
+ if (input.isClosed() || input.signal.aborted) {
547
+ throw input.isClosed() ? new Error("The Claude SDK session is closed") : abortReason(input.signal);
548
+ }
549
+ } catch (error) {
550
+ input.setInFlightClose(undefined);
551
+ input.recordPid(undefined);
552
+ closeHandle();
553
+ throw error;
554
+ }
555
+ input.setInFlightClose(undefined);
556
+ return handle;
557
+ }
155
558
  async function openClaudeSdkSession(config, limits, input) {
156
559
  const ambient = config.ambient ?? process.env;
157
560
  const profile = engineProfile("claude-sdk", input.profile);
158
561
  input.signal?.throwIfAborted();
159
- const sessionId = input.nativeThreadId ?? randomUUID();
562
+ const sessionId = input.nativeThreadId ?? randomUUID2();
160
563
  const transcript = claudeTranscriptPath2({ home: profile.home, cwd: input.cwd, sessionId });
161
564
  let resume = input.nativeThreadId !== undefined && await claudeTranscriptExists(transcript);
162
565
  let current;
566
+ let startingTurn = false;
163
567
  let closed = false;
568
+ let providerPid;
569
+ let activeModel = config.model;
570
+ let activePermissionMode = config.permissionMode ?? "default";
571
+ let flagSettingsOverlay;
164
572
  let running;
573
+ let opening;
574
+ let inFlightClose;
165
575
  const shutdown = (reason) => {
166
576
  if (closed)
167
577
  return;
168
578
  closed = true;
579
+ providerPid = undefined;
169
580
  const turn = current;
170
581
  current = undefined;
171
582
  loseEngineTurn(turn, stoppedPermission("The session was closed"), reason);
583
+ const pendingClose = inFlightClose;
584
+ inFlightClose = undefined;
585
+ pendingClose?.();
172
586
  const active = running;
173
587
  running = undefined;
174
588
  active?.close();
@@ -181,109 +595,117 @@ async function openClaudeSdkSession(config, limits, input) {
181
595
  getTurn: () => current,
182
596
  isClosed: () => closed
183
597
  });
184
- const start = () => {
185
- const pushed = pushablePrompt();
186
- const query = config.query({
187
- prompt: pushed.prompt,
188
- options: {
598
+ const ensureQuery = async (startLoopImmediately) => {
599
+ if (closed)
600
+ throw new Error("The Claude SDK session is closed");
601
+ if (running !== undefined) {
602
+ if (startLoopImmediately)
603
+ running.startLoop();
604
+ return running;
605
+ }
606
+ if (opening === undefined) {
607
+ const promise = launchSingleSdkQuery({
608
+ config,
189
609
  cwd: input.cwd,
190
610
  env: engineEnvironment2(profile, ambient),
191
- includePartialMessages: true,
192
- permissionMode: config.permissionMode ?? "default",
611
+ profileId: profile.profileId,
612
+ limits,
613
+ sessionId,
614
+ resume,
615
+ activeModel,
616
+ activePermissionMode,
617
+ flagSettingsOverlay,
618
+ signal: linked.signal,
193
619
  canUseTool,
194
- ...config.model !== undefined && { model: config.model },
195
- ...resume ? { resume: sessionId } : { sessionId }
196
- }
197
- });
198
- let closedOnce = false;
199
- const closeHandle = () => {
200
- if (closedOnce)
201
- return;
202
- closedOnce = true;
203
- pushed.end();
204
- closeQuerySafely(query);
205
- };
206
- const handle = { query, send: pushed.send, close: closeHandle };
207
- running = handle;
208
- resume = true;
209
- (async () => {
210
- try {
211
- for await (const record of query) {
212
- const turn = current;
213
- const verdict = classifyClaudeRecord(record, turn?.state ?? newClaudeTurnState("between-turns"));
214
- if (verdict.kind === "limits") {
215
- limits.set(profile.profileId, mergeRateLimitEvent2({
216
- previous: limits.get(profile.profileId),
217
- windows: claudePlanWindows2(verdict.info),
218
- now: new Date
219
- }));
220
- } else if (verdict.kind === "deltas") {
221
- for (const delta of verdict.deltas)
222
- offerTurnDelta(turn?.channel, delta);
223
- } else if (verdict.kind === "end") {
224
- endEngineTurn(turn, stoppedPermission("The turn ended"), verdict.deltas);
620
+ isClosed: () => closed,
621
+ getTurn: () => current,
622
+ clearTurn: () => {
623
+ current = undefined;
624
+ },
625
+ setInFlightClose: (fn) => {
626
+ inFlightClose = fn;
627
+ },
628
+ recordPid: (pid) => {
629
+ providerPid = pid;
630
+ },
631
+ onPidExit: (exitedPid) => {
632
+ if (providerPid === exitedPid)
633
+ providerPid = undefined;
634
+ },
635
+ onExit: (exited, error) => {
636
+ const ownsSession = running === exited;
637
+ const turn = ownsSession ? current : undefined;
638
+ if (ownsSession) {
639
+ running = undefined;
225
640
  current = undefined;
226
- } else if (verdict.kind === "unhandled") {
227
- offerTurnDelta(turn?.channel, verdict.delta);
641
+ providerPid = undefined;
228
642
  }
643
+ loseEngineTurn(turn, stoppedPermission("The Claude SDK query ended"), error);
644
+ exited.close();
229
645
  }
230
- throw new Error("The Agent SDK query ended during the turn");
231
- } catch (error) {
232
- const ownsSession = running === handle;
233
- const turn = ownsSession ? current : undefined;
234
- if (ownsSession) {
235
- running = undefined;
236
- current = undefined;
237
- }
238
- loseEngineTurn(turn, stoppedPermission("The Claude SDK query ended"), error);
239
- closeHandle();
240
- }
241
- })();
646
+ }).then((handle) => {
647
+ running = handle;
648
+ return handle;
649
+ }).finally(() => {
650
+ if (opening === promise)
651
+ opening = undefined;
652
+ });
653
+ opening = promise;
654
+ }
655
+ const handle = await opening;
656
+ if (startLoopImmediately)
657
+ handle.startLoop();
242
658
  return handle;
243
659
  };
244
- const startTurn = imageTurnStarter({
245
- driverLabel: "The Agent SDK driver",
246
- busyMessage: "A turn is already running in this Claude session",
247
- imageOptions: config,
660
+ if (hasDelegationVerification(config.verifyDelegation)) {
661
+ try {
662
+ await ensureQuery(true);
663
+ } catch (error) {
664
+ shutdown(error);
665
+ linked.abort();
666
+ linked.release();
667
+ throw error;
668
+ }
669
+ }
670
+ const startTurn = createSdkStartTurn({
671
+ config,
672
+ sessionId,
248
673
  signal: linked.signal,
249
- check(turnInput) {
250
- if (closed)
251
- throw new Error("The Claude SDK session is closed");
252
- if (current !== undefined)
253
- throw new Error("A turn is already running in this Claude session");
254
- if (!isUuid(turnInput.clientId))
255
- throw new TypeError("The Agent SDK driver needs a UUID client id");
256
- },
257
- dispatch(turnInput, parts) {
258
- const clientId = turnInput.clientId;
259
- if (!isUuid(clientId))
260
- throw new TypeError("The Agent SDK driver needs a UUID client id");
261
- const turn = {
262
- state: newClaudeTurnState(turnInput.turnId),
263
- channel: createTurnDeltaChannel(),
264
- pending: new Map
265
- };
674
+ isClosed: () => closed,
675
+ getTurn: () => current,
676
+ setTurn: (turn) => {
266
677
  current = turn;
267
- try {
268
- const active = running ?? start();
269
- active.send({
270
- type: "user",
271
- message: { role: "user", content: claudeUserContent(parts) },
272
- parent_tool_use_id: null,
273
- uuid: clientId,
274
- session_id: sessionId
275
- });
276
- return sdkTurnHandle(turn, active.query);
277
- } catch (error) {
278
- if (current === turn)
279
- current = undefined;
280
- throw error;
281
- }
678
+ },
679
+ isStarting: () => startingTurn,
680
+ setStarting: (value) => {
681
+ startingTurn = value;
682
+ },
683
+ markResumable: () => {
684
+ resume = true;
685
+ },
686
+ ensureQuery
687
+ });
688
+ const controls = createClaudeSdkControls({
689
+ signal: linked.signal,
690
+ isClosed: () => closed,
691
+ ensureQuery: () => ensureQuery(true),
692
+ setActiveModel: (model) => {
693
+ activeModel = model;
694
+ },
695
+ setActivePermissionMode: (mode) => {
696
+ activePermissionMode = mode;
697
+ },
698
+ recordFlagSettings: (settings) => {
699
+ flagSettingsOverlay = { ...flagSettingsOverlay, ...settings };
282
700
  }
283
701
  });
284
702
  return {
285
703
  nativeThreadId: sessionId,
704
+ get providerPid() {
705
+ return providerPid;
706
+ },
286
707
  startTurn,
708
+ ...controls,
287
709
  async close() {
288
710
  shutdown(new Error("The Claude SDK session closed"));
289
711
  linked.abort();
@@ -294,7 +716,7 @@ async function openClaudeSdkSession(config, limits, input) {
294
716
 
295
717
  // src/agent-executor/claude-sdk/driver.ts
296
718
  function createClaudeSdkDriver(config) {
297
- validateImageOptions(config);
719
+ validateClaudeSdkConfig(config);
298
720
  const limits = new Map;
299
721
  return {
300
722
  engine: "claude-sdk",
@@ -317,7 +739,16 @@ function createClaudeSdkDriver(config) {
317
739
  };
318
740
  },
319
741
  findInput: (input) => findTranscriptInput("claude-sdk", input),
320
- open: (input) => openClaudeSdkSession(config, limits, input)
742
+ open: (input) => openClaudeSdkSession(config, limits, input),
743
+ async forkSession(sessionId, options) {
744
+ if (sessionId.trim().length === 0) {
745
+ throw new TypeError("Claude SDK forkSession requires a non-empty sessionId");
746
+ }
747
+ if (config.forkSession === undefined) {
748
+ throw new Error("Claude SDK driver was not configured with forkSession");
749
+ }
750
+ return config.forkSession(sessionId, options);
751
+ }
321
752
  };
322
753
  }
323
754
  export {