fascicle 0.8.13 → 0.9.0

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/mcp.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { G as Step, J as TrajectoryLogger } from "./index-CEj6hY9z.js";
2
- import { P as Tool } from "./index-C3NcdaSY.js";
1
+ import { G as Step, J as TrajectoryLogger } from "./index-JhJahQNi.js";
2
+ import { P as Tool } from "./index-CJRUqgsV.js";
3
3
  import { z } from "zod";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
package/dist/mcp.js CHANGED
@@ -1,4 +1,4 @@
1
- import { T as run } from "./core-BhmclJzj.js";
1
+ import { T as run } from "./core-CYpxskeT.js";
2
2
  import { z } from "zod";
3
3
  //#region src/mcp/errors.ts
4
4
  /**
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp/errors.ts","../src/mcp/internal.ts","../src/mcp/result_mapping.ts","../src/mcp/schema_bridge.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 * Small shared guards for the MCP adapter. Kept in one place so the client,\n * schema bridge, and result mapping do not each carry a copy.\n */\n\nexport function is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function as_record(value: unknown): Record<string, unknown> | undefined {\n return is_record(value) ? value : undefined\n}\n","/**\n * Mapping between MCP `CallToolResult` payloads and fascicle tool values.\n *\n * Inbound (`call_result_to_output`): a remote tool result becomes the value a\n * fascicle `Tool.execute` returns. `isError: true` is a tool-level failure, so\n * it throws rather than returns, letting the tool loop's error policy feed it\n * back to the model. Structured output is preferred over text when present.\n *\n * Outbound (`output_to_call_result`): a fascicle flow's output becomes a\n * `CallToolResult` for `serve_flow`. Objects are emitted as both a JSON text\n * part (every MCP host can read it) and `structuredContent` (typed hosts get\n * the object).\n */\n\nimport { mcp_error } from './errors.js'\nimport { as_record, is_record } from './internal.js'\n\nexport type McpToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n}\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\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\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\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\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * JSON Schema to Zod conversion for inbound MCP tools.\n *\n * An MCP tool advertises its input as JSON Schema, but a fascicle `Tool` carries\n * a Zod `input_schema` that the tool loop `safeParse`s before `execute` and the\n * engine serializes back to JSON Schema for the provider. So the converted Zod\n * must do two things at once: stay permissive enough never to reject an arg the\n * remote server would accept, and round-trip through `z.toJSONSchema` to a shape\n * the provider can fill.\n *\n * Two deliberate choices serve those goals. Objects are `looseObject` so extra\n * keys survive to the server (which re-validates and is the real authority), and\n * a freeform object maps to `z.looseObject({})` (emits `{type:\"object\"}`) rather\n * than `z.unknown()` (emits `{}`), preserving the \"takes an object\" signal. Value\n * constraints (min/max, length, pattern, format) are intentionally not modeled:\n * they add rejection risk for marginal provider benefit, and the server enforces\n * them anyway. Structure, types, enums, const, unions, and descriptions are\n * preserved; anything unrecognized degrades to `z.unknown()`.\n */\n\nimport { z } from 'zod'\nimport { as_record, is_record } from './internal.js'\n\nexport function json_schema_to_zod(schema: unknown): z.ZodType {\n try {\n return convert(schema)\n } catch {\n // An arbitrary remote schema must never crash tool discovery.\n return z.unknown()\n }\n}\n\nfunction convert(node: unknown): z.ZodType {\n const schema = as_record(node)\n if (schema === undefined) return z.unknown()\n\n const described = (inner: z.ZodType): z.ZodType => {\n const description = schema['description']\n return typeof description === 'string' ? inner.describe(description) : inner\n }\n\n if ('const' in schema) return described(literal_of(schema['const']))\n if (Array.isArray(schema['enum'])) return described(enum_of(schema['enum']))\n if (Array.isArray(schema['anyOf'])) return described(union_of(schema['anyOf']))\n if (Array.isArray(schema['oneOf'])) return described(union_of(schema['oneOf']))\n if (Array.isArray(schema['allOf'])) return described(intersection_of(schema['allOf']))\n\n const type = schema['type']\n if (Array.isArray(type)) {\n return described(union_of_types(type, schema))\n }\n if (typeof type === 'string') {\n return described(for_type(type, schema))\n }\n // No explicit type: an object with declared properties is still an object;\n // otherwise nothing structural is known, so stay permissive.\n if (is_record(schema['properties'])) return described(build_object(schema))\n return described(z.unknown())\n}\n\nfunction for_type(type: string, schema: Record<string, unknown>): z.ZodType {\n switch (type) {\n case 'object':\n return build_object(schema)\n case 'array':\n return build_array(schema)\n case 'string':\n return z.string()\n case 'number':\n return z.number()\n case 'integer':\n return z.number().int()\n case 'boolean':\n return z.boolean()\n case 'null':\n return z.null()\n default:\n return z.unknown()\n }\n}\n\nfunction build_object(schema: Record<string, unknown>): z.ZodType {\n const properties = as_record(schema['properties']) ?? {}\n const required = new Set(string_array(schema['required']))\n const shape: Record<string, z.ZodType> = {}\n for (const [key, prop] of Object.entries(properties)) {\n const child = convert(prop)\n shape[key] = required.has(key) ? child : child.optional()\n }\n return z.looseObject(shape)\n}\n\nfunction build_array(schema: Record<string, unknown>): z.ZodType {\n // A positional-tuple `items` array and a missing `items` both convert to\n // `z.unknown()`, so one permissive element type covers every case. Tuple\n // schemas are rare in MCP tools and the server re-validates them anyway.\n return z.array(convert(schema['items']))\n}\n\nfunction enum_of(values: unknown[]): z.ZodType {\n if (values.length === 0) return z.unknown()\n if (values.every((v): v is string => typeof v === 'string')) {\n return z.enum(values)\n }\n return combine_union(values.map(literal_of))\n}\n\nfunction union_of(nodes: unknown[]): z.ZodType {\n return combine_union(nodes.map(convert))\n}\n\nfunction union_of_types(types: unknown[], schema: Record<string, unknown>): z.ZodType {\n return combine_union(types.map((t) => for_type(String(t), schema)))\n}\n\nfunction intersection_of(nodes: unknown[]): z.ZodType {\n const parts = nodes.map(convert)\n if (parts.length === 0) return z.unknown()\n return parts.reduce((acc, part) => z.intersection(acc, part))\n}\n\nfunction combine_union(variants: z.ZodType[]): z.ZodType {\n const [first, second, ...rest] = variants\n if (first === undefined) return z.unknown()\n if (second === undefined) return first\n return z.union([first, second, ...rest])\n}\n\nfunction literal_of(value: unknown): z.ZodType {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return z.literal(value)\n }\n if (value === null) return z.null()\n // Object and array literals are not expressible as z.literal; accept anything.\n return z.unknown()\n}\n\nfunction string_array(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []\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\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 * `mcp_client` owns the connection lifecycle (config in, `{ tools, close }`\n * out) so callers do not have to import SDK transport classes themselves. Each\n * advertised MCP tool becomes an ordinary `Tool`: its JSON Schema is bridged to\n * Zod for the loop's `safeParse` and the provider, and `execute` forwards to\n * `callTool`, propagating the run's abort signal.\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 { mcp_error } from './errors.js'\nimport { is_record } from './internal.js'\nimport { call_result_to_output } from './result_mapping.js'\nimport { json_schema_to_zod } from './schema_bridge.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}\n\nexport type McpClientHandle = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\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()\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\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\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\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,\n description,\n input_schema: json_schema_to_zod(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 ServeFlowOptions<i, o> = {\n server: McpServer\n flow: Step<i, o>\n name: string\n description: string\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\nexport function serve_flow<i, o>(options: ServeFlowOptions<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = options\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;AACA,QAAM,QAAQ;AACd,OAAK,OAAO;;;AAIhB,IAAa,YAAb,cAA+B,MAAM;CACnC,OAAgB;CAChB;CACA,YAAY,SAAiB,WAAmC,EAAE,EAAE;AAClE,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,YAAY,SAAS;;;;;;;;;ACnB9B,SAAgB,UAAU,OAAkD;AAC1E,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAG7E,SAAgB,UAAU,OAAqD;AAC7E,QAAO,UAAU,MAAM,GAAG,QAAQ,KAAA;;;;;;;;;;;;;;;;;ACYpC,SAAgB,sBAAs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AM,GAAG,QAAQ,KAAA;IAAW,EACzD,KAAA,GACA,EAAE,QAAQ,IAAI,OAAO,CACtB,EACoC,KAAK;;EAE7C;;;;AChHH,SAAgB,WAAiB,SAAuC;CACtE,MAAM,EAAE,QAAQ,MAAM,MAAM,aAAa,cAAc,YAAY,cAAc;AACjF,QAAO,aACL,MACA;EAAE;EAAa,aAAa;EAAc,EAC1C,OAAO,OAAU,UAAU;AACzB,MAAI;AAMF,UAAO,sBALQ,MAAM,IAAI,MAAM,OAAO;IACpC,yBAAyB;IACzB,OAAO,MAAM;IACb,GAAI,eAAe,KAAA,IAAY,EAAE,YAAY,GAAG,EAAE;IACnD,CAAC,EACmC,UAAU;WACxC,KAAc;AACrB,UAAO;IACL,SAAS;IACT,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI;KAAE,CAAC;IACpF;;GAGN"}
1
+ {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp/errors.ts","../src/mcp/internal.ts","../src/mcp/result_mapping.ts","../src/mcp/schema_bridge.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 * Small shared guards for the MCP adapter. Kept in one place so the client,\n * schema bridge, and result mapping do not each carry a copy.\n */\n\nexport function is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function as_record(value: unknown): Record<string, unknown> | undefined {\n return is_record(value) ? value : undefined\n}\n","/**\n * Mapping between MCP `CallToolResult` payloads and fascicle tool values.\n *\n * Inbound (`call_result_to_output`): a remote tool result becomes the value a\n * fascicle `Tool.execute` returns. `isError: true` is a tool-level failure, so\n * it throws rather than returns, letting the tool loop's error policy feed it\n * back to the model. Structured output is preferred over text when present.\n *\n * Outbound (`output_to_call_result`): a fascicle flow's output becomes a\n * `CallToolResult` for `serve_flow`. Objects are emitted as both a JSON text\n * part (every MCP host can read it) and `structuredContent` (typed hosts get\n * the object).\n */\n\nimport { mcp_error } from './errors.js'\nimport { as_record, is_record } from './internal.js'\n\nexport type McpToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n}\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\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\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\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\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * JSON Schema to Zod conversion for inbound MCP tools.\n *\n * An MCP tool advertises its input as JSON Schema, but a fascicle `Tool` carries\n * a Zod `input_schema` that the tool loop `safeParse`s before `execute` and the\n * engine serializes back to JSON Schema for the provider. So the converted Zod\n * must do two things at once: stay permissive enough never to reject an arg the\n * remote server would accept, and round-trip through `z.toJSONSchema` to a shape\n * the provider can fill.\n *\n * Two deliberate choices serve those goals. Objects are `looseObject` so extra\n * keys survive to the server (which re-validates and is the real authority), and\n * a freeform object maps to `z.looseObject({})` (emits `{type:\"object\"}`) rather\n * than `z.unknown()` (emits `{}`), preserving the \"takes an object\" signal. Value\n * constraints (min/max, length, pattern, format) are intentionally not modeled:\n * they add rejection risk for marginal provider benefit, and the server enforces\n * them anyway. Structure, types, enums, const, unions, and descriptions are\n * preserved; anything unrecognized degrades to `z.unknown()`.\n */\n\nimport { z } from 'zod'\nimport { as_record, is_record } from './internal.js'\n\nexport function json_schema_to_zod(schema: unknown): z.ZodType {\n try {\n return convert(schema)\n } catch {\n // An arbitrary remote schema must never crash tool discovery.\n return z.unknown()\n }\n}\n\nfunction convert(node: unknown): z.ZodType {\n const schema = as_record(node)\n if (schema === undefined) return z.unknown()\n\n const described = (inner: z.ZodType): z.ZodType => {\n const description = schema['description']\n return typeof description === 'string' ? inner.describe(description) : inner\n }\n\n if ('const' in schema) return described(literal_of(schema['const']))\n if (Array.isArray(schema['enum'])) return described(enum_of(schema['enum']))\n if (Array.isArray(schema['anyOf'])) return described(union_of(schema['anyOf']))\n if (Array.isArray(schema['oneOf'])) return described(union_of(schema['oneOf']))\n if (Array.isArray(schema['allOf'])) return described(intersection_of(schema['allOf']))\n\n const type = schema['type']\n if (Array.isArray(type)) {\n return described(union_of_types(type, schema))\n }\n if (typeof type === 'string') {\n return described(for_type(type, schema))\n }\n // No explicit type: an object with declared properties is still an object;\n // otherwise nothing structural is known, so stay permissive.\n if (is_record(schema['properties'])) return described(build_object(schema))\n return described(z.unknown())\n}\n\nfunction for_type(type: string, schema: Record<string, unknown>): z.ZodType {\n switch (type) {\n case 'object':\n return build_object(schema)\n case 'array':\n return build_array(schema)\n case 'string':\n return z.string()\n case 'number':\n return z.number()\n case 'integer':\n return z.number().int()\n case 'boolean':\n return z.boolean()\n case 'null':\n return z.null()\n default:\n return z.unknown()\n }\n}\n\nfunction build_object(schema: Record<string, unknown>): z.ZodType {\n const properties = as_record(schema['properties']) ?? {}\n const required = new Set(string_array(schema['required']))\n const shape: Record<string, z.ZodType> = {}\n for (const [key, prop] of Object.entries(properties)) {\n const child = convert(prop)\n shape[key] = required.has(key) ? child : child.optional()\n }\n return z.looseObject(shape)\n}\n\nfunction build_array(schema: Record<string, unknown>): z.ZodType {\n // A positional-tuple `items` array and a missing `items` both convert to\n // `z.unknown()`, so one permissive element type covers every case. Tuple\n // schemas are rare in MCP tools and the server re-validates them anyway.\n return z.array(convert(schema['items']))\n}\n\nfunction enum_of(values: unknown[]): z.ZodType {\n if (values.length === 0) return z.unknown()\n if (values.every((v): v is string => typeof v === 'string')) {\n return z.enum(values)\n }\n return combine_union(values.map(literal_of))\n}\n\nfunction union_of(nodes: unknown[]): z.ZodType {\n return combine_union(nodes.map(convert))\n}\n\nfunction union_of_types(types: unknown[], schema: Record<string, unknown>): z.ZodType {\n return combine_union(types.map((t) => for_type(String(t), schema)))\n}\n\nfunction intersection_of(nodes: unknown[]): z.ZodType {\n const parts = nodes.map(convert)\n if (parts.length === 0) return z.unknown()\n return parts.reduce((acc, part) => z.intersection(acc, part))\n}\n\nfunction combine_union(variants: z.ZodType[]): z.ZodType {\n const [first, second, ...rest] = variants\n if (first === undefined) return z.unknown()\n if (second === undefined) return first\n return z.union([first, second, ...rest])\n}\n\nfunction literal_of(value: unknown): z.ZodType {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return z.literal(value)\n }\n if (value === null) return z.null()\n // Object and array literals are not expressible as z.literal; accept anything.\n return z.unknown()\n}\n\nfunction string_array(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []\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\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 * `mcp_client` owns the connection lifecycle (config in, `{ tools, close }`\n * out) so callers do not have to import SDK transport classes themselves. Each\n * advertised MCP tool becomes an ordinary `Tool`: its JSON Schema is bridged to\n * Zod for the loop's `safeParse` and the provider, and `execute` forwards to\n * `callTool`, propagating the run's abort signal.\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 { mcp_error } from './errors.js'\nimport { is_record } from './internal.js'\nimport { call_result_to_output } from './result_mapping.js'\nimport { json_schema_to_zod } from './schema_bridge.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}\n\nexport type McpClientHandle = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\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()\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\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\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\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,\n description,\n input_schema: json_schema_to_zod(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 ServeFlowOptions<i, o> = {\n server: McpServer\n flow: Step<i, o>\n name: string\n description: string\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\nexport function serve_flow<i, o>(options: ServeFlowOptions<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = options\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;;;;;;;ACrBA,SAAgB,UAAU,OAAkD;CAC1E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,UAAU,OAAqD;CAC7E,OAAO,UAAU,KAAK,IAAI,QAAQ,KAAA;AACpC;;;;;;;;;;;;;;;;ACWA,SAAgB,sBAAsB,QAAiB,WAA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AAI,MAAM,SACV,IAAI,UAAU,YAAY,KAAK,6BAA6B,EAAE,WAAW,KAAK,CAAC;GAOrF,OAAO,sBAAsB,MALR,OAAO,SAC1B;IAAE;IAAM,WAAW,UAAU,KAAK,IAAI,QAAQ,KAAA;GAAU,GACxD,KAAA,GACA,EAAE,QAAQ,IAAI,MAAM,CACtB,GACqC,IAAI;EAC3C;CACF;AACF;;;ACjHA,SAAgB,WAAiB,SAAuC;CACtE,MAAM,EAAE,QAAQ,MAAM,MAAM,aAAa,cAAc,YAAY,cAAc;CACjF,OAAO,aACL,MACA;EAAE;EAAa,aAAa;CAAa,GACzC,OAAO,OAAU,UAAU;EACzB,IAAI;GAMF,OAAO,sBAAsB,MALR,IAAI,MAAM,OAAO;IACpC,yBAAyB;IACzB,OAAO,MAAM;IACb,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;GACnD,CAAC,GACoC,SAAS;EAChD,SAAS,KAAc;GACrB,OAAO;IACL,SAAS;IACT,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;IAAE,CAAC;GACpF;EACF;CACF,CACF;AACF"}
package/dist/stdio.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { G as Step, J as TrajectoryLogger } from "./index-CEj6hY9z.js";
1
+ import { G as Step, J as TrajectoryLogger } from "./index-JhJahQNi.js";
2
2
  import { z } from "zod";
