@cargo-ai/cli 1.0.94 → 1.0.96

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 (123) hide show
  1. package/build/commands/ai/chat.d.ts.map +1 -1
  2. package/build/commands/ai/chat.js +2 -1
  3. package/build/commands/ai/message.d.ts.map +1 -1
  4. package/build/commands/ai/message.js +2 -1
  5. package/build/commands/ai/release.d.ts.map +1 -1
  6. package/build/commands/ai/release.js +7 -6
  7. package/build/commands/ask/harness/approvals.d.ts +7 -0
  8. package/build/commands/ask/harness/approvals.d.ts.map +1 -0
  9. package/build/commands/ask/harness/approvals.js +81 -0
  10. package/build/commands/ask/harness/artifacts.d.ts.map +1 -0
  11. package/build/commands/ask/harness/askUserQuestion.d.ts +69 -0
  12. package/build/commands/ask/harness/askUserQuestion.d.ts.map +1 -0
  13. package/build/commands/ask/harness/askUserQuestion.js +218 -0
  14. package/build/commands/ask/harness/claudeConfig.d.ts.map +1 -0
  15. package/build/commands/ask/{claudeConfig.js → harness/claudeConfig.js} +28 -13
  16. package/build/commands/ask/harness/create.d.ts +59 -0
  17. package/build/commands/ask/harness/create.d.ts.map +1 -0
  18. package/build/commands/ask/harness/create.js +314 -0
  19. package/build/commands/ask/harness/index.d.ts +9 -0
  20. package/build/commands/ask/harness/index.d.ts.map +1 -0
  21. package/build/commands/ask/harness/index.js +8 -0
  22. package/build/commands/ask/harness/ingest.d.ts +25 -0
  23. package/build/commands/ask/harness/ingest.d.ts.map +1 -0
  24. package/build/commands/ask/harness/ingest.js +35 -0
  25. package/build/commands/ask/harness/instructions.d.ts +13 -0
  26. package/build/commands/ask/harness/instructions.d.ts.map +1 -0
  27. package/build/commands/ask/harness/instructions.js +43 -0
  28. package/build/commands/ask/harness/layout.d.ts +23 -0
  29. package/build/commands/ask/harness/layout.d.ts.map +1 -0
  30. package/build/commands/ask/harness/layout.js +32 -0
  31. package/build/commands/ask/harness/mcp.d.ts +25 -0
  32. package/build/commands/ask/harness/mcp.d.ts.map +1 -0
  33. package/build/commands/ask/harness/mcp.js +72 -0
  34. package/build/commands/ask/harness/pnpmShim.d.ts.map +1 -0
  35. package/build/commands/ask/harness/release.d.ts +18 -0
  36. package/build/commands/ask/harness/release.d.ts.map +1 -0
  37. package/build/commands/ask/harness/release.js +117 -0
  38. package/build/commands/ask/harness/sandbox.d.ts +9 -0
  39. package/build/commands/ask/harness/sandbox.d.ts.map +1 -0
  40. package/build/commands/ask/harness/sandbox.js +27 -0
  41. package/build/commands/ask/harness/timing.d.ts +16 -0
  42. package/build/commands/ask/harness/timing.d.ts.map +1 -0
  43. package/build/commands/ask/harness/timing.js +72 -0
  44. package/build/commands/ask/harness/turn.d.ts +152 -0
  45. package/build/commands/ask/harness/turn.d.ts.map +1 -0
  46. package/build/commands/ask/harness/turn.js +676 -0
  47. package/build/commands/ask/harness/usage.d.ts +50 -0
  48. package/build/commands/ask/harness/usage.d.ts.map +1 -0
  49. package/build/commands/ask/harness/usage.js +87 -0
  50. package/build/commands/ask/index.d.ts +9 -0
  51. package/build/commands/ask/index.d.ts.map +1 -1
  52. package/build/commands/ask/index.js +7 -7
  53. package/build/commands/ask/input/completer.d.ts.map +1 -0
  54. package/build/commands/ask/input/index.d.ts +5 -0
  55. package/build/commands/ask/input/index.d.ts.map +1 -0
  56. package/build/commands/ask/input/index.js +4 -0
  57. package/build/commands/ask/input/prompt.d.ts.map +1 -0
  58. package/build/commands/ask/{prompt.js → input/prompt.js} +1 -1
  59. package/build/commands/ask/input/slash.d.ts.map +1 -0
  60. package/build/commands/ask/{slash.js → input/slash.js} +1 -1
  61. package/build/commands/ask/input/typeAhead.d.ts.map +1 -0
  62. package/build/commands/ask/{history.d.ts → persist/history.d.ts} +1 -1
  63. package/build/commands/ask/persist/history.d.ts.map +1 -0
  64. package/build/commands/ask/persist/index.d.ts +4 -0
  65. package/build/commands/ask/persist/index.d.ts.map +1 -0
  66. package/build/commands/ask/persist/index.js +3 -0
  67. package/build/commands/ask/persist/persist.d.ts.map +1 -0
  68. package/build/commands/ask/persist/state.d.ts.map +1 -0
  69. package/build/commands/ask/session/claim.d.ts +56 -0
  70. package/build/commands/ask/session/claim.d.ts.map +1 -0
  71. package/build/commands/ask/session/claim.js +76 -0
  72. package/build/commands/ask/session/index.d.ts +5 -0
  73. package/build/commands/ask/session/index.d.ts.map +1 -0
  74. package/build/commands/ask/session/index.js +4 -0
  75. package/build/commands/ask/session/run.d.ts +36 -0
  76. package/build/commands/ask/session/run.d.ts.map +1 -0
  77. package/build/commands/ask/session/run.js +846 -0
  78. package/build/commands/ask/session/thinking.d.ts.map +1 -0
  79. package/build/commands/ask/session/tree.d.ts +99 -0
  80. package/build/commands/ask/session/tree.d.ts.map +1 -0
  81. package/build/commands/ask/session/tree.js +356 -0
  82. package/package.json +6 -5
  83. package/build/commands/ask/artifacts.d.ts.map +0 -1
  84. package/build/commands/ask/binding.d.ts +0 -13
  85. package/build/commands/ask/binding.d.ts.map +0 -1
  86. package/build/commands/ask/binding.js +0 -19
  87. package/build/commands/ask/claudeConfig.d.ts.map +0 -1
  88. package/build/commands/ask/completer.d.ts.map +0 -1
  89. package/build/commands/ask/history.d.ts.map +0 -1
  90. package/build/commands/ask/localHarness.d.ts +0 -278
  91. package/build/commands/ask/localHarness.d.ts.map +0 -1
  92. package/build/commands/ask/localHarness.js +0 -1300
  93. package/build/commands/ask/messageStream.d.ts +0 -33
  94. package/build/commands/ask/messageStream.d.ts.map +0 -1
  95. package/build/commands/ask/messageStream.js +0 -114
  96. package/build/commands/ask/persist.d.ts.map +0 -1
  97. package/build/commands/ask/pnpmShim.d.ts.map +0 -1
  98. package/build/commands/ask/prompt.d.ts.map +0 -1
  99. package/build/commands/ask/session.d.ts +0 -101
  100. package/build/commands/ask/session.d.ts.map +0 -1
  101. package/build/commands/ask/session.js +0 -1328
  102. package/build/commands/ask/slash.d.ts.map +0 -1
  103. package/build/commands/ask/state.d.ts.map +0 -1
  104. package/build/commands/ask/thinking.d.ts.map +0 -1
  105. package/build/commands/ask/typeAhead.d.ts.map +0 -1
  106. /package/build/commands/ask/{artifacts.d.ts → harness/artifacts.d.ts} +0 -0
  107. /package/build/commands/ask/{artifacts.js → harness/artifacts.js} +0 -0
  108. /package/build/commands/ask/{claudeConfig.d.ts → harness/claudeConfig.d.ts} +0 -0
  109. /package/build/commands/ask/{pnpmShim.d.ts → harness/pnpmShim.d.ts} +0 -0
  110. /package/build/commands/ask/{pnpmShim.js → harness/pnpmShim.js} +0 -0
  111. /package/build/commands/ask/{completer.d.ts → input/completer.d.ts} +0 -0
  112. /package/build/commands/ask/{completer.js → input/completer.js} +0 -0
  113. /package/build/commands/ask/{prompt.d.ts → input/prompt.d.ts} +0 -0
  114. /package/build/commands/ask/{slash.d.ts → input/slash.d.ts} +0 -0
  115. /package/build/commands/ask/{typeAhead.d.ts → input/typeAhead.d.ts} +0 -0
  116. /package/build/commands/ask/{typeAhead.js → input/typeAhead.js} +0 -0
  117. /package/build/commands/ask/{history.js → persist/history.js} +0 -0
  118. /package/build/commands/ask/{persist.d.ts → persist/persist.d.ts} +0 -0
  119. /package/build/commands/ask/{persist.js → persist/persist.js} +0 -0
  120. /package/build/commands/ask/{state.d.ts → persist/state.d.ts} +0 -0
  121. /package/build/commands/ask/{state.js → persist/state.js} +0 -0
  122. /package/build/commands/ask/{thinking.d.ts → session/thinking.d.ts} +0 -0
  123. /package/build/commands/ask/{thinking.js → session/thinking.js} +0 -0
