@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.
@@ -0,0 +1,295 @@
1
+ import {
2
+ emitLog,
3
+ getMeter,
4
+ getTracer,
5
+ SeverityNumber,
6
+ } from "@catamorphic/otel";
7
+ import {
8
+ type Attributes,
9
+ context,
10
+ type Span,
11
+ SpanKind,
12
+ SpanStatusCode,
13
+ trace,
14
+ } from "@opentelemetry/api";
15
+ import type { LanguageModel, Telemetry } from "ai";
16
+
17
+ const scope = "@catamorphic/ai-sdk";
18
+ const durationBuckets = [
19
+ 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48,
20
+ 40.96, 81.92,
21
+ ];
22
+
23
+ /** GenAI development conventions, reviewed 2026-09-10. No content capture. */
24
+ export function agentTelemetry(args: {
25
+ model: LanguageModel;
26
+ sessionId: string;
27
+ projectId?: string;
28
+ turnId?: string;
29
+ userId?: string;
30
+ }) {
31
+ const tracer = getTracer(scope);
32
+ const model =
33
+ typeof args.model === "string" ? args.model : args.model.modelId;
34
+ const provider =
35
+ typeof args.model === "string"
36
+ ? undefined
37
+ : args.model.provider.split(".")[0];
38
+ const agentAttributes: Attributes = {
39
+ "gen_ai.operation.name": "invoke_agent",
40
+ "gen_ai.agent.name": "ai-sdk",
41
+ "gen_ai.request.model": model,
42
+ ...(provider ? { "gen_ai.provider.name": provider } : {}),
43
+ };
44
+ const root = tracer.startSpan("invoke_agent ai-sdk", {
45
+ attributes: {
46
+ ...agentAttributes,
47
+ ...(args.userId ? { "user.id": args.userId } : {}),
48
+ "gen_ai.conversation.id": args.sessionId,
49
+ "catamorphic.agent.session.id": args.sessionId,
50
+ ...(args.projectId ? { "catamorphic.project.id": args.projectId } : {}),
51
+ ...(args.turnId ? { "catamorphic.agent.turn.id": args.turnId } : {}),
52
+ },
53
+ });
54
+ const rootContext = trace.setSpan(context.active(), root);
55
+ const meter = context.with(rootContext, () => getMeter(scope));
56
+ const histogram = (name: string, unit = "s", boundaries = durationBuckets) =>
57
+ meter.createHistogram(name, {
58
+ unit,
59
+ advice: { explicitBucketBoundaries: boundaries },
60
+ });
61
+ const durations = histogram("gen_ai.client.operation.duration");
62
+ const tokens = histogram(
63
+ "gen_ai.client.token.usage",
64
+ "{token}",
65
+ [
66
+ 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,
67
+ 16777216, 67108864,
68
+ ],
69
+ );
70
+ const firstChunk = histogram("gen_ai.client.operation.time_to_first_chunk");
71
+ const toolDurations = histogram("gen_ai.execute_tool.duration");
72
+ const invocationDuration = histogram("gen_ai.invoke_agent.duration");
73
+ const began = performance.now();
74
+ type Pending = { span: Span; started: number; attributes: Attributes };
75
+ const calls = new Map<string, Pending>();
76
+ const tools = new Map<string, Pending>();
77
+ let failure: string | undefined;
78
+ let ended = false;
79
+ let modelCalls = 0;
80
+ let toolCalls = 0;
81
+
82
+ const fail = (span: Span, error: unknown) => {
83
+ const type = error instanceof Error ? error.name : "_OTHER";
84
+ // Provider exceptions can embed prompts, API keys, or request bodies.
85
+ span.setAttribute("error.type", type);
86
+ span.setStatus({ code: SpanStatusCode.ERROR });
87
+ return type;
88
+ };
89
+ const finishPending = (
90
+ pending: Pending,
91
+ metric: ReturnType<typeof histogram>,
92
+ error?: string,
93
+ ) => {
94
+ if (error) {
95
+ pending.span.setAttribute("error.type", error);
96
+ pending.span.setStatus({ code: SpanStatusCode.ERROR });
97
+ }
98
+ context.with(trace.setSpan(rootContext, pending.span), () =>
99
+ metric.record((performance.now() - pending.started) / 1000, {
100
+ ...pending.attributes,
101
+ ...(error ? { "error.type": error } : {}),
102
+ }),
103
+ );
104
+ pending.span.end();
105
+ };
106
+ const integration: Telemetry = {
107
+ onLanguageModelCallStart(event) {
108
+ const attributes: Attributes = {
109
+ "gen_ai.operation.name": "chat",
110
+ "gen_ai.provider.name": event.provider.split(".")[0] ?? event.provider,
111
+ "gen_ai.request.model": event.modelId,
112
+ };
113
+ modelCalls += 1;
114
+ calls.set(event.callId, {
115
+ span: tracer.startSpan(
116
+ `chat ${event.modelId}`,
117
+ { kind: SpanKind.CLIENT, attributes },
118
+ rootContext,
119
+ ),
120
+ started: performance.now(),
121
+ attributes,
122
+ });
123
+ },
124
+ async executeLanguageModelCall({ callId, execute }) {
125
+ const pending = calls.get(callId);
126
+ try {
127
+ return await context.with(
128
+ pending ? trace.setSpan(rootContext, pending.span) : rootContext,
129
+ execute,
130
+ );
131
+ } catch (error) {
132
+ if (pending && calls.delete(callId)) {
133
+ finishPending(
134
+ pending,
135
+ durations,
136
+ error instanceof Error && error.name === "AbortError"
137
+ ? undefined
138
+ : fail(pending.span, error),
139
+ );
140
+ }
141
+ throw error;
142
+ }
143
+ },
144
+ onLanguageModelCallEnd(event) {
145
+ const pending = calls.get(event.callId);
146
+ if (!pending) return;
147
+ calls.delete(event.callId);
148
+ pending.span.setAttributes({
149
+ "gen_ai.response.id": event.responseId,
150
+ "gen_ai.response.finish_reasons": [event.finishReason],
151
+ });
152
+ context.with(trace.setSpan(rootContext, pending.span), () => {
153
+ for (const [kind, count] of [
154
+ ["input", event.usage.inputTokens],
155
+ ["output", event.usage.outputTokens],
156
+ ] as const) {
157
+ if (typeof count !== "number" || !Number.isFinite(count) || count < 0)
158
+ continue;
159
+ pending.span.setAttribute(`gen_ai.usage.${kind}_tokens`, count);
160
+ tokens.record(count, {
161
+ ...pending.attributes,
162
+ "gen_ai.token.type": kind,
163
+ });
164
+ }
165
+ for (const [attribute, count] of [
166
+ [
167
+ "gen_ai.usage.cache_read.input_tokens",
168
+ event.usage.inputTokenDetails.cacheReadTokens,
169
+ ],
170
+ [
171
+ "gen_ai.usage.cache_write.input_tokens",
172
+ event.usage.inputTokenDetails.cacheWriteTokens,
173
+ ],
174
+ [
175
+ "gen_ai.usage.reasoning.output_tokens",
176
+ event.usage.outputTokenDetails.reasoningTokens,
177
+ ],
178
+ ] as const) {
179
+ if (typeof count === "number" && Number.isFinite(count) && count >= 0)
180
+ pending.span.setAttribute(attribute, count);
181
+ }
182
+ const first = event.performance.timeToFirstOutputMs;
183
+ if (first !== undefined && Number.isFinite(first) && first >= 0)
184
+ firstChunk.record(first / 1000, pending.attributes);
185
+ });
186
+ finishPending(pending, durations);
187
+ },
188
+ onToolExecutionStart(event) {
189
+ toolCalls += 1;
190
+ const attributes = {
191
+ "gen_ai.tool.name": event.toolCall.toolName,
192
+ "gen_ai.tool.type": "function",
193
+ "gen_ai.agent.name": "ai-sdk",
194
+ };
195
+ tools.set(event.toolCall.toolCallId, {
196
+ span: tracer.startSpan(
197
+ `execute_tool ${event.toolCall.toolName}`,
198
+ {
199
+ attributes: {
200
+ ...attributes,
201
+ "gen_ai.operation.name": "execute_tool",
202
+ "gen_ai.tool.call.id": event.toolCall.toolCallId,
203
+ },
204
+ },
205
+ rootContext,
206
+ ),
207
+ started: performance.now(),
208
+ attributes,
209
+ });
210
+ },
211
+ executeTool({ toolCallId, execute }) {
212
+ const span = tools.get(toolCallId)?.span;
213
+ return context.with(
214
+ span ? trace.setSpan(rootContext, span) : rootContext,
215
+ execute,
216
+ );
217
+ },
218
+ onToolExecutionEnd(event) {
219
+ const pending = tools.get(event.toolCall.toolCallId);
220
+ if (!pending) return;
221
+ tools.delete(event.toolCall.toolCallId);
222
+ const error =
223
+ event.toolOutput.type === "tool-error"
224
+ ? fail(pending.span, event.toolOutput.error)
225
+ : undefined;
226
+ finishPending(pending, toolDurations, error);
227
+ },
228
+ };
229
+ return {
230
+ settings: {
231
+ isEnabled: true,
232
+ recordInputs: false,
233
+ recordOutputs: false,
234
+ integrations: integration,
235
+ },
236
+ run<T>(fn: () => T): T {
237
+ return context.with(rootContext, fn);
238
+ },
239
+ fail(error: unknown) {
240
+ failure = fail(root, error);
241
+ },
242
+ finish({ cancelled = false }: { cancelled?: boolean } = {}) {
243
+ if (ended) return;
244
+ ended = true;
245
+ root.setAttribute(
246
+ "catamorphic.agent.outcome",
247
+ cancelled ? "cancelled" : failure ? "error" : "completed",
248
+ );
249
+ for (const pending of calls.values())
250
+ finishPending(
251
+ pending,
252
+ durations,
253
+ failure ?? (cancelled ? undefined : "_OTHER"),
254
+ );
255
+ for (const pending of tools.values())
256
+ finishPending(
257
+ pending,
258
+ toolDurations,
259
+ failure ?? (cancelled ? undefined : "_OTHER"),
260
+ );
261
+ calls.clear();
262
+ tools.clear();
263
+ context.with(rootContext, () => {
264
+ emitLog({
265
+ scope,
266
+ body: "Agent turn settled",
267
+ severity: failure ? SeverityNumber.ERROR : SeverityNumber.INFO,
268
+ attributes: {
269
+ "catamorphic.agent.outcome": cancelled
270
+ ? "cancelled"
271
+ : failure
272
+ ? "error"
273
+ : "completed",
274
+ ...(failure ? { "error.type": failure } : {}),
275
+ },
276
+ });
277
+ invocationDuration.record((performance.now() - began) / 1000, {
278
+ ...agentAttributes,
279
+ ...(failure ? { "error.type": failure } : {}),
280
+ });
281
+ histogram(
282
+ "gen_ai.invoke_agent.model_calls",
283
+ "{call}",
284
+ [1, 2, 4, 8, 16, 32, 64, 128],
285
+ ).record(modelCalls, { "gen_ai.agent.name": "ai-sdk" });
286
+ histogram(
287
+ "gen_ai.invoke_agent.tool_calls",
288
+ "{call}",
289
+ [1, 2, 4, 8, 16, 32, 64, 128],
290
+ ).record(toolCalls, { "gen_ai.agent.name": "ai-sdk" });
291
+ });
292
+ root.end();
293
+ },
294
+ };
295
+ }
@@ -0,0 +1,349 @@
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 { APICallError, wrapLanguageModel } from "ai";
13
+ import { MockLanguageModelV4 } from "ai/test";
14
+
15
+ type StreamResult = Awaited<ReturnType<MockLanguageModelV4["doStream"]>>;
16
+ type CallOptions = Parameters<MockLanguageModelV4["doStream"]>[0];
17
+
18
+ /** One part of a provider's stream, exactly as the model transport yields it. */
19
+ export type ModelStreamPart =
20
+ StreamResult["stream"] extends ReadableStream<infer Part> ? Part : never;
21
+
22
+ /** What the model received for one call: the prompt, tools and settings. */
23
+ export type ModelCallOptions = CallOptions;
24
+
25
+ export type ModelCall =
26
+ | {
27
+ /** The parts the provider streamed for this call. */
28
+ parts: ModelStreamPart[];
29
+ /**
30
+ * Keep the stream open after the parts until the call is aborted, as
31
+ * a provider does while the model is still writing.
32
+ */
33
+ hang?: boolean;
34
+ }
35
+ | {
36
+ /** The provider refused the request before streaming anything. */
37
+ reject: {
38
+ message: string;
39
+ statusCode?: number;
40
+ responseBody?: string;
41
+ isRetryable?: boolean;
42
+ };
43
+ };
44
+
45
+ export interface ModelTranscript {
46
+ /** The model id the replay reports; `replay-model` by default. */
47
+ modelId?: string;
48
+ provider?: string;
49
+ calls: ModelCall[];
50
+ }
51
+
52
+ export interface ReplayModel {
53
+ /** The model to hand the adapter. */
54
+ model: MockLanguageModelV4;
55
+ /** What each call received, in order. */
56
+ readonly calls: ModelCallOptions[];
57
+ /** Calls the transcript holds that nobody made yet. */
58
+ remaining(): number;
59
+ }
60
+
61
+ /**
62
+ * A model that plays a transcript back. A call past its end fails the
63
+ * test with a clear message instead of hanging. `beforeCall` runs before
64
+ * a call streams: a test can hold the model there (to steer, to
65
+ * interrupt) or inspect its prompt.
66
+ */
67
+ export function replayModel(
68
+ transcript: ModelTranscript,
69
+ hooks?: {
70
+ beforeCall?: (input: {
71
+ index: number;
72
+ options: ModelCallOptions;
73
+ }) => void | Promise<void>;
74
+ },
75
+ ): ReplayModel {
76
+ let next = 0;
77
+ const calls: ModelCallOptions[] = [];
78
+ const model = new MockLanguageModelV4({
79
+ provider: transcript.provider ?? "replay",
80
+ modelId: transcript.modelId ?? "replay-model",
81
+ doStream: async (options) => {
82
+ const index = next;
83
+ next += 1;
84
+ calls.push(options);
85
+ await hooks?.beforeCall?.({ index, options });
86
+ const call = transcript.calls[index];
87
+ if (!call)
88
+ throw new Error(
89
+ `The model was called ${index + 1} times; the transcript holds ${transcript.calls.length} calls.`,
90
+ );
91
+ if ("reject" in call)
92
+ throw new APICallError({
93
+ message: call.reject.message,
94
+ url: "https://replay.invalid/v1/messages",
95
+ requestBodyValues: {},
96
+ ...(call.reject.statusCode !== undefined
97
+ ? { statusCode: call.reject.statusCode }
98
+ : {}),
99
+ ...(call.reject.responseBody !== undefined
100
+ ? { responseBody: call.reject.responseBody }
101
+ : {}),
102
+ ...(call.reject.isRetryable !== undefined
103
+ ? { isRetryable: call.reject.isRetryable }
104
+ : {}),
105
+ });
106
+ return { stream: partStream(call.parts, call.hang, options.abortSignal) };
107
+ },
108
+ });
109
+ return {
110
+ model,
111
+ calls,
112
+ remaining: () => Math.max(0, transcript.calls.length - next),
113
+ };
114
+ }
115
+
116
+ function partStream(
117
+ parts: readonly ModelStreamPart[],
118
+ hang: boolean | undefined,
119
+ signal: AbortSignal | undefined,
120
+ ): ReadableStream<ModelStreamPart> {
121
+ let index = 0;
122
+ return new ReadableStream<ModelStreamPart>({
123
+ async pull(controller) {
124
+ const part = parts[index];
125
+ index += 1;
126
+ if (part) {
127
+ // A tick between parts, as a network stream has.
128
+ await new Promise((resolve) => setTimeout(resolve, 0));
129
+ controller.enqueue(structuredClone(part));
130
+ return;
131
+ }
132
+ if (!hang) {
133
+ controller.close();
134
+ return;
135
+ }
136
+ await new Promise<void>((resolve) => {
137
+ if (signal?.aborted) resolve();
138
+ else signal?.addEventListener("abort", () => resolve(), { once: true });
139
+ });
140
+ controller.error(signal?.reason ?? new Error("aborted"));
141
+ },
142
+ });
143
+ }
144
+
145
+ /**
146
+ * Wrap a live model so every call's streamed parts are kept: run a scenario
147
+ * against a real provider once, then save `transcript()` as the test's
148
+ * fixture.
149
+ */
150
+ export function recordModel(
151
+ model: Parameters<typeof wrapLanguageModel>[0]["model"],
152
+ ): {
153
+ model: ReturnType<typeof wrapLanguageModel>;
154
+ transcript(): ModelTranscript;
155
+ } {
156
+ const calls: ModelCall[] = [];
157
+ const wrapped = wrapLanguageModel({
158
+ model,
159
+ middleware: {
160
+ wrapStream: async ({ doStream }) => {
161
+ const result = await doStream();
162
+ const parts: ModelStreamPart[] = [];
163
+ calls.push({ parts });
164
+ return {
165
+ ...result,
166
+ stream: result.stream.pipeThrough(
167
+ new TransformStream<ModelStreamPart, ModelStreamPart>({
168
+ transform(part, controller) {
169
+ parts.push(structuredClone(part));
170
+ controller.enqueue(part);
171
+ },
172
+ }),
173
+ ),
174
+ };
175
+ },
176
+ },
177
+ });
178
+ return {
179
+ model: wrapped,
180
+ transcript: () => ({
181
+ modelId: wrapped.modelId,
182
+ provider: wrapped.provider,
183
+ calls: structuredClone(calls),
184
+ }),
185
+ };
186
+ }
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // Builders for hand-written transcripts
190
+
191
+ export interface StepUsage {
192
+ input?: number;
193
+ output?: number;
194
+ cacheRead?: number;
195
+ cacheWrite?: number;
196
+ reasoning?: number;
197
+ }
198
+
199
+ const DEFAULT_USAGE: Required<StepUsage> = {
200
+ input: 10,
201
+ output: 5,
202
+ cacheRead: 0,
203
+ cacheWrite: 0,
204
+ reasoning: 0,
205
+ };
206
+
207
+ /** The `finish` part a provider ends a call with. */
208
+ export function finishPart(input: {
209
+ reason: "stop" | "tool-calls" | "length" | "error" | "other";
210
+ usage?: StepUsage;
211
+ }): ModelStreamPart {
212
+ const usage = { ...DEFAULT_USAGE, ...input.usage };
213
+ return {
214
+ type: "finish",
215
+ finishReason: { unified: input.reason, raw: undefined },
216
+ usage: {
217
+ inputTokens: {
218
+ total: usage.input,
219
+ noCache: usage.input - usage.cacheRead - usage.cacheWrite,
220
+ cacheRead: usage.cacheRead,
221
+ cacheWrite: usage.cacheWrite,
222
+ },
223
+ outputTokens: {
224
+ total: usage.output,
225
+ text: usage.output - usage.reasoning,
226
+ reasoning: usage.reasoning,
227
+ },
228
+ },
229
+ };
230
+ }
231
+
232
+ /** A text block, streamed in `chunks` deltas. */
233
+ export function textParts(
234
+ text: string,
235
+ options?: { id?: string; chunks?: number },
236
+ ): ModelStreamPart[] {
237
+ const id = options?.id ?? "text-0";
238
+ return [
239
+ { type: "text-start", id },
240
+ ...split(text, options?.chunks ?? 2).map(
241
+ (delta): ModelStreamPart => ({ type: "text-delta", id, delta }),
242
+ ),
243
+ { type: "text-end", id },
244
+ ];
245
+ }
246
+
247
+ /** A reasoning block (a summary opening with a bold heading becomes status). */
248
+ export function reasoningParts(
249
+ text: string,
250
+ options?: { id?: string },
251
+ ): ModelStreamPart[] {
252
+ const id = options?.id ?? "reasoning-0";
253
+ return [
254
+ { type: "reasoning-start", id },
255
+ { type: "reasoning-delta", id, delta: text },
256
+ { type: "reasoning-end", id },
257
+ ];
258
+ }
259
+
260
+ /** One tool call, its input as the model wrote it. */
261
+ export function toolCallPart(input: {
262
+ id: string;
263
+ name: string;
264
+ input: unknown;
265
+ }): ModelStreamPart {
266
+ return {
267
+ type: "tool-call",
268
+ toolCallId: input.id,
269
+ toolName: input.name,
270
+ input: JSON.stringify(input.input),
271
+ };
272
+ }
273
+
274
+ /** A call that answers in text and stops. */
275
+ export function replyCall(
276
+ text: string,
277
+ options?: { reasoning?: string; usage?: StepUsage; hang?: boolean },
278
+ ): ModelCall {
279
+ return {
280
+ parts: [
281
+ { type: "stream-start", warnings: [] },
282
+ ...(options?.reasoning ? reasoningParts(options.reasoning) : []),
283
+ ...textParts(text),
284
+ ...(options?.hang
285
+ ? []
286
+ : [finishPart({ reason: "stop", ...usageOf(options) })]),
287
+ ],
288
+ ...(options?.hang ? { hang: true } : {}),
289
+ };
290
+ }
291
+
292
+ /** A call that (optionally says something and) calls tools. */
293
+ export function toolCallsCall(
294
+ calls: Array<{ id: string; name: string; input: unknown }>,
295
+ options?: { text?: string; usage?: StepUsage },
296
+ ): ModelCall {
297
+ return {
298
+ parts: [
299
+ { type: "stream-start", warnings: [] },
300
+ ...(options?.text ? textParts(options.text) : []),
301
+ ...calls.map(toolCallPart),
302
+ finishPart({ reason: "tool-calls", ...usageOf(options) }),
303
+ ],
304
+ };
305
+ }
306
+
307
+ /** A call the provider refuses (a 429, a 401, a 400 about reasoning). */
308
+ export function rejectedCall(
309
+ reject: Extract<ModelCall, { reject: unknown }>["reject"],
310
+ ): ModelCall {
311
+ return { reject };
312
+ }
313
+
314
+ /** A call whose stream fails after it started. */
315
+ export function streamErrorCall(message: string): ModelCall {
316
+ return {
317
+ parts: [
318
+ { type: "stream-start", warnings: [] },
319
+ { type: "error", error: { message } },
320
+ ],
321
+ };
322
+ }
323
+
324
+ /** A call that starts writing and never finishes until it is aborted. */
325
+ export function hangingCall(text = ""): ModelCall {
326
+ return {
327
+ parts: [
328
+ { type: "stream-start", warnings: [] },
329
+ ...(text ? [{ type: "text-start" as const, id: "text-0" }] : []),
330
+ ...(text
331
+ ? [{ type: "text-delta" as const, id: "text-0", delta: text }]
332
+ : []),
333
+ ],
334
+ hang: true,
335
+ };
336
+ }
337
+
338
+ function usageOf(options?: { usage?: StepUsage }): { usage?: StepUsage } {
339
+ return options?.usage ? { usage: options.usage } : {};
340
+ }
341
+
342
+ function split(text: string, chunks: number): string[] {
343
+ if (chunks <= 1 || text.length < chunks) return [text];
344
+ const size = Math.ceil(text.length / chunks);
345
+ const parts: string[] = [];
346
+ for (let start = 0; start < text.length; start += size)
347
+ parts.push(text.slice(start, start + size));
348
+ return parts;
349
+ }