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

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.
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Replay harness for the built-in agent (ADR 0198: tests replay real
3
+ * transcripts). A {@link ModelTranscript} is what the model provider
4
+ * streamed, call by call, as AI SDK provider stream parts; {@link replayModel}
5
+ * plays it back as a `LanguageModel`, so a test replaces only the model
6
+ * transport and runs the adapter, its tools, the runner and the host for
7
+ * real. {@link recordModel} captures a transcript from a live model.
8
+ *
9
+ * Transcripts are JSON: record one against a real provider once, save it
10
+ * beside the test, and replay it in every run.
11
+ */
12
+ import { wrapLanguageModel } from "ai";
13
+ import { MockLanguageModelV4 } from "ai/test";
14
+ type StreamResult = Awaited<ReturnType<MockLanguageModelV4["doStream"]>>;
15
+ type CallOptions = Parameters<MockLanguageModelV4["doStream"]>[0];
16
+ /** One part of a provider's stream, exactly as the model transport yields it. */
17
+ export type ModelStreamPart = StreamResult["stream"] extends ReadableStream<infer Part> ? Part : never;
18
+ /** What the model received for one call: the prompt, tools and settings. */
19
+ export type ModelCallOptions = CallOptions;
20
+ export type ModelCall = {
21
+ /** The parts the provider streamed for this call. */
22
+ parts: ModelStreamPart[];
23
+ /**
24
+ * Keep the stream open after the parts until the call is aborted, as
25
+ * a provider does while the model is still writing.
26
+ */
27
+ hang?: boolean;
28
+ } | {
29
+ /** The provider refused the request before streaming anything. */
30
+ reject: {
31
+ message: string;
32
+ statusCode?: number;
33
+ responseBody?: string;
34
+ isRetryable?: boolean;
35
+ };
36
+ };
37
+ export interface ModelTranscript {
38
+ /** The model id the replay reports; `replay-model` by default. */
39
+ modelId?: string;
40
+ provider?: string;
41
+ calls: ModelCall[];
42
+ }
43
+ export interface ReplayModel {
44
+ /** The model to hand the adapter. */
45
+ model: MockLanguageModelV4;
46
+ /** What each call received, in order. */
47
+ readonly calls: ModelCallOptions[];
48
+ /** Calls the transcript holds that nobody made yet. */
49
+ remaining(): number;
50
+ }
51
+ /**
52
+ * A model that plays a transcript back. A call past its end fails the
53
+ * test with a clear message instead of hanging. `beforeCall` runs before
54
+ * a call streams: a test can hold the model there (to steer, to
55
+ * interrupt) or inspect its prompt.
56
+ */
57
+ export declare function replayModel(transcript: ModelTranscript, hooks?: {
58
+ beforeCall?: (input: {
59
+ index: number;
60
+ options: ModelCallOptions;
61
+ }) => void | Promise<void>;
62
+ }): ReplayModel;
63
+ /**
64
+ * Wrap a live model so every call's streamed parts are kept: run a scenario
65
+ * against a real provider once, then save `transcript()` as the test's
66
+ * fixture.
67
+ */
68
+ export declare function recordModel(model: Parameters<typeof wrapLanguageModel>[0]["model"]): {
69
+ model: ReturnType<typeof wrapLanguageModel>;
70
+ transcript(): ModelTranscript;
71
+ };
72
+ export interface StepUsage {
73
+ input?: number;
74
+ output?: number;
75
+ cacheRead?: number;
76
+ cacheWrite?: number;
77
+ reasoning?: number;
78
+ }
79
+ /** The `finish` part a provider ends a call with. */
80
+ export declare function finishPart(input: {
81
+ reason: "stop" | "tool-calls" | "length" | "error" | "other";
82
+ usage?: StepUsage;
83
+ }): ModelStreamPart;
84
+ /** A text block, streamed in `chunks` deltas. */
85
+ export declare function textParts(text: string, options?: {
86
+ id?: string;
87
+ chunks?: number;
88
+ }): ModelStreamPart[];
89
+ /** A reasoning block (a summary opening with a bold heading becomes status). */
90
+ export declare function reasoningParts(text: string, options?: {
91
+ id?: string;
92
+ }): ModelStreamPart[];
93
+ /** One tool call, its input as the model wrote it. */
94
+ export declare function toolCallPart(input: {
95
+ id: string;
96
+ name: string;
97
+ input: unknown;
98
+ }): ModelStreamPart;
99
+ /** A call that answers in text and stops. */
100
+ export declare function replyCall(text: string, options?: {
101
+ reasoning?: string;
102
+ usage?: StepUsage;
103
+ hang?: boolean;
104
+ }): ModelCall;
105
+ /** A call that (optionally says something and) calls tools. */
106
+ export declare function toolCallsCall(calls: Array<{
107
+ id: string;
108
+ name: string;
109
+ input: unknown;
110
+ }>, options?: {
111
+ text?: string;
112
+ usage?: StepUsage;
113
+ }): ModelCall;
114
+ /** A call the provider refuses (a 429, a 401, a 400 about reasoning). */
115
+ export declare function rejectedCall(reject: Extract<ModelCall, {
116
+ reject: unknown;
117
+ }>["reject"]): ModelCall;
118
+ /** A call whose stream fails after it started. */
119
+ export declare function streamErrorCall(message: string): ModelCall;
120
+ /** A call that starts writing and never finishes until it is aborted. */
121
+ export declare function hangingCall(text?: string): ModelCall;
122
+ export {};
123
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAgB,iBAAiB,EAAE,MAAM,IAAI,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAE9C,KAAK,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACzE,KAAK,WAAW,GAAG,UAAU,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAElE,iFAAiF;AACjF,MAAM,MAAM,eAAe,GACzB,YAAY,CAAC,QAAQ,CAAC,SAAS,cAAc,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK,CAAC;AAE3E,4EAA4E;AAC5E,MAAM,MAAM,gBAAgB,GAAG,WAAW,CAAC;AAE3C,MAAM,MAAM,SAAS,GACjB;IACE,qDAAqD;IACrD,KAAK,EAAE,eAAe,EAAE,CAAC;IACzB;;;OAGG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB,GACD;IACE,kEAAkE;IAClE,MAAM,EAAE;QACN,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,YAAY,CAAC,EAAE,MAAM,CAAC;QACtB,WAAW,CAA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AAClD,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAO1D;AAED,yEAAyE;AACzE,wBAAgB,WAAW,CAAC,IAAI,SAAK,GAAG,SAAS,CAWhD"}
@@ -0,0 +1,211 @@
1
+ // src/testing/index.ts
2
+ import { APICallError, wrapLanguageModel } from "ai";
3
+ import { MockLanguageModelV4 } from "ai/test";
4
+ function replayModel(transcript, hooks) {
5
+ let next = 0;
6
+ const calls = [];
7
+ const model = new MockLanguageModelV4({
8
+ provider: transcript.provider ?? "replay",
9
+ modelId: transcript.modelId ?? "replay-model",
10
+ doStream: async (options) => {
11
+ const index = next;
12
+ next += 1;
13
+ calls.push(options);
14
+ await hooks?.beforeCall?.({ index, options });
15
+ const call = transcript.calls[index];
16
+ if (!call)
17
+ throw new Error(`The model was called ${index + 1} times; the transcript holds ${transcript.calls.length} calls.`);
18
+ if ("reject" in call)
19
+ throw new APICallError({
20
+ message: call.reject.message,
21
+ url: "https://replay.invalid/v1/messages",
22
+ requestBodyValues: {},
23
+ ...call.reject.statusCode !== undefined ? { statusCode: call.reject.statusCode } : {},
24
+ ...call.reject.responseBody !== undefined ? { responseBody: call.reject.responseBody } : {},
25
+ ...call.reject.isRetryable !== undefined ? { isRetryable: call.reject.isRetryable } : {}
26
+ });
27
+ return { stream: partStream(call.parts, call.hang, options.abortSignal) };
28
+ }
29
+ });
30
+ return {
31
+ model,
32
+ calls,
33
+ remaining: () => Math.max(0, transcript.calls.length - next)
34
+ };
35
+ }
36
+ function partStream(parts, hang, signal) {
37
+ let index = 0;
38
+ return new ReadableStream({
39
+ async pull(controller) {
40
+ const part = parts[index];
41
+ index += 1;
42
+ if (part) {
43
+ await new Promise((resolve) => setTimeout(resolve, 0));
44
+ controller.enqueue(structuredClone(part));
45
+ return;
46
+ }
47
+ if (!hang) {
48
+ controller.close();
49
+ return;
50
+ }
51
+ await new Promise((resolve) => {
52
+ if (signal?.aborted)
53
+ resolve();
54
+ else
55
+ signal?.addEventListener("abort", () => resolve(), { once: true });
56
+ });
57
+ controller.error(signal?.reason ?? new Error("aborted"));
58
+ }
59
+ });
60
+ }
61
+ function recordModel(model) {
62
+ const calls = [];
63
+ const wrapped = wrapLanguageModel({
64
+ model,
65
+ middleware: {
66
+ wrapStream: async ({ doStream }) => {
67
+ const result = await doStream();
68
+ const parts = [];
69
+ calls.push({ parts });
70
+ return {
71
+ ...result,
72
+ stream: result.stream.pipeThrough(new TransformStream({
73
+ transform(part, controller) {
74
+ parts.push(structuredClone(part));
75
+ controller.enqueue(part);
76
+ }
77
+ }))
78
+ };
79
+ }
80
+ }
81
+ });
82
+ return {
83
+ model: wrapped,
84
+ transcript: () => ({
85
+ modelId: wrapped.modelId,
86
+ provider: wrapped.provider,
87
+ calls: structuredClone(calls)
88
+ })
89
+ };
90
+ }
91
+ var DEFAULT_USAGE = {
92
+ input: 10,
93
+ output: 5,
94
+ cacheRead: 0,
95
+ cacheWrite: 0,
96
+ reasoning: 0
97
+ };
98
+ function finishPart(input) {
99
+ const usage = { ...DEFAULT_USAGE, ...input.usage };
100
+ return {
101
+ type: "finish",
102
+ finishReason: { unified: input.reason, raw: undefined },
103
+ usage: {
104
+ inputTokens: {
105
+ total: usage.input,
106
+ noCache: usage.input - usage.cacheRead - usage.cacheWrite,
107
+ cacheRead: usage.cacheRead,
108
+ cacheWrite: usage.cacheWrite
109
+ },
110
+ outputTokens: {
111
+ total: usage.output,
112
+ text: usage.output - usage.reasoning,
113
+ reasoning: usage.reasoning
114
+ }
115
+ }
116
+ };
117
+ }
118
+ function textParts(text, options) {
119
+ const id = options?.id ?? "text-0";
120
+ return [
121
+ { type: "text-start", id },
122
+ ...split(text, options?.chunks ?? 2).map((delta) => ({ type: "text-delta", id, delta })),
123
+ { type: "text-end", id }
124
+ ];
125
+ }
126
+ function reasoningParts(text, options) {
127
+ const id = options?.id ?? "reasoning-0";
128
+ return [
129
+ { type: "reasoning-start", id },
130
+ { type: "reasoning-delta", id, delta: text },
131
+ { type: "reasoning-end", id }
132
+ ];
133
+ }
134
+ function toolCallPart(input) {
135
+ return {
136
+ type: "tool-call",
137
+ toolCallId: input.id,
138
+ toolName: input.name,
139
+ input: JSON.stringify(input.input)
140
+ };
141
+ }
142
+ function replyCall(text, options) {
143
+ return {
144
+ parts: [
145
+ { type: "stream-start", warnings: [] },
146
+ ...options?.reasoning ? reasoningParts(options.reasoning) : [],
147
+ ...textParts(text),
148
+ ...options?.hang ? [] : [finishPart({ reason: "stop", ...usageOf(options) })]
149
+ ],
150
+ ...options?.hang ? { hang: true } : {}
151
+ };
152
+ }
153
+ function toolCallsCall(calls, options) {
154
+ return {
155
+ parts: [
156
+ { type: "stream-start", warnings: [] },
157
+ ...options?.text ? textParts(options.text) : [],
158
+ ...calls.map(toolCallPart),
159
+ finishPart({ reason: "tool-calls", ...usageOf(options) })
160
+ ]
161
+ };
162
+ }
163
+ function rejectedCall(reject) {
164
+ return { reject };
165
+ }
166
+ function streamErrorCall(message) {
167
+ return {
168
+ parts: [
169
+ { type: "stream-start", warnings: [] },
170
+ { type: "error", error: { message } }
171
+ ]
172
+ };
173
+ }
174
+ function hangingCall(text = "") {
175
+ return {
176
+ parts: [
177
+ { type: "stream-start", warnings: [] },
178
+ ...text ? [{ type: "text-start", id: "text-0" }] : [],
179
+ ...text ? [{ type: "text-delta", id: "text-0", delta: text }] : []
180
+ ],
181
+ hang: true
182
+ };
183
+ }
184
+ function usageOf(options) {
185
+ return options?.usage ? { usage: options.usage } : {};
186
+ }
187
+ function split(text, chunks) {
188
+ if (chunks <= 1 || text.length < chunks)
189
+ return [text];
190
+ const size = Math.ceil(text.length / chunks);
191
+ const parts = [];
192
+ for (let start = 0;start < text.length; start += size)
193
+ parts.push(text.slice(start, start + size));
194
+ return parts;
195
+ }
196
+ export {
197
+ finishPart,
198
+ hangingCall,
199
+ reasoningParts,
200
+ recordModel,
201
+ rejectedCall,
202
+ replayModel,
203
+ replyCall,
204
+ streamErrorCall,
205
+ textParts,
206
+ toolCallPart,
207
+ toolCallsCall
208
+ };
209
+
210
+ //# debugId=E495730765020FDF64756E2164756E21
211
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/testing/index.ts"],"sourcesContent":["/**\n * Replay harness for the built-in agent (ADR 0198: tests replay real\n * transcripts). A {@link ModelTranscript} is what the model provider\n * streamed, call by call, as AI SDK provider stream parts; {@link replayModel}\n * plays it back as a `LanguageModel`, so a test replaces only the model\n * transport and runs the adapter, its tools, the runner and the host for\n * real. {@link recordModel} captures a transcript from a live model.\n *\n * Transcripts are JSON: record one against a real provider once, save it\n * beside the test, and replay it in every run.\n */\nimport { APICallError, wrapLanguageModel } from \"ai\";\nimport { MockLanguageModelV4 } from \"ai/test\";\n\ntype StreamResult = Awaited<ReturnType<MockLanguageModelV4[\"doStream\"]>>;\ntype CallOptions = Parameters<MockLanguageModelV4[\"doStream\"]>[0];\n\n/** One part of a provider's stream, exactly as the model transport yields it. */\nexport type ModelStreamPart =\n StreamResult[\"stream\"] extends ReadableStream<infer Part> ? Part : never;\n\n/** What the model received for one call: the prompt, tools and settings. */\nexport type ModelCallOptions = CallOptions;\n\nexport type ModelCall =\n | {\n /** The parts the provider streamed for this call. */\n parts: ModelStreamPart[];\n /**\n * Keep the stream open after the parts until the call is aborted, as\n * a provider does while the model is still writing.\n */\n hang?: boolean;\n }\n | {\n /** The provider refused the request before streaming anything. */\n reject: {\n message: string;\n statusCode?: number;\n responseBody?: string;\n isRetryable?: boolean;\n };\n };\n\nexport interface ModelTranscript {\n /** The model id the replay reports; `replay-model` by default. */\n modelId?: string;\n provider?: string;\n calls: ModelCall[];\n}\n\nexport interface ReplayModel {\n /** The model to hand the adapter. */\n model: MockLanguageModelV4;\n /** What each call received, in order. */\n readonly calls: ModelCallOptions[];\n /** Calls the transcript holds that nobody made yet. */\n remaining(): number;\n}\n\n/**\n * A model that plays a transcript back. A call past its end fails the\n * test with a clear message instead of hanging. `beforeCall` runs before\n * a call streams: a test can hold the model there (to steer, to\n * interrupt) or inspect its prompt.\n */\nexport function replayModel(\n transcript: ModelTranscript,\n hooks?: {\n beforeCall?: (input: {\n index: number;\n options: ModelCallOptions;\n }) => void | Promise<void>;\n },\n): ReplayModel {\n let next = 0;\n const calls: ModelCallOptions[] = [];\n const model = new MockLanguageModelV4({\n provider: transcript.provider ?? \"replay\",\n modelId: transcript.modelId ?? \"replay-model\",\n doStream: async (options) => {\n const index = next;\n next += 1;\n calls.push(options);\n await hooks?.beforeCall?.({ index, options });\n const call = transcript.calls[index];\n if (!call)\n throw new Error(\n `The model was called ${index + 1} times; the transcript holds ${transcript.calls.length} calls.`,\n );\n if (\"reject\" in call)\n throw new APICallError({\n message: call.reject.message,\n url: \"https://replay.invalid/v1/messages\",\n requestBodyValues: {},\n ...(call.reject.statusCode !== undefined\n ? { statusCode: call.reject.statusCode }\n : {}),\n ...(call.reject.responseBody !== undefined\n ? { responseBody: call.reject.responseBody }\n : {}),\n ...(call.reject.isRetryable !== undefined\n ? { isRetryable: call.reject.isRetryable }\n : {}),\n });\n return { stream: partStream(call.parts, call.hang, options.abortSignal) };\n },\n });\n return {\n model,\n calls,\n remaining: () => Math.max(0, transcript.calls.length - next),\n };\n}\n\nfunction partStream(\n parts: readonly ModelStreamPart[],\n hang: boolean | undefined,\n signal: AbortSignal | undefined,\n): ReadableStream<ModelStreamPart> {\n let index = 0;\n return new ReadableStream<ModelStreamPart>({\n async pull(controller) {\n const part = parts[index];\n index += 1;\n if (part) {\n // A tick between parts, as a network stream has.\n await new Promise((resolve) => setTimeout(resolve, 0));\n controller.enqueue(structuredClone(part));\n return;\n }\n if (!hang) {\n controller.close();\n return;\n }\n await new Promise<void>((resolve) => {\n if (signal?.aborted) resolve();\n else signal?.addEventListener(\"abort\", () => resolve(), { once: true });\n });\n controller.error(signal?.reason ?? new Error(\"aborted\"));\n },\n });\n}\n\n/**\n * Wrap a live model so every call's streamed parts are kept: run a scenario\n * against a real provider once, then save `transcript()` as the test's\n * fixture.\n */\nexport function recordModel(\n model: Parameters<typeof wrapLanguageModel>[0][\"model\"],\n): {\n model: ReturnType<typeof wrapLanguageModel>;\n transcript(): ModelTranscript;\n} {\n const calls: ModelCall[] = [];\n const wrapped = wrapLanguageModel({\n model,\n middleware: {\n wrapStream: async ({ doStream }) => {\n const result = await doStream();\n const parts: ModelStreamPart[] = [];\n calls.push({ parts });\n return {\n ...result,\n stream: result.stream.pipeThrough(\n new TransformStream<ModelStreamPart, ModelStreamPart>({\n transform(part, controller) {\n parts.push(structuredClone(part));\n controller.enqueue(part);\n },\n }),\n ),\n };\n },\n },\n });\n return {\n model: wrapped,\n transcript: () => ({\n modelId: wrapped.modelId,\n provider: wrapped.provider,\n calls: structuredClone(calls),\n }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Builders for hand-written transcripts\n\nexport interface StepUsage {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n reasoning?: number;\n}\n\nconst DEFAULT_USAGE: Required<StepUsage> = {\n input: 10,\n output: 5,\n cacheRead: 0,\n cacheWrite: 0,\n reasoning: 0,\n};\n\n/** The `finish` part a provider ends a call with. */\nexport function finishPart(input: {\n reason: \"stop\" | \"tool-calls\" | \"length\" | \"error\" | \"other\";\n usage?: StepUsage;\n}): ModelStreamPart {\n const usage = { ...DEFAULT_USAGE, ...input.usage };\n return {\n type: \"finish\",\n finishReason: { unified: input.reason, raw: undefined },\n usage: {\n inputTokens: {\n total: usage.input,\n noCache: usage.input - usage.cacheRead - usage.cacheWrite,\n cacheRead: usage.cacheRead,\n cacheWrite: usage.cacheWrite,\n },\n outputTokens: {\n total: usage.output,\n text: usage.output - usage.reasoning,\n reasoning: usage.reasoning,\n },\n },\n };\n}\n\n/** A text block, streamed in `chunks` deltas. */\nexport function textParts(\n text: string,\n options?: { id?: string; chunks?: number },\n): ModelStreamPart[] {\n const id = options?.id ?? \"text-0\";\n return [\n { type: \"text-start\", id },\n ...split(text, options?.chunks ?? 2).map(\n (delta): ModelStreamPart => ({ type: \"text-delta\", id, delta }),\n ),\n { type: \"text-end\", id },\n ];\n}\n\n/** A reasoning block (a summary opening with a bold heading becomes status). */\nexport function reasoningParts(\n text: string,\n options?: { id?: string },\n): ModelStreamPart[] {\n const id = options?.id ?? \"reasoning-0\";\n return [\n { type: \"reasoning-start\", id },\n { type: \"reasoning-delta\", id, delta: text },\n { type: \"reasoning-end\", id },\n ];\n}\n\n/** One tool call, its input as the model wrote it. */\nexport function toolCallPart(input: {\n id: string;\n name: string;\n input: unknown;\n}): ModelStreamPart {\n return {\n type: \"tool-call\",\n toolCallId: input.id,\n toolName: input.name,\n input: JSON.stringify(input.input),\n };\n}\n\n/** A call that answers in text and stops. */\nexport function replyCall(\n text: string,\n options?: { reasoning?: string; usage?: StepUsage; hang?: boolean },\n): ModelCall {\n return {\n parts: [\n { type: \"stream-start\", warnings: [] },\n ...(options?.reasoning ? reasoningParts(options.reasoning) : []),\n ...textParts(text),\n ...(options?.hang\n ? []\n : [finishPart({ reason: \"stop\", ...usageOf(options) })]),\n ],\n ...(options?.hang ? { hang: true } : {}),\n };\n}\n\n/** A call that (optionally says something and) calls tools. */\nexport function toolCallsCall(\n calls: Array<{ id: string; name: string; input: unknown }>,\n options?: { text?: string; usage?: StepUsage },\n): ModelCall {\n return {\n parts: [\n { type: \"stream-start\", warnings: [] },\n ...(options?.text ? textParts(options.text) : []),\n ...calls.map(toolCallPart),\n finishPart({ reason: \"tool-calls\", ...usageOf(options) }),\n ],\n };\n}\n\n/** A call the provider refuses (a 429, a 401, a 400 about reasoning). */\nexport function rejectedCall(\n reject: Extract<ModelCall, { reject: unknown }>[\"reject\"],\n): ModelCall {\n return { reject };\n}\n\n/** A call whose stream fails after it started. */\nexport function streamErrorCall(message: string): ModelCall {\n return {\n parts: [\n { type: \"stream-start\", warnings: [] },\n { type: \"error\", error: { message } },\n ],\n };\n}\n\n/** A call that starts writing and never finishes until it is aborted. */\nexport function hangingCall(text = \"\"): ModelCall {\n return {\n parts: [\n { type: \"stream-start\", warnings: [] },\n ...(text ? [{ type: \"text-start\" as const, id: \"text-0\" }] : []),\n ...(text\n ? [{ type: \"text-delta\" as const, id: \"text-0\", delta: text }]\n : []),\n ],\n hang: true,\n };\n}\n\nfunction usageOf(options?: { usage?: StepUsage }): { usage?: StepUsage } {\n return options?.usage ? { usage: options.usage } : {};\n}\n\nfunction split(text: string, chunks: number): string[] {\n if (chunks <= 1 || text.length < chunks) return [text];\n const size = Math.ceil(text.length / chunks);\n const parts: string[] = [];\n for (let start = 0; start < text.length; start += size)\n parts.push(text.slice(start, start + size));\n return parts;\n}\n"],"mappings":";AAWA;AACA;AAsDO,SAAS,WAAW,CACzB,YACA,OAMa;AAAA,EACb,IAAI,OAAO;AAAA,EACX,MAAM,QAA4B,CAAC;AAAA,EACnC,MAAM,QAAQ,IAAI,oBAAoB;AAAA,IACpC,UAAU,WAAW,YAAY;AAAA,IACjC,SAAS,WAAW,WAAW;AAAA,IAC/B,UAAU,OAAO,YAAY;AAAA,MAC3B,MAAM,QAAQ;AAAA,MACd,QAAQ;AAAA,MACR,MAAM,KAAK,OAAO;AAAA,MAClB,MAAM,OAAO,aAAa,EAAE,OAAO,QAAQ,CAAC;AAAA,MAC5C,MAAM,OAAO,WAAW,MAAM;AAAA,MAC9B,IAAI,CAAC;AAAA,QACH,MAAM,IAAI,MACR,wBAAwB,QAAQ,iCAAiC,WAAW,MAAM,eACpF;AAAA,MACF,IAAI,YAAY;AAAA,QACd,MAAM,IAAI,aAAa;AAAA,UACrB,SAAS,KAAK,OAAO;AAAA,UACrB,KAAK;AAAA,UACL,mBAAmB,CAAC;AAAA,aAChB,KAAK,OAAO,eAAe,YAC3B,EAAE,YAAY,KAAK,OAAO,WAAW,IACrC,CAAC;AAAA,aACD,KAAK,OAAO,iBAAiB,YAC7B,EAAE,cAAc,KAAK,OAAO,aAAa,IACzC,CAAC;AAAA,aACD,KAAK,OAAO,gBAAgB,YAC5B,EAAE,aAAa,KAAK,OAAO,YAAY,IACvC,CAAC;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AAIX,SAAS,eAAe,CAAC,SAA4B;AAAA,EAC1D,OAAO;AAAA,IACL,OAAO;AAAA,MACL,EAAE,MAAM,gBAAgB,UAAU,CAAC,EAAE;AAAA,MACrC,EAAE,MAAM,SAAS,OAAO,EAAE,QAAQ,EAAE;AAAA,IACtC;AAAA,EACF;AAAA;AAIK,SAAS,WAAW,CAAC,OAAO,IAAe;AAAA,EAChD,OAAO;AAAA,IACL,OAAO;AAAA,MACL,EAAE,MAAM,gBAAgB,UAAU,CAAC,EAAE;AAAA,MACrC,GAAI,OAAO,CAAC,EAAE,MAAM,cAAuB,IAAI,SAAS,CAAC,IAAI,CAAC;AAAA,MAC9D,GAAI,OACA,CAAC,EAAE,MAAM,cAAuB,IAAI,UAAU,OAAO,KAAK,CAAC,IAC3D,CAAC;AAAA,IACP;AAAA,IACA,MAAM;AAAA,EACR;AAAA;AAGF,SAAS,OAAO,CAAC,SAAwD;AAAA,EACvE,OAAO,SAAS,QAAQ,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;AAAA;AAGtD,SAAS,KAAK,CAAC,MAAc,QAA0B;AAAA,EACrD,IAAI,UAAU,KAAK,KAAK,SAAS;AAAA,IAAQ,OAAO,CAAC,IAAI;AAAA,EACrD,MAAM,OAAO,KAAK,KAAK,KAAK,SAAS,MAAM;AAAA,EAC3C,MAAM,QAAkB,CAAC;AAAA,EACzB,SAAS,QAAQ,EAAG,QAAQ,KAAK,QAAQ,SAAS;AAAA,IAChD,MAAM,KAAK,KAAK,MAAM,OAAO,QAAQ,IAAI,CAAC;AAAA,EAC5C,OAAO;AAAA;","debugId":"E495730765020FDF64756E2164756E21","names":[]}
@@ -0,0 +1,71 @@
1
+ import type { JsonValue } from "@catamorphic/agent-protocol";
2
+ import { type ModelMessage } from "ai";
3
+ /**
4
+ * The built-in agent's native thread (ADR 0198) is its AI SDK message
5
+ * history, stored with Work as append-only entries: one `turn` entry with
6
+ * the turn's input, one `step` entry per finished model step, and a
7
+ * `turn_end` boundary a fork or a retry cuts at. Any replica, or a new
8
+ * process, folds the entries back into the same history.
9
+ */
10
+ export type ThreadEntry = {
11
+ v: 1;
12
+ kind: "turn";
13
+ /** The turn's native ref (its attempt id), named again by `turn_end`. */
14
+ ref: string;
15
+ input: ModelMessage[];
16
+ /** Trailing messages a retry replaced: dropped before `input`. */
17
+ drop?: number;
18
+ } | {
19
+ v: 1;
20
+ kind: "step";
21
+ /** The model that wrote the step; another model gets it without reasoning. */
22
+ model?: string;
23
+ messages: ModelMessage[];
24
+ } | {
25
+ v: 1;
26
+ kind: "turn_end";
27
+ ref: string;
28
+ status: "completed" | "failed" | "interrupted";
29
+ };
30
+ /** Stored entries back into typed ones; a malformed entry fails loudly. */
31
+ export declare function parseThreadEntries(entries: readonly JsonValue[]): ThreadEntry[];
32
+ /**
33
+ * Entries as stored, each small enough for one runner frame: a long step
34
+ * is stored message by message, and media too large for a frame (a
35
+ * screenshot a tool returned) is kept out of the stored history, said so
36
+ * in its place. The live turn still saw it.
37
+ */
38
+ export declare function storedEntries(entry: ThreadEntry): JsonValue[];
39
+ export interface FoldedThread {
40
+ messages: ModelMessage[];
41
+ /** Where the last turn's input ended in `messages`, when there was a turn. */
42
+ lastTurnInputEnd?: number;
43
+ }
44
+ /**
45
+ * Fold entries into the model history. Steps written by another model than
46
+ * `model` lose their reasoning parts (signed by the model that produced
47
+ * them, rejected by another); `sanitize` strips reasoning everywhere.
48
+ */
49
+ export declare function foldThread(input: {
50
+ entries: readonly ThreadEntry[];
51
+ model?: string;
52
+ sanitize?: boolean;
53
+ }): FoldedThread;
54
+ /**
55
+ * The entries through the end of the turn `ref` names, for a fork; undefined
56
+ * when that turn never ended in this thread.
57
+ */
58
+ export declare function entriesThroughTurn(entries: readonly ThreadEntry[], ref: string): ThreadEntry[] | undefined;
59
+ /**
60
+ * Drop reasoning parts from assistant history. Reasoning output is signed
61
+ * by the model that produced it; after a mid-conversation model switch the
62
+ * new model rejects those signatures ("encrypted reasoning" errors).
63
+ */
64
+ export declare function stripReasoning(messages: ModelMessage[]): ModelMessage[];
65
+ /**
66
+ * Any value as JSON: binary data becomes base64, URLs and dates strings,
67
+ * functions and undefined fields disappear. Model messages and tool values
68
+ * cross the runner protocol this way.
69
+ */
70
+ export declare function toJsonValue(value: unknown): JsonValue;
71
+ //# sourceMappingURL=thread.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"thread.d.ts","sourceRoot":"","sources":["../src/thread.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,KAAK,YAAY,EAAsB,MAAM,IAAI,CAAC;AAG3D;;;;;;GAMG;AACH,MAAM,MAAM,WAAW,GACnB;IACE,CAAC,EAAE,CAAC,CAAC;IACL,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB,kEAAkE;IAClE,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GACD;IACE,CAAC,EAAE,CAAC,CAAC;IACL,IAAI,EAAE,MAAM,CAAC;IACb,8EAA8E;IAC9E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,YAAY,EAAE,CAAC;CAC1B,GACD;IACE,CAAC,EAAE,CAAC,CAAC;IACL,IAAI,EAAE,UAAU,CAAC;IACjB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,WAAW,GAAG,QAAQ,GAAG,aAAa,CAAC;CAChD,CAAC;AAwBN,2EAA2E;AAC3E,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,SAAS,SAAS,EAAE,GAC5B,WAAW,EAAE,CASf;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,WAAW,GAAG,SAAS,EAAE,CAQ7D;AAyBD,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,8EAA8E;IAC9E,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE;IAChC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IAChC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,GAAG,YAAY,CAuBf;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,SAAS,WAAW,EAAE,EAC/B,GAAG,EAAE,MAAM,GACV,WAAW,EAAE,GAAG,SAAS,CAO3B;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,YAAY,EAAE,CAWvE;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,CAmBrD"}
@@ -0,0 +1,148 @@
1
+ import type { HostToolDescriptor, HostToolResult } from "@catamorphic/agent-protocol/runner";
2
+ import { type ConnectedMcpServer, type McpToolInfo } from "@catamorphic/mcp";
3
+ import { agentQuestionInputSchema, type SandboxProvider } from "@catamorphic/sandbox";
4
+ import { type Tool } from "ai";
5
+ import { z } from "zod";
6
+ import { type ShellProvider, type ShellState } from "./shell.js";
7
+ /** The sandbox surface the built-in file and shell tools run on. */
8
+ export type AiSdkSandboxProvider = ShellProvider & Pick<SandboxProvider, "uploadFiles" | "downloadFile">;
9
+ /**
10
+ * What a model tool name stands for, so its calls become the right
11
+ * transcript items: shell commands, file changes, or tool calls.
12
+ */
13
+ export type ToolMeta = {
14
+ kind: "command";
15
+ } | {
16
+ kind: "file";
17
+ change: "modified" | null;
18
+ } | {
19
+ kind: "title";
20
+ } | {
21
+ kind: "ask";
22
+ } | {
23
+ kind: "tool";
24
+ server: string | null;
25
+ source: "builtin";
26
+ } | {
27
+ kind: "tool";
28
+ server: string;
29
+ source: "host" | "mcp";
30
+ };
31
+ export interface ToolSetWithMeta {
32
+ tools: Record<string, Tool>;
33
+ meta: Map<string, ToolMeta>;
34
+ }
35
+ export interface WorkspaceToolContext {
36
+ provider: AiSdkSandboxProvider;
37
+ sandboxId: string;
38
+ workingDirectory: string;
39
+ /** Read-only directories beside the working directory. */
40
+ readableRoots: readonly string[];
41
+ /** Where the next shell command starts and this chat's background commands. */
42
+ shell: ShellState;
43
+ /** The Environment's budget for one foreground command (ADR 0174). */
44
+ budgetSeconds?: number;
45
+ /**
46
+ * The session's environment files, which every command loads (ADRs
47
+ * 0206, 0212).
48
+ */
49
+ envFiles?: readonly string[];
50
+ /** Fires when the agent should stop waiting (ADR 0264). */
51
+ stopWaiting(): AbortSignal;
52
+ }
53
+ /**
54
+ * The tools every attempt has: the conversation title, questions, and web
55
+ * access. `ask` runs one question batch and returns what the model reads.
56
+ */
57
+ export declare function conversationTools(input: {
58
+ ask: (args: {
59
+ questions: z.output<typeof agentQuestionInputSchema>["questions"];
60
+ blocking: boolean;
61
+ toolCallId: string;
62
+ abortSignal?: AbortSignal;
63
+ }) => Promise<string>;
64
+ }): ToolSetWithMeta;
65
+ /**
66
+ * The project tools on the session's sandbox: `read`, `write`, `edit`, and
67
+ * the shell (`bash`, plus background commands where the sandbox runs
68
+ * processes). Paths never escape the working directory, except reads of
69
+ * the host's read-only roots.
70
+ */
71
+ export declare function workspaceTools(context: WorkspaceToolContext): ToolSetWithMeta;
72
+ /** A project-relative or absolute path, kept inside the working directory. */
73
+ export declare function resolveProjectPath(workingDirectory: string, filePath: string): string;
74
+ /**
75
+ * The host's tools (ADR 0198 host calls): offered under their own names,
76
+ * run by the host. `call` returns MCP-shaped content; an `isError` result
77
+ * reads to the model as the tool's error.
78
+ */
79
+ export declare function hostTools(input: {
80
+ descriptors: readonly HostToolDescriptor[];
81
+ call: (args: {
82
+ name: string;
83
+ input: unknown;
84
+ toolCallId: string;
85
+ abortSignal?: AbortSignal;
86
+ }) => Promise<HostToolResult>;
87
+ }): ToolSetWithMeta;
88
+ declare const hostToolResultSchema: z.ZodObject<{
89
+ content: z.ZodArray<z.ZodDiscriminatedUnion<[z.ZodObject<{
90
+ type: z.ZodLiteral<"text">;
91
+ text: z.ZodString;
92
+ }, z.core.$strip>, z.ZodObject<{
93
+ type: z.ZodLiteral<"image">;
94
+ data: z.ZodString;
95
+ mimeType: z.ZodString;
96
+ }, z.core.$strip>], "type">>;
97
+ structured: z.ZodOptional<z.ZodUnknown>;
98
+ isError: z.ZodOptional<z.ZodBoolean>;
99
+ }, z.core.$strip>;
100
+ /** A host tool's output, when it is one. */
101
+ export declare function parseHostToolResult(output: unknown): z.output<typeof hostToolResultSchema> | undefined;
102
+ /**
103
+ * The name the model calls an MCP tool by: `mcp__<server>__<tool>`, with
104
+ * what model APIs refuse (MCP allows dots, `chat.postMessage`) as `_`. A
105
+ * name that is too long, or already names another tool (`a.b` beside
106
+ * `a_b`), ends in a short hash of the server and tool instead.
107
+ */
108
+ export declare function mcpModelToolName(args: {
109
+ server: string;
110
+ tool: string;
111
+ taken: Readonly<Record<string, unknown>>;
112
+ }): string;
113
+ /**
114
+ * MCP server tools as AI SDK dynamic tools named `mcp__<server>__<tool>`
115
+ * (the namespacing Claude Code uses, so transcripts read alike across
116
+ * harnesses). `authorize` runs before every call and throws to refuse it;
117
+ * the model reads the refusal as the tool's error and the turn goes on.
118
+ */
119
+ export declare function mcpTools(input: {
120
+ servers: ReadonlyMap<string, ConnectedMcpServer>;
121
+ taken: Readonly<Record<string, unknown>>;
122
+ authorize: (args: {
123
+ server: string;
124
+ tool: McpToolInfo;
125
+ input: Record<string, unknown>;
126
+ toolCallId: string;
127
+ abortSignal?: AbortSignal;
128
+ }) => Promise<void>;
129
+ }): ToolSetWithMeta;
130
+ /**
131
+ * Some models (OpenAI-family especially) fill every declared property and
132
+ * send `""`/`null` for the ones they have no value for; servers that
133
+ * validate optional fields then reject the call ("value is not a channel
134
+ * ID" for `context_channel_id: ""`, from Slack's search tool). Drop such
135
+ * values for optional properties, but ONLY when the property's own schema
136
+ * could not have meant them: a `null` a schema admits (`type: [...,
137
+ * "null"]`, `nullable`, an `anyOf` null branch, an `enum` with null) is a
138
+ * value ("clear this field"), and so is `""` on a plain string with no
139
+ * `format`/`pattern`/`minLength`/`enum` ruling it out. Unknown properties
140
+ * (no schema) keep the blanket rule.
141
+ */
142
+ export declare function pruneEmptyOptionalArgs(input: Record<string, unknown>, schema: Record<string, unknown>): Record<string, unknown>;
143
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
144
+ export declare function truncateToolOutput(output: string): string;
145
+ /** Keep media in what the model reads; keep image bytes out of the transcript. */
146
+ export declare function transcriptToolResult(output: unknown): unknown;
147
+ export {};
148
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,kBAAkB,EAClB,cAAc,EACf,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EACL,KAAK,kBAAkB,EAEvB,KAAK,WAAW,EACjB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,wBAAwB,EAGxB,KAAK,eAAe,EACrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAA2B,KAAK,IAAI,EAAQ,MAAM,IAAI,CAAC;AAC9D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,UAAU,EAAc,MAAM,YAAY,CAAC;AAO7E,oEAAoE;AACpE,MAAM,MAAM,oBAAoB,GAAG,aAAa,GAC9C,IAAI,CAAC,eAAe,EAAE,aAAa,GAAG,cAAc,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAChB;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GACnB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,UAAU,GAAG,IAAI,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GACjB;IAAE,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