3
3
 
4
4
  //#region src/stdio/execute_stdio.d.ts
package/dist/stdio.js CHANGED
@@ -1,5 +1,5 @@
1
- import { T as run } from "./core-BhmclJzj.js";
2
- import { r as stderr_logger } from "./adapters-DdUx-_b3.js";
1
+ import { T as run } from "./core-CYpxskeT.js";
2
+ import { r as stderr_logger } from "./adapters-Dbx3M8m-.js";
3
3
  import { text } from "node:stream/consumers";
4
4
  //#region src/stdio/execute_stdio.ts
5
5
  async function execute_stdio(flow, options, io) {
package/dist/stdio.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"stdio.js","names":[],"sources":["../src/stdio/execute_stdio.ts","../src/stdio/run_stdio.ts"],"sourcesContent":["/**\n * The stdio agent contract, minus the process.\n *\n * `execute_stdio` is everything `run_stdio` does (read, parse, validate, run,\n * validate, serialize, dispose), expressed over an injected `StdioIo` and\n * returning a `StdioOutcome` instead of touching `process.*` or exiting. The\n * split keeps the contract's branching unit-testable; the thin glue in\n * `run_stdio.ts` owns the real streams and the exit.\n *\n * The governing invariant: code 0 if and only if stdout carries an\n * authoritative result. That is why the engine is disposed before the output\n * is written (a teardown failure on the success path yields code 1 and no\n * stdout) and why every failure class short-circuits before `write_output`.\n * Code 1 means the flow did not produce a result (including a forwarded\n * SIGINT/SIGTERM aborting the run, or a failed delivery); code 2 means the\n * contract itself was violated (unparseable stdin, schema mismatch in either\n * direction, unserializable result).\n */\n\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { stderr_logger } from '#adapters'\n\nexport type RunStdioOptions<i, o> = {\n readonly input_schema?: z.ZodType<i>\n readonly output_schema?: z.ZodType<o>\n // Structural on purpose: anything with an async dispose qualifies, and the\n // stdio module never imports the engine layer.\n readonly engine?: { readonly dispose: () => Promise<void> }\n readonly trajectory?: TrajectoryLogger\n readonly abort?: AbortSignal\n}\n\nexport type StdioFailure = {\n readonly error: string\n readonly stage?:\n | 'read'\n | 'parse'\n | 'validate_input'\n | 'run'\n | 'validate_output'\n | 'serialize'\n | 'write'\n | 'dispose'\n readonly cause?: unknown\n}\n\nexport type StdioOutcome =\n | { readonly code: 0 }\n | { readonly code: 1 | 2; readonly failure: StdioFailure }\n\nexport type StdioIo = {\n readonly read_input: () => Promise<string>\n // Resolves once the bytes are flushed to the OS, so the caller may exit.\n readonly write_output: (text: string) => Promise<void>\n readonly error_stream: { write(chunk: string): unknown }\n}\n\nexport async function execute_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<StdioOutcome> {\n const produced = await produce_output(flow, options, io)\n const dispose_failure = await dispose_engine(options.engine)\n if (produced.kind === 'failed') return { code: produced.code, failure: produced.failure }\n if (dispose_failure !== null) return { code: 1, failure: dispose_failure }\n try {\n await io.write_output(`${produced.json}\\n`)\n } catch (err) {\n return { code: 1, failure: make_failure('write', err) }\n }\n return { code: 0 }\n}\n\ntype ProduceResult =\n | { readonly kind: 'ok'; readonly json: string }\n | { readonly kind: 'failed'; readonly code: 1 | 2; readonly failure: StdioFailure }\n\nasync function produce_output<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<ProduceResult> {\n let raw: string\n try {\n raw = await io.read_input()\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('read', err) }\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('parse', err) }\n }\n\n let input: i\n if (options.input_schema !== undefined) {\n const checked = options.input_schema.safeParse(parsed)\n if (!checked.success) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'input failed schema validation',\n stage: 'validate_input',\n cause: to_json_safe(checked.error.issues),\n },\n }\n }\n input = checked.data\n } else {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n input = parsed as i\n }\n\n const trajectory = options.trajectory ?? stderr_logger({ stream: io.error_stream })\n\n let result: o\n try {\n result = await run(flow, input, {\n trajectory,\n ...(options.abort !== undefined ? { abort: options.abort } : {}),\n })\n } catch (err) {\n return { kind: 'failed', code: 1, failure: make_failure('run', err) }\n }\n\n let output: unknown = result\n if (options.output_schema !== undefined) {\n const checked = options.output_schema.safeParse(result)\n if (!checked.success) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'flow result failed schema validation',\n stage: 'validate_output',\n cause: to_json_safe(checked.error.issues),\n },\n }\n }\n output = checked.data\n }\n\n let json: string | undefined\n try {\n json = JSON.stringify(output)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('serialize', err) }\n }\n if (json === undefined) {\n return {\n kind: 'failed',\n code: 2,\n failure: { error: 'flow result is not JSON-serializable', stage: 'serialize' },\n }\n }\n return { kind: 'ok', json }\n}\n\nasync function dispose_engine(\n engine: RunStdioOptions<never, never>['engine'],\n): Promise<StdioFailure | null> {\n if (engine === undefined) return null\n try {\n await engine.dispose()\n return null\n } catch (err) {\n return make_failure('dispose', err)\n }\n}\n\nfunction make_failure(stage: NonNullable<StdioFailure['stage']>, err: unknown): StdioFailure {\n const cause = safe_cause(err)\n return {\n error: err instanceof Error ? err.message : String(err),\n stage,\n ...(cause !== undefined ? { cause } : {}),\n }\n}\n\nfunction safe_cause(err: unknown): unknown {\n if (err instanceof Error) {\n const path = Reflect.get(err, 'path')\n return {\n name: err.name,\n message: err.message,\n ...(Array.isArray(path) ? { path: to_json_safe(path) } : {}),\n }\n }\n return to_json_safe(err)\n}\n\n// The glue serializes the failure with JSON.stringify; cause must never make\n// that throw (circular refs, BigInt) or silently vanish (undefined-only).\nfunction to_json_safe(value: unknown): unknown {\n try {\n const json = JSON.stringify(value)\n if (json === undefined) return undefined\n return JSON.parse(json) as unknown\n } catch {\n return undefined\n }\n}\n","/**\n * Process glue for the stdio agent contract.\n *\n * Binds `execute_stdio` to the real process: stdin to EOF in, exactly one JSON\n * document on stdout out, trajectory on stderr, exit code as the verdict\n * (0 = result on stdout is authoritative, 1 = flow failure, 2 = contract\n * violation). On a non-zero exit the LAST stderr line is the `StdioFailure`\n * as a single JSON object, so parents that want machine-readable detail take\n * the tail line.\n *\n * Final writes await the write callback before `process.exit`: on pipes,\n * exiting with buffered data truncates it, and a large JSON result is exactly\n * the risk case. Signal handlers stay at the runner's default (installed): a\n * single-shot child must die when the parent forwards SIGINT.\n *\n * Excluded from mutation testing as process/IO glue (see stryker.config.mjs);\n * the spawn-based contract tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { text } from 'node:stream/consumers'\nimport type { Step } from '#core'\nimport { execute_stdio } from './execute_stdio.js'\nimport type { RunStdioOptions } from './execute_stdio.js'\n\nexport async function run_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o> = {},\n): Promise<void> {\n const outcome = await execute_stdio(flow, options, {\n read_input: () => text(process.stdin),\n write_output: (chunk) => write_flushed(process.stdout, chunk),\n error_stream: process.stderr,\n })\n if (outcome.code !== 0) {\n try {\n await write_flushed(process.stderr, `${JSON.stringify(outcome.failure)}\\n`)\n } catch {\n // stderr is gone; the exit code still carries the verdict.\n }\n }\n process.exit(outcome.code)\n}\n\nfunction write_flushed(stream: NodeJS.WriteStream, chunk: string): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.write(chunk, (err) => {\n if (err) reject(err)\n else resolve()\n })\n })\n}\n"],"mappings":";;;;AA2DA,eAAsB,cACpB,MACA,SACA,IACuB;CACvB,MAAM,WAAW,MAAM,eAAe,MAAM,SAAS,GAAG;CACxD,MAAM,kBAAkB,MAAM,eAAe,QAAQ,OAAO;AAC5D,KAAI,SAAS,SAAS,SAAU,QAAO;EAAE,MAAM,SAAS;EAAM,SAAS,SAAS;EAAS;AACzF,KAAI,oBAAoB,KAAM,QAAO;EAAE,MAAM;EAAG,SAAS;EAAiB;AAC1E,KAAI;AACF,QAAM,GAAG,aAAa,GAAG,SAAS,KAAK,IAAI;UACpC,KAAK;AACZ,SAAO;GAAE,MAAM;GAAG,SAAS,aAAa,SAAS,IAAI;GAAE;;AAEzD,QAAO,EAAE,MAAM,GAAG;;AAOpB,eAAe,eACb,MACA,SACA,IACwB;CACxB,IAAI;AACJ,KAAI;AACF,QAAM,MAAM,GAAG,YAAY;UACpB,KAAK;AACZ,SAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,QAAQ,IAAI;GAAE;;CAGxE,IAAI;AACJ,KAAI;AACF,WAAS,KAAK,MAAM,IAAI;UACjB,KAAK;AACZ,SAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,SAAS,IAAI;GAAE;;CAGzE,IAAI;A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io.ts"],"sourcesContent":["/**\n * The stdio agent contract, minus the process.\n *\n * `execute_stdio` is everything `run_stdio` does (read, parse, validate, run,\n * validate, serialize, dispose), expressed over an injected `StdioIo` and\n * returning a `StdioOutcome` instead of touching `process.*` or exiting. The\n * split keeps the contract's branching unit-testable; the thin glue in\n * `run_stdio.ts` owns the real streams and the exit.\n *\n * The governing invariant: code 0 if and only if stdout carries an\n * authoritative result. That is why the engine is disposed before the output\n * is written (a teardown failure on the success path yields code 1 and no\n * stdout) and why every failure class short-circuits before `write_output`.\n * Code 1 means the flow did not produce a result (including a forwarded\n * SIGINT/SIGTERM aborting the run, or a failed delivery); code 2 means the\n * contract itself was violated (unparseable stdin, schema mismatch in either\n * direction, unserializable result).\n */\n\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { stderr_logger } from '#adapters'\n\nexport type RunStdioOptions<i, o> = {\n readonly input_schema?: z.ZodType<i>\n readonly output_schema?: z.ZodType<o>\n // Structural on purpose: anything with an async dispose qualifies, and the\n // stdio module never imports the engine layer.\n readonly engine?: { readonly dispose: () => Promise<void> }\n readonly trajectory?: TrajectoryLogger\n readonly abort?: AbortSignal\n}\n\nexport type StdioFailure = {\n readonly error: string\n readonly stage?:\n | 'read'\n | 'parse'\n | 'validate_input'\n | 'run'\n | 'validate_output'\n | 'serialize'\n | 'write'\n | 'dispose'\n readonly cause?: unknown\n}\n\nexport type StdioOutcome =\n | { readonly code: 0 }\n | { readonly code: 1 | 2; readonly failure: StdioFailure }\n\nexport type StdioIo = {\n readonly read_input: () => Promise<string>\n // Resolves once the bytes are flushed to the OS, so the caller may exit.\n readonly write_output: (text: string) => Promise<void>\n readonly error_stream: { write(chunk: string): unknown }\n}\n\nexport async function execute_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<StdioOutcome> {\n const produced = await produce_output(flow, options, io)\n const dispose_failure = await dispose_engine(options.engine)\n if (produced.kind === 'failed') return { code: produced.code, failure: produced.failure }\n if (dispose_failure !== null) return { code: 1, failure: dispose_failure }\n try {\n await io.write_output(`${produced.json}\\n`)\n } catch (err) {\n return { code: 1, failure: make_failure('write', err) }\n }\n return { code: 0 }\n}\n\ntype ProduceResult =\n | { readonly kind: 'ok'; readonly json: string }\n | { readonly kind: 'failed'; readonly code: 1 | 2; readonly failure: StdioFailure }\n\nasync function produce_output<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<ProduceResult> {\n let raw: string\n try {\n raw = await io.read_input()\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('read', err) }\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('parse', err) }\n }\n\n let input: i\n if (options.input_schema !== undefined) {\n const checked = options.input_schema.safeParse(parsed)\n if (!checked.success) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'input failed schema validation',\n stage: 'validate_input',\n cause: to_json_safe(checked.error.issues),\n },\n }\n }\n input = checked.data\n } else {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n input = parsed as i\n }\n\n const trajectory = options.trajectory ?? stderr_logger({ stream: io.error_stream })\n\n let result: o\n try {\n result = await run(flow, input, {\n trajectory,\n ...(options.abort !== undefined ? { abort: options.abort } : {}),\n })\n } catch (err) {\n return { kind: 'failed', code: 1, failure: make_failure('run', err) }\n }\n\n let output: unknown = result\n if (options.output_schema !== undefined) {\n const checked = options.output_schema.safeParse(result)\n if (!checked.success) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'flow result failed schema validation',\n stage: 'validate_output',\n cause: to_json_safe(checked.error.issues),\n },\n }\n }\n output = checked.data\n }\n\n let json: string | undefined\n try {\n json = JSON.stringify(output)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('serialize', err) }\n }\n if (json === undefined) {\n return {\n kind: 'failed',\n code: 2,\n failure: { error: 'flow result is not JSON-serializable', stage: 'serialize' },\n }\n }\n return { kind: 'ok', json }\n}\n\nasync function dispose_engine(\n engine: RunStdioOptions<never, never>['engine'],\n): Promise<StdioFailure | null> {\n if (engine === undefined) return null\n try {\n await engine.dispose()\n return null\n } catch (err) {\n return make_failure('dispose', err)\n }\n}\n\nfunction make_failure(stage: NonNullable<StdioFailure['stage']>, err: unknown): StdioFailure {\n const cause = safe_cause(err)\n return {\n error: err instanceof Error ? err.message : String(err),\n stage,\n ...(cause !== undefined ? { cause } : {}),\n }\n}\n\nfunction safe_cause(err: unknown): unknown {\n if (err instanceof Error) {\n const path = Reflect.get(err, 'path')\n return {\n name: err.name,\n message: err.message,\n ...(Array.isArray(path) ? { path: to_json_safe(path) } : {}),\n }\n }\n return to_json_safe(err)\n}\n\n// The glue serializes the failure with JSON.stringify; cause must never make\n// that throw (circular refs, BigInt) or silently vanish (undefined-only).\nfunction to_json_safe(value: unknown): unknown {\n try {\n const json = JSON.stringify(value)\n if (json === undefined) return undefined\n return JSON.parse(json) as unknown\n } catch {\n return undefined\n }\n}\n","/**\n * Process glue for the stdio agent contract.\n *\n * Binds `execute_stdio` to the real process: stdin to EOF in, exactly one JSON\n * document on stdout out, trajectory on stderr, exit code as the verdict\n * (0 = result on stdout is authoritative, 1 = flow failure, 2 = contract\n * violation). On a non-zero exit the LAST stderr line is the `StdioFailure`\n * as a single JSON object, so parents that want machine-readable detail take\n * the tail line.\n *\n * Final writes await the write callback before `process.exit`: on pipes,\n * exiting with buffered data truncates it, and a large JSON result is exactly\n * the risk case. Signal handlers stay at the runner's default (installed): a\n * single-shot child must die when the parent forwards SIGINT.\n *\n * Excluded from mutation testing as process/IO glue (see stryker.config.mjs);\n * the spawn-based contract tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { text } from 'node:stream/consumers'\nimport type { Step } from '#core'\nimport { execute_stdio } from './execute_stdio.js'\nimport type { RunStdioOptions } from './execute_stdio.js'\n\nexport async function run_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o> = {},\n): Promise<void> {\n const outcome = await execute_stdio(flow, options, {\n read_input: () => text(process.stdin),\n write_output: (chunk) => write_flushed(process.stdout, chunk),\n error_stream: process.stderr,\n })\n if (outcome.code !== 0) {\n try {\n await write_flushed(process.stderr, `${JSON.stringify(outcome.failure)}\\n`)\n } catch {\n // stderr is gone; the exit code still carries the verdict.\n }\n }\n process.exit(outcome.code)\n}\n\nfunction write_flushed(stream: NodeJS.WriteStream, chunk: string): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.write(chunk, (err) => {\n if (err) reject(err)\n else resolve()\n })\n })\n}\n"],"mappings":";;;;AA2DA,eAAsB,cACpB,MACA,SACA,IACuB;CACvB,MAAM,WAAW,MAAM,eAAe,MAAM,SAAS,EAAE;CACvD,MAAM,kBAAkB,MAAM,eAAe,QAAQ,MAAM;CAC3D,IAAI,SAAS,SAAS,UAAU,OAAO;EAAE,MAAM,SAAS;EAAM,SAAS,SAAS;CAAQ;CACxF,IAAI,oBAAoB,MAAM,OAAO;EAAE,MAAM;EAAG,SAAS;CAAgB;CACzE,IAAI;EACF,MAAM,GAAG,aAAa,GAAG,SAAS,KAAK,GAAG;CAC5C,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAG,SAAS,aAAa,SAAS,GAAG;EAAE;CACxD;CACA,OAAO,EAAE,MAAM,EAAE;AACnB;AAMA,eAAe,eACb,MACA,SACA,IACwB;CACxB,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,GAAG,WAAW;CAC5B,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,QAAQ,GAAG;EAAE;CACvE;CAEA,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,SAAS,GAAG;EAAE;CACxE;CAEA,IAAI;CACJ,IAAI,QAAQ,iBAAiB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AC;AACH"}
package/dist/ui.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { q as TrajectoryEvent } from "./index-JhJahQNi.js";
2
+ import { UIMessageChunk } from "ai";
3
+ import { ServerResponse } from "node:http";
4
+
5
+ //#region src/ui/to_ui_message_stream.d.ts
6
+ /**
7
+ * The structural shape of a `run.stream(...)` handle. Typed structurally rather
8
+ * than importing the core `StreamingRunHandle` so this module depends on no
9
+ * core value and a caller can pass `run.stream(...)` directly.
10
+ */
11
+ type RunStreamLike = {
12
+ readonly events: AsyncIterable<TrajectoryEvent>;
13
+ readonly result: Promise<unknown>;
14
+ };
15
+ type ToUiStreamOptions = {
16
+ /** Map a thrown run error to the text of an `error` part. */readonly on_error?: (error: unknown) => string;
17
+ };
18
+ /**
19
+ * Per-stream state: which text/reasoning blocks are open (so `*-start` fires
20
+ * once and `*-end` closes them) and the tool name for each in-flight call (so
21
+ * `tool-input-available` can echo it after only the id arrives at close).
22
+ */
23
+ type UiMapperState = {
24
+ readonly open_text: Set<number>;
25
+ readonly open_reasoning: Set<number>;
26
+ readonly tool_names: Map<string, string>;
27
+ };
28
+ declare function create_ui_mapper_state(): UiMapperState;
29
+ declare function close_open_blocks(state: UiMapperState): UIMessageChunk[];
30
+ /**
31
+ * Map one run event to zero or more UI message chunks, advancing `state`.
32
+ * Non-`model_chunk` events (spans, cost, user emits) yield nothing in v1.
33
+ */
34
+ declare function to_ui_message_chunks(event: TrajectoryEvent, state: UiMapperState): UIMessageChunk[];
35
+ /**
36
+ * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint
37
+ * can return directly.
38
+ */
39
+ declare function to_ui_message_response(handle: RunStreamLike, options?: ToUiStreamOptions): Response;
40
+ /**
41
+ * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for
42
+ * `node:http` servers that hold a `ServerResponse` rather than returning a
43
+ * web `Response`.
44
+ */
45
+ declare function pipe_ui_message_stream_to_response(handle: RunStreamLike, response: ServerResponse, options?: ToUiStreamOptions): void;
46
+ //#endregion
47
+ export { type RunStreamLike, type ToUiStreamOptions, type UiMapperState, close_open_blocks, create_ui_mapper_state, pipe_ui_message_stream_to_response, to_ui_message_chunks, to_ui_message_response };
48
+ //# sourceMappingURL=ui.d.ts.map
package/dist/ui.js ADDED
@@ -0,0 +1,175 @@
1
+ import { createUIMessageStream, createUIMessageStreamResponse, pipeUIMessageStreamToResponse } from "ai";
2
+ //#region src/ui/to_ui_message_stream.ts
3
+ /**
4
+ * fascicle/ui — bridge a run's event stream to the AI SDK "UI message stream".
5
+ *
6
+ * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,
7
+ * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.
8
+ * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a
9
+ * fascicle flow can back a `useChat` endpoint rendered by AI Elements /
10
+ * Streamdown, with zero bespoke glue.
11
+ *
12
+ * It is the outbound inverse of the engine's inbound provider->StreamChunk
13
+ * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the
14
+ * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this
15
+ * file only translates chunk shapes and manages open text/reasoning blocks.
16
+ *
17
+ * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk
18
+ * vocabulary has no generated-file kind (those provider parts drop at the
19
+ * inbound mapping), so there is nothing here to translate them from.
20
+ */
21
+ function create_ui_mapper_state() {
22
+ return {
23
+ open_text: /* @__PURE__ */ new Set(),
24
+ open_reasoning: /* @__PURE__ */ new Set(),
25
+ tool_names: /* @__PURE__ */ new Map()
26
+ };
27
+ }
28
+ function text_id(step_index) {
29
+ return `text-${step_index}`;
30
+ }
31
+ function reasoning_id(step_index) {
32
+ return `reasoning-${step_index}`;
33
+ }
34
+ function close_step_blocks(step_index, state) {
35
+ const parts = [];
36
+ if (state.open_text.delete(step_index)) parts.push({
37
+ type: "text-end",
38
+ id: text_id(step_index)
39
+ });
40
+ if (state.open_reasoning.delete(step_index)) parts.push({
41
+ type: "reasoning-end",
42
+ id: reasoning_id(step_index)
43
+ });
44
+ return parts;
45
+ }
46
+ function close_open_blocks(state) {
47
+ const parts = [];
48
+ for (const step_index of state.open_text) parts.push({
49
+ type: "text-end",
50
+ id: text_id(step_index)
51
+ });
52
+ for (const step_index of state.open_reasoning) parts.push({
53
+ type: "reasoning-end",
54
+ id: reasoning_id(step_index)
55
+ });
56
+ state.open_text.clear();
57
+ state.open_reasoning.clear();
58
+ return parts;
59
+ }
60
+ function map_chunk(chunk, state) {
61
+ switch (chunk.kind) {
62
+ case "text": {
63
+ const id = text_id(chunk.step_index);
64
+ const parts = [];
65
+ if (!state.open_text.has(chunk.step_index)) {
66
+ state.open_text.add(chunk.step_index);
67
+ parts.push({
68
+ type: "text-start",
69
+ id
70
+ });
71
+ }
72
+ parts.push({
73
+ type: "text-delta",
74
+ id,
75
+ delta: chunk.text
76
+ });
77
+ return parts;
78
+ }
79
+ case "reasoning": {
80
+ const id = reasoning_id(chunk.step_index);
81
+ const parts = [];
82
+ if (!state.open_reasoning.has(chunk.step_index)) {
83
+ state.open_reasoning.add(chunk.step_index);
84
+ parts.push({
85
+ type: "reasoning-start",
86
+ id
87
+ });
88
+ }
89
+ parts.push({
90
+ type: "reasoning-delta",
91
+ id,
92
+ delta: chunk.text
93
+ });
94
+ return parts;
95
+ }
96
+ case "tool_call_start":
97
+ state.tool_names.set(chunk.id, chunk.name);
98
+ return [{
99
+ type: "tool-input-start",
100
+ toolCallId: chunk.id,
101
+ toolName: chunk.name
102
+ }];
103
+ case "tool_call_input_delta": return [{
104
+ type: "tool-input-delta",
105
+ toolCallId: chunk.id,
106
+ inputTextDelta: chunk.delta
107
+ }];
108
+ case "tool_call_end": return [{
109
+ type: "tool-input-available",
110
+ toolCallId: chunk.id,
111
+ toolName: state.tool_names.get(chunk.id) ?? "",
112
+ input: chunk.input
113
+ }];
114
+ case "tool_result": return chunk.error !== void 0 ? [{
115
+ type: "tool-output-error",
116
+ toolCallId: chunk.id,
117
+ errorText: chunk.error.message
118
+ }] : [{
119
+ type: "tool-output-available",
120
+ toolCallId: chunk.id,
121
+ output: chunk.output
122
+ }];
123
+ case "step_finish": return close_step_blocks(chunk.step_index, state);
124
+ case "finish": return close_open_blocks(state);
125
+ default: return [];
126
+ }
127
+ }
128
+ function as_stream_chunk(value) {
129
+ if (typeof value !== "object" || value === null) return void 0;
130
+ if (typeof Reflect.get(value, "kind") !== "string") return void 0;
131
+ return value;
132
+ }
133
+ /**
134
+ * Map one run event to zero or more UI message chunks, advancing `state`.
135
+ * Non-`model_chunk` events (spans, cost, user emits) yield nothing in v1.
136
+ */
137
+ function to_ui_message_chunks(event, state) {
138
+ if (event.kind !== "model_chunk") return [];
139
+ const chunk = as_stream_chunk(event["chunk"]);
140
+ return chunk === void 0 ? [] : map_chunk(chunk, state);
141
+ }
142
+ function build_stream(handle, options) {
143
+ const on_error = options.on_error;
144
+ return createUIMessageStream({
145
+ execute: async ({ writer }) => {
146
+ const state = create_ui_mapper_state();
147
+ for await (const event of handle.events) for (const part of to_ui_message_chunks(event, state)) writer.write(part);
148
+ for (const part of close_open_blocks(state)) writer.write(part);
149
+ await handle.result;
150
+ },
151
+ ...on_error !== void 0 ? { onError: on_error } : {}
152
+ });
153
+ }
154
+ /**
155
+ * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint
156
+ * can return directly.
157
+ */
158
+ function to_ui_message_response(handle, options = {}) {
159
+ return createUIMessageStreamResponse({ stream: build_stream(handle, options) });
160
+ }
161
+ /**
162
+ * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for
163
+ * `node:http` servers that hold a `ServerResponse` rather than returning a
164
+ * web `Response`.
165
+ */
166
+ function pipe_ui_message_stream_to_response(handle, response, options = {}) {
167
+ pipeUIMessageStreamToResponse({
168
+ response,
169
+ stream: build_stream(handle, options)
170
+ });
171
+ }
172
+ //#endregion
173
+ export { close_open_blocks, create_ui_mapper_state, pipe_ui_message_stream_to_response, to_ui_message_chunks, to_ui_message_response };
174
+
175
+ //# sourceMappingURL=ui.js.map
package/dist/ui.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ui.js","names":[],"sources":["../src/ui/to_ui_message_stream.ts"],"sourcesContent":["/**\n * fascicle/ui — bridge a run's event stream to the AI SDK \"UI message stream\".\n *\n * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,\n * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.\n * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a\n * fascicle flow can back a `useChat` endpoint rendered by AI Elements /\n * Streamdown, with zero bespoke glue.\n *\n * It is the outbound inverse of the engine's inbound provider->StreamChunk\n * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the\n * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this\n * file only translates chunk shapes and manages open text/reasoning blocks.\n *\n * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk\n * vocabulary has no generated-file kind (those provider parts drop at the\n * inbound mapping), so there is nothing here to translate them from.\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n pipeUIMessageStreamToResponse,\n} from 'ai'\nimport type { UIMessageChunk } from 'ai'\nimport type { ServerResponse } from 'node:http'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\n\n/**\n * The structural shape of a `run.stream(...)` handle. Typed structurally rather\n * than importing the core `StreamingRunHandle` so this module depends on no\n * core value and a caller can pass `run.stream(...)` directly.\n */\nexport type RunStreamLike = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<unknown>\n}\n\nexport type ToUiStreamOptions = {\n /** Map a thrown run error to the text of an `error` part. */\n readonly on_error?: (error: unknown) => string\n}\n\n/**\n * Per-stream state: which text/reasoning blocks are open (so `*-start` fires\n * once and `*-end` closes them) and the tool name for each in-flight call (so\n * `tool-input-available` can echo it after only the id arrives at close).\n */\nexport type UiMapperState = {\n readonly open_text: Set<number>\n readonly open_reasoning: Set<number>\n readonly tool_names: Map<string, string>\n}\n\nexport function create_ui_mapper_state(): UiMapperState {\n return { open_text: new Set(), open_reasoning: new Set(), tool_names: new Map() }\n}\n\nfunction text_id(step_index: number): string {\n return `text-${step_index}`\n}\n\nfunction reasoning_id(step_index: number): string {\n return `reasoning-${step_index}`\n}\n\nfunction close_step_blocks(step_index: number, state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n if (state.open_text.delete(step_index)) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n if (state.open_reasoning.delete(step_index)) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n return parts\n}\n\nexport function close_open_blocks(state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n for (const step_index of state.open_text) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n for (const step_index of state.open_reasoning) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n state.open_text.clear()\n state.open_reasoning.clear()\n return parts\n}\n\nfunction map_chunk(chunk: StreamChunk, state: UiMapperState): UIMessageChunk[] {\n switch (chunk.kind) {\n case 'text': {\n const id = text_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_text.has(chunk.step_index)) {\n state.open_text.add(chunk.step_index)\n parts.push({ type: 'text-start', id })\n }\n parts.push({ type: 'text-delta', id, delta: chunk.text })\n return parts\n }\n case 'reasoning': {\n const id = reasoning_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_reasoning.has(chunk.step_index)) {\n state.open_reasoning.add(chunk.step_index)\n parts.push({ type: 'reasoning-start', id })\n }\n parts.push({ type: 'reasoning-delta', id, delta: chunk.text })\n return parts\n }\n case 'tool_call_start': {\n state.tool_names.set(chunk.id, chunk.name)\n return [{ type: 'tool-input-start', toolCallId: chunk.id, toolName: chunk.name }]\n }\n case 'tool_call_input_delta':\n return [{ type: 'tool-input-delta', toolCallId: chunk.id, inputTextDelta: chunk.delta }]\n case 'tool_call_end':\n return [\n {\n type: 'tool-input-available',\n toolCallId: chunk.id,\n toolName: state.tool_names.get(chunk.id) ?? '',\n input: chunk.input,\n },\n ]\n case 'tool_result':\n return chunk.error !== undefined\n ? [{ type: 'tool-output-error', toolCallId: chunk.id, errorText: chunk.error.message }]\n : [{ type: 'tool-output-available', toolCallId: chunk.id, output: chunk.output }]\n case 'step_finish':\n return close_step_blocks(chunk.step_index, state)\n case 'finish':\n return close_open_blocks(state)\n default:\n return []\n }\n}\n\nfunction as_stream_chunk(value: unknown): StreamChunk | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const kind = Reflect.get(value, 'kind')\n if (typeof kind !== 'string') return undefined\n // The value rode a loose TrajectoryEvent bag; model_call only records real\n // StreamChunks under `chunk`, and map_chunk narrows on `kind`, so treating it\n // as a StreamChunk is sound. Unknown kinds fall through to `[]`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as StreamChunk\n}\n\n/**\n * Map one run event to zero or more UI message chunks, advancing `state`.\n * Non-`model_chunk` events (spans, cost, user emits) yield nothing in v1.\n */\nexport function to_ui_message_chunks(\n event: TrajectoryEvent,\n state: UiMapperState,\n): UIMessageChunk[] {\n if (event.kind !== 'model_chunk') return []\n const chunk = as_stream_chunk(event['chunk'])\n return chunk === undefined ? [] : map_chunk(chunk, state)\n}\n\nfunction build_stream(\n handle: RunStreamLike,\n options: ToUiStreamOptions,\n): ReadableStream<UIMessageChunk> {\n const on_error = options.on_error\n return createUIMessageStream({\n execute: async ({ writer }) => {\n const state = create_ui_mapper_state()\n for await (const event of handle.events) {\n for (const part of to_ui_message_chunks(event, state)) writer.write(part)\n }\n for (const part of close_open_blocks(state)) writer.write(part)\n await handle.result\n },\n ...(on_error !== undefined ? { onError: on_error } : {}),\n })\n}\n\n/**\n * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint\n * can return directly.\n */\nexport function to_ui_message_response(\n handle: RunStreamLike,\n options: ToUiStreamOptions = {},\n): Response {\n return createUIMessageStreamResponse({ stream: build_stream(handle, options) })\n}\n\n/**\n * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for\n * `node:http` servers that hold a `ServerResponse` rather than returning a\n * web `Response`.\n */\nexport function pipe_ui_message_stream_to_response(\n handle: RunStreamLike,\n response: ServerResponse,\n options: ToUiStreamOptions = {},\n): void {\n pipeUIMessageStreamToResponse({ response, stream: build_stream(handle, options) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,IAAI,IAAI;CAAE;AAClF;AAEA,SAAS,QAAQ,YAA4B;CAC3C,OAAO,QAAQ;AACjB;AAEA,SAAS,aAAa,YAA4B;CAChD,OAAO,aAAa;AACtB;AAEA,SAAS,kBAAkB,YAAoB,OAAwC;CACrF,MAAM,QAA0B,CAAC;CACjC,IAAI,MAAM,UAAU,OAAO,UAAU,GACnC,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,IAAI,MAAM,eAAe,OAAO,UAAU,GACxC,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,aAAa,UAAU;CAAE,CAAC;CAEpE,OAAO;AACT;AAEA,SAAgB,kBAAkB,OAAwC;CACxE,MAAM,QAA0B,CAAC;CACjC,KAAK,MAAM,cAAc,MAAM,WAC7B,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,KAAK,MAAM,cAAc,MAAM,gBAC7B,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,aAAa,UAAU;CAAE,CAAC;CAEpE,MAAM,UAAU,MAAM;CACtB,MAAM,eAAe,MAAM;CAC3B,OAAO;AACT;AAEA,SAAS,UAAU,OAAoB,OAAwC;CAC7E,QAAQ,MAAM,MAAd;EACE,KAAK,QAAQ;GACX,MAAM,KAAK,QAAQ,MAAM,UA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AC;CACZ;AACF;AAEA,SAAS,gBAAgB,OAAyC;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CAExD,IAAI,OADS,QAAQ,IAAI,OAAO,MAClB,MAAM,UAAU,OAAO,KAAA;CAKrC,OAAO;AACT;;;;;AAMA,SAAgB,qBACd,OACA,OACkB;CAClB,IAAI,MAAM,SAAS,eAAe,OAAO,CAAC;CAC1C,MAAM,QAAQ,gBAAgB,MAAM,QAAQ;CAC5C,OAAO,UAAU,KAAA,IAAY,CAAC,IAAI,UAAU,OAAO,KAAK;AAC1D;AAEA,SAAS,aACP,QACA,SACgC;CAChC,MAAM,WAAW,QAAQ;CACzB,OAAO,sBAAsB;EAC3B,SAAS,OAAO,EAAE,aAAa;GAC7B,MAAM,QAAQ,uBAAuB;GACrC,WAAW,MAAM,SAAS,OAAO,QAC/B,KAAK,MAAM,QAAQ,qBAAqB,OAAO,KAAK,GAAG,OAAO,MAAM,IAAI;GAE1E,KAAK,MAAM,QAAQ,kBAAkB,KAAK,GAAG,OAAO,MAAM,IAAI;GAC9D,MAAM,OAAO;EACf;EACA,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,SAAS,IAAI,CAAC;CACxD,CAAC;AACH;;;;;AAMA,SAAgB,uBACd,QACA,UAA6B,CAAC,GACpB;CACV,OAAO,8BAA8B,EAAE,QAAQ,aAAa,QAAQ,OAAO,EAAE,CAAC;AAChF;;;;;;AAOA,SAAgB,mCACd,QACA,UACA,UAA6B,CAAC,GACxB;CACN,8BAA8B;EAAE;EAAU,QAAQ,aAAa,QAAQ,OAAO;CAAE,CAAC;AACnF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fascicle",
3
- "version": "0.8.13",
3
+ "version": "0.9.0",
4
4
  "description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
