fascicle 0.17.5 → 0.17.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as FlowValue, c as Step, d as StepMetadata, f as StepOptions, h as TrajectoryLogger, i as FlowNode, l as StepFn, m as TrajectoryEvent, n as CheckpointStore, o as RunContext, p as StepOutput, r as CleanupFn, s as ScopedCheckpointStore, t as AnyStep, u as StepInput } from "./types-CPqLZOEr.js";
2
2
  import { n as SchemaIssue, r as ToolSchema, t as AnySchema } from "./types-BK0UW28o.js";
3
3
  import { _ as is_run_end_event, a as MapItemFailedEvent, b as is_step_replayed_event, c as RunEndStatus, d as StepReplayedEvent, f as TrajectoryParseResult, g as is_map_item_failed_event, h as is_emit_event, i as EmitEvent, l as SpanEndEvent, m as is_custom_trajectory_event, n as CheckpointStatus, o as ParsedTrajectoryEvent, p as is_checkpoint_event, r as CustomTrajectoryEvent, s as RunEndEvent, t as CheckpointEvent, u as SpanStartEvent, v as is_span_end_event, x as parse_trajectory_event, y as is_span_start_event } from "./trajectory-BKGNxi7u.js";
4
- import { A as StepTiming, B as UsageTotals, C as ProviderConfigMap, D as RetryFailureKind, E as ResolvedModel, F as ToolCallRecord, G as NativeProviderAdapter, H as AiSdkProviderAdapter, I as ToolExecContext, J as ProviderFactory, K as ProviderAdapter, L as TruncatedTurnPolicy, M as Tool, N as ToolApprovalHandler, O as RetryPolicy, P as ToolApprovalRequest, Q as ClaudeCliProviderReported, R as TurnRequest, S as PricingTable, T as ProviderOptions, U as EffortTranslation, V as UserContentPart, W as ExternalAgentAdapter, X as RawProviderUsage, Y as ProviderTransport, Z as default_normalize_usage, _ as Message, a as CacheSetting, b as PrepareStepResult, c as CostBreakdown, d as EngineConfig, f as EngineDefaults, g as GenerateTiming, h as GenerateResult, i as BedrockCredentials, j as StreamChunk, k as StepRecord, l as EffortLevel, m as GenerateOptions, n as AssistantContentPart, o as CaptureLevel, p as FinishReason, q as ProviderCapability, r as BedrockCredentialProvider, s as CapturePayload, t as AiSdkTelemetrySettings, u as Engine, v as PrepareStepContext, w as ProviderInit, x as Pricing, y as PrepareStepHook, z as TurnResult } from "./types-C23S11Kk.js";
4
+ import { A as StepTiming, B as UsageTotals, C as ProviderConfigMap, D as RetryFailureKind, E as ResolvedModel, F as ToolCallRecord, G as NativeProviderAdapter, H as AiSdkProviderAdapter, I as ToolExecContext, J as ProviderFactory, K as ProviderAdapter, L as TruncatedTurnPolicy, M as Tool, N as ToolApprovalHandler, O as RetryPolicy, P as ToolApprovalRequest, Q as ClaudeCliProviderReported, R as TurnRequest, S as PricingTable, T as ProviderOptions, U as EffortTranslation, V as UserContentPart, W as ExternalAgentAdapter, X as RawProviderUsage, Y as ProviderTransport, Z as default_normalize_usage, _ as Message, a as CacheSetting, b as PrepareStepResult, c as CostBreakdown, d as EngineConfig, f as EngineDefaults, g as GenerateTiming, h as GenerateResult, i as BedrockCredentials, j as StreamChunk, k as StepRecord, l as EffortLevel, m as GenerateOptions, n as AssistantContentPart, o as CaptureLevel, p as FinishReason, q as ProviderCapability, r as BedrockCredentialProvider, s as CapturePayload, t as AiSdkTelemetrySettings, u as Engine, v as PrepareStepContext, w as ProviderInit, x as Pricing, y as PrepareStepHook, z as TurnResult } from "./types-xYjCEd6i.js";
5
5
  //#region src/core/runner.d.ts
