@catamorphic/ai-sdk 0.0.0-stage → 0.1.0-alpha.31

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.
package/src/adapter.ts ADDED
@@ -0,0 +1,1378 @@
1
+ import path from "node:path";
2
+ import type {
3
+ AgentAttachment,
4
+ AgentEffort,
5
+ AgentTurnUsage,
6
+ JsonValue,
7
+ NativeRef,
8
+ TurnError,
9
+ } from "@catamorphic/agent-protocol";
10
+ import {
11
+ type AttemptControl,
12
+ type AttemptHost,
13
+ type AttemptStart,
14
+ type HarnessAdapter,
15
+ type HarnessCapabilities,
16
+ type HarnessEvent,
17
+ type HostToolResult,
18
+ type McpServerSpec,
19
+ RequestClosedError,
20
+ type RequestDraft,
21
+ } from "@catamorphic/agent-protocol/runner";
22
+ import {
23
+ type ConnectedMcpServer,
24
+ connectMcpServer,
25
+ type ElicitHandler,
26
+ type ElicitRequest,
27
+ type ElicitResult,
28
+ } from "@catamorphic/mcp";
29
+ import {
30
+ isMediaAttachment,
31
+ positiveTokenCount,
32
+ reasoningHeading,
33
+ renderUserMessage,
34
+ } from "@catamorphic/sandbox";
35
+ import {
36
+ type LanguageModel,
37
+ type LanguageModelUsage,
38
+ type ModelMessage,
39
+ stepCountIs,
40
+ type TextStreamPart,
41
+ type Tool,
42
+ ToolLoopAgent,
43
+ } from "ai";
44
+ import { z } from "zod";
45
+ import { classifyModelError, errorMessage } from "./errors.js";
46
+ import type { ShellState } from "./shell.js";
47
+ import { agentTelemetry } from "./telemetry.js";
48
+ import {
49
+ entriesThroughTurn,
50
+ type FoldedThread,
51
+ foldThread,
52
+ parseThreadEntries,
53
+ storedEntries,
54
+ type ThreadEntry,
55
+ toJsonValue,
56
+ } from "./thread.js";
57
+ import {
58
+ type AiSdkSandboxProvider,
59
+ conversationTools,
60
+ hostTools,
61
+ isRecord,
62
+ mcpTools,
63
+ parseHostToolResult,
64
+ resolveProjectPath,
65
+ type ToolMeta,
66
+ type ToolSetWithMeta,
67
+ transcriptToolResult,
68
+ workspaceTools,
69
+ } from "./tools.js";
70
+
71
+ /** The adapter id: an attempt's `harness` names it. */
72
+ export const AI_SDK_HARNESS = "ai-sdk";
73
+
74
+ const DEFAULT_INSTRUCTIONS = `You are an agent working with a person in their project folder, which can hold any kind of work: documents, notes, data, code, automations, apps.
75
+ Use the provided tools to inspect and edit the project in your working directory.
76
+ Read AGENTS.md and relevant .work/skills/*/SKILL.md and .agents/skills/*/SKILL.md files, when they exist, before making substantial changes.
77
+ Keep changes focused, run relevant checks, and do not commit changes.
78
+ At the start of a new conversation, once the topic is clear from the first user message, call set_title with a concise conversation title; update it whenever the current title no longer fits the conversation, but not for minor detours.`;
79
+
80
+ /**
81
+ * The AI SDK's default stop condition is stepCountIs(20), far too small for
82
+ * real work (scaffold, build, fix, rebuild easily exceeds it), and it ends
83
+ * the turn silently mid-work. Interruption stays available; the cap is a
84
+ * runaway guard.
85
+ */
86
+ const DEFAULT_MAX_STEPS = 150;
87
+
88
+ const CAPABILITIES: HarnessCapabilities = {
89
+ steer: true,
90
+ interrupt: true,
91
+ retry: true,
92
+ fork: true,
93
+ rollback: false,
94
+ questions: true,
95
+ approvals: true,
96
+ elicitations: true,
97
+ toolSearch: false,
98
+ subagents: false,
99
+ streamsText: true,
100
+ streamsReasoning: true,
101
+ nativeState: "store",
102
+ ids: { thread: "strong", turn: "strong", item: "none" },
103
+ };
104
+
105
+ /** Connects one MCP server for an attempt; `onElicit` asks the person. */
106
+ export type McpConnector = (input: {
107
+ name: string;
108
+ spec: McpServerSpec;
109
+ onElicit: ElicitHandler;
110
+ }) => Promise<ConnectedMcpServer>;
111
+
112
+ export interface AiSdkAdapterOptions {
113
+ /** The AI SDK model the host constructed and configured. */
114
+ model: LanguageModel;
115
+ /**
116
+ * Turn a model id into a model, enabling an attempt's `model` override
117
+ * (the host binds provider and key). Without it, overrides are ignored.
118
+ */
119
+ resolveModel?: (modelId: string) => LanguageModel;
120
+ /**
121
+ * Default reasoning effort, mapped onto the provider's native knob
122
+ * (Anthropic thinking budgets, OpenAI reasoning effort). An attempt's
123
+ * `effort` overrides it.
124
+ */
125
+ effort?: AgentEffort;
126
+ /** Host-level instructions, after the built-in ones, before the attempt's. */
127
+ instructions?: string;
128
+ /** Model steps one turn may take before it stops; 150 by default. */
129
+ maxSteps?: number;
130
+ /**
131
+ * How an attempt connects its MCP servers; `@catamorphic/mcp` by
132
+ * default. Hosts that pool connections, and tests, supply their own.
133
+ */
134
+ connectMcp?: McpConnector;
135
+ }
136
+
137
+ /**
138
+ * Host objects for one attempt (`local` of an in-process runner, never
139
+ * serialized). Without `sandbox` the agent has no file or shell tools,
140
+ * only the host's.
141
+ */
142
+ export type AiSdkLocal = {
143
+ /** The session's sandbox: file and shell tools run on it. */
144
+ sandbox?: {
145
+ provider: AiSdkSandboxProvider;
146
+ sandboxId: string;
147
+ /** The project folder in the provider's filesystem. */
148
+ workingDirectory: string;
149
+ /** The Environment's budget for one foreground command (ADR 0174). */
150
+ commandBudgetSeconds?: number;
151
+ /**
152
+ * The session's environment files (ADRs 0206, 0212), relative to
153
+ * `workingDirectory` or absolute: every shell command loads each that
154
+ * exists first.
155
+ */
156
+ envFiles?: readonly string[];
157
+ };
158
+ /**
159
+ * Directories outside the working directory the `read` tool may read
160
+ * (never write): the host's store of files pasted into the chat.
161
+ */
162
+ readableRoots?: readonly string[];
163
+ /**
164
+ * The chat's shell: where the next command starts and the background
165
+ * commands it owns. Kept by the host across attempts, so a command
166
+ * started in one turn is read or stopped in the next; end them with
167
+ * `stopBackgroundCommands` when the chat closes.
168
+ */
169
+ shell?: ShellState;
170
+ /** The person the attempt runs for, for telemetry. */
171
+ userId?: string;
172
+ };
173
+
174
+ /**
175
+ * The built-in agent as a harness adapter (ADR 0198): the Vercel AI SDK
176
+ * tool loop, run in the host's own process (the desktop, the control
177
+ * plane), never in a sandbox bundle. Model calls run in the host; project
178
+ * IO runs on the session's sandbox (`local.sandbox`).
179
+ *
180
+ * Its native thread is the AI SDK message history, stored with Work
181
+ * through `nativeState` one step at a time, so a later turn on another
182
+ * replica or after a restart continues the same history.
183
+ */
184
+ export function createAiSdkAdapter(
185
+ options: AiSdkAdapterOptions,
186
+ ): HarnessAdapter {
187
+ return {
188
+ id: AI_SDK_HARNESS,
189
+ capabilities: () => CAPABILITIES,
190
+ start: (attempt, host, local) =>
191
+ new AiSdkAttempt(options, attempt, host, readLocal(local)).control(),
192
+ };
193
+ }
194
+
195
+ interface SteerInput {
196
+ itemId: string;
197
+ text: string;
198
+ attachments: AgentAttachment[];
199
+ }
200
+
201
+ interface Deferred {
202
+ promise: Promise<void>;
203
+ resolve: () => void;
204
+ }
205
+
206
+ /** An item still being written. */
207
+ interface OpenSegment {
208
+ key: string;
209
+ text: string;
210
+ started: boolean;
211
+ }
212
+
213
+ class AiSdkAttempt {
214
+ /** Interrupts and runner stops. */
215
+ private readonly abort = new AbortController();
216
+ /** A failed state write stops the loop as a failure, not an interrupt. */
217
+ private readonly failure = new AbortController();
218
+ private failureCause: unknown;
219
+ private readonly steers: SteerInput[] = [];
220
+ /**
221
+ * The built-in tools' waits end when this fires (ADR 0264): a steer is
222
+ * read only at the next step, after they return. Replaced as it fires.
223
+ */
224
+ private waits = new AbortController();
225
+ private accepting = true;
226
+ /** An item was reported: a retry would repeat visible work. */
227
+ private workStarted = false;
228
+ private readonly announced = new Map<string, Deferred>();
229
+ private text: OpenSegment | undefined;
230
+ private readonly reasoning = new Map<string, OpenSegment>();
231
+ /** The agent's latest reasoning heading: its own words for its work. */
232
+ private heading?: string;
233
+ private readonly toolItems = new Map<
234
+ string,
235
+ { key: string | null; meta: ToolMeta | undefined }
236
+ >();
237
+ private segments = 0;
238
+ private requests = 0;
239
+ private readonly usage = new UsageTally();
240
+ private readonly model: LanguageModel;
241
+ private readonly modelId: string | undefined;
242
+ private readonly workingDirectory: string;
243
+ private readonly threadRef: NativeRef;
244
+ private readonly turnRef: NativeRef;
245
+
246
+ constructor(
247
+ private readonly options: AiSdkAdapterOptions,
248
+ private readonly attempt: AttemptStart,
249
+ private readonly host: AttemptHost,
250
+ private readonly local: AiSdkLocal,
251
+ ) {
252
+ this.model =
253
+ attempt.model && options.resolveModel
254
+ ? options.resolveModel(attempt.model)
255
+ : options.model;
256
+ this.modelId = modelIdOf(this.model);
257
+ this.workingDirectory =
258
+ local.sandbox?.workingDirectory ?? attempt.workingDirectory;
259
+ this.threadRef =
260
+ attempt.thread.mode === "resume" || attempt.thread.mode === "restore"
261
+ ? attempt.thread.nativeRef
262
+ : { id: attempt.thread.providerThreadId, strength: "strong" };
263
+ // The attempt is the native turn: a fork or retry through it names it.
264
+ this.turnRef = { id: attempt.attemptId, strength: "strong" };
265
+ if (host.signal.aborted) this.abort.abort();
266
+ else
267
+ host.signal.addEventListener("abort", () => this.abort.abort(), {
268
+ once: true,
269
+ });
270
+ }
271
+
272
+ control(): AttemptControl {
273
+ return {
274
+ steer: async (input) => {
275
+ if (!this.accepting || this.abort.signal.aborted) return false;
276
+ this.steers.push(input);
277
+ this.waits.abort();
278
+ this.waits = new AbortController();
279
+ return true;
280
+ },
281
+ interrupt: () => this.abort.abort(),
282
+ finished: this.run(),
283
+ };
284
+ }
285
+
286
+ private emit(event: HarnessEvent): void {
287
+ if (event.type === "item.started") this.workStarted = true;
288
+ this.host.emit(event);
289
+ }
290
+
291
+ private async run(): Promise<void> {
292
+ this.emit({ type: "thread", ref: this.threadRef });
293
+ const telemetry = agentTelemetry({
294
+ model: this.model,
295
+ sessionId: this.attempt.sessionId,
296
+ projectId: this.attempt.projectId,
297
+ turnId: this.attempt.turnId,
298
+ ...(this.local.userId ? { userId: this.local.userId } : {}),
299
+ });
300
+ let servers = new Map<string, ConnectedMcpServer>();
301
+ let turnStored = false;
302
+ let status: "completed" | "failed" | "interrupted" = "completed";
303
+ let error: TurnError | undefined;
304
+ try {
305
+ const folded = await this.history();
306
+ const turn = this.turnInput(folded);
307
+ await this.append([turn.entry]);
308
+ turnStored = true;
309
+ // Begun once its input is on the stored thread (ADR 0240).
310
+ this.emit({ type: "turn.started", ref: this.turnRef });
311
+ servers = await this.connectMcp();
312
+ await this.loop({
313
+ messages: turn.messages,
314
+ tools: this.tools(servers),
315
+ telemetry,
316
+ });
317
+ if (this.abort.signal.aborted) status = "interrupted";
318
+ } catch (cause) {
319
+ if (this.abort.signal.aborted) status = "interrupted";
320
+ else {
321
+ status = "failed";
322
+ const failed = this.failure.signal.aborted ? this.failureCause : cause;
323
+ telemetry.fail(failed);
324
+ const classified = classifyModelError(failed);
325
+ error = {
326
+ message: classified.message,
327
+ ...(classified.kind ? { kind: classified.kind } : {}),
328
+ ...(classified.providerRejected && !this.workStarted
329
+ ? { retrySafe: true }
330
+ : {}),
331
+ };
332
+ }
333
+ }
334
+ this.accepting = false;
335
+ this.settleAnnounced();
336
+ this.closeOpenItems(status);
337
+ telemetry.finish({ cancelled: status === "interrupted" });
338
+ const usage = this.usage.toUsage(this.attempt.model ?? this.modelId);
339
+ if (usage) this.emit({ type: "usage", usage });
340
+ if (turnStored)
341
+ await this.append([
342
+ { v: 1, kind: "turn_end", ref: this.turnRef.id, status },
343
+ ]).catch((cause: unknown) =>
344
+ this.emit({
345
+ type: "diagnostic",
346
+ level: "warn",
347
+ message: `The end of this turn was not stored: ${errorMessage(cause)}`,
348
+ }),
349
+ );
350
+ this.emit({
351
+ type: "turn.completed",
352
+ status,
353
+ ...(error ? { error } : {}),
354
+ ...(turnStored ? { ref: this.turnRef } : {}),
355
+ });
356
+ await Promise.all(
357
+ [...servers.values()].map((server) => server.close().catch(() => {})),
358
+ );
359
+ }
360
+
361
+ // -------------------------------------------------------------------------
362
+ // The native thread
363
+
364
+ /** The history this attempt continues, from the stored thread. */
365
+ private async history(): Promise<FoldedThread> {
366
+ const thread = this.attempt.thread;
367
+ const sanitize = this.attempt.options.sanitizeReasoning === true;
368
+ const fold = (entries: readonly ThreadEntry[]) =>
369
+ foldThread({
370
+ entries,
371
+ ...((this.attempt.model ?? this.modelId)
372
+ ? { model: this.attempt.model ?? this.modelId }
373
+ : {}),
374
+ sanitize,
375
+ });
376
+ if (thread.mode === "fresh") return { messages: [] };
377
+ if (thread.mode === "fork") {
378
+ // A fork attempt that ran before already copied its source.
379
+ const own = await this.load();
380
+ if (own && own.length > 0) return fold(own);
381
+ const source = await this.load(thread.source.id);
382
+ if (!source)
383
+ throw new Error("The conversation to fork from is not stored.");
384
+ const through = thread.throughTurnRef
385
+ ? entriesThroughTurn(source, thread.throughTurnRef.id)
386
+ : source;
387
+ if (!through)
388
+ throw new Error(
389
+ "The turn to fork from is not in the stored conversation.",
390
+ );
391
+ // The fork's thread starts as a copy, so it resumes anywhere too.
392
+ await this.append(through);
393
+ return fold(through);
394
+ }
395
+ const entries = await this.load();
396
+ if (!entries)
397
+ throw new Error("This conversation's stored history is missing.");
398
+ return fold(entries);
399
+ }
400
+
401
+ /** The turn's opening messages and the entry that records them. */
402
+ private turnInput(folded: FoldedThread): {
403
+ messages: ModelMessage[];
404
+ entry: ThreadEntry;
405
+ } {
406
+ const input = this.attempt.input;
407
+ if (input) {
408
+ const opening: ModelMessage[] = [
409
+ // Turn context arrives as a system message beside the prompt,
410
+ // never inside the person's words (ADR 0152).
411
+ ...(this.attempt.context.trim()
412
+ ? [{ role: "system" as const, content: this.attempt.context }]
413
+ : []),
414
+ userMessage(input),
415
+ ];
416
+ return {
417
+ messages: [...folded.messages, ...opening],
418
+ entry: { v: 1, kind: "turn", ref: this.turnRef.id, input: opening },
419
+ };
420
+ }
421
+ // A native retry re-runs the last turn on the history as it stands:
422
+ // a failed turn continues after its finished steps; a final answer is
423
+ // replaced.
424
+ const end = folded.lastTurnInputEnd;
425
+ if (end === undefined)
426
+ throw new Error("There is no earlier turn to retry.");
427
+ const messages = [...folded.messages];
428
+ let drop = 0;
429
+ while (messages.length > end && messages.at(-1)?.role === "assistant") {
430
+ messages.pop();
431
+ drop += 1;
432
+ }
433
+ return {
434
+ messages,
435
+ entry: {
436
+ v: 1,
437
+ kind: "turn",
438
+ ref: this.turnRef.id,
439
+ input: [],
440
+ ...(drop ? { drop } : {}),
441
+ },
442
+ };
443
+ }
444
+
445
+ private async load(thread?: string): Promise<ThreadEntry[] | null> {
446
+ const entries = await untilAborted(
447
+ this.host.nativeState.load(thread ? { thread } : {}),
448
+ this.host.signal,
449
+ );
450
+ return entries ? parseThreadEntries(entries) : null;
451
+ }
452
+
453
+ /** Store entries; the runner sends a large append as several calls. */
454
+ private async append(entries: readonly ThreadEntry[]): Promise<void> {
455
+ if (this.host.signal.aborted) return;
456
+ const stored = entries.flatMap(storedEntries);
457
+ if (stored.length === 0) return;
458
+ await untilAborted(
459
+ this.host.nativeState.append({ entries: stored }),
460
+ this.host.signal,
461
+ );
462
+ }
463
+
464
+ // -------------------------------------------------------------------------
465
+ // The tool loop
466
+
467
+ private instructions(): string {
468
+ const plugins = this.attempt.plugins.length
469
+ ? [
470
+ "Plugins installed for you (read their files with the read tool):",
471
+ ...this.attempt.plugins.map(
472
+ (plugin) => `- ${plugin.name}: ${plugin.path}`,
473
+ ),
474
+ ].join("\n")
475
+ : undefined;
476
+ return [
477
+ DEFAULT_INSTRUCTIONS,
478
+ this.options.instructions,
479
+ plugins,
480
+ this.attempt.systemPrompt,
481
+ ]
482
+ .filter((part): part is string => Boolean(part?.trim()))
483
+ .join("\n\n");
484
+ }
485
+
486
+ private async loop(input: {
487
+ messages: ModelMessage[];
488
+ tools: Record<string, Tool>;
489
+ telemetry: ReturnType<typeof agentTelemetry>;
490
+ }): Promise<void> {
491
+ let messages = input.messages;
492
+ let stepsLeft = this.options.maxSteps ?? DEFAULT_MAX_STEPS;
493
+ const effort = this.attempt.effort ?? this.options.effort;
494
+ const signal = AbortSignal.any([this.abort.signal, this.failure.signal]);
495
+ for (;;) {
496
+ let prepared = messages;
497
+ const agent = new ToolLoopAgent({
498
+ telemetry: input.telemetry.settings,
499
+ model: this.model,
500
+ instructions: this.instructions(),
501
+ allowSystemInMessages: true,
502
+ tools: input.tools,
503
+ // Steered input joins the turn before the next model step. It is
504
+ // stored first: read, it survives a stop during that step.
505
+ prepareStep: async ({ messages: stepMessages }) => {
506
+ const fresh = this.steers.splice(0);
507
+ const inserted = fresh.map(userMessage);
508
+ prepared = [...stepMessages, ...inserted];
509
+ if (fresh.length > 0) {
510
+ try {
511
+ await this.append([
512
+ {
513
+ v: 1,
514
+ kind: "step",
515
+ ...(this.modelId ? { model: this.modelId } : {}),
516
+ messages: inserted,
517
+ },
518
+ ]);
519
+ this.emit({
520
+ type: "input.consumed",
521
+ itemIds: fresh.map((steer) => steer.itemId),
522
+ });
523
+ } catch (cause) {
524
+ // Unread, it runs as a turn of its own after this failed one.
525
+ this.failureCause = cause;
526
+ this.failure.abort();
527
+ }
528
+ }
529
+ return { messages: prepared };
530
+ },
531
+ onStepFinish: async (step) => {
532
+ stepsLeft -= 1;
533
+ messages = [...prepared, ...step.response.messages];
534
+ const written = step.response.messages;
535
+ try {
536
+ await this.append([
537
+ {
538
+ v: 1,
539
+ kind: "step",
540
+ ...(this.modelId ? { model: this.modelId } : {}),
541
+ messages: written,
542
+ },
543
+ ]);
544
+ } catch (cause) {
545
+ this.failureCause = cause;
546
+ this.failure.abort();
547
+ }
548
+ },
549
+ stopWhen: stepCountIs(Math.max(1, stepsLeft)),
550
+ ...(effort ? { providerOptions: effortProviderOptions(effort) } : {}),
551
+ });
552
+ const result = await input.telemetry.run(() =>
553
+ agent.stream({ messages, abortSignal: signal }),
554
+ );
555
+ try {
556
+ for await (const part of result.stream) this.onPart(part);
557
+ } finally {
558
+ this.closeText();
559
+ this.settleAnnounced();
560
+ }
561
+ if (this.failure.signal.aborted) throw this.failureCause;
562
+ if (this.abort.signal.aborted) return;
563
+ // A steer that arrived during the last step starts one more round.
564
+ if (this.steers.length === 0 || stepsLeft <= 0) {
565
+ this.accepting = false;
566
+ return;
567
+ }
568
+ }
569
+ }
570
+
571
+ private tools(servers: ReadonlyMap<string, ConnectedMcpServer>) {
572
+ const sets: ToolSetWithMeta[] = [];
573
+ const sandbox = this.local.sandbox;
574
+ if (sandbox)
575
+ sets.push(
576
+ workspaceTools({
577
+ provider: sandbox.provider,
578
+ sandboxId: sandbox.sandboxId,
579
+ workingDirectory: this.workingDirectory,
580
+ readableRoots: [
581
+ ...(this.local.readableRoots ?? []),
582
+ ...this.attempt.plugins.map((plugin) => plugin.path),
583
+ ],
584
+ shell: this.local.shell ?? {},
585
+ ...(sandbox.commandBudgetSeconds
586
+ ? { budgetSeconds: sandbox.commandBudgetSeconds }
587
+ : {}),
588
+ ...(sandbox.envFiles ? { envFiles: sandbox.envFiles } : {}),
589
+ stopWaiting: () => this.waits.signal,
590
+ }),
591
+ );
592
+ sets.push(
593
+ conversationTools({ ask: (args) => this.askUser(args) }),
594
+ hostTools({
595
+ descriptors: this.attempt.hostTools,
596
+ call: (args) => this.callHostTool(args),
597
+ }),
598
+ );
599
+ // Earlier sets win: a host or MCP tool never shadows a built-in.
600
+ const tools: Record<string, Tool> = {};
601
+ const meta = new Map<string, ToolMeta>();
602
+ const add = (set: ToolSetWithMeta) => {
603
+ for (const [name, entry] of Object.entries(set.tools)) {
604
+ if (Object.hasOwn(tools, name)) continue;
605
+ tools[name] = this.announcedFirst(entry);
606
+ const info = set.meta.get(name);
607
+ if (info) meta.set(name, info);
608
+ }
609
+ };
610
+ for (const set of sets) add(set);
611
+ add(
612
+ mcpTools({
613
+ servers,
614
+ taken: tools,
615
+ authorize: (args) => this.authorizeMcp(args),
616
+ }),
617
+ );
618
+ this.toolMeta = meta;
619
+ return tools;
620
+ }
621
+
622
+ private toolMeta = new Map<string, ToolMeta>();
623
+
624
+ /**
625
+ * A tool runs only after its call was reported: the text before it, its
626
+ * item, then whatever it asks the host, in that order.
627
+ */
628
+ private announcedFirst(entry: Tool): Tool {
629
+ const execute = entry.execute;
630
+ if (!execute) return entry;
631
+ return {
632
+ ...entry,
633
+ execute: async (args, options) => {
634
+ await this.announcement(options.toolCallId).promise;
635
+ options.abortSignal?.throwIfAborted();
636
+ return execute(args, options);
637
+ },
638
+ };
639
+ }
640
+
641
+ private announcement(toolCallId: string): Deferred {
642
+ let entry = this.announced.get(toolCallId);
643
+ if (!entry) {
644
+ let resolve = () => {};
645
+ const promise = new Promise<void>((done) => {
646
+ resolve = done;
647
+ });
648
+ entry = { promise, resolve };
649
+ this.announced.set(toolCallId, entry);
650
+ }
651
+ return entry;
652
+ }
653
+
654
+ private settleAnnounced(): void {
655
+ for (const entry of this.announced.values()) entry.resolve();
656
+ }
657
+
658
+ // -------------------------------------------------------------------------
659
+ // Stream parts → harness events
660
+
661
+ private onPart(part: TextStreamPart<Record<string, Tool>>): void {
662
+ switch (part.type) {
663
+ case "text-delta":
664
+ this.textDelta(part.text);
665
+ return;
666
+ case "reasoning-start":
667
+ this.closeText();
668
+ this.reasoningSegment(part.id);
669
+ return;
670
+ case "reasoning-delta":
671
+ this.reasoningDelta(part.id, part.text);
672
+ return;
673
+ case "reasoning-end":
674
+ this.reasoningEnd(part.id);
675
+ return;
676
+ case "tool-input-start":
677
+ this.closeText();
678
+ return;
679
+ case "tool-call":
680
+ this.closeText();
681
+ this.toolCall({
682
+ toolCallId: part.toolCallId,
683
+ toolName: part.toolName,
684
+ input: part.input,
685
+ });
686
+ this.announcement(part.toolCallId).resolve();
687
+ return;
688
+ case "tool-result":
689
+ this.toolResult(part.toolCallId, part.output);
690
+ return;
691
+ case "tool-error":
692
+ this.toolFailed(part.toolCallId, errorMessage(part.error));
693
+ return;
694
+ case "tool-output-denied":
695
+ this.toolFailed(part.toolCallId, "The tool call was denied.");
696
+ return;
697
+ case "finish-step":
698
+ this.closeText();
699
+ this.usage.add(part.usage);
700
+ return;
701
+ case "error":
702
+ throw part.error;
703
+ default:
704
+ return;
705
+ }
706
+ }
707
+
708
+ private textDelta(delta: string): void {
709
+ this.text ??= {
710
+ key: `text:${++this.segments}`,
711
+ text: "",
712
+ started: false,
713
+ };
714
+ const segment = this.text;
715
+ segment.text += delta;
716
+ if (!segment.started) {
717
+ // Whitespace before the first word starts nothing.
718
+ if (!segment.text.trim()) return;
719
+ segment.started = true;
720
+ this.emit({
721
+ type: "item.started",
722
+ key: segment.key,
723
+ item: { kind: "assistant_message", text: "", agentId: null },
724
+ });
725
+ this.emit({
726
+ type: "item.delta",
727
+ key: segment.key,
728
+ field: "text",
729
+ text: segment.text,
730
+ });
731
+ return;
732
+ }
733
+ this.emit({
734
+ type: "item.delta",
735
+ key: segment.key,
736
+ field: "text",
737
+ text: delta,
738
+ });
739
+ }
740
+
741
+ private closeText(): void {
742
+ const segment = this.text;
743
+ this.text = undefined;
744
+ if (!segment?.started) return;
745
+ this.emit({
746
+ type: "item.completed",
747
+ key: segment.key,
748
+ status: "completed",
749
+ item: { text: segment.text },
750
+ });
751
+ }
752
+
753
+ private reasoningSegment(id: string): OpenSegment {
754
+ let segment = this.reasoning.get(id);
755
+ if (!segment) {
756
+ segment = {
757
+ key: `reasoning:${++this.segments}`,
758
+ text: "",
759
+ started: false,
760
+ };
761
+ this.reasoning.set(id, segment);
762
+ }
763
+ return segment;
764
+ }
765
+
766
+ private reasoningDelta(id: string, delta: string): void {
767
+ const segment = this.reasoningSegment(id);
768
+ segment.text += delta;
769
+ if (!segment.started) {
770
+ // Providers stream empty reasoning beside encrypted content.
771
+ if (!segment.text.trim()) return;
772
+ segment.started = true;
773
+ this.emit({
774
+ type: "item.started",
775
+ key: segment.key,
776
+ item: { kind: "reasoning", text: "" },
777
+ });
778
+ this.emit({
779
+ type: "item.delta",
780
+ key: segment.key,
781
+ field: "text",
782
+ text: segment.text,
783
+ });
784
+ return;
785
+ }
786
+ this.emit({
787
+ type: "item.delta",
788
+ key: segment.key,
789
+ field: "text",
790
+ text: delta,
791
+ });
792
+ }
793
+
794
+ private reasoningEnd(id: string): void {
795
+ const segment = this.reasoning.get(id);
796
+ this.reasoning.delete(id);
797
+ if (!segment?.started) return;
798
+ this.emit({
799
+ type: "item.completed",
800
+ key: segment.key,
801
+ status: "completed",
802
+ item: { text: segment.text },
803
+ });
804
+ // Reasoning summaries open with a bold heading: the live status, held
805
+ // through the steps it leads to.
806
+ const heading = reasoningHeading(segment.text);
807
+ if (heading) {
808
+ this.heading = heading;
809
+ this.emit({ type: "status", text: heading });
810
+ }
811
+ }
812
+
813
+ private toolCall(call: {
814
+ toolCallId: string;
815
+ toolName: string;
816
+ input: unknown;
817
+ }): void {
818
+ const meta = this.toolMeta.get(call.toolName);
819
+ const values = isRecord(call.input) ? call.input : {};
820
+ const key = `tool:${call.toolCallId}`;
821
+ const description =
822
+ typeof values.description === "string" && values.description
823
+ ? values.description
824
+ : null;
825
+ if (meta?.kind === "title") {
826
+ if (typeof values.title === "string" && values.title.trim())
827
+ this.emit({ type: "title", text: values.title.trim() });
828
+ this.toolItems.set(call.toolCallId, { key: null, meta });
829
+ return;
830
+ }
831
+ // A question is its runtime request, not a tool call.
832
+ if (meta?.kind === "ask") {
833
+ this.toolItems.set(call.toolCallId, { key: null, meta });
834
+ return;
835
+ }
836
+ this.toolItems.set(call.toolCallId, { key, meta });
837
+ if (meta?.kind === "command") {
838
+ this.emit({
839
+ type: "item.started",
840
+ key,
841
+ item: {
842
+ kind: "command",
843
+ command: typeof values.command === "string" ? values.command : "",
844
+ description,
845
+ output: "",
846
+ exitCode: null,
847
+ },
848
+ ...this.said(),
849
+ });
850
+ return;
851
+ }
852
+ if (meta?.kind === "file") {
853
+ const filePath = typeof values.path === "string" ? values.path : "";
854
+ this.emit({
855
+ type: "item.started",
856
+ key,
857
+ item: {
858
+ kind: "file_change",
859
+ path: this.projectRelative(filePath),
860
+ change: meta.change,
861
+ previousPath: null,
862
+ },
863
+ ...this.said(),
864
+ });
865
+ return;
866
+ }
867
+ this.emit({
868
+ type: "item.started",
869
+ key,
870
+ item: {
871
+ kind: "tool_call",
872
+ tool: call.toolName,
873
+ server: meta?.kind === "tool" ? meta.server : null,
874
+ description,
875
+ input: toJsonValue(call.input),
876
+ result: null,
877
+ error: null,
878
+ },
879
+ ...this.said(),
880
+ });
881
+ }
882
+
883
+ /** The agent's latest reasoning heading, for the steps it leads to. */
884
+ private said(): { activity?: string } {
885
+ return this.heading ? { activity: this.heading } : {};
886
+ }
887
+
888
+ private projectRelative(filePath: string): string {
889
+ try {
890
+ return path.posix.relative(
891
+ this.workingDirectory,
892
+ resolveProjectPath(this.workingDirectory, filePath),
893
+ );
894
+ } catch {
895
+ return filePath;
896
+ }
897
+ }
898
+
899
+ private toolResult(toolCallId: string, output: unknown): void {
900
+ const entry = this.toolItems.get(toolCallId);
901
+ this.toolItems.delete(toolCallId);
902
+ if (!entry?.key) return;
903
+ if (entry.meta?.kind === "command") {
904
+ const shell = shellResultSchema.safeParse(output);
905
+ this.emit({
906
+ type: "item.completed",
907
+ key: entry.key,
908
+ status: "completed",
909
+ item: shell.success
910
+ ? { output: shell.data.output, exitCode: shell.data.exitCode }
911
+ : { output: typeof output === "string" ? output : "" },
912
+ });
913
+ return;
914
+ }
915
+ if (entry.meta?.kind === "file") {
916
+ this.emit({
917
+ type: "item.completed",
918
+ key: entry.key,
919
+ status: "completed",
920
+ });
921
+ return;
922
+ }
923
+ const host = parseHostToolResult(output);
924
+ const result = toJsonValue(transcriptToolResult(output));
925
+ if (
926
+ entry.meta?.kind === "tool" &&
927
+ entry.meta.source === "host" &&
928
+ host?.isError
929
+ ) {
930
+ this.emit({
931
+ type: "item.completed",
932
+ key: entry.key,
933
+ status: "failed",
934
+ item: {
935
+ result,
936
+ error: host.content
937
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
938
+ .join("\n"),
939
+ },
940
+ });
941
+ return;
942
+ }
943
+ this.emit({
944
+ type: "item.completed",
945
+ key: entry.key,
946
+ status: "completed",
947
+ item: { result },
948
+ });
949
+ }
950
+
951
+ private toolFailed(toolCallId: string, message: string): void {
952
+ const entry = this.toolItems.get(toolCallId);
953
+ this.toolItems.delete(toolCallId);
954
+ if (!entry?.key) return;
955
+ this.emit({
956
+ type: "item.completed",
957
+ key: entry.key,
958
+ status: "failed",
959
+ item:
960
+ entry.meta?.kind === "command"
961
+ ? { output: message }
962
+ : entry.meta?.kind === "file"
963
+ ? {}
964
+ : { error: message },
965
+ });
966
+ }
967
+
968
+ private closeOpenItems(status: "completed" | "failed" | "interrupted"): void {
969
+ this.closeText();
970
+ for (const id of [...this.reasoning.keys()]) this.reasoningEnd(id);
971
+ for (const [toolCallId, entry] of this.toolItems) {
972
+ this.toolItems.delete(toolCallId);
973
+ if (!entry.key) continue;
974
+ this.emit({
975
+ type: "item.completed",
976
+ key: entry.key,
977
+ status: status === "interrupted" ? "cancelled" : "failed",
978
+ });
979
+ }
980
+ }
981
+
982
+ // -------------------------------------------------------------------------
983
+ // Host calls and requests
984
+
985
+ /** Open a request and wait; an interrupt withdraws it. */
986
+ private async request(key: string, draft: RequestDraft) {
987
+ try {
988
+ return await untilAborted(
989
+ this.host.request(key, draft),
990
+ this.abort.signal,
991
+ );
992
+ } catch (cause) {
993
+ if (this.abort.signal.aborted && !(cause instanceof RequestClosedError))
994
+ this.emit({ type: "request.closed", key, reason: "The turn stopped." });
995
+ throw cause;
996
+ }
997
+ }
998
+
999
+ private async askUser(args: {
1000
+ questions: Array<{
1001
+ question: string;
1002
+ header: string;
1003
+ multiSelect: boolean;
1004
+ options: Array<{ label: string; description: string }>;
1005
+ }>;
1006
+ blocking: boolean;
1007
+ toolCallId: string;
1008
+ }): Promise<string> {
1009
+ const key = `ask:${args.toolCallId}`;
1010
+ const first = args.questions[0];
1011
+ const draft: RequestDraft = {
1012
+ kind: "question",
1013
+ blocking: args.blocking,
1014
+ title:
1015
+ args.questions.length === 1 && first
1016
+ ? first.question
1017
+ : `${args.questions.length} questions`,
1018
+ origin: { kind: "tool", id: "ask_user", displayName: "Ask User" },
1019
+ questions: args.questions,
1020
+ };
1021
+ if (!args.blocking) {
1022
+ // The answer arrives as a message (ADR 0198); nothing waits here.
1023
+ this.host.request(key, draft).catch(() => {});
1024
+ return "Asked. The answer arrives as a message when the person replies; keep working on what does not depend on it.";
1025
+ }
1026
+ try {
1027
+ const response = await this.request(key, draft);
1028
+ if (response.kind !== "question") return "The person did not answer.";
1029
+ return args.questions
1030
+ .map(
1031
+ (question, index) =>
1032
+ `${question.question}\nAnswer: ${response.answers[index] ?? "(no answer)"}`,
1033
+ )
1034
+ .concat(response.answers.slice(args.questions.length))
1035
+ .join("\n\n");
1036
+ } catch (cause) {
1037
+ if (cause instanceof RequestClosedError)
1038
+ return `The question was closed without an answer: ${cause.reason}`;
1039
+ throw cause;
1040
+ }
1041
+ }
1042
+
1043
+ private async callHostTool(args: {
1044
+ name: string;
1045
+ input: unknown;
1046
+ toolCallId: string;
1047
+ }): Promise<HostToolResult> {
1048
+ return untilAborted(
1049
+ this.host.callTool({
1050
+ name: args.name,
1051
+ input: toJsonValue(args.input),
1052
+ itemKey: `tool:${args.toolCallId}`,
1053
+ }),
1054
+ this.abort.signal,
1055
+ );
1056
+ }
1057
+
1058
+ /** Servers with a policy are decided by it; only `ask` reaches a person. */
1059
+ private async authorizeMcp(args: {
1060
+ server: string;
1061
+ tool: { name: string };
1062
+ input: Record<string, unknown>;
1063
+ toolCallId: string;
1064
+ }): Promise<void> {
1065
+ if (!this.attempt.toolPolicies[args.server]) return;
1066
+ const verdict = await untilAborted(
1067
+ this.host.authorize({
1068
+ server: args.server,
1069
+ tool: args.tool.name,
1070
+ input: toJsonValue(args.input),
1071
+ itemKey: `tool:${args.toolCallId}`,
1072
+ }),
1073
+ this.abort.signal,
1074
+ );
1075
+ if (!verdict.allowed) throw new Error(verdict.message);
1076
+ }
1077
+
1078
+ private async connectMcp(): Promise<Map<string, ConnectedMcpServer>> {
1079
+ const connect: McpConnector =
1080
+ this.options.connectMcp ??
1081
+ (({ spec, onElicit }) => connectMcpServer(spec, { onElicit }));
1082
+ const entries = Object.entries(this.attempt.mcpServers);
1083
+ const connected = await Promise.all(
1084
+ entries.map(async ([name, spec]) => {
1085
+ try {
1086
+ return await connect({
1087
+ name,
1088
+ spec,
1089
+ onElicit: (request) => this.elicit(name, request),
1090
+ });
1091
+ } catch (cause) {
1092
+ // A broken connector never breaks the chat.
1093
+ this.emit({
1094
+ type: "diagnostic",
1095
+ level: "warn",
1096
+ message: `The MCP server "${name}" did not connect: ${errorMessage(cause)}`,
1097
+ });
1098
+ return undefined;
1099
+ }
1100
+ }),
1101
+ );
1102
+ const servers = new Map<string, ConnectedMcpServer>();
1103
+ entries.forEach(([name], index) => {
1104
+ const server = connected[index];
1105
+ if (server) servers.set(name, server);
1106
+ });
1107
+ return servers;
1108
+ }
1109
+
1110
+ /** An MCP server asks the person for input (form or URL). */
1111
+ private async elicit(
1112
+ server: string,
1113
+ request: ElicitRequest,
1114
+ ): Promise<ElicitResult> {
1115
+ const key = `elicitation:${server}:${++this.requests}`;
1116
+ try {
1117
+ const response = await this.request(key, {
1118
+ kind: "elicitation",
1119
+ blocking: true,
1120
+ title: `${server} needs your input`,
1121
+ description: request.message,
1122
+ origin: { kind: "mcp", id: server, displayName: server },
1123
+ elicitation: {
1124
+ server,
1125
+ message: request.message,
1126
+ ...(request.mode === "url"
1127
+ ? { url: request.url }
1128
+ : { schema: elicitationSchema(request.fields) }),
1129
+ },
1130
+ });
1131
+ if (response.kind !== "elicitation") return { action: "cancel" };
1132
+ if (response.action === "accept")
1133
+ return {
1134
+ action: "accept",
1135
+ ...(isRecord(response.content) ? { content: response.content } : {}),
1136
+ };
1137
+ return { action: response.action };
1138
+ } catch {
1139
+ return { action: "cancel" };
1140
+ }
1141
+ }
1142
+ }
1143
+
1144
+ const shellResultSchema = z.object({
1145
+ exitCode: z.number(),
1146
+ output: z.string(),
1147
+ });
1148
+
1149
+ /** An elicitation form's fields as the JSON Schema a request carries. */
1150
+ function elicitationSchema(
1151
+ fields: Extract<ElicitRequest, { mode: "form" }>["fields"],
1152
+ ): { [key: string]: JsonValue } {
1153
+ const properties: { [key: string]: JsonValue } = {};
1154
+ for (const field of fields) {
1155
+ const values = field.options?.map((option) => option.value);
1156
+ const base = {
1157
+ ...(field.title ? { title: field.title } : {}),
1158
+ ...(field.description ? { description: field.description } : {}),
1159
+ ...(field.format ? { format: field.format } : {}),
1160
+ ...(field.default !== undefined ? { default: field.default } : {}),
1161
+ };
1162
+ properties[field.name] =
1163
+ field.type === "enum"
1164
+ ? field.multiSelect
1165
+ ? {
1166
+ ...base,
1167
+ type: "array",
1168
+ items: { type: "string", enum: values ?? [] },
1169
+ }
1170
+ : { ...base, type: "string", enum: values ?? [] }
1171
+ : { ...base, type: field.type };
1172
+ }
1173
+ return {
1174
+ type: "object",
1175
+ properties,
1176
+ required: fields
1177
+ .filter((field) => field.required)
1178
+ .map((field) => field.name),
1179
+ };
1180
+ }
1181
+
1182
+ /**
1183
+ * Prose with inline references in place of attachment markers, text
1184
+ * attachments as labelled context blocks after it, media as image and file
1185
+ * parts beside it.
1186
+ */
1187
+ function userMessage(input: {
1188
+ text: string;
1189
+ attachments: AgentAttachment[];
1190
+ }): ModelMessage {
1191
+ const text = renderUserMessage(input.text, input.attachments);
1192
+ const media = input.attachments.filter(isMediaAttachment);
1193
+ if (media.length === 0) return { role: "user", content: text };
1194
+ return {
1195
+ role: "user",
1196
+ content: [
1197
+ { type: "text", text },
1198
+ ...media.map((attachment) =>
1199
+ attachment.kind === "image"
1200
+ ? {
1201
+ type: "image" as const,
1202
+ image: attachment.dataBase64,
1203
+ mediaType: attachment.mediaType,
1204
+ }
1205
+ : {
1206
+ type: "file" as const,
1207
+ data: attachment.dataBase64,
1208
+ mediaType: attachment.mediaType,
1209
+ filename: attachment.name,
1210
+ },
1211
+ ),
1212
+ ],
1213
+ };
1214
+ }
1215
+
1216
+ /**
1217
+ * The normalized effort scale on each provider's native reasoning knob.
1218
+ * Both keys are always present: providers ignore options addressed to
1219
+ * someone else. Anthropic gets a thinking budget per level; OpenAI's
1220
+ * reasoning effort stops at "high", so the top levels clamp to it.
1221
+ */
1222
+ const ANTHROPIC_THINKING_BUDGETS: Record<AgentEffort, number> = {
1223
+ low: 0,
1224
+ medium: 10_000,
1225
+ high: 32_000,
1226
+ xhigh: 48_000,
1227
+ max: 64_000,
1228
+ };
1229
+
1230
+ function effortProviderOptions(effort: AgentEffort) {
1231
+ return {
1232
+ anthropic:
1233
+ effort === "low"
1234
+ ? { thinking: { type: "disabled" } }
1235
+ : {
1236
+ thinking: {
1237
+ type: "enabled",
1238
+ budgetTokens: ANTHROPIC_THINKING_BUDGETS[effort],
1239
+ },
1240
+ },
1241
+ openai: {
1242
+ reasoningEffort: effort === "xhigh" || effort === "max" ? "high" : effort,
1243
+ // Summaries carry the headings the host shows as live status.
1244
+ reasoningSummary: "auto",
1245
+ },
1246
+ };
1247
+ }
1248
+
1249
+ /**
1250
+ * A turn's token accounting (ADR 0057), summed over its model steps. The
1251
+ * AI SDK's `inputTokens` is the provider's whole prompt; the cached splits
1252
+ * live in `inputTokenDetails` when the provider reports them. The context
1253
+ * after the turn is the last step's prompt plus what it wrote.
1254
+ */
1255
+ class UsageTally {
1256
+ private input = 0;
1257
+ private cached = 0;
1258
+ private cacheCreation = 0;
1259
+ private output = 0;
1260
+ private reasoning = 0;
1261
+ private context = 0;
1262
+
1263
+ add(usage: LanguageModelUsage): void {
1264
+ const input = positiveTokenCount(usage.inputTokens);
1265
+ const output = positiveTokenCount(usage.outputTokens);
1266
+ this.input += input;
1267
+ this.cached += positiveTokenCount(usage.inputTokenDetails?.cacheReadTokens);
1268
+ this.cacheCreation += positiveTokenCount(
1269
+ usage.inputTokenDetails?.cacheWriteTokens,
1270
+ );
1271
+ this.output += output;
1272
+ this.reasoning += positiveTokenCount(
1273
+ usage.outputTokenDetails?.reasoningTokens,
1274
+ );
1275
+ if (input + output > 0) this.context = input + output;
1276
+ }
1277
+
1278
+ toUsage(model: string | undefined): AgentTurnUsage | undefined {
1279
+ if (this.input + this.output === 0) return undefined;
1280
+ return {
1281
+ ...(model ? { model } : {}),
1282
+ // Prompt totals include the cached portion; report the uncached
1283
+ // remainder so counters never double count.
1284
+ inputTokens: Math.max(0, this.input - this.cached - this.cacheCreation),
1285
+ cachedInputTokens: this.cached,
1286
+ cacheCreationTokens: this.cacheCreation,
1287
+ outputTokens: this.output,
1288
+ reasoningTokens: Math.min(this.output, this.reasoning),
1289
+ ...(this.context ? { contextTokens: this.context } : {}),
1290
+ };
1291
+ }
1292
+ }
1293
+
1294
+ function modelIdOf(model: LanguageModel): string | undefined {
1295
+ return typeof model === "string" ? model : model.modelId;
1296
+ }
1297
+
1298
+ /** Settle with the promise, or reject once the signal aborts. */
1299
+ function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
1300
+ if (signal.aborted) {
1301
+ promise.catch(() => {});
1302
+ return Promise.reject(abortError());
1303
+ }
1304
+ return new Promise<T>((resolve, reject) => {
1305
+ const onAbort = () => {
1306
+ promise.catch(() => {});
1307
+ reject(abortError());
1308
+ };
1309
+ signal.addEventListener("abort", onAbort, { once: true });
1310
+ promise.then(
1311
+ (value) => {
1312
+ signal.removeEventListener("abort", onAbort);
1313
+ resolve(value);
1314
+ },
1315
+ (cause: unknown) => {
1316
+ signal.removeEventListener("abort", onAbort);
1317
+ reject(cause);
1318
+ },
1319
+ );
1320
+ });
1321
+ }
1322
+
1323
+ function abortError(): Error {
1324
+ const error = new Error("The turn stopped.");
1325
+ error.name = "AbortError";
1326
+ return error;
1327
+ }
1328
+
1329
+ /** `local` as this adapter's host objects; a malformed sandbox fails loudly. */
1330
+ function readLocal(local: Record<string, unknown> | undefined): AiSdkLocal {
1331
+ if (!local) return {};
1332
+ const sandbox = local.sandbox;
1333
+ if (sandbox !== undefined && !isSandboxHandle(sandbox))
1334
+ throw new Error(
1335
+ "The ai-sdk harness was given a sandbox without a provider, sandbox id and working directory.",
1336
+ );
1337
+ const roots = local.readableRoots;
1338
+ const shell = local.shell;
1339
+ return {
1340
+ ...(sandbox ? { sandbox } : {}),
1341
+ ...(Array.isArray(roots)
1342
+ ? {
1343
+ readableRoots: roots.filter(
1344
+ (root): root is string => typeof root === "string",
1345
+ ),
1346
+ }
1347
+ : {}),
1348
+ ...(isShellState(shell) ? { shell } : {}),
1349
+ ...(typeof local.userId === "string" ? { userId: local.userId } : {}),
1350
+ };
1351
+ }
1352
+
1353
+ function isSandboxHandle(
1354
+ value: unknown,
1355
+ ): value is NonNullable<AiSdkLocal["sandbox"]> {
1356
+ return (
1357
+ isRecord(value) &&
1358
+ isRecord(value.provider) &&
1359
+ typeof value.provider.executeCommand === "function" &&
1360
+ typeof value.provider.uploadFiles === "function" &&
1361
+ typeof value.provider.downloadFile === "function" &&
1362
+ typeof value.sandboxId === "string" &&
1363
+ typeof value.workingDirectory === "string" &&
1364
+ (value.commandBudgetSeconds === undefined ||
1365
+ typeof value.commandBudgetSeconds === "number") &&
1366
+ (value.envFiles === undefined ||
1367
+ (Array.isArray(value.envFiles) &&
1368
+ value.envFiles.every((file: unknown) => typeof file === "string")))
1369
+ );
1370
+ }
1371
+
1372
+ function isShellState(value: unknown): value is ShellState {
1373
+ return (
1374
+ isRecord(value) &&
1375
+ (value.cwd === undefined || typeof value.cwd === "string") &&
1376
+ (value.background === undefined || value.background instanceof Map)
1377
+ );
1378
+ }