5
5
  "keywords": [
6
6
  "agents",
@@ -38,6 +38,7 @@
38
38
  "node": ">=24.0.0",
39
39
  "pnpm": ">=10.13.0"
40
40
  },
41
+ "packageManager": "pnpm@11.1.2",
41
42
  "main": "./dist/index.js",
42
43
  "module": "./dist/index.js",
43
44
  "types": "./dist/index.d.ts",
@@ -57,6 +58,10 @@
57
58
  "./stdio": {
58
59
  "types": "./dist/stdio.d.ts",
59
60
  "import": "./dist/stdio.js"
61
+ },
62
+ "./ui": {
63
+ "types": "./dist/ui.d.ts",
64
+ "import": "./dist/ui.js"
60
65
  }
61
66
  },
62
67
  "imports": {
@@ -66,7 +71,8 @@
66
71
  "#adapters": "./src/adapters/index.ts",
67
72
  "#viewer": "./src/viewer/index.ts",
68
73
  "#agents": "./src/agents/index.ts",
69
- "#stdio": "./src/stdio/index.ts"
74
+ "#stdio": "./src/stdio/index.ts",
75
+ "#ui": "./src/ui/index.ts"
70
76
  },
71
77
  "bin": {
72
78
  "fascicle-viewer": "./dist/bin/fascicle-viewer.js"
@@ -88,16 +94,32 @@
88
94
  "publishConfig": {
89
95
  "access": "public"
90
96
  },
97
+ "scripts": {
98
+ "build": "node scripts/build.mjs",
99
+ "check": "node scripts/check.mjs",
100
+ "check:all": "node scripts/check.mjs --all",
101
+ "check:json": "node scripts/check.mjs --json",
102
+ "check:bail": "node scripts/check.mjs --bail",
103
+ "check:fix": "pnpm exec oxlint --type-aware --fix && node scripts/strip-semicolons.mjs && pnpm exec fallow fix",
104
+ "check:mutation": "stryker run",
105
+ "check:publish": "node scripts/check-publish.mjs",
106
+ "check:security": "pnpm audit --audit-level=high",
107
+ "prepublishOnly": "pnpm check && pnpm build && pnpm check:publish",
108
+ "test": "vitest run",
109
+ "test:watch": "vitest",
110
+ "types": "tsc --noEmit",
111
+ "fascicle-viewer": "tsx src/viewer/cli.ts"
112
+ },
91
113
  "peerDependencies": {
92
- "@ai-sdk/amazon-bedrock": "^3.0.0",
93
- "@ai-sdk/anthropic": "^3.0.0",
94
- "@ai-sdk/google": "^3.0.0",
95
- "@ai-sdk/openai": "^3.0.0",
96
- "@ai-sdk/openai-compatible": "^2.0.0",
114
+ "@ai-sdk/amazon-bedrock": "^5.0.0",
115
+ "@ai-sdk/anthropic": "^4.0.0",
116
+ "@ai-sdk/google": "^4.0.0",
117
+ "@ai-sdk/openai": "^4.0.0",
118
+ "@ai-sdk/openai-compatible": "^3.0.0",
97
119
  "@modelcontextprotocol/sdk": "^1.29.0",
98
- "@openrouter/ai-sdk-provider": "^2.0.0",
99
- "ai": "^6.0.0",
100
- "ai-sdk-ollama": "^3.0.0",
120
+ "@openrouter/ai-sdk-provider": "^3.0.0",
121
+ "ai": "^7.0.0",
122
+ "ai-sdk-ollama": "^4.0.0",
101
123
  "zod": "^4.0.0"
102
124
  },
103
125
  "peerDependenciesMeta": {
@@ -127,37 +149,22 @@
127
149
  }
128
150
  },
