fascicle 0.16.4 → 0.17.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/CHANGELOG.md +59 -0
- package/README.md +3 -2
- package/dist/AGENTS.md +69 -18
- package/dist/acp.d.ts +1 -1
- package/dist/acp.js +6 -1
- package/dist/acp.js.map +1 -1
- package/dist/agents.d.ts +1 -1
- package/dist/{engine-D1QMcyIG.js → engine-BMdRqWL2.js} +1018 -231
- package/dist/engine-BMdRqWL2.js.map +1 -0
- package/dist/index.d.ts +108 -16
- package/dist/index.js +225 -16
- package/dist/index.js.map +1 -1
- package/dist/{invoke-LbzZLZFw.js → invoke-BbJLQcLl.js} +62 -106
- package/dist/invoke-BbJLQcLl.js.map +1 -0
- package/dist/{leading_system-WhW76tRn.js → leading_system-DmNxhvzL.js} +45 -16
- package/dist/leading_system-DmNxhvzL.js.map +1 -0
- package/dist/mcp.d.ts +2 -1
- package/dist/mcp.js +6 -3
- package/dist/mcp.js.map +1 -1
- package/dist/otel.js +48 -3
- package/dist/otel.js.map +1 -1
- package/dist/testing.d.ts +77 -2
- package/dist/testing.js +202 -19
- package/dist/testing.js.map +1 -1
- package/dist/{types-Sw0oHW-_.d.ts → types-BNgAUQP1.d.ts} +170 -17
- package/dist/viewer-app/assets/index-9eVv6Mar.css +1 -0
- package/dist/viewer-app/assets/index-BkS2ZQu0.js +4 -0
- package/dist/viewer-app/index.html +2 -2
- package/dist/viewer.d.ts +37 -10
- package/dist/viewer.js +101 -46
- package/dist/viewer.js.map +1 -1
- package/package.json +1 -1
- package/dist/engine-D1QMcyIG.js.map +0 -1
- package/dist/invoke-LbzZLZFw.js.map +0 -1
- package/dist/leading_system-WhW76tRn.js.map +0 -1
- package/dist/viewer-app/assets/index-Cev83tcH.css +0 -1
- package/dist/viewer-app/assets/index-D8UmFVfR.js +0 -2
package/dist/mcp.js
CHANGED
|
@@ -205,16 +205,19 @@ function build_transport(sdk, config) {
|
|
|
205
205
|
}
|
|
206
206
|
/**
|
|
207
207
|
* Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards
|
|
208
|
-
* to `callTool` on the shared client.
|
|
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.
|
|
209
211
|
*
|
|
210
212
|
* An already-aborted signal short-circuits before the wire call; otherwise the
|
|
211
213
|
* signal is passed through so cancelling the run cancels the remote call.
|
|
212
214
|
*/
|
|
213
215
|
function to_fascicle_tool(client, advertised, options) {
|
|
214
216
|
const name = advertised.name;
|
|
217
|
+
const description = advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`;
|
|
215
218
|
return {
|
|
216
|
-
name
|
|
217
|
-
description
|
|
219
|
+
name: `${options.name_prefix ?? ""}${name}`,
|
|
220
|
+
description,
|
|
218
221
|
input_schema: json_schema_to_standard(advertised.inputSchema),
|
|
219
222
|
execute: async (input, ctx) => {
|
|
220
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 });
|
package/dist/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.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}\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.\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,\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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A,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"}
|
|
1
|
+
{"version":3,"file":"mcp.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,MAAM;CAC1D,IAAI,UAAU,MAAM,GAAG,OAAO,aAAa,UAAU,MAAM,GAAG,MA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AO,IAAI,IAAI,8BAA8B,IAAI,IAAI,OAAO,GAAG,GAAG,IAAI;AACxE;;;;;;;;;;AAWA,SAAS,iBACP,QACA,YACA,SACM;CACN,MAAM,OAAO,WAAW;CACxB,MAAM,cACJ,WAAW,eAAe,QAAQ,sBAAsB,IAAI,KAAK,YAAY;CAC/E,OAAO;EACL,MAAM,GAAG,QAAQ,eAAe,KAAK;EACrC;EACA,cAAc,wBAAwB,WAAW,WAAW;EAC5D,SAAS,OAAO,OAAgB,QAAyB;GACvD,IAAI,IAAI,MAAM,SACZ,MAAM,IAAI,MAAM,kBAAkB,QAC9B,IAAI,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;;;;;;;;;;;ACnIA,SAAgB,WAAiB,QAAqC;CACpE,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/otel.js
CHANGED
|
@@ -8,12 +8,15 @@ import { SpanStatusCode, context, metrics, trace } from "@opentelemetry/api";
|
|
|
8
8
|
* hour"), which want real OTel metric instruments rather than a
|
|
9
9
|
* spans-to-metrics pipeline. This recorder listens to the same trajectory
|
|
10
10
|
* events the span bridge mirrors and records the GenAI semantic-convention
|
|
11
|
-
* client histograms, plus
|
|
12
|
-
* conventions do not cover yet (cost, absorbed retries).
|
|
11
|
+
* client histograms, plus three Fascicle-named instruments for the data the
|
|
12
|
+
* conventions do not cover yet (cost, absorbed retries, cache traffic).
|
|
13
13
|
*
|
|
14
14
|
* Instruments and sources:
|
|
15
15
|
* - `gen_ai.client.token.usage` ({token}) from `response_received`, one
|
|
16
16
|
* point per direction via `gen_ai.token.type`.
|
|
17
|
+
* - `fascicle.client.cache.token.usage` ({token}) from `response_received`'s
|
|
18
|
+
* `cached_input_tokens` and `cache_write_tokens`, one point per direction
|
|
19
|
+
* above zero via `fascicle.cache.direction` (`read` or `write`).
|
|
17
20
|
* - `gen_ai.client.operation.duration` (s) from `response_received`
|
|
18
21
|
* `duration_ms`, the model-only round trip.
|
|
19
22
|
* - `gen_ai.client.operation.time_to_first_chunk` (s) from
|
|
@@ -104,6 +107,11 @@ function create_metrics_recorder(options) {
|
|
|
104
107
|
description: "Tool execution duration",
|
|
105
108
|
advice: { explicitBucketBoundaries: DURATION_BOUNDARIES }
|
|
106
109
|
});
|
|
110
|
+
const cache_token_usage = meter.createHistogram("fascicle.client.cache.token.usage", {
|
|
111
|
+
unit: "{token}",
|
|
112
|
+
description: "Number of input tokens read from or written to the prompt cache per model turn",
|
|
113
|
+
advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES }
|
|
114
|
+
});
|
|
107
115
|
const cost = meter.createHistogram("fascicle.client.operation.cost", {
|
|
108
116
|
unit: "usd",
|
|
109
117
|
description: "Estimated cost per model turn"
|
|
@@ -120,8 +128,21 @@ function create_metrics_recorder(options) {
|
|
|
120
128
|
if (top?.model !== void 0) attrs["gen_ai.request.model"] = top.model;
|
|
121
129
|
return attrs;
|
|
122
130
|
};
|
|
131
|
+
const record_cache_tokens = (event, base) => {
|
|
132
|
+
const reads = event_number(event, "cached_input_tokens") ?? 0;
|
|
133
|
+
if (reads > 0) cache_token_usage.record(reads, {
|
|
134
|
+
...base,
|
|
135
|
+
"fascicle.cache.direction": "read"
|
|
136
|
+
});
|
|
137
|
+
const writes = event_number(event, "cache_write_tokens") ?? 0;
|
|
138
|
+
if (writes > 0) cache_token_usage.record(writes, {
|
|
139
|
+
...base,
|
|
140
|
+
"fascicle.cache.direction": "write"
|
|
141
|
+
});
|
|
142
|
+
};
|
|
123
143
|
const on_response_received = (event) => {
|
|
124
144
|
const base = base_attributes();
|
|
145
|
+
record_cache_tokens(event, base);
|
|
125
146
|
const input = event_number(event, "input_tokens");
|
|
126
147
|
if (input !== void 0) token_usage.record(input, {
|
|
127
148
|
...base,
|
|
@@ -293,6 +314,30 @@ function to_attributes(meta, prefix, flatten = false) {
|
|
|
293
314
|
return attrs;
|
|
294
315
|
}
|
|
295
316
|
/**
|
|
317
|
+
* The engine events that carry a captured payload, and the field that holds
|
|
318
|
+
* it: a turn's request, the reply's parts, and the body that went on the
|
|
319
|
+
* wire. A `ctx.emit` event carries its own keys and isn't one of them.
|
|
320
|
+
*/
|
|
321
|
+
const CAPTURED_FIELDS = /* @__PURE__ */ new Map([
|
|
322
|
+
["request_sent", "request"],
|
|
323
|
+
["response_received", "content"],
|
|
324
|
+
["request_wire", "body"]
|
|
325
|
+
]);
|
|
326
|
+
/**
|
|
327
|
+
* A recorded event's attributes. A captured payload, which grows with the
|
|
328
|
+
* conversation, is left out and recorded as `<prefix>capture.bytes`, the
|
|
329
|
+
* UTF-8 length of its JSON, since an attribute has to stay small.
|
|
330
|
+
*/
|
|
331
|
+
function event_attributes(event, prefix) {
|
|
332
|
+
const field = CAPTURED_FIELDS.get(event.kind);
|
|
333
|
+
if (field === void 0 || !(field in event)) return to_attributes(event, prefix);
|
|
334
|
+
const { [field]: payload, ...rest } = event;
|
|
335
|
+
return {
|
|
336
|
+
...to_attributes(rest, prefix),
|
|
337
|
+
[`${prefix}capture.bytes`]: Buffer.byteLength(safe_json(payload))
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
296
341
|
* Create a `TrajectoryLogger` that mirrors spans and events onto
|
|
297
342
|
* OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).
|
|
298
343
|
*
|
|
@@ -362,7 +407,7 @@ function create_otel_trajectory_logger(options = {}) {
|
|
|
362
407
|
const span = target_for_event(event);
|
|
363
408
|
if (span === void 0) return;
|
|
364
409
|
const name = typeof event.kind === "string" ? event.kind : "event";
|
|
365
|
-
span.addEvent(name,
|
|
410
|
+
span.addEvent(name, event_attributes(event, prefix));
|
|
366
411
|
}
|
|
367
412
|
};
|
|
368
413
|
}
|
package/dist/otel.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otel.js","names":["otel_metrics","otel_context"],"sources":["../src/otel/metrics.ts","../src/otel/trajectory_logger.ts"],"sourcesContent":["/**\n * Opt-in OpenTelemetry metrics derived from the trajectory stream.\n *\n * The bridge's spans answer \"what happened on this run\"; SRE dashboards ask\n * aggregate questions (\"p95 latency by model\", \"429s per minute\", \"tokens per\n * hour\"), which want real OTel metric instruments rather than a\n * spans-to-metrics pipeline. This recorder listens to the same trajectory\n * events the span bridge mirrors and records the GenAI semantic-convention\n * client histograms, plus two Fascicle-named instruments for the data the\n * conventions do not cover yet (cost, absorbed retries).\n *\n * Instruments and sources:\n * - `gen_ai.client.token.usage` ({token}) from `response_received`, one\n * point per direction via `gen_ai.token.type`.\n * - `gen_ai.client.operation.duration` (s) from `response_received`\n * `duration_ms`, the model-only round trip.\n * - `gen_ai.client.operation.time_to_first_chunk` (s) from\n * `first_chunk_ms` on streamed turns.\n * - `gen_ai.execute_tool.duration` (s) from `tool_result`, tagged\n * `gen_ai.tool.name`.\n * - `fascicle.client.operation.cost` (usd) from the `cost` event's\n * `total_usd`.\n * - `fascicle.client.turn_retries` ({retry}) counter from `turn_retry`,\n * tagged `error.type` with the classified failure kind.\n *\n * Provider and model attributes come from the enclosing `engine.generate`\n * span's start meta, tracked on a stack with the same documented\n * approximation as the span bridge: concurrent generates sharing one logger\n * attribute to the innermost open call. The GenAI semantic conventions are\n * experimental, so a revision of them may rename an instrument this module\n * records.\n */\n\nimport {\n metrics as otel_metrics,\n type Attributes,\n type Counter,\n type Histogram,\n type Meter,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent } from '#core'\n\nexport type OtelMetricsOptions = {\n /**\n * Meter to create instruments on. Defaults to\n * `metrics.getMeter('fascicle')`, which resolves against the global\n * MeterProvider the host has registered.\n */\n readonly meter?: Meter\n}\n\n/**\n * The span-lifecycle + event listener the trajectory logger drives when\n * metrics are enabled.\n */\nexport type MetricsRecorder = {\n readonly on_start_span: (\n id: string,\n name: string,\n meta: Record<string, unknown> | undefined,\n ) => void\n readonly on_end_span: (id: string) => void\n readonly on_record: (event: TrajectoryEvent) => void\n}\n\n/** Semconv-suggested boundaries for the duration histograms, in seconds. */\nconst DURATION_BOUNDARIES = [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48,\n 40.96, 81.92,\n]\n\n/** Semconv-suggested boundaries for the token-usage histogram. */\nconst TOKEN_BOUNDARIES = [\n 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,\n]\n\n/**\n * Read `key` off the loose event and return it only when it is a number.\n */\nfunction event_number(event: TrajectoryEvent, key: string): number | undefined {\n const value = event[key]\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read `key` off the loose event and return it only when it is a string.\n */\nfunction event_string(event: TrajectoryEvent, key: string): string | undefined {\n const value = event[key]\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Create the metrics recorder: instruments are created once here, and every\n * recording stamps the provider/model of the innermost open generate call.\n */\nexport function create_metrics_recorder(options: OtelMetricsOptions): MetricsRecorder {\n const meter = options.meter ?? otel_metrics.getMeter('fascicle')\n\n const token_usage: Histogram = meter.createHistogram('gen_ai.client.token.usage', {\n unit: '{token}',\n description: 'Number of input and output tokens used per model turn',\n advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES },\n })\n const operation_duration: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.duration',\n {\n unit: 's',\n description: 'Model round-trip duration of the successful turn attempt',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const time_to_first_chunk: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.time_to_first_chunk',\n {\n unit: 's',\n description: 'Time from turn start to the first streamed chunk',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const tool_duration: Histogram = meter.createHistogram('gen_ai.execute_tool.duration', {\n unit: 's',\n description: 'Tool execution duration',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n })\n const cost: Histogram = meter.createHistogram('fascicle.client.operation.cost', {\n unit: 'usd',\n description: 'Estimated cost per model turn',\n })\n const retries: Counter = meter.createCounter('fascicle.client.turn_retries', {\n unit: '{retry}',\n description: 'Provider turn attempts that failed and were retried',\n })\n\n // Open engine.generate calls in the order they started, each with the\n // identity its metric attributes carry; the last one is the innermost.\n const context_stack: Array<{ readonly id: string; readonly provider?: string; readonly model?: string }> = []\n\n const base_attributes = (): Attributes => {\n const attrs: Attributes = { 'gen_ai.operation.name': 'chat' }\n const top = context_stack[context_stack.length - 1]\n if (top?.provider !== undefined) attrs['gen_ai.provider.name'] = top.provider\n if (top?.model !== undefined) attrs['gen_ai.request.model'] = top.model\n return attrs\n }\n\n const on_response_received = (event: TrajectoryEvent): void => {\n const base = base_attributes()\n const input = event_number(event, 'input_tokens')\n if (input !== undefined) {\n token_usage.record(input, { ...base, 'gen_ai.token.type': 'input' })\n }\n const output = event_number(event, 'output_tokens')\n if (output !== undefined) {\n token_usage.record(output, { ...base, 'gen_ai.token.type': 'output' })\n }\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms !== undefined) operation_duration.record(duration_ms / 1000, base)\n const first_chunk_ms = event_number(event, 'first_chunk_ms')\n if (first_chunk_ms !== undefined) {\n time_to_first_chunk.record(first_chunk_ms / 1000, base)\n }\n }\n\n return {\n on_start_span(id, name, meta) {\n if (name !== 'engine.generate') return\n const provider = meta?.['provider']\n const model = meta?.['model_id']\n context_stack.push({\n id,\n ...(typeof provider === 'string' ? { provider } : {}),\n ...(typeof model === 'string' ? { model } : {}),\n })\n },\n on_end_span(id) {\n // Removed by id, since interleaved generates need not end in the\n // reverse of the order they started.\n const idx = context_stack.findIndex((entry) => entry.id === id)\n if (idx !== -1) context_stack.splice(idx, 1)\n },\n on_record(event) {\n if (event.kind === 'response_received') {\n on_response_received(event)\n return\n }\n if (event.kind === 'tool_result') {\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms === undefined) return\n const name = event_string(event, 'name')\n tool_duration.record(duration_ms / 1000, {\n ...base_attributes(),\n ...(name !== undefined ? { 'gen_ai.tool.name': name } : {}),\n })\n return\n }\n if (event.kind === 'cost') {\n const total_usd = event_number(event, 'total_usd')\n if (total_usd !== undefined) cost.record(total_usd, base_attributes())\n return\n }\n if (event.kind === 'turn_retry') {\n const failure_kind = event_string(event, 'failure_kind')\n retries.add(1, {\n ...base_attributes(),\n ...(failure_kind !== undefined ? { 'error.type': failure_kind } : {}),\n })\n }\n },\n }\n}\n","/**\n * OpenTelemetry bridge for Fascicle trajectory events.\n *\n * `create_otel_trajectory_logger` returns a plain TrajectoryLogger that turns\n * the engine's own span + event stream into OpenTelemetry spans: the\n * `engine.generate` span becomes an OTel root span, each `engine.generate.step`\n * a child span, and every `record`ed event (tool_call, tool_result, cost, ...)\n * an OTel span event on the currently open span. It is transport-neutral: the\n * spans come from events the engine already emits, so native and external\n * transports get traces without any AI-SDK involvement.\n *\n * `@opentelemetry/api` is imported ONLY under `src/otel/` (this module and\n * metrics.ts), outside `src/engine/` on purpose: engine code outside\n * `providers/` imports no npm package (rules/no-engine-npm-dep.yml), and an\n * app that never imports `fascicle/otel` pulls in zero OTel packages at\n * runtime.\n *\n * Nesting is resolved two ways, in order: an explicit `parent_span_id` on the\n * start meta (how the composition runner threads composer-span parenthood) wins;\n * otherwise the currently open span (top of the open stack) is the parent. This\n * is exact for the sequential engine flow (generate → step → step) and for\n * runner-nested spans; genuinely interleaved sibling spans that carry no\n * `parent_span_id` (concurrent branches sharing one logger) fall back to stack\n * order, which is this bridge's one documented approximation.\n */\n\nimport {\n context as otel_context,\n trace,\n SpanStatusCode,\n type AttributeValue,\n type Attributes,\n type Context,\n type Span,\n type Tracer,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { create_metrics_recorder, type OtelMetricsOptions } from './metrics.js'\n\nexport type OtelTrajectoryLoggerOptions = {\n /**\n * Tracer to open spans on. Defaults to `trace.getTracer('fascicle')`, which\n * resolves against whatever global TracerProvider the host has registered.\n */\n readonly tracer?: Tracer\n /**\n * Prefix for span + event attributes derived from event metadata, keeping\n * them out of the OTel semantic-convention namespace. Defaults to `fascicle.`.\n */\n readonly attribute_prefix?: string\n /**\n * Opt-in metric instruments recorded from the same trajectory stream the\n * spans mirror (GenAI semconv client histograms plus Fascicle's cost and\n * retry instruments; see metrics.ts). `true` uses the global MeterProvider's\n * `fascicle` meter; an object supplies a custom Meter. Off by default so the\n * bridge stays a pure tracer for hosts without a metrics pipeline.\n */\n readonly metrics?: boolean | OtelMetricsOptions\n}\n\n// Event/meta keys that are bridge plumbing, not span attributes.\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set(['kind', 'span_id', 'parent_span_id'])\n\n/**\n * JSON-stringify `value`, falling back to `String(value)` when `stringify`\n * throws or returns `undefined`, as it does for functions and symbols.\n */\nfunction safe_json(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/**\n * Convert a JS value into an OTel-compatible attribute value.\n *\n * Primitives and homogeneous primitive arrays pass through unchanged;\n * anything else falls back to `safe_json`; `null`/`undefined` drop out\n * entirely (returning `undefined`) so the caller can omit the attribute.\n */\nfunction to_attribute_value(value: unknown): AttributeValue | undefined {\n if (value === null || value === undefined) return undefined\n const kind = typeof value\n if (kind === 'string' || kind === 'number' || kind === 'boolean') {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return value as AttributeValue\n }\n if (Array.isArray(value)) {\n if (value.every((v) => typeof v === 'string')) return value\n if (value.every((v) => typeof v === 'number')) return value\n if (value.every((v) => typeof v === 'boolean')) return value\n return safe_json(value)\n }\n return safe_json(value)\n}\n\n/**\n * True for a plain object value (not null, not an array): the shape span-meta\n * flattening applies to.\n */\nfunction is_plain_object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Spread one object-valued span-meta field into dotted attribute keys\n * (`usage` + `input_tokens` becomes `<prefix>usage.input_tokens`), with\n * deeper nesting falling back to `to_attribute_value`'s JSON form.\n */\nfunction flatten_into(\n attrs: Attributes,\n key: string,\n value: Record<string, unknown>,\n prefix: string,\n): void {\n for (const [inner_key, inner_value] of Object.entries(value)) {\n const attr = to_attribute_value(inner_value)\n if (attr !== undefined) attrs[`${prefix}${key}.${inner_key}`] = attr\n }\n}\n\n/**\n * Build an OTel `Attributes` object from event/meta fields.\n *\n * Skips the bridge's internal plumbing keys (`kind`, `span_id`,\n * `parent_span_id`) and prefixes the rest with `prefix` so they stay out of\n * OTel's semantic-convention namespace.\n *\n * With `flatten`, an object-valued field spreads one level into dotted keys\n * (`usage: { input_tokens: 5 }` becomes `<prefix>usage.input_tokens = 5`), so\n * span metadata like usage and model_resolved lands as numeric attributes a\n * dashboard can aggregate rather than a JSON string it cannot query. Flattening\n * applies to span meta only, never to `record`ed events: an event may carry\n * arbitrary payloads (a tool call's input, a salvage blob) where\n * attribute-per-key would explode cardinality and leak structure, so those\n * keep the JSON-string fallback.\n */\nfunction to_attributes(\n meta: Readonly<Record<string, unknown>> | undefined,\n prefix: string,\n flatten = false,\n): Attributes {\n const attrs: Attributes = {}\n if (meta === undefined) return attrs\n for (const [key, value] of Object.entries(meta)) {\n if (INTERNAL_KEYS.has(key)) continue\n if (flatten && is_plain_object(value)) {\n flatten_into(attrs, key, value, prefix)\n continue\n }\n const attr = to_attribute_value(value)\n if (attr !== undefined) attrs[`${prefix}${key}`] = attr\n }\n return attrs\n}\n\ntype OpenSpan = { readonly span: Span; readonly context: Context }\n\n/**\n * Create a `TrajectoryLogger` that mirrors spans and events onto\n * OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).\n *\n * Parent resolution favors an explicit `parent_span_id` on the start meta;\n * otherwise it falls back to the currently open span on an internal stack.\n */\nexport function create_otel_trajectory_logger(\n options: OtelTrajectoryLoggerOptions = {},\n): TrajectoryLogger {\n const tracer = options.tracer ?? trace.getTracer('fascicle')\n const prefix = options.attribute_prefix ?? 'fascicle.'\n const metrics_recorder =\n options.metrics === undefined || options.metrics === false\n ? undefined\n : create_metrics_recorder(options.metrics === true ? {} : options.metrics)\n const open = new Map<string, OpenSpan>()\n const stack: string[] = []\n let counter = 0\n\n const top_context = (): Context | undefined => {\n const top = stack[stack.length - 1]\n if (top === undefined) return undefined\n return open.get(top)?.context\n }\n\n const parent_context = (meta: Record<string, unknown> | undefined): Context => {\n const explicit = meta?.['parent_span_id']\n if (typeof explicit === 'string') {\n const parent = open.get(explicit)\n if (parent !== undefined) return parent.context\n }\n return top_context() ?? otel_context.active()\n }\n\n const target_for_event = (event: TrajectoryEvent): Span | undefined => {\n if (typeof event.span_id === 'string') {\n const target = open.get(event.span_id)\n if (target !== undefined) return target.span\n }\n const top = stack[stack.length - 1]\n return top !== undefined ? open.get(top)?.span : undefined\n }\n\n return {\n start_span(name, meta) {\n const parent = parent_context(meta)\n const span = tracer.startSpan(\n name,\n { attributes: to_attributes(meta, prefix, true) },\n parent,\n )\n counter += 1\n const id = `fascicle-otel-${counter}`\n open.set(id, { span, context: trace.setSpan(parent, span) })\n stack.push(id)\n metrics_recorder?.on_start_span(id, name, meta)\n return id\n },\n end_span(id, meta) {\n metrics_recorder?.on_end_span(id)\n const entry = open.get(id)\n if (entry === undefined) return\n const { span } = entry\n span.setAttributes(to_attributes(meta, prefix, true))\n const error = meta?.['error']\n if (typeof error === 'string' && error.length > 0) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: error })\n }\n span.end()\n open.delete(id)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n record(event) {\n metrics_recorder?.on_record(event)\n const span = target_for_event(event)\n if (span === undefined) return\n const name = typeof event.kind === 'string' ? event.kind : 'event'\n span.addEvent(name, to_attributes(event, prefix))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,MAAM,sBAAsB;CAC1B;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAO;CACnE;CAAO;AACT;;AAGA,MAAM,mBAAmB;CACvB;CAAG;CAAG;CAAI;CAAI;CAAK;CAAM;CAAM;CAAO;CAAO;CAAQ;CAAS;AAChE;;;;AAKA,SAAS,aAAa,OAAwB,KAAiC;CAC7E,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;;;AAKA,SAAS,aAAa,OAAwB,KAAiC;CAC7E,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;;;;AAMA,SAAgB,wBAAwB,SAA8C;CACpF,MAAM,QAAQ,QAAQ,SAASA,QAAa,SAAS,UAAU;CAE/D,MAAM,cAAyB,MAAM,gBAAgB,6BAA6B;EAChF,MAAM;EACN,aAAa;EACb,QAAQ,EAAE,0BAA0B,iBAAiB;CACvD,CAAC;CACD,MAAM,qBAAgC,MAAM,gBAC1C,oCACA;EACE,MAAM;EACN,aAAa;EACb,QAAQ,EAAE,0BAA0B,oBAAoB;CAC1D,CACF;CACA,MAAM,sBAAiC,MAAM,gBAC3C,+CACA;EACE,MAAM;EACN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;EACA,SAAS,IAAI,MAAM;GACjB,kBAAkB,YAAY,EAAE;GAChC,MAAM,QAAQ,KAAK,IAAI,EAAE;GACzB,IAAI,UAAU,KAAA,GAAW;GACzB,MAAM,EAAE,SAAS;GACjB,KAAK,cAAc,cAAc,MAAM,QAAQ,IAAI,CAAC;GACpD,MAAM,QAAQ,OAAO;GACrB,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC9C,KAAK,UAAU;IAAE,MAAM,eAAe;IAAO,SAAS;GAAM,CAAC;GAE/D,KAAK,IAAI;GACT,KAAK,OAAO,EAAE;GACd,MAAM,MAAM,MAAM,YAAY,EAAE;GAChC,IAAI,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;EACrC;EACA,OAAO,OAAO;GACZ,kBAAkB,UAAU,KAAK;GACjC,MAAM,OAAO,iBAAiB,KAAK;GACnC,IAAI,SAAS,KAAA,GAAW;GACxB,MAAM,OAAO,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;GAC3D,KAAK,SAAS,MAAM,cAAc,OAAO,MAAM,CAAC;EAClD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"otel.js","names":["otel_metrics","otel_context"],"sources":["../src/otel/metrics.ts","../src/otel/trajectory_logger.ts"],"sourcesContent":["/**\n * Opt-in OpenTelemetry metrics derived from the trajectory stream.\n *\n * The bridge's spans answer \"what happened on this run\"; SRE dashboards ask\n * aggregate questions (\"p95 latency by model\", \"429s per minute\", \"tokens per\n * hour\"), which want real OTel metric instruments rather than a\n * spans-to-metrics pipeline. This recorder listens to the same trajectory\n * events the span bridge mirrors and records the GenAI semantic-convention\n * client histograms, plus three Fascicle-named instruments for the data the\n * conventions do not cover yet (cost, absorbed retries, cache traffic).\n *\n * Instruments and sources:\n * - `gen_ai.client.token.usage` ({token}) from `response_received`, one\n * point per direction via `gen_ai.token.type`.\n * - `fascicle.client.cache.token.usage` ({token}) from `response_received`'s\n * `cached_input_tokens` and `cache_write_tokens`, one point per direction\n * above zero via `fascicle.cache.direction` (`read` or `write`).\n * - `gen_ai.client.operation.duration` (s) from `response_received`\n * `duration_ms`, the model-only round trip.\n * - `gen_ai.client.operation.time_to_first_chunk` (s) from\n * `first_chunk_ms` on streamed turns.\n * - `gen_ai.execute_tool.duration` (s) from `tool_result`, tagged\n * `gen_ai.tool.name`.\n * - `fascicle.client.operation.cost` (usd) from the `cost` event's\n * `total_usd`.\n * - `fascicle.client.turn_retries` ({retry}) counter from `turn_retry`,\n * tagged `error.type` with the classified failure kind.\n *\n * Provider and model attributes come from the enclosing `engine.generate`\n * span's start meta, tracked on a stack with the same documented\n * approximation as the span bridge: concurrent generates sharing one logger\n * attribute to the innermost open call. The GenAI semantic conventions are\n * experimental, so a revision of them may rename an instrument this module\n * records.\n */\n\nimport {\n metrics as otel_metrics,\n type Attributes,\n type Counter,\n type Histogram,\n type Meter,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent } from '#core'\n\nexport type OtelMetricsOptions = {\n /**\n * Meter to create instruments on. Defaults to\n * `metrics.getMeter('fascicle')`, which resolves against the global\n * MeterProvider the host has registered.\n */\n readonly meter?: Meter\n}\n\n/**\n * The span-lifecycle + event listener the trajectory logger drives when\n * metrics are enabled.\n */\nexport type MetricsRecorder = {\n readonly on_start_span: (\n id: string,\n name: string,\n meta: Record<string, unknown> | undefined,\n ) => void\n readonly on_end_span: (id: string) => void\n readonly on_record: (event: TrajectoryEvent) => void\n}\n\n/** Semconv-suggested boundaries for the duration histograms, in seconds. */\nconst DURATION_BOUNDARIES = [\n 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48,\n 40.96, 81.92,\n]\n\n/** Semconv-suggested boundaries for the token-usage histogram. */\nconst TOKEN_BOUNDARIES = [\n 1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,\n]\n\n/**\n * Read `key` off the loose event and return it only when it is a number.\n */\nfunction event_number(event: TrajectoryEvent, key: string): number | undefined {\n const value = event[key]\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read `key` off the loose event and return it only when it is a string.\n */\nfunction event_string(event: TrajectoryEvent, key: string): string | undefined {\n const value = event[key]\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Create the metrics recorder: instruments are created once here, and every\n * recording stamps the provider/model of the innermost open generate call.\n */\nexport function create_metrics_recorder(options: OtelMetricsOptions): MetricsRecorder {\n const meter = options.meter ?? otel_metrics.getMeter('fascicle')\n\n const token_usage: Histogram = meter.createHistogram('gen_ai.client.token.usage', {\n unit: '{token}',\n description: 'Number of input and output tokens used per model turn',\n advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES },\n })\n const operation_duration: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.duration',\n {\n unit: 's',\n description: 'Model round-trip duration of the successful turn attempt',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const time_to_first_chunk: Histogram = meter.createHistogram(\n 'gen_ai.client.operation.time_to_first_chunk',\n {\n unit: 's',\n description: 'Time from turn start to the first streamed chunk',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n },\n )\n const tool_duration: Histogram = meter.createHistogram('gen_ai.execute_tool.duration', {\n unit: 's',\n description: 'Tool execution duration',\n advice: { explicitBucketBoundaries: DURATION_BOUNDARIES },\n })\n const cache_token_usage: Histogram = meter.createHistogram('fascicle.client.cache.token.usage', {\n unit: '{token}',\n description: 'Number of input tokens read from or written to the prompt cache per model turn',\n advice: { explicitBucketBoundaries: TOKEN_BOUNDARIES },\n })\n const cost: Histogram = meter.createHistogram('fascicle.client.operation.cost', {\n unit: 'usd',\n description: 'Estimated cost per model turn',\n })\n const retries: Counter = meter.createCounter('fascicle.client.turn_retries', {\n unit: '{retry}',\n description: 'Provider turn attempts that failed and were retried',\n })\n\n // Open engine.generate calls in the order they started, each with the\n // identity its metric attributes carry; the last one is the innermost.\n const context_stack: Array<{ readonly id: string; readonly provider?: string; readonly model?: string }> = []\n\n const base_attributes = (): Attributes => {\n const attrs: Attributes = { 'gen_ai.operation.name': 'chat' }\n const top = context_stack[context_stack.length - 1]\n if (top?.provider !== undefined) attrs['gen_ai.provider.name'] = top.provider\n if (top?.model !== undefined) attrs['gen_ai.request.model'] = top.model\n return attrs\n }\n\n // A provider that caches reports zero counts on a turn that didn't, so a\n // direction records a point only above zero.\n const record_cache_tokens = (event: TrajectoryEvent, base: Attributes): void => {\n const reads = event_number(event, 'cached_input_tokens') ?? 0\n if (reads > 0) cache_token_usage.record(reads, { ...base, 'fascicle.cache.direction': 'read' })\n const writes = event_number(event, 'cache_write_tokens') ?? 0\n if (writes > 0) cache_token_usage.record(writes, { ...base, 'fascicle.cache.direction': 'write' })\n }\n\n const on_response_received = (event: TrajectoryEvent): void => {\n const base = base_attributes()\n record_cache_tokens(event, base)\n const input = event_number(event, 'input_tokens')\n if (input !== undefined) {\n token_usage.record(input, { ...base, 'gen_ai.token.type': 'input' })\n }\n const output = event_number(event, 'output_tokens')\n if (output !== undefined) {\n token_usage.record(output, { ...base, 'gen_ai.token.type': 'output' })\n }\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms !== undefined) operation_duration.record(duration_ms / 1000, base)\n const first_chunk_ms = event_number(event, 'first_chunk_ms')\n if (first_chunk_ms !== undefined) {\n time_to_first_chunk.record(first_chunk_ms / 1000, base)\n }\n }\n\n return {\n on_start_span(id, name, meta) {\n if (name !== 'engine.generate') return\n const provider = meta?.['provider']\n const model = meta?.['model_id']\n context_stack.push({\n id,\n ...(typeof provider === 'string' ? { provider } : {}),\n ...(typeof model === 'string' ? { model } : {}),\n })\n },\n on_end_span(id) {\n // Removed by id, since interleaved generates need not end in the\n // reverse of the order they started.\n const idx = context_stack.findIndex((entry) => entry.id === id)\n if (idx !== -1) context_stack.splice(idx, 1)\n },\n on_record(event) {\n if (event.kind === 'response_received') {\n on_response_received(event)\n return\n }\n if (event.kind === 'tool_result') {\n const duration_ms = event_number(event, 'duration_ms')\n if (duration_ms === undefined) return\n const name = event_string(event, 'name')\n tool_duration.record(duration_ms / 1000, {\n ...base_attributes(),\n ...(name !== undefined ? { 'gen_ai.tool.name': name } : {}),\n })\n return\n }\n if (event.kind === 'cost') {\n const total_usd = event_number(event, 'total_usd')\n if (total_usd !== undefined) cost.record(total_usd, base_attributes())\n return\n }\n if (event.kind === 'turn_retry') {\n const failure_kind = event_string(event, 'failure_kind')\n retries.add(1, {\n ...base_attributes(),\n ...(failure_kind !== undefined ? { 'error.type': failure_kind } : {}),\n })\n }\n },\n }\n}\n","/**\n * OpenTelemetry bridge for Fascicle trajectory events.\n *\n * `create_otel_trajectory_logger` returns a plain TrajectoryLogger that turns\n * the engine's own span + event stream into OpenTelemetry spans: the\n * `engine.generate` span becomes an OTel root span, each `engine.generate.step`\n * a child span, and every `record`ed event (tool_call, tool_result, cost, ...)\n * an OTel span event on the currently open span. It is transport-neutral: the\n * spans come from events the engine already emits, so native and external\n * transports get traces without any AI-SDK involvement.\n *\n * `@opentelemetry/api` is imported ONLY under `src/otel/` (this module and\n * metrics.ts), outside `src/engine/` on purpose: engine code outside\n * `providers/` imports no npm package (rules/no-engine-npm-dep.yml), and an\n * app that never imports `fascicle/otel` pulls in zero OTel packages at\n * runtime.\n *\n * Nesting is resolved two ways, in order: an explicit `parent_span_id` on the\n * start meta (how the composition runner threads composer-span parenthood) wins;\n * otherwise the currently open span (top of the open stack) is the parent. This\n * is exact for the sequential engine flow (generate → step → step) and for\n * runner-nested spans; genuinely interleaved sibling spans that carry no\n * `parent_span_id` (concurrent branches sharing one logger) fall back to stack\n * order, which is this bridge's one documented approximation.\n */\n\nimport {\n context as otel_context,\n trace,\n SpanStatusCode,\n type AttributeValue,\n type Attributes,\n type Context,\n type Span,\n type Tracer,\n} from '@opentelemetry/api'\nimport type { TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { create_metrics_recorder, type OtelMetricsOptions } from './metrics.js'\n\nexport type OtelTrajectoryLoggerOptions = {\n /**\n * Tracer to open spans on. Defaults to `trace.getTracer('fascicle')`, which\n * resolves against whatever global TracerProvider the host has registered.\n */\n readonly tracer?: Tracer\n /**\n * Prefix for span + event attributes derived from event metadata, keeping\n * them out of the OTel semantic-convention namespace. Defaults to `fascicle.`.\n */\n readonly attribute_prefix?: string\n /**\n * Opt-in metric instruments recorded from the same trajectory stream the\n * spans mirror (GenAI semconv client histograms plus Fascicle's cost and\n * retry instruments; see metrics.ts). `true` uses the global MeterProvider's\n * `fascicle` meter; an object supplies a custom Meter. Off by default so the\n * bridge stays a pure tracer for hosts without a metrics pipeline.\n */\n readonly metrics?: boolean | OtelMetricsOptions\n}\n\n// Event/meta keys that are bridge plumbing, not span attributes.\nconst INTERNAL_KEYS: ReadonlySet<string> = new Set(['kind', 'span_id', 'parent_span_id'])\n\n/**\n * JSON-stringify `value`, falling back to `String(value)` when `stringify`\n * throws or returns `undefined`, as it does for functions and symbols.\n */\nfunction safe_json(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/**\n * Convert a JS value into an OTel-compatible attribute value.\n *\n * Primitives and homogeneous primitive arrays pass through unchanged;\n * anything else falls back to `safe_json`; `null`/`undefined` drop out\n * entirely (returning `undefined`) so the caller can omit the attribute.\n */\nfunction to_attribute_value(value: unknown): AttributeValue | undefined {\n if (value === null || value === undefined) return undefined\n const kind = typeof value\n if (kind === 'string' || kind === 'number' || kind === 'boolean') {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return value as AttributeValue\n }\n if (Array.isArray(value)) {\n if (value.every((v) => typeof v === 'string')) return value\n if (value.every((v) => typeof v === 'number')) return value\n if (value.every((v) => typeof v === 'boolean')) return value\n return safe_json(value)\n }\n return safe_json(value)\n}\n\n/**\n * True for a plain object value (not null, not an array): the shape span-meta\n * flattening applies to.\n */\nfunction is_plain_object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Spread one object-valued span-meta field into dotted attribute keys\n * (`usage` + `input_tokens` becomes `<prefix>usage.input_tokens`), with\n * deeper nesting falling back to `to_attribute_value`'s JSON form.\n */\nfunction flatten_into(\n attrs: Attributes,\n key: string,\n value: Record<string, unknown>,\n prefix: string,\n): void {\n for (const [inner_key, inner_value] of Object.entries(value)) {\n const attr = to_attribute_value(inner_value)\n if (attr !== undefined) attrs[`${prefix}${key}.${inner_key}`] = attr\n }\n}\n\n/**\n * Build an OTel `Attributes` object from event/meta fields.\n *\n * Skips the bridge's internal plumbing keys (`kind`, `span_id`,\n * `parent_span_id`) and prefixes the rest with `prefix` so they stay out of\n * OTel's semantic-convention namespace.\n *\n * With `flatten`, an object-valued field spreads one level into dotted keys\n * (`usage: { input_tokens: 5 }` becomes `<prefix>usage.input_tokens = 5`), so\n * span metadata like usage and model_resolved lands as numeric attributes a\n * dashboard can aggregate rather than a JSON string it cannot query. Flattening\n * applies to span meta only, never to `record`ed events: an event may carry\n * arbitrary payloads (a tool call's input, a salvage blob) where\n * attribute-per-key would explode cardinality and leak structure, so those\n * keep the JSON-string fallback.\n */\nfunction to_attributes(\n meta: Readonly<Record<string, unknown>> | undefined,\n prefix: string,\n flatten = false,\n): Attributes {\n const attrs: Attributes = {}\n if (meta === undefined) return attrs\n for (const [key, value] of Object.entries(meta)) {\n if (INTERNAL_KEYS.has(key)) continue\n if (flatten && is_plain_object(value)) {\n flatten_into(attrs, key, value, prefix)\n continue\n }\n const attr = to_attribute_value(value)\n if (attr !== undefined) attrs[`${prefix}${key}`] = attr\n }\n return attrs\n}\n\n/**\n * The engine events that carry a captured payload, and the field that holds\n * it: a turn's request, the reply's parts, and the body that went on the\n * wire. A `ctx.emit` event carries its own keys and isn't one of them.\n */\nconst CAPTURED_FIELDS: ReadonlyMap<string, string> = new Map([\n ['request_sent', 'request'],\n ['response_received', 'content'],\n ['request_wire', 'body'],\n])\n\n/**\n * A recorded event's attributes. A captured payload, which grows with the\n * conversation, is left out and recorded as `<prefix>capture.bytes`, the\n * UTF-8 length of its JSON, since an attribute has to stay small.\n */\nfunction event_attributes(event: TrajectoryEvent, prefix: string): Attributes {\n const field = CAPTURED_FIELDS.get(event.kind)\n // Stryker disable next-line ConditionalExpression: with the first test gone, `undefined in event` looks for a key named \"undefined\", which no event of another kind carries, so it returns here all the same.\n if (field === undefined || !(field in event)) return to_attributes(event, prefix)\n const { [field]: payload, ...rest } = event\n return {\n ...to_attributes(rest, prefix),\n [`${prefix}capture.bytes`]: Buffer.byteLength(safe_json(payload)),\n }\n}\n\ntype OpenSpan = { readonly span: Span; readonly context: Context }\n\n/**\n * Create a `TrajectoryLogger` that mirrors spans and events onto\n * OpenTelemetry, using `options.tracer` (or the global `fascicle` tracer).\n *\n * Parent resolution favors an explicit `parent_span_id` on the start meta;\n * otherwise it falls back to the currently open span on an internal stack.\n */\nexport function create_otel_trajectory_logger(\n options: OtelTrajectoryLoggerOptions = {},\n): TrajectoryLogger {\n const tracer = options.tracer ?? trace.getTracer('fascicle')\n const prefix = options.attribute_prefix ?? 'fascicle.'\n const metrics_recorder =\n options.metrics === undefined || options.metrics === false\n ? undefined\n : create_metrics_recorder(options.metrics === true ? {} : options.metrics)\n const open = new Map<string, OpenSpan>()\n const stack: string[] = []\n let counter = 0\n\n const top_context = (): Context | undefined => {\n const top = stack[stack.length - 1]\n if (top === undefined) return undefined\n return open.get(top)?.context\n }\n\n const parent_context = (meta: Record<string, unknown> | undefined): Context => {\n const explicit = meta?.['parent_span_id']\n if (typeof explicit === 'string') {\n const parent = open.get(explicit)\n if (parent !== undefined) return parent.context\n }\n return top_context() ?? otel_context.active()\n }\n\n const target_for_event = (event: TrajectoryEvent): Span | undefined => {\n if (typeof event.span_id === 'string') {\n const target = open.get(event.span_id)\n if (target !== undefined) return target.span\n }\n const top = stack[stack.length - 1]\n return top !== undefined ? open.get(top)?.span : undefined\n }\n\n return {\n start_span(name, meta) {\n const parent = parent_context(meta)\n const span = tracer.startSpan(\n name,\n { attributes: to_attributes(meta, prefix, true) },\n parent,\n )\n counter += 1\n const id = `fascicle-otel-${counter}`\n open.set(id, { span, context: trace.setSpan(parent, span) })\n stack.push(id)\n metrics_recorder?.on_start_span(id, name, meta)\n return id\n },\n end_span(id, meta) {\n metrics_recorder?.on_end_span(id)\n const entry = open.get(id)\n if (entry === undefined) return\n const { span } = entry\n span.setAttributes(to_attributes(meta, prefix, true))\n const error = meta?.['error']\n if (typeof error === 'string' && error.length > 0) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: error })\n }\n span.end()\n open.delete(id)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n record(event) {\n metrics_recorder?.on_record(event)\n const span = target_for_event(event)\n if (span === undefined) return\n const name = typeof event.kind === 'string' ? event.kind : 'event'\n span.addEvent(name, event_attributes(event, prefix))\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,sBAAsB;CAC1B;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAO;CACnE;CAAO;AACT;;AAGA,MAAM,mBAAmB;CACvB;CAAG;CAAG;CAAI;CAAI;CAAK;CAAM;CAAM;CAAO;CAAO;CAAQ;CAAS;AAChE;;;;AAKA,SAAS,aAAa,OAAwB,KAAiC;CAC7E,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;;;AAKA,SAAS,aAAa,OAAwB,KAAiC;CAC7E,MAAM,QAAQ,MAAM;CACpB,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;;;;AAMA,SAAgB,wBAAwB,SAA8C;CACpF,MAAM,QAAQ,QAAQ,SAASA,QAAa,SAAS,UAAU;CAE/D,MAAM,cAAyB,MAAM,gBAAgB,6BAA6B;EAChF,MAAM;EACN,aAAa;EACb,QAAQ,EAAE,0BAA0B,iBAAiB;CACvD,CAAC;CACD,MAAM,qBAAgC,MAAM,gBAC1C,oCACA;EACE,M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B,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC9C,KAAK,UAAU;IAAE,MAAM,eAAe;IAAO,SAAS;GAAM,CAAC;GAE/D,KAAK,IAAI;GACT,KAAK,OAAO,EAAE;GACd,MAAM,MAAM,MAAM,YAAY,EAAE;GAChC,IAAI,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;EACrC;EACA,OAAO,OAAO;GACZ,kBAAkB,UAAU,KAAK;GACjC,MAAM,OAAO,iBAAiB,KAAK;GACnC,IAAI,SAAS,KAAA,GAAW;GACxB,MAAM,OAAO,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO;GAC3D,KAAK,SAAS,MAAM,iBAAiB,OAAO,MAAM,CAAC;EACrD;CACF;AACF"}
|
package/dist/testing.d.ts
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import { n as CheckpointStore } from "./types-CPqLZOEr.js";
|
|
2
|
-
import {
|
|
2
|
+
import { F as ToolCallRecord, L as TurnRequest, W as NativeProviderAdapter, h as GenerateResult, m as GenerateOptions, n as AssistantContentPart, p as FinishReason, u as Engine, z as UsageTotals } from "./types-BNgAUQP1.js";
|
|
3
|
+
//#region src/testing/assert_prefix_stable.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Check that every turn of every call in `requests` sends the turn before it
|
|
6
|
+
* unchanged: the same system prompt, the same tools in the same order
|
|
7
|
+
* (names, descriptions, and input schemas), and every earlier message again,
|
|
8
|
+
* as the same JSON text, before any new one.
|
|
9
|
+
*
|
|
10
|
+
* Throws a plain `Error` at the first difference, naming the call (counted
|
|
11
|
+
* from 1), the step (its `step_index`), and the difference, with message and
|
|
12
|
+
* tool positions as the request's arrays hold them, from 0. A new call
|
|
13
|
+
* starts wherever a `step_index` doesn't increase, so the check reads calls
|
|
14
|
+
* that ran one at a time, and a `parallel` flow takes one double per branch.
|
|
15
|
+
*/
|
|
16
|
+
export declare function assert_prefix_stable(requests: ReadonlyArray<TurnRequest>): void;
|
|
17
|
+
//#endregion
|
|
3
18
|
//#region src/testing/engine_from_generate.d.ts
|
|
4
19
|
/**
|
|
5
20
|
* Build an `Engine` whose only live member is the supplied `generate`.
|
|
@@ -62,6 +77,66 @@ type CaptureEngine = {
|
|
|
62
77
|
*/
|
|
63
78
|
export declare function make_capture_engine(options?: CaptureEngineOptions): CaptureEngine;
|
|
64
79
|
//#endregion
|
|
80
|
+
//#region src/testing/make_loop_engine.d.ts
|
|
81
|
+
/** One tool call a scripted turn makes. A call without an `id` gets `call_<turn>_<n>`. */
|
|
82
|
+
type LoopCall = {
|
|
83
|
+
readonly id?: string;
|
|
84
|
+
readonly name: string;
|
|
85
|
+
readonly input: unknown;
|
|
86
|
+
};
|
|
87
|
+
/** A turn spelled out field by field. */
|
|
88
|
+
type LoopTurnFields = {
|
|
89
|
+
/** The turn's text (default: its `content`'s text parts, joined). */
|
|
90
|
+
readonly text?: string;
|
|
91
|
+
/** The calls the turn makes (default: its `content`'s tool_call parts). */
|
|
92
|
+
readonly tool_calls?: ReadonlyArray<LoopCall>;
|
|
93
|
+
/** The turn's parts, which the loop sends back as the assistant message. */
|
|
94
|
+
readonly content?: ReadonlyArray<AssistantContentPart>;
|
|
95
|
+
/** Default: `'tool_calls'` when the turn makes calls, `'stop'` otherwise. */
|
|
96
|
+
readonly finish_reason?: FinishReason;
|
|
97
|
+
/** Default: the engine's `usage` option. */
|
|
98
|
+
readonly usage?: UsageTotals;
|
|
99
|
+
/**
|
|
100
|
+
* True to play a turn the provider paused partway through (Anthropic's
|
|
101
|
+
* `pause_turn`), which the loop sends back and continues with another turn.
|
|
102
|
+
*/
|
|
103
|
+
readonly paused?: boolean;
|
|
104
|
+
/** An error to throw for this turn instead of answering. */
|
|
105
|
+
readonly throw?: Error;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* One model turn: a string is a final answer, an array is the calls the turn
|
|
109
|
+
* makes, and an object spells the turn out field by field.
|
|
110
|
+
*/
|
|
111
|
+
type LoopTurn = string | ReadonlyArray<LoopCall> | LoopTurnFields;
|
|
112
|
+
type LoopEngineOptions = {
|
|
113
|
+
/** The model every call resolves to unless it names one (default `'loop'`). */
|
|
114
|
+
readonly model_id?: string;
|
|
115
|
+
/** The usage a turn reports when it sets none (default `{ input_tokens: 40, output_tokens: 20 }`). */
|
|
116
|
+
readonly usage?: UsageTotals;
|
|
117
|
+
/**
|
|
118
|
+
* The caching the double's provider declares, which decides the `cache`
|
|
119
|
+
* each request carries (default: none, so no request carries one).
|
|
120
|
+
*/
|
|
121
|
+
readonly prompt_cache?: NativeProviderAdapter['prompt_cache'];
|
|
122
|
+
};
|
|
123
|
+
type LoopEngine = {
|
|
124
|
+
readonly engine: Engine;
|
|
125
|
+
/** Every request the model was sent, in order, growing as the script plays. */
|
|
126
|
+
readonly requests: TurnRequest[];
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Build an engine whose one provider, `'loop'`, plays `turns` in order, a
|
|
130
|
+
* turn each time any call through the engine asks the model for one, and
|
|
131
|
+
* the array that records every request it was sent.
|
|
132
|
+
*
|
|
133
|
+
* `options.model_id` sets the default model (default `'loop'`),
|
|
134
|
+
* `options.usage` the usage a turn reports when it sets none (default
|
|
135
|
+
* `{ input_tokens: 40, output_tokens: 20 }`), and `options.prompt_cache` the
|
|
136
|
+
* caching its provider declares (default: none).
|
|
137
|
+
*/
|
|
138
|
+
export declare function make_loop_engine(turns: ReadonlyArray<LoopTurn>, options?: LoopEngineOptions): LoopEngine;
|
|
139
|
+
//#endregion
|
|
65
140
|
//#region src/testing/make_script_engine.d.ts
|
|
66
141
|
type ScriptResponse = {
|
|
67
142
|
readonly content?: unknown;
|
|
@@ -134,5 +209,5 @@ export declare function make_stub_engine(canned: ReadonlyArray<StubResponse>, op
|
|
|
134
209
|
*/
|
|
135
210
|
export declare function text_of<t = unknown>(opts: GenerateOptions<t>): string;
|
|
136
211
|
//#endregion
|
|
137
|
-
export type { CaptureEngine, CaptureEngineOptions, ScriptEngineOptions, ScriptResponse, StoreConformanceFailure, StoreConformanceOptions, StoreConformanceReport, StubContent, StubContentFn, StubEngineOptions, StubResponse };
|
|
212
|
+
export type { CaptureEngine, CaptureEngineOptions, LoopCall, LoopEngine, LoopEngineOptions, LoopTurn, ScriptEngineOptions, ScriptResponse, StoreConformanceFailure, StoreConformanceOptions, StoreConformanceReport, StubContent, StubContentFn, StubEngineOptions, StubResponse };
|
|
138
213
|
//# sourceMappingURL=testing.d.ts.map
|