fascicle 0.10.1 → 0.10.3

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,451 @@
1
+ import { A as aborted_error } from "./core-DkuJqLwd.js";
2
+ import { n as load_optional_peer, t as default_normalize_usage } from "./types-kO1JoGNZ.js";
3
+ import { NoObjectGeneratedError, Output, generateText, isStepCount, streamText, tool } from "ai";
4
+ //#region src/engine/providers/ai_sdk/telemetry.ts
5
+ /**
6
+ * Build the AI SDK's `experimental_telemetry` option from engine settings,
7
+ * loading the `@ai-sdk/otel` peer only when telemetry is enabled.
8
+ */
9
+ async function build_ai_sdk_telemetry(settings) {
10
+ if (!settings?.enabled) return void 0;
11
+ const out = {
12
+ isEnabled: true,
13
+ integrations: [new (await (load_optional_peer("@ai-sdk/otel"))).OpenTelemetry(settings.tracer !== void 0 ? { tracer: settings.tracer } : {})]
14
+ };
15
+ if (settings.function_id !== void 0) out.functionId = settings.function_id;
16
+ if (settings.record_inputs !== void 0) out.recordInputs = settings.record_inputs;
17
+ if (settings.record_outputs !== void 0) out.recordOutputs = settings.record_outputs;
18
+ if (settings.metadata !== void 0) out.metadata = settings.metadata;
19
+ return out;
20
+ }
21
+ //#endregion
22
+ //#region src/engine/providers/ai_sdk/invoke.ts
23
+ /**
24
+ * The ai_sdk transport: the engine's only Vercel AI SDK call site.
25
+ *
26
+ * Only this module imports from `ai` or invokes generateText / streamText.
27
+ * generate.ts drives this transport through create_ai_sdk_turn and stays
28
+ * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native
29
+ * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.
30
+ *
31
+ * Retry stays out of this module on purpose: generate.ts wraps the turn
32
+ * returned here in the engine-owned retry_turn, exactly as it wraps a native
33
+ * adapter's invoke_turn. This module owns request/response mapping only.
34
+ */
35
+ /**
36
+ * Map the AI SDK's finish reason string to the engine's FinishReason.
37
+ */
38
+ function map_finish_reason(raw) {
39
+ switch (raw) {
40
+ case "stop": return "stop";
41
+ case "length": return "length";
42
+ case "content-filter":
43
+ case "content_filter": return "content_filter";
44
+ case "tool-calls":
45
+ case "tool_calls": return "tool_calls";
46
+ default: return "stop";
47
+ }
48
+ }
49
+ /**
50
+ * Extract the usage fields `default_normalize_usage` understands from an AI
51
+ * SDK usage object, tolerating both the SDK's camelCase shape and the
52
+ * flattened snake_case fields some provider mocks return directly.
53
+ */
54
+ function to_raw_provider_usage(usage) {
55
+ if (usage === null || typeof usage !== "object") return {};
56
+ const raw = {};
57
+ const input_tokens = Reflect.get(usage, "inputTokens");
58
+ if (typeof input_tokens === "number") raw.input_tokens = input_tokens;
59
+ const output_tokens = Reflect.get(usage, "outputTokens");
60
+ if (typeof output_tokens === "number") raw.output_tokens = output_tokens;
61
+ const input_details = Reflect.get(usage, "inputTokenDetails");
62
+ if (input_details !== null && typeof input_details === "object") {
63
+ const cache_read = Reflect.get(input_details, "cacheReadTokens");
64
+ const cache_write = Reflect.get(input_details, "cacheWriteTokens");
65
+ raw.input_token_details = {};
66
+ if (typeof cache_read === "number") raw.input_token_details.cached_tokens = cache_read;
67
+ if (typeof cache_write === "number") raw.input_token_details.cache_creation_input_tokens = cache_write;
68
+ }
69
+ const output_details = Reflect.get(usage, "outputTokenDetails");
70
+ if (output_details !== null && typeof output_details === "object") {
71
+ const reasoning = Reflect.get(output_details, "reasoningTokens");
72
+ raw.output_token_details = {};
73
+ if (typeof reasoning === "number") raw.output_token_details.reasoning_tokens = reasoning;
74
+ }
75
+ const cached_flat = Reflect.get(usage, "cached_input_tokens");
76
+ if (typeof cached_flat === "number") raw.cached_input_tokens = cached_flat;
77
+ const cache_write_flat = Reflect.get(usage, "cache_write_tokens");
78
+ if (typeof cache_write_flat === "number") raw.cache_write_tokens = cache_write_flat;
79
+ const reasoning_flat = Reflect.get(usage, "reasoning_tokens");
80
+ if (typeof reasoning_flat === "number") raw.reasoning_tokens = reasoning_flat;
81
+ const input_flat = Reflect.get(usage, "input_tokens");
82
+ if (raw.input_tokens === void 0 && typeof input_flat === "number") raw.input_tokens = input_flat;
83
+ const output_flat = Reflect.get(usage, "output_tokens");
84
+ if (raw.output_tokens === void 0 && typeof output_flat === "number") raw.output_tokens = output_flat;
85
+ return raw;
86
+ }
87
+ /**
88
+ * Normalize an AI SDK `providerMetadata` value into the neutral
89
+ * TurnResult.provider_reported shape.
90
+ *
91
+ * The SDK's metadata is already keyed by provider name, which is the shape
92
+ * provider_reported documents, so the keys ride through untranslated and every
93
+ * ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,
94
+ * anthropic's cache detail, openai's own fields. The payloads stay opaque
95
+ * (callers narrow them at the use site), so this copies the top level and
96
+ * inspects nothing below it. An absent or empty map returns undefined, keeping
97
+ * "the provider reported nothing" spelled one way.
98
+ */
99
+ function to_provider_reported(metadata) {
100
+ if (metadata === null || typeof metadata !== "object") return void 0;
101
+ const keys = Object.keys(metadata);
102
+ if (keys.length === 0) return void 0;
103
+ const reported = {};
104
+ for (const key of keys) reported[key] = Reflect.get(metadata, key);
105
+ return reported;
106
+ }
107
+ /**
108
+ * Map fascicle's Message[] to the AI SDK's ModelMessage[] shape.
109
+ */
110
+ function to_sdk_messages(messages) {
111
+ const out = [];
112
+ for (const m of messages) {
113
+ if (m.role === "system") {
114
+ out.push({
115
+ role: "system",
116
+ content: m.content
117
+ });
118
+ continue;
119
+ }
120
+ if (m.role === "user") {
121
+ if (typeof m.content === "string") out.push({
122
+ role: "user",
123
+ content: m.content
124
+ });
125
+ else {
126
+ const parts = m.content.map((p) => {
127
+ if (p.type === "text") return {
128
+ type: "text",
129
+ text: p.text
130
+ };
131
+ const image_part = {
132
+ type: "image",
133
+ image: p.image
134
+ };
135
+ if (p.media_type !== void 0) image_part.mediaType = p.media_type;
136
+ return image_part;
137
+ });
138
+ out.push({
139
+ role: "user",
140
+ content: parts
141
+ });
142
+ }
143
+ continue;
144
+ }
145
+ if (m.role === "tool") {
146
+ out.push({
147
+ role: "tool",
148
+ content: [{
149
+ type: "tool-result",
150
+ toolCallId: m.tool_call_id,
151
+ toolName: m.name,
152
+ output: {
153
+ type: "text",
154
+ value: m.content
155
+ }
156
+ }]
157
+ });
158
+ continue;
159
+ }
160
+ if (typeof m.content === "string") {
161
+ out.push({
162
+ role: "assistant",
163
+ content: m.content
164
+ });
165
+ continue;
166
+ }
167
+ const parts = m.content.map((p) => {
168
+ if (p.type === "text") return {
169
+ type: "text",
170
+ text: p.text
171
+ };
172
+ return {
173
+ type: "tool-call",
174
+ toolCallId: p.id,
175
+ toolName: p.name,
176
+ input: p.input
177
+ };
178
+ });
179
+ out.push({
180
+ role: "assistant",
181
+ content: parts
182
+ });
183
+ }
184
+ return out;
185
+ }
186
+ /**
187
+ * Hoist a leading run of system messages out of the SDK message list into the
188
+ * AI SDK's top-level `system` option.
189
+ *
190
+ * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it
191
+ * as potentially attacker-controlled: it warns on every call (and newer `ai`
192
+ * versions throw unless `allowSystemInMessages` is set). fascicle's system
193
+ * content is the developer's own prompt, and the SDK's own recommendation is to
194
+ * deliver it through the top-level `instructions` option (v7's rename of the
195
+ * former `system` option), which removes the warning at its source rather than
196
+ * suppressing it.
197
+ *
198
+ * Only the *leading* run is hoisted (fascicle's only shape: one or more system
199
+ * messages, then the conversation). A system message that appears after a
200
+ * non-system message keeps its position rather than being silently reordered to
201
+ * the top, and the original list is returned untouched when hoisting would leave
202
+ * `messages` empty, since the SDK rejects an empty messages array.
203
+ */
204
+ function split_leading_system(messages) {
205
+ let run_end = 0;
206
+ const system_parts = [];
207
+ while (run_end < messages.length) {
208
+ const m = messages[run_end];
209
+ if (m?.role !== "system") break;
210
+ system_parts.push(m.content);
211
+ run_end += 1;
212
+ }
213
+ const rest = messages.slice(run_end);
214
+ if (system_parts.length === 0 || rest.length === 0) return { messages: [...messages] };
215
+ return {
216
+ system: system_parts.join("\n\n"),
217
+ messages: rest
218
+ };
219
+ }
220
+ /**
221
+ * Map fascicle's Tool[] to the AI SDK's ToolSet.
222
+ *
223
+ * Returns undefined for an empty tool list so the caller can omit `tools`
224
+ * from the call params entirely instead of passing an empty object.
225
+ */
226
+ function to_sdk_tools(tools) {
227
+ if (tools.length === 0) return void 0;
228
+ const entries = {};
229
+ for (const t of tools) entries[t.name] = tool({
230
+ description: t.description,
231
+ inputSchema: t.input_schema
232
+ });
233
+ return entries;
234
+ }
235
+ /**
236
+ * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined
237
+ * for a part kind the engine does not model.
238
+ */
239
+ function map_stream_part_to_chunk(part, step_index) {
240
+ switch (part.type) {
241
+ case "text-delta": return {
242
+ kind: "text",
243
+ text: part.text,
244
+ step_index
245
+ };
246
+ case "reasoning-delta": return {
247
+ kind: "reasoning",
248
+ text: part.text,
249
+ step_index
250
+ };
251
+ case "tool-input-start": return {
252
+ kind: "tool_call_start",
253
+ id: part.id,
254
+ name: part.toolName,
255
+ step_index
256
+ };
257
+ case "tool-input-delta": return {
258
+ kind: "tool_call_input_delta",
259
+ id: part.id,
260
+ delta: part.delta,
261
+ step_index
262
+ };
263
+ case "tool-call": return {
264
+ kind: "tool_call_end",
265
+ id: part.toolCallId,
266
+ input: part.input,
267
+ step_index
268
+ };
269
+ case "finish-step": return {
270
+ kind: "step_finish",
271
+ step_index,
272
+ finish_reason: map_finish_reason(part.finishReason),
273
+ usage: default_usage_from_sdk(part.usage)
274
+ };
275
+ default: return;
276
+ }
277
+ }
278
+ /**
279
+ * Normalize a raw AI SDK usage object into UsageTotals for a streamed
280
+ * step_finish chunk.
281
+ */
282
+ function default_usage_from_sdk(usage) {
283
+ return default_normalize_usage(to_raw_provider_usage(usage));
284
+ }
285
+ /**
286
+ * Run one streamText call, dispatching StreamChunks as parts arrive and
287
+ * accumulating them into a TurnResult once the stream completes.
288
+ */
289
+ async function collect_stream(params, step_index, dispatcher, on_first_chunk, internal_controller, adapter) {
290
+ const stream_result = streamText(params);
291
+ let text = "";
292
+ const tool_calls = [];
293
+ let finish_reason = "stop";
294
+ let raw_usage = {};
295
+ let provider_reported;
296
+ let first = true;
297
+ for await (const part of stream_result.stream) {
298
+ if (first) {
299
+ first = false;
300
+ on_first_chunk();
301
+ }
302
+ if (part.type === "text-delta") text += part.text;
303
+ if (part.type === "tool-call") tool_calls.push({
304
+ id: part.toolCallId,
305
+ name: part.toolName,
306
+ input: part.input
307
+ });
308
+ if (part.type === "finish-step") {
309
+ finish_reason = map_finish_reason(part.finishReason);
310
+ raw_usage = to_raw_provider_usage(part.usage);
311
+ provider_reported = to_provider_reported(part.providerMetadata);
312
+ }
313
+ if (part.type === "error") throw part.error;
314
+ if (part.type === "abort") throw new aborted_error("aborted", { step_index });
315
+ const chunk = map_stream_part_to_chunk(part, step_index);
316
+ if (chunk === void 0) continue;
317
+ try {
318
+ await dispatcher.dispatch(chunk);
319
+ } catch (err) {
320
+ internal_controller.abort();
321
+ throw err;
322
+ }
323
+ }
324
+ return {
325
+ text,
326
+ tool_calls,
327
+ finish_reason,
328
+ usage: adapter.normalize_usage(raw_usage),
329
+ ...provider_reported !== void 0 ? { provider_reported } : {}
330
+ };
331
+ }
332
+ /**
333
+ * Run one generateText call and map its result into a TurnResult, recovering
334
+ * a schema-validation failure from the SDK via recover_no_object_generated
335
+ * instead of letting it throw.
336
+ */
337
+ async function collect_non_stream(params, adapter) {
338
+ let result;
339
+ try {
340
+ result = await generateText(params);
341
+ } catch (err) {
342
+ const recovered = recover_no_object_generated(err, adapter);
343
+ if (recovered !== void 0) return recovered;
344
+ throw err;
345
+ }
346
+ const tool_calls = [];
347
+ for (const tc of result.toolCalls) tool_calls.push({
348
+ id: tc.toolCallId,
349
+ name: tc.toolName,
350
+ input: tc.input
351
+ });
352
+ const raw_usage = to_raw_provider_usage(result.usage);
353
+ const provider_reported = to_provider_reported(result.providerMetadata);
354
+ return {
355
+ text: result.text,
356
+ tool_calls,
357
+ finish_reason: map_finish_reason(result.finishReason),
358
+ usage: adapter.normalize_usage(raw_usage),
359
+ ...provider_reported !== void 0 ? { provider_reported } : {}
360
+ };
361
+ }
362
+ /**
363
+ * When `output` (structured output) is in play, `generateText` eagerly parses the
364
+ * model's text against the schema and throws `NoObjectGeneratedError` if it
365
+ * does not conform. That parse is the SDK's, not fascicle's: turning it into a
366
+ * thrown error would skip the engine's own schema-parse + repair loop (and the
367
+ * error is not a retryable transient, so it would surface raw). Instead we
368
+ * recover the model's raw text from the error and hand it back as a normal
369
+ * turn result, so `parse_with_schema` re-validates it and the repair loop
370
+ * engages exactly as it does for the prompt-based path. Returns undefined for
371
+ * any other error so the caller rethrows.
372
+ *
373
+ * The recovered turn carries no provider_reported: the SDK's error exposes
374
+ * text, usage, finishReason and response metadata, but not providerMetadata,
375
+ * so there is nothing to read. The repair turn that follows reports normally.
376
+ */
377
+ function recover_no_object_generated(err, adapter) {
378
+ if (!NoObjectGeneratedError.isInstance(err)) return void 0;
379
+ const text_field = Reflect.get(err, "text");
380
+ const finish_field = Reflect.get(err, "finishReason");
381
+ const raw_usage = to_raw_provider_usage(Reflect.get(err, "usage"));
382
+ return {
383
+ text: typeof text_field === "string" ? text_field : "",
384
+ tool_calls: [],
385
+ finish_reason: map_finish_reason(typeof finish_field === "string" ? finish_field : void 0),
386
+ usage: adapter.normalize_usage(raw_usage)
387
+ };
388
+ }
389
+ /**
390
+ * Build the single-attempt SDK turn for one generate call: the
391
+ * generateText/streamText call body behind the same neutral seam a native
392
+ * adapter's invoke_turn implements. The built model is memoized across steps
393
+ * of one generate call. No retry here: generate.ts wraps the returned turn in
394
+ * the engine-owned retry_turn.
395
+ */
396
+ function create_ai_sdk_turn(cfg) {
397
+ let model_instance;
398
+ const get_model = async () => {
399
+ if (model_instance === void 0) model_instance = await cfg.adapter.build_model(cfg.model_id);
400
+ return model_instance;
401
+ };
402
+ let telemetry_options;
403
+ let telemetry_resolved = false;
404
+ const get_telemetry = async () => {
405
+ if (!telemetry_resolved) {
406
+ telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry);
407
+ telemetry_resolved = true;
408
+ }
409
+ return telemetry_options;
410
+ };
411
+ const sdk_tools = to_sdk_tools(cfg.tools);
412
+ let output_spec;
413
+ if (cfg.schema !== void 0 && cfg.tools.length === 0 && cfg.adapter.supports("structured_output")) output_spec = Output.object({ schema: cfg.schema });
414
+ const provider_options = cfg.provider_options;
415
+ return async (args) => {
416
+ const model = await get_model();
417
+ const telemetry = await get_telemetry();
418
+ const internal_controller = new AbortController();
419
+ const cancel_on_user_abort = () => {
420
+ internal_controller.abort(args.abort.reason);
421
+ };
422
+ if (args.abort.aborted) internal_controller.abort(args.abort.reason);
423
+ else args.abort.addEventListener("abort", cancel_on_user_abort, { once: true });
424
+ const { system: hoisted_system, messages: sdk_messages } = split_leading_system(to_sdk_messages(args.messages));
425
+ const base_params = {
426
+ model,
427
+ messages: sdk_messages,
428
+ abortSignal: internal_controller.signal,
429
+ stopWhen: isStepCount(1),
430
+ maxRetries: 0
431
+ };
432
+ if (hoisted_system !== void 0) base_params.instructions = hoisted_system;
433
+ if (sdk_tools !== void 0) base_params.tools = sdk_tools;
434
+ if (output_spec !== void 0) base_params.output = output_spec;
435
+ if (provider_options !== void 0) base_params.providerOptions = provider_options;
436
+ if (cfg.temperature !== void 0) base_params.temperature = cfg.temperature;
437
+ if (cfg.max_tokens !== void 0) base_params.maxOutputTokens = cfg.max_tokens;
438
+ if (cfg.top_p !== void 0) base_params.topP = cfg.top_p;
439
+ if (telemetry !== void 0) base_params.experimental_telemetry = telemetry;
440
+ try {
441
+ if (args.stream) return await collect_stream(base_params, args.step_index, cfg.dispatcher, args.on_first_chunk, internal_controller, cfg.adapter);
442
+ return await collect_non_stream(base_params, cfg.adapter);
443
+ } finally {
444
+ args.abort.removeEventListener("abort", cancel_on_user_abort);
445
+ }
446
+ };
447
+ }
448
+ //#endregion
449
+ export { create_ai_sdk_turn, default_usage_from_sdk, map_finish_reason, map_stream_part_to_chunk, split_leading_system, to_provider_reported, to_raw_provider_usage, to_sdk_messages, to_sdk_tools };
450
+
451
+ //# sourceMappingURL=invoke-D9pxbZcu.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoke-D9pxbZcu.js","names":["ai_tool"],"sources":["../src/engine/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts"],"sourcesContent":["/**\n * AI SDK telemetry wiring, confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam: it instruments one\n * turn inside this module, never the loop. The peer is loaded lazily and only\n * when telemetry is explicitly enabled, so the disabled default (every call\n * that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge.\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\n/**\n * Build the AI SDK's `experimental_telemetry` option from engine settings,\n * loading the `@ai-sdk/otel` peer only when telemetry is enabled.\n */\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Only this module imports from `ai` or invokes generateText / streamText.\n * generate.ts drives this transport through create_ai_sdk_turn and stays\n * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native\n * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose: generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n generateText,\n NoObjectGeneratedError,\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type LanguageModel,\n type ModelMessage,\n type TextStreamPart,\n type ToolSet,\n} from 'ai'\nimport type { ToolSchema } from '#schema'\nimport type {\n AiSdkTelemetrySettings,\n FinishReason,\n Message,\n StreamChunk,\n Tool,\n TurnResult,\n UsageTotals,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type RawProviderUsage,\n} from '../types.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n/**\n * Map the AI SDK's finish reason string to the engine's FinishReason.\n */\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\n/**\n * Extract the usage fields `default_normalize_usage` understands from an AI\n * SDK usage object, tolerating both the SDK's camelCase shape and the\n * flattened snake_case fields some provider mocks return directly.\n */\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = Reflect.get(usage, 'inputTokens')\n if (typeof input_tokens === 'number') raw.input_tokens = input_tokens\n const output_tokens = Reflect.get(usage, 'outputTokens')\n if (typeof output_tokens === 'number') raw.output_tokens = output_tokens\n const input_details = Reflect.get(usage, 'inputTokenDetails')\n if (input_details !== null && typeof input_details === 'object') {\n const cache_read = Reflect.get(input_details, 'cacheReadTokens')\n const cache_write = Reflect.get(input_details, 'cacheWriteTokens')\n raw.input_token_details = {}\n if (typeof cache_read === 'number') raw.input_token_details.cached_tokens = cache_read\n if (typeof cache_write === 'number') raw.input_token_details.cache_creation_input_tokens = cache_write\n }\n const output_details = Reflect.get(usage, 'outputTokenDetails')\n if (output_details !== null && typeof output_details === 'object') {\n const reasoning = Reflect.get(output_details, 'reasoningTokens')\n raw.output_token_details = {}\n if (typeof reasoning === 'number') raw.output_token_details.reasoning_tokens = reasoning\n }\n // Passthrough for mocks that provide flattened fields directly.\n const cached_flat = Reflect.get(usage, 'cached_input_tokens')\n if (typeof cached_flat === 'number') raw.cached_input_tokens = cached_flat\n const cache_write_flat = Reflect.get(usage, 'cache_write_tokens')\n if (typeof cache_write_flat === 'number') raw.cache_write_tokens = cache_write_flat\n const reasoning_flat = Reflect.get(usage, 'reasoning_tokens')\n if (typeof reasoning_flat === 'number') raw.reasoning_tokens = reasoning_flat\n const input_flat = Reflect.get(usage, 'input_tokens')\n if (raw.input_tokens === undefined && typeof input_flat === 'number') raw.input_tokens = input_flat\n const output_flat = Reflect.get(usage, 'output_tokens')\n if (raw.output_tokens === undefined && typeof output_flat === 'number') raw.output_tokens = output_flat\n return raw\n}\n\n/**\n * Normalize an AI SDK `providerMetadata` value into the neutral\n * TurnResult.provider_reported shape.\n *\n * The SDK's metadata is already keyed by provider name, which is the shape\n * provider_reported documents, so the keys ride through untranslated and every\n * ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,\n * anthropic's cache detail, openai's own fields. The payloads stay opaque\n * (callers narrow them at the use site), so this copies the top level and\n * inspects nothing below it. An absent or empty map returns undefined, keeping\n * \"the provider reported nothing\" spelled one way.\n */\nexport function to_provider_reported(metadata: unknown): Record<string, unknown> | undefined {\n if (metadata === null || typeof metadata !== 'object') return undefined\n const keys = Object.keys(metadata)\n if (keys.length === 0) return undefined\n const reported: Record<string, unknown> = {}\n for (const key of keys) reported[key] = Reflect.get(metadata, key)\n return reported\n}\n\n/**\n * Map fascicle's Message[] to the AI SDK's ModelMessage[] shape.\n */\nexport function to_sdk_messages(messages: ReadonlyArray<Message>): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<\n | { type: 'text'; text: string }\n | { type: 'image'; image: string | Uint8Array; mediaType?: string }\n > = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text', text: p.text }\n const image_part: { type: 'image'; image: string | Uint8Array; mediaType?: string } = {\n type: 'image',\n image: p.image,\n }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return image_part\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: 'text', value: m.content },\n },\n ],\n })\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text' as const, text: p.text }\n return {\n type: 'tool-call' as const,\n toolCallId: p.id,\n toolName: p.name,\n input: p.input,\n }\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n let run_end = 0\n const system_parts: string[] = []\n while (run_end < messages.length) {\n const m = messages[run_end]\n if (m?.role !== 'system') break\n system_parts.push(m.content)\n run_end += 1\n }\n const rest = messages.slice(run_end)\n if (system_parts.length === 0 || rest.length === 0) {\n return { messages: [...messages] }\n }\n return { system: system_parts.join('\\n\\n'), messages: rest }\n}\n\n/**\n * Map fascicle's Tool[] to the AI SDK's ToolSet.\n *\n * Returns undefined for an empty tool list so the caller can omit `tools`\n * from the call params entirely instead of passing an empty object.\n */\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\n/**\n * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined\n * for a part kind the engine does not model.\n */\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: default_usage_from_sdk(part.usage),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\n/**\n * Normalize a raw AI SDK usage object into UsageTotals for a streamed\n * step_finish chunk.\n */\nexport function default_usage_from_sdk(usage: unknown): UsageTotals {\n // Streamed step_finish chunks must carry the same cache/reasoning\n // granularity the step record gets via adapter.normalize_usage; every\n // built-in adapter routes through default_normalize_usage, so this keeps\n // the chunk surface consistent with the non-streamed result.\n return default_normalize_usage(to_raw_provider_usage(usage))\n}\n\n/**\n * Run one streamText call, dispatching StreamChunks as parts arrive and\n * accumulating them into a TurnResult once the stream completes.\n */\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n on_first_chunk: () => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText(params)\n let text = ''\n const tool_calls: RawToolCall[] = []\n let finish_reason: FinishReason = 'stop'\n let raw_usage: RawProviderUsage = {}\n let provider_reported: Record<string, unknown> | undefined\n let first = true\n\n for await (const part of stream_result.stream) {\n if (first) {\n first = false\n on_first_chunk()\n }\n if (part.type === 'text-delta') {\n text += part.text\n }\n if (part.type === 'tool-call') {\n tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n }\n if (part.type === 'finish-step') {\n finish_reason = map_finish_reason(part.finishReason)\n raw_usage = to_raw_provider_usage(part.usage)\n // The streamed finish-step carries the same providerMetadata generateText\n // returns on its result, which is what keeps a streamed run's\n // provider_reported identical to a plain run's.\n provider_reported = to_provider_reported(part.providerMetadata)\n }\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index)\n if (chunk === undefined) continue\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n return {\n text,\n tool_calls,\n finish_reason,\n usage: adapter.normalize_usage(raw_usage),\n // Stryker disable next-line ConditionalExpression: an always-true spread only adds an explicit `provider_reported: undefined` key, which every reader of TurnResult treats identically to the absent key.\n ...(provider_reported !== undefined ? { provider_reported } : {}),\n }\n}\n\n/**\n * Run one generateText call and map its result into a TurnResult, recovering\n * a schema-validation failure from the SDK via recover_no_object_generated\n * instead of letting it throw.\n */\nasync function collect_non_stream(\n params: Parameters<typeof generateText>[0],\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n let result: Awaited<ReturnType<typeof generateText>>\n try {\n result = await generateText(params)\n } catch (err: unknown) {\n const recovered = recover_no_object_generated(err, adapter)\n if (recovered !== undefined) return recovered\n throw err\n }\n const tool_calls: RawToolCall[] = []\n for (const tc of result.toolCalls) {\n tool_calls.push({\n id: tc.toolCallId,\n name: tc.toolName,\n input: tc.input,\n })\n }\n const raw_usage = to_raw_provider_usage(result.usage)\n // result.providerMetadata rather than result.finalStep.providerMetadata: the\n // two are the same value under stopWhen isStepCount(1), and the flat field\n // exists across the whole `ai` ^7 peer range this package declares.\n const provider_reported = to_provider_reported(result.providerMetadata)\n return {\n text: result.text,\n tool_calls,\n finish_reason: map_finish_reason(result.finishReason),\n usage: adapter.normalize_usage(raw_usage),\n // Stryker disable next-line ConditionalExpression: see collect_stream; the always-true spread is unobservable through every TurnResult reader.\n ...(provider_reported !== undefined ? { provider_reported } : {}),\n }\n}\n\n/**\n * When `output` (structured output) is in play, `generateText` eagerly parses the\n * model's text against the schema and throws `NoObjectGeneratedError` if it\n * does not conform. That parse is the SDK's, not fascicle's: turning it into a\n * thrown error would skip the engine's own schema-parse + repair loop (and the\n * error is not a retryable transient, so it would surface raw). Instead we\n * recover the model's raw text from the error and hand it back as a normal\n * turn result, so `parse_with_schema` re-validates it and the repair loop\n * engages exactly as it does for the prompt-based path. Returns undefined for\n * any other error so the caller rethrows.\n *\n * The recovered turn carries no provider_reported: the SDK's error exposes\n * text, usage, finishReason and response metadata, but not providerMetadata,\n * so there is nothing to read. The repair turn that follows reports normally.\n */\nfunction recover_no_object_generated(\n err: unknown,\n adapter: AiSdkProviderAdapter,\n): TurnResult | undefined {\n if (!NoObjectGeneratedError.isInstance(err)) return undefined\n const text_field = Reflect.get(err, 'text')\n const finish_field = Reflect.get(err, 'finishReason')\n const raw_usage = to_raw_provider_usage(Reflect.get(err, 'usage'))\n return {\n text: typeof text_field === 'string' ? text_field : '',\n tool_calls: [],\n finish_reason: map_finish_reason(typeof finish_field === 'string' ? finish_field : undefined),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0] & Parameters<typeof generateText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: ToolSchema | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n readonly stream: boolean\n readonly on_first_chunk: () => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the\n * generateText/streamText call body behind the same neutral seam a native\n * adapter's invoke_turn implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (e.g. Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what generateText/streamText consume to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n if (args.stream) {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.on_first_chunk,\n internal_controller,\n cfg.adapter,\n )\n }\n return await collect_non_stream(base_params, cfg.adapter)\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\n }\n}\n"],"mappings":";;;;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9 @@
1
- import { G as Step, J as TrajectoryLogger } from "./index-SkPG_Rew.js";
2
- import { z as Tool } from "./index-BNgtkeUf.js";
3
- import { z } from "zod";
1
+ import { r as Step, s as TrajectoryLogger } from "./types-BDSbSUAO.js";
2
+ import { r as ToolSchema } from "./types-BCtKsxrX.js";
3
+ import { w as Tool } from "./types-B3HIsBBD.js";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
+ import { z } from "zod";
6
7
 
