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
@@ -0,0 +1,1300 @@
1
+ import {
2
+ InteractionReplySchema2,
3
+ PlanWindowSchema2,
4
+ PlanLimitsSchema2,
5
+ engineProfile
6
+ } from "./index-dbp6xemn.js";
7
+ import {
8
+ nonEmptyString,
9
+ epochSecondsToIso,
10
+ safeJsonValue,
11
+ clampUniqueWindowName
12
+ } from "./index-2s8sy57y.js";
13
+ import {
14
+ isSupportedImageMediaType
15
+ } from "./index-y0a4gt1s.js";
16
+ import {
17
+ errnoOf
18
+ } from "./index-jj9228tt.js";
19
+
20
+ // src/agent-executor/claude/classify.ts
21
+ import { z as z3 } from "zod";
22
+
23
+ // src/agent-executor/claude/events.ts
24
+ import { z } from "zod";
25
+ var MAX_BACKGROUND_TASKS = 1024;
26
+ var ClaudeTaskUsageSchema2 = z.strictObject({
27
+ totalTokens: z.int().nonnegative(),
28
+ toolUses: z.int().nonnegative(),
29
+ durationMs: z.number().nonnegative()
30
+ });
31
+ var ClaudeBackgroundTaskEntrySchema = z.strictObject({
32
+ taskId: z.string().min(1),
33
+ runId: z.string().min(1).optional(),
34
+ taskType: z.string().min(1),
35
+ subagentType: z.string().min(1).optional(),
36
+ description: z.string(),
37
+ parentTaskId: z.string().min(1).optional(),
38
+ ambient: z.boolean().optional()
39
+ });
40
+ var ClaudeTaskUpdatedPatchSchema = z.strictObject({
41
+ status: z.string().min(1).optional(),
42
+ description: z.string().optional(),
43
+ endTime: z.number().nonnegative().optional(),
44
+ totalPausedMs: z.number().nonnegative().optional(),
45
+ error: z.string().optional(),
46
+ isBackgrounded: z.boolean().optional()
47
+ });
48
+ var ClaudeApiRetryNoResponseSchema = z.strictObject({
49
+ waitedMs: z.number().nonnegative(),
50
+ retryWaitMs: z.number().nonnegative()
51
+ });
52
+ var ClaudeSubagentRetrySchema = z.strictObject({
53
+ agentId: z.string().min(1),
54
+ attempt: z.int().nonnegative(),
55
+ maxRetries: z.int().nonnegative(),
56
+ retryDelayMs: z.number().nonnegative(),
57
+ errorStatus: z.int().nullable(),
58
+ errorCategory: z.string().min(1)
59
+ });
60
+ var eventBase = {
61
+ uuid: z.string().min(1).optional(),
62
+ sessionId: z.string().min(1).optional()
63
+ };
64
+ var ClaudeRuntimeEventSchema2 = z.discriminatedUnion("type", [
65
+ z.strictObject({
66
+ type: z.literal("task_started"),
67
+ taskId: z.string().min(1),
68
+ runId: z.string().min(1).optional(),
69
+ toolUseId: z.string().min(1).optional(),
70
+ description: z.string(),
71
+ subagentType: z.string().min(1).optional(),
72
+ isBackgrounded: z.boolean().optional(),
73
+ spawnDepth: z.int().nonnegative().optional(),
74
+ parentTaskId: z.string().min(1).optional(),
75
+ taskType: z.string().min(1).optional(),
76
+ workflowName: z.string().min(1).optional(),
77
+ prompt: z.string().optional(),
78
+ skipTranscript: z.boolean().optional(),
79
+ ambient: z.boolean().optional(),
80
+ ...eventBase
81
+ }),
82
+ z.strictObject({
83
+ type: z.literal("task_updated"),
84
+ taskId: z.string().min(1),
85
+ runId: z.string().min(1).optional(),
86
+ patch: ClaudeTaskUpdatedPatchSchema,
87
+ ...eventBase
88
+ }),
89
+ z.strictObject({
90
+ type: z.literal("task_progress"),
91
+ taskId: z.string().min(1),
92
+ runId: z.string().min(1).optional(),
93
+ toolUseId: z.string().min(1).optional(),
94
+ description: z.string(),
95
+ subagentType: z.string().min(1).optional(),
96
+ usage: ClaudeTaskUsageSchema2.optional(),
97
+ lastToolName: z.string().min(1).optional(),
98
+ summary: z.string().optional(),
99
+ ...eventBase
100
+ }),
101
+ z.strictObject({
102
+ type: z.literal("task_notification"),
103
+ taskId: z.string().min(1),
104
+ runId: z.string().min(1).optional(),
105
+ toolUseId: z.string().min(1).optional(),
106
+ status: z.string().min(1),
107
+ reason: z.string().min(1).optional(),
108
+ outputFile: z.string().optional(),
109
+ summary: z.string(),
110
+ usage: ClaudeTaskUsageSchema2.optional(),
111
+ skipTranscript: z.boolean().optional(),
112
+ ambient: z.boolean().optional(),
113
+ ...eventBase
114
+ }),
115
+ z.strictObject({
116
+ type: z.literal("background_tasks_changed"),
117
+ tasks: z.array(ClaudeBackgroundTaskEntrySchema).max(MAX_BACKGROUND_TASKS),
118
+ ...eventBase
119
+ }),
120
+ z.strictObject({
121
+ type: z.literal("api_retry"),
122
+ attempt: z.int().nonnegative(),
123
+ maxRetries: z.int().nonnegative(),
124
+ retryDelayMs: z.number().nonnegative(),
125
+ errorStatus: z.int().nullable(),
126
+ error: z.string().min(1),
127
+ noResponse: ClaudeApiRetryNoResponseSchema.optional(),
128
+ ...eventBase
129
+ }),
130
+ z.strictObject({
131
+ type: z.literal("elicitation_complete"),
132
+ mcpServerName: z.string().min(1),
133
+ elicitationId: z.string().min(1),
134
+ ...eventBase
135
+ }),
136
+ z.strictObject({
137
+ type: z.literal("tool_progress"),
138
+ toolUseId: z.string().min(1),
139
+ toolName: z.string().min(1),
140
+ parentToolUseId: z.string().nullable(),
141
+ elapsedTimeSeconds: z.number().nonnegative(),
142
+ taskId: z.string().min(1).optional(),
143
+ heartbeat: z.boolean().optional(),
144
+ subagentType: z.string().min(1).optional(),
145
+ subagentRetry: ClaudeSubagentRetrySchema.optional(),
146
+ ...eventBase
147
+ })
148
+ ]);
149
+ var optWireStr = z.string().optional().transform(nonEmptyString);
150
+ var WireTaskUsageSchema = z.looseObject({
151
+ total_tokens: z.int().nonnegative(),
152
+ tool_uses: z.int().nonnegative(),
153
+ duration_ms: z.number().nonnegative()
154
+ }).transform((u) => ({
155
+ totalTokens: u.total_tokens,
156
+ toolUses: u.tool_uses,
157
+ durationMs: u.duration_ms
158
+ }));
159
+ var WireBase = { uuid: optWireStr, session_id: optWireStr };
160
+ var WireTaskStartedSchema = z.looseObject({
161
+ type: z.literal("system"),
162
+ subtype: z.literal("task_started"),
163
+ task_id: z.string().min(1),
164
+ run_id: optWireStr,
165
+ tool_use_id: optWireStr,
166
+ description: z.string(),
167
+ subagent_type: optWireStr,
168
+ is_backgrounded: z.boolean().optional(),
169
+ spawn_depth: z.int().nonnegative().optional(),
170
+ parent_task_id: optWireStr,
171
+ task_type: optWireStr,
172
+ workflow_name: optWireStr,
173
+ prompt: z.string().optional(),
174
+ skip_transcript: z.boolean().optional(),
175
+ ambient: z.boolean().optional(),
176
+ ...WireBase
177
+ });
178
+ var WireTaskUpdatedSchema = z.looseObject({
179
+ type: z.literal("system"),
180
+ subtype: z.literal("task_updated"),
181
+ task_id: z.string().min(1),
182
+ run_id: optWireStr,
183
+ patch: z.looseObject({
184
+ status: optWireStr,
185
+ description: z.string().optional(),
186
+ end_time: z.number().nonnegative().optional(),
187
+ total_paused_ms: z.number().nonnegative().optional(),
188
+ error: z.string().optional(),
189
+ is_backgrounded: z.boolean().optional()
190
+ }),
191
+ ...WireBase
192
+ });
193
+ var WireTaskProgressSchema = z.looseObject({
194
+ type: z.literal("system"),
195
+ subtype: z.literal("task_progress"),
196
+ task_id: z.string().min(1),
197
+ run_id: optWireStr,
198
+ tool_use_id: optWireStr,
199
+ description: z.string(),
200
+ subagent_type: optWireStr,
201
+ usage: WireTaskUsageSchema.optional(),
202
+ last_tool_name: optWireStr,
203
+ summary: z.string().optional(),
204
+ ...WireBase
205
+ });
206
+ var WireTaskNotificationSchema = z.looseObject({
207
+ type: z.literal("system"),
208
+ subtype: z.literal("task_notification"),
209
+ task_id: z.string().min(1),
210
+ run_id: optWireStr,
211
+ tool_use_id: optWireStr,
212
+ status: z.string().min(1),
213
+ reason: optWireStr,
214
+ output_file: z.string().optional(),
215
+ summary: z.string(),
216
+ usage: WireTaskUsageSchema.optional(),
217
+ skip_transcript: z.boolean().optional(),
218
+ ambient: z.boolean().optional(),
219
+ ...WireBase
220
+ });
221
+ var WireBackgroundTasksChangedSchema = z.looseObject({
222
+ type: z.literal("system"),
223
+ subtype: z.literal("background_tasks_changed"),
224
+ tasks: z.array(z.looseObject({
225
+ task_id: z.string().min(1),
226
+ run_id: optWireStr,
227
+ task_type: z.string().min(1),
228
+ subagent_type: optWireStr,
229
+ description: z.string(),
230
+ parent_task_id: optWireStr,
231
+ ambient: z.boolean().optional()
232
+ })).max(MAX_BACKGROUND_TASKS),
233
+ ...WireBase
234
+ });
235
+ var WireApiRetrySchema = z.looseObject({
236
+ type: z.literal("system"),
237
+ subtype: z.literal("api_retry"),
238
+ attempt: z.int().nonnegative(),
239
+ max_retries: z.int().nonnegative(),
240
+ retry_delay_ms: z.number().nonnegative(),
241
+ error_status: z.int().nullable(),
242
+ error: z.string().min(1),
243
+ no_response: z.looseObject({
244
+ waited_ms: z.number().nonnegative(),
245
+ retry_wait_ms: z.number().nonnegative()
246
+ }).optional(),
247
+ ...WireBase
248
+ });
249
+ var WireElicitationCompleteSchema = z.looseObject({
250
+ type: z.literal("system"),
251
+ subtype: z.literal("elicitation_complete"),
252
+ mcp_server_name: z.string().min(1),
253
+ elicitation_id: z.string().min(1),
254
+ ...WireBase
255
+ });
256
+ var WireToolProgressSchema = z.looseObject({
257
+ type: z.literal("tool_progress"),
258
+ tool_use_id: z.string().min(1),
259
+ tool_name: z.string().min(1),
260
+ parent_tool_use_id: z.string().nullable().optional(),
261
+ elapsed_time_seconds: z.number().nonnegative(),
262
+ task_id: optWireStr,
263
+ heartbeat: z.boolean().optional(),
264
+ subagent_type: optWireStr,
265
+ subagent_retry: z.looseObject({
266
+ agent_id: z.string().min(1),
267
+ attempt: z.int().nonnegative(),
268
+ max_retries: z.int().nonnegative(),
269
+ retry_delay_ms: z.number().nonnegative(),
270
+ error_status: z.int().nullable(),
271
+ error_category: z.string().min(1)
272
+ }).optional(),
273
+ ...WireBase
274
+ });
275
+ var RUNTIME_SYSTEM_SUBTYPES = new Set([
276
+ "task_started",
277
+ "task_updated",
278
+ "task_progress",
279
+ "task_notification",
280
+ "background_tasks_changed",
281
+ "api_retry",
282
+ "elicitation_complete"
283
+ ]);
284
+ function isClaudeRuntimeSystemSubtype(subtype) {
285
+ return RUNTIME_SYSTEM_SUBTYPES.has(subtype);
286
+ }
287
+ function baseFields(wire) {
288
+ return {
289
+ ...wire.uuid !== undefined && { uuid: wire.uuid },
290
+ ...wire.session_id !== undefined && { sessionId: wire.session_id }
291
+ };
292
+ }
293
+ function parseSystemRuntimeEvent(subtype, record) {
294
+ if (subtype === "task_started") {
295
+ const p = WireTaskStartedSchema.safeParse(record);
296
+ if (!p.success)
297
+ return;
298
+ const d = p.data;
299
+ return {
300
+ type: "task_started",
301
+ taskId: d.task_id,
302
+ description: d.description,
303
+ ...d.run_id !== undefined && { runId: d.run_id },
304
+ ...d.tool_use_id !== undefined && { toolUseId: d.tool_use_id },
305
+ ...d.subagent_type !== undefined && { subagentType: d.subagent_type },
306
+ ...d.is_backgrounded !== undefined && { isBackgrounded: d.is_backgrounded },
307
+ ...d.spawn_depth !== undefined && { spawnDepth: d.spawn_depth },
308
+ ...d.parent_task_id !== undefined && { parentTaskId: d.parent_task_id },
309
+ ...d.task_type !== undefined && { taskType: d.task_type },
310
+ ...d.workflow_name !== undefined && { workflowName: d.workflow_name },
311
+ ...d.prompt !== undefined && { prompt: d.prompt },
312
+ ...d.skip_transcript !== undefined && { skipTranscript: d.skip_transcript },
313
+ ...d.ambient !== undefined && { ambient: d.ambient },
314
+ ...baseFields(d)
315
+ };
316
+ }
317
+ if (subtype === "task_updated") {
318
+ const p = WireTaskUpdatedSchema.safeParse(record);
319
+ if (!p.success)
320
+ return;
321
+ const d = p.data;
322
+ return {
323
+ type: "task_updated",
324
+ taskId: d.task_id,
325
+ ...d.run_id !== undefined && { runId: d.run_id },
326
+ patch: {
327
+ ...d.patch.status !== undefined && { status: d.patch.status },
328
+ ...d.patch.description !== undefined && { description: d.patch.description },
329
+ ...d.patch.end_time !== undefined && { endTime: d.patch.end_time },
330
+ ...d.patch.total_paused_ms !== undefined && {
331
+ totalPausedMs: d.patch.total_paused_ms
332
+ },
333
+ ...d.patch.error !== undefined && { error: d.patch.error },
334
+ ...d.patch.is_backgrounded !== undefined && {
335
+ isBackgrounded: d.patch.is_backgrounded
336
+ }
337
+ },
338
+ ...baseFields(d)
339
+ };
340
+ }
341
+ if (subtype === "task_progress") {
342
+ const p = WireTaskProgressSchema.safeParse(record);
343
+ if (!p.success)
344
+ return;
345
+ const d = p.data;
346
+ return {
347
+ type: "task_progress",
348
+ taskId: d.task_id,
349
+ description: d.description,
350
+ ...d.run_id !== undefined && { runId: d.run_id },
351
+ ...d.tool_use_id !== undefined && { toolUseId: d.tool_use_id },
352
+ ...d.subagent_type !== undefined && { subagentType: d.subagent_type },
353
+ ...d.usage !== undefined && { usage: d.usage },
354
+ ...d.last_tool_name !== undefined && { lastToolName: d.last_tool_name },
355
+ ...d.summary !== undefined && { summary: d.summary },
356
+ ...baseFields(d)
357
+ };
358
+ }
359
+ if (subtype === "task_notification") {
360
+ const p = WireTaskNotificationSchema.safeParse(record);
361
+ if (!p.success)
362
+ return;
363
+ const d = p.data;
364
+ return {
365
+ type: "task_notification",
366
+ taskId: d.task_id,
367
+ status: d.status,
368
+ summary: d.summary,
369
+ ...d.run_id !== undefined && { runId: d.run_id },
370
+ ...d.tool_use_id !== undefined && { toolUseId: d.tool_use_id },
371
+ ...d.reason !== undefined && { reason: d.reason },
372
+ ...d.output_file !== undefined && { outputFile: d.output_file },
373
+ ...d.usage !== undefined && { usage: d.usage },
374
+ ...d.skip_transcript !== undefined && { skipTranscript: d.skip_transcript },
375
+ ...d.ambient !== undefined && { ambient: d.ambient },
376
+ ...baseFields(d)
377
+ };
378
+ }
379
+ if (subtype === "background_tasks_changed") {
380
+ const p = WireBackgroundTasksChangedSchema.safeParse(record);
381
+ if (!p.success)
382
+ return;
383
+ const d = p.data;
384
+ return {
385
+ type: "background_tasks_changed",
386
+ tasks: d.tasks.map((t) => ({
387
+ taskId: t.task_id,
388
+ taskType: t.task_type,
389
+ description: t.description,
390
+ ...t.run_id !== undefined && { runId: t.run_id },
391
+ ...t.subagent_type !== undefined && { subagentType: t.subagent_type },
392
+ ...t.parent_task_id !== undefined && { parentTaskId: t.parent_task_id },
393
+ ...t.ambient !== undefined && { ambient: t.ambient }
394
+ })),
395
+ ...baseFields(d)
396
+ };
397
+ }
398
+ if (subtype === "api_retry") {
399
+ const p = WireApiRetrySchema.safeParse(record);
400
+ if (!p.success)
401
+ return;
402
+ const d = p.data;
403
+ return {
404
+ type: "api_retry",
405
+ attempt: d.attempt,
406
+ maxRetries: d.max_retries,
407
+ retryDelayMs: d.retry_delay_ms,
408
+ errorStatus: d.error_status,
409
+ error: d.error,
410
+ ...d.no_response !== undefined && {
411
+ noResponse: {
412
+ waitedMs: d.no_response.waited_ms,
413
+ retryWaitMs: d.no_response.retry_wait_ms
414
+ }
415
+ },
416
+ ...baseFields(d)
417
+ };
418
+ }
419
+ if (subtype === "elicitation_complete") {
420
+ const p = WireElicitationCompleteSchema.safeParse(record);
421
+ if (!p.success)
422
+ return;
423
+ const d = p.data;
424
+ return {
425
+ type: "elicitation_complete",
426
+ mcpServerName: d.mcp_server_name,
427
+ elicitationId: d.elicitation_id,
428
+ ...baseFields(d)
429
+ };
430
+ }
431
+ return;
432
+ }
433
+ function parseClaudeRuntimeEvent(record) {
434
+ if (record.type === "system" && record.subtype !== undefined) {
435
+ return parseSystemRuntimeEvent(record.subtype, record);
436
+ }
437
+ if (record.type !== "tool_progress")
438
+ return;
439
+ const p = WireToolProgressSchema.safeParse(record);
440
+ if (!p.success)
441
+ return;
442
+ const d = p.data;
443
+ return {
444
+ type: "tool_progress",
445
+ toolUseId: d.tool_use_id,
446
+ toolName: d.tool_name,
447
+ parentToolUseId: d.parent_tool_use_id ?? null,
448
+ elapsedTimeSeconds: d.elapsed_time_seconds,
449
+ ...d.task_id !== undefined && { taskId: d.task_id },
450
+ ...d.heartbeat !== undefined && { heartbeat: d.heartbeat },
451
+ ...d.subagent_type !== undefined && { subagentType: d.subagent_type },
452
+ ...d.subagent_retry !== undefined && {
453
+ subagentRetry: {
454
+ agentId: d.subagent_retry.agent_id,
455
+ attempt: d.subagent_retry.attempt,
456
+ maxRetries: d.subagent_retry.max_retries,
457
+ retryDelayMs: d.subagent_retry.retry_delay_ms,
458
+ errorStatus: d.subagent_retry.error_status,
459
+ errorCategory: d.subagent_retry.error_category
460
+ }
461
+ },
462
+ ...baseFields(d)
463
+ };
464
+ }
465
+
466
+ // src/agent-executor/claude/protocol.ts
467
+ import { z as z2 } from "zod";
468
+ var TextBlock = z2.looseObject({ type: z2.literal("text"), text: z2.string() });
469
+ var ThinkingBlock = z2.looseObject({
470
+ type: z2.literal("thinking"),
471
+ thinking: z2.string().optional()
472
+ });
473
+ var ToolUseBlock = z2.looseObject({
474
+ type: z2.literal("tool_use"),
475
+ id: z2.string().min(1),
476
+ name: z2.string().min(1),
477
+ input: z2.json()
478
+ });
479
+ var ToolResultBlock = z2.looseObject({
480
+ type: z2.literal("tool_result"),
481
+ tool_use_id: z2.string().min(1),
482
+ content: z2.json().optional(),
483
+ is_error: z2.boolean().optional()
484
+ });
485
+ var OtherBlock = z2.looseObject({ type: z2.string() });
486
+ var ClaudeContentBlockSchema = z2.union([
487
+ TextBlock,
488
+ ThinkingBlock,
489
+ ToolUseBlock,
490
+ ToolResultBlock,
491
+ OtherBlock
492
+ ]);
493
+ var Usage = z2.looseObject({
494
+ input_tokens: z2.int().nonnegative().nullish(),
495
+ output_tokens: z2.int().nonnegative().nullish(),
496
+ cache_read_input_tokens: z2.int().nonnegative().nullish(),
497
+ cache_creation_input_tokens: z2.int().nonnegative().nullish(),
498
+ output_tokens_details: z2.looseObject({
499
+ thinking_tokens: z2.int().nonnegative().nullish()
500
+ }).nullish()
501
+ });
502
+ var ClaudeRecordSchema = z2.discriminatedUnion("type", [
503
+ z2.looseObject({
504
+ type: z2.literal("system"),
505
+ subtype: z2.string(),
506
+ session_id: z2.string().optional(),
507
+ model: z2.string().optional(),
508
+ uuid: z2.string().optional()
509
+ }),
510
+ z2.looseObject({
511
+ type: z2.literal("user"),
512
+ uuid: z2.string().optional(),
513
+ isReplay: z2.boolean().optional(),
514
+ message: z2.looseObject({
515
+ content: z2.union([z2.string(), z2.array(ClaudeContentBlockSchema)])
516
+ })
517
+ }),
518
+ z2.looseObject({
519
+ type: z2.literal("assistant"),
520
+ parent_tool_use_id: z2.string().nullable().optional(),
521
+ message: z2.looseObject({
522
+ id: z2.string().min(1),
523
+ model: z2.string().optional(),
524
+ content: z2.array(ClaudeContentBlockSchema)
525
+ })
526
+ }),
527
+ z2.looseObject({
528
+ type: z2.literal("stream_event"),
529
+ api_message_id: z2.string().optional(),
530
+ event: z2.looseObject({
531
+ type: z2.string(),
532
+ index: z2.int().nonnegative().optional(),
533
+ delta: z2.union([
534
+ z2.looseObject({ type: z2.literal("text_delta"), text: z2.string() }),
535
+ z2.looseObject({ type: z2.literal("thinking_delta"), thinking: z2.string() }),
536
+ z2.looseObject({ type: z2.string().optional() })
537
+ ]).optional(),
538
+ message: z2.looseObject({ id: z2.string().optional() }).optional()
539
+ })
540
+ }),
541
+ z2.looseObject({
542
+ type: z2.literal("result"),
543
+ subtype: z2.string(),
544
+ is_error: z2.boolean(),
545
+ session_id: z2.string().optional(),
546
+ terminal_reason: z2.string().optional(),
547
+ api_error_status: z2.union([z2.int(), z2.string()]).nullable().optional(),
548
+ result: z2.string().optional(),
549
+ total_cost_usd: z2.number().nonnegative().optional(),
550
+ usage: Usage.nullish(),
551
+ modelUsage: z2.record(z2.string(), z2.unknown()).nullish()
552
+ }),
553
+ z2.looseObject({ type: z2.literal("rate_limit_event"), rate_limit_info: z2.looseObject({}) }),
554
+ z2.looseObject({
555
+ type: z2.literal("control_request"),
556
+ request_id: z2.string().min(1),
557
+ request: z2.looseObject({
558
+ subtype: z2.string(),
559
+ tool_name: z2.string().optional(),
560
+ input: z2.json().optional(),
561
+ tool_use_id: z2.string().optional(),
562
+ suppress_always_allow_rule: z2.boolean().optional()
563
+ })
564
+ }),
565
+ z2.looseObject({
566
+ type: z2.literal("control_response"),
567
+ response: z2.looseObject({ subtype: z2.string(), request_id: z2.string().optional() })
568
+ }),
569
+ z2.looseObject({
570
+ type: z2.literal("command_lifecycle"),
571
+ command_uuid: z2.string().optional(),
572
+ state: z2.string()
573
+ }),
574
+ z2.looseObject({
575
+ type: z2.literal("tool_progress")
576
+ })
577
+ ]);
578
+ var ClaudeUnknownRecordSchema = z2.looseObject({ type: z2.string() });
579
+ function claudeUserContent(parts) {
580
+ if (parts.every((part) => part.type === "text")) {
581
+ return parts.map((part) => part.text).join(`
582
+ `);
583
+ }
584
+ return parts.map((part) => {
585
+ if (part.type === "text")
586
+ return { type: "text", text: part.text };
587
+ if (!isSupportedImageMediaType(part.mediaType)) {
588
+ throw new TypeError(`Unsupported Claude image media type: ${part.mediaType}`);
589
+ }
590
+ return {
591
+ type: "image",
592
+ source: { type: "base64", media_type: part.mediaType, data: part.base64 }
593
+ };
594
+ });
595
+ }
596
+ function claudeUserMessage(input) {
597
+ return {
598
+ type: "user",
599
+ message: { role: "user", content: input.content },
600
+ uuid: input.clientId,
601
+ parent_tool_use_id: null,
602
+ session_id: input.sessionId
603
+ };
604
+ }
605
+ function safeJsonObject(value) {
606
+ const cloned = safeJsonValue(value);
607
+ if (typeof cloned !== "object" || cloned === null || Array.isArray(cloned)) {
608
+ throw new TypeError("Claude permission updatedInput must be a plain JSON object");
609
+ }
610
+ return cloned;
611
+ }
612
+ function resolveClaudePermissionReply(detail, rawReply) {
613
+ const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
614
+ if (reply.kind === "input") {
615
+ throw new TypeError("A Claude permission request is approved or denied, not answered with input");
616
+ }
617
+ if (reply.kind === "approve") {
618
+ if (reply.scope === "session") {
619
+ if (detail.toolName === undefined) {
620
+ throw new TypeError("Cannot grant a session-scoped Claude approval without a non-empty toolName");
621
+ }
622
+ if (detail.suppressSessionRule) {
623
+ throw new TypeError("This Claude permission request does not allow a session-scoped approval rule");
624
+ }
625
+ }
626
+ const updatedInput = reply.updatedInput !== undefined ? safeJsonObject(reply.updatedInput) : detail.input;
627
+ return {
628
+ behavior: "allow",
629
+ input: updatedInput,
630
+ ...reply.scope === "session" && detail.toolName !== undefined && {
631
+ updatedPermissions: [
632
+ {
633
+ type: "addRules",
634
+ rules: [{ toolName: detail.toolName }],
635
+ behavior: "allow",
636
+ destination: "session"
637
+ }
638
+ ]
639
+ }
640
+ };
641
+ }
642
+ return {
643
+ behavior: "deny",
644
+ message: reply.message,
645
+ ...reply.interrupt === true && { interrupt: true }
646
+ };
647
+ }
648
+ function claudePermissionResponse(requestId, decision) {
649
+ return {
650
+ type: "control_response",
651
+ response: {
652
+ subtype: "success",
653
+ request_id: requestId,
654
+ response: decision.behavior === "allow" ? {
655
+ behavior: "allow",
656
+ updatedInput: decision.input,
657
+ ...decision.updatedPermissions !== undefined && {
658
+ updatedPermissions: decision.updatedPermissions
659
+ }
660
+ } : {
661
+ behavior: "deny",
662
+ message: decision.message,
663
+ ...decision.interrupt === true && { interrupt: true }
664
+ }
665
+ }
666
+ };
667
+ }
668
+ function claudeControlError(requestId, error) {
669
+ return {
670
+ type: "control_response",
671
+ response: { subtype: "error", request_id: requestId, error }
672
+ };
673
+ }
674
+ function claudeInterrupt(requestId) {
675
+ return { type: "control_request", request_id: requestId, request: { subtype: "interrupt" } };
676
+ }
677
+
678
+ // src/agent-executor/claude/classify.ts
679
+ var MAX_MODEL_USAGE_ENTRIES = 64;
680
+ var MAX_MODEL_KEY_CHARS = 256;
681
+ var MAX_PROVIDER_CHARS = 128;
682
+ var ClaudeWireModelUsageSchema = z3.looseObject({
683
+ inputTokens: z3.int().nonnegative(),
684
+ outputTokens: z3.int().nonnegative(),
685
+ cacheReadInputTokens: z3.int().nonnegative().nullish(),
686
+ cacheCreationInputTokens: z3.int().nonnegative().nullish(),
687
+ thinkingTokens: z3.int().nonnegative().nullish(),
688
+ cacheCreationEphemeral5mInputTokens: z3.int().nonnegative().nullish(),
689
+ cacheCreationEphemeral1hInputTokens: z3.int().nonnegative().nullish(),
690
+ webSearchRequests: z3.int().nonnegative().nullish(),
691
+ costUSD: z3.number().nonnegative().nullish(),
692
+ contextWindow: z3.int().nonnegative().nullish(),
693
+ maxOutputTokens: z3.int().nonnegative().nullish(),
694
+ canonicalModel: z3.string().nullish(),
695
+ provider: z3.string().nullish(),
696
+ costBasis: z3.string().nullish()
697
+ });
698
+ function newClaudeTurnState(turnId) {
699
+ return { turnId, toolNames: new Map, interruptRequested: false, compactCount: 0 };
700
+ }
701
+ var QUIET_SYSTEM = new Set(["hook_started", "hook_response", "status", "thinking_tokens"]);
702
+ var QUIET_STREAM = new Set([
703
+ "message_start",
704
+ "message_delta",
705
+ "message_stop",
706
+ "content_block_start",
707
+ "content_block_stop"
708
+ ]);
709
+ function raw(type, subtype) {
710
+ return { source: "claude", type: subtype === undefined ? type : `${type}/${subtype}` };
711
+ }
712
+ function unhandled(state, type, subtype) {
713
+ return {
714
+ kind: "unhandled",
715
+ delta: {
716
+ type: "error",
717
+ turnId: state.turnId,
718
+ itemId: `unhandled:${type}${subtype === undefined ? "" : `/${subtype}`}`,
719
+ raw: raw(type, subtype),
720
+ kind: "unhandled",
721
+ message: `Claude record ${type}${subtype === undefined ? "" : `/${subtype}`} is not known to this driver`
722
+ }
723
+ };
724
+ }
725
+ function failureKind(status) {
726
+ const code = Number(status);
727
+ if (code === 401 || code === 403)
728
+ return "authRequired";
729
+ if (code === 429)
730
+ return "rateLimited";
731
+ return "restartRecommended";
732
+ }
733
+ function outcomeOf(record, state) {
734
+ if (state.interruptRequested)
735
+ return "interrupted";
736
+ return record.is_error ? "failed" : "completed";
737
+ }
738
+ function normalizeCostBasis(value) {
739
+ return value === "list" || value === "managed" || value === "unknown" ? value : undefined;
740
+ }
741
+ function extractClaudeModelUsage(rawMap) {
742
+ if (rawMap === null || rawMap === undefined)
743
+ return;
744
+ const entries = new Map;
745
+ for (const key of Object.keys(rawMap).sort((a, b) => a.localeCompare(b))) {
746
+ if (entries.size >= MAX_MODEL_USAGE_ENTRIES)
747
+ break;
748
+ const trimmedKey = nonEmptyString(key)?.trim();
749
+ if (trimmedKey === undefined)
750
+ continue;
751
+ const normalizedKey = trimmedKey.slice(0, MAX_MODEL_KEY_CHARS);
752
+ if (normalizedKey === "__proto__" || entries.has(normalizedKey))
753
+ continue;
754
+ const parsed = ClaudeWireModelUsageSchema.safeParse(rawMap[key]);
755
+ if (!parsed.success)
756
+ continue;
757
+ const row = parsed.data;
758
+ const canonicalModel = nonEmptyString(row.canonicalModel)?.trim().slice(0, MAX_MODEL_KEY_CHARS);
759
+ const provider = nonEmptyString(row.provider)?.trim().slice(0, MAX_PROVIDER_CHARS);
760
+ const costBasis = normalizeCostBasis(row.costBasis);
761
+ entries.set(normalizedKey, {
762
+ inputTokens: row.inputTokens,
763
+ outputTokens: row.outputTokens,
764
+ ...row.cacheReadInputTokens != null && {
765
+ cacheReadInputTokens: row.cacheReadInputTokens
766
+ },
767
+ ...row.cacheCreationInputTokens != null && {
768
+ cacheCreationInputTokens: row.cacheCreationInputTokens
769
+ },
770
+ ...row.thinkingTokens != null && { thinkingTokens: row.thinkingTokens },
771
+ ...row.cacheCreationEphemeral5mInputTokens != null && {
772
+ cacheCreationEphemeral5mInputTokens: row.cacheCreationEphemeral5mInputTokens
773
+ },
774
+ ...row.cacheCreationEphemeral1hInputTokens != null && {
775
+ cacheCreationEphemeral1hInputTokens: row.cacheCreationEphemeral1hInputTokens
776
+ },
777
+ ...row.webSearchRequests != null && { webSearchRequests: row.webSearchRequests },
778
+ ...row.costUSD != null && Number.isFinite(row.costUSD) && { costUsd: row.costUSD },
779
+ ...row.contextWindow != null && { contextWindow: row.contextWindow },
780
+ ...row.maxOutputTokens != null && { maxOutputTokens: row.maxOutputTokens },
781
+ ...canonicalModel !== undefined && { canonicalModel },
782
+ ...provider !== undefined && { provider },
783
+ ...costBasis !== undefined && { costBasis }
784
+ });
785
+ }
786
+ return entries.size > 0 ? Object.fromEntries(entries) : undefined;
787
+ }
788
+ function classifyClaudeResult(record, state) {
789
+ const outcome = outcomeOf(record, state);
790
+ const usage = record.usage;
791
+ const thinkingTokens = usage?.output_tokens_details?.thinking_tokens;
792
+ const modelUsage = extractClaudeModelUsage(record.modelUsage);
793
+ const deltas = [
794
+ {
795
+ type: "usage",
796
+ turnId: state.turnId,
797
+ itemId: "usage",
798
+ raw: raw("result", record.subtype),
799
+ ...usage?.input_tokens != null && { inputTokens: usage.input_tokens },
800
+ ...usage?.output_tokens != null && { outputTokens: usage.output_tokens },
801
+ ...usage?.cache_read_input_tokens != null && {
802
+ cachedInputTokens: usage.cache_read_input_tokens
803
+ },
804
+ ...usage?.cache_creation_input_tokens != null && {
805
+ cacheCreationInputTokens: usage.cache_creation_input_tokens
806
+ },
807
+ ...thinkingTokens != null && { thinkingTokens },
808
+ ...record.total_cost_usd !== undefined && { costUsd: record.total_cost_usd },
809
+ ...modelUsage !== undefined && { modelUsage }
810
+ }
811
+ ];
812
+ if (outcome === "failed") {
813
+ deltas.push({
814
+ type: "error",
815
+ turnId: state.turnId,
816
+ itemId: "failure",
817
+ raw: raw("result", record.subtype),
818
+ kind: failureKind(record.api_error_status),
819
+ message: record.result?.trim() || `Claude ended the turn with ${record.subtype}`
820
+ });
821
+ }
822
+ deltas.push({
823
+ type: "turn-end",
824
+ turnId: state.turnId,
825
+ itemId: "end",
826
+ raw: raw("result", record.subtype),
827
+ outcome
828
+ });
829
+ return { kind: "end", deltas, outcome };
830
+ }
831
+ function classifyClaudeRecord(value, state) {
832
+ const parsed = ClaudeRecordSchema.safeParse(value);
833
+ if (!parsed.success) {
834
+ const shape = ClaudeUnknownRecordSchema.safeParse(value);
835
+ return unhandled(state, shape.success ? shape.data.type : "invalid");
836
+ }
837
+ const record = parsed.data;
838
+ switch (record.type) {
839
+ case "system":
840
+ if (record.subtype === "init" && record.session_id !== undefined) {
841
+ return {
842
+ kind: "session",
843
+ sessionId: record.session_id,
844
+ ...record.model !== undefined && { model: record.model }
845
+ };
846
+ }
847
+ if (record.subtype === "compact_boundary") {
848
+ state.compactCount += 1;
849
+ const compactId = nonEmptyString(record.uuid) ?? `${state.turnId}:${state.compactCount}`;
850
+ return {
851
+ kind: "deltas",
852
+ deltas: [
853
+ {
854
+ type: "window",
855
+ turnId: state.turnId,
856
+ itemId: `compact:${compactId}`,
857
+ raw: raw("system", "compact_boundary"),
858
+ reset: "context"
859
+ }
860
+ ]
861
+ };
862
+ }
863
+ if (isClaudeRuntimeSystemSubtype(record.subtype)) {
864
+ const event = parseClaudeRuntimeEvent(record);
865
+ return event !== undefined ? { kind: "event", event } : unhandled(state, "system", record.subtype);
866
+ }
867
+ return QUIET_SYSTEM.has(record.subtype) ? { kind: "ignore", reason: `system/${record.subtype}` } : unhandled(state, "system", record.subtype);
868
+ case "user": {
869
+ if (record.isReplay)
870
+ return { kind: "ignore", reason: "the echo of the input" };
871
+ const content = record.message.content;
872
+ if (typeof content === "string")
873
+ return { kind: "ignore", reason: "a note the CLI addressed to itself" };
874
+ const deltas = [];
875
+ content.forEach((block, index) => {
876
+ if (block.type !== "tool_result" || !("tool_use_id" in block))
877
+ return;
878
+ const callId = nonEmptyString(block.tool_use_id) ?? `result-${index}`;
879
+ deltas.push({
880
+ type: "tool-result",
881
+ turnId: state.turnId,
882
+ itemId: `result:${callId}`,
883
+ raw: raw("user", "tool_result"),
884
+ callId,
885
+ toolName: state.toolNames.get(callId) ?? "unknown",
886
+ outcome: "is_error" in block && block.is_error === true ? "error" : "success",
887
+ ..."content" in block && block.content !== undefined && {
888
+ output: safeJsonValue(block.content)
889
+ }
890
+ });
891
+ });
892
+ return { kind: "deltas", deltas };
893
+ }
894
+ case "assistant": {
895
+ if (record.parent_tool_use_id == null) {
896
+ const rootModel = nonEmptyString(record.message.model)?.trim().slice(0, MAX_MODEL_KEY_CHARS);
897
+ if (rootModel !== undefined)
898
+ state.primaryModel = rootModel;
899
+ }
900
+ const deltas = [];
901
+ record.message.content.forEach((block, index) => {
902
+ if (block.type !== "tool_use" || !("id" in block) || !("name" in block))
903
+ return;
904
+ const itemId = `${record.message.id}:${index}`;
905
+ const callId = nonEmptyString(block.id) ?? itemId;
906
+ const toolName = nonEmptyString(block.name) ?? "unknown";
907
+ state.toolNames.set(callId, toolName);
908
+ deltas.push({
909
+ type: "tool-call",
910
+ turnId: state.turnId,
911
+ itemId,
912
+ raw: raw("assistant", "tool_use"),
913
+ callId,
914
+ toolName,
915
+ input: safeJsonValue("input" in block && block.input !== undefined ? block.input : null)
916
+ });
917
+ });
918
+ return { kind: "deltas", deltas };
919
+ }
920
+ case "stream_event": {
921
+ const event = record.event;
922
+ if (event.type === "content_block_delta" && event.delta !== undefined) {
923
+ const itemId = `${record.api_message_id ?? "message"}:${event.index ?? 0}`;
924
+ const delta = event.delta;
925
+ if (delta.type === "text_delta" && "text" in delta) {
926
+ return {
927
+ kind: "deltas",
928
+ deltas: [
929
+ {
930
+ type: "text",
931
+ turnId: state.turnId,
932
+ itemId,
933
+ raw: raw("stream_event", "text_delta"),
934
+ text: String(delta.text)
935
+ }
936
+ ]
937
+ };
938
+ }
939
+ if (delta.type === "thinking_delta" && "thinking" in delta) {
940
+ return {
941
+ kind: "deltas",
942
+ deltas: [
943
+ {
944
+ type: "reasoning",
945
+ turnId: state.turnId,
946
+ itemId,
947
+ raw: raw("stream_event", "thinking_delta"),
948
+ text: String(delta.thinking)
949
+ }
950
+ ]
951
+ };
952
+ }
953
+ return {
954
+ kind: "ignore",
955
+ reason: `stream_event/${delta.type}: arrives in the final message`
956
+ };
957
+ }
958
+ return QUIET_STREAM.has(event.type) ? { kind: "ignore", reason: `stream_event/${event.type}` } : unhandled(state, "stream_event", event.type);
959
+ }
960
+ case "result":
961
+ return classifyClaudeResult(record, state);
962
+ case "rate_limit_event":
963
+ return { kind: "limits", info: record.rate_limit_info };
964
+ case "control_request": {
965
+ const request = record.request;
966
+ if (request.subtype !== "can_use_tool" || request.tool_name === undefined) {
967
+ return {
968
+ ...unhandled(state, "control_request", request.subtype),
969
+ refuse: {
970
+ requestId: record.request_id,
971
+ message: `Claude control request ${request.subtype} is not known to this driver`
972
+ }
973
+ };
974
+ }
975
+ const callId = nonEmptyString(request.tool_use_id);
976
+ const rawToolName = nonEmptyString(request.tool_name);
977
+ return {
978
+ kind: "request",
979
+ input: request.input ?? null,
980
+ toolName: rawToolName,
981
+ suppressSessionRule: request.suppress_always_allow_rule === true,
982
+ delta: {
983
+ type: "request",
984
+ turnId: state.turnId,
985
+ itemId: `request:${record.request_id}`,
986
+ raw: raw("control_request", "can_use_tool"),
987
+ interactionId: record.request_id,
988
+ kind: "approval",
989
+ toolName: rawToolName ?? "tool",
990
+ ...callId !== undefined && { callId },
991
+ ...request.input !== undefined && { input: request.input }
992
+ }
993
+ };
994
+ }
995
+ case "control_response":
996
+ return { kind: "ignore", reason: "the answer to a request the executor sent" };
997
+ case "command_lifecycle":
998
+ return { kind: "ignore", reason: `the input's own lifecycle (${record.state})` };
999
+ case "tool_progress": {
1000
+ const event = parseClaudeRuntimeEvent(record);
1001
+ return event !== undefined ? { kind: "event", event } : unhandled(state, "tool_progress");
1002
+ }
1003
+ }
1004
+ }
1005
+
1006
+ // src/agent-executor/claude/limits.ts
1007
+ import { z as z4 } from "zod";
1008
+ var MAX_WINDOW_NAME_CHARS = 256;
1009
+ var MAX_PLAN_WINDOWS = 32;
1010
+ var ClaudeWindowSchema = z4.looseObject({
1011
+ utilization: z4.number().min(0),
1012
+ resetsAt: z4.number().positive().optional()
1013
+ });
1014
+ var ClaudeRateLimitInfoSchema = z4.looseObject({
1015
+ rateLimitType: z4.string().optional(),
1016
+ utilization: z4.number().min(0).optional(),
1017
+ resetsAt: z4.number().positive().optional(),
1018
+ unifiedWindows: z4.record(z4.string(), ClaudeWindowSchema).optional()
1019
+ });
1020
+ var ClaudeUsageWindowSchema = z4.looseObject({
1021
+ utilization: z4.number().min(0).nullish(),
1022
+ resets_at: z4.string().nullish()
1023
+ });
1024
+ var ClaudeModelScopedWindowSchema = z4.looseObject({
1025
+ display_name: z4.string().nullish(),
1026
+ utilization: z4.number().min(0).nullish(),
1027
+ resets_at: z4.string().nullish()
1028
+ });
1029
+ var ClaudeUsageResponseSchema = z4.looseObject({
1030
+ subscription_type: z4.string().nullish(),
1031
+ rate_limits_available: z4.boolean().optional(),
1032
+ rate_limits: z4.record(z4.string(), z4.unknown()).nullish()
1033
+ });
1034
+ var FIXED_USAGE_WINDOWS = [
1035
+ "five_hour",
1036
+ "seven_day",
1037
+ "seven_day_oauth_apps",
1038
+ "seven_day_opus",
1039
+ "seven_day_sonnet"
1040
+ ];
1041
+ function parseIsoReset(value) {
1042
+ if (typeof value !== "string")
1043
+ return;
1044
+ const parsed = PlanWindowSchema2.shape.resetsAt.safeParse(value);
1045
+ return parsed.success ? parsed.data : undefined;
1046
+ }
1047
+ function claudeUsagePlanLimits(raw, now) {
1048
+ const parsed = ClaudeUsageResponseSchema.safeParse(raw);
1049
+ if (!parsed.success) {
1050
+ return PlanLimitsSchema2.parse({
1051
+ answer: "unpublished",
1052
+ windows: [],
1053
+ observedAt: now.toISOString()
1054
+ });
1055
+ }
1056
+ const { subscription_type, rate_limits_available, rate_limits } = parsed.data;
1057
+ if (rate_limits_available === false) {
1058
+ return PlanLimitsSchema2.parse({
1059
+ answer: nonEmptyString(subscription_type) !== undefined ? "unpublished" : "no-plan-limit",
1060
+ windows: [],
1061
+ observedAt: now.toISOString()
1062
+ });
1063
+ }
1064
+ const windows = [];
1065
+ const seenNames = new Set;
1066
+ if (rate_limits != null) {
1067
+ for (const key of FIXED_USAGE_WINDOWS) {
1068
+ if (windows.length >= MAX_PLAN_WINDOWS)
1069
+ break;
1070
+ const entryParsed = ClaudeUsageWindowSchema.safeParse(rate_limits[key]);
1071
+ if (!entryParsed.success)
1072
+ continue;
1073
+ const entry = entryParsed.data;
1074
+ if (entry.utilization == null || !Number.isFinite(entry.utilization))
1075
+ continue;
1076
+ const resetsAt = parseIsoReset(entry.resets_at);
1077
+ seenNames.add(key);
1078
+ windows.push(PlanWindowSchema2.parse({
1079
+ name: key,
1080
+ usedPercent: Math.min(100, entry.utilization),
1081
+ ...resetsAt !== undefined && { resetsAt }
1082
+ }));
1083
+ }
1084
+ const modelScoped = rate_limits.model_scoped;
1085
+ if (Array.isArray(modelScoped)) {
1086
+ for (let index = 0;index < modelScoped.length; index += 1) {
1087
+ if (windows.length >= MAX_PLAN_WINDOWS)
1088
+ break;
1089
+ const entry = ClaudeModelScopedWindowSchema.safeParse(modelScoped[index]);
1090
+ if (!entry.success)
1091
+ continue;
1092
+ const { display_name, utilization, resets_at } = entry.data;
1093
+ const label = nonEmptyString(display_name)?.trim().slice(0, MAX_WINDOW_NAME_CHARS);
1094
+ if (label === undefined || utilization == null || !Number.isFinite(utilization))
1095
+ continue;
1096
+ const name = clampUniqueWindowName(`model:${label}`, "", seenNames, `model:${display_name ?? label}:${index}`, MAX_WINDOW_NAME_CHARS);
1097
+ const resetsAt = parseIsoReset(resets_at);
1098
+ windows.push(PlanWindowSchema2.parse({
1099
+ name,
1100
+ usedPercent: Math.min(100, utilization),
1101
+ ...resetsAt !== undefined && { resetsAt },
1102
+ label
1103
+ }));
1104
+ }
1105
+ }
1106
+ }
1107
+ return PlanLimitsSchema2.parse({
1108
+ answer: rate_limits_available === true && windows.length > 0 ? "known" : "unpublished",
1109
+ windows,
1110
+ observedAt: now.toISOString()
1111
+ });
1112
+ }
1113
+ function claudePlanWindows2(info) {
1114
+ const parsed = ClaudeRateLimitInfoSchema.safeParse(info);
1115
+ if (!parsed.success)
1116
+ return [];
1117
+ const toWindow = (name, value) => {
1118
+ const resetsAt = epochSecondsToIso(value.resetsAt);
1119
+ return PlanWindowSchema2.parse({
1120
+ name,
1121
+ usedPercent: Math.min(100, value.utilization * 100),
1122
+ ...resetsAt !== undefined && { resetsAt }
1123
+ });
1124
+ };
1125
+ const { unifiedWindows, rateLimitType, utilization, resetsAt } = parsed.data;
1126
+ if (unifiedWindows !== undefined) {
1127
+ return Object.entries(unifiedWindows).flatMap(([name, value]) => nonEmptyString(name) !== undefined ? [toWindow(name, value)] : []);
1128
+ }
1129
+ const singleName = nonEmptyString(rateLimitType);
1130
+ if (singleName !== undefined && utilization !== undefined) {
1131
+ return [
1132
+ toWindow(singleName, { utilization, ...resetsAt !== undefined && { resetsAt } })
1133
+ ];
1134
+ }
1135
+ return [];
1136
+ }
1137
+
1138
+ // src/agent-executor/claude/transcript.ts
1139
+ import { realpathSync } from "node:fs";
1140
+ import { open } from "node:fs/promises";
1141
+ import { basename, dirname, join } from "node:path";
1142
+ var SAFE_SESSION_ID = /^[A-Za-z0-9_-]+$/;
1143
+ function stripTrailingSlashes(path) {
1144
+ const stripped = path.replace(/\/+$/, "");
1145
+ return stripped.length === 0 && path.startsWith("/") ? "/" : stripped;
1146
+ }
1147
+ function canonicalClaudeCwd(cwd) {
1148
+ if (cwd.length === 0)
1149
+ return cwd;
1150
+ const normalized = stripTrailingSlashes(cwd);
1151
+ const missingTail = [];
1152
+ let probe = normalized;
1153
+ for (;; ) {
1154
+ try {
1155
+ const resolved = realpathSync(probe);
1156
+ return missingTail.length === 0 ? resolved : join(resolved, ...missingTail.reverse());
1157
+ } catch (error) {
1158
+ const code = errnoOf(error);
1159
+ if (code !== "ENOENT" && code !== "ENOTDIR")
1160
+ throw error;
1161
+ const parent = dirname(probe);
1162
+ if (parent === probe)
1163
+ return normalized;
1164
+ missingTail.push(basename(probe));
1165
+ probe = parent;
1166
+ }
1167
+ }
1168
+ }
1169
+ function claudeTranscriptPath2(input) {
1170
+ if (!SAFE_SESSION_ID.test(input.sessionId)) {
1171
+ throw new TypeError(`Invalid Claude sessionId: ${input.sessionId}`);
1172
+ }
1173
+ const canonicalCwd = canonicalClaudeCwd(input.cwd);
1174
+ return join(input.home, "projects", canonicalCwd.replace(/[^A-Za-z0-9-]/g, "-"), `${input.sessionId}.jsonl`);
1175
+ }
1176
+ var MAX_RECORD_BYTES = 16 * 1024 * 1024;
1177
+ var INITIAL_RECORD_BYTES = 64 * 1024;
1178
+ var READ_CHUNK_BYTES = 64 * 1024;
1179
+ var UTF8_STRICT = new TextDecoder("utf-8", { fatal: true });
1180
+ function classifyTranscriptLine(bytes, uuid) {
1181
+ const end = bytes.length > 0 && bytes[bytes.length - 1] === 13 ? bytes.length - 1 : bytes.length;
1182
+ if (end === 0)
1183
+ return "other";
1184
+ let record;
1185
+ try {
1186
+ record = JSON.parse(UTF8_STRICT.decode(bytes.subarray(0, end)));
1187
+ } catch {
1188
+ return "invalid";
1189
+ }
1190
+ if (typeof record !== "object" || record === null || Array.isArray(record))
1191
+ return "invalid";
1192
+ if (Reflect.get(record, "type") !== "user")
1193
+ return "other";
1194
+ const recordUuid = Reflect.get(record, "uuid");
1195
+ if (typeof recordUuid !== "string")
1196
+ return "invalid";
1197
+ return recordUuid === uuid ? "match" : "other";
1198
+ }
1199
+ async function claudeTranscriptHasUuid(path, uuid) {
1200
+ let handle;
1201
+ try {
1202
+ handle = await open(path, "r");
1203
+ } catch (error) {
1204
+ if (errnoOf(error) === "ENOENT")
1205
+ return false;
1206
+ throw error;
1207
+ }
1208
+ try {
1209
+ const chunk = new Uint8Array(READ_CHUNK_BYTES);
1210
+ let lineBuf = new Uint8Array(INITIAL_RECORD_BYTES);
1211
+ let lineLen = 0;
1212
+ let lineOverflow = false;
1213
+ let lineNumber = 1;
1214
+ let problem;
1215
+ const appendSlice = (src, start, end) => {
1216
+ if (lineOverflow || end <= start)
1217
+ return;
1218
+ const add = end - start;
1219
+ const needed = lineLen + add;
1220
+ if (needed > MAX_RECORD_BYTES) {
1221
+ lineOverflow = true;
1222
+ lineLen = 0;
1223
+ return;
1224
+ }
1225
+ if (needed > lineBuf.length) {
1226
+ let nextCap = lineBuf.length;
1227
+ while (nextCap < needed)
1228
+ nextCap = Math.min(MAX_RECORD_BYTES, nextCap * 2);
1229
+ const grown = new Uint8Array(nextCap);
1230
+ grown.set(lineBuf.subarray(0, lineLen));
1231
+ lineBuf = grown;
1232
+ }
1233
+ lineBuf.set(src.subarray(start, end), lineLen);
1234
+ lineLen = needed;
1235
+ };
1236
+ const finishLine = () => {
1237
+ const currentLine = lineNumber;
1238
+ lineNumber += 1;
1239
+ if (lineOverflow) {
1240
+ problem ??= `line ${currentLine} exceeds the ${MAX_RECORD_BYTES}-byte record limit`;
1241
+ lineOverflow = false;
1242
+ lineLen = 0;
1243
+ return false;
1244
+ }
1245
+ const verdict = classifyTranscriptLine(lineBuf.subarray(0, lineLen), uuid);
1246
+ lineLen = 0;
1247
+ if (verdict === "match")
1248
+ return true;
1249
+ if (verdict === "invalid") {
1250
+ problem ??= `line ${currentLine} could not be parsed as a valid transcript record`;
1251
+ }
1252
+ return false;
1253
+ };
1254
+ for (;; ) {
1255
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
1256
+ if (bytesRead === 0)
1257
+ break;
1258
+ let start = 0;
1259
+ for (let i = 0;i < bytesRead; i += 1) {
1260
+ if (chunk[i] === 10) {
1261
+ appendSlice(chunk, start, i);
1262
+ if (finishLine())
1263
+ return true;
1264
+ start = i + 1;
1265
+ }
1266
+ }
1267
+ appendSlice(chunk, start, bytesRead);
1268
+ }
1269
+ if ((lineLen > 0 || lineOverflow) && finishLine())
1270
+ return true;
1271
+ if (problem !== undefined) {
1272
+ throw new Error(`Claude transcript ${path} could not prove absence of input: ${problem}`);
1273
+ }
1274
+ return false;
1275
+ } finally {
1276
+ await handle.close();
1277
+ }
1278
+ }
1279
+ async function claudeTranscriptExists(path) {
1280
+ let handle;
1281
+ try {
1282
+ handle = await open(path, "r");
1283
+ } catch (error) {
1284
+ if (errnoOf(error) === "ENOENT")
1285
+ return false;
1286
+ throw error;
1287
+ }
1288
+ await handle.close();
1289
+ return true;
1290
+ }
1291
+ async function findTranscriptInput(engine, input) {
1292
+ const profile = engineProfile(engine, input.profile);
1293
+ return claudeTranscriptHasUuid(claudeTranscriptPath2({
1294
+ home: profile.home,
1295
+ cwd: input.cwd,
1296
+ sessionId: input.nativeThreadId
1297
+ }), input.clientId);
1298
+ }
1299
+
1300
+ export { ClaudeTaskUsageSchema2, ClaudeRuntimeEventSchema2, claudeUserContent, claudeUserMessage, resolveClaudePermissionReply, claudePermissionResponse, claudeControlError, claudeInterrupt, newClaudeTurnState, classifyClaudeRecord, claudeUsagePlanLimits, claudePlanWindows2, claudeTranscriptPath2, claudeTranscriptExists, findTranscriptInput };