@@ -0,0 +1,676 @@
1
+ import { DENIED_TOOL_REASON, isAlwaysDenied, isAutoApproved, } from "./approvals.js";
2
+ import { ASK_USER_QUESTION_DENIED_REASON, ASK_USER_QUESTION_TOOL_NAME, formatAskUserQuestionAnswers, summarizeAskUserQuestion, } from "./askUserQuestion.js";
3
+ import { addTurnUsage, createTurnAccumulator, } from "./usage.js";
4
+ /**
5
+ * How many times one turn may suspend for approvals. Each round trip is a
6
+ * decision the user made, so this is only a stop for a harness that keeps
7
+ * re-asking for a tool it was already refused.
8
+ */
9
+ const MAX_APPROVAL_ROUNDS = 64;
10
+ /**
11
+ * How long a turn may produce nothing at all while no tool is running.
12
+ *
13
+ * Generous on purpose: this is a deadlock detector, not a latency budget. The
14
+ * clock only runs when nothing is in flight, so the wait is over a turn that
15
+ * is neither working nor talking.
16
+ *
17
+ * `CARGO_ASK_STALL_TIMEOUT_MS` shortens it for the end-to-end tests, which
18
+ * would otherwise have to sit out the real deadline to prove a hang is caught.
19
+ */
20
+ const TURN_STALL_TIMEOUT_MS = readTimeoutEnv("CARGO_ASK_STALL_TIMEOUT_MS", 120_000);
21
+ /**
22
+ * The same deadline, for a turn that has a tool executing.
23
+ *
24
+ * A tool at work is silent by design — a test run says nothing for as long as
25
+ * it takes — so this cannot be the deadline above. But it cannot be *no*
26
+ * deadline either, which is what it used to be: a tool the user approved and
27
+ * that never reported back left the turn waiting forever, spinner and all,
28
+ * with nothing to do but kill the terminal. That is the shape of every "it got
29
+ * stuck on the tool" report.
30
+ *
31
+ * Twelve minutes, from Claude Code's own ten-minute ceiling on a Bash tool.
32
+ * That is the bound for the common case, not for every case: the ceiling is
33
+ * configurable, and it does not apply to an MCP tool at all. A `mcp__cargo__*`
34
+ * call that genuinely runs longer than this is cut off with its work lost, so
35
+ * `CARGO_ASK_TOOL_STALL_TIMEOUT_MS` raises it for a workspace that does that
36
+ * routinely. The trade is deliberate: a deadline that covers every conceivable
37
+ * tool is indistinguishable from the hang it replaced.
38
+ *
39
+ * Recoverable either way — the session is replaced and the chat, its history
40
+ * and the working copy all survive.
41
+ */
42
+ const TURN_TOOL_STALL_TIMEOUT_MS = readTimeoutEnv("CARGO_ASK_TOOL_STALL_TIMEOUT_MS", 12 * 60_000);
43
+ function readTimeoutEnv(name, fallbackMs) {
44
+ const raw = process.env[name];
45
+ if (raw === undefined) {
46
+ return fallbackMs;
47
+ }
48
+ const parsed = Number(raw);
49
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallbackMs;
50
+ }
51
+ /**
52
+ * Run one turn to completion, answering approval requests along the way.
53
+ *
54
+ * A turn suspends whenever Claude Code wants a tool `permissionMode` does not
55
+ * cover: the stream ends with the approvals still pending, and the turn only
56
+ * finishes once decisions are fed back in. Exported for tests.
57
+ */
58
+ export async function runPromptTurn(input) {
59
+ const handlers = input.handlers === undefined ? {} : input.handlers;
60
+ const onApproval = handlers.onApproval;
61
+ const accumulator = input.accumulator === undefined
62
+ ? createTurnAccumulator()
63
+ : input.accumulator;
64
+ const stallTimeoutMs = input.stallTimeoutMs === undefined
65
+ ? TURN_STALL_TIMEOUT_MS
66
+ : input.stallTimeoutMs;
67
+ const toolStallTimeoutMs = input.toolStallTimeoutMs === undefined
68
+ ? TURN_TOOL_STALL_TIMEOUT_MS
69
+ : input.toolStallTimeoutMs;
70
+ const assistantChunks = accumulator.chunks;
71
+ const toolCalls = new Map();
72
+ const turnState = {
73
+ toolRanSinceText: false,
74
+ announced: [],
75
+ };
76
+ let stream = await input.driver.start();
77
+ let round = 0;
78
+ for (;;) {
79
+ const approvals = await consumeTurn({
80
+ stream,
81
+ handlers,
82
+ assistantChunks,
83
+ toolCalls,
84
+ usage: accumulator.usage,
85
+ turnState,
86
+ stallTimeoutMs,
87
+ toolStallTimeoutMs,
88
+ onStall: input.onStall,
89
+ });
90
+ if (approvals.length === 0) {
91
+ break;
92
+ }
93
+ if (input.unanswered !== undefined) {
94
+ input.unanswered.push(...approvals);
95
+ }
96
+ round += 1;
97
+ if (round > MAX_APPROVAL_ROUNDS) {
98
+ throw new Error(`Local Claude Code asked for tool approval ${String(MAX_APPROVAL_ROUNDS)} times in one turn without finishing. Stopping the turn.`);
99
+ }
100
+ const continuations = [];
101
+ for (const approval of approvals) {
102
+ // Refused before the user is asked: not their call to make, and a
103
+ // prompt for it could not say what it was granting.
104
+ const denied = isAlwaysDenied(approval.toolName);
105
+ const question = approval.toolName === ASK_USER_QUESTION_TOOL_NAME
106
+ ? await settleAskUserQuestion(approval.input, handlers.onUserQuestion)
107
+ : undefined;
108
+ const approved = question !== undefined
109
+ ? false
110
+ : denied === true
111
+ ? false
112
+ : isAutoApproved(approval.toolName, {
113
+ unattended: onApproval === undefined,
114
+ }) === true
115
+ ? true
116
+ : onApproval === undefined
117
+ ? false
118
+ : await onApproval(approval);
119
+ // Recorded against the call so the retraction pass below knows it is
120
+ // settled: an approved one is running and must be left alone, a refused
121
+ // one is certainly not and needs no reprieve to find out. Absent when
122
+ // its result already arrived, which takes it off the list.
123
+ const announced = turnState.announced.find((call) => call.toolCallId === approval.toolCallId);
124
+ if (announced !== undefined) {
125
+ announced.status = approved === true ? "approved" : "refused";
126
+ }
127
+ // Answered, so the drain on a later turn must not deny it again.
128
+ if (input.unanswered !== undefined) {
129
+ const at = input.unanswered.indexOf(approval);
130
+ if (at !== -1) {
131
+ input.unanswered.splice(at, 1);
132
+ }
133
+ }
134
+ continuations.push({
135
+ approvalResponse: {
136
+ type: "tool-approval-response",
137
+ approvalId: approval.approvalId,
138
+ approved,
139
+ // Told why, so it does something else rather than asking again
140
+ // until the approval-round cap ends the turn.
141
+ reason: question !== undefined
142
+ ? question.reason
143
+ : denied === true
144
+ ? DENIED_TOOL_REASON
145
+ : undefined,
146
+ },
147
+ toolCall: {
148
+ type: "tool-call",
149
+ toolCallId: approval.toolCallId,
150
+ toolName: approval.toolName,
151
+ input: approval.input,
152
+ },
153
+ });
154
+ }
155
+ retractAbandonedCalls(turnState.announced, handlers.onActivity);
156
+ stream = await input.driver.continueWithApprovals(continuations);
157
+ }
158
+ const streamed = assistantChunks.join("");
159
+ if (streamed.length > 0) {
160
+ return streamed;
161
+ }
162
+ const fallback = await stream.text;
163
+ if (typeof fallback !== "string" || fallback.length === 0) {
164
+ return "";
165
+ }
166
+ if (handlers.onTextDelta !== undefined) {
167
+ handlers.onTextDelta(fallback);
168
+ }
169
+ return fallback;
170
+ }
171
+ /**
172
+ * Retract the calls the caller was told about and will never hear the end of,
173
+ * at the boundary where the answers to this round's approvals are known.
174
+ *
175
+ * Left on screen instead, an abandoned call outlives the work: no result is
176
+ * coming, so no `end` event is either, and the caller keeps showing a tool
177
+ * that stopped existing.
178
+ *
179
+ * `"approved"` is kept, and `"running"` is the one case that cannot be judged
180
+ * yet — the reason this is not a plain sweep. It is either the sibling whose
181
+ * approval request the harness lost (it surfaces one per stream) or a tool
182
+ * Claude Code ran without asking, whose result has simply not arrived. Both
183
+ * look identical here, so it gets one more stream to prove itself: a live one
184
+ * reports its result and leaves this list on its own.
185
+ *
186
+ * Everything else is certain and retracted — `"streaming"` never finished
187
+ * arriving, `"refused"` was told no, and `"abandoning"` already had its
188
+ * stream and stayed silent. Refusals matter especially: a tool
189
+ * `isAlwaysDenied` refuses never reaches `onApproval`, so this is the caller's
190
+ * only notice.
191
+ *
192
+ * The reprieve is for the caller's benefit only — `"abandoning"` is not an
193
+ * executing status, so the stall watchdog keeps its short deadline throughout
194
+ * it. Extending the reprieve to the watchdog would deadlock the very hang it
195
+ * exists to prevent: a dropped sibling would hold the timer off, the stream
196
+ * would stay silent, and the next boundary, the thing that resolves the
197
+ * ambiguity, would never arrive.
198
+ */
199
+ function retractAbandonedCalls(announced, onActivity) {
200
+ for (const call of [...announced]) {
201
+ if (call.status === "approved") {
202
+ continue;
203
+ }
204
+ if (call.status === "running") {
205
+ call.status = "abandoning";
206
+ continue;
207
+ }
208
+ announced.splice(announced.indexOf(call), 1);
209
+ if (onActivity !== undefined) {
210
+ onActivity({
211
+ kind: "dropped",
212
+ toolCallId: call.toolCallId,
213
+ toolName: call.toolName,
214
+ });
215
+ }
216
+ }
217
+ }
218
+ /**
219
+ * The previous turn could not be wound down, so this session cannot take
220
+ * another prompt. Raised rather than pressed on with: the harness would either
221
+ * refuse the prompt itself or run it alongside the turn we failed to finish.
222
+ *
223
+ * The caller's recovery is to replace the session — nothing about a wedged
224
+ * runtime gets better by asking it again.
225
+ */
226
+ export class HarnessTurnStuck extends Error {
227
+ constructor() {
228
+ super("The previous turn could not be wound down, so this coding session cannot take another question.");
229
+ this.name = "HarnessTurnStuck";
230
+ }
231
+ }
232
+ /**
233
+ * The turn produced nothing for `TURN_STALL_TIMEOUT_MS` while no tool was in
234
+ * flight. Common causes: a step that asked to run several confirmable tools at
235
+ * once (the harness only surfaces one approval), or the Claude Code bridge
236
+ * going silent. Recoverable — replace the session and ask again.
237
+ */
238
+ export class HarnessTurnStalled extends Error {
239
+ constructor(timeoutMs, whileToolRunning = false) {
240
+ const seconds = String(Math.round(timeoutMs / 1000));
241
+ super(whileToolRunning === true
242
+ ? `A tool has been running for ${seconds}s without reporting anything back, which is longer than Claude Code lets any tool run. Treating it as never coming back rather than waiting on it.`
243
+ : `Local Claude Code went quiet for ${seconds}s with no tool running. Often this is a step that asked to run several confirmable tools at once (only the first can be answered), or the coding session itself stalled.`);
244
+ this.name = "HarnessTurnStalled";
245
+ }
246
+ }
247
+ /**
248
+ * The Claude Code bridge dropped mid-turn. Same recovery as a stall: the
249
+ * process behind the session is gone, so the next question needs a new one.
250
+ */
251
+ export function isBridgeClosedError(error) {
252
+ return (error instanceof Error &&
253
+ error.message.includes("bridge closed before the turn finished") === true);
254
+ }
255
+ /**
256
+ * Fail a turn that has gone silent with no tool running, instead of hanging.
257
+ *
258
+ * `@ai-sdk/harness` surfaces one approval per stream and ends the stream
259
+ * there, so a step that asks to run two tools at once loses the second
260
+ * request: Claude Code keeps waiting for a decision that is never offered,
261
+ * while we keep waiting for output that never comes. Both sides wait forever.
262
+ * `LOCAL_WORKING_COPY_INSTRUCTIONS` asks for one confirmable tool per step to
263
+ * avoid it; this is the backstop for when the model does it anyway.
264
+ *
265
+ * Two deadlines rather than one, because a tool at work is silent by design
266
+ * and a ten-minute test run must not be cut off: `timeoutMs` for a stream with
267
+ * nothing executing, and the far longer `toolTimeoutMs` while a tool is. What
268
+ * there is never again is *no* deadline — a tool that never reports back used
269
+ * to leave the turn on the spinner forever.
270
+ */
271
+ async function* withStallTimeout(stream, timeoutMs, toolTimeoutMs, isToolInFlight, onStall) {
272
+ if (Number.isFinite(timeoutMs) === false &&
273
+ Number.isFinite(toolTimeoutMs) === false) {
274
+ for await (const part of stream) {
275
+ yield part;
276
+ }
277
+ return;
278
+ }
279
+ const iterator = stream[Symbol.asyncIterator]();
280
+ for (;;) {
281
+ const next = iterator.next();
282
+ const running = isToolInFlight();
283
+ const budgetMs = running === true ? toolTimeoutMs : timeoutMs;
284
+ const result = await (Number.isFinite(budgetMs) === false
285
+ ? next
286
+ : rejectIfIdle(next, budgetMs, onStall, running));
287
+ if (result.done === true) {
288
+ return;
289
+ }
290
+ yield result.value;
291
+ }
292
+ }
293
+ /**
294
+ * Wait for `work`, but give up after `timeoutMs` rather than blocking a
295
+ * teardown forever. Resolves either way; the caller has already decided that
296
+ * an unfinished result is better than waiting.
297
+ *
298
+ * Exported for tests.
299
+ */
300
+ export async function settleWithin(work, timeoutMs) {
301
+ let timer;
302
+ try {
303
+ await Promise.race([
304
+ work,
305
+ new Promise((resolve) => {
306
+ timer = setTimeout(resolve, timeoutMs);
307
+ }),
308
+ ]);
309
+ }
310
+ finally {
311
+ if (timer !== undefined) {
312
+ clearTimeout(timer);
313
+ }
314
+ }
315
+ }
316
+ async function rejectIfIdle(next, timeoutMs, onStall, whileToolRunning) {
317
+ let timer;
318
+ try {
319
+ return await Promise.race([
320
+ next,
321
+ new Promise((_resolve, reject) => {
322
+ timer = setTimeout(() => {
323
+ // Reject first so Promise.race settles on HarnessTurnStalled, not
324
+ // on an AbortError the interrupt below may race onto `next`.
325
+ reject(new HarnessTurnStalled(timeoutMs, whileToolRunning));
326
+ // Then stop the bridge so teardown is an intentional abort, not a
327
+ // mysterious "bridge closed before the turn finished" after we
328
+ // have already walked away from the stream.
329
+ if (onStall !== undefined) {
330
+ onStall();
331
+ }
332
+ }, timeoutMs);
333
+ }),
334
+ ]);
335
+ }
336
+ finally {
337
+ if (timer !== undefined) {
338
+ clearTimeout(timer);
339
+ }
340
+ // On a stall we walk away from `next`; a later failure has no other
341
+ // handler and would come back as an unhandled rejection.
342
+ next.catch(() => undefined);
343
+ }
344
+ }
345
+ /** Tool inputs that name a file the turn is about to change. */
346
+ const FILE_WRITING_TOOLS = new Set([
347
+ "write",
348
+ "edit",
349
+ "Write",
350
+ "Edit",
351
+ "NotebookEdit",
352
+ ]);
353
+ /**
354
+ * Drain one turn: text deltas go to the caller, tool calls are remembered so
355
+ * an approval request can be matched back to its call, and pending approvals
356
+ * are returned so the caller can decide and continue the turn.
357
+ */
358
+ async function consumeTurn(input) {
359
+ const approvals = [];
360
+ const { handlers } = input;
361
+ const pendingFiles = new Map();
362
+ const parts = withStallTimeout(input.stream.fullStream, input.stallTimeoutMs, input.toolStallTimeoutMs, () => input.turnState.announced.some((call) => call.status === "running" || call.status === "approved"), input.onStall);
363
+ for await (const rawPart of parts) {
364
+ if (typeof rawPart !== "object" || rawPart === null) {
365
+ continue;
366
+ }
367
+ const part = rawPart;
368
+ if (part["type"] === "error") {
369
+ const error = part["error"];
370
+ throw new Error(error instanceof Error
371
+ ? error.message
372
+ : typeof error === "string"
373
+ ? error
374
+ : "Local Claude Code turn failed.");
375
+ }
376
+ // Claude Code streams the tool name before the full call is assembled.
377
+ // Surface that early so the spinner is not stuck on "Asking…" while the
378
+ // input is still arriving — and so a later `tool-call` can fill in the
379
+ // summary without looking like a second tool.
380
+ if (part["type"] === "tool-input-start") {
381
+ const toolCallId = part["id"];
382
+ const toolName = part["toolName"];
383
+ if (typeof toolCallId === "string" && typeof toolName === "string") {
384
+ if (input.toolCalls.has(toolCallId) === false) {
385
+ input.toolCalls.set(toolCallId, {
386
+ toolName,
387
+ input: undefined,
388
+ });
389
+ input.turnState.toolRanSinceText = true;
390
+ // Announced, because the spinner is about to show this name and is
391
+ // owed a retraction if the call never happens — but `"streaming"`,
392
+ // not executing. The tool is not running yet, its input is still
393
+ // being generated, and the deltas that carry it are output the
394
+ // watchdog is entitled to expect; standing it down here would turn a
395
+ // bridge that dies mid-input into a hang.
396
+ input.turnState.announced.push({
397
+ toolCallId,
398
+ toolName,
399
+ status: "streaming",
400
+ });
401
+ if (handlers.onActivity !== undefined) {
402
+ handlers.onActivity({
403
+ kind: "start",
404
+ toolCallId,
405
+ toolName,
406
+ summary: "",
407
+ });
408
+ }
409
+ }
410
+ }
411
+ continue;
412
+ }
413
+ if (isToolCallPart(part) === true) {
414
+ const toolCallId = part["toolCallId"];
415
+ const toolName = part["toolName"];
416
+ if (typeof toolCallId === "string" && typeof toolName === "string") {
417
+ input.toolCalls.set(toolCallId, {
418
+ toolName,
419
+ input: part["input"],
420
+ });
421
+ input.turnState.toolRanSinceText = true;
422
+ // The full call is assembled, so something is executing it — that is
423
+ // what stands the stall watchdog down, and it deliberately waits until
424
+ // here rather than firing at `tool-input-start`.
425
+ const announced = input.turnState.announced.find((call) => call.toolCallId === toolCallId);
426
+ if (announced === undefined) {
427
+ input.turnState.announced.push({
428
+ toolCallId,
429
+ toolName,
430
+ status: "running",
431
+ });
432
+ }
433
+ else {
434
+ announced.status = "running";
435
+ }
436
+ // Re-emitted when `tool-input-start` already announced the name, so
437
+ // the spinner can pick up the input summary once it is known.
438
+ if (handlers.onActivity !== undefined) {
439
+ handlers.onActivity({
440
+ kind: "start",
441
+ toolCallId,
442
+ toolName,
443
+ summary: summarizeToolInput(part["input"]),
444
+ });
445
+ }
446
+ const touched = FILE_WRITING_TOOLS.has(toolName) === true
447
+ ? readFilePath(part["input"])
448
+ : undefined;
449
+ // Held until the result says the write happened: a denied or failed
450
+ // edit must not show up under "files changed".
451
+ if (touched !== undefined) {
452
+ pendingFiles.set(toolCallId, touched);
453
+ }
454
+ }
455
+ continue;
456
+ }
457
+ if (isToolEndPart(part) === true) {
458
+ const toolCallId = part["toolCallId"];
459
+ const recorded = typeof toolCallId === "string"
460
+ ? input.toolCalls.get(toolCallId)
461
+ : undefined;
462
+ const isError = isToolErrorPart(part);
463
+ // A preliminary result is progress from a tool that is still running,
464
+ // so it must not clear the spinner or tell the stall watchdog the tool
465
+ // is done.
466
+ const preliminary = part["preliminary"] === true;
467
+ if (preliminary === false &&
468
+ typeof toolCallId === "string" &&
469
+ handlers.onActivity !== undefined) {
470
+ handlers.onActivity({
471
+ kind: "end",
472
+ toolCallId,
473
+ toolName: recorded === undefined ? "tool" : recorded.toolName,
474
+ isError,
475
+ });
476
+ }
477
+ if (typeof toolCallId === "string" && preliminary === false) {
478
+ // Off the list on the way out. The `end` above is the caller's
479
+ // retraction, so a later approval round must not announce a second
480
+ // one — and leaving under its own steam is how a tool that ran unasked
481
+ // proves it was alive rather than abandoned.
482
+ const at = input.turnState.announced.findIndex((call) => call.toolCallId === toolCallId);
483
+ if (at !== -1) {
484
+ input.turnState.announced.splice(at, 1);
485
+ }
486
+ const touched = pendingFiles.get(toolCallId);
487
+ pendingFiles.delete(toolCallId);
488
+ if (touched !== undefined &&
489
+ isError === false &&
490
+ handlers.onFileTouched !== undefined) {
491
+ handlers.onFileTouched(touched);
492
+ }
493
+ }
494
+ continue;
495
+ }
496
+ if (part["type"] === "finish") {
497
+ // One suspended turn is several streams, each ending with its own
498
+ // `finish` and its own totals — sum them. Per-step parts are ignored
499
+ // so the same tokens are not counted twice.
500
+ addTurnUsage(input.usage, part);
501
+ continue;
502
+ }
503
+ if (part["type"] === "tool-approval-request") {
504
+ const approval = readApprovalRequest(part, input.toolCalls);
505
+ if (approval !== undefined) {
506
+ approvals.push(approval);
507
+ }
508
+ continue;
509
+ }
510
+ if (part["type"] === "text-delta") {
511
+ const text = typeof part["text"] === "string"
512
+ ? part["text"]
513
+ : typeof part["delta"] === "string"
514
+ ? part["delta"]
515
+ : undefined;
516
+ if (text === undefined || text.length === 0) {
517
+ continue;
518
+ }
519
+ // Claude Code narrates, runs tools, then narrates again. Without a
520
+ // break the two sides of a tool call run into one another mid-sentence.
521
+ const previous = input.assistantChunks.join("");
522
+ if (input.turnState.toolRanSinceText === true &&
523
+ previous.length > 0 &&
524
+ previous.endsWith("\n") === false) {
525
+ input.assistantChunks.push("\n\n");
526
+ if (handlers.onTextDelta !== undefined) {
527
+ handlers.onTextDelta("\n\n");
528
+ }
529
+ }
530
+ input.turnState.toolRanSinceText = false;
531
+ input.assistantChunks.push(text);
532
+ if (handlers.onTextDelta !== undefined) {
533
+ handlers.onTextDelta(text);
534
+ }
535
+ }
536
+ }
537
+ return approvals;
538
+ }
539
+ /**
540
+ * The AI SDK part nests the whole `toolCall`; the harness bridge part carries
541
+ * only `toolCallId`. Accept both and fall back to the recorded call.
542
+ */
543
+ function readApprovalRequest(part, toolCalls) {
544
+ const approvalId = part["approvalId"];
545
+ if (typeof approvalId !== "string") {
546
+ return undefined;
547
+ }
548
+ const nested = part["toolCall"];
549
+ const toolCall = typeof nested === "object" && nested !== null
550
+ ? nested
551
+ : undefined;
552
+ const toolCallId = toolCall !== undefined && typeof toolCall["toolCallId"] === "string"
553
+ ? toolCall["toolCallId"]
554
+ : typeof part["toolCallId"] === "string"
555
+ ? part["toolCallId"]
556
+ : undefined;
557
+ if (toolCallId === undefined) {
558
+ return undefined;
559
+ }
560
+ const recorded = toolCalls.get(toolCallId);
561
+ const toolName = toolCall !== undefined && typeof toolCall["toolName"] === "string"
562
+ ? toolCall["toolName"]
563
+ : recorded !== undefined
564
+ ? recorded.toolName
565
+ : "tool";
566
+ const toolInput = toolCall !== undefined && "input" in toolCall
567
+ ? toolCall["input"]
568
+ : recorded !== undefined
569
+ ? recorded.input
570
+ : undefined;
571
+ return {
572
+ approvalId,
573
+ toolCallId,
574
+ toolName,
575
+ summary: summarizeToolInput(toolInput),
576
+ input: toolInput,
577
+ };
578
+ }
579
+ /** Fields worth showing first when asking to run a tool. */
580
+ const TOOL_INPUT_PREVIEW_KEYS = [
581
+ "command",
582
+ "file_path",
583
+ "path",
584
+ "pattern",
585
+ "url",
586
+ ];
587
+ const TOOL_SUMMARY_MAX_LENGTH = 160;
588
+ /**
589
+ * The bridge sends tool input as a JSON string, while the AI SDK part carries
590
+ * the parsed object. Normalize to a record when the shape allows it.
591
+ */
592
+ function readToolInputRecord(toolInput) {
593
+ if (typeof toolInput === "string") {
594
+ try {
595
+ const parsed = JSON.parse(toolInput);
596
+ return typeof parsed === "object" && parsed !== null
597
+ ? parsed
598
+ : undefined;
599
+ }
600
+ catch {
601
+ return undefined;
602
+ }
603
+ }
604
+ return typeof toolInput === "object" && toolInput !== null
605
+ ? toolInput
606
+ : undefined;
607
+ }
608
+ function readFilePath(toolInput) {
609
+ const record = readToolInputRecord(toolInput);
610
+ if (record === undefined) {
611
+ return undefined;
612
+ }
613
+ const filePath = record["file_path"];
614
+ return typeof filePath === "string" && filePath.length > 0
615
+ ? filePath
616
+ : undefined;
617
+ }
618
+ function summarizeToolInput(toolInput) {
619
+ const record = readToolInputRecord(toolInput);
620
+ if (record === undefined) {
621
+ return typeof toolInput === "string" ? truncate(toolInput) : "";
622
+ }
623
+ for (const key of TOOL_INPUT_PREVIEW_KEYS) {
624
+ const value = record[key];
625
+ if (typeof value === "string" && value.length > 0) {
626
+ return truncate(value);
627
+ }
628
+ }
629
+ const question = summarizeAskUserQuestion(toolInput);
630
+ if (question !== undefined) {
631
+ return truncate(question);
632
+ }
633
+ return truncate(JSON.stringify(record));
634
+ }
635
+ async function settleAskUserQuestion(toolInput, onUserQuestion) {
636
+ if (onUserQuestion === undefined) {
637
+ return { reason: ASK_USER_QUESTION_DENIED_REASON };
638
+ }
639
+ const answers = await onUserQuestion(toolInput);
640
+ if (answers === undefined || Object.keys(answers).length === 0) {
641
+ return { reason: ASK_USER_QUESTION_DENIED_REASON };
642
+ }
643
+ return { reason: formatAskUserQuestionAnswers(answers) };
644
+ }
645
+ function truncate(value) {
646
+ const flat = value.replace(/\s+/g, " ").trim();
647
+ return flat.length > TOOL_SUMMARY_MAX_LENGTH
648
+ ? `${flat.slice(0, TOOL_SUMMARY_MAX_LENGTH - 1)}…`
649
+ : flat;
650
+ }
651
+ /**
652
+ * `fullStream` still uses `tool-call`. The UI message stream — and some
653
+ * harness adapters after AI SDK 7 — spell the assembled call
654
+ * `tool-input-available` instead. Treat them as the same moment: the tool
655
+ * is now executing.
656
+ */
657
+ function isToolCallPart(part) {
658
+ return (part["type"] === "tool-call" || part["type"] === "tool-input-available");
659
+ }
660
+ /**
661
+ * Same split for the result. Missing the UI names left the tool "running"
662
+ * after it had already finished, which is the spinner-stuck-on-every-tool
663
+ * hang: the stall watchdog switched to its long deadline and waited there.
664
+ */
665
+ function isToolEndPart(part) {
666
+ return (part["type"] === "tool-result" ||
667
+ part["type"] === "tool-error" ||
668
+ part["type"] === "tool-output-available" ||
669
+ part["type"] === "tool-output-error" ||
670
+ part["type"] === "tool-output-denied");
671
+ }
672
+ function isToolErrorPart(part) {
673
+ return (part["type"] === "tool-error" ||
674
+ part["type"] === "tool-output-error" ||
675
+ part["type"] === "tool-output-denied");
676
+ }