129
151
  "devDependencies": {
130
- "@arethetypeswrong/cli": "0.18.2",
131
- "@ast-grep/cli": "0.42.1",
152
+ "@arethetypeswrong/cli": "0.18.4",
153
+ "@ast-grep/cli": "0.44.1",
132
154
  "@modelcontextprotocol/sdk": "1.29.0",
133
155
  "@stryker-mutator/core": "9.6.1",
134
156
  "@stryker-mutator/vitest-runner": "9.6.1",
135
- "@types/node": "24.12.2",
136
- "@vitest/coverage-v8": "4.1.4",
137
- "cspell": "10.0.0",
138
- "fallow": "2.40.3",
139
- "markdownlint-cli2": "0.22.0",
140
- "oxlint": "1.60.0",
141
- "oxlint-tsgolint": "0.21.1",
142
- "tsdown": "0.21.9",
143
- "tsx": "4.21.0",
157
+ "@types/node": "26.1.0",
158
+ "@vitest/coverage-v8": "4.1.10",
159
+ "cspell": "10.0.1",
160
+ "fallow": "3.2.0",
161
+ "markdownlint-cli2": "0.23.0",
162
+ "oxlint": "1.73.0",
163
+ "oxlint-tsgolint": "0.24.0",
164
+ "tsdown": "0.22.3",
165
+ "tsx": "4.23.0",
144
166
  "typescript": "6.0.3",
145
- "vitest": "4.1.4",
146
- "zod": "4.3.6"
147
- },
148
- "scripts": {
149
- "build": "node scripts/build.mjs",
150
- "check": "node scripts/check.mjs",
151
- "check:all": "node scripts/check.mjs --all",
152
- "check:json": "node scripts/check.mjs --json",
153
- "check:bail": "node scripts/check.mjs --bail",
154
- "check:fix": "pnpm exec oxlint --type-aware --fix && node scripts/strip-semicolons.mjs && pnpm exec fallow fix",
155
- "check:mutation": "stryker run",
156
- "check:publish": "node scripts/check-publish.mjs",
157
- "check:security": "pnpm audit --audit-level=high",
158
- "test": "vitest run",
159
- "test:watch": "vitest",
160
- "types": "tsc --noEmit",
161
- "fascicle-viewer": "tsx src/viewer/cli.ts"
167
+ "vitest": "4.1.10",
168
+ "zod": "4.4.3"
162
169
  }
163
- }
170
+ }