7
8
  //#region src/mcp/client.d.ts
8
9
  type McpStdioConfig = {
@@ -40,10 +41,11 @@ type McpClientHandle = {
40
41
  *
41
42
  * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
42
43
  * do not have to import SDK transport classes themselves. Each advertised MCP
43
- * tool becomes an ordinary `Tool`: its JSON Schema is bridged to Zod for the
44
- * loop's `safeParse` and the provider, and `execute` forwards to `callTool`,
45
- * propagating the run's abort signal. For the `client` transport variant the
46
- * caller keeps ownership of the connection, so `close` is a no-op.
44
+ * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`
45
+ * the loop validates against and the provider receives back unchanged, and
46
+ * `execute` forwards to `callTool`, propagating the run's abort signal. For the
47
+ * `client` transport variant the caller keeps ownership of the connection, so
48
+ * `close` is a no-op.
47
49
  */
48
50
  declare function mcp_client(config: McpClientConfig, options?: McpClientOptions): Promise<McpClientHandle>;
49
51
  //#endregion
@@ -53,6 +55,13 @@ type ServeFlowOptions<i, o> = {
53
55
  flow: Step<i, o>;
54
56
  name: string;
55
57
  description: string;
58
+ /**
59
+ * Stays zod rather than joining the rest of the surface on `ToolSchema`.
60
+ * `McpServer.registerTool` types `inputSchema` as a zod schema and offers no
61
+ * JSON Schema entry point, and the SDK carries zod as a hard runtime
62
+ * dependency, so a `serve_flow` caller already has zod resolved. Widening
63
+ * this to a neutral schema would typecheck and then fail inside the SDK.
64
+ */
56
65
  input_schema: z.ZodType<i>;
57
66
  trajectory?: TrajectoryLogger;
58
67
  to_result?: (output: o) => {
@@ -72,13 +81,16 @@ declare function serve_flow<i, o>(options: ServeFlowOptions<i, o>): void;
72
81
  //#endregion
73
82
  //#region src/mcp/schema_bridge.d.ts
74
83
  /**
75
- * Converts a JSON Schema node into a Zod type, never throwing.
84
+ * Builds a `ToolSchema` over an MCP server's advertised JSON Schema.
76
85
  *
77
- * A malformed or unrecognized schema falls back to `z.unknown()` instead of
78
- * propagating an error, since an arbitrary remote MCP server's schema must
79
- * never crash tool discovery.
86
+ * The advertised schema is snapshotted once, deeply, and both faces of the
87
+ * returned object read that snapshot. A malformed or hostile schema degrades to
88
+ * the empty schema during the snapshot rather than propagating an error, since
89
+ * an arbitrary remote server's advertisement must never crash tool discovery,
90
+ * and it leaves both faces describing the same thing: accept anything, emit
91
+ * nothing.
80
92
  */
81
- declare function json_schema_to_zod(schema: unknown): z.ZodType;
93
+ declare function json_schema_to_standard(schema: unknown): ToolSchema;
82
94
  //#endregion
83
95
  //#region src/mcp/errors.d.ts
84
96
  /**
@@ -100,5 +112,5 @@ declare class mcp_error extends Error {
100
112
  });
101
113
  }
102
114
  //#endregion
103
- export { type McpClientConfig, type McpClientHandle, type McpClientOptions, type McpExistingClientConfig, type McpStdioConfig, type McpStreamableHttpConfig, type ServeFlowOptions, json_schema_to_zod, mcp_client, mcp_error, mcp_sdk_missing_error, serve_flow };
115
+ export { type McpClientConfig, type McpClientHandle, type McpClientOptions, type McpExistingClientConfig, type McpStdioConfig, type McpStreamableHttpConfig, type ServeFlowOptions, json_schema_to_standard, mcp_client, mcp_error, mcp_sdk_missing_error, serve_flow };
104
116
  //# sourceMappingURL=mcp.d.ts.map