@cargo-ai/cli 1.0.78 → 1.0.80

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 (67) hide show
  1. package/README.md +12 -0
  2. package/build/commands/ask/argvFlags.d.ts +18 -0
  3. package/build/commands/ask/argvFlags.d.ts.map +1 -0
  4. package/build/commands/ask/argvFlags.js +46 -0
  5. package/build/commands/ask/artifacts.d.ts +2 -0
  6. package/build/commands/ask/artifacts.d.ts.map +1 -0
  7. package/build/commands/ask/artifacts.js +100 -0
  8. package/build/commands/ask/binding.d.ts +13 -0
  9. package/build/commands/ask/binding.d.ts.map +1 -0
  10. package/build/commands/ask/binding.js +19 -0
  11. package/build/commands/ask/claudeConfig.d.ts +23 -0
  12. package/build/commands/ask/claudeConfig.d.ts.map +1 -0
  13. package/build/commands/ask/claudeConfig.js +33 -0
  14. package/build/commands/ask/completer.d.ts +48 -0
  15. package/build/commands/ask/completer.d.ts.map +1 -0
  16. package/build/commands/ask/completer.js +217 -0
  17. package/build/commands/ask/history.d.ts +32 -0
  18. package/build/commands/ask/history.d.ts.map +1 -0
  19. package/build/commands/ask/history.js +122 -0
  20. package/build/commands/ask/index.d.ts +14 -0
  21. package/build/commands/ask/index.d.ts.map +1 -0
  22. package/build/commands/ask/index.js +111 -0
  23. package/build/commands/ask/localHarness.d.ts +225 -0
  24. package/build/commands/ask/localHarness.d.ts.map +1 -0
  25. package/build/commands/ask/localHarness.js +1074 -0
  26. package/build/commands/ask/messageStream.d.ts +33 -0
  27. package/build/commands/ask/messageStream.d.ts.map +1 -0
  28. package/build/commands/ask/messageStream.js +114 -0
  29. package/build/commands/ask/persist.d.ts +5 -0
  30. package/build/commands/ask/persist.d.ts.map +1 -0
  31. package/build/commands/ask/persist.js +31 -0
  32. package/build/commands/ask/pnpmShim.d.ts +20 -0
  33. package/build/commands/ask/pnpmShim.d.ts.map +1 -0
  34. package/build/commands/ask/pnpmShim.js +39 -0
  35. package/build/commands/ask/prompt.d.ts +20 -0
  36. package/build/commands/ask/prompt.d.ts.map +1 -0
  37. package/build/commands/ask/prompt.js +228 -0
  38. package/build/commands/ask/rewriteChatFlag.d.ts +9 -0
  39. package/build/commands/ask/rewriteChatFlag.d.ts.map +1 -0
  40. package/build/commands/ask/rewriteChatFlag.js +26 -0
  41. package/build/commands/ask/session.d.ts +94 -0
  42. package/build/commands/ask/session.d.ts.map +1 -0
  43. package/build/commands/ask/session.js +965 -0
  44. package/build/commands/ask/slash.d.ts +20 -0
  45. package/build/commands/ask/slash.d.ts.map +1 -0
  46. package/build/commands/ask/slash.js +73 -0
  47. package/build/commands/ask/state.d.ts +9 -0
  48. package/build/commands/ask/state.d.ts.map +1 -0
  49. package/build/commands/ask/state.js +18 -0
  50. package/build/commands/bookDemo.d.ts +14 -0
  51. package/build/commands/bookDemo.d.ts.map +1 -0
  52. package/build/commands/bookDemo.js +100 -0
  53. package/build/commands/runHandler.d.ts +9 -1
  54. package/build/commands/runHandler.d.ts.map +1 -1
  55. package/build/commands/runHandler.js +16 -1
  56. package/build/index.js +56 -18
  57. package/build/paletteLayout.d.ts +6 -1
  58. package/build/paletteLayout.d.ts.map +1 -1
  59. package/build/paletteLayout.js +35 -9
  60. package/build/utils/cdkState.d.ts +17 -4
  61. package/build/utils/cdkState.d.ts.map +1 -1
  62. package/build/utils/cdkState.js +26 -4
  63. package/build/utils/loadCompiledAgent.d.ts.map +1 -1
  64. package/build/utils/loadCompiledAgent.js +51 -11
  65. package/build/utils/prompt.d.ts.map +1 -1
  66. package/build/utils/prompt.js +4 -1
  67. package/package.json +8 -4