6
6
  type RunOptions = {
7
7
  readonly install_signal_handlers?: boolean;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { A as is_step, B as timeout_error, F as flow_changed_error, H as is_step_kind, I as gate_result_error, L as resume_validation_error, M as describe_cycle_error, N as duplicate_suspend_id_error, O as same_input_as, P as error_path, R as run_not_found_error, U as resolve_display_name, V as STEP_KINDS, _ as step, a as suspend, b as suggest_step_id, c as loop, d as retry, f as pipe, g as sequence, h as parallel, i as use, j as aborted_error, k as describe, l as timeout, m as branch, n as scope, o as checkpoint, p as map, r as stash, s as compose, t as chain, u as fallback, v as assert_valid_step_id, w as run, x as durable, y as is_valid_step_id, z as suspended_error } from "./core-Bfzt55Fl.js";
2
- import { t as create_engine } from "./engine-BTijBDlY.js";
2
+ import { t as create_engine } from "./engine-B5iQ3if9.js";
3
3
  import { n as is_record$1 } from "./records-1HU7mWXf.js";
4
4
  import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
5
5
  import { a as is_run_end_event, c as is_step_replayed_event, i as is_map_item_failed_event, l as parse_trajectory_event, n as is_custom_trajectory_event, o as is_span_end_event, r as is_emit_event, s as is_span_start_event, t as is_checkpoint_event } from "./trajectory-DeURWIhj.js";
@@ -0,0 +1,267 @@
1
+ import { w as run } from "./core-Bfzt55Fl.js";
2
+ import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
3
+ import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
4
+ //#region src/mcp/errors.ts
5
+ /**
6
+ * Typed errors for the MCP adapter.
7
+ *
8
+ * Listed alongside src/core/errors.ts and src/engine/errors.ts in the
9
+ * `no-class` rule ignores: `instanceof` branching is how callers distinguish a
10
+ * missing optional peer from a tool-level failure surfaced over the wire.
11
+ */
12
+ var mcp_sdk_missing_error = class extends Error {
13
+ kind = "mcp_sdk_missing_error";
14
+ constructor(message = "@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk") {
15
+ super(message);
16
+ this.name = "mcp_sdk_missing_error";
17
+ }
18
+ };
19
+ var mcp_error = class extends Error {
20
+ kind = "mcp_error";
21
+ tool_name;
22
+ constructor(message, metadata = {}) {
23
+ super(message);
24
+ this.name = "mcp_error";
25
+ this.tool_name = metadata.tool_name;
26
+ }
27
+ };
28
+ //#endregion
29
+ //#region src/mcp/result_mapping.ts
30
+ /**
31
+ * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in
32
+ * both directions: inbound results from `mcp_client` tools, outbound results
33
+ * for `serve_flow`.
34
+ */
35
+ /**
36
+ * Converts a remote tool's `CallToolResult` into the value a Fascicle
37
+ * `Tool.execute` returns.
38
+ *
39
+ * `isError: true` marks a tool-level failure, so it throws `mcp_error` rather
40
+ * than returning, letting the tool loop's error policy feed it back to the
41
+ * model. `structuredContent` is preferred over joined text parts when present;
42
+ * with neither, the raw `content` (or `null`) is returned.
43
+ */
44
+ function call_result_to_output(result, tool_name) {
45
+ const record = as_record(result) ?? {};
46
+ if (record["isError"] === true) throw new mcp_error(join_text(record["content"]) ?? "MCP tool returned an error", tool_name !== void 0 ? { tool_name } : {});
47
+ if (is_record(record["structuredContent"])) return record["structuredContent"];
48
+ const text = join_text(record["content"]);
49
+ if (text !== void 0) return text;
50
+ return record["content"] ?? null;
51
+ }
52
+ /**
53
+ * Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.
54
+ *
55
+ * A `to_result` override takes precedence over the default mapping. By
56
+ * default, objects are emitted as both a JSON text part (every MCP host can
57
+ * read text) and `structuredContent` (typed hosts get the object); everything
58
+ * else becomes a single text part.
59
+ */
60
+ function output_to_call_result(output, to_result) {
61
+ if (to_result !== void 0) {
62
+ const shaped = to_result(output);
63
+ return build_result(shaped.text, shaped.structured);
64
+ }
65
+ if (typeof output === "string") return build_result(output);
66
+ if (is_record(output)) return build_result(stringify(output), output);
67
+ if (Array.isArray(output)) return build_result(stringify(output));
68
+ return build_result(String(output));
69
+ }
70
+ /**
71
+ * Assembles a `CallToolResult` with one text part and, when given, structured
72
+ * content.
73
+ */
74
+ function build_result(text, structured) {
75
+ return structured !== void 0 ? {
76
+ content: [{
77
+ type: "text",
78
+ text
79
+ }],
80
+ structuredContent: structured
81
+ } : { content: [{
82
+ type: "text",
83
+ text
84
+ }] };
85
+ }
86
+ /**
87
+ * Joins the `text` parts of an MCP content array with newlines, skipping
88
+ * non-text parts; `undefined` when there is nothing to join.
89
+ */
90
+ function join_text(content) {
91
+ if (!Array.isArray(content)) return void 0;
92
+ const parts = [];
93
+ for (const part of content) if (is_record(part) && part["type"] === "text" && typeof part["text"] === "string") parts.push(part["text"]);
94
+ return parts.length > 0 ? parts.join("\n") : void 0;
95
+ }
96
+ /**
97
+ * `JSON.stringify` that falls back to `String` instead of throwing on
98
+ * unserializable values (circular references, BigInt).
99
+ */
100
+ function stringify(value) {
101
+ try {
102
+ return JSON.stringify(value);
103
+ } catch {
104
+ return String(value);
105
+ }
106
+ }
107
+ //#endregion
108
+ //#region src/mcp/sdk_loader.ts
109
+ /**
110
+ * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.
111
+ *
112
+ * `mcp_client` needs SDK values (the Client and transport constructors), so it
113
+ * imports them dynamically rather than statically: a consumer can import
114
+ * `fascicle/mcp` without the SDK installed and only pays the cost when they
115
+ * actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`
116
+ * with install guidance, mirroring the engine's `load_optional_peer`.
117
+ *
118
+ * `serve_flow` is not covered here: it operates on a caller-constructed
119
+ * `McpServer`, so it needs only a type-only import and no runtime SDK load.
120
+ */
121
+ /**
122
+ * Dynamically imports the `@modelcontextprotocol/sdk` client modules,
123
+ * throwing a typed `mcp_sdk_missing_error` when the optional peer is not
124
+ * installed.
125
+ */
126
+ async function load_client_sdk() {
127
+ try {
128
+ const [client_mod, stdio_mod, http_mod] = await Promise.all([
129
+ import("@modelcontextprotocol/sdk/client/index.js"),
130
+ import("@modelcontextprotocol/sdk/client/stdio.js"),
131
+ import("@modelcontextprotocol/sdk/client/streamableHttp.js")
132
+ ]);
133
+ return {
134
+ Client: client_mod.Client,
135
+ StdioClientTransport: stdio_mod.StdioClientTransport,
136
+ StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport
137
+ };
138
+ } catch (err) {
139
+ throw new mcp_sdk_missing_error(`@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${err instanceof Error ? err.message : String(err)})`);
140
+ }
141
+ }
142
+ //#endregion
143
+ //#region src/mcp/client.ts
144
+ const DEFAULT_CLIENT_INFO = {
145
+ name: "fascicle",
146
+ version: "0.0.0"
147
+ };
148
+ /**
149
+ * Connects to an MCP server and surfaces its advertised tools as Fascicle
150
+ * `Tool[]`, plus a `close` handle for the connection.
151
+ *
152
+ * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
153
+ * do not have to import SDK transport classes themselves. Each advertised MCP
154
+ * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`
155
+ * the loop validates against and the provider receives back unchanged, and
156
+ * `execute` forwards to `callTool`, propagating the run's abort signal. For the
157
+ * `client` transport variant the caller keeps ownership of the connection, so
158
+ * `close` is a no-op. A connection this call opened is closed again when
159
+ * listing its tools fails.
160
+ */
161
+ async function mcp_client(config, options = {}) {
162
+ const owns_client = config.transport !== "client";
163
+ const client = await connect_client(config, options);
164
+ const include = options.include !== void 0 ? new Set(options.include) : void 0;
165
+ const listed = await client.listTools().catch(async (err) => {
166
+ if (owns_client) await client.close().catch(() => void 0);
167
+ throw err;
168
+ });
169
+ const tools = [];
170
+ for (const advertised of listed.tools) {
171
+ if (include !== void 0 && !include.has(advertised.name)) continue;
172
+ tools.push(to_fascicle_tool(client, advertised, options));
173
+ }
174
+ return {
175
+ tools,
176
+ close: async () => {
177
+ if (owns_client) await client.close();
178
+ }
179
+ };
180
+ }
181
+ /**
182
+ * Returns the caller's already-connected client as-is, or lazily loads the
183
+ * SDK and connects a fresh client over the configured transport.
184
+ */
185
+ async function connect_client(config, options) {
186
+ if (config.transport === "client") return config.client;
187
+ const sdk = await load_client_sdk();
188
+ const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO);
189
+ await client.connect(build_transport(sdk, config));
190
+ return client;
191
+ }
192
+ /**
193
+ * Constructs the SDK transport matching the config: a spawned child process
194
+ * for `stdio`, a Streamable HTTP connection for `http`.
195
+ */
196
+ function build_transport(sdk, config) {
197
+ if (config.transport === "stdio") return new sdk.StdioClientTransport({
198
+ command: config.command,
199
+ ...config.args !== void 0 ? { args: config.args } : {},
200
+ ...config.env !== void 0 ? { env: config.env } : {},
201
+ ...config.cwd !== void 0 ? { cwd: config.cwd } : {}
202
+ });
203
+ const opts = config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {};
204
+ return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts);
205
+ }
206
+ /**
207
+ * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards
208
+ * to `callTool` on the shared client. Only the `Tool`'s name carries
209
+ * `name_prefix`; the call, the fallback description, and the errors use the
210
+ * server's own name.
211
+ *
212
+ * An already-aborted signal short-circuits before the wire call; otherwise the
213
+ * signal is passed through so cancelling the run cancels the remote call.
214
+ */
215
+ function to_fascicle_tool(client, advertised, options) {
216
+ const name = advertised.name;
217
+ const description = advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`;
218
+ return {
219
+ name: `${options.name_prefix ?? ""}${name}`,
220
+ description,
221
+ input_schema: json_schema_to_standard(advertised.inputSchema),
222
+ execute: async (input, ctx) => {
223
+ if (ctx.abort.aborted) throw ctx.abort.reason instanceof Error ? ctx.abort.reason : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name });
224
+ return call_result_to_output(await client.callTool({
225
+ name,
226
+ arguments: is_record(input) ? input : void 0
227
+ }, void 0, { signal: ctx.abort }), name);
228
+ }
229
+ };
230
+ }
231
+ //#endregion
232
+ //#region src/mcp/serve.ts
233
+ /**
234
+ * Registers a Fascicle flow as a tool on a caller-owned MCP server.
235
+ *
236
+ * Drives the flow with `run`, threading the per-request abort signal so an
237
+ * MCP client cancellation aborts the in-flight flow, and maps the result
238
+ * into a `CallToolResult`. A thrown flow becomes an `isError` result rather
239
+ * than a JSON-RPC protocol error.
240
+ */
241
+ function serve_flow(config) {
242
+ const { server, flow, name, description, input_schema, trajectory, to_result } = config;
243
+ server.registerTool(name, {
244
+ description,
245
+ inputSchema: input_schema
246
+ }, async (input, extra) => {
247
+ try {
248
+ return output_to_call_result(await run(flow, input, {
249
+ install_signal_handlers: false,
250
+ abort: extra.signal,
251
+ ...trajectory !== void 0 ? { trajectory } : {}
252
+ }), to_result);
253
+ } catch (err) {
254
+ return {
255
+ isError: true,
256
+ content: [{
257
+ type: "text",
258
+ text: err instanceof Error ? err.message : String(err)
259
+ }]
260
+ };
261
+ }
262
+ });
263
+ }
264
+ //#endregion
265
+ export { mcp_sdk_missing_error as i, mcp_client as n, mcp_error as r, serve_flow as t };
266
+
267
+ //# sourceMappingURL=mcp-8mKK7eDY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-8mKK7eDY.js","names":[],"sources":["../src/mcp/errors.ts","../src/mcp/result_mapping.ts","../src/mcp/sdk_loader.ts","../src/mcp/client.ts","../src/mcp/serve.ts"],"sourcesContent":["/**\n * Typed errors for the MCP adapter.\n *\n * Listed alongside src/core/errors.ts and src/engine/errors.ts in the\n * `no-class` rule ignores: `instanceof` branching is how callers distinguish a\n * missing optional peer from a tool-level failure surfaced over the wire.\n */\n\nexport class mcp_sdk_missing_error extends Error {\n readonly kind = 'mcp_sdk_missing_error' as const;\n constructor(\n message = '@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk',\n ) {\n super(message)\n this.name = 'mcp_sdk_missing_error'\n }\n}\n\nexport class mcp_error extends Error {\n readonly kind = 'mcp_error' as const;\n readonly tool_name: string | undefined;\n constructor(message: string, metadata: { tool_name?: string } = {}) {\n super(message)\n this.name = 'mcp_error'\n this.tool_name = metadata.tool_name\n }\n}\n","/**\n * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in\n * both directions: inbound results from `mcp_client` tools, outbound results\n * for `serve_flow`.\n */\n\nimport { as_record, is_record } from '#schema'\nimport { mcp_error } from './errors.js'\n\nexport type McpToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n}\n\n/**\n * Converts a remote tool's `CallToolResult` into the value a Fascicle\n * `Tool.execute` returns.\n *\n * `isError: true` marks a tool-level failure, so it throws `mcp_error` rather\n * than returning, letting the tool loop's error policy feed it back to the\n * model. `structuredContent` is preferred over joined text parts when present;\n * with neither, the raw `content` (or `null`) is returned.\n */\nexport function call_result_to_output(result: unknown, tool_name?: string): unknown {\n const record = as_record(result) ?? {}\n\n if (record['isError'] === true) {\n const detail = join_text(record['content']) ?? 'MCP tool returned an error'\n throw new mcp_error(detail, tool_name !== undefined ? { tool_name } : {})\n }\n\n if (is_record(record['structuredContent'])) return record['structuredContent']\n\n const text = join_text(record['content'])\n if (text !== undefined) return text\n\n return record['content'] ?? null\n}\n\n/**\n * Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.\n *\n * A `to_result` override takes precedence over the default mapping. By\n * default, objects are emitted as both a JSON text part (every MCP host can\n * read text) and `structuredContent` (typed hosts get the object); everything\n * else becomes a single text part.\n */\nexport function output_to_call_result<o>(\n output: o,\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> },\n): McpToolResult {\n if (to_result !== undefined) {\n const shaped = to_result(output)\n return build_result(shaped.text, shaped.structured)\n }\n if (typeof output === 'string') return build_result(output)\n if (is_record(output)) return build_result(stringify(output), output)\n if (Array.isArray(output)) return build_result(stringify(output))\n return build_result(String(output))\n}\n\n/**\n * Assembles a `CallToolResult` with one text part and, when given, structured\n * content.\n */\nfunction build_result(text: string, structured?: Record<string, unknown>): McpToolResult {\n return structured !== undefined\n ? { content: [{ type: 'text', text }], structuredContent: structured }\n : { content: [{ type: 'text', text }] }\n}\n\n/**\n * Joins the `text` parts of an MCP content array with newlines, skipping\n * non-text parts; `undefined` when there is nothing to join.\n */\nfunction join_text(content: unknown): string | undefined {\n if (!Array.isArray(content)) return undefined\n const parts: string[] = []\n for (const part of content) {\n if (is_record(part) && part['type'] === 'text' && typeof part['text'] === 'string') {\n parts.push(part['text'])\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined\n}\n\n/**\n * `JSON.stringify` that falls back to `String` instead of throwing on\n * unserializable values (circular references, BigInt).\n */\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.\n *\n * `mcp_client` needs SDK values (the Client and transport constructors), so it\n * imports them dynamically rather than statically: a consumer can import\n * `fascicle/mcp` without the SDK installed and only pays the cost when they\n * actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`\n * with install guidance, mirroring the engine's `load_optional_peer`.\n *\n * `serve_flow` is not covered here: it operates on a caller-constructed\n * `McpServer`, so it needs only a type-only import and no runtime SDK load.\n */\n\nimport { mcp_sdk_missing_error } from './errors.js'\n\nexport type McpClientSdk = Awaited<ReturnType<typeof load_client_sdk>>\n\n/**\n * Dynamically imports the `@modelcontextprotocol/sdk` client modules,\n * throwing a typed `mcp_sdk_missing_error` when the optional peer is not\n * installed.\n */\nexport async function load_client_sdk() {\n try {\n const [client_mod, stdio_mod, http_mod] = await Promise.all([\n import('@modelcontextprotocol/sdk/client/index.js'),\n import('@modelcontextprotocol/sdk/client/stdio.js'),\n import('@modelcontextprotocol/sdk/client/streamableHttp.js'),\n ])\n return {\n Client: client_mod.Client,\n StdioClientTransport: stdio_mod.StdioClientTransport,\n StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport,\n }\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new mcp_sdk_missing_error(\n `@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${detail})`,\n )\n }\n}\n","/**\n * Inbound MCP: connect to an external MCP server and surface its tools as plain\n * Fascicle `Tool[]`.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'\nimport type { Tool, ToolExecContext } from '#engine'\nimport { is_record, json_schema_to_standard } from '#schema'\nimport { mcp_error } from './errors.js'\nimport { call_result_to_output } from './result_mapping.js'\nimport { load_client_sdk, type McpClientSdk } from './sdk_loader.js'\n\nconst DEFAULT_CLIENT_INFO = { name: 'fascicle', version: '0.0.0' }\n\nexport type McpStdioConfig = {\n transport: 'stdio'\n command: string\n args?: string[]\n env?: Record<string, string>\n cwd?: string\n}\n\nexport type McpStreamableHttpConfig = {\n transport: 'http'\n url: string\n headers?: Record<string, string>\n}\n\n// Escape hatch: hand in an already-connected Client (a transport the adapter\n// does not build, a test harness, a shared connection). Its lifecycle stays\n// with the caller, so the returned `close` is a no-op for this variant.\nexport type McpExistingClientConfig = {\n transport: 'client'\n client: Client\n}\n\nexport type McpClientConfig =\n | McpStdioConfig\n | McpStreamableHttpConfig\n | McpExistingClientConfig\n\nexport type McpClientOptions = {\n // Identity sent in the MCP handshake; defaults to Fascicle.\n client_info?: { name: string; version: string }\n // When set, only tools whose name is listed are surfaced.\n include?: ReadonlyArray<string>\n // Supplies a description for tools that advertise none.\n default_description?: (tool_name: string) => string\n // Prepended, as written, to each surfaced tool's name, so two servers'\n // tools can share a call without colliding. The server is still called by\n // its own name, and `include` and `default_description` see that name too.\n name_prefix?: string\n}\n\nexport type McpClientHandle = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\n\n/**\n * Connects to an MCP server and surfaces its advertised tools as Fascicle\n * `Tool[]`, plus a `close` handle for the connection.\n *\n * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers\n * do not have to import SDK transport classes themselves. Each advertised MCP\n * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`\n * the loop validates against and the provider receives back unchanged, and\n * `execute` forwards to `callTool`, propagating the run's abort signal. For the\n * `client` transport variant the caller keeps ownership of the connection, so\n * `close` is a no-op. A connection this call opened is closed again when\n * listing its tools fails.\n */\nexport async function mcp_client(\n config: McpClientConfig,\n options: McpClientOptions = {},\n): Promise<McpClientHandle> {\n const owns_client = config.transport !== 'client'\n const client = await connect_client(config, options)\n\n const include = options.include !== undefined ? new Set(options.include) : undefined\n const listed = await client.listTools().catch(async (err: unknown) => {\n // A client this call connected has no other owner yet, so it closes here,\n // taking a spawned stdio server with it. The listing failure is the one\n // the caller sees, even if the close fails too.\n if (owns_client) await client.close().catch(() => undefined)\n throw err\n })\n const tools: Tool[] = []\n for (const advertised of listed.tools) {\n if (include !== undefined && !include.has(advertised.name)) continue\n tools.push(to_fascicle_tool(client, advertised, options))\n }\n\n return {\n tools,\n close: async () => {\n if (owns_client) await client.close()\n },\n }\n}\n\n/**\n * Returns the caller's already-connected client as-is, or lazily loads the\n * SDK and connects a fresh client over the configured transport.\n */\nasync function connect_client(\n config: McpClientConfig,\n options: McpClientOptions,\n): Promise<Client> {\n if (config.transport === 'client') return config.client\n const sdk = await load_client_sdk()\n const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO)\n await client.connect(build_transport(sdk, config))\n return client\n}\n\n/**\n * Constructs the SDK transport matching the config: a spawned child process\n * for `stdio`, a Streamable HTTP connection for `http`.\n */\nfunction build_transport(\n sdk: McpClientSdk,\n config: McpStdioConfig | McpStreamableHttpConfig,\n): Transport {\n if (config.transport === 'stdio') {\n return new sdk.StdioClientTransport({\n command: config.command,\n ...(config.args !== undefined ? { args: config.args } : {}),\n ...(config.env !== undefined ? { env: config.env } : {}),\n ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),\n })\n }\n const opts = config.headers !== undefined ? { requestInit: { headers: config.headers } } : {}\n // The SDK declares this class `implements Transport`, but its `onmessage`\n // overload is narrower than the interface's, which only strict mode flags.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts) as Transport\n}\n\n/**\n * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards\n * to `callTool` on the shared client. Only the `Tool`'s name carries\n * `name_prefix`; the call, the fallback description, and the errors use the\n * server's own name.\n *\n * An already-aborted signal short-circuits before the wire call; otherwise the\n * signal is passed through so cancelling the run cancels the remote call.\n */\nfunction to_fascicle_tool(\n client: Client,\n advertised: { name: string; description?: string | undefined; inputSchema: unknown },\n options: McpClientOptions,\n): Tool {\n const name = advertised.name\n const description =\n advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`\n return {\n name: `${options.name_prefix ?? ''}${name}`,\n description,\n input_schema: json_schema_to_standard(advertised.inputSchema),\n execute: async (input: unknown, ctx: ToolExecContext) => {\n if (ctx.abort.aborted) {\n throw ctx.abort.reason instanceof Error\n ? ctx.abort.reason\n : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name })\n }\n const result = await client.callTool(\n { name, arguments: is_record(input) ? input : undefined },\n undefined,\n { signal: ctx.abort },\n )\n return call_result_to_output(result, name)\n },\n }\n}\n","/**\n * Outbound MCP: expose a composed Fascicle flow as an MCP tool.\n *\n * `serve_flow` registers onto a caller-constructed `McpServer` (the caller owns\n * the transport, identity, and lifecycle, and can host many flows on one\n * server), so it needs only a type-only SDK import. The registered handler\n * drives the existing `run`, threading the per-request abort signal so an MCP\n * client cancellation aborts the in-flight flow, and maps the result into a\n * `CallToolResult`. A thrown flow becomes an `isError` result rather than a\n * JSON-RPC protocol error.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { output_to_call_result } from './result_mapping.js'\n\nexport type ServeFlowConfig<i, o> = {\n server: McpServer\n flow: Step<i, o>\n name: string\n description: string\n /**\n * Stays zod rather than joining the rest of the surface on `ToolSchema`.\n * `McpServer.registerTool` types `inputSchema` as a zod schema and offers no\n * JSON Schema entry point, and the SDK carries zod as a hard runtime\n * dependency, so a `serve_flow` caller already has zod resolved. Widening\n * this to a neutral schema would typecheck and then fail inside the SDK.\n */\n input_schema: z.ZodType<i>\n trajectory?: TrajectoryLogger\n // Overrides the default value-to-CallToolResult mapping.\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> }\n}\n\n/**\n * Registers a Fascicle flow as a tool on a caller-owned MCP server.\n *\n * Drives the flow with `run`, threading the per-request abort signal so an\n * MCP client cancellation aborts the in-flight flow, and maps the result\n * into a `CallToolResult`. A thrown flow becomes an `isError` result rather\n * than a JSON-RPC protocol error.\n */\nexport function serve_flow<i, o>(config: ServeFlowConfig<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = config\n server.registerTool(\n name,\n { description, inputSchema: input_schema },\n async (input: i, extra) => {\n try {\n const output = await run(flow, input, {\n install_signal_handlers: false,\n abort: extra.signal,\n ...(trajectory !== undefined ? { trajectory } : {}),\n })\n return output_to_call_result(output, to_result)\n } catch (err: unknown) {\n return {\n isError: true,\n content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],\n }\n }\n },\n )\n}\n"],"mappings":";;;;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,OAAgB;CAChB,YACE,UAAU,0GACV;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAa,YAAb,cAA+B,MAAM;CACnC,OAAgB;CAChB;CACA,YAAY,SAAiB,WAAmC,CAAC,GAAG;EAClE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS;CAC5B;AACF;;;;;;;;;;;;;;;;;ACHA,SAAgB,sBAAsB,QAAiB,WAA6B;CAClF,MAAM,SAAS,UAAU,MAAM,KAAK,CAAC;CAErC,IAAI,OAAO,eAAe,MAExB,MAAM,IAAI,UADK,UAAU,OAAO,UAAU,KAAK,8BACnB,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC,CAAC;CAG1E,IAAI,UAAU,OAAO,oBAAoB,GAAG,OAAO,OAAO;CAE1D,MAAM,OAAO,UAAU,OAAO,UAAU;CACxC,IAAI,SAAS,KAAA,GAAW,OAAO;CAE/B,OAAO,OAAO,cAAc;AAC9B;;;;;;;;;AAUA,SAAgB,sBACd,QACA,WACe;CACf,IAAI,cAAc,KAAA,GAAW;EAC3B,MAAM,SAAS,UAAU,MAAM;EAC/B,OAAO,aAAa,OAAO,MAAM,OAAO,UAAU;CACpD;CACA,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,MA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1
1
  import { c as Step, h as TrajectoryLogger } from "./types-CPqLZOEr.js";
2
2
  import { r as ToolSchema } from "./types-BK0UW28o.js";
3
- import { M as Tool } from "./types-C23S11Kk.js";
3
+ import { M as Tool } from "./types-xYjCEd6i.js";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
  import { z } from "zod";
package/dist/mcp.js CHANGED
@@ -1,267 +1,3 @@
1
- import { w as run } from "./core-Bfzt55Fl.js";
2
- import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
3
1
  import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
4
- //#region src/mcp/errors.ts
5
- /**
6
- * Typed errors for the MCP adapter.
7
- *
8
- * Listed alongside src/core/errors.ts and src/engine/errors.ts in the
9
- * `no-class` rule ignores: `instanceof` branching is how callers distinguish a
10
- * missing optional peer from a tool-level failure surfaced over the wire.
11
- */
12
- var mcp_sdk_missing_error = class extends Error {
13
- kind = "mcp_sdk_missing_error";
14
- constructor(message = "@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk") {
15
- super(message);
16
- this.name = "mcp_sdk_missing_error";
17
- }
18
- };
19
- var mcp_error = class extends Error {
20
- kind = "mcp_error";
21
- tool_name;
22
- constructor(message, metadata = {}) {
23
- super(message);
24
- this.name = "mcp_error";
25
- this.tool_name = metadata.tool_name;
26
- }
27
- };
28
- //#endregion
29
- //#region src/mcp/result_mapping.ts
30
- /**
31
- * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in
32
- * both directions: inbound results from `mcp_client` tools, outbound results
33
- * for `serve_flow`.
34
- */
35
- /**
36
- * Converts a remote tool's `CallToolResult` into the value a Fascicle
37
- * `Tool.execute` returns.
38
- *
39
- * `isError: true` marks a tool-level failure, so it throws `mcp_error` rather
40
- * than returning, letting the tool loop's error policy feed it back to the
41
- * model. `structuredContent` is preferred over joined text parts when present;
42
- * with neither, the raw `content` (or `null`) is returned.
43
- */
44
- function call_result_to_output(result, tool_name) {
45
- const record = as_record(result) ?? {};
46
- if (record["isError"] === true) throw new mcp_error(join_text(record["content"]) ?? "MCP tool returned an error", tool_name !== void 0 ? { tool_name } : {});
47
- if (is_record(record["structuredContent"])) return record["structuredContent"];
48
- const text = join_text(record["content"]);
49
- if (text !== void 0) return text;
50
- return record["content"] ?? null;
51
- }
52
- /**
53
- * Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.
54
- *
55
- * A `to_result` override takes precedence over the default mapping. By
56
- * default, objects are emitted as both a JSON text part (every MCP host can
57
- * read text) and `structuredContent` (typed hosts get the object); everything
58
- * else becomes a single text part.
59
- */
60
- function output_to_call_result(output, to_result) {
61
- if (to_result !== void 0) {
62
- const shaped = to_result(output);
63
- return build_result(shaped.text, shaped.structured);
64
- }
65
- if (typeof output === "string") return build_result(output);
66
- if (is_record(output)) return build_result(stringify(output), output);
67
- if (Array.isArray(output)) return build_result(stringify(output));
68
- return build_result(String(output));
69
- }
70
- /**
71
- * Assembles a `CallToolResult` with one text part and, when given, structured
72
- * content.
73
- */
74
- function build_result(text, structured) {
75
- return structured !== void 0 ? {
76
- content: [{
77
- type: "text",
78
- text
79
- }],
80
- structuredContent: structured
81
- } : { content: [{
82
- type: "text",
83
- text
84
- }] };
85
- }
86
- /**
87
- * Joins the `text` parts of an MCP content array with newlines, skipping
88
- * non-text parts; `undefined` when there is nothing to join.
89
- */
90
- function join_text(content) {
91
- if (!Array.isArray(content)) return void 0;
92
- const parts = [];
93
- for (const part of content) if (is_record(part) && part["type"] === "text" && typeof part["text"] === "string") parts.push(part["text"]);
94
- return parts.length > 0 ? parts.join("\n") : void 0;
95
- }
96
- /**
97
- * `JSON.stringify` that falls back to `String` instead of throwing on
98
- * unserializable values (circular references, BigInt).
99
- */
100
- function stringify(value) {
101
- try {
102
- return JSON.stringify(value);
103
- } catch {
104
- return String(value);
105
- }
106
- }
107
- //#endregion
108
- //#region src/mcp/sdk_loader.ts
109
- /**
110
- * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.
111
- *
112
- * `mcp_client` needs SDK values (the Client and transport constructors), so it
113
- * imports them dynamically rather than statically: a consumer can import
114
- * `fascicle/mcp` without the SDK installed and only pays the cost when they
115
- * actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`
116
- * with install guidance, mirroring the engine's `load_optional_peer`.
117
- *
118
- * `serve_flow` is not covered here: it operates on a caller-constructed
119
- * `McpServer`, so it needs only a type-only import and no runtime SDK load.
120
- */
121
- /**
122
- * Dynamically imports the `@modelcontextprotocol/sdk` client modules,
123
- * throwing a typed `mcp_sdk_missing_error` when the optional peer is not
124
- * installed.
125
- */
126
- async function load_client_sdk() {
127
- try {
128
- const [client_mod, stdio_mod, http_mod] = await Promise.all([
129
- import("@modelcontextprotocol/sdk/client/index.js"),
130
- import("@modelcontextprotocol/sdk/client/stdio.js"),
131
- import("@modelcontextprotocol/sdk/client/streamableHttp.js")
132
- ]);
133
- return {
134
- Client: client_mod.Client,
135
- StdioClientTransport: stdio_mod.StdioClientTransport,
136
- StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport
137
- };
138
- } catch (err) {
139
- throw new mcp_sdk_missing_error(`@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${err instanceof Error ? err.message : String(err)})`);
140
- }
141
- }
142
- //#endregion
143
- //#region src/mcp/client.ts
144
- const DEFAULT_CLIENT_INFO = {
145
- name: "fascicle",
146
- version: "0.0.0"
147
- };
148
- /**
149
- * Connects to an MCP server and surfaces its advertised tools as Fascicle
150
- * `Tool[]`, plus a `close` handle for the connection.
151
- *
152
- * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers
153
- * do not have to import SDK transport classes themselves. Each advertised MCP
154
- * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`
155
- * the loop validates against and the provider receives back unchanged, and
156
- * `execute` forwards to `callTool`, propagating the run's abort signal. For the
157
- * `client` transport variant the caller keeps ownership of the connection, so
158
- * `close` is a no-op. A connection this call opened is closed again when
159
- * listing its tools fails.
160
- */
161
- async function mcp_client(config, options = {}) {
162
- const owns_client = config.transport !== "client";
163
- const client = await connect_client(config, options);
164
- const include = options.include !== void 0 ? new Set(options.include) : void 0;
165
- const listed = await client.listTools().catch(async (err) => {
166
- if (owns_client) await client.close().catch(() => void 0);
167
- throw err;
168
- });
169
- const tools = [];
170
- for (const advertised of listed.tools) {
171
- if (include !== void 0 && !include.has(advertised.name)) continue;
172
- tools.push(to_fascicle_tool(client, advertised, options));
173
- }
174
- return {
175
- tools,
176
- close: async () => {
177
- if (owns_client) await client.close();
178
- }
179
- };
180
- }
181
- /**
182
- * Returns the caller's already-connected client as-is, or lazily loads the
183
- * SDK and connects a fresh client over the configured transport.
184
- */
185
- async function connect_client(config, options) {
186
- if (config.transport === "client") return config.client;
187
- const sdk = await load_client_sdk();
188
- const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO);
189
- await client.connect(build_transport(sdk, config));
190
- return client;
191
- }
192
- /**
193
- * Constructs the SDK transport matching the config: a spawned child process
194
- * for `stdio`, a Streamable HTTP connection for `http`.
195
- */
196
- function build_transport(sdk, config) {
197
- if (config.transport === "stdio") return new sdk.StdioClientTransport({
198
- command: config.command,
199
- ...config.args !== void 0 ? { args: config.args } : {},
200
- ...config.env !== void 0 ? { env: config.env } : {},
201
- ...config.cwd !== void 0 ? { cwd: config.cwd } : {}
202
- });
203
- const opts = config.headers !== void 0 ? { requestInit: { headers: config.headers } } : {};
204
- return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts);
205
- }
206
- /**
207
- * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards
208
- * to `callTool` on the shared client. Only the `Tool`'s name carries
209
- * `name_prefix`; the call, the fallback description, and the errors use the
210
- * server's own name.
211
- *
212
- * An already-aborted signal short-circuits before the wire call; otherwise the
213
- * signal is passed through so cancelling the run cancels the remote call.
214
- */
215
- function to_fascicle_tool(client, advertised, options) {
216
- const name = advertised.name;
217
- const description = advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`;
218
- return {
219
- name: `${options.name_prefix ?? ""}${name}`,
220
- description,
221
- input_schema: json_schema_to_standard(advertised.inputSchema),
222
- execute: async (input, ctx) => {
223
- if (ctx.abort.aborted) throw ctx.abort.reason instanceof Error ? ctx.abort.reason : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name });
224
- return call_result_to_output(await client.callTool({
225
- name,
226
- arguments: is_record(input) ? input : void 0
227
- }, void 0, { signal: ctx.abort }), name);
228
- }
229
- };
230
- }
231
- //#endregion
232
- //#region src/mcp/serve.ts
233
- /**
234
- * Registers a Fascicle flow as a tool on a caller-owned MCP server.
235
- *
236
- * Drives the flow with `run`, threading the per-request abort signal so an
237
- * MCP client cancellation aborts the in-flight flow, and maps the result
238
- * into a `CallToolResult`. A thrown flow becomes an `isError` result rather
239
- * than a JSON-RPC protocol error.
240
- */
241
- function serve_flow(config) {
242
- const { server, flow, name, description, input_schema, trajectory, to_result } = config;
243
- server.registerTool(name, {
244
- description,
245
- inputSchema: input_schema
246
- }, async (input, extra) => {
247
- try {
248
- return output_to_call_result(await run(flow, input, {
249
- install_signal_handlers: false,
250
- abort: extra.signal,
251
- ...trajectory !== void 0 ? { trajectory } : {}
252
- }), to_result);
253
- } catch (err) {
254
- return {
255
- isError: true,
256
- content: [{
257
- type: "text",
258
- text: err instanceof Error ? err.message : String(err)
259
- }]
260
- };
261
- }
262
- });
263
- }
264
- //#endregion
2
+ import { i as mcp_sdk_missing_error, n as mcp_client, r as mcp_error, t as serve_flow } from "./mcp-8mKK7eDY.js";
265
3
  export { json_schema_to_standard, mcp_client, mcp_error, mcp_sdk_missing_error, serve_flow };
266
-
267
- //# sourceMappingURL=mcp.js.map
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as CheckpointStore } from "./types-CPqLZOEr.js";
2
- import { B as UsageTotals, F as ToolCallRecord, G as NativeProviderAdapter, R as TurnRequest, h as GenerateResult, m as GenerateOptions, n as AssistantContentPart, p as FinishReason, u as Engine } from "./types-C23S11Kk.js";
2
+ import { B as UsageTotals, F as ToolCallRecord, G as NativeProviderAdapter, R as TurnRequest, h as GenerateResult, m as GenerateOptions, n as AssistantContentPart, p as FinishReason, u as Engine } from "./types-xYjCEd6i.js";
3
3
  //#region src/testing/assert_prefix_stable.d.ts
4
4
  /**
5
5
  * Check that every turn of every call in `requests` sends the turn before it
package/dist/testing.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { C as validate_schema, S as format_schema_issues, j as aborted_error } from "./core-Bfzt55Fl.js";
2
- import { n as to_json_schema, t as create_engine } from "./engine-BTijBDlY.js";
2
+ import { n as to_json_schema, t as create_engine } from "./engine-B5iQ3if9.js";
3
3
  import { I as schema_validation_error } from "./leading_system-CHSYz0h9.js";
4
4
  //#region src/testing/assert_prefix_stable.ts
5
5
  const ONE_AT_A_TIME = "the check reads calls that ran one at a time, so a parallel flow takes one double per branch";
@@ -40,6 +40,14 @@ type ClaudeCliProviderConfig = {
40
40
  * session. Set to `false` to opt out and start from an empty env.
41
41
  */
42
42
  readonly inherit_env?: boolean;
43
+ /**
44
+ * Variable names the subprocess never sees, whether inherited from
45
+ * `process.env` or set in a call's `env`. Under `auth_mode: 'oauth'` the
46
+ * CLI inherits everything, so this is how a host keeps its other
47
+ * providers' keys away from the Claude CLI and the commands it runs. The
48
+ * configured `api_key` still reaches the CLI under `'api_key'` and `'auto'`.
49
+ */
50
+ readonly omit_env?: ReadonlyArray<string>;
43
51
  readonly default_cwd?: string;
44
52
  readonly startup_timeout_ms?: number;
45
53
  readonly stall_timeout_ms?: number;
@@ -943,4 +951,4 @@ type Engine = {
943
951
  };
944
952
  //#endregion
945
953
  export { StepTiming as A, UsageTotals as B, ProviderConfigMap as C, RetryFailureKind as D, ResolvedModel as E, ToolCallRecord as F, NativeProviderAdapter as G, AiSdkProviderAdapter as H, ToolExecContext as I, ProviderFactory as J, ProviderAdapter as K, TruncatedTurnPolicy as L, Tool as M, ToolApprovalHandler as N, RetryPolicy as O, ToolApprovalRequest as P, ClaudeCliProviderReported as Q, TurnRequest as R, PricingTable as S, ProviderOptions as T, EffortTranslation as U, UserContentPart as V, ExternalAgentAdapter as W, RawProviderUsage as X, ProviderTransport as Y, default_normalize_usage as Z, Message as _, CacheSetting as a, PrepareStepResult as b, CostBreakdown as c, EngineConfig as d, EngineDefaults as f, GenerateTiming as g, GenerateResult as h, BedrockCredentials as i, StreamChunk as j, StepRecord as k, EffortLevel as l, GenerateOptions as m, AssistantContentPart as n, CaptureLevel as o, FinishReason as p, ProviderCapability as q, BedrockCredentialProvider as r, CapturePayload as s, AiSdkTelemetrySettings as t, Engine as u, PrepareStepContext as v, ProviderInit as w, Pricing as x, PrepareStepHook as y, TurnResult as z };
946
- //# sourceMappingURL=types-C23S11Kk.d.ts.map
954
+ //# sourceMappingURL=types-xYjCEd6i.d.ts.map