@@ -0,0 +1,1074 @@
1
+ import { accessSync, constants } from "node:fs";
2
+ import { basename, dirname } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { HarnessAgent } from "@ai-sdk/harness/agent";
5
+ import { createClaudeCode } from "@ai-sdk/harness-claude-code";
6
+ import { cdkProjectRoot } from "@cargo-ai/cdk/cli";
7
+ import { createLocalSandbox } from "ai-sdk-sandbox-local";
8
+ import { pruneHarnessArtifacts } from "./artifacts.js";
9
+ import { askClaudeConfigDir } from "./claudeConfig.js";
10
+ import { ensureHarnessPnpmOnPath } from "./pnpmShim.js";
11
+ /**
12
+ * A local turn spends far longer getting the prompt into Claude Code than it
13
+ * spends generating the answer, and none of that is visible from the tree or
14
+ * from Claude Code's own transcript. `CARGO_ASK_TIMING=1` writes the phase
15
+ * boundaries — and the harness's own diagnostics — to stderr. Unset, every
16
+ * call below is a no-op and nothing is added to the stream.
17
+ */
18
+ const ASK_TIMING_ENABLED = process.env["CARGO_ASK_TIMING"] === "1";
19
+ function createPhaseLog(label) {
20
+ if (ASK_TIMING_ENABLED === false) {
21
+ return () => undefined;
22
+ }
23
+ const start = Date.now();
24
+ let previous = start;
25
+ return (phase) => {
26
+ const now = Date.now();
27
+ const total = ((now - start) / 1000).toFixed(2).padStart(6);
28
+ const step = ((now - previous) / 1000).toFixed(2).padStart(5);
29
+ previous = now;
30
+ process.stderr.write(`[ask:timing] ${label} ${total}s (+${step}s) ${phase}\n`);
31
+ };
32
+ }
33
+ /**
34
+ * The harness prints its own diagnostics without a clock, which is what the
35
+ * gap needs. Reprint them relative to process start instead.
36
+ */
37
+ function reportHarnessDiagnostic(event) {
38
+ const elapsed = process.uptime().toFixed(2).padStart(6);
39
+ process.stderr.write(`[ask:timing] harness ${elapsed}s ${event.level} ${event.subsystem ?? "-"} ${event.message}\n`);
40
+ }
41
+ /** Marks when each part of a turn's stream arrives, and when it ends. */
42
+ function timeStreamParts(stream, phase) {
43
+ if (ASK_TIMING_ENABLED === false) {
44
+ return stream;
45
+ }
46
+ return { text: stream.text, fullStream: timeParts(stream.fullStream, phase) };
47
+ }
48
+ async function* timeParts(parts, phase) {
49
+ let seen = 0;
50
+ for await (const part of parts) {
51
+ seen += 1;
52
+ const type = typeof part === "object" && part !== null && "type" in part
53
+ ? String(part.type)
54
+ : "unknown";
55
+ // Text arrives one delta per token, which would bury everything else.
56
+ if (type.startsWith("text-delta") === false) {
57
+ phase(`part ${String(seen)}: ${type}`);
58
+ }
59
+ yield part;
60
+ }
61
+ phase(`stream ended after ${String(seen)} parts`);
62
+ }
63
+ const LOCAL_WORKING_COPY_INSTRUCTIONS = `You are working in the user's local working copy, not a sandbox. Prefer plan over deploy.
64
+
65
+ The user confirms each Bash, Write, Edit and NotebookEdit call, and can only answer one at a time. Ask for a single one of those per step and wait for its result before asking for the next; two in one step leaves the second waiting on a confirmation it will never be offered. Reads (Read, Glob, Grep) and the Cargo \`mcp__cargo__*\` tools need no confirmation — batch those freely.
66
+
67
+ Prefer minimal, focused diffs; match the existing code style; run the project's own checks when they exist. End each task with a short summary of what changed and how it was validated.`;
68
+ const CDK_RAILS_INSTRUCTIONS = `This directory is a Cargo CDK project.
69
+ - Never edit cargo.state.json, cargo.state.lock, or .cargo-ai/ by hand — they are generated.
70
+ - Validate your changes before declaring them done: run \`npx tsc --noEmit\` and \`npx cargo-cdk plan\` (plan is offline and safe).
71
+ - Never run \`cargo-cdk deploy\`, \`destroy\`, \`import\`, or \`rollback\` unless the user explicitly asked.`;
72
+ const LOCAL_CDK_RAILS_SKILL = {
73
+ name: "cdk-rails",
74
+ description: "Rails for working on a Cargo CDK project on this machine.",
75
+ content: CDK_RAILS_INSTRUCTIONS,
76
+ };
77
+ /**
78
+ * Always-on local-copy rails, plus CDK rails only when `dir` is a CDK project.
79
+ * Exported for tests.
80
+ */
81
+ export function localHarnessInstructions(dir) {
82
+ if (cdkProjectRoot(dir) !== undefined) {
83
+ return `${LOCAL_WORKING_COPY_INSTRUCTIONS}\n\n${CDK_RAILS_INSTRUCTIONS}`;
84
+ }
85
+ return LOCAL_WORKING_COPY_INSTRUCTIONS;
86
+ }
87
+ /** Exported for tests. */
88
+ export function localHarnessSkills(dir) {
89
+ if (cdkProjectRoot(dir) !== undefined) {
90
+ return [LOCAL_CDK_RAILS_SKILL];
91
+ }
92
+ return [];
93
+ }
94
+ /** Exported for tests. */
95
+ export function createTurnAccumulator() {
96
+ return {
97
+ chunks: [],
98
+ usage: {
99
+ costUsd: 0,
100
+ totalTokens: 0,
101
+ inputTokens: 0,
102
+ outputTokens: 0,
103
+ cacheReadTokens: 0,
104
+ cacheWriteTokens: 0,
105
+ reasoningTokens: 0,
106
+ },
107
+ };
108
+ }
109
+ /**
110
+ * `ai-sdk-sandbox-local@0.1.2` still ships deprecated `getPortUrl` only.
111
+ * Claude Code's harness treats a session without `getPortEndpoint` as a basic
112
+ * sandbox and then demands an explicit port — wrap until the local provider
113
+ * catches up.
114
+ */
115
+ function withGetPortEndpoint(provider) {
116
+ const resumeSession = provider.resumeSession;
117
+ return {
118
+ specificationVersion: provider.specificationVersion,
119
+ providerId: provider.providerId,
120
+ createSession: async (options) => ensureGetPortEndpoint(await provider.createSession(options)),
121
+ resumeSession: resumeSession === undefined
122
+ ? undefined
123
+ : async (options) => ensureGetPortEndpoint(await resumeSession(options)),
124
+ };
125
+ }
126
+ function ensureGetPortEndpoint(session) {
127
+ if ("getPortEndpoint" in session) {
128
+ return session;
129
+ }
130
+ const getPortEndpoint = async (options) => ({
131
+ url: await session.getPortUrl(options),
132
+ });
133
+ Object.assign(session, { getPortEndpoint });
134
+ return session;
135
+ }
136
+ /**
137
+ * The workspace half of local Ask: the hosted Cargo MCP server, reached
138
+ * through this CLI's own `mcp` bridge.
139
+ *
140
+ * Going through the bridge rather than configuring the HTTP endpoint directly
141
+ * is what keeps a long chat working — the bridge rebuilds the `Authorization`
142
+ * header per request from the same credentials every other command uses, so an
143
+ * OAuth session that expires mid-session renews instead of 401ing. `CARGO_BASE_URL`
144
+ * is pinned so the bridge cannot end up on a different API than this session.
145
+ *
146
+ * Everything the workspace can do arrives this way: actions, runs, models and
147
+ * SQL, the context, usage. That includes `execute_action`, which spends credits
148
+ * and writes to connected systems — see the approval note on
149
+ * `isAutoApproved`.
150
+ */
151
+ /**
152
+ * What Claude Code mounts this server as, and so the `mcp__<server>__` prefix
153
+ * its tools carry. Read by `isAutoApproved`, which trusts this server and no
154
+ * other — see the note there.
155
+ *
156
+ * Exported for tests.
157
+ */
158
+ export const CARGO_MCP_SERVER_NAME = "cargo";
159
+ function cargoMcpServer(apiBaseUrl) {
160
+ return {
161
+ type: "stdio",
162
+ command: process.execPath,
163
+ args: [...loaderArgs(), cliEntryPath(), "mcp"],
164
+ env: { CARGO_BASE_URL: apiBaseUrl },
165
+ };
166
+ }
167
+ /**
168
+ * This CLI's own entry, so the bridge is the same code and version as the
169
+ * session that spawned it — not whatever `cargo-ai` happens to be on PATH.
170
+ */
171
+ function cliEntryPath() {
172
+ const entry = process.argv[1];
173
+ return entry !== undefined && entry.length > 0
174
+ ? entry
175
+ : fileURLToPath(new URL("../../index.js", import.meta.url));
176
+ }
177
+ /**
178
+ * Loader flags only. A dev run under `tsx` starts from a `.ts` entry that bare
179
+ * node cannot execute, so the child needs the same loader; the rest of
180
+ * `execArgv` (`--inspect` above all, which would fight over a port) must not
181
+ * be inherited.
182
+ */
183
+ function loaderArgs() {
184
+ const flags = ["--import", "--loader", "--require"];
185
+ const args = [];
186
+ for (let index = 0; index < process.execArgv.length; index += 1) {
187
+ const arg = process.execArgv[index];
188
+ if (arg === undefined) {
189
+ continue;
190
+ }
191
+ // `--import=tsx` carries its value; `--import tsx` is two entries and the
192
+ // second one has to come along.
193
+ if (flags.some((flag) => arg.startsWith(`${flag}=`)) === true) {
194
+ args.push(arg);
195
+ continue;
196
+ }
197
+ if (flags.includes(arg) === true) {
198
+ const value = process.execArgv[index + 1];
199
+ if (value !== undefined) {
200
+ args.push(arg, value);
201
+ index += 1;
202
+ }
203
+ }
204
+ }
205
+ return args;
206
+ }
207
+ /**
208
+ * Where to root the sandbox, and which directory inside it the session works in.
209
+ *
210
+ * The harness gives every session a work directory under the sandbox root and
211
+ * starts Claude Code there — `cwd: workdir` in the bridge — and it refuses to
212
+ * use the root itself. Rooted at the project, that means the agent begins in an
213
+ * empty `claude-code-<sessionId>` directory one level below the working copy it
214
+ * was asked about. Rooting at the project's parent instead makes the session
215
+ * work directory *be* the project, so the agent starts where the user is, and
216
+ * the harness's own artifacts land beside the project rather than in it.
217
+ *
218
+ * Falls back to the project when the parent cannot serve — a project at a
219
+ * filesystem root has no usable name, and a parent we cannot write to would
220
+ * fail the session at startup. The per-session directory returns in that case,
221
+ * and `pruneHarnessArtifacts` sweeps it once it is cold.
222
+ */
223
+ export function resolveWorkspaceLayout(dir) {
224
+ const parent = dirname(dir);
225
+ const name = basename(dir);
226
+ if (parent === dir || name.length === 0) {
227
+ return { sandboxCwd: dir, workDir: undefined };
228
+ }
229
+ try {
230
+ accessSync(parent, constants.W_OK);
231
+ }
232
+ catch {
233
+ return { sandboxCwd: dir, workDir: undefined };
234
+ }
235
+ return { sandboxCwd: parent, workDir: name };
236
+ }
237
+ export async function createLocalHarness(input) {
238
+ const setupPhase = createPhaseLog("setup");
239
+ // Claude Code bootstrap shells out to `pnpm`; Volta often has a dead shim
240
+ // and pnpm 9 refuses this npm packageManager root — put pnpm@10 first.
241
+ ensureHarnessPnpmOnPath();
242
+ setupPhase("pnpm shim written to PATH");
243
+ const workspace = resolveWorkspaceLayout(input.dir);
244
+ pruneHarnessArtifacts(workspace.sandboxCwd);
245
+ // Earlier versions rooted the sandbox at the project, so its artifacts are
246
+ // still in there to collect.
247
+ if (workspace.sandboxCwd !== input.dir) {
248
+ pruneHarnessArtifacts(input.dir);
249
+ }
250
+ setupPhase("stale harness artifacts pruned");
251
+ const anthropicBaseUrl = `${input.apiBaseUrl.replace(/\/$/, "")}/sandbox/anthropic`;
252
+ const harnessAgent = new HarnessAgent({
253
+ // Pin auth the same way the backend harness stream does. Credentials go
254
+ // through `auth`, not `env`: passing them via `env` alone lets
255
+ // createClaudeCode auto-detect AI Gateway from the host process and ignore
256
+ // the Cargo proxy.
257
+ harness: createClaudeCode({
258
+ auth: {
259
+ ANTHROPIC_BASE_URL: anthropicBaseUrl,
260
+ ANTHROPIC_API_KEY: input.proxyToken,
261
+ },
262
+ env: { CLAUDE_CONFIG_DIR: askClaudeConfigDir() },
263
+ mcpServers: {
264
+ [CARGO_MCP_SERVER_NAME]: cargoMcpServer(input.apiBaseUrl),
265
+ },
266
+ }),
267
+ id: "cargo-ai-ask",
268
+ sandbox: withGetPortEndpoint(createLocalSandbox({ cwd: workspace.sandboxCwd })),
269
+ sandboxConfig: workspace.workDir === undefined ? {} : { workDir: workspace.workDir },
270
+ instructions: localHarnessInstructions(input.dir),
271
+ skills: localHarnessSkills(input.dir),
272
+ permissionMode: "allow-reads",
273
+ ...(ASK_TIMING_ENABLED === false
274
+ ? {}
275
+ : { debug: { enabled: true }, onLog: reportHarnessDiagnostic }),
276
+ });
277
+ setupPhase("harness agent constructed");
278
+ // Local sandbox cannot broker credentials via request transforms; the
279
+ // harness always warns. Keep that off the Ask tree (stderr mid-reply).
280
+ const session = await withMutedCredentialBrokerWarning(() => harnessAgent.createSession());
281
+ setupPhase("harness session created");
282
+ // Consumed by the first prompt: this session has never seen the chat, so it
283
+ // is told the story once rather than on every question.
284
+ let pendingHistory = input.history;
285
+ let proxyLastUsedAtMs;
286
+ // Approvals the previous turn asked about and never answered — a turn
287
+ // cancelled at the confirmation prompt leaves one here.
288
+ const unanswered = [];
289
+ return {
290
+ streamPrompt: async (question, options) => {
291
+ const turnPhase = createPhaseLog("turn ");
292
+ turnPhase("prompt submitted");
293
+ const abortSignal = options === undefined ? undefined : options.abortSignal;
294
+ // The turn is stored and shown as the user wrote it; only what Claude
295
+ // Code is asked carries the replayed history.
296
+ const prompt = pendingHistory === undefined
297
+ ? question
298
+ : `${pendingHistory}\n\n${question}`;
299
+ // A cancelled turn stays unfinished, and the harness refuses a new
300
+ // prompt until it is drained. Do that here rather than making the next
301
+ // question fail with "must be continued before accepting a new prompt".
302
+ if (session.hasUnfinishedTurn() === true) {
303
+ // Anything the last turn asked about and never got an answer for is
304
+ // denied. Draining with no continuations leaves the runtime waiting
305
+ // on a response that is never coming, and the honest reading of a
306
+ // user who walked away from the prompt is "no" — carrying the
307
+ // question into a turn they did not ask for would be worse.
308
+ const denials = unanswered.map((approval) => ({
309
+ approvalResponse: {
310
+ type: "tool-approval-response",
311
+ approvalId: approval.approvalId,
312
+ approved: false,
313
+ },
314
+ toolCall: {
315
+ type: "tool-call",
316
+ toolCallId: approval.toolCallId,
317
+ toolName: approval.toolName,
318
+ input: approval.input,
319
+ },
320
+ }));
321
+ unanswered.length = 0;
322
+ // The drain gets its own controller so the timeout can stop it rather
323
+ // than walk away from it. Nothing watches this call the way the stall
324
+ // watchdog watches a turn's stream, so a runtime that never settles
325
+ // would otherwise hang the question just asked — but abandoning the
326
+ // promise and carrying on is no better: `continueGenerate` keeps
327
+ // running, and submitting the new prompt to the same session races the
328
+ // turn we failed to wind down. Chained to the turn's signal so ctrl-c
329
+ // still gets out of it.
330
+ const drain = new AbortController();
331
+ const abortDrain = () => drain.abort();
332
+ if (abortSignal !== undefined) {
333
+ if (abortSignal.aborted === true) {
334
+ drain.abort();
335
+ }
336
+ else {
337
+ abortSignal.addEventListener("abort", abortDrain, { once: true });
338
+ }
339
+ }
340
+ const drainTimer = setTimeout(abortDrain, TURN_DRAIN_TIMEOUT_MS);
341
+ try {
342
+ await harnessAgent.continueGenerate({
343
+ session,
344
+ toolApprovalContinuations: denials,
345
+ abortSignal: drain.signal,
346
+ });
347
+ }
348
+ catch {
349
+ // Whether it failed or was cut off, the session itself is the only
350
+ // thing that can say if a new prompt is allowed.
351
+ }
352
+ finally {
353
+ clearTimeout(drainTimer);
354
+ if (abortSignal !== undefined) {
355
+ abortSignal.removeEventListener("abort", abortDrain);
356
+ }
357
+ }
358
+ if (session.hasUnfinishedTurn() === true) {
359
+ throw new HarnessTurnStuck();
360
+ }
361
+ turnPhase("unfinished previous turn drained");
362
+ }
363
+ const accumulator = createTurnAccumulator();
364
+ let answer;
365
+ try {
366
+ answer = await runPromptTurn({
367
+ driver: {
368
+ start: async () => {
369
+ turnPhase("harness stream() called");
370
+ const stream = (await harnessAgent.stream({
371
+ prompt,
372
+ session,
373
+ abortSignal,
374
+ }));
375
+ turnPhase("harness stream() returned");
376
+ // The prompt is in the session now, so the replayed history has
377
+ // been told. Cleared here rather than before submitting: a turn
378
+ // that never reached the harness must keep it for the retry, or
379
+ // a cancelled first question would leave every later one in this
380
+ // process without the earlier conversation.
381
+ pendingHistory = undefined;
382
+ return timeStreamParts(stream, turnPhase);
383
+ },
384
+ continueWithApprovals: async (continuations) => {
385
+ turnPhase("harness continueStream() called");
386
+ const stream = (await harnessAgent.continueStream({
387
+ session,
388
+ toolApprovalContinuations: continuations,
389
+ abortSignal,
390
+ }));
391
+ turnPhase("harness continueStream() returned");
392
+ return timeStreamParts(stream, turnPhase);
393
+ },
394
+ },
395
+ handlers: options,
396
+ accumulator,
397
+ unanswered,
398
+ });
399
+ }
400
+ catch (error) {
401
+ // Cancelled or failed after Claude Code already spent tokens. Record
402
+ // what it spent, then let the caller handle the failure.
403
+ if (didReachAnthropic(accumulator.usage) === true) {
404
+ proxyLastUsedAtMs = Date.now();
405
+ }
406
+ await ingestTurn({
407
+ api: input.api,
408
+ chatUuid: input.chatUuid,
409
+ agentUuid: input.agentUuid,
410
+ question,
411
+ answer: accumulator.chunks.join(""),
412
+ usage: accumulator.usage,
413
+ // Whatever it managed to say is a fragment, not the answer. Stored
414
+ // as cancelled so a later session does not replay it as work done.
415
+ cancelled: true,
416
+ turnOwnerId: input.turnOwnerId,
417
+ onNotice: options === undefined ? undefined : options.onNotice,
418
+ });
419
+ throw error;
420
+ }
421
+ if (didReachAnthropic(accumulator.usage) === true) {
422
+ proxyLastUsedAtMs = Date.now();
423
+ }
424
+ // A turn that spent tokens or edited files is recorded even when it
425
+ // produced no prose, so history and billing match what actually ran.
426
+ await ingestTurn({
427
+ api: input.api,
428
+ chatUuid: input.chatUuid,
429
+ agentUuid: input.agentUuid,
430
+ question,
431
+ answer,
432
+ usage: accumulator.usage,
433
+ turnOwnerId: input.turnOwnerId,
434
+ onNotice: options === undefined ? undefined : options.onNotice,
435
+ });
436
+ // Nothing said and nothing spent means the harness never reached
437
+ // Anthropic — a misconfigured proxy rather than a quiet tool-only turn.
438
+ // Same predicate `ingestTurn` uses, so a turn that was billed is never
439
+ // also reported as unreachable.
440
+ if (answer.length === 0 &&
441
+ didReachAnthropic(accumulator.usage) === false) {
442
+ throw new Error(`Local Claude Code returned no text. The harness called ${anthropicBaseUrl} with the minted proxy token — confirm CARGO_BASE_URL points at your API and that /sandbox/anthropic is reachable.`);
443
+ }
444
+ return answer;
445
+ },
446
+ proxyLastUsedAtMs: () => proxyLastUsedAtMs,
447
+ close: async () => {
448
+ // `detach` would leave the bridge and Claude Code running for a resume
449
+ // that never comes, which is how orphaned bridges piled up. Nothing here
450
+ // is resumable by design, so take the runtime down with the session.
451
+ //
452
+ // Bounded, because Ctrl-C at the prompt now unwinds through here: a
453
+ // destroy that never settles would turn "stop" into a hang, which is
454
+ // what pressing it was meant to escape. Giving up can leave the orphan
455
+ // this call exists to prevent, but a teardown already stuck is no more
456
+ // likely to finish while the user waits on it.
457
+ await settleWithin(session.destroy().catch(() => undefined), SESSION_DESTROY_TIMEOUT_MS);
458
+ },
459
+ };
460
+ }
461
+ /**
462
+ * Persist the turn and what it spent. Local Ask runs on the platform
463
+ * Anthropic key through the proxy, so this call is the only thing that makes
464
+ * the turn billable — the mint-time credit check gates the session, not the
465
+ * spend. Sending `costUsd` rather than a credit count keeps pricing on the
466
+ * server.
467
+ *
468
+ * History is best effort: a failed ingest is reported but never turns a reply
469
+ * the user already read into a failed turn.
470
+ */
471
+ /**
472
+ * Whether the turn got as far as Anthropic. `costUsd` and `totalTokens` are
473
+ * reported independently by the harness, so either alone means it did.
474
+ */
475
+ function didReachAnthropic(usage) {
476
+ return usage.costUsd > 0 || usage.totalTokens > 0;
477
+ }
478
+ async function ingestTurn(input) {
479
+ if (input.answer.length === 0 && didReachAnthropic(input.usage) === false) {
480
+ return;
481
+ }
482
+ try {
483
+ await input.api.ai.message.ingest({
484
+ chatUuid: input.chatUuid,
485
+ agentUuid: input.agentUuid,
486
+ userParts: [{ type: "text", text: input.question }],
487
+ // A turn cancelled before it said anything is recorded for its usage
488
+ // alone, so it has no text part rather than an empty one.
489
+ assistantParts: input.answer.length === 0 ? [] : [{ type: "text", text: input.answer }],
490
+ usage: didReachAnthropic(input.usage) === true ? input.usage : undefined,
491
+ cancelled: input.cancelled,
492
+ turnOwnerId: input.turnOwnerId,
493
+ });
494
+ }
495
+ catch (error) {
496
+ if (input.onNotice !== undefined) {
497
+ input.onNotice(`Could not save this turn to the chat history: ${error instanceof Error ? error.message : "unknown error"}`);
498
+ }
499
+ }
500
+ }
501
+ /**
502
+ * How many times one turn may suspend for approvals. Each round trip is a
503
+ * decision the user made, so this is only a stop for a harness that keeps
504
+ * re-asking for a tool it was already refused.
505
+ */
506
+ const MAX_APPROVAL_ROUNDS = 64;
507
+ /**
508
+ * Run one turn to completion, answering approval requests along the way.
509
+ *
510
+ * A turn suspends whenever Claude Code wants a tool `permissionMode` does not
511
+ * cover: the stream ends with the approvals still pending, and the turn only
512
+ * finishes once decisions are fed back in. Exported for tests.
513
+ */
514
+ export async function runPromptTurn(input) {
515
+ const handlers = input.handlers === undefined ? {} : input.handlers;
516
+ const onApproval = handlers.onApproval;
517
+ const accumulator = input.accumulator === undefined
518
+ ? createTurnAccumulator()
519
+ : input.accumulator;
520
+ const stallTimeoutMs = input.stallTimeoutMs === undefined
521
+ ? TURN_STALL_TIMEOUT_MS
522
+ : input.stallTimeoutMs;
523
+ const assistantChunks = accumulator.chunks;
524
+ const toolCalls = new Map();
525
+ const turnState = {
526
+ toolRanSinceText: false,
527
+ inFlightToolCallIds: new Set(),
528
+ };
529
+ let stream = await input.driver.start();
530
+ let round = 0;
531
+ for (;;) {
532
+ const approvals = await consumeTurn({
533
+ stream,
534
+ handlers,
535
+ assistantChunks,
536
+ toolCalls,
537
+ usage: accumulator.usage,
538
+ turnState,
539
+ stallTimeoutMs,
540
+ });
541
+ if (approvals.length === 0) {
542
+ break;
543
+ }
544
+ if (input.unanswered !== undefined) {
545
+ input.unanswered.push(...approvals);
546
+ }
547
+ round += 1;
548
+ if (round > MAX_APPROVAL_ROUNDS) {
549
+ throw new Error(`Local Claude Code asked for tool approval ${String(MAX_APPROVAL_ROUNDS)} times in one turn without finishing. Stopping the turn.`);
550
+ }
551
+ const continuations = [];
552
+ const approvedToolCallIds = [];
553
+ for (const approval of approvals) {
554
+ // Refused before the user is asked: not their call to make, and a
555
+ // prompt for it could not say what it was granting.
556
+ const denied = isAlwaysDenied(approval.toolName);
557
+ const approved = denied === true
558
+ ? false
559
+ : isAutoApproved(approval.toolName) === true
560
+ ? true
561
+ : onApproval === undefined
562
+ ? false
563
+ : await onApproval(approval);
564
+ if (approved === true) {
565
+ approvedToolCallIds.push(approval.toolCallId);
566
+ }
567
+ // Answered, so the drain on a later turn must not deny it again.
568
+ if (input.unanswered !== undefined) {
569
+ const at = input.unanswered.indexOf(approval);
570
+ if (at !== -1) {
571
+ input.unanswered.splice(at, 1);
572
+ }
573
+ }
574
+ continuations.push({
575
+ approvalResponse: {
576
+ type: "tool-approval-response",
577
+ approvalId: approval.approvalId,
578
+ approved,
579
+ // Told why, so it does something else rather than asking again
580
+ // until the approval-round cap ends the turn.
581
+ reason: denied === true ? DENIED_TOOL_REASON : undefined,
582
+ },
583
+ toolCall: {
584
+ type: "tool-call",
585
+ toolCallId: approval.toolCallId,
586
+ toolName: approval.toolName,
587
+ input: approval.input,
588
+ },
589
+ });
590
+ }
591
+ // Only the tools just approved are actually going to run. The harness
592
+ // surfaces one approval per stream, so a sibling the model announced in
593
+ // the same stream was never asked about and will never report a result —
594
+ // left in the set it would tell the stall watchdog a tool is in flight
595
+ // for the rest of the turn, turning a silent stream into a hang.
596
+ turnState.inFlightToolCallIds.clear();
597
+ for (const toolCallId of approvedToolCallIds) {
598
+ turnState.inFlightToolCallIds.add(toolCallId);
599
+ }
600
+ stream = await input.driver.continueWithApprovals(continuations);
601
+ }
602
+ const streamed = assistantChunks.join("");
603
+ if (streamed.length > 0) {
604
+ return streamed;
605
+ }
606
+ const fallback = await stream.text;
607
+ if (typeof fallback !== "string" || fallback.length === 0) {
608
+ return "";
609
+ }
610
+ if (handlers.onTextDelta !== undefined) {
611
+ handlers.onTextDelta(fallback);
612
+ }
613
+ return fallback;
614
+ }
615
+ /**
616
+ * How long a turn may produce nothing at all while no tool is running.
617
+ *
618
+ * Generous on purpose: this is a deadlock detector, not a latency budget. The
619
+ * clock only runs when nothing is in flight, so the wait is over a turn that
620
+ * is neither working nor talking.
621
+ */
622
+ const TURN_STALL_TIMEOUT_MS = 120_000;
623
+ /**
624
+ * How long teardown may take before the session is abandoned. Short, because
625
+ * the caller is usually someone who just pressed Ctrl-C.
626
+ */
627
+ const SESSION_DESTROY_TIMEOUT_MS = 5_000;
628
+ /**
629
+ * How long winding down a previous unfinished turn may take before it is cut
630
+ * off and the question refused.
631
+ */
632
+ const TURN_DRAIN_TIMEOUT_MS = 30_000;
633
+ /**
634
+ * The previous turn could not be wound down, so this session cannot take
635
+ * another prompt. Raised rather than pressed on with: the harness would either
636
+ * refuse the prompt itself or run it alongside the turn we failed to finish.
637
+ *
638
+ * The caller's recovery is to replace the session — nothing about a wedged
639
+ * runtime gets better by asking it again.
640
+ */
641
+ export class HarnessTurnStuck extends Error {
642
+ constructor() {
643
+ super("The previous turn could not be wound down, so this coding session cannot take another question.");
644
+ this.name = "HarnessTurnStuck";
645
+ }
646
+ }
647
+ /**
648
+ * Fail a turn that has gone silent with no tool running, instead of hanging.
649
+ *
650
+ * `@ai-sdk/harness` surfaces one approval per stream and ends the stream
651
+ * there, so a step that asks to run two tools at once loses the second
652
+ * request: Claude Code keeps waiting for a decision that is never offered,
653
+ * while we keep waiting for output that never comes. Both sides wait forever.
654
+ * `LOCAL_WORKING_COPY_INSTRUCTIONS` asks for one confirmable tool per step to
655
+ * avoid it; this is the backstop for when the model does it anyway.
656
+ *
657
+ * The timer is armed only while no tool is in flight — a ten-minute test run
658
+ * is silent too, and must not be cut off.
659
+ */
660
+ async function* withStallTimeout(stream, timeoutMs, isToolInFlight) {
661
+ if (Number.isFinite(timeoutMs) === false) {
662
+ for await (const part of stream) {
663
+ yield part;
664
+ }
665
+ return;
666
+ }
667
+ const iterator = stream[Symbol.asyncIterator]();
668
+ for (;;) {
669
+ const next = iterator.next();
670
+ const result = await (isToolInFlight() === true
671
+ ? next
672
+ : rejectIfIdle(next, timeoutMs));
673
+ if (result.done === true) {
674
+ return;
675
+ }
676
+ yield result.value;
677
+ }
678
+ }
679
+ /**
680
+ * Wait for `work`, but give up after `timeoutMs` rather than blocking a
681
+ * teardown forever. Resolves either way; the caller has already decided that
682
+ * an unfinished result is better than waiting.
683
+ *
684
+ * Exported for tests.
685
+ */
686
+ export async function settleWithin(work, timeoutMs) {
687
+ let timer;
688
+ try {
689
+ await Promise.race([
690
+ work,
691
+ new Promise((resolve) => {
692
+ timer = setTimeout(resolve, timeoutMs);
693
+ }),
694
+ ]);
695
+ }
696
+ finally {
697
+ if (timer !== undefined) {
698
+ clearTimeout(timer);
699
+ }
700
+ }
701
+ }
702
+ async function rejectIfIdle(next, timeoutMs) {
703
+ let timer;
704
+ try {
705
+ return await Promise.race([
706
+ next,
707
+ new Promise((_resolve, reject) => {
708
+ timer = setTimeout(() => {
709
+ reject(new Error(`Local Claude Code went quiet for ${String(Math.round(timeoutMs / 1000))}s with no tool running. A single step that asks to run several tools needing confirmation ends up here: only the first can be answered, and the rest leave the turn waiting. Ask again, or in smaller steps.`));
710
+ }, timeoutMs);
711
+ }),
712
+ ]);
713
+ }
714
+ finally {
715
+ if (timer !== undefined) {
716
+ clearTimeout(timer);
717
+ }
718
+ // On a stall we walk away from `next`; a later failure has no other
719
+ // handler and would come back as an unhandled rejection.
720
+ next.catch(() => undefined);
721
+ }
722
+ }
723
+ /**
724
+ * Claude Code's own bookkeeping. `allow-reads` classifies these as edits
725
+ * because they call a write-shaped tool, but they touch nothing outside the
726
+ * session — prompting for a todo-list update is noise, and Claude Code
727
+ * rewrites its list on every step of any multi-step task.
728
+ */
729
+ const AUTO_APPROVED_TOOL_NAMES = new Set([
730
+ "TodoWrite",
731
+ "EnterPlanMode",
732
+ "ExitPlanMode",
733
+ "TaskCreate",
734
+ "TaskUpdate",
735
+ "TaskStop",
736
+ "AskUserQuestion",
737
+ ]);
738
+ /**
739
+ * Cargo's MCP tools run unattended, `execute_action` included: a turn can
740
+ * spend credits and write to a connected system on its own. That is the
741
+ * deliberate trade for a chat that answers without being nursed, and it is
742
+ * defensible only because this server reaches the workspace with the user's
743
+ * own credentials — it can do nothing they could not do from the CLI.
744
+ *
745
+ * Only this server's tools. Claude Code names them `mcp__<server>__<tool>`,
746
+ * and matching the bare `mcp__` was safe only while Ask owned the config
747
+ * directory: `CLAUDE_CONFIG_DIR` reinstates the user's own MCP servers, whose
748
+ * tools write and shell out with none of the above reasoning behind them.
749
+ * Those go through approval like anything else that touches the machine.
750
+ *
751
+ * Built from the mount key so renaming the server cannot silently widen this.
752
+ */
753
+ const CARGO_MCP_TOOL_PREFIX = `mcp__${CARGO_MCP_SERVER_NAME}__`;
754
+ /** Exported for tests. */
755
+ export function isAutoApproved(toolName) {
756
+ if (toolName.startsWith(CARGO_MCP_TOOL_PREFIX) === true) {
757
+ return true;
758
+ }
759
+ return AUTO_APPROVED_TOOL_NAMES.has(toolName);
760
+ }
761
+ /**
762
+ * `Agent` spawns a subagent to run a task of its own. It does reach the
763
+ * approval prompt — the bridge defaults an unlisted tool to `edit`, which
764
+ * `allow-reads` asks about — but approving it is a different kind of decision
765
+ * from approving a `Bash`: the subagent runs its own tools, can be asked for
766
+ * with `mode: "bypassPermissions"`, and whether its calls come back here for
767
+ * individual approval is not something we control or currently know.
768
+ *
769
+ * Until that is established, refuse it. A prompt that cannot describe what it
770
+ * is granting is worse than not offering the capability, and nothing in the
771
+ * adapter settings or the harness's `inactiveTools` can withhold this tool at
772
+ * source — the approval is the only lever there is.
773
+ */
774
+ const DENIED_TOOL_NAMES = new Set(["Agent"]);
775
+ const DENIED_TOOL_REASON = "Spawning a subagent is not available in this session. Do the work in this turn instead, asking for each tool you need.";
776
+ /** Exported for tests. */
777
+ export function isAlwaysDenied(toolName) {
778
+ return DENIED_TOOL_NAMES.has(toolName);
779
+ }
780
+ /** Tool inputs that name a file the turn is about to change. */
781
+ const FILE_WRITING_TOOLS = new Set([
782
+ "write",
783
+ "edit",
784
+ "Write",
785
+ "Edit",
786
+ "NotebookEdit",
787
+ ]);
788
+ /**
789
+ * Drain one turn: text deltas go to the caller, tool calls are remembered so
790
+ * an approval request can be matched back to its call, and pending approvals
791
+ * are returned so the caller can decide and continue the turn.
792
+ */
793
+ async function consumeTurn(input) {
794
+ const approvals = [];
795
+ const { handlers } = input;
796
+ const pendingFiles = new Map();
797
+ const parts = withStallTimeout(input.stream.fullStream, input.stallTimeoutMs, () => input.turnState.inFlightToolCallIds.size > 0);
798
+ for await (const rawPart of parts) {
799
+ if (typeof rawPart !== "object" || rawPart === null) {
800
+ continue;
801
+ }
802
+ const part = rawPart;
803
+ if (part["type"] === "error") {
804
+ const error = part["error"];
805
+ throw new Error(error instanceof Error
806
+ ? error.message
807
+ : typeof error === "string"
808
+ ? error
809
+ : "Local Claude Code turn failed.");
810
+ }
811
+ if (part["type"] === "tool-call") {
812
+ const toolCallId = part["toolCallId"];
813
+ const toolName = part["toolName"];
814
+ if (typeof toolCallId === "string" && typeof toolName === "string") {
815
+ input.toolCalls.set(toolCallId, {
816
+ toolName,
817
+ input: part["input"],
818
+ });
819
+ input.turnState.toolRanSinceText = true;
820
+ input.turnState.inFlightToolCallIds.add(toolCallId);
821
+ if (handlers.onActivity !== undefined) {
822
+ handlers.onActivity({
823
+ kind: "start",
824
+ toolName,
825
+ summary: summarizeToolInput(part["input"]),
826
+ });
827
+ }
828
+ const touched = FILE_WRITING_TOOLS.has(toolName) === true
829
+ ? readFilePath(part["input"])
830
+ : undefined;
831
+ // Held until the result says the write happened: a denied or failed
832
+ // edit must not show up under "files changed".
833
+ if (touched !== undefined) {
834
+ pendingFiles.set(toolCallId, touched);
835
+ }
836
+ }
837
+ continue;
838
+ }
839
+ if (part["type"] === "tool-result" || part["type"] === "tool-error") {
840
+ const toolCallId = part["toolCallId"];
841
+ const recorded = typeof toolCallId === "string"
842
+ ? input.toolCalls.get(toolCallId)
843
+ : undefined;
844
+ const isError = part["type"] === "tool-error";
845
+ if (handlers.onActivity !== undefined) {
846
+ handlers.onActivity({
847
+ kind: "end",
848
+ toolName: recorded === undefined ? "tool" : recorded.toolName,
849
+ isError,
850
+ });
851
+ }
852
+ if (typeof toolCallId === "string") {
853
+ // A preliminary result is progress from a tool that is still running,
854
+ // so it must not tell the stall watchdog the tool is done.
855
+ if (part["preliminary"] !== true) {
856
+ input.turnState.inFlightToolCallIds.delete(toolCallId);
857
+ }
858
+ const touched = pendingFiles.get(toolCallId);
859
+ pendingFiles.delete(toolCallId);
860
+ if (touched !== undefined &&
861
+ isError === false &&
862
+ handlers.onFileTouched !== undefined) {
863
+ handlers.onFileTouched(touched);
864
+ }
865
+ }
866
+ continue;
867
+ }
868
+ if (part["type"] === "finish") {
869
+ // One suspended turn is several streams, each ending with its own
870
+ // `finish` and its own totals — sum them. Per-step parts are ignored
871
+ // so the same tokens are not counted twice.
872
+ addTurnUsage(input.usage, part);
873
+ continue;
874
+ }
875
+ if (part["type"] === "tool-approval-request") {
876
+ const approval = readApprovalRequest(part, input.toolCalls);
877
+ if (approval !== undefined) {
878
+ approvals.push(approval);
879
+ }
880
+ continue;
881
+ }
882
+ if (part["type"] === "text-delta") {
883
+ const text = typeof part["text"] === "string"
884
+ ? part["text"]
885
+ : typeof part["delta"] === "string"
886
+ ? part["delta"]
887
+ : undefined;
888
+ if (text === undefined || text.length === 0) {
889
+ continue;
890
+ }
891
+ // Claude Code narrates, runs tools, then narrates again. Without a
892
+ // break the two sides of a tool call run into one another mid-sentence.
893
+ const previous = input.assistantChunks.join("");
894
+ if (input.turnState.toolRanSinceText === true &&
895
+ previous.length > 0 &&
896
+ previous.endsWith("\n") === false) {
897
+ input.assistantChunks.push("\n\n");
898
+ if (handlers.onTextDelta !== undefined) {
899
+ handlers.onTextDelta("\n\n");
900
+ }
901
+ }
902
+ input.turnState.toolRanSinceText = false;
903
+ input.assistantChunks.push(text);
904
+ if (handlers.onTextDelta !== undefined) {
905
+ handlers.onTextDelta(text);
906
+ }
907
+ }
908
+ }
909
+ return approvals;
910
+ }
911
+ /**
912
+ * Add one stream's `finish` totals to the turn. `totalUsage` is the AI SDK
913
+ * shape; `costUsd` is what Claude Code reports for the same stream under
914
+ * `harnessMetadata`, and is what the API prices into credits.
915
+ */
916
+ function addTurnUsage(usage, part) {
917
+ const costUsd = readClaudeCodeCostUsd(part);
918
+ if (costUsd !== undefined) {
919
+ usage.costUsd += costUsd;
920
+ }
921
+ const totalUsage = part["totalUsage"];
922
+ if (typeof totalUsage !== "object" || totalUsage === null) {
923
+ return;
924
+ }
925
+ const totals = totalUsage;
926
+ usage.totalTokens += readCount(totals["totalTokens"]);
927
+ usage.inputTokens += readCount(totals["inputTokens"]);
928
+ usage.outputTokens += readCount(totals["outputTokens"]);
929
+ const inputDetails = totals["inputTokenDetails"];
930
+ if (typeof inputDetails === "object" && inputDetails !== null) {
931
+ const details = inputDetails;
932
+ usage.cacheReadTokens += readCount(details["cacheReadTokens"]);
933
+ usage.cacheWriteTokens += readCount(details["cacheWriteTokens"]);
934
+ }
935
+ const outputDetails = totals["outputTokenDetails"];
936
+ if (typeof outputDetails === "object" && outputDetails !== null) {
937
+ const details = outputDetails;
938
+ usage.reasoningTokens += readCount(details["reasoningTokens"]);
939
+ }
940
+ }
941
+ function readCount(value) {
942
+ return typeof value === "number" && Number.isFinite(value) && value > 0
943
+ ? value
944
+ : 0;
945
+ }
946
+ function readClaudeCodeCostUsd(part) {
947
+ const harnessMetadata = part["harnessMetadata"];
948
+ if (typeof harnessMetadata !== "object" || harnessMetadata === null) {
949
+ return undefined;
950
+ }
951
+ const claudeCode = harnessMetadata["claude-code"];
952
+ if (typeof claudeCode !== "object" || claudeCode === null) {
953
+ return undefined;
954
+ }
955
+ const costUsd = claudeCode["costUsd"];
956
+ return typeof costUsd === "number" && Number.isFinite(costUsd) && costUsd > 0
957
+ ? costUsd
958
+ : undefined;
959
+ }
960
+ /**
961
+ * The AI SDK part nests the whole `toolCall`; the harness bridge part carries
962
+ * only `toolCallId`. Accept both and fall back to the recorded call.
963
+ */
964
+ function readApprovalRequest(part, toolCalls) {
965
+ const approvalId = part["approvalId"];
966
+ if (typeof approvalId !== "string") {
967
+ return undefined;
968
+ }
969
+ const nested = part["toolCall"];
970
+ const toolCall = typeof nested === "object" && nested !== null
971
+ ? nested
972
+ : undefined;
973
+ const toolCallId = toolCall !== undefined && typeof toolCall["toolCallId"] === "string"
974
+ ? toolCall["toolCallId"]
975
+ : typeof part["toolCallId"] === "string"
976
+ ? part["toolCallId"]
977
+ : undefined;
978
+ if (toolCallId === undefined) {
979
+ return undefined;
980
+ }
981
+ const recorded = toolCalls.get(toolCallId);
982
+ const toolName = toolCall !== undefined && typeof toolCall["toolName"] === "string"
983
+ ? toolCall["toolName"]
984
+ : recorded !== undefined
985
+ ? recorded.toolName
986
+ : "tool";
987
+ const toolInput = toolCall !== undefined && "input" in toolCall
988
+ ? toolCall["input"]
989
+ : recorded !== undefined
990
+ ? recorded.input
991
+ : undefined;
992
+ return {
993
+ approvalId,
994
+ toolCallId,
995
+ toolName,
996
+ summary: summarizeToolInput(toolInput),
997
+ input: toolInput,
998
+ };
999
+ }
1000
+ /** Fields worth showing first when asking to run a tool. */
1001
+ const TOOL_INPUT_PREVIEW_KEYS = [
1002
+ "command",
1003
+ "file_path",
1004
+ "path",
1005
+ "pattern",
1006
+ "url",
1007
+ ];
1008
+ const TOOL_SUMMARY_MAX_LENGTH = 160;
1009
+ /**
1010
+ * The bridge sends tool input as a JSON string, while the AI SDK part carries
1011
+ * the parsed object. Normalize to a record when the shape allows it.
1012
+ */
1013
+ function readToolInputRecord(toolInput) {
1014
+ if (typeof toolInput === "string") {
1015
+ try {
1016
+ const parsed = JSON.parse(toolInput);
1017
+ return typeof parsed === "object" && parsed !== null
1018
+ ? parsed
1019
+ : undefined;
1020
+ }
1021
+ catch {
1022
+ return undefined;
1023
+ }
1024
+ }
1025
+ return typeof toolInput === "object" && toolInput !== null
1026
+ ? toolInput
1027
+ : undefined;
1028
+ }
1029
+ function readFilePath(toolInput) {
1030
+ const record = readToolInputRecord(toolInput);
1031
+ if (record === undefined) {
1032
+ return undefined;
1033
+ }
1034
+ const filePath = record["file_path"];
1035
+ return typeof filePath === "string" && filePath.length > 0
1036
+ ? filePath
1037
+ : undefined;
1038
+ }
1039
+ function summarizeToolInput(toolInput) {
1040
+ const record = readToolInputRecord(toolInput);
1041
+ if (record === undefined) {
1042
+ return typeof toolInput === "string" ? truncate(toolInput) : "";
1043
+ }
1044
+ for (const key of TOOL_INPUT_PREVIEW_KEYS) {
1045
+ const value = record[key];
1046
+ if (typeof value === "string" && value.length > 0) {
1047
+ return truncate(value);
1048
+ }
1049
+ }
1050
+ return truncate(JSON.stringify(record));
1051
+ }
1052
+ function truncate(value) {
1053
+ const flat = value.replace(/\s+/g, " ").trim();
1054
+ return flat.length > TOOL_SUMMARY_MAX_LENGTH
1055
+ ? `${flat.slice(0, TOOL_SUMMARY_MAX_LENGTH - 1)}…`
1056
+ : flat;
1057
+ }
1058
+ async function withMutedCredentialBrokerWarning(run) {
1059
+ const originalWarn = console.warn;
1060
+ console.warn = (...args) => {
1061
+ const first = args[0];
1062
+ if (typeof first === "string" &&
1063
+ first.includes("credential brokering does not work")) {
1064
+ return;
1065
+ }
1066
+ originalWarn.apply(console, args);
1067
+ };
1068
+ try {
1069
+ return await run();
1070
+ }
1071
+ finally {
1072
+ console.warn = originalWarn;
1073
+ }
1074
+ }