@astral-mcp/projection 0.2.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/LICENSE +21 -0
- package/README.md +61 -0
- package/dist/index.d.mts +862 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2929 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +63 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["#connections","#catalog","#connect","#closeConnections","resolvePath"],"sources":["../src/errors.ts","../src/introspector/introspector.ts","../src/types.ts","../src/blob/versions.ts","../src/blob/sealer.ts","../src/sandbox/logs.ts","../src/sandbox/mounts.ts","../src/sandbox/session.ts","../src/policy/decision.ts","../src/text-safety.ts","../src/policy/elicitation.ts","../src/machine-host/contract.ts","../src/machine-host/drivers.ts","../src/machine-host/host.ts","../src/mrtr/protocol.ts","../src/mrtr/adapter.ts","../src/mrtr/discover.ts","../src/typegen/json-schema.ts","../src/typegen/generate.ts","../src/wrap.ts"],"sourcesContent":["import type { Diagnostic, ErrorPhase, LogEntry, StructuredError } from './types.js';\n\n/**\n * Error carrying the structured `isError` body every failure returns (R25).\n */\nexport class ProjectionError extends Error {\n readonly phase: ErrorPhase;\n readonly diagnostics: Diagnostic[];\n readonly hint: string;\n logs: LogEntry[];\n\n constructor(\n phase: ErrorPhase,\n message: string,\n options: { diagnostics?: Diagnostic[]; hint?: string; logs?: LogEntry[]; cause?: unknown } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = 'ProjectionError';\n this.phase = phase;\n this.diagnostics = options.diagnostics ?? [];\n this.hint = options.hint ?? '';\n this.logs = options.logs ?? [];\n }\n\n toStructured(): StructuredError {\n return {\n phase: this.phase,\n message: this.message,\n diagnostics: this.diagnostics,\n hint: this.hint,\n logs: this.logs,\n };\n }\n}\n\n/** Convert any thrown value into a StructuredError, defaulting to `runtime` phase. */\nexport function toStructuredError(err: unknown, logs: LogEntry[] = []): StructuredError {\n if (err instanceof ProjectionError) {\n const structured = err.toStructured();\n return { ...structured, logs: structured.logs.length > 0 ? structured.logs : logs };\n }\n return {\n phase: 'runtime',\n message: err instanceof Error ? err.message : String(err),\n diagnostics: [],\n hint: '',\n logs,\n };\n}\n","/**\n * Introspector — connects to the wrapped server(s), reads `tools/list`,\n * annotations, and `instructions`, and maintains the tool catalog (PRD §7,\n * G1, R29, R30). Also implements {@link ToolExecutor}: all tool calls the\n * machine host performs against a wrapped server go through here.\n *\n * Two source kinds are supported (R4):\n *\n * - **In-process instance**: an `McpServer` from `@modelcontextprotocol/server`.\n * The introspector connects it to an in-memory transport pair and talks to\n * it with a real MCP client, so introspection and execution exercise the\n * exact same code path as a remote server. The instance must be dedicated\n * to Projection (not already connected to another transport) — Projection is\n * the facade; the wrapped server is never exposed directly (R1).\n * - **Remote connection**: an already-connected SDK `Client`. The caller owns\n * its lifecycle; `close()` will not touch it.\n */\n\nimport { Client } from '@modelcontextprotocol/client';\nimport {\n InMemoryTransport,\n McpServer,\n ProtocolError,\n ProtocolErrorCode,\n type Tool,\n} from '@modelcontextprotocol/server';\nimport { ProjectionError } from '../errors.js';\nimport type {\n ServerAlias,\n ServerCatalog,\n ToolAnnotations,\n ToolCallOutcome,\n ToolCatalog,\n ToolCatalogEntry,\n ToolExecutor,\n} from '../types.js';\n\n/** A wrapped-server source: an in-process instance or a connected client. */\nexport type ServerSource = McpServer | Client;\n\n/**\n * Aliased server sources (R30). v1 instantiates exactly one entry, but the\n * interface accepts a set so the multi-server stretch goal (PRD §12.2) needs\n * no signature break.\n */\nexport type IntrospectorSources = Record<ServerAlias, ServerSource>;\n\ninterface Connection {\n client: Client;\n /** True when the introspector created the client (in-process source). */\n owned: boolean;\n}\n\nconst CLIENT_INFO = { name: 'projection-introspector', version: '0.1.0' };\n\nfunction isTextBlock(block: unknown): block is { type: 'text'; text: string } {\n return (\n typeof block === 'object' &&\n block !== null &&\n (block as { type?: unknown }).type === 'text' &&\n typeof (block as { text?: unknown }).text === 'string'\n );\n}\n\nfunction mapAnnotations(annotations: Tool['annotations']): ToolAnnotations | undefined {\n if (annotations === undefined) return undefined;\n const mapped: ToolAnnotations = {};\n if (annotations.title !== undefined) mapped.title = annotations.title;\n if (annotations.readOnlyHint !== undefined) mapped.readOnlyHint = annotations.readOnlyHint;\n if (annotations.destructiveHint !== undefined) {\n mapped.destructiveHint = annotations.destructiveHint;\n }\n if (annotations.idempotentHint !== undefined) {\n mapped.idempotentHint = annotations.idempotentHint;\n }\n return Object.keys(mapped).length > 0 ? mapped : undefined;\n}\n\nfunction toCatalogEntry(tool: Tool): ToolCatalogEntry {\n const entry: ToolCatalogEntry = {\n name: tool.name,\n inputSchema: tool.inputSchema as Record<string, unknown>,\n };\n if (tool.description !== undefined) entry.description = tool.description;\n if (tool.outputSchema !== undefined) {\n entry.outputSchema = tool.outputSchema as Record<string, unknown>;\n }\n const annotations = mapAnnotations(tool.annotations);\n if (annotations !== undefined) entry.annotations = annotations;\n return entry;\n}\n\n/**\n * Bounds on `tools/list` introspection. A wrapped server is untrusted (S5)\n * and could return an endless chain of `nextCursor` pages, or a tool count\n * large enough to blow up the generated artifacts; either would hang or\n * exhaust the process before any workflow runs.\n */\nconst MAX_TOOL_LIST_PAGES = 100;\nconst MAX_TOOLS = 2_000;\n\nasync function listAllTools(client: Client, alias: ServerAlias): Promise<Tool[]> {\n const tools: Tool[] = [];\n let cursor: string | undefined;\n let pages = 0;\n try {\n do {\n const page = await client.listTools(cursor !== undefined ? { cursor } : undefined);\n tools.push(...page.tools);\n cursor = page.nextCursor;\n pages += 1;\n if (pages >= MAX_TOOL_LIST_PAGES || tools.length >= MAX_TOOLS) {\n if (cursor !== undefined) {\n throw new ProjectionError(\n 'protocol',\n `wrapped server \"${alias}\" exceeded introspection limits (${pages} pages, ${tools.length} tools)`,\n {\n hint: `Projection reads at most ${MAX_TOOL_LIST_PAGES} tools/list pages and ${MAX_TOOLS} tools. Wrap a server with a bounded tool surface.`,\n },\n );\n }\n break;\n }\n } while (cursor !== undefined);\n } catch (err) {\n // Our own limit breach already carries the right phase and hint.\n if (err instanceof ProjectionError) throw err;\n // A server with zero registered tools never declares the `tools`\n // capability (client-side assertion) and answers tools/list with\n // Method not found; treat both as an empty catalog, not a failure.\n if (err instanceof ProtocolError && err.code === ProtocolErrorCode.MethodNotFound) {\n return [];\n }\n if (err instanceof Error && /does not support tools/i.test(err.message)) {\n return [];\n }\n throw new ProjectionError(\n 'protocol',\n `tools/list failed for wrapped server \"${alias}\": ${err instanceof Error ? err.message : String(err)}`,\n {\n hint: 'Check that the wrapped server is running, connected, and supports the tools capability.',\n cause: err,\n },\n );\n }\n return tools;\n}\n\nasync function buildServerCatalog(alias: ServerAlias, client: Client): Promise<ServerCatalog> {\n const tools = await listAllTools(client, alias);\n const info = client.getServerVersion();\n const catalog: ServerCatalog = {\n alias,\n // Stable identity recorded into blobs (R30): server name + version.\n identity: info !== undefined ? `${info.name}@${info.version}` : alias,\n tools: tools.map(toCatalogEntry),\n };\n const instructions = client.getInstructions();\n if (instructions !== undefined) catalog.instructions = instructions;\n return catalog;\n}\n\n/** Extract a one-line error message from an `isError` tool result's content. */\nfunction errorTextFromContent(content: unknown): string | undefined {\n if (!Array.isArray(content)) return undefined;\n const text = content\n .filter(isTextBlock)\n .map((block) => block.text)\n .join('\\n')\n .trim();\n return text.length > 0 ? text : undefined;\n}\n\n/**\n * Pick the value delivered to the machine as `TOOL_RESULT` payload:\n * `structuredContent` when the tool declares one, otherwise the text of a\n * single text block, otherwise the raw content array (`null` when empty).\n */\nfunction pickResultValue(result: { structuredContent?: unknown; content?: unknown }): unknown {\n if (result.structuredContent !== undefined) return result.structuredContent;\n const content = Array.isArray(result.content) ? result.content : [];\n const first = content[0];\n if (content.length === 1 && isTextBlock(first)) return first.text;\n if (content.length === 0) return null;\n return content;\n}\n\n/**\n * Holds one MCP client per wrapped-server alias, exposes the aggregated\n * {@link ToolCatalog}, and executes tool calls (implements\n * {@link ToolExecutor}). Construct with {@link createIntrospector}.\n */\nexport class Introspector implements ToolExecutor {\n readonly #connections: Map<ServerAlias, Connection>;\n #catalog: ToolCatalog;\n\n private constructor(connections: Map<ServerAlias, Connection>, catalog: ToolCatalog) {\n this.#connections = connections;\n this.#catalog = catalog;\n }\n\n static async create(sources: IntrospectorSources): Promise<Introspector> {\n const aliases = Object.keys(sources);\n if (aliases.length === 0) {\n throw new ProjectionError('protocol', 'No wrapped server was provided.', {\n hint: 'Pass at least one server source, e.g. { default: myMcpServer }.',\n });\n }\n const connections = new Map<ServerAlias, Connection>();\n const servers = new Map<ServerAlias, ServerCatalog>();\n // Each server is an independent host-side connection, so introspect\n // them concurrently (v1 has one; the fan-out matters for R30 multi-server).\n //\n // `allSettled`, not `all`: a fast-rejecting alias must not sweep cleanup\n // while a sibling's #connect is still in flight — that sibling would\n // register its connection after the sweep and leak it. Waiting for every\n // task to settle guarantees the sweep sees all opened connections.\n const settled = await Promise.allSettled(\n aliases.map(async (alias) => {\n const source = sources[alias];\n if (source === undefined) return;\n const connection = await Introspector.#connect(alias, source);\n connections.set(alias, connection);\n servers.set(alias, await buildServerCatalog(alias, connection.client));\n }),\n );\n const failed = settled.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n );\n if (failed !== undefined) {\n await Introspector.#closeConnections(connections);\n throw failed.reason;\n }\n return new Introspector(connections, { servers });\n }\n\n static async #connect(alias: ServerAlias, source: ServerSource): Promise<Connection> {\n if (source instanceof McpServer) {\n if (source.isConnected()) {\n throw new ProjectionError(\n 'protocol',\n `Wrapped server \"${alias}\" is already connected to a transport.`,\n {\n hint: \"Pass a dedicated McpServer instance — Projection owns the wrapped server's transport and exposes it only through the code-mode facade.\",\n },\n );\n }\n const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();\n const client = new Client(CLIENT_INFO, { capabilities: {} });\n await source.connect(serverTransport);\n await client.connect(clientTransport);\n return { client, owned: true };\n }\n return { client: source, owned: false };\n }\n\n static async #closeConnections(connections: Map<ServerAlias, Connection>): Promise<void> {\n await Promise.all(\n [...connections.values()]\n .filter((connection) => connection.owned)\n .map((connection) => connection.client.close().catch(() => undefined)),\n );\n }\n\n /** The aggregated tool catalog, keyed by server alias (R30). */\n get catalog(): ToolCatalog {\n return this.#catalog;\n }\n\n /** Re-read `tools/list` from every wrapped server and rebuild the catalog. */\n async refresh(): Promise<ToolCatalog> {\n const rebuilt = await Promise.all(\n [...this.#connections].map(\n async ([alias, connection]) =>\n [alias, await buildServerCatalog(alias, connection.client)] as const,\n ),\n );\n this.#catalog = { servers: new Map(rebuilt) };\n return this.#catalog;\n }\n\n /**\n * Execute a tool call against the wrapped server identified by `alias`,\n * mapping the MCP result to a {@link ToolCallOutcome}:\n *\n * - success → `{ ok: true, result }` where `result` is the tool's\n * `structuredContent` when present, else a single text block's text,\n * else the raw content array.\n * - `isError` result or transport/protocol failure → `{ ok: false, error }`.\n *\n * An unknown alias is a wiring bug, not a tool failure, and throws.\n */\n async callTool(\n alias: ServerAlias,\n name: string,\n args: Record<string, unknown>,\n ): Promise<ToolCallOutcome> {\n const connection = this.#connections.get(alias);\n if (connection === undefined) {\n throw new ProjectionError('protocol', `Unknown wrapped-server alias \"${alias}\".`, {\n hint: `Known aliases: ${[...this.#connections.keys()].join(', ')}. v1 wraps exactly one server under the \"default\" alias.`,\n });\n }\n try {\n // The SDK's return type is a union that includes a legacy\n // `{ toolResult }` compatibility shape; narrow to the modern fields.\n const result = (await connection.client.callTool({ name, arguments: args })) as {\n content?: unknown;\n structuredContent?: unknown;\n isError?: unknown;\n };\n if (result.isError === true) {\n return {\n ok: false,\n error: {\n message:\n errorTextFromContent(result.content) ?? `Tool \"${name}\" returned an error result.`,\n detail: result.structuredContent ?? result.content,\n },\n };\n }\n return { ok: true, result: pickResultValue(result) };\n } catch (err) {\n return {\n ok: false,\n error: {\n message: `Tool call \"${name}\" failed: ${err instanceof Error ? err.message : String(err)}`,\n detail: err instanceof Error ? { name: err.name } : err,\n },\n };\n }\n }\n\n /**\n * Close connections the introspector created (in-process sources).\n * Caller-provided remote clients are left untouched.\n */\n async close(): Promise<void> {\n await Introspector.#closeConnections(this.#connections);\n this.#connections.clear();\n }\n}\n\n/**\n * Connect to the given wrapped servers and build their tool catalog.\n *\n * v1 usage: `createIntrospector({ [DEFAULT_SERVER_ALIAS]: serverOrClient })`.\n */\nexport async function createIntrospector(sources: IntrospectorSources): Promise<Introspector> {\n return Introspector.create(sources);\n}\n","/**\n * Shared core types for Projection.\n *\n * These types are the contract between the seven components (introspector,\n * typegen, sandbox runtime, machine host, policy engine, blob sealer, MRTR\n * adapter). Component implementations depend on this module; it depends on\n * nothing inside the package.\n */\n\n// ---------------------------------------------------------------------------\n// Tool catalog (Introspector output — PRD R14, R30)\n// ---------------------------------------------------------------------------\n\n/** Alias identifying a wrapped server. v1 instantiates exactly one. */\nexport type ServerAlias = string;\n\nexport const DEFAULT_SERVER_ALIAS: ServerAlias = 'default';\n\n/** MCP tool annotations we care about (untrusted hints — S5). */\nexport interface ToolAnnotations {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n title?: string;\n}\n\nexport interface ToolCatalogEntry {\n /** Tool name as declared by the wrapped server. */\n name: string;\n description?: string;\n /** JSON Schema for the tool's input. */\n inputSchema: Record<string, unknown>;\n /** JSON Schema for the tool's output, when declared. */\n outputSchema?: Record<string, unknown>;\n annotations?: ToolAnnotations;\n}\n\nexport interface ToolCatalog {\n /** Keyed by server alias (R30). v1 has exactly one entry. */\n servers: Map<ServerAlias, ServerCatalog>;\n}\n\nexport interface ServerCatalog {\n alias: ServerAlias;\n /** Stable identity string recorded into blobs (R30). */\n identity: string;\n /** The wrapped server's `instructions` field, verbatim (R29). */\n instructions?: string;\n tools: ToolCatalogEntry[];\n}\n\n/**\n * Name → entry index, built lazily and cached per catalog object. The\n * catalog is immutable once introspected, so a `WeakMap` keyed on identity\n * lets every consumer look a tool up in O(1) without the catalog having to\n * carry (and every construction site having to build) the index itself.\n */\nconst catalogIndex = new WeakMap<ServerCatalog, Map<string, ToolCatalogEntry>>();\n\n/**\n * Look up a tool by name in a catalog, O(1) after the first call.\n *\n * Duplicate names resolve to the FIRST occurrence, matching `Array#find` and\n * typegen's `dedupeToolNames` (S5): a hostile server declaring the same name\n * twice must not be able to make the policy gate see a different entry (e.g.\n * a later `readOnlyHint: true` copy) than the one typegen exposed.\n */\nexport function findTool(catalog: ServerCatalog, name: string): ToolCatalogEntry | undefined {\n let index = catalogIndex.get(catalog);\n if (index === undefined) {\n index = new Map();\n for (const tool of catalog.tools) {\n if (!index.has(tool.name)) index.set(tool.name, tool);\n }\n catalogIndex.set(catalog, index);\n }\n return index.get(name);\n}\n\n/** Narrow to a non-null, non-array object. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Executes a tool call against the wrapped server. Implemented by the introspector. */\nexport interface ToolExecutor {\n callTool(\n alias: ServerAlias,\n name: string,\n args: Record<string, unknown>,\n ): Promise<ToolCallOutcome>;\n}\n\nexport type ToolCallOutcome =\n { ok: true; result: unknown } | { ok: false; error: { message: string; detail?: unknown } };\n\n// ---------------------------------------------------------------------------\n// Policy engine (PRD R14)\n// ---------------------------------------------------------------------------\n\nexport type PolicyDecision = 'auto' | 'ask' | 'deny';\n\nexport interface PolicyOverrides {\n /** Per-tool decision override, keyed by tool name (v1: single server). */\n [toolName: string]: PolicyDecision;\n}\n\n// ---------------------------------------------------------------------------\n// Machine <-> host event protocol (PRD R7)\n// ---------------------------------------------------------------------------\n\n/** A tool call requested by the machine via the `toolCall` action creator. */\nexport interface PendingToolCall {\n /** Unique id for this call within the workflow (also the inputRequest key). */\n id: string;\n name: string;\n args: Record<string, unknown>;\n /** Machine state path that requested the call (for elicitation copy — R16). */\n stateName: string;\n}\n\n/** Events the host injects into the machine. The machine never performs I/O itself. */\nexport type HostEvent =\n | { type: 'TOOL_RESULT'; callId: string; result: unknown }\n | { type: 'TOOL_ERROR'; callId: string; error: { message: string; detail?: unknown } }\n | { type: 'TOOL_DENIED'; callId: string; reason?: string };\n\n// ---------------------------------------------------------------------------\n// Structured errors and logs (PRD R25, R31)\n// ---------------------------------------------------------------------------\n\nexport type ErrorPhase =\n | 'transpile'\n | 'validate'\n | 'runtime'\n | 'cap_exceeded'\n | 'blob_verification'\n | 'protocol'\n | 'terminal';\n\nexport interface Diagnostic {\n message: string;\n /** Optional source location within the submitted code. */\n line?: number;\n column?: number;\n}\n\nexport interface StructuredError {\n phase: ErrorPhase;\n message: string;\n diagnostics: Diagnostic[];\n /** One-line actionable fix (R25). */\n hint: string;\n logs: LogEntry[];\n}\n\nexport type LogLevel = 'log' | 'info' | 'warn' | 'error' | 'debug';\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n /** Milliseconds since segment start. */\n ts: number;\n /** Zero-based MRTR segment index this entry was captured in. */\n segment: number;\n}\n\n// ---------------------------------------------------------------------------\n// Resource caps (PRD R12)\n// ---------------------------------------------------------------------------\n\nexport interface ResourceCaps {\n /** Wall-clock per execution segment, ms. */\n segmentWallClockMs: number;\n /** WASM memory, bytes. */\n wasmMemoryBytes: number;\n /** Submitted code size, bytes. */\n maxCodeBytes: number;\n /** Submitted machine input, bytes of its JSON serialization. */\n maxInputBytes: number;\n /** Read-only tool calls per segment. */\n maxReadCallsPerSegment: number;\n /** MRTR round trips per workflow. */\n maxRoundTrips: number;\n /** Machine events processed per segment. */\n maxEventsPerSegment: number;\n /** Final result payload, bytes. */\n maxResultBytes: number;\n /** Machine state nodes (static count at validation). */\n maxStateNodes: number;\n /** Captured console output per segment, bytes. */\n maxConsoleBytes: number;\n}\n\nexport const DEFAULT_CAPS: ResourceCaps = {\n segmentWallClockMs: 30_000,\n wasmMemoryBytes: 128 * 1024 * 1024,\n maxCodeBytes: 128 * 1024,\n maxInputBytes: 128 * 1024,\n maxReadCallsPerSegment: 50,\n maxRoundTrips: 8,\n maxEventsPerSegment: 10_000,\n maxResultBytes: 256 * 1024,\n maxStateNodes: 100,\n maxConsoleBytes: 64 * 1024,\n};\n\nexport const MAX_CAPS: ResourceCaps = {\n segmentWallClockMs: 60_000,\n wasmMemoryBytes: 256 * 1024 * 1024,\n maxCodeBytes: 256 * 1024,\n maxInputBytes: 256 * 1024,\n maxReadCallsPerSegment: 200,\n maxRoundTrips: 16,\n maxEventsPerSegment: 50_000,\n maxResultBytes: 1024 * 1024,\n maxStateNodes: 1_000,\n maxConsoleBytes: 256 * 1024,\n};\n\n/**\n * Smallest value each cap may be configured down to.\n *\n * Caps are \"configurable downward\" (R12), but zero or negative would brick\n * the flow rather than restrict it — a `maxRoundTrips` of 0 makes every\n * gated workflow terminal, and a `segmentWallClockMs` of 0 fails every\n * execution. Misconfiguration should not look like a library bug.\n */\nconst MIN_CAPS: ResourceCaps = {\n segmentWallClockMs: 100,\n wasmMemoryBytes: 1024 * 1024,\n maxCodeBytes: 1024,\n maxInputBytes: 1024,\n maxReadCallsPerSegment: 1,\n maxRoundTrips: 1,\n maxEventsPerSegment: 1,\n maxResultBytes: 1024,\n maxStateNodes: 1,\n maxConsoleBytes: 1024,\n};\n\n/** Clamp requested caps into [MIN_CAPS, MAX_CAPS] (R12). */\nexport function clampCaps(requested: Partial<ResourceCaps>): ResourceCaps {\n const caps = { ...DEFAULT_CAPS };\n for (const key of Object.keys(caps) as (keyof ResourceCaps)[]) {\n const value = requested[key];\n if (value !== undefined && Number.isFinite(value)) {\n caps[key] = Math.max(MIN_CAPS[key], Math.min(value, MAX_CAPS[key]));\n }\n }\n return caps;\n}\n\n// ---------------------------------------------------------------------------\n// Suspension blob (PRD R19–R23)\n// ---------------------------------------------------------------------------\n\nexport const BLOB_SCHEMA_VERSION = 1;\n\nexport interface BlobPayload {\n /** Blob schema version; unknown versions are rejected. */\n v: number;\n /** Library version that produced the snapshot. */\n libv: string;\n /** Exact XState version that produced the snapshot. */\n xstatev: string;\n /** SHA-256 (hex) of the original `code` argument. */\n codeHash: string;\n /** Server identity the blob was minted against (R30). */\n serverIdentity: string;\n /** `getPersistedSnapshot()` output of the machine actor. */\n snapshot: unknown;\n /** inputRequest key -> gated tool call awaiting a verdict (S2). */\n pending: Record<string, PendingToolCall>;\n /**\n * Approval audit accumulated in earlier segments (PRD §8).\n *\n * Carried in the blob because the library holds no cross-request state\n * (R27): without it a completed workflow would report only the approvals\n * of its final segment.\n */\n audit: AuditEntry[];\n /** Round-trip counter (R18). */\n trip: number;\n /** Random nonce for replay scoping. */\n nonce: string;\n /** Issued-at, Unix ms. */\n iat: number;\n /** Expiry, Unix ms (default TTL 15 min). */\n exp: number;\n}\n\nexport interface BlobSealerConfig {\n /** Current encryption key (32 bytes). */\n key: Uint8Array;\n /** Previous keys accepted for decryption during rotation (R22). */\n previousKeys?: Uint8Array[];\n /** Blob TTL in ms. Default 15 minutes. */\n ttlMs?: number;\n /** Sealed+compressed size ceiling in bytes. Default 128 KB (R23). */\n maxBlobBytes?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Execution results (what the machine host / MRTR adapter exchange)\n// ---------------------------------------------------------------------------\n\n/** Verdict delivered on retry for a pending gated call. */\nexport type ApprovalVerdict = { kind: 'approved' } | { kind: 'declined'; reason?: string };\n\n/** Outcome of running one execution segment. */\nexport type SegmentOutcome =\n | {\n status: 'completed';\n /** Final machine output/context to return to the client. */\n output: unknown;\n /** Per-call approval audit trail. */\n audit: AuditEntry[];\n logs: LogEntry[];\n }\n | {\n status: 'suspended';\n /** Gated calls awaiting approval, keyed by inputRequest key. */\n pending: Record<string, PendingToolCall>;\n /** Actor snapshot to seal into the blob. */\n snapshot: unknown;\n trip: number;\n audit: AuditEntry[];\n logs: LogEntry[];\n }\n | {\n status: 'error';\n error: StructuredError;\n };\n\nexport interface AuditEntry {\n callId: string;\n tool: string;\n args: Record<string, unknown>;\n decision: 'auto' | 'approved' | 'declined' | 'denied_by_policy' | 'error';\n reason?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Top-level configuration (integrating developer surface)\n// ---------------------------------------------------------------------------\n\nexport interface RedactionHook {\n /**\n * Mask sensitive argument fields before they appear in elicitation copy\n * (R16). Receives the tool name and resolved args; returns args to display.\n */\n (toolName: string, args: Record<string, unknown>): Record<string, unknown>;\n}\n\nexport interface ProjectionConfig {\n /** Resource cap overrides, clamped at maxima (R12). */\n caps?: Partial<ResourceCaps>;\n /** Per-tool policy overrides (R14). */\n policy?: PolicyOverrides;\n /** Blob sealing configuration (required for any gated flow). */\n blob: BlobSealerConfig;\n /** Redaction hook for elicitation copy (R16). */\n redact?: RedactionHook;\n /** Override the code-mode preamble appended to instructions (R29). */\n codeModePreamble?: string;\n}\n","/**\n * Version constants recorded into every blob (R20) and strict-matched on\n * open (R21, Q3: no migration — mismatches are rejected).\n *\n * Hardcoded rather than imported from package.json at runtime: JSON import\n * attributes complicate the tsdown/dist story for zero benefit, and both\n * versions are pinned exactly (DECISIONS.md D2). A test in\n * `test/blob/versions.test.ts` asserts these constants match the installed\n * package.json versions, so a version bump that forgets to update them fails\n * CI instead of silently minting blobs with a stale version stamp.\n */\n\n/** `@astral-mcp/projection` package version (must match packages/projection/package.json). */\nexport const LIB_VERSION = '0.2.0';\n\n/** Pinned XState version (must match the exact pin in package.json — D2). */\nexport const XSTATE_VERSION = '5.32.5';\n","/**\n * Suspension blob sealer (PRD §7 \"Blob sealer\"; R19–R23, S2–S4).\n *\n * Packages a {@link BlobPayload} into an opaque, authenticated, encrypted,\n * compressed envelope string that rides in the MRTR `requestState` field,\n * and verifies/opens it on resume. Clients are honest-but-curious couriers\n * (S3): they must neither read machine context (encryption) nor modify\n * anything (authentication). Every failure mode fails closed with a\n * ProjectionError; a payload is never returned partially verified.\n *\n * ## Envelope format (version `proj1`)\n *\n * ```\n * proj1.<salt>.<iv>.<ciphertext>.<tag>\n * ```\n *\n * Five dot-separated fields; all but the literal `proj1` prefix are\n * unpadded base64url:\n *\n * - `salt` — 16 random bytes, HKDF salt for per-blob key derivation\n * - `iv` — 12 random bytes, AES-GCM nonce\n * - `ciphertext` — AES-256-GCM over deflateRaw(JSON(payload))\n * - `tag` — 16-byte GCM authentication tag\n *\n * AAD is the UTF-8 bytes of the envelope header `proj1.<salt>.<iv>` (the\n * exact base64url text as transmitted), so the version prefix and header\n * fields are covered by the authentication tag. Tampering with any field\n * fails closed: the prefix and header break AAD verification, the salt\n * additionally derives a different key, and the iv/ciphertext/tag break GCM\n * authentication directly.\n *\n * ## Crypto choices\n *\n * - **AES-256-GCM** (R19): AEAD, native in node:crypto.\n * - **HKDF-SHA256** per-blob key derivation: the developer-supplied 32-byte\n * key is treated as input keying material, never used directly as a\n * cipher key. A fresh random 16-byte salt per blob means every blob is\n * encrypted under a distinct derived key, so the 96-bit random GCM nonce\n * can never repeat *under the same key* even across horizontally scaled\n * instances sealing concurrently (nonce-reuse would be catastrophic for\n * GCM). Fixed info string `@astral-mcp/projection/blob/v1` domain-separates the\n * derivation.\n * - **deflateRaw** compression (R23), not brotli: brotli's default quality\n * is far too slow for the seal+verify+rehydrate p95 < 100 ms budget\n * (PRD §10), and at speed-comparable quality settings its ratio edge on\n * small (< 32 KB typical) JSON payloads is marginal. Raw deflate also\n * omits the zlib header/adler32 checksum — GCM already guarantees\n * integrity — saving a few bytes.\n * - **Sync APIs throughout**: payloads are small (128 KB ceiling), so the\n * sync node:crypto/node:zlib forms are faster than promise overhead and\n * keep the API non-async.\n */\n\nimport { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes } from 'node:crypto';\nimport { deflateRawSync, inflateRawSync } from 'node:zlib';\nimport { ProjectionError } from '../errors.js';\nimport {\n BLOB_SCHEMA_VERSION,\n isRecord,\n type BlobPayload,\n type AuditEntry,\n type BlobSealerConfig,\n type PendingToolCall,\n} from '../types.js';\nimport { LIB_VERSION, XSTATE_VERSION } from './versions.js';\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/** Envelope format version prefix. Bump (proj2, …) on any wire-format change. */\nexport const ENVELOPE_PREFIX = 'proj1';\n\n/** Default blob TTL: 15 minutes (R20). */\nexport const DEFAULT_TTL_MS = 15 * 60 * 1000;\n\n/** Default sealed-blob size ceiling: 128 KB (R23). */\nexport const DEFAULT_MAX_BLOB_BYTES = 128 * 1024;\n\nconst KEY_BYTES = 32;\nconst SALT_BYTES = 16;\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\nconst HKDF_INFO = '@astral-mcp/projection/blob/v1';\nconst BASE64URL = /^[A-Za-z0-9_-]+$/;\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\n\nfunction verificationError(message: string, hint: string): ProjectionError {\n return new ProjectionError('blob_verification', message, { hint });\n}\n\nconst HINT_CORRUPT =\n 'The requestState blob is corrupt; retry with the exact requestState echoed from the input_required result, or re-run execute_machine to start a new workflow.';\nconst HINT_AUTH =\n 'The blob failed authentication — it was modified in transit or sealed under a key this deployment does not accept. Re-run execute_machine to start a new workflow.';\nconst HINT_VERSION =\n 'The server was upgraded since this workflow suspended; suspended workflows do not survive version changes. Re-run execute_machine to start a new workflow.';\nconst HINT_EXPIRED =\n 'The approval window elapsed before the retry arrived. Re-run execute_machine and respond to approval prompts within the TTL.';\nconst HINT_CODE =\n 'Retry the call with the byte-exact original code argument; a blob only resumes the code that produced it.';\nconst HINT_SERVER =\n 'This blob was minted against a different wrapped server and cannot be resumed here. Re-run execute_machine against this server.';\n\n// ---------------------------------------------------------------------------\n// Key handling\n// ---------------------------------------------------------------------------\n\nfunction assertKey(key: Uint8Array, label: string): void {\n if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {\n // Developer misconfiguration, not client tampering — terminal.\n throw new ProjectionError(\n 'terminal',\n `blob sealer ${label} must be exactly ${KEY_BYTES} bytes`,\n {\n hint: 'Provide a 32-byte key (e.g. crypto.randomBytes(32)) shared across all instances.',\n },\n );\n }\n}\n\nfunction assertConfigKeys(config: BlobSealerConfig): void {\n assertKey(config.key, 'key');\n for (const prev of config.previousKeys ?? []) {\n assertKey(prev, 'previousKeys entry');\n }\n}\n\n/** Derive the actual AES key from developer IKM via HKDF-SHA256 (R19). */\nfunction deriveKey(ikm: Uint8Array, salt: Buffer): Buffer {\n return Buffer.from(hkdfSync('sha256', ikm, salt, HKDF_INFO, KEY_BYTES));\n}\n\n// ---------------------------------------------------------------------------\n// Envelope\n// ---------------------------------------------------------------------------\n\ninterface ParsedEnvelope {\n salt: Buffer;\n iv: Buffer;\n ciphertext: Buffer;\n tag: Buffer;\n /** Header bytes exactly as transmitted; must match the AAD used at seal. */\n aad: Buffer;\n}\n\nfunction buildAad(saltPart: string, ivPart: string): Buffer {\n return Buffer.from(`${ENVELOPE_PREFIX}.${saltPart}.${ivPart}`, 'utf8');\n}\n\nfunction decodePart(part: string, field: string, expectedBytes?: number): Buffer {\n if (part.length === 0 || !BASE64URL.test(part)) {\n throw verificationError(`envelope parse failed: ${field} is not valid base64url`, HINT_CORRUPT);\n }\n const bytes = Buffer.from(part, 'base64url');\n if (expectedBytes !== undefined && bytes.length !== expectedBytes) {\n throw verificationError(`envelope parse failed: ${field} has unexpected length`, HINT_CORRUPT);\n }\n return bytes;\n}\n\nfunction parseEnvelope(blob: string): ParsedEnvelope {\n const parts = blob.split('.');\n const [prefix, saltPart, ivPart, ciphertextPart, tagPart] = parts;\n if (\n parts.length !== 5 ||\n prefix === undefined ||\n saltPart === undefined ||\n ivPart === undefined ||\n ciphertextPart === undefined ||\n tagPart === undefined\n ) {\n throw verificationError('envelope parse failed: expected 5 dot-separated fields', HINT_CORRUPT);\n }\n if (prefix !== ENVELOPE_PREFIX) {\n // Downgrade/upgrade of the version prefix fails closed here; even a\n // hypothetical alternate prefix with a re-encrypted body could not be\n // forged without the key, since the prefix is also covered by AAD.\n throw verificationError(\n `envelope parse failed: unsupported envelope version (expected \"${ENVELOPE_PREFIX}\")`,\n HINT_VERSION,\n );\n }\n return {\n salt: decodePart(saltPart, 'salt', SALT_BYTES),\n iv: decodePart(ivPart, 'iv', IV_BYTES),\n ciphertext: decodePart(ciphertextPart, 'ciphertext'),\n tag: decodePart(tagPart, 'tag', TAG_BYTES),\n aad: buildAad(saltPart, ivPart),\n };\n}\n\nfunction decryptWith(envelope: ParsedEnvelope, ikm: Uint8Array): Buffer {\n const key = deriveKey(ikm, envelope.salt);\n const decipher = createDecipheriv('aes-256-gcm', key, envelope.iv);\n decipher.setAAD(envelope.aad);\n decipher.setAuthTag(envelope.tag);\n return Buffer.concat([decipher.update(envelope.ciphertext), decipher.final()]);\n}\n\n/** Try the current key, then each previous key (R22 rotation grace). */\nfunction decryptWithAnyKey(envelope: ParsedEnvelope, config: BlobSealerConfig): Buffer {\n const candidates = [config.key, ...(config.previousKeys ?? [])];\n for (const ikm of candidates) {\n try {\n return decryptWith(envelope, ikm);\n } catch {\n // Auth failure under this key; try the next. Never leak which key or\n // why — the message below is uniform for all authentication failures.\n }\n }\n throw verificationError(\n 'authentication failed: blob could not be decrypted and verified with any configured key',\n HINT_AUTH,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Payload shape validation\n// ---------------------------------------------------------------------------\n\nfunction malformed(field: string): ProjectionError {\n return verificationError(\n `blob payload malformed: field \"${field}\" is missing or mistyped`,\n HINT_CORRUPT,\n );\n}\n\n/**\n * Structural check of everything except v/libv/xstatev (already exact-matched\n * by the caller before this runs). The payload is authenticated, so failures\n * here indicate a sealer bug or cross-version confusion — still fail closed.\n */\nfunction assertPayloadShape(payload: Record<string, unknown>): void {\n if (typeof payload['codeHash'] !== 'string' || payload['codeHash'].length === 0) {\n throw malformed('codeHash');\n }\n if (typeof payload['serverIdentity'] !== 'string' || payload['serverIdentity'].length === 0) {\n throw malformed('serverIdentity');\n }\n if (typeof payload['nonce'] !== 'string' || payload['nonce'].length === 0) {\n throw malformed('nonce');\n }\n if (typeof payload['iat'] !== 'number' || !Number.isFinite(payload['iat'])) {\n throw malformed('iat');\n }\n if (typeof payload['exp'] !== 'number' || !Number.isFinite(payload['exp'])) {\n throw malformed('exp');\n }\n if (typeof payload['trip'] !== 'number' || !Number.isInteger(payload['trip'])) {\n throw malformed('trip');\n }\n if (!('snapshot' in payload)) {\n throw malformed('snapshot');\n }\n const pending = payload['pending'];\n if (!isRecord(pending)) {\n throw malformed('pending');\n }\n for (const [key, call] of Object.entries(pending)) {\n if (\n !isRecord(call) ||\n typeof call['id'] !== 'string' ||\n typeof call['name'] !== 'string' ||\n typeof call['stateName'] !== 'string' ||\n !isRecord(call['args'])\n ) {\n throw malformed(`pending[\"${key}\"]`);\n }\n }\n if (!Array.isArray(payload['audit'])) {\n throw malformed('audit');\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** SHA-256 hex digest of a code argument (S4 binding — R20 `codeHash`). */\nexport function hashCode(code: string): string {\n return createHash('sha256').update(code, 'utf8').digest('hex');\n}\n\nexport interface BuildBlobPayloadInput {\n /** The original `code` argument; hashed into `codeHash` (S4). */\n code: string;\n /** Identity of the wrapped server this blob is minted against (R30). */\n serverIdentity: string;\n /** `getPersistedSnapshot()` output of the machine actor. */\n snapshot: unknown;\n /** inputRequest key -> gated tool call awaiting a verdict (S2). */\n pending: Record<string, PendingToolCall>;\n /** Approval audit accumulated so far in this workflow (PRD §8). */\n audit?: AuditEntry[] | undefined;\n /** Round-trip counter (R18). */\n trip: number;\n /** Blob TTL in ms. Default {@link DEFAULT_TTL_MS} (15 minutes). */\n ttlMs?: number | undefined;\n /** Clock override for testability, Unix ms. Default `Date.now()`. */\n now?: number | undefined;\n}\n\n/**\n * Construct a fully populated {@link BlobPayload}: stamps the schema and\n * library/XState versions, hashes the code, and fills nonce/iat/exp.\n */\nexport function buildBlobPayload(input: BuildBlobPayloadInput): BlobPayload {\n const iat = input.now ?? Date.now();\n const ttlMs = input.ttlMs ?? DEFAULT_TTL_MS;\n return {\n v: BLOB_SCHEMA_VERSION,\n libv: LIB_VERSION,\n xstatev: XSTATE_VERSION,\n codeHash: hashCode(input.code),\n serverIdentity: input.serverIdentity,\n snapshot: input.snapshot,\n pending: input.pending,\n audit: input.audit ?? [],\n trip: input.trip,\n nonce: randomBytes(16).toString('base64url'),\n iat,\n exp: iat + ttlMs,\n };\n}\n\n/**\n * Seal a payload into an opaque `proj1.` envelope string (R19, R23).\n *\n * JSON → deflateRaw → AES-256-GCM under an HKDF-SHA256 per-blob derived key,\n * with the envelope header as AAD. Throws ProjectionError phase `terminal` if\n * the sealed envelope exceeds `maxBlobBytes` (default 128 KB) or the config\n * keys are malformed.\n */\nexport function sealBlob(payload: BlobPayload, config: BlobSealerConfig): string {\n assertKey(config.key, 'key');\n const compressed = deflateRawSync(Buffer.from(JSON.stringify(payload), 'utf8'), { level: 9 });\n const salt = randomBytes(SALT_BYTES);\n const iv = randomBytes(IV_BYTES);\n const saltPart = salt.toString('base64url');\n const ivPart = iv.toString('base64url');\n const cipher = createCipheriv('aes-256-gcm', deriveKey(config.key, salt), iv);\n cipher.setAAD(buildAad(saltPart, ivPart));\n const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]);\n const tag = cipher.getAuthTag();\n const blob = `${ENVELOPE_PREFIX}.${saltPart}.${ivPart}.${ciphertext.toString('base64url')}.${tag.toString('base64url')}`;\n\n const maxBlobBytes = config.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES;\n const size = Buffer.byteLength(blob, 'utf8');\n if (size > maxBlobBytes) {\n throw new ProjectionError(\n 'terminal',\n `sealed suspension blob is ${size} bytes, exceeding the ${maxBlobBytes}-byte ceiling`,\n {\n hint: 'Machine context is too large to suspend. Keep large tool results out of context — store only the fields later states need — then re-run execute_machine.',\n },\n );\n }\n return blob;\n}\n\nexport interface OpenBlobOptions {\n /** The `code` argument re-sent with the retried call (S4). */\n code: string;\n /** Identity of the wrapped server handling the retry (R30). */\n serverIdentity: string;\n config: BlobSealerConfig;\n /** Clock override for testability, Unix ms. Default `Date.now()`. */\n now?: number | undefined;\n}\n\n/**\n * Verify and open a sealed blob (R21 — check order is normative):\n *\n * 1. parse envelope + decrypt/authenticate (current key, then each\n * `previousKeys` — R22 rotation grace)\n * 2. schema version, then exact `libv`/`xstatev` match (Q3: strict, no\n * migration)\n * 3. expiry (`exp` strictly in the future relative to `now`)\n * 4. `codeHash` equality against the re-sent code, and `serverIdentity`\n * match\n *\n * Any failure throws ProjectionError phase `blob_verification` naming the\n * failed check (never key material or plaintext). A payload is only\n * returned once every check has passed.\n */\nexport function openBlob(blob: string, options: OpenBlobOptions): BlobPayload {\n assertConfigKeys(options.config);\n\n // (0) Inbound size guard: the sealer never emits a blob above\n // `maxBlobBytes` (R23), so anything larger is garbage — reject it before\n // spending any base64/AES work on it (pre-auth DoS resistance). A small\n // slack multiple keeps this insensitive to byte-vs-char accounting.\n const maxBlobBytes = options.config.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES;\n if (blob.length > maxBlobBytes * 2) {\n throw verificationError(\n `blob rejected: ${blob.length} characters exceeds the acceptance limit for a ${maxBlobBytes}-byte ceiling`,\n HINT_CORRUPT,\n );\n }\n\n // (1) Parse + decrypt/authenticate.\n const envelope = parseEnvelope(blob);\n const compressed = decryptWithAnyKey(envelope, options.config);\n let payload: unknown;\n try {\n // Decompression cap (defense-in-depth): bound the inflate output\n // rather than trusting it. Generous multiple — the ceiling applies to\n // the sealed size, and a legitimate payload may compress well — but a\n // decompression bomb is cut off long before it exhausts memory.\n payload = JSON.parse(\n inflateRawSync(compressed, { maxOutputLength: maxBlobBytes * 64 }).toString('utf8'),\n ) as unknown;\n } catch {\n throw verificationError(\n 'blob payload is corrupt: decompression or JSON parse failed after authentication',\n HINT_CORRUPT,\n );\n }\n if (!isRecord(payload)) {\n throw verificationError('blob payload malformed: not a JSON object', HINT_CORRUPT);\n }\n\n // (2) Schema version, then exact library/XState version match (Q3).\n if (payload['v'] !== BLOB_SCHEMA_VERSION) {\n throw verificationError(\n `unknown blob schema version ${JSON.stringify(payload['v'])} (this library expects ${BLOB_SCHEMA_VERSION})`,\n HINT_VERSION,\n );\n }\n if (payload['libv'] !== LIB_VERSION) {\n throw verificationError(\n `library version mismatch: blob was sealed by @astral-mcp/projection ${JSON.stringify(payload['libv'])}, this instance runs ${LIB_VERSION}`,\n HINT_VERSION,\n );\n }\n if (payload['xstatev'] !== XSTATE_VERSION) {\n throw verificationError(\n `xstate version mismatch: blob snapshot was produced under xstate ${JSON.stringify(payload['xstatev'])}, this instance runs ${XSTATE_VERSION}`,\n HINT_VERSION,\n );\n }\n assertPayloadShape(payload);\n const verified = payload as unknown as BlobPayload;\n\n // (3) Expiry.\n const now = options.now ?? Date.now();\n if (now >= verified.exp) {\n throw verificationError(\n `blob expired: exp was ${verified.exp} and it is now ${now}`,\n HINT_EXPIRED,\n );\n }\n\n // (4) Code hash (S4) and server identity (R30, cross-server replay).\n if (hashCode(options.code) !== verified.codeHash) {\n throw verificationError(\n \"code hash mismatch: the retried call's code differs from the code that produced this blob\",\n HINT_CODE,\n );\n }\n if (options.serverIdentity !== verified.serverIdentity) {\n throw verificationError(\n 'server identity mismatch: blob was minted against a different wrapped server',\n HINT_SERVER,\n );\n }\n\n return verified;\n}\n","/**\n * Console capture with byte-capped, drop-middle truncation (R31, R12).\n *\n * All `console.log/info/warn/error/debug` calls inside the VM are recorded as\n * structured {@link LogEntry} values. The total captured output per segment is\n * capped at `maxConsoleBytes`: the head and tail of the stream are kept (half\n * the budget each) and the middle is dropped, replaced by a single explicit\n * truncation marker entry.\n */\n\nimport type { LogEntry, LogLevel } from '../types.js';\n\nconst encoder = new TextEncoder();\n\n/** UTF-8 byte length of a string (shared cached encoder). */\nexport function utf8Length(value: string): number {\n return encoder.encode(value).length;\n}\n\n/** Truncate a string to at most `maxBytes` UTF-8 bytes, appending a marker. */\nfunction truncateUtf8(value: string, maxBytes: number): string {\n if (utf8Length(value) <= maxBytes) {\n return value;\n }\n const suffix = '…[truncated]';\n let end = Math.min(value.length, maxBytes);\n while (end > 0 && utf8Length(value.slice(0, end)) + utf8Length(suffix) > maxBytes) {\n end = Math.floor(end / 2);\n }\n return value.slice(0, end) + suffix;\n}\n\n/** Best-effort single-string rendering of one console argument. */\nfunction formatParam(param: unknown): string {\n if (typeof param === 'string') {\n return param;\n }\n if (param instanceof Error) {\n return `${param.name}: ${param.message}`;\n }\n if (typeof param === 'function') {\n return '[function]';\n }\n try {\n const json = JSON.stringify(param);\n return json === undefined ? String(param) : json;\n } catch {\n return String(param);\n }\n}\n\n/** Marker prefix used in the synthetic truncation entry. */\nexport const TRUNCATION_MARKER_PREFIX = '[@astral-mcp/projection] console output truncated:';\n\n/**\n * Collects console output for one execution segment, enforcing the\n * `maxConsoleBytes` cap with drop-middle truncation.\n */\nexport class LogCollector {\n private readonly head: LogEntry[] = [];\n private readonly tail: LogEntry[] = [];\n private headBytes = 0;\n private tailBytes = 0;\n private dropped = 0;\n private readonly halfBudget: number;\n private readonly startedAt = Date.now();\n\n constructor(\n private readonly maxBytes: number,\n private readonly segment: number,\n ) {\n this.halfBudget = Math.max(64, Math.floor(maxBytes / 2));\n }\n\n /** Record one console call. `params` are the marshaled console arguments. */\n push(level: LogLevel, params: unknown[]): void {\n const message = truncateUtf8(params.map(formatParam).join(' '), this.halfBudget);\n const cost = utf8Length(message);\n const entry: LogEntry = {\n level,\n message,\n ts: Date.now() - this.startedAt,\n segment: this.segment,\n };\n if (this.tail.length === 0 && this.headBytes + cost <= this.halfBudget) {\n this.head.push(entry);\n this.headBytes += cost;\n return;\n }\n this.tail.push(entry);\n this.tailBytes += cost;\n while (this.tailBytes > this.halfBudget && this.tail.length > 1) {\n const evicted = this.tail.shift();\n if (evicted !== undefined) {\n this.tailBytes -= utf8Length(evicted.message);\n this.dropped += 1;\n }\n }\n }\n\n /**\n * The captured entries in order. When entries were dropped, a synthetic\n * `warn` marker entry sits between the kept head and tail.\n */\n snapshot(): LogEntry[] {\n if (this.dropped === 0) {\n return [...this.head, ...this.tail];\n }\n const marker: LogEntry = {\n level: 'warn',\n message: `${TRUNCATION_MARKER_PREFIX} ${this.dropped} entries dropped (maxConsoleBytes=${this.maxBytes})`,\n ts: this.tail[0]?.ts ?? Date.now() - this.startedAt,\n segment: this.segment,\n };\n return [...this.head, marker, ...this.tail];\n }\n}\n","/**\n * Module mounting and import resolution for the QuickJS sandbox (R8, R9, S1).\n *\n * The sandbox's virtual filesystem contains exactly what module resolution\n * needs and nothing else:\n *\n * - `/src/machine.js` — the (transpiled) authored module\n * - `/node_modules/xstate/*` — the pinned XState v5 ESM build\n * - `/node_modules/@astral-mcp/tools/index.js` — the caller-supplied bridge\n *\n * Import resolution is allowlist-based: only `xstate` and `@astral-mcp/tools`\n * resolve for authored code (plus the handful of pure-utility modules the\n * QuickJS runtime itself boots with: `buffer`, `util`, `url` and the\n * `@node_compatibility/*` shims — none of which perform I/O). Every other\n * specifier — including `node:fs`, `node:child_process`, `http`, arbitrary\n * package names — resolves to a sentinel path whose load fails with a\n * structured, model-actionable error message.\n */\n\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve as resolvePath } from 'node:path';\nimport { getModuleLoader, type SandboxOptions } from '@sebastianwessel/quickjs';\n\ntype NodeModulesMount = NonNullable<SandboxOptions['nodeModules']>;\ntype ModulePathNormalizer = NonNullable<SandboxOptions['modulePathNormalizer']>;\ntype GetModuleLoader = NonNullable<SandboxOptions['getModuleLoader']>;\n\n/** In-sandbox path of the authored module. Driver code imports it as `./machine.js`. */\nexport const AUTHORED_MODULE_PATH = '/src/machine.js';\n\n/** Specifier the authored code uses to import XState (R8). */\nexport const XSTATE_SPECIFIER = 'xstate';\n\n/** Specifier the authored code uses to import the generated tools bridge (R8). */\nexport const TOOLS_SPECIFIER = '@astral-mcp/tools';\n\n/** Sentinel path prefix produced by the normalizer for disallowed imports. */\nconst DENIED_PREFIX = '/__projection_denied__/';\n\n/** Marker embedded in denied-import error messages; used for error classification. */\nexport const DENIED_IMPORT_MARKER = 'cannot be imported inside the sandbox';\n\n/**\n * Bare specifiers that resolve inside the sandbox. `xstate` and\n * `@astral-mcp/tools` are the authoring contract (R8); the rest are pure\n * utilities required by the QuickJS runtime's own node-compatibility\n * bootstrap (`node:buffer`, `node:util`, `node:url` and the\n * `@node_compatibility/*` shims). None of them expose I/O.\n */\nconst ALLOWED_SPECIFIERS: ReadonlySet<string> = new Set([\n XSTATE_SPECIFIER,\n TOOLS_SPECIFIER,\n 'buffer',\n 'util',\n 'url',\n '@node_compatibility/event-target',\n '@node_compatibility/headers',\n '@node_compatibility/request',\n '@node_compatibility/response',\n]);\n\nlet cachedXStateMount: Record<string, string> | undefined;\n\n/**\n * Build the virtual `node_modules/xstate` directory from the pinned XState v5\n * package installed on the host: the production ESM entry (`xstate.esm.js`,\n * mounted additionally as `index.js`) plus its sibling ESM chunk files, which\n * it references via relative imports. The chunks are self-contained (no bare\n * imports), so nothing else needs to resolve.\n */\nexport function getXStateMount(): Record<string, string> {\n if (cachedXStateMount === undefined) {\n const require = createRequire(import.meta.url);\n const distDir = join(dirname(require.resolve('xstate/package.json')), 'dist');\n const mount: Record<string, string> = {};\n for (const file of readdirSync(distDir)) {\n if (file.endsWith('.esm.js') && !file.includes('development')) {\n mount[file] = readFileSync(join(distDir, file), 'utf8');\n }\n }\n const entry = mount['xstate.esm.js'];\n if (entry === undefined) {\n throw new Error('xstate package layout not recognized: dist/xstate.esm.js missing');\n }\n mount['index.js'] = entry;\n cachedXStateMount = mount;\n }\n return cachedXStateMount;\n}\n\n/** Assemble the sandbox `node_modules` mount: xstate + the tools bridge. */\nexport function buildNodeModulesMount(bridgeJs: string): NodeModulesMount {\n return {\n xstate: { ...getXStateMount() },\n '@astral-mcp': { tools: { 'index.js': bridgeJs } },\n };\n}\n\n/**\n * Allowlisting module path normalizer (R8/R9). Relative imports resolve\n * against the importing module; allowlisted bare specifiers resolve into\n * `/node_modules`; everything else maps to a denied sentinel path.\n *\n * `xstate` and `@astral-mcp/tools` map directly to their `index.js` files\n * (rather than the package directory) so that the relative chunk imports\n * inside them resolve against the package directory.\n */\nexport const modulePathNormalizer: ModulePathNormalizer = (baseName, requestedName) => {\n if (requestedName.startsWith('.')) {\n const parts = baseName.split('/');\n parts.pop();\n return resolvePath(`/${parts.join('/')}`, requestedName);\n }\n const name = requestedName.replace(/^node:/, '');\n if (name === XSTATE_SPECIFIER) {\n return '/node_modules/xstate/index.js';\n }\n if (name === TOOLS_SPECIFIER) {\n return '/node_modules/@astral-mcp/tools/index.js';\n }\n if (ALLOWED_SPECIFIERS.has(name)) {\n return join('/node_modules', name);\n }\n return `${DENIED_PREFIX}${requestedName}`;\n};\n\n/**\n * Module loader wrapping the package default: turns denied sentinel paths\n * into a structured, actionable error (R25); defers everything else to the\n * default memfs-backed loader.\n */\nexport const getSandboxModuleLoader: GetModuleLoader = (fs, runtimeOptions) => {\n const defaultLoader = getModuleLoader(fs, runtimeOptions);\n return (name, context) => {\n if (name.startsWith(DENIED_PREFIX)) {\n const specifier = name.slice(DENIED_PREFIX.length);\n return {\n error: new Error(\n `'${specifier}' ${DENIED_IMPORT_MARKER}; only '${XSTATE_SPECIFIER}' and '${TOOLS_SPECIFIER}' are importable`,\n ),\n };\n }\n return defaultLoader(name, context);\n };\n};\n","/**\n * Sandbox session implementation. See ./index.ts for the boundary contract\n * the machine host builds against.\n */\n\nimport {\n getTypescriptSupport,\n loadQuickJs,\n type ErrorResponse,\n type SandboxEvalCode,\n type SandboxOptions,\n} from '@sebastianwessel/quickjs';\nimport type TS from 'typescript';\nimport { ProjectionError } from '../errors.js';\nimport { clampCaps, type LogEntry, type ResourceCaps } from '../types.js';\nimport { LogCollector, utf8Length } from './logs.js';\nimport {\n buildNodeModulesMount,\n DENIED_IMPORT_MARKER,\n getSandboxModuleLoader,\n modulePathNormalizer,\n TOOLS_SPECIFIER,\n XSTATE_SPECIFIER,\n} from './mounts.js';\n\n// ---------------------------------------------------------------------------\n// Public option/handle types\n// ---------------------------------------------------------------------------\n\n/** A tool call surfaced from the `@astral-mcp/tools` bridge inside the VM. */\nexport interface SandboxToolCall {\n name: string;\n args: Record<string, unknown>;\n}\n\n/**\n * Host callback invoked for every bridge tool call made inside the VM.\n *\n * The returned value (or resolved promise value) is marshaled back into the\n * VM as the bridge call's result; a thrown error / rejected promise rejects\n * the in-VM promise. Values must be JSON-serializable. The sandbox attaches\n * no semantics to the payload — result/error/denial encoding is the machine\n * host's protocol.\n */\nexport type SandboxToolCallHandler = (call: SandboxToolCall) => unknown | Promise<unknown>;\n\nexport interface SandboxSessionOptions {\n /** The submitted module source (R2). */\n code: string;\n /** Language of `code`. TypeScript is transpiled without type checking (R10). */\n lang?: 'ts' | 'js';\n /** Resource cap overrides; clamped at the hard maxima via `clampCaps` (R12). */\n caps?: Partial<ResourceCaps>;\n /**\n * Source text of the module mounted at `@astral-mcp/tools` (R8). Generated\n * by the typegen component. May be TypeScript or JavaScript; must be a\n * single module (relative imports do not resolve outside the mount).\n */\n bridgeSource: string;\n /** Host callback for bridge tool calls. */\n onToolCall: SandboxToolCallHandler;\n /** Zero-based MRTR segment index, recorded on every log entry (R31). */\n segment?: number;\n}\n\n/**\n * A live sandbox holding the evaluated authored module. One session is one\n * execution segment: it owns a fresh wall-clock budget (R13) and a fresh log\n * collector (R31). Sessions are single-threaded — `evaluate` calls are\n * serialized internally.\n */\nexport interface SandboxSession {\n /** The effective (clamped) caps this session enforces. */\n readonly caps: ResourceCaps;\n /** Zero-based MRTR segment index this session was created for. */\n readonly segment: number;\n /**\n * Evaluate an ESM driver module inside the VM and return its default\n * export marshaled to the host (promises are awaited). Rejects with\n * {@link ProjectionError} on failure. See ./index.ts for the contract.\n */\n evaluate(source: string): Promise<unknown>;\n /** Logs captured so far this segment, truncated per `maxConsoleBytes`. */\n getLogs(): LogEntry[];\n /** Tear down the VM. Idempotent. Pending bridge promises are rejected. */\n dispose(): Promise<void>;\n}\n\n// ---------------------------------------------------------------------------\n// In-VM binding points (also part of the boundary contract)\n// ---------------------------------------------------------------------------\n\n/** Global object the boot script installs inside the VM. */\nexport const SANDBOX_GLOBAL = '__projection';\n\n/**\n * Name of the host bridge function on the in-VM `env` object. The bridge\n * module calls `env.__projection_toolCall(name, args)` and receives a promise.\n */\nexport const TOOL_CALL_BINDING = '__projection_toolCall';\n\n// ---------------------------------------------------------------------------\n// Lazy singletons: QuickJS WASM runtime and TypeScript transpiler\n// ---------------------------------------------------------------------------\n\ntype QuickJsRuntime = Awaited<ReturnType<typeof loadQuickJs>>;\ntype TsSupport = Awaited<ReturnType<typeof getTypescriptSupport>>;\n\nlet quickJsPromise: Promise<QuickJsRuntime> | undefined;\nlet tsSupportPromise: Promise<TsSupport> | undefined;\n\nconst QUICKJS_VARIANT = '@jitl/quickjs-ng-wasmfile-release-sync';\n\nfunction getQuickJs(): Promise<QuickJsRuntime> {\n quickJsPromise ??= (async () => {\n let variant: { default: Parameters<typeof loadQuickJs>[0] };\n try {\n variant = await import(QUICKJS_VARIANT);\n } catch (cause) {\n quickJsPromise = undefined;\n throw new ProjectionError(\n 'runtime',\n `QuickJS WASM variant '${QUICKJS_VARIANT}' is not installed`,\n {\n hint: `Add ${QUICKJS_VARIANT} to the @astral-mcp/projection package dependencies`,\n cause,\n },\n );\n }\n return loadQuickJs(variant.default);\n })();\n return quickJsPromise;\n}\n\n/**\n * Environment-class transpile failure: the TypeScript transpiler itself is\n * missing or incompatible, as opposed to a syntax error in the source being\n * transpiled. `createSandboxSession` lets these pass through unrewrapped so\n * the environment diagnostics (and their hints) reach the consumer instead\n * of being misreported as an invalid-bridgeSource integration bug.\n */\nclass TranspilerUnavailableError extends ProjectionError {}\n\nfunction getTsSupport(): Promise<TsSupport> {\n tsSupportPromise ??= (async () => {\n // `typescript` is a real dependency (the generated tools bridge is\n // always TypeScript), but guard against a consumer force-resolving an\n // incompatible major: TS 7 removed the `ts.transpile` API the QuickJS\n // support layer calls, which would otherwise surface as an opaque\n // \"ts.transpile is not a function\" at machine run time.\n const ts = (await import('typescript')) as { transpile?: unknown; version?: string };\n if (typeof ts.transpile !== 'function') {\n throw new TranspilerUnavailableError(\n 'transpile',\n `the installed typescript@${ts.version ?? 'unknown'} does not provide ts.transpile`,\n {\n hint: '@astral-mcp/projection requires typescript ^5 (TS 6+/7+ removed the transpile API). Pin typescript to ^5.7.0.',\n },\n );\n }\n // quickjs's getTypescriptSupport performs its own `import('typescript')`,\n // which under flat/hoisted node_modules layouts can resolve a DIFFERENT\n // copy than the one validated above (e.g. a hoisted root typescript@7\n // next to @astral-mcp/projection's own nested 5.x). Pass our resolved specifier so\n // the support layer loads the exact copy we just checked. Falls back to\n // quickjs's own resolution where import.meta.resolve is unavailable\n // (e.g. bundler-transformed environments).\n const typescriptImportFile =\n typeof import.meta.resolve === 'function' ? import.meta.resolve('typescript') : undefined;\n return getTypescriptSupport(true, typescriptImportFile);\n })().catch((cause: unknown) => {\n tsSupportPromise = undefined;\n if (cause instanceof ProjectionError) throw cause;\n throw new TranspilerUnavailableError('transpile', 'TypeScript transpiler is not available', {\n hint: 'Reinstall dependencies: @astral-mcp/projection depends on typescript ^5 for machine and bridge transpilation.',\n cause,\n });\n });\n return tsSupportPromise;\n}\n\n// ---------------------------------------------------------------------------\n// TypeScript transpilation (in-sandbox toolchain, no type checking — R10)\n// ---------------------------------------------------------------------------\n\nfunction flattenDiagnosticMessage(messageText: string | TS.DiagnosticMessageChain): string {\n if (typeof messageText === 'string') {\n return messageText;\n }\n const parts = [messageText.messageText];\n for (const next of messageText.next ?? []) {\n parts.push(flattenDiagnosticMessage(next.messageText));\n }\n return parts.join(' ');\n}\n\n/**\n * Transpile the (invariant) tools bridge, memoized by source. Bounded so a\n * process that wraps many distinct servers can't grow the cache unbounded.\n */\nconst bridgeCache = new Map<string, string>();\nconst BRIDGE_CACHE_MAX = 32;\n\nasync function transpileBridge(source: string): Promise<string> {\n const cached = bridgeCache.get(source);\n if (cached !== undefined) return cached;\n const js = await transpileTs(source, '/bridge/index.ts');\n if (bridgeCache.size >= BRIDGE_CACHE_MAX) {\n const oldest = bridgeCache.keys().next().value;\n if (oldest !== undefined) bridgeCache.delete(oldest);\n }\n bridgeCache.set(source, js);\n return js;\n}\n\nasync function transpileTs(source: string, fileName: string): Promise<string> {\n const support = await getTsSupport();\n const diagnostics: TS.Diagnostic[] = [];\n const js = support.transpileFile(source, undefined, fileName, diagnostics);\n const errors = diagnostics.filter((d) => d.category === 1 /* ts.DiagnosticCategory.Error */);\n if (errors.length > 0) {\n throw new ProjectionError('transpile', 'TypeScript transpilation failed', {\n diagnostics: errors.map((d) => {\n const message = flattenDiagnosticMessage(d.messageText);\n if (d.file !== undefined && d.start !== undefined) {\n const pos = d.file.getLineAndCharacterOfPosition(d.start);\n return { message, line: pos.line + 1, column: pos.character + 1 };\n }\n return { message };\n }),\n hint: 'Fix the syntax error; TypeScript is transpiled without type checking, so only syntax matters',\n });\n }\n return js;\n}\n\n// ---------------------------------------------------------------------------\n// Error classification (R25 phases)\n// ---------------------------------------------------------------------------\n\nfunction classifyEvalError(\n response: ErrorResponse,\n caps: ResourceCaps,\n logs: LogEntry[],\n): ProjectionError {\n const { name, message, stack } = response.error;\n const diagnostics = stack !== undefined && stack.length > 0 ? [{ message: stack }] : [];\n if (\n name === 'ExecutionTimeout' ||\n message === 'interrupted' ||\n message.includes('maximum allowed time limit')\n ) {\n return new ProjectionError(\n 'cap_exceeded',\n `Execution exceeded the wall-clock budget of ${caps.segmentWallClockMs} ms for this segment`,\n {\n diagnostics,\n hint: 'Remove long or unbounded loops; heavy work must happen through tool calls, not in-machine computation',\n logs,\n },\n );\n }\n if (/out of memory/i.test(message)) {\n return new ProjectionError(\n 'cap_exceeded',\n `Execution exceeded the memory limit of ${caps.wasmMemoryBytes} bytes`,\n {\n diagnostics,\n hint: 'Keep machine context small; avoid accumulating large arrays or strings in the sandbox',\n logs,\n },\n );\n }\n if (message.includes(DENIED_IMPORT_MARKER) || message.includes('not installed or available')) {\n return new ProjectionError('validate', message, {\n diagnostics,\n hint: `Only '${XSTATE_SPECIFIER}' and '${TOOLS_SPECIFIER}' can be imported; there is no filesystem or network access`,\n logs,\n });\n }\n if (response.isSyntaxError === true || name === 'SyntaxError') {\n return new ProjectionError('validate', `${name}: ${message}`, {\n diagnostics,\n hint: 'Fix the JavaScript syntax error shown in diagnostics',\n logs,\n });\n }\n return new ProjectionError('runtime', `${name}: ${message}`, {\n diagnostics,\n hint: 'Uncaught error inside the sandbox; see diagnostics and logs, correct the code, and retry',\n logs,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Session\n// ---------------------------------------------------------------------------\n\ninterface Deferred<T> {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n}\n\nfunction deferred<T>(): Deferred<T> {\n let resolve!: (value: T) => void;\n let reject!: (error: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n}\n\n/** No-op sink for console methods that are captured nowhere (R31 covers five levels). */\nconst silent = (): void => {};\n\n/**\n * Create a sandbox session: boot a fresh QuickJS VM, mount xstate and the\n * bridge, evaluate the authored module, and return a handle for driving it.\n * See ./index.ts for the full boundary contract.\n */\nexport async function createSandboxSession(\n options: SandboxSessionOptions,\n): Promise<SandboxSession> {\n const caps = clampCaps(options.caps ?? {});\n const segment = options.segment ?? 0;\n const lang = options.lang ?? 'js';\n\n const codeBytes = utf8Length(options.code);\n if (codeBytes > caps.maxCodeBytes) {\n throw new ProjectionError(\n 'cap_exceeded',\n `Submitted code is ${codeBytes} bytes; the maximum is ${caps.maxCodeBytes} bytes`,\n {\n hint: 'Shrink the machine: remove comments and dead states, and keep large data out of the source',\n },\n );\n }\n\n const machineJs =\n lang === 'ts' ? await transpileTs(options.code, '/src/machine.ts') : options.code;\n // The bridge is library/typegen-supplied and invariant across every segment\n // of a workflow, so its transpile output is cached by source (a plain-JS\n // bridge passes through unchanged). Only the machine code varies per call.\n let bridgeJs: string;\n try {\n bridgeJs = await transpileBridge(options.bridgeSource);\n } catch (error) {\n // Transpiler-availability failures (typescript missing or incompatible)\n // are environment diagnostics, not a bad bridgeSource — pass them\n // through so the consumer sees the real cause and its fix hint.\n if (error instanceof TranspilerUnavailableError) throw error;\n if (error instanceof ProjectionError && error.phase === 'transpile') {\n throw new ProjectionError(\n 'runtime',\n 'The @astral-mcp/tools bridge module failed to transpile',\n {\n diagnostics: error.diagnostics,\n hint: 'The bridgeSource passed to createSandboxSession is invalid; this is an integration bug, not a model error',\n cause: error,\n },\n );\n }\n throw error;\n }\n\n const logs = new LogCollector(caps.maxConsoleBytes, segment);\n const capture =\n (level: 'log' | 'info' | 'warn' | 'error' | 'debug') =>\n (...params: unknown[]) => {\n logs.push(level, params);\n };\n\n const onToolCall = options.onToolCall;\n const sandboxOptions: SandboxOptions = {\n // Hard caps (R12/R13). The wall-clock budget is enforced by a QuickJS\n // interrupt handler installed by the runtime, with an absolute deadline\n // of `now + segmentWallClockMs` at session creation.\n executionTimeout: caps.segmentWallClockMs,\n memoryLimit: caps.wasmMemoryBytes,\n // N3/R11 invariant: `allowFetch` and `allowFs` are never set — they\n // default to disabled and this options object is built here, never from\n // caller input. The boot script below additionally deletes the `fetch`\n // global stub.\n mountFs: { src: { 'machine.js': machineJs } },\n nodeModules: buildNodeModulesMount(bridgeJs),\n modulePathNormalizer,\n getModuleLoader: getSandboxModuleLoader,\n env: {\n [TOOL_CALL_BINDING]: (name: unknown, args: unknown) => {\n const call: SandboxToolCall = {\n name: typeof name === 'string' ? name : String(name),\n args:\n typeof args === 'object' && args !== null && !Array.isArray(args)\n ? (args as Record<string, unknown>)\n : {},\n };\n return Promise.resolve(onToolCall(call));\n },\n },\n console: {\n log: capture('log'),\n info: capture('info'),\n warn: capture('warn'),\n error: capture('error'),\n debug: capture('debug'),\n trace: capture('debug'),\n assert: (condition?: boolean, ...data: unknown[]) => {\n if (condition !== true) {\n logs.push('error', ['Assertion failed:', ...data]);\n }\n },\n dir: capture('log'),\n table: capture('log'),\n count: silent,\n countReset: silent,\n dirxml: silent,\n group: silent,\n groupCollapsed: silent,\n groupEnd: silent,\n time: silent,\n timeEnd: silent,\n timeLog: silent,\n clear: silent,\n },\n };\n\n const runtime = await getQuickJs();\n\n // Absolute segment deadline (R13). The QuickJS interrupt handler enforces\n // it inside the VM; this host-side copy makes post-deadline `evaluate`\n // calls fail deterministically even when a script is too short to hit an\n // interrupt check.\n const deadlineAt = Date.now() + caps.segmentWallClockMs;\n\n const ready = deferred<{ evalCode: SandboxEvalCode }>();\n const hold = deferred<void>();\n let disposed = false;\n\n const runPromise = runtime.runSandboxed(async ({ evalCode }) => {\n ready.resolve({ evalCode });\n await hold.promise;\n }, sandboxOptions);\n // The run promise is also awaited in dispose(); avoid unhandled rejections.\n runPromise.catch(() => {});\n\n const { evalCode } = await Promise.race([\n ready.promise,\n runPromise.then(() => {\n throw new ProjectionError('runtime', 'QuickJS sandbox terminated during startup', {\n hint: 'This is a sandbox runtime bug; check the host logs',\n logs: logs.snapshot(),\n });\n }),\n ]);\n\n const dispose = async (): Promise<void> => {\n if (!disposed) {\n disposed = true;\n hold.resolve();\n await runPromise.catch(() => {});\n }\n };\n\n // Serialize all VM entries: QuickJS contexts are single-threaded and the\n // eval helper is not reentrant.\n let queue: Promise<unknown> = Promise.resolve();\n let evalCounter = 0;\n const runInVm = (source: string): Promise<unknown> => {\n const task = async (): Promise<unknown> => {\n if (disposed) {\n throw new ProjectionError('runtime', 'Sandbox session already disposed', {\n hint: 'Create a new session for each execution segment',\n });\n }\n if (Date.now() >= deadlineAt) {\n throw new ProjectionError(\n 'cap_exceeded',\n `Execution exceeded the wall-clock budget of ${caps.segmentWallClockMs} ms for this segment`,\n {\n hint: 'The segment budget is spent; a fresh session (MRTR resume) gets a fresh budget',\n logs: logs.snapshot(),\n },\n );\n }\n const filename = `/src/__projection_eval_${evalCounter++}__.js`;\n const result = await evalCode(source, filename);\n if (!result.ok) {\n throw classifyEvalError(result, caps, logs.snapshot());\n }\n return result.data;\n };\n const run = queue.then(task, task);\n queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n };\n\n // Boot: harden globals first (N3) — a separate eval, because ESM imports\n // are hoisted and would otherwise run the authored module before the\n // hardening statements. Then evaluate the authored module (R10) and publish\n // its namespace at `globalThis.__projection.module`.\n //\n // S1 note on `process`: the QuickJS provider injects a `process` global\n // whose `process.env` is the `env` binding object built at `env:` above —\n // it holds ONLY `__projection_toolCall` and never any host environment\n // variable (verified: PATH/HOME and planted canaries are absent in-VM). It\n // is deliberately not deleted here because that same object is how the\n // tools bridge reaches the host (the sole I/O channel). Any change to the\n // `env:` option below MUST keep it to the tool-call binding alone; adding\n // host-derived entries would leak them into authored code through\n // `process.env`.\n try {\n await runInVm(`delete globalThis.fetch; export default null;`);\n await runInVm(\n `import * as mod from './machine.js';\n globalThis.${SANDBOX_GLOBAL} = { module: mod, state: {} };\n export default null;`,\n );\n } catch (error) {\n await dispose();\n throw error;\n }\n\n return {\n caps,\n segment,\n evaluate: runInVm,\n getLogs: () => logs.snapshot(),\n dispose,\n };\n}\n","/**\n * Policy decisions for tool calls (PRD R14, S5).\n *\n * Pure functions: annotation-derived defaults plus developer overrides.\n * Annotations come from a possibly third-party wrapped server and are\n * untrusted hints — they can only ever make the default *stricter* than an\n * explicit developer override, never looser. A developer override always\n * wins, in every combination.\n */\n\nimport { ProjectionError } from '../errors.js';\nimport { findTool } from '../types.js';\nimport type {\n PendingToolCall,\n PolicyDecision,\n PolicyOverrides,\n ServerCatalog,\n ToolCatalogEntry,\n} from '../types.js';\n\nconst VALID_DECISIONS: ReadonlySet<string> = new Set(['auto', 'ask', 'deny']);\n\n/**\n * Decide the policy for a catalog tool (R14).\n *\n * - A developer override (`auto` | `ask` | `deny`) always wins.\n * - With no override, `annotations.readOnlyHint === true` yields `auto`;\n * an absent or `false` hint yields `ask` (S5: unannotated defaults to ask).\n * - An override entry with an unrecognized value (possible when the config\n * arrives untyped) fails safe to `ask` — it never grants `auto`.\n *\n * Only own properties of `overrides` are consulted, so tools named like\n * `Object.prototype` members (`toString`, `constructor`, ...) cannot pick up\n * inherited junk as a decision.\n */\nexport function decidePolicy(entry: ToolCatalogEntry, overrides?: PolicyOverrides): PolicyDecision {\n if (overrides !== undefined && Object.hasOwn(overrides, entry.name)) {\n const override: unknown = overrides[entry.name];\n if (typeof override === 'string' && VALID_DECISIONS.has(override)) {\n return override as PolicyDecision;\n }\n // Malformed override value: fail safe. Never auto-execute on garbage.\n return 'ask';\n }\n return entry.annotations?.readOnlyHint === true ? 'auto' : 'ask';\n}\n\n/** Result of resolving a pending call against a server catalog. */\nexport type ResolvedCallPolicy =\n | { ok: true; decision: PolicyDecision; entry: ToolCatalogEntry }\n | { ok: false; error: ProjectionError };\n\n/**\n * Resolve a machine-requested tool call against the server catalog and\n * decide its policy.\n *\n * Returns the decision together with the matching catalog entry (the entry\n * is what elicitation copy must be built from — S6), or a structured\n * `validate`-phase {@link ProjectionError} when the machine names a tool the\n * wrapped server does not declare.\n */\nexport function resolveCallPolicy(\n call: PendingToolCall,\n catalog: ServerCatalog,\n overrides?: PolicyOverrides,\n): ResolvedCallPolicy {\n const entry = findTool(catalog, call.name);\n if (entry === undefined) {\n return {\n ok: false,\n error: new ProjectionError(\n 'validate',\n `Unknown tool \"${call.name}\": the wrapped server does not declare it`,\n {\n diagnostics: [\n { message: `Requested from machine state \"${call.stateName}\" (call id ${call.id})` },\n ],\n hint: 'Call discover_apis and use only the tool names listed in @astral-mcp/tools.',\n },\n ),\n };\n }\n return { ok: true, decision: decidePolicy(entry, overrides), entry };\n}\n\n/**\n * Canonical TOOL_DENIED reason for calls blocked by a `deny` policy\n * decision. A `deny` decision never produces an elicitation — the machine\n * host injects `TOOL_DENIED` with this reason instead.\n */\nexport const POLICY_DENIED_REASON = 'denied by server policy';\n\n/**\n * Build the TOOL_DENIED reason string for a policy-denied call. With a tool\n * name it names the denied tool so the machine (and audit trail) can tell\n * which call was blocked.\n */\nexport function policyDeniedReason(toolName?: string): string {\n return toolName === undefined\n ? POLICY_DENIED_REASON\n : `${POLICY_DENIED_REASON}: tool \"${toolName}\" is configured as deny`;\n}\n","/**\n * Rendering untrusted strings inertly (S5, S6).\n *\n * Tool names, descriptions, the wrapped server's identity, and machine state\n * names all flow from a possibly third-party server or a model-authored\n * machine. Wherever they are rendered into human-facing prompt copy or into\n * generated source, they must not be able to forge structure with control\n * characters (newlines, ESC for ANSI sequences) or reorder text with Unicode\n * bidi overrides. Centralizing the character class here keeps every call site\n * on the same, complete definition — an earlier divergence let generated\n * `.d.ts`/bridge comments miss the directional-isolate range that the\n * elicitation copy already stripped.\n */\n\n/**\n * C0 control characters (incl. ESC and, unless `allowNewline`, `\\n`), DEL, C1\n * controls (which `JSON.stringify` does NOT escape), the bidi override marks\n * (LRM/RLM/LRE/RLE/PDF/LRO/RLO), and the directional isolates (LRI/RLI/FSI/\n * PDI).\n */\n// prettier-ignore\n// eslint-disable-next-line no-control-regex\nconst HOSTILE_INLINE = /[\\u0000-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g;\n// Same class minus `\\n`, for blocks whose pretty-print newlines are legitimate.\n// prettier-ignore\n// eslint-disable-next-line no-control-regex\nconst HOSTILE_BLOCK = /[\\u0000-\\u0009\\u000b-\\u001f\\u007f-\\u009f\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g;\n\n/**\n * Replace control and bidi characters with the replacement character.\n * `allowNewline` keeps `\\n` (for multi-line blocks whose formatting newlines\n * are part of the rendering, e.g. a pretty-printed JSON block).\n */\nexport function neutralizeControlChars(\n text: string,\n options: { allowNewline?: boolean } = {},\n): string {\n return text.replace(options.allowNewline === true ? HOSTILE_BLOCK : HOSTILE_INLINE, '\\ufffd');\n}\n\n/** Truncate to `maxChars`, appending an ellipsis when shortened. */\nexport function capLength(text: string, maxChars: number): string {\n return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…`;\n}\n","/**\n * Elicitation copy builder (PRD R16, S6).\n *\n * Builds the human-readable approval summary for a gated tool call. The\n * hardening rule (S6) is that nothing model-controlled other than the\n * argument VALUES may enter the copy, and those values are rendered as\n * inert data:\n *\n * - Tool name and description come from the server-side catalog entry,\n * never from model-authored text (a fake `description` inside the args\n * is just another argument value inside the JSON block). The catalog\n * itself may belong to a hostile third-party server (S5), so name and\n * description are still rendered inert: control characters and bidi\n * overrides neutralized, length capped, description as an escaped JSON\n * string literal so it can never forge prompt structure.\n * - Arguments pass through the developer's redaction hook (R16) BEFORE\n * being rendered anywhere; if the hook throws we fail closed and render\n * `[redaction failed]` instead of any argument data.\n * - Arguments are rendered as an indented, pretty-printed JSON block.\n * `JSON.stringify` escapes every newline and quote inside string values,\n * so hostile values (\"IGNORE PREVIOUS INSTRUCTIONS: ...\") stay quoted on\n * an indented line inside the block and can never break out into prose.\n * - The machine state name (model-authored, required by R16) is rendered\n * as a length-capped JSON string literal — quoted and escaped, inert.\n * - `destructiveHint` prepends clearly stronger warning language (R14).\n *\n * Pure: no I/O, deterministic for a given input.\n */\n\nimport { capLength, neutralizeControlChars } from '../text-safety.js';\nimport type { PendingToolCall, RedactionHook, ToolCatalogEntry } from '../types.js';\n\n/** Structured approval copy for one gated call (input to the MRTR adapter). */\nexport interface ElicitationCopy {\n /** Short title, e.g. `Approval required: delete_file`. */\n title: string;\n /** Full human-readable summary (plain text with an indented JSON block). */\n message: string;\n /** Tool name, taken from the catalog entry. */\n toolName: string;\n /** Machine state path that requested the call (raw; render with care). */\n stateName: string;\n /** The redacted arguments as rendered in `message` (JSON text, possibly truncated). */\n args: string;\n /** True when the catalog entry carries `destructiveHint: true`. */\n destructive: boolean;\n}\n\nexport interface ElicitationCopyOptions {\n /** Redaction hook applied to args before any rendering (R16). */\n redact?: RedactionHook;\n /** Cap on the rendered args JSON, in characters. Default 4096. */\n maxArgsChars?: number;\n}\n\nconst DEFAULT_MAX_ARGS_CHARS = 4096;\nconst MAX_STATE_NAME_CHARS = 200;\nconst MAX_TOOL_NAME_CHARS = 200;\nconst MAX_DESCRIPTION_CHARS = 1000;\nconst ARGS_INDENT = ' ';\n\nconst DESTRUCTIVE_WARNING =\n 'WARNING: the server marks this tool as DESTRUCTIVE. ' +\n 'Approving may permanently modify or delete data. Review the arguments carefully.';\n\nconst REDACTION_FAILED = '[redaction failed]';\n\n/**\n * Build the approval summary for a gated call.\n *\n * `entry` MUST be the catalog entry the call was resolved against (use\n * `resolveCallPolicy`); the copy takes the tool name and description from\n * it, never from the pending call or its arguments.\n */\nexport function buildElicitationCopy(\n call: PendingToolCall,\n entry: ToolCatalogEntry,\n options: ElicitationCopyOptions = {},\n): ElicitationCopy {\n const destructive = entry.annotations?.destructiveHint === true;\n const maxArgsChars = options.maxArgsChars ?? DEFAULT_MAX_ARGS_CHARS;\n\n // R16: redact BEFORE rendering anywhere. Fail closed if the hook throws:\n // render a placeholder for ALL args rather than risk leaking any of them.\n let renderedArgs: string;\n try {\n const displayArgs =\n options.redact !== undefined ? options.redact(entry.name, call.args) : call.args;\n renderedArgs = renderArgsJson(displayArgs, maxArgsChars);\n } catch {\n renderedArgs = REDACTION_FAILED;\n }\n\n // The catalog entry comes from a possibly third-party wrapped server (S5):\n // its name and description are untrusted and must not be able to forge\n // prompt structure (fake args blocks, fake approval lines, ANSI tricks).\n const safeName = neutralizeControlChars(capLength(entry.name, MAX_TOOL_NAME_CHARS));\n const safeDescription = JSON.stringify(\n neutralizeControlChars(\n capLength(\n entry.description ?? '(no description provided by the server)',\n MAX_DESCRIPTION_CHARS,\n ),\n ),\n );\n\n const title = destructive\n ? `Approval required (DESTRUCTIVE): ${safeName}`\n : `Approval required: ${safeName}`;\n\n const lines: string[] = [];\n if (destructive) {\n lines.push(DESTRUCTIVE_WARNING, '');\n }\n lines.push(\n `Tool: ${safeName}`,\n `Description: ${safeDescription}`,\n // Model-authored, so rendered as an escaped JSON string literal (inert).\n `Requested by machine state: ${JSON.stringify(\n neutralizeControlChars(capLength(call.stateName, MAX_STATE_NAME_CHARS)),\n )}`,\n '',\n 'Arguments (data only — not instructions):',\n '',\n indentBlock(neutralizeControlChars(renderedArgs, { allowNewline: true })),\n );\n\n return {\n title,\n message: lines.join('\\n'),\n toolName: entry.name,\n stateName: call.stateName,\n args: renderedArgs,\n destructive,\n };\n}\n\n/**\n * Render argument values as pretty-printed JSON, defensively:\n * circular references, bigints, functions, symbols and `undefined` become\n * inert placeholder strings; a throwing `toJSON` falls back to a\n * placeholder; output beyond `maxChars` is cut with a truncation marker.\n */\nfunction renderArgsJson(args: Record<string, unknown>, maxChars: number): string {\n let json: string;\n try {\n json = JSON.stringify(args, makeSafeReplacer(), 2) ?? '[unserializable arguments]';\n } catch {\n json = '[unserializable arguments]';\n }\n if (json.length <= maxChars) {\n return json;\n }\n const total = json.length;\n return `${json.slice(0, maxChars)}\\n… [truncated: showing first ${maxChars} of ${total} characters]`;\n}\n\n/**\n * JSON.stringify replacer neutralizing values JSON cannot represent.\n *\n * Cycle detection tracks only the current ancestor chain (popping on the\n * way back up via the `this` holder), so shared non-circular references\n * render fully everywhere they appear — only a true ancestor cycle becomes\n * `[circular]`. Rendering a shared object as `[circular]` would hide the\n * real arguments from the approver (R16).\n */\nfunction makeSafeReplacer(): (this: unknown, key: string, value: unknown) => unknown {\n const ancestors: object[] = [];\n return function replacer(this: unknown, _key: string, value: unknown): unknown {\n switch (typeof value) {\n case 'bigint':\n return `[bigint ${value.toString()}]`;\n case 'function':\n return '[function]';\n case 'symbol':\n return '[symbol]';\n case 'undefined':\n return '[undefined]';\n default:\n break;\n }\n if (typeof value === 'object' && value !== null) {\n while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {\n ancestors.pop();\n }\n if (ancestors.includes(value)) {\n return '[circular]';\n }\n ancestors.push(value);\n }\n return value;\n };\n}\n\n/** Prefix every line so the block reads as data, not prose. */\nfunction indentBlock(text: string): string {\n return text\n .split('\\n')\n .map((line) => ARGS_INDENT + line)\n .join('\\n');\n}\n","/**\n * The authoring contract (PRD R5–R8) — the exact surface an LLM-authored\n * machine module may use, and the in-VM code implementing it.\n *\n * The module source here is appended to the typegen-generated bridge and\n * mounted together at `@astral-mcp/tools`, so an authored module writes:\n *\n * ```ts\n * import { setup } from 'xstate';\n * import { toolCall } from '@astral-mcp/tools';\n * ```\n *\n * `toolCall` is the ONLY supported way to reach a tool (R7). It returns an\n * ordinary XState action function, so the machine never models a tool call\n * as an invoked promise actor — restoring a snapshot restarts invoked\n * actors, which would re-execute an already-approved write.\n */\n\n/**\n * Prelude + `toolCall` implementation, appended to the generated bridge.\n *\n * `toolCall` pushes a request onto an in-VM queue that the host drains after\n * the actor settles. It is deliberately synchronous and promise-free: the\n * machine records *that* it wants a call, and the host — never the machine —\n * performs the I/O and injects the result as an event (R7, S1).\n *\n * The generated bridge's `tools.<name>(args)` functions reach the host\n * through the sandbox's `env` binding; the shim below wires the global the\n * bridge expects to that binding. Calling `tools.<name>()` directly also\n * registers a gated request, but the returned promise is never resolved\n * within the segment — awaiting it is the banned pattern. Author with\n * `toolCall`.\n */\nexport const TOOL_CALL_MODULE_SOURCE = `\n// --- Projection machine-host prelude -----------------------------------\n// Bind the generated bridge's host hook to the sandbox env binding.\nif (typeof globalThis.__projection_toolcall !== 'function') {\n globalThis.__projection_toolcall = function (name, args) {\n return env.__projection_toolCall(name, args);\n };\n}\n\nfunction __projQueue() {\n const state = globalThis.__projection.state;\n if (!state.queue) state.queue = [];\n return state.queue;\n}\n\nlet __projSeq = 0;\n\n/**\n * Request a tool call from a machine action.\n *\n * entry: toolCall('write_file', ({ context }) => ({ path: context.path }))\n *\n * @param name Tool name exactly as catalogued.\n * @param args Plain object, or a function of the XState action arguments\n * ({ context, event }) returning one.\n * @param options Optional { id } to correlate the resulting event; a\n * stable id is generated when omitted.\n */\nexport function toolCall(name, args, options) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error('toolCall(name, args): name must be a non-empty tool name string');\n }\n return function projectionToolCall(actionArgs) {\n let resolved;\n try {\n resolved = typeof args === 'function' ? args(actionArgs) : args;\n } catch (err) {\n throw new Error('toolCall(\"' + name + '\") argument function threw: ' + String(err));\n }\n if (resolved === undefined || resolved === null) resolved = {};\n if (typeof resolved !== 'object' || Array.isArray(resolved)) {\n throw new Error('toolCall(\"' + name + '\") arguments must resolve to a plain object');\n }\n __projSeq += 1;\n const id = options && options.id !== undefined ? String(options.id) : name + '#' + __projSeq;\n __projQueue().push({ id: id, name: name, args: resolved });\n };\n}\n\n/**\n * Guard matching the event for one specific call id.\n *\n * XState delivers an event to every region that can handle it, so a machine\n * with two calls outstanding at once (parallel regions) MUST guard each\n * waiting state — otherwise one region consumes the other's result and the\n * machine records an approved write against the wrong branch.\n *\n * on: { TOOL_RESULT: { guard: whenCall('a'), target: 'done' } }\n */\nexport function whenCall(id) {\n const wanted = String(id);\n return function projectionWhenCall(guardArgs) {\n const event = guardArgs && guardArgs.event;\n return Boolean(event) && event.callId === wanted;\n };\n}\n`;\n\n/**\n * Human-readable authoring contract. `discover_apis` publishes this inline\n * (R3) so a model can author a valid machine without fetching resources.\n */\nexport const AUTHORING_CONTRACT = `Projection authoring contract (execute_machine)\n\nWrite ONE module whose only top-level statements are imports and a single\ndefault-exported XState v5 machine. The module is re-evaluated on every\napproval round trip, so top-level side effects are rejected.\n\n import { setup } from 'xstate';\n import { toolCall } from '@astral-mcp/tools';\n\n export default setup({}).createMachine({ /* ... */ });\n\nRules:\n1. Default-export a machine built with XState v5 setup(...).createMachine(...).\n XState v4 Machine(...) is rejected.\n2. Machine context must be JSON-serializable at all times. No Map, Set, Date,\n class instances, functions, undefined, bigint or symbols in context.\n3. Request tools with the toolCall action. NEVER wrap a tool call in\n fromPromise/invoke — restored snapshots restart invoked actors, which\n would re-execute an approved write. Machines using invoke are rejected.\n4. After a toolCall, wait in a state for one of these events:\n TOOL_RESULT { callId, result } the call succeeded\n TOOL_ERROR { callId, error } the call failed\n TOOL_DENIED { callId, reason } the user declined, or policy denies it\n Denial is not an abort: handle TOOL_DENIED and continue or finish.\n IMPORTANT: if your machine has more than one call outstanding at the same\n time (parallel regions), give each toolCall an explicit id and guard every\n waiting state with whenCall(id) — events reach every region that can\n handle them, so an unguarded region will consume another call's result:\n\n import { toolCall, whenCall } from '@astral-mcp/tools';\n entry: toolCall('write_file', () => ({ path: '/a' }), { id: 'a' }),\n on: { TOOL_RESULT: { guard: whenCall('a'), target: 'done' } },\n5. Read-only tools run immediately. Every other tool pauses the machine for\n user approval; the arguments captured at that moment are the arguments\n that execute.\n6. Only 'xstate' and '@astral-mcp/tools' resolve as imports. There is no\n filesystem, no network, no fetch. All working state lives in context.\n7. Finish by reaching a final state. Use the machine's output for the result.\n\nExample — happy path with a read-only call:\n\n import { setup, assign } from 'xstate';\n import { toolCall } from '@astral-mcp/tools';\n\n export default setup({}).createMachine({\n id: 'readNotes',\n context: ({ input }) => ({ path: input?.path ?? '/notes.txt', text: null }),\n initial: 'reading',\n states: {\n reading: {\n entry: toolCall('read_file', ({ context }) => ({ path: context.path })),\n on: {\n TOOL_RESULT: { target: 'done', actions: assign({ text: ({ event }) => event.result }) },\n TOOL_ERROR: 'failed',\n },\n },\n done: { type: 'final' },\n failed: { type: 'final' },\n },\n output: ({ context }) => ({ text: context.text }),\n });\n\nExample — handling a denied approval:\n\n import { setup, assign } from 'xstate';\n import { toolCall } from '@astral-mcp/tools';\n\n export default setup({}).createMachine({\n id: 'writeNotes',\n context: { status: 'pending' },\n initial: 'writing',\n states: {\n writing: {\n entry: toolCall('write_file', () => ({ path: '/notes.txt', content: 'hello' })),\n on: {\n TOOL_RESULT: { target: 'done', actions: assign({ status: 'written' }) },\n TOOL_DENIED: { target: 'done', actions: assign({ status: 'skipped' }) },\n TOOL_ERROR: { target: 'done', actions: assign({ status: 'failed' }) },\n },\n },\n done: { type: 'final' },\n },\n output: ({ context }) => ({ status: context.status }),\n });\n`;\n","/**\n * Driver module sources evaluated inside the sandbox (PRD R24, R5–R7).\n *\n * The sandbox evaluates an ESM module and marshals its default export back\n * to the host, so each host↔VM step is a small module built here. Values\n * interpolated into these templates are always `JSON.stringify`d — never\n * raw text — so nothing from the model or the wrapped server can extend the\n * driver's own code.\n */\n\n/**\n * Static validation of the default-exported machine (R24).\n *\n * Runs without starting an actor: entry actions must not fire during\n * validation, or a `toolCall` in the initial state would register a request\n * before policy has been consulted. `createActor(m).getSnapshot()` yields\n * the initial snapshot with actions resolved but not executed.\n *\n * The caller's `input` is passed to the probe actor exactly as the\n * bootstrap will pass it: a machine whose context factory dereferences\n * `input` (`context: ({ input }) => ({ path: input.path })`) must validate\n * against the input it will actually run with, not against `undefined`.\n */\nexport function validationDriver(maxStateNodes: number, input: unknown): string {\n const probeActor =\n input === undefined\n ? 'createActor(machine)'\n : `createActor(machine, { input: ${JSON.stringify(input)} })`;\n return `\nimport { createActor } from 'xstate';\n\nconst g = globalThis.__projection;\nconst machine = g.module ? g.module.default : undefined;\nconst fail = (code, detail) => ({ ok: false, code: code, detail: detail === undefined ? null : detail });\n\nfunction run() {\n if (machine === undefined || machine === null) {\n return fail('no_default_export');\n }\n if (typeof machine !== 'object' && typeof machine !== 'function') {\n return fail('default_export_not_machine', typeof machine);\n }\n // XState v5 machines carry __xstatenode and a root state node; a v4\n // Machine(...) result and every non-machine value lack one or the other.\n const isV5 =\n machine.__xstatenode === true &&\n machine.root !== undefined &&\n typeof machine.getPersistedSnapshot === 'function';\n if (!isV5) {\n const looksV4 =\n machine.__xstatenode === true ||\n typeof machine.withConfig === 'function' ||\n typeof machine.withContext === 'function';\n return fail(looksV4 ? 'xstate_v4_machine' : 'default_export_not_machine');\n }\n\n // (a) State-node count: a tree walk of the instantiated definition (R12).\n let nodes = 0;\n const walkNodes = (node) => {\n nodes += 1;\n if (nodes > ${JSON.stringify(maxStateNodes)}) return;\n const states = node.states;\n if (states) for (const key of Object.keys(states)) walkNodes(states[key]);\n };\n walkNodes(machine.root);\n if (nodes > ${JSON.stringify(maxStateNodes)}) {\n return fail('too_many_state_nodes', nodes);\n }\n\n // (b) Banned invoked actors (R7). Any invoke at all is rejected: a\n // restored snapshot restarts invoked actors, so an invoked tool call\n // would re-execute an approved write. Walk the raw config, which is the\n // authored shape before XState normalizes it.\n const seen = new Set();\n let invokeAt = null;\n const walkConfig = (value, path) => {\n if (invokeAt !== null) return;\n if (value === null || typeof value !== 'object') return;\n if (seen.has(value)) return;\n seen.add(value);\n if (!Array.isArray(value) && value.invoke !== undefined) {\n invokeAt = path.length > 0 ? path : '(root)';\n return;\n }\n for (const key of Object.keys(value)) {\n walkConfig(value[key], path.length > 0 ? path + '.' + key : key);\n }\n };\n walkConfig(machine.config, '');\n if (invokeAt !== null) {\n return fail('invoke_banned', invokeAt);\n }\n\n // (c) Serializability probe (R6). JSON.stringify silently drops functions\n // and flattens Map/Set, so walk for non-JSON values instead of relying on\n // a throw, then round-trip to catch anything left (e.g. cycles).\n let snapshot;\n try {\n snapshot = ${probeActor}.getSnapshot();\n } catch (err) {\n return fail('machine_init_threw', String(err && err.message ? err.message : err));\n }\n const badPath = findNonSerializable(snapshot.context, 'context', new Set());\n if (badPath !== null) {\n return fail('context_not_serializable', badPath);\n }\n try {\n JSON.parse(JSON.stringify(snapshot.context));\n } catch (err) {\n return fail('context_not_serializable', 'context (' + String(err && err.message ? err.message : err) + ')');\n }\n return { ok: true, stateNodes: nodes };\n}\n\nfunction findNonSerializable(value, path, seen) {\n if (value === null) return null;\n const t = typeof value;\n if (t === 'string' || t === 'number' || t === 'boolean') {\n return t === 'number' && !Number.isFinite(value) ? path + ' (' + String(value) + ')' : null;\n }\n if (t === 'undefined') return path + ' (undefined)';\n if (t === 'function') return path + ' (function)';\n if (t === 'symbol') return path + ' (symbol)';\n if (t === 'bigint') return path + ' (bigint)';\n if (t !== 'object') return path + ' (' + t + ')';\n if (seen.has(value)) return path + ' (circular reference)';\n seen.add(value);\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i += 1) {\n const bad = findNonSerializable(value[i], path + '[' + i + ']', seen);\n if (bad !== null) return bad;\n }\n return null;\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n const name = value.constructor && value.constructor.name ? value.constructor.name : 'non-plain object';\n return path + ' (' + name + ')';\n }\n for (const key of Object.keys(value)) {\n const bad = findNonSerializable(value[key], path + '.' + key, seen);\n if (bad !== null) return bad;\n }\n return null;\n}\n\nexport default run();\n`;\n}\n\n/** Read the request queue without starting the actor (top-level effects, R5). */\nexport const TOP_LEVEL_EFFECT_PROBE = `\nconst state = globalThis.__projection.state;\nexport default { queued: state.queue ? state.queue.length : 0 };\n`;\n\n/**\n * Create (or restore) the actor and settle it, returning the drained state.\n *\n * `input` and `snapshot` are interpolated as JSON literals. A restored\n * actor resumes exactly where the snapshot left off (R21).\n */\nexport function bootstrapDriver(input: unknown, snapshot: unknown): string {\n const hasSnapshot = snapshot !== undefined;\n return `\nimport { createActor } from 'xstate';\n\nconst g = globalThis.__projection;\nconst machine = g.module.default;\nif (!g.state.queue) g.state.queue = [];\n\n${DRAIN_HELPER}\n\nconst actor = ${\n hasSnapshot\n ? `createActor(machine, { snapshot: ${JSON.stringify(snapshot)} })`\n : input === undefined\n ? 'createActor(machine)'\n : `createActor(machine, { input: ${JSON.stringify(input)} })`\n };\ng.state.actor = actor;\ng.state.drain = drain;\nactor.start();\n\nexport default drain();\n`;\n}\n\n/** Send host events into the running actor and return the drained state. */\nexport function sendDriver(events: unknown[]): string {\n return `\nconst g = globalThis.__projection;\nconst events = ${JSON.stringify(events)};\nfor (const event of events) {\n g.state.actor.send(event);\n}\nexport default g.state.drain();\n`;\n}\n\n/** Return the persisted snapshot for sealing into the blob (R20). */\nexport const SNAPSHOT_DRIVER = `\nconst g = globalThis.__projection;\nexport default { snapshot: g.state.actor.getPersistedSnapshot() };\n`;\n\n/**\n * Collect everything the host needs after the actor settles: the queued\n * tool requests (cleared as they are read), the machine status, and the\n * final output when it has reached a final state.\n */\nconst DRAIN_HELPER = `\nfunction drain() {\n const snapshot = g.state.actor.getSnapshot();\n const queue = g.state.queue;\n const requests = queue.splice(0, queue.length);\n return {\n status: snapshot.status,\n value: snapshot.value === undefined ? null : snapshot.value,\n output: snapshot.output === undefined ? null : snapshot.output,\n error: snapshot.error === undefined ? null : String(snapshot.error),\n requests: requests,\n };\n}\n`;\n","/**\n * Machine host — evaluates the authored module in the sandbox, enforces the\n * authoring contract, drives the actor, and turns tool requests into\n * host-side execution or an approval suspension (PRD §7 \"Machine host\").\n */\n\nimport { ProjectionError, toStructuredError } from '../errors.js';\nimport { createSandboxSession, type SandboxSession } from '../sandbox/index.js';\nimport { policyDeniedReason, resolveCallPolicy } from '../policy/index.js';\nimport {\n clampCaps,\n type ApprovalVerdict,\n type AuditEntry,\n type ErrorPhase,\n type HostEvent,\n type LogEntry,\n type PendingToolCall,\n type PolicyOverrides,\n type ResourceCaps,\n type SegmentOutcome,\n type ServerCatalog,\n type ToolExecutor,\n} from '../types.js';\nimport { TOOL_CALL_MODULE_SOURCE } from './contract.js';\nimport {\n bootstrapDriver,\n sendDriver,\n SNAPSHOT_DRIVER,\n TOP_LEVEL_EFFECT_PROBE,\n validationDriver,\n} from './drivers.js';\n\n/** A tool request as it comes out of the VM queue. */\ninterface RawRequest {\n id: string;\n name: string;\n args: Record<string, unknown>;\n}\n\ninterface DrainResult {\n status: 'active' | 'done' | 'error' | 'stopped';\n value: unknown;\n output: unknown;\n error: string | null;\n requests: RawRequest[];\n}\n\nexport interface RunSegmentOptions {\n /** Submitted module source (R2). */\n code: string;\n lang?: 'ts' | 'js';\n /** Machine input, passed as the machine's `input` on a fresh run. */\n input?: unknown;\n /** Catalog of the wrapped server whose tools the machine may call. */\n catalog: ServerCatalog;\n /** Generated `@astral-mcp/tools` bridge source (from typegen). */\n bridgeSource: string;\n /** Executes approved/auto tool calls against the wrapped server. */\n executor: ToolExecutor;\n /** Resource caps; clamped at the hard maxima (R12). */\n caps?: Partial<ResourceCaps>;\n /** Per-tool policy overrides (R14). */\n policy?: PolicyOverrides;\n /** Zero-based MRTR segment index — stamps logs (R31). */\n segment?: number;\n /**\n * Resume state. Present on every segment after the first: the verified\n * snapshot and the pending calls sealed alongside it, plus the verdicts\n * the client returned for those calls.\n */\n resume?: {\n snapshot: unknown;\n /** Gated calls as sealed into the blob — the approved name+args (S2). */\n pending: Record<string, PendingToolCall>;\n /** Verdict per pending key; a missing entry counts as declined (R17). */\n verdicts: Record<string, ApprovalVerdict>;\n /** Audit entries accumulated in earlier segments. */\n audit?: AuditEntry[];\n /** Round-trip counter carried in the blob (R18). */\n trip: number;\n };\n}\n\n/**\n * Run one execution segment to completion, suspension, or error.\n *\n * A segment is one MRTR round trip: fresh sandbox, fresh wall-clock budget,\n * fresh logs. On the first segment the module is validated (R24) before the\n * actor starts; on a resume the module is re-evaluated from the re-sent code\n * and the actor is restored from the sealed snapshot.\n *\n * Note: `runSegment` interpolates `input` into driver source without a size\n * check of its own — `executeMachine` enforces `maxInputBytes` before calling\n * it. Callers invoking `runSegment` directly must bound `input` themselves.\n */\nexport async function runSegment(options: RunSegmentOptions): Promise<SegmentOutcome> {\n const caps = clampCaps(options.caps ?? {});\n const segment = options.segment ?? 0;\n const audit: AuditEntry[] = [...(options.resume?.audit ?? [])];\n\n let session: SandboxSession | undefined;\n // Requests that arrive through the generated bridge's host hook rather\n // than the `toolCall` action. Same gate, collected the same way.\n const hookRequests: RawRequest[] = [];\n let hookSeq = 0;\n\n try {\n session = await createSandboxSession({\n code: options.code,\n ...(options.lang !== undefined ? { lang: options.lang } : {}),\n caps,\n bridgeSource: `${options.bridgeSource}\\n${TOOL_CALL_MODULE_SOURCE}`,\n segment,\n onToolCall: (call) => {\n hookSeq += 1;\n hookRequests.push({ id: `${call.name}@${hookSeq}`, name: call.name, args: call.args });\n // The machine must not consume this as a promise (R7); the result\n // is delivered as an event to the (possibly rehydrated) actor.\n return null;\n },\n });\n\n // R5: the module is re-evaluated on every resume, so a tool call fired\n // at module top level would repeat on each round trip.\n const probe = (await session.evaluate(TOP_LEVEL_EFFECT_PROBE)) as { queued?: number };\n if ((probe.queued ?? 0) > 0 || hookRequests.length > 0) {\n throw new ProjectionError(\n 'validate',\n 'the submitted module requests a tool call at top level',\n {\n hint: 'Move tool calls into machine states: the module is re-evaluated on every approval round trip, so top-level effects would repeat. Use toolCall(...) as a state entry action.',\n },\n );\n }\n\n if (options.resume === undefined) {\n await validate(session, caps, options.input);\n }\n\n const runner = new SegmentRunner({\n session,\n caps,\n segment,\n catalog: options.catalog,\n executor: options.executor,\n ...(options.policy !== undefined ? { policy: options.policy } : {}),\n audit,\n hookRequests,\n trip: options.resume?.trip ?? 0,\n });\n\n return await runner.run(options);\n } catch (err) {\n return { status: 'error', error: toStructuredError(err, session?.getLogs() ?? []) };\n } finally {\n await session?.dispose();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Validation (R24)\n// ---------------------------------------------------------------------------\n\ninterface ValidationFailure {\n ok: false;\n code: string;\n detail: unknown;\n}\ntype ValidationResult = { ok: true; stateNodes: number } | ValidationFailure;\n\nasync function validate(\n session: SandboxSession,\n caps: ResourceCaps,\n input: unknown,\n): Promise<void> {\n const result = (await session.evaluate(\n validationDriver(caps.maxStateNodes, input),\n )) as ValidationResult;\n if (result.ok) return;\n throw validationError(result, caps);\n}\n\n/** Each validation failure code maps to a phase, a message, and a fix hint. */\ninterface ValidationSpec {\n phase: ErrorPhase;\n message: (detail: string, caps: ResourceCaps) => string;\n hint: (caps: ResourceCaps) => string;\n}\n\nconst VALIDATION_SPECS: Record<string, ValidationSpec> = {\n no_default_export: {\n phase: 'validate',\n message: () => 'the submitted module has no default export',\n hint: () =>\n 'Default-export a machine: `export default setup({}).createMachine({ ... })`. See discover_apis.',\n },\n xstate_v4_machine: {\n phase: 'validate',\n message: () => 'the default export is an XState v4 machine, not a v5 machine',\n hint: () =>\n 'Rewrite for XState v5: `import { setup } from \"xstate\"` then `setup({}).createMachine({ ... })` — v4 Machine(...) is not supported.',\n },\n default_export_not_machine: {\n phase: 'validate',\n message: (detail) =>\n `the default export is not an XState v5 machine${detail ? ` (got ${detail})` : ''}`,\n hint: () =>\n 'Default-export the machine itself, not an actor or a factory: `export default setup({}).createMachine({ ... })`.',\n },\n too_many_state_nodes: {\n phase: 'cap_exceeded',\n message: (detail, caps) =>\n `the machine has ${detail} state nodes, exceeding the limit of ${caps.maxStateNodes}`,\n hint: (caps) =>\n `Simplify the machine to at most ${caps.maxStateNodes} state nodes, or split the work across separate execute_machine calls.`,\n },\n invoke_banned: {\n phase: 'validate',\n message: (detail) =>\n `the machine uses invoke (at ${detail || 'the machine root'}), which is not allowed`,\n hint: () =>\n 'Tool calls must use the toolCall action, not fromPromise/invoke: restored snapshots restart invoked actors and would re-execute approved writes. See discover_apis.',\n },\n context_not_serializable: {\n phase: 'validate',\n message: (detail) => `machine context is not JSON-serializable at ${detail}`,\n hint: () =>\n 'Keep context to plain JSON values — no Map, Set, Date, class instances, functions or undefined. Store a string or number instead.',\n },\n machine_init_threw: {\n phase: 'validate',\n message: (detail) => `creating the machine actor threw: ${detail}`,\n hint: () => 'Fix the error thrown while building the machine context or initial state.',\n },\n};\n\nfunction validationError(result: ValidationFailure, caps: ResourceCaps): ProjectionError {\n const detail = result.detail === null ? '' : String(result.detail);\n const spec = VALIDATION_SPECS[result.code];\n if (spec === undefined) {\n return new ProjectionError('validate', `machine validation failed: ${result.code}`, {\n hint: 'Review the authoring contract from discover_apis and resubmit.',\n });\n }\n return new ProjectionError(spec.phase, spec.message(detail, caps), { hint: spec.hint(caps) });\n}\n\n// ---------------------------------------------------------------------------\n// Segment execution\n// ---------------------------------------------------------------------------\n\ninterface RunnerDeps {\n session: SandboxSession;\n caps: ResourceCaps;\n segment: number;\n catalog: ServerCatalog;\n executor: ToolExecutor;\n policy?: PolicyOverrides;\n audit: AuditEntry[];\n hookRequests: RawRequest[];\n trip: number;\n}\n\nclass SegmentRunner {\n private readonly deps: RunnerDeps;\n private readCalls = 0;\n private eventsProcessed = 0;\n\n constructor(deps: RunnerDeps) {\n this.deps = deps;\n }\n\n async run(options: RunSegmentOptions): Promise<SegmentOutcome> {\n const { session } = this.deps;\n const resume = options.resume;\n\n let drained: DrainResult;\n if (resume === undefined) {\n drained = (await session.evaluate(bootstrapDriver(options.input, undefined))) as DrainResult;\n } else {\n drained = (await session.evaluate(\n bootstrapDriver(undefined, resume.snapshot),\n )) as DrainResult;\n // Deliver verdicts for the calls sealed alongside the snapshot. The\n // args come from the sealed map, never from the restored machine (S2).\n const events = await this.applyVerdicts(resume.pending, resume.verdicts);\n drained = await this.send(events);\n }\n\n // Gated calls accumulate across settle passes so that everything reached\n // before the machine goes quiet lands in ONE suspension (R15).\n const gatedBatch: PendingToolCall[] = [];\n\n // Settle: process requests until the machine either finishes, errors,\n // or is waiting on gated calls that need approval.\n for (;;) {\n if (drained.status === 'error') {\n throw new ProjectionError('runtime', `the machine errored: ${drained.error ?? 'unknown'}`, {\n hint: 'Handle the failure in the machine (e.g. a TOOL_ERROR transition) or fix the action that threw.',\n });\n }\n\n const requests = this.collectRequests(drained);\n if (requests.length === 0) {\n // Nothing more to run: suspend on whatever accumulated, if anything.\n if (gatedBatch.length > 0) {\n return await this.suspend(gatedBatch);\n }\n if (drained.status === 'done' || drained.status === 'stopped') {\n return this.complete(drained);\n }\n // Quiescent, nothing pending, not final: the machine is waiting for\n // an event that will never arrive.\n throw new ProjectionError(\n 'runtime',\n `the machine is stuck in state ${JSON.stringify(drained.value)} with no pending tool call and no final state`,\n {\n hint: 'Every non-final state must either request a tool call or transition on an event the host sends. Reach a final state to return a result.',\n },\n );\n }\n\n const { events, gated } = await this.classify(requests, drained.value);\n gatedBatch.push(...gated);\n\n if (events.length === 0) {\n // Only gated calls remain, so the machine cannot advance further\n // without a human. Snapshot now.\n return await this.suspend(gatedBatch);\n }\n\n // Deliver auto/denied results before snapshotting. This must go\n // through the settle loop rather than a send-and-forget inside\n // `suspend`: `drain()` splices the in-VM request queue, so any call\n // the machine queues in response to these events would be consumed\n // and lost — and an already-approved write could then execute against\n // a workflow that resumes with nowhere to go.\n drained = await this.send(events);\n }\n }\n\n /** Merge queued `toolCall` requests with any that came via the bridge hook. */\n private collectRequests(drained: DrainResult): RawRequest[] {\n const hook = this.deps.hookRequests.splice(0, this.deps.hookRequests.length);\n return [...drained.requests, ...hook];\n }\n\n /**\n * Apply the policy to each request: run read-only calls now, deny denied\n * ones now, and set gated ones aside for approval.\n */\n private async classify(\n requests: RawRequest[],\n stateValue: unknown,\n ): Promise<{ events: HostEvent[]; gated: PendingToolCall[] }> {\n const events: HostEvent[] = [];\n const gated: PendingToolCall[] = [];\n const stateName = describeState(stateValue);\n\n for (const request of requests) {\n const call: PendingToolCall = {\n id: request.id,\n name: request.name,\n args: request.args,\n stateName,\n };\n // Single resolution path shared with the MRTR adapter: catalog lookup,\n // unknown-tool error, and policy decision in one place.\n const resolved = resolveCallPolicy(call, this.deps.catalog, this.deps.policy);\n if (!resolved.ok) throw resolved.error;\n\n if (resolved.decision === 'deny') {\n const reason = policyDeniedReason(request.name);\n events.push({ type: 'TOOL_DENIED', callId: request.id, reason });\n this.deps.audit.push({\n callId: request.id,\n tool: request.name,\n args: request.args,\n decision: 'denied_by_policy',\n reason,\n });\n continue;\n }\n\n if (resolved.decision === 'ask') {\n gated.push(call);\n continue;\n }\n\n this.readCalls += 1;\n if (this.readCalls > this.deps.caps.maxReadCallsPerSegment) {\n throw new ProjectionError(\n 'cap_exceeded',\n `the machine made more than ${this.deps.caps.maxReadCallsPerSegment} read-only tool calls in one segment`,\n {\n hint: `Batch the work or reduce the number of read-only calls to at most ${this.deps.caps.maxReadCallsPerSegment} per segment.`,\n },\n );\n }\n events.push(await this.execute(request, 'auto'));\n }\n\n return { events, gated };\n }\n\n /** Execute one call against the wrapped server and build its event. */\n private async execute(request: RawRequest, decision: 'auto' | 'approved'): Promise<HostEvent> {\n const outcome = await this.deps.executor.callTool(\n this.deps.catalog.alias,\n request.name,\n request.args,\n );\n if (outcome.ok) {\n this.deps.audit.push({\n callId: request.id,\n tool: request.name,\n args: request.args,\n decision,\n });\n return { type: 'TOOL_RESULT', callId: request.id, result: outcome.result };\n }\n this.deps.audit.push({\n callId: request.id,\n tool: request.name,\n args: request.args,\n decision: 'error',\n reason: outcome.error.message,\n });\n return { type: 'TOOL_ERROR', callId: request.id, error: outcome.error };\n }\n\n /**\n * Turn the client's verdicts into events (R17).\n *\n * The arguments executed are the ones sealed in `pending` — the approval\n * authorized those exact arguments, not whatever the restored machine\n * might ask for now (S2).\n */\n private async applyVerdicts(\n pending: Record<string, PendingToolCall>,\n verdicts: Record<string, ApprovalVerdict>,\n ): Promise<HostEvent[]> {\n const events: HostEvent[] = [];\n for (const [key, call] of Object.entries(pending)) {\n const verdict = Object.hasOwn(verdicts, key) ? verdicts[key] : undefined;\n // R17: a request missing from inputResponses is treated as declined.\n if (verdict === undefined || verdict.kind === 'declined') {\n const reason = verdict?.kind === 'declined' ? verdict.reason : undefined;\n events.push({\n type: 'TOOL_DENIED',\n callId: call.id,\n ...(reason !== undefined ? { reason } : {}),\n });\n this.deps.audit.push({\n callId: call.id,\n tool: call.name,\n args: call.args,\n decision: 'declined',\n ...(reason !== undefined ? { reason } : {}),\n });\n continue;\n }\n events.push(\n await this.execute({ id: call.id, name: call.name, args: call.args }, 'approved'),\n );\n }\n return events;\n }\n\n /** Send events into the actor, counting them against the segment cap. */\n private async send(events: HostEvent[]): Promise<DrainResult> {\n this.eventsProcessed += events.length;\n if (this.eventsProcessed > this.deps.caps.maxEventsPerSegment) {\n throw new ProjectionError(\n 'cap_exceeded',\n `the machine processed more than ${this.deps.caps.maxEventsPerSegment} events in one segment`,\n {\n hint: `Reduce the number of transitions; at most ${this.deps.caps.maxEventsPerSegment} events run per segment.`,\n },\n );\n }\n return (await this.deps.session.evaluate(sendDriver(events))) as DrainResult;\n }\n\n /**\n * Suspend for approval, sealing the exact calls that were requested.\n *\n * Every event the machine could act on has already been delivered by the\n * settle loop, so the in-VM request queue is empty and the snapshot taken\n * here is complete.\n */\n private async suspend(gated: PendingToolCall[]): Promise<SegmentOutcome> {\n const { snapshot } = (await this.deps.session.evaluate(SNAPSHOT_DRIVER)) as {\n snapshot: unknown;\n };\n const pending: Record<string, PendingToolCall> = {};\n for (const call of gated) {\n pending[call.id] = call;\n }\n return {\n status: 'suspended',\n pending,\n snapshot,\n trip: this.deps.trip + 1,\n audit: this.deps.audit,\n logs: this.logs(),\n };\n }\n\n private complete(drained: DrainResult): SegmentOutcome {\n const output = drained.output;\n const size = Buffer.byteLength(JSON.stringify(output ?? null), 'utf8');\n if (size > this.deps.caps.maxResultBytes) {\n throw new ProjectionError(\n 'cap_exceeded',\n `the final result is ${size} bytes, exceeding the limit of ${this.deps.caps.maxResultBytes}`,\n {\n hint: `Return a summary instead of the full data: the result must be at most ${this.deps.caps.maxResultBytes} bytes.`,\n },\n );\n }\n return {\n status: 'completed',\n output,\n audit: this.deps.audit,\n logs: this.logs(),\n };\n }\n\n private logs(): LogEntry[] {\n return this.deps.session.getLogs();\n }\n}\n\n/** Render an XState state value as a readable path for elicitation copy (R16). */\nfunction describeState(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === null || value === undefined) return '(unknown)';\n const parts: string[] = [];\n const walk = (node: unknown, prefix: string): void => {\n if (typeof node === 'string') {\n parts.push(prefix.length > 0 ? `${prefix}.${node}` : node);\n return;\n }\n if (typeof node === 'object' && node !== null) {\n for (const [key, child] of Object.entries(node)) {\n walk(child, prefix.length > 0 ? `${prefix}.${key}` : key);\n }\n }\n };\n walk(value, '');\n return parts.length > 0 ? parts.join(' | ') : JSON.stringify(value);\n}\n","/**\n * MRTR wire vocabulary (MCP 2026-07-28, SEP-2322).\n *\n * Everything on the wire comes from `@modelcontextprotocol/server@2.x`,\n * which ships MRTR as a stable surface: `InputRequiredResult`,\n * `InputRequest(s)`, `InputResponse(s)`, the `inputRequired()` builder and\n * the `inputResponse()` / `acceptedContent()` readers. Hand-rolling a\n * parallel definition of a stable wire format only invites silent drift, so\n * this module re-exports the SDK's types and keeps exactly three things the\n * SDK genuinely does not provide (see below) — docs/DECISIONS.md D1.\n */\n\nimport type {\n ElicitRequestFormParams,\n HandlerResultTypeMap,\n InputResponses,\n ProtocolEra,\n} from '@modelcontextprotocol/server';\n\nexport {\n acceptedContent,\n inputRequired,\n inputResponse,\n isInputRequiredResult,\n} from '@modelcontextprotocol/server';\nexport type {\n CallToolResult,\n ContentBlock,\n InputRequest,\n InputRequests,\n InputRequiredResult,\n InputResponse,\n InputResponses,\n InputResponseView,\n ProtocolEra,\n} from '@modelcontextprotocol/server';\n\n/**\n * What a `tools/call` handler may return on the 2026-07-28 era: a finished\n * result, or the input-required suspension. This is the SDK's own\n * handler-return type for the method, not a shape of ours.\n */\nexport type ToolCallResult = HandlerResultTypeMap['tools/call'];\n\n/**\n * The MRTR retry fields the client re-sends alongside the original\n * arguments. The SDK lifts them off the params into `ctx.mcpReq`, so a\n * handler never reads them from `args`; Projection still names them because\n * `executeMachine` is callable outside an SDK handler (R27 — the facade is\n * plain functions).\n *\n * `inputResponses` is deliberately widened the same way the SDK's own\n * `inputResponse()` / `acceptedContent()` readers widen it: the values come\n * from the client and are never validated by the SDK, so a caller may hand\n * over whatever the wire carried.\n */\nexport interface RetryEnvelope {\n /** The `requestState` echoed back unchanged. */\n requestState?: string;\n /** Answers keyed by the same keys as `inputRequests`. */\n inputResponses?: InputResponses | Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// The three things the SDK does not provide\n// ---------------------------------------------------------------------------\n\n/**\n * The JSON Schema an approval elicitation asks the client to collect, typed\n * as the SDK's restricted elicitation schema so `inputRequired.elicit()`\n * accepts it without a cast.\n *\n * Projection-specific: MRTR carries whatever schema the server asks for, and\n * an approval prompt whose only payload is an optional decline reason is our\n * product decision (R16/R17), not a protocol shape.\n */\nexport const APPROVAL_SCHEMA: ElicitRequestFormParams['requestedSchema'] = {\n type: 'object',\n properties: {\n reason: {\n type: 'string',\n description: 'Optional note shown to the model when declining.',\n },\n },\n additionalProperties: false,\n};\n\n/**\n * Protocol revision that introduced MRTR.\n *\n * The SDK has no exported constant for it: `LATEST_PROTOCOL_VERSION` and\n * `SUPPORTED_PROTOCOL_VERSIONS` cover the *legacy* (`initialize`-negotiated)\n * family only — `2025-11-25` and earlier. The 2026-07-28 era is selected by\n * `server/discover`, and the SDK models it as the `ProtocolEra` value\n * `'modern'` rather than as a version string. We keep the literal purely so\n * error copy can name the revision a client must speak (R28).\n */\nexport const MRTR_PROTOCOL_REVISION = '2026-07-28';\n\n/**\n * Whether the era a request is being served on can carry MRTR (R28).\n *\n * The SDK binds an era to the *serving instance*, not to a per-request\n * header: `createMcpHandler` / `serveStdio` hand the era to the server\n * factory as `McpRequestContext.era`, and a hand-connected `McpServer` is\n * always `'legacy'`. So this takes the era, not a version string — there is\n * no `extra.protocolVersion` to read, and reading one was the bug this\n * migration fixes (docs/DECISIONS.md D1).\n */\nexport function supportsMrtr(era: ProtocolEra | undefined): boolean {\n return era === 'modern';\n}\n","/**\n * MRTR adapter — maps segment outcomes to `tools/call` results and parses\n * retries back into verdicts (PRD §7 \"MRTR adapter\"; R15, R17, R18, R27,\n * R28, S2).\n */\n\nimport { hashCode, openBlob, sealBlob, buildBlobPayload } from '../blob/index.js';\nimport { ProjectionError, toStructuredError } from '../errors.js';\nimport { runSegment } from '../machine-host/index.js';\nimport { buildElicitationCopy } from '../policy/index.js';\nimport {\n clampCaps,\n findTool,\n type ApprovalVerdict,\n type AuditEntry,\n type BlobSealerConfig,\n type LogEntry,\n type PendingToolCall,\n type PolicyOverrides,\n type RedactionHook,\n type ErrorPhase,\n type ResourceCaps,\n type SegmentOutcome,\n type ServerCatalog,\n type StructuredError,\n type ToolExecutor,\n} from '../types.js';\nimport {\n APPROVAL_SCHEMA,\n MRTR_PROTOCOL_REVISION,\n inputRequired,\n inputResponse,\n supportsMrtr,\n type CallToolResult,\n type ContentBlock,\n type InputRequests,\n type ProtocolEra,\n type RetryEnvelope,\n type ToolCallResult,\n} from './protocol.js';\n\nexport interface ExecuteMachineArgs extends RetryEnvelope {\n /** The authored module source (R2). */\n code: string;\n lang?: 'ts' | 'js';\n /** Passed to the machine as its input. */\n input?: unknown;\n}\n\nexport interface ExecuteMachineDeps {\n catalog: ServerCatalog;\n bridgeSource: string;\n executor: ToolExecutor;\n blob: BlobSealerConfig;\n caps?: Partial<ResourceCaps>;\n policy?: PolicyOverrides;\n redact?: RedactionHook;\n /**\n * Protocol era this request is being served on, for down-negotiation\n * (R28). The SDK hands it to the server factory as\n * `McpRequestContext.era`; `undefined` is treated as legacy.\n */\n protocolEra?: ProtocolEra;\n}\n\n/**\n * Run `execute_machine` for one `tools/call`, whether it is a first attempt\n * or an MRTR retry.\n *\n * Statelessness (R27): everything needed to resume rides in `requestState`,\n * so any instance can serve any retry. Nothing is held between calls.\n */\nexport async function executeMachine(\n args: ExecuteMachineArgs,\n deps: ExecuteMachineDeps,\n): Promise<ToolCallResult> {\n const caps = clampCaps(deps.caps ?? {});\n\n try {\n assertCodeSize(args.code, caps);\n assertInputSize(args.input, caps);\n\n const resume = args.requestState !== undefined ? openResume(args, deps, caps) : undefined;\n\n const outcome = await runSegment({\n code: args.code,\n ...(args.lang !== undefined ? { lang: args.lang } : {}),\n ...(args.input !== undefined ? { input: args.input } : {}),\n catalog: deps.catalog,\n bridgeSource: deps.bridgeSource,\n executor: deps.executor,\n caps,\n ...(deps.policy !== undefined ? { policy: deps.policy } : {}),\n segment: resume?.trip ?? 0,\n ...(resume !== undefined ? { resume } : {}),\n });\n\n return toToolCallResult(outcome, args, deps, caps);\n } catch (err) {\n return errorResult(toStructuredError(err));\n }\n}\n\n// ---------------------------------------------------------------------------\n// Retry handling\n// ---------------------------------------------------------------------------\n\ninterface ResumeState {\n snapshot: unknown;\n pending: Record<string, PendingToolCall>;\n verdicts: Record<string, ApprovalVerdict>;\n audit: AuditEntry[];\n trip: number;\n}\n\n/**\n * Verify the echoed blob and turn `inputResponses` into verdicts.\n *\n * The blob sealer performs the full R21 check chain (authenticate, version,\n * expiry, codeHash, server identity) and throws on any failure, so nothing\n * gated executes from an unverified blob.\n */\nfunction openResume(\n args: ExecuteMachineArgs,\n deps: ExecuteMachineDeps,\n caps: ResourceCaps,\n): ResumeState {\n const payload = openBlob(args.requestState as string, {\n code: args.code,\n serverIdentity: deps.catalog.identity,\n config: deps.blob,\n });\n\n // R18: the trip cap bounds a workflow's total round trips. The counter is\n // authenticated inside the blob, so a client cannot wind it back.\n //\n // `trip` is 1 on the first suspension, so a blob carrying trip === N is\n // the Nth round trip and must be allowed; only N+1 is over the cap. The\n // cap is also enforced at suspension time, which is what actually refuses\n // the workflow — this arm only catches a blob minted before a cap change.\n if (payload.trip > caps.maxRoundTrips) {\n throw new ProjectionError(\n 'terminal',\n `this workflow reached the limit of ${caps.maxRoundTrips} approval round trips`,\n {\n hint: `Restructure the machine to need at most ${caps.maxRoundTrips} approval round trips, for example by batching writes into fewer states.`,\n },\n );\n }\n\n const verdicts: Record<string, ApprovalVerdict> = {};\n for (const key of Object.keys(payload.pending)) {\n // The SDK's discriminated reader covers every non-approval outcome in\n // one place: a missing key, a response of another kind (sampling,\n // roots), and the decline/cancel actions. R17 treats all of them as a\n // decline, so only an accepted elicitation approves the call.\n const view = inputResponse(args.inputResponses, key);\n if (view.kind !== 'elicit' || view.action !== 'accept') {\n const reason = view.kind === 'elicit' ? readReason(view.content) : undefined;\n verdicts[key] = reason !== undefined ? { kind: 'declined', reason } : { kind: 'declined' };\n continue;\n }\n verdicts[key] = { kind: 'approved' };\n }\n\n return {\n snapshot: payload.snapshot,\n pending: payload.pending,\n verdicts,\n // PRD §8: the audit trail spans the whole workflow, so it rides in the\n // blob — the library keeps no state between round trips (R27).\n audit: payload.audit,\n trip: payload.trip,\n };\n}\n\nfunction readReason(content: Record<string, unknown> | undefined): string | undefined {\n const reason = content?.['reason'];\n return typeof reason === 'string' && reason.length > 0 ? reason : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Outcome mapping\n// ---------------------------------------------------------------------------\n\nfunction toToolCallResult(\n outcome: SegmentOutcome,\n args: ExecuteMachineArgs,\n deps: ExecuteMachineDeps,\n caps: ResourceCaps,\n): ToolCallResult {\n switch (outcome.status) {\n case 'completed':\n // A finished result is a plain `CallToolResult`: the `resultType`\n // discriminator only ever appears on the input-required branch, and\n // the SDK lifts complete results before the client sees them.\n return {\n content: [\n { type: 'text', text: JSON.stringify(outcome.output ?? null, null, 2) },\n ...logBlocks(outcome.logs),\n ],\n structuredContent: {\n output: outcome.output ?? null,\n approvals: outcome.audit,\n logs: outcome.logs,\n },\n };\n\n case 'suspended':\n return suspendResult(outcome, args, deps, caps);\n\n case 'error':\n return errorResult(outcome.error);\n }\n}\n\nfunction suspendResult(\n outcome: Extract<SegmentOutcome, { status: 'suspended' }>,\n args: ExecuteMachineArgs,\n deps: ExecuteMachineDeps,\n caps: ResourceCaps,\n): ToolCallResult {\n // This segment's console output rides on every failure below (R31).\n const fail = (phase: ErrorPhase, message: string, hint: string): ToolCallResult =>\n errorResult({ phase, message, diagnostics: [], hint, logs: outcome.logs });\n\n // R28: a client that cannot carry MRTR must fail here rather than silently\n // executing an unapproved write or hanging.\n //\n // The SDK would otherwise fulfil an `input_required` return on a legacy\n // connection through its server→client elicitation shim. Projection refuses\n // that path deliberately: R28 mandates a fail-fast error naming the\n // required revision, and the shim's push-style round trips hold a\n // connection open, which is exactly the statelessness (R27) the MRTR\n // design buys us.\n if (!supportsMrtr(deps.protocolEra)) {\n return fail(\n 'protocol',\n `this machine needs approval for a non-read-only tool call, which requires MCP protocol revision ${MRTR_PROTOCOL_REVISION} or later (this request is being served on the ${deps.protocolEra ?? 'legacy'} protocol era)`,\n 'Author a machine that only calls read-only tools, or connect with a client that negotiates the 2026-07-28 revision (SDK v2: `versionNegotiation: { mode: \"auto\" }`).',\n );\n }\n\n // R18: refuse to suspend again once the cap is reached, rather than\n // minting a blob the retry would reject.\n if (outcome.trip > caps.maxRoundTrips) {\n return fail(\n 'terminal',\n `this workflow reached the limit of ${caps.maxRoundTrips} approval round trips`,\n `Restructure the machine to need at most ${caps.maxRoundTrips} approval round trips.`,\n );\n }\n\n const inputRequests: InputRequests = {};\n for (const [key, call] of Object.entries(outcome.pending)) {\n const entry = findTool(deps.catalog, call.name);\n if (entry === undefined) {\n return fail(\n 'validate',\n `the machine requested approval for unknown tool \"${call.name}\"`,\n 'Call only tools listed by discover_apis.',\n );\n }\n // S6: copy is built from catalog data and redacted args only — never\n // from model-authored free text.\n const copy = buildElicitationCopy(\n call,\n entry,\n deps.redact !== undefined ? { redact: deps.redact } : {},\n );\n // The 2026-07-28 elicitation params dropped `title` (the revision carries\n // `message` and `requestedSchema` only), so the summary line becomes the\n // first line of the message rather than being silently lost.\n inputRequests[key] = inputRequired.elicit({\n message: `${copy.title}\\n\\n${copy.message}`,\n requestedSchema: APPROVAL_SCHEMA,\n });\n }\n\n const payload = buildBlobPayload({\n code: args.code,\n serverIdentity: deps.catalog.identity,\n snapshot: outcome.snapshot,\n pending: outcome.pending,\n audit: outcome.audit,\n trip: outcome.trip,\n ...(deps.blob.ttlMs !== undefined ? { ttlMs: deps.blob.ttlMs } : {}),\n });\n\n let requestState: string;\n try {\n requestState = sealBlob(payload, deps.blob);\n } catch (err) {\n // R23 (blob over the size ceiling) is a failure the model can act on, so\n // it must keep this segment's console output (R31) rather than losing it\n // to the generic catch in executeMachine.\n const structured = toStructuredError(err, outcome.logs);\n return errorResult({ ...structured, logs: outcome.logs });\n }\n\n // The SDK's builder enforces the spec's at-least-one rule and stamps the\n // `resultType` discriminator, so the suspension is never hand-assembled.\n //\n // R31 caveat, verified against the SDK's wire codec: an `InputRequiredResult`\n // carries `resultType`, `inputRequests` and `requestState` and nothing else\n // — the 2026-07-28 encode seam drops `content` and `_meta` alike. So the\n // suspending segment's console output cannot ride this leg. It is not\n // smuggled into the elicitation prompt either: that copy is server-derived\n // by S6, and logs are model-authored. Every other response (completion,\n // `isError`, and each resumed segment) still carries its own logs.\n return inputRequired({ inputRequests, requestState });\n}\n\n/** Every failure is a normal result with `isError: true` and a structured body (R25). */\nfunction errorResult(error: StructuredError): CallToolResult {\n return {\n isError: true,\n content: [{ type: 'text', text: JSON.stringify(error, null, 2) }],\n structuredContent: { ...error },\n };\n}\n\nfunction logBlocks(logs: LogEntry[]): ContentBlock[] {\n if (logs.length === 0) return [];\n const text = logs.map((log) => `[${log.level}] ${log.message}`).join('\\n');\n return [{ type: 'text', text: `Console output:\\n${text}` }];\n}\n\nfunction assertCodeSize(code: string, caps: ResourceCaps): void {\n const size = Buffer.byteLength(code, 'utf8');\n if (size > caps.maxCodeBytes) {\n throw new ProjectionError(\n 'cap_exceeded',\n `submitted code is ${size} bytes, exceeding the limit of ${caps.maxCodeBytes}`,\n {\n hint: `Shorten the machine to at most ${caps.maxCodeBytes} bytes.`,\n },\n );\n }\n}\n\n/**\n * The input is interpolated into the validation and bootstrap driver sources\n * as a JSON literal, so its serialized size — not the wire size of the raw\n * value — is what the sandbox actually pays for. Bounding it here yields a\n * structured cap_exceeded error instead of an opaque WASM memory failure.\n */\nfunction assertInputSize(input: unknown, caps: ResourceCaps): void {\n if (input === undefined) return;\n let json: string | undefined;\n try {\n json = JSON.stringify(input);\n } catch (err) {\n throw new ProjectionError('validate', 'machine input is not JSON-serializable', {\n hint: 'Remove circular references from the input; it must serialize to plain JSON.',\n cause: err,\n });\n }\n // A top-level function or symbol stringifies to undefined. Unreachable over\n // the wire (JSON transport); leave it to downstream handling as before.\n if (json === undefined) return;\n const size = Buffer.byteLength(json, 'utf8');\n if (size > caps.maxInputBytes) {\n throw new ProjectionError(\n 'cap_exceeded',\n `submitted input serializes to ${size} bytes, exceeding the limit of ${caps.maxInputBytes}`,\n {\n hint: `Shrink the machine input to at most ${caps.maxInputBytes} bytes of JSON.`,\n },\n );\n }\n}\n\n/** Re-exported so callers can bind a blob to code without importing the sealer. */\nexport { hashCode };\n","/**\n * `discover_apis` — the tool that teaches the model to author a machine\n * (PRD G6, R3, R29).\n *\n * Returns a compact inline overview that is sufficient on its own, plus a\n * `resource_link` per artifact so a model can pull full contents only when\n * it wants them. Clients with weak resource support still function.\n */\n\nimport { AUTHORING_CONTRACT } from '../machine-host/index.js';\nimport { XSTATE_VERSION } from '../blob/index.js';\nimport type { ServerCatalog } from '../types.js';\nimport type { CallToolResult, ContentBlock } from './protocol.js';\n\n/** Stable URIs the server serves via `resources/read` (R3). */\nexport const RESOURCE_URIS = {\n toolTypes: 'projection://types/tools.d.ts',\n contract: 'projection://docs/authoring-contract.md',\n happyPath: 'projection://examples/happy-path.ts',\n denialFallback: 'projection://examples/denial-fallback.ts',\n} as const;\n\n/** One resource Projection serves, ready to register on the MCP server. */\nexport interface ProjectionResource {\n uri: string;\n name: string;\n description: string;\n mimeType: string;\n text: string;\n}\n\nexport const EXAMPLE_HAPPY_PATH = `import { setup, assign } from 'xstate';\nimport { toolCall } from '@astral-mcp/tools';\n\n// Read a file and return its contents. Read-only calls run immediately,\n// so this whole machine completes in one round trip.\nexport default setup({}).createMachine({\n id: 'readNotes',\n context: ({ input }) => ({ path: input?.path ?? '/notes.txt', text: null }),\n initial: 'reading',\n states: {\n reading: {\n entry: toolCall('read_file', ({ context }) => ({ path: context.path })),\n on: {\n TOOL_RESULT: {\n target: 'done',\n actions: assign({ text: ({ event }) => event.result }),\n },\n TOOL_ERROR: {\n target: 'failed',\n actions: assign({ text: ({ event }) => \\`error: \\${event.error.message}\\` }),\n },\n },\n },\n done: { type: 'final' },\n failed: { type: 'final' },\n },\n output: ({ context }) => ({ text: context.text }),\n});\n`;\n\nexport const EXAMPLE_DENIAL_FALLBACK = `import { setup, assign } from 'xstate';\nimport { toolCall } from '@astral-mcp/tools';\n\n// Write a file, but keep going if the user declines. TOOL_DENIED is an\n// ordinary transition — denial is never an automatic abort.\nexport default setup({}).createMachine({\n id: 'writeWithFallback',\n context: { status: 'pending', note: null },\n initial: 'writing',\n states: {\n writing: {\n entry: toolCall('write_file', () => ({ path: '/notes.txt', content: 'hello' })),\n on: {\n TOOL_RESULT: {\n target: 'summarizing',\n actions: assign({ status: 'written' }),\n },\n TOOL_DENIED: {\n // The user said no: record it and carry on with the read-only\n // part of the work instead of failing the whole workflow.\n target: 'summarizing',\n actions: assign({\n status: 'skipped',\n note: ({ event }) => event.reason ?? 'declined by user',\n }),\n },\n TOOL_ERROR: {\n target: 'summarizing',\n actions: assign({ status: 'failed' }),\n },\n },\n },\n summarizing: {\n entry: toolCall('list_dir', () => ({ path: '/' })),\n on: {\n TOOL_RESULT: { target: 'done' },\n TOOL_ERROR: { target: 'done' },\n },\n },\n done: { type: 'final' },\n },\n output: ({ context }) => ({ status: context.status, note: context.note }),\n});\n`;\n\n/** Build the resources Projection serves for a wrapped server (R3). */\nexport function buildResources(catalog: ServerCatalog, dts: string): ProjectionResource[] {\n return [\n {\n uri: RESOURCE_URIS.toolTypes,\n name: 'tools.d.ts',\n description: `TypeScript definitions for the tools of ${catalog.identity}.`,\n mimeType: 'text/plain',\n text: dts,\n },\n {\n uri: RESOURCE_URIS.contract,\n name: 'authoring-contract.md',\n description: 'Rules an authored machine must follow.',\n mimeType: 'text/markdown',\n text: AUTHORING_CONTRACT,\n },\n {\n uri: RESOURCE_URIS.happyPath,\n name: 'happy-path.ts',\n description: 'Example machine: read-only work, completes in one call.',\n mimeType: 'text/plain',\n text: EXAMPLE_HAPPY_PATH,\n },\n {\n uri: RESOURCE_URIS.denialFallback,\n name: 'denial-fallback.ts',\n description: 'Example machine: continues gracefully when approval is declined.',\n mimeType: 'text/plain',\n text: EXAMPLE_DENIAL_FALLBACK,\n },\n ];\n}\n\n/**\n * The `discover_apis` result: an inline overview sufficient to author a\n * simple machine unaided, plus resource links for the full artifacts.\n */\nexport function discoverApis(catalog: ServerCatalog, overview: string): CallToolResult {\n const inline = [\n `Projection code mode over \"${catalog.identity}\".`,\n '',\n `XState version: ${XSTATE_VERSION} (pinned). Importable modules: 'xstate', '@astral-mcp/tools'. Nothing else resolves; there is no network and no filesystem.`,\n '',\n overview,\n '',\n AUTHORING_CONTRACT,\n ].join('\\n');\n\n const links: ContentBlock[] = buildResources(catalog, '').map((resource) => ({\n type: 'resource_link',\n uri: resource.uri,\n name: resource.name,\n description: resource.description,\n mimeType: resource.mimeType,\n }));\n\n return {\n content: [{ type: 'text', text: inline }, ...links],\n };\n}\n\n/**\n * The wrapped server's `instructions`, followed by the code-mode preamble\n * (R29). The preamble is library copy the integrating developer can replace.\n */\nexport const DEFAULT_CODE_MODE_PREAMBLE = `This server runs in code mode: instead of calling its tools directly, author an XState v5 state machine and run it with execute_machine, which orchestrates the tool calls for you. Any tool that is not read-only pauses the machine and asks the user to approve that specific action before it runs. Call discover_apis first for the tool types, the authoring contract, and worked examples.`;\n\nexport function buildInstructions(catalog: ServerCatalog, preamble?: string): string {\n const wrapped = catalog.instructions?.trim();\n const codeMode = preamble ?? DEFAULT_CODE_MODE_PREAMBLE;\n return wrapped !== undefined && wrapped.length > 0 ? `${wrapped}\\n\\n${codeMode}` : codeMode;\n}\n","/**\n * Hand-rolled JSON Schema → TypeScript type-text converter (R4).\n *\n * Deliberately a subset: it covers the constructs MCP tool schemas actually\n * use (objects/properties/required, primitive types, enum/const, arrays and\n * tuples, anyOf/oneOf unions, allOf intersections, in-document $ref,\n * additionalProperties, nested objects, property descriptions as doc\n * comments). Anything it does not understand degrades to `unknown` — never\n * an exception — because generated types are model guidance, not a\n * correctness gate (G5: no host-side type checking in the hot path).\n */\n\nimport { isRecord } from '../types.js';\n\nconst MAX_DEPTH = 24;\n\ninterface RenderContext {\n /** Root schema document, for resolving in-document $refs. */\n root: unknown;\n /** Recursion depth guard. */\n depth: number;\n /** $ref pointers currently being expanded (cycle guard). */\n refStack: string[];\n /** Indentation prefix of the line the type appears on. */\n indent: string;\n}\n\n/** Render a JSON literal as a TS literal type; non-primitives become `unknown`. */\nfunction literalType(value: unknown): string {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return JSON.stringify(value);\n }\n return 'unknown';\n}\n\n/** Resolve an in-document JSON pointer like `#/$defs/Foo`. */\nfunction resolvePointer(root: unknown, pointer: string): unknown {\n if (!pointer.startsWith('#')) return undefined;\n const path = pointer.slice(1);\n if (path === '') return root;\n if (!path.startsWith('/')) return undefined;\n let current: unknown = root;\n for (const rawSegment of path.slice(1).split('/')) {\n const segment = rawSegment.replaceAll('~1', '/').replaceAll('~0', '~');\n if (Array.isArray(current)) {\n const index = Number(segment);\n current = Number.isInteger(index) ? current[index] : undefined;\n } else if (isRecord(current)) {\n current = current[segment];\n } else {\n return undefined;\n }\n if (current === undefined) return undefined;\n }\n return current;\n}\n\n/** Wrap a type in parentheses when it is a top-level union/intersection. */\nfunction parenthesize(type: string): string {\n return /[|&]/.test(type) ? `(${type})` : type;\n}\n\nconst BARE_KEY_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/** Quote an object key unless it is a valid bare property name. */\nexport function propertyKey(name: string): string {\n return BARE_KEY_RE.test(name) ? name : JSON.stringify(name);\n}\n\n/** Format a description as a doc comment block at the given indent. */\nexport function docComment(description: string, indent: string): string {\n const safe = description.replaceAll('*/', '*\\\\/').trimEnd();\n const lines = safe.split('\\n');\n if (lines.length === 1) return `${indent}/** ${lines[0]} */`;\n return [\n `${indent}/**`,\n ...lines.map((line) => `${indent} * ${line}`.trimEnd()),\n `${indent} */`,\n ].join('\\n');\n}\n\nfunction renderEnum(values: unknown[]): string {\n if (values.length === 0) return 'never';\n return values.map(literalType).join(' | ');\n}\n\nfunction renderArray(schema: Record<string, unknown>, ctx: RenderContext): string {\n // Draft 2020-12 tuples use prefixItems; older drafts use an items array.\n const prefixItems = Array.isArray(schema['prefixItems'])\n ? schema['prefixItems']\n : Array.isArray(schema['items'])\n ? schema['items']\n : undefined;\n if (prefixItems !== undefined) {\n const members = prefixItems.map((item) => render(item, deeper(ctx)));\n return `[${members.join(', ')}]`;\n }\n const items = schema['items'];\n if (items === undefined) return 'unknown[]';\n const itemType = render(items, deeper(ctx));\n return /[|&]/.test(itemType) || itemType.includes('\\n') ? `Array<${itemType}>` : `${itemType}[]`;\n}\n\nfunction renderObject(schema: Record<string, unknown>, ctx: RenderContext): string {\n const properties = isRecord(schema['properties']) ? schema['properties'] : undefined;\n const additional = schema['additionalProperties'];\n const additionalType = isRecord(additional)\n ? render(additional, deeper(ctx))\n : additional === false\n ? undefined\n : 'unknown';\n\n if (properties === undefined || Object.keys(properties).length === 0) {\n if (additional === false) return 'Record<string, never>';\n return `Record<string, ${additionalType ?? 'unknown'}>`;\n }\n\n const required = new Set(\n Array.isArray(schema['required'])\n ? schema['required'].filter((name): name is string => typeof name === 'string')\n : [],\n );\n const childIndent = `${ctx.indent} `;\n const lines: string[] = ['{'];\n for (const [name, propSchema] of Object.entries(properties)) {\n const description = isRecord(propSchema) ? propSchema['description'] : undefined;\n if (typeof description === 'string' && description.length > 0) {\n lines.push(docComment(description, childIndent));\n }\n const optional = required.has(name) ? '' : '?';\n const type = render(propSchema, { ...deeper(ctx), indent: childIndent });\n lines.push(`${childIndent}${propertyKey(name)}${optional}: ${type};`);\n }\n lines.push(`${ctx.indent}}`);\n const objectType = lines.join('\\n');\n // An explicit additionalProperties schema alongside named properties is\n // expressed as an intersection, which stays valid strict TS.\n return isRecord(additional)\n ? `${objectType} & Record<string, ${additionalType ?? 'unknown'}>`\n : objectType;\n}\n\nfunction renderByType(type: string, schema: Record<string, unknown>, ctx: RenderContext): string {\n switch (type) {\n case 'string':\n return 'string';\n case 'number':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'null':\n return 'null';\n case 'array':\n return renderArray(schema, ctx);\n case 'object':\n return renderObject(schema, ctx);\n default:\n return 'unknown';\n }\n}\n\nfunction deeper(ctx: RenderContext): RenderContext {\n return { ...ctx, depth: ctx.depth + 1 };\n}\n\nfunction render(schema: unknown, ctx: RenderContext): string {\n if (schema === true) return 'unknown';\n if (schema === false) return 'never';\n if (!isRecord(schema)) return 'unknown';\n if (ctx.depth > MAX_DEPTH) return 'unknown';\n\n const ref = schema['$ref'];\n if (typeof ref === 'string') {\n if (ctx.refStack.includes(ref)) return 'unknown'; // circular $ref\n const resolved = resolvePointer(ctx.root, ref);\n if (resolved === undefined) return 'unknown';\n return render(resolved, { ...deeper(ctx), refStack: [...ctx.refStack, ref] });\n }\n\n const enumValues = schema['enum'];\n if (Array.isArray(enumValues)) return renderEnum(enumValues);\n if ('const' in schema) return literalType(schema['const']);\n\n const parts: string[] = [];\n\n const allOf = schema['allOf'];\n if (Array.isArray(allOf) && allOf.length > 0) {\n parts.push(...allOf.map((member) => render(member, deeper(ctx))));\n }\n\n const unionMembers = Array.isArray(schema['anyOf'])\n ? schema['anyOf']\n : Array.isArray(schema['oneOf'])\n ? schema['oneOf']\n : undefined;\n if (unionMembers !== undefined && unionMembers.length > 0) {\n parts.push(unionMembers.map((member) => render(member, deeper(ctx))).join(' | '));\n }\n\n const type = schema['type'];\n if (Array.isArray(type)) {\n const members = type\n .filter((entry): entry is string => typeof entry === 'string')\n .map((entry) => renderByType(entry, schema, ctx));\n if (members.length > 0) parts.push(members.join(' | '));\n } else if (typeof type === 'string') {\n parts.push(renderByType(type, schema, ctx));\n } else if (\n schema['properties'] !== undefined ||\n schema['additionalProperties'] !== undefined ||\n schema['required'] !== undefined\n ) {\n parts.push(renderObject(schema, ctx));\n } else if (schema['items'] !== undefined || schema['prefixItems'] !== undefined) {\n parts.push(renderArray(schema, ctx));\n }\n\n if (parts.length === 0) return 'unknown';\n if (parts.length === 1) {\n const only = parts[0];\n return only ?? 'unknown';\n }\n return parts.map(parenthesize).join(' & ');\n}\n\n/**\n * Convert a JSON Schema into TypeScript type text.\n *\n * @param schema - The schema (also used as the $ref resolution root).\n * @param indent - Indentation prefix of the line the type is emitted on;\n * nested object literals indent relative to it.\n */\nexport function schemaToTsType(schema: unknown, indent = ''): string {\n return render(schema, { root: schema, depth: 0, refStack: [], indent });\n}\n\n/**\n * True when the schema requires at least one argument property — used to\n * decide whether the generated tool function's `args` parameter is optional.\n */\nexport function schemaRequiresArgs(schema: unknown): boolean {\n return isRecord(schema) && Array.isArray(schema['required']) && schema['required'].length > 0;\n}\n","/**\n * Typegen — produces the `@astral-mcp/tools` artifacts from a ServerCatalog\n * (PRD G6, R3, R4, R30):\n *\n * 1. `.d.ts` text describing the namespaced `tools` API surface,\n * 2. the runtime bridge module source mounted at `@astral-mcp/tools` inside\n * the QuickJS sandbox, and\n * 3. a compact human-readable overview block for `discover_apis`.\n */\n\nimport { ProjectionError } from '../errors.js';\nimport { capLength, neutralizeControlChars } from '../text-safety.js';\nimport type { ServerCatalog, ToolCatalog, ToolCatalogEntry } from '../types.js';\nimport { docComment, propertyKey, schemaRequiresArgs, schemaToTsType } from './json-schema.js';\n\n/**\n * Module specifier authored machines import the tools surface from (R4).\n * The sandbox component mounts {@link GeneratedToolTypes.bridgeSource} here.\n */\nexport const TOOLS_MODULE_SPECIFIER = '@astral-mcp/tools';\n\n/**\n * Name of the global the sandbox host MUST inject before authored code runs.\n *\n * Contract (for the sandbox / machine-host components):\n *\n * ```js\n * globalThis.__projection_toolcall = (name, args) => <host-defined value>\n * ```\n *\n * - `name` is the wrapped server's tool name exactly as catalogued.\n * - `args` is a plain JSON-serializable object (never `undefined`; the\n * bridge substitutes `{}` for a missing argument).\n * - The bridge performs no I/O itself and returns the hook's value\n * verbatim. Per R7, authored machines never consume that value as a\n * promise inside invoked actors — the library-supplied `toolCall` action\n * is the intended caller, and results come back as TOOL_RESULT /\n * TOOL_ERROR / TOOL_DENIED events injected by the host.\n * - If the hook is missing, every tool function throws, keeping the bridge\n * inert outside a properly initialized sandbox (S1).\n */\nexport const TOOL_CALL_HOST_GLOBAL = '__projection_toolcall';\n\n/** Output of {@link generateToolTypes}. */\nexport interface GeneratedToolTypes {\n /** `.d.ts` text for the `@astral-mcp/tools` surface (serve via discover_apis, R3). */\n dts: string;\n /** ESM source of the runtime bridge to mount at `@astral-mcp/tools` in the sandbox. */\n bridgeSource: string;\n /** Compact per-tool overview block for inline embedding by discover_apis (R3). */\n overview: string;\n}\n\nconst PASCAL_FALLBACK = 'Tool';\n\n/**\n * Longest catalog-supplied identity rendered into generated artifacts.\n * A hostile wrapped server controls this string (S5).\n */\nconst MAX_IDENTITY_CHARS = 200;\n\n/**\n * Render an untrusted catalog string for safe inclusion in a `//` line\n * comment of generated source.\n *\n * The bridge source is EVALUATED (mounted at `@astral-mcp/tools` and imported\n * by every machine that calls a tool), so a newline in a wrapped server's\n * name or version would terminate the comment and inject executable\n * statements into the bridge — a hostile server would then run code inside\n * the sandbox on every `execute_machine`, regardless of what the model\n * authored (S1/S5). The same string lands in the `.d.ts` header the model\n * reads as authoritative guidance.\n *\n * `JSON.stringify` escapes newlines and quotes; the control/bidi pass covers\n * the separators JSON leaves raw, and the length cap bounds the artifact.\n */\nfunction commentSafe(text: string): string {\n return JSON.stringify(neutralizeControlChars(capLength(text, MAX_IDENTITY_CHARS)));\n}\n\n/** Derive a unique PascalCase type-name base from a tool name. */\nfunction pascalBase(toolName: string, taken: Set<string>): string {\n const joined = toolName\n .split(/[^A-Za-z0-9]+/)\n .filter((segment) => segment.length > 0)\n .map((segment) => (segment[0] ?? '').toUpperCase() + segment.slice(1))\n .join('');\n let base = /^[A-Za-z]/.test(joined) ? joined : `${PASCAL_FALLBACK}${joined}`;\n if (base.length === 0) base = PASCAL_FALLBACK;\n if (taken.has(base)) {\n let counter = 2;\n while (taken.has(`${base}${counter}`)) counter += 1;\n base = `${base}${counter}`;\n }\n taken.add(base);\n return base;\n}\n\ninterface ToolTypeNames {\n input: string;\n output: string | undefined;\n}\n\nfunction approvalNote(tool: ToolCatalogEntry): string {\n if (tool.annotations?.readOnlyHint === true) {\n return 'Read-only: executes immediately, no user approval required.';\n }\n if (tool.annotations?.destructiveHint === true) {\n return 'DESTRUCTIVE write: pauses the machine for user approval before executing.';\n }\n return 'Write (or unannotated): pauses the machine for user approval before executing.';\n}\n\nfunction toolDoc(tool: ToolCatalogEntry): string {\n const lines: string[] = [];\n if (tool.description !== undefined && tool.description.length > 0) {\n lines.push(tool.description.trim(), '');\n }\n lines.push(approvalNote(tool));\n return lines.join('\\n');\n}\n\nfunction generateDts(server: ServerCatalog): string {\n const taken = new Set<string>();\n const names = new Map<string, ToolTypeNames>();\n const sections: string[] = [];\n\n sections.push(\n [\n `// Generated by Projection from wrapped server ${commentSafe(server.identity)}. Do not edit.`,\n '//',\n '// Import inside an authored machine module as:',\n `// import { tools } from '${TOOLS_MODULE_SPECIFIER}';`,\n '//',\n '// Tool functions are the transport used by the library-supplied',\n '// `toolCall` action. Do NOT wrap them in fromPromise / invoked actors',\n '// (banned pattern R7) — emit toolCall(name, args) and handle the',\n '// TOOL_RESULT / TOOL_ERROR / TOOL_DENIED events instead.',\n ].join('\\n'),\n );\n\n for (const tool of server.tools) {\n const base = pascalBase(tool.name, taken);\n const typeNames: ToolTypeNames = {\n input: `${base}Input`,\n output: tool.outputSchema !== undefined ? `${base}Output` : undefined,\n };\n names.set(tool.name, typeNames);\n\n sections.push(\n `${docComment(`Input for tool \"${tool.name}\".`, '')}\\n` +\n `export type ${typeNames.input} = ${schemaToTsType(tool.inputSchema)};`,\n );\n if (typeNames.output !== undefined) {\n sections.push(\n `${docComment(`Output of tool \"${tool.name}\".`, '')}\\n` +\n `export type ${typeNames.output} = ${schemaToTsType(tool.outputSchema)};`,\n );\n }\n }\n\n const memberLines: string[] = [];\n for (const tool of server.tools) {\n // Names are set for every tool in the loop above (dedupeToolNames ran\n // first), so the lookup is always present.\n const typeNames = names.get(tool.name) as ToolTypeNames;\n memberLines.push(docComment(toolDoc(tool), ' '));\n const optional = schemaRequiresArgs(tool.inputSchema) ? '' : '?';\n const returnType = typeNames.output ?? 'unknown';\n memberLines.push(\n ` ${propertyKey(tool.name)}: (args${optional}: ${typeNames.input}) => Promise<${returnType}>;`,\n );\n }\n\n const surfaceDoc = docComment(\n `Namespaced tool surface of wrapped server ${commentSafe(server.identity)}.`,\n '',\n );\n const body =\n memberLines.length > 0\n ? `export declare const tools: {\\n${memberLines.join('\\n')}\\n};`\n : 'export declare const tools: Record<string, never>;';\n sections.push(`${surfaceDoc}\\n${body}\\n\\nexport default tools;`);\n\n return `${sections.join('\\n\\n')}\\n`;\n}\n\nfunction generateBridgeSource(server: ServerCatalog): string {\n // Assigned imperatively rather than as object-literal keys: a tool named\n // `__proto__` in a literal is the prototype-setter form, which would make\n // `tools` unusable and hide the tool from enumeration while the .d.ts\n // still advertises it. Bracket assignment onto a null-prototype object\n // treats every tool name as ordinary data (S5).\n const memberLines = server.tools.map(\n (tool) => `tools[${JSON.stringify(tool.name)}] = bindTool(${JSON.stringify(tool.name)});`,\n );\n return [\n `// ${TOOLS_MODULE_SPECIFIER} — runtime bridge generated by Projection`,\n `// from wrapped server ${commentSafe(server.identity)}. Do not edit.`,\n '//',\n '// Sandbox-host contract:',\n '// Before authored code runs, the sandbox host MUST inject:',\n `// globalThis.${TOOL_CALL_HOST_GLOBAL} = (name, args) => <host-defined>`,\n '// `name` is the catalogued tool name, `args` a plain JSON-serializable',\n '// object (the bridge substitutes {} when called without arguments).',\n '// This module performs no I/O itself; the injected hook is the only',\n '// channel out of the sandbox (S1), and its return value is handed back',\n '// verbatim to the caller — the library-supplied `toolCall` action.',\n '',\n 'function bindTool(name) {',\n ' return function (args) {',\n ` const hook = globalThis[${JSON.stringify(TOOL_CALL_HOST_GLOBAL)}];`,\n \" if (typeof hook !== 'function') {\",\n ' throw new Error(',\n ` 'Projection tools bridge: missing host hook globalThis.${TOOL_CALL_HOST_GLOBAL}. ' +`,\n \" 'The sandbox host must inject it before authored code runs.',\",\n ' );',\n ' }',\n ' return hook(name, args === undefined ? {} : args);',\n ' };',\n '}',\n '',\n 'const tools = Object.create(null);',\n ...memberLines,\n 'Object.freeze(tools);',\n '',\n 'export { tools };',\n 'export default tools;',\n '',\n ].join('\\n');\n}\n\nfunction overviewFlags(tool: ToolCatalogEntry): string {\n if (tool.annotations?.readOnlyHint === true) return '[read-only]';\n if (tool.annotations?.destructiveHint === true) return '[approval, destructive]';\n return '[approval]';\n}\n\nfunction firstLine(text: string | undefined): string {\n if (text === undefined) return '(no description)';\n const line = (text.split('\\n')[0] ?? '').trim();\n if (line.length === 0) return '(no description)';\n return line.length > 100 ? `${line.slice(0, 97)}...` : line;\n}\n\nfunction generateOverview(server: ServerCatalog): string {\n const lines = [`Tools (server: ${server.identity}):`];\n if (server.tools.length === 0) {\n lines.push(' (none)');\n }\n for (const tool of server.tools) {\n lines.push(`- ${tool.name} ${overviewFlags(tool)} — ${firstLine(tool.description)}`);\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction resolveSingleServer(catalog: ToolCatalog | ServerCatalog): ServerCatalog {\n if ('servers' in catalog) {\n if (catalog.servers.size !== 1) {\n throw new ProjectionError(\n 'protocol',\n `Typegen requires exactly one wrapped server; catalog has ${catalog.servers.size}.`,\n {\n hint: 'v1 wraps a single server (multi-server namespacing is a stretch goal, PRD 12.2). Pass a single-entry catalog or a ServerCatalog directly.',\n },\n );\n }\n const server = catalog.servers.values().next().value;\n if (server === undefined) {\n throw new ProjectionError('protocol', 'Tool catalog contains no servers.', {\n hint: 'Build the catalog with createIntrospector before generating types.',\n });\n }\n return server;\n }\n return catalog;\n}\n\n/**\n * Generate the `@astral-mcp/tools` artifacts for a wrapped server.\n *\n * Accepts either the full aliased {@link ToolCatalog} (which must contain\n * exactly one server in v1, per R30's single-instance instantiation) or a\n * {@link ServerCatalog} directly.\n */\nexport function generateToolTypes(catalog: ToolCatalog | ServerCatalog): GeneratedToolTypes {\n const server = dedupeToolNames(resolveSingleServer(catalog));\n return {\n dts: generateDts(server),\n bridgeSource: generateBridgeSource(server),\n overview: generateOverview(server),\n };\n}\n\n/**\n * Drop tools whose name repeats an earlier one, first occurrence wins.\n *\n * A wrapped server may return the same tool name twice (S5: the catalog is\n * untrusted). Emitting it twice would produce a duplicate member in the\n * `.d.ts` object type — invalid TypeScript — and a silently last-wins\n * shadowed key in the bridge, so the types and the runtime would disagree\n * about which schema the tool takes. Collapsing to the first occurrence\n * matches what `callTool` reaches on the wrapped server.\n */\nfunction dedupeToolNames(server: ServerCatalog): ServerCatalog {\n const seen = new Set<string>();\n const tools = server.tools.filter((tool) => {\n if (seen.has(tool.name)) return false;\n seen.add(tool.name);\n return true;\n });\n return tools.length === server.tools.length ? server : { ...server, tools };\n}\n","/**\n * `wrapMcpServer` — the integrating developer's entry point (PRD G1, R1).\n *\n * Introspects a wrapped MCP server, generates its `@astral-mcp/tools`\n * artifacts, and returns a facade exposing exactly two tools —\n * `execute_machine` and `discover_apis` — plus the resources backing\n * discovery. The wrapped server's own tools are never exposed (R1).\n *\n * The facade's primary shape is an SDK **server factory**, because that is\n * the only place the SDK tells a server which protocol era it is serving:\n *\n * ```ts\n * import { createMcpHandler } from '@modelcontextprotocol/server';\n *\n * const facade = await wrapMcpServer(myServer, { blob: { key } });\n * export default createMcpHandler(facade.serverFactory);\n * ```\n *\n * `createMcpHandler` (and `serveStdio`) call the factory once per serving\n * unit with `McpRequestContext.era`, so `createServer` can both apply the\n * code-mode `instructions` (R29 — `Server` only accepts them in its\n * constructor) and hand the era to the MRTR adapter for down-negotiation\n * (R28). `registerOn` remains for callers who build the `McpServer`\n * themselves, and takes the era explicitly for the same reason.\n *\n * Anything more exotic can drive `facade.executeMachine` /\n * `facade.discoverApis` directly — the facade is plain data and functions,\n * holding no cross-request state (R27).\n */\n\nimport type { Client } from '@modelcontextprotocol/client';\nimport {\n McpServer,\n type Implementation,\n type McpServerFactory,\n} from '@modelcontextprotocol/server';\nimport { z } from 'zod';\nimport { createIntrospector, type Introspector } from './introspector/index.js';\nimport {\n buildInstructions,\n buildResources,\n discoverApis,\n executeMachine,\n type CallToolResult,\n type ExecuteMachineArgs,\n type ProjectionResource,\n type ProtocolEra,\n type ToolCallResult,\n} from './mrtr/index.js';\nimport { generateToolTypes } from './typegen/index.js';\nimport {\n DEFAULT_SERVER_ALIAS,\n type BlobSealerConfig,\n type PolicyOverrides,\n type RedactionHook,\n type ResourceCaps,\n type ServerCatalog,\n} from './types.js';\nimport { ProjectionError } from './errors.js';\n\nexport interface WrapOptions {\n /** Blob sealing configuration; required for any gated flow (R22). */\n blob: BlobSealerConfig;\n /** Resource cap overrides, clamped at the hard maxima (R12). */\n caps?: Partial<ResourceCaps>;\n /** Per-tool policy overrides (R14). */\n policy?: PolicyOverrides;\n /** Masks sensitive argument fields before they reach an approval prompt (R16). */\n redact?: RedactionHook;\n /** Replaces the library's code-mode preamble (R29). */\n codeModePreamble?: string;\n /** Identity the servers built by `createServer` advertise. */\n serverInfo?: Implementation;\n}\n\n/** Options for registering the code-mode surface on a server the caller built. */\nexport interface RegisterOptions {\n /**\n * The protocol era this server instance serves (R28). Omitted means\n * `'legacy'`: a hand-connected `McpServer` never negotiates 2026-07-28, so\n * defaulting to legacy is the honest — and fail-safe — reading.\n */\n era?: ProtocolEra;\n}\n\nexport interface ProjectionFacade {\n /** Catalog of the wrapped server. */\n readonly catalog: ServerCatalog;\n /** Instructions to advertise: the wrapped server's, then the preamble (R29). */\n readonly instructions: string;\n /** Generated `.d.ts` for the wrapped server's tools. */\n readonly dts: string;\n /** Resources served at stable `projection://` URIs (R3). */\n readonly resources: ProjectionResource[];\n /**\n * Server factory to hand to `createMcpHandler` or `serveStdio` (R28, R29).\n * Every instance it builds carries the code-mode `instructions` and knows\n * the era it is serving.\n */\n readonly serverFactory: McpServerFactory;\n\n /** Run `execute_machine` for one `tools/call`, first attempt or retry. */\n executeMachine(args: ExecuteMachineArgs, era?: ProtocolEra): Promise<ToolCallResult>;\n /** Run `discover_apis`. */\n discoverApis(): CallToolResult;\n /** Build an `McpServer` carrying the instructions, both tools and the resources. */\n createServer(ctx?: RegisterOptions): McpServer;\n /** Register both tools and the resources on an `McpServer` the caller built. */\n registerOn(server: McpServer, options?: RegisterOptions): void;\n /** Close the connection to the wrapped server. */\n close(): Promise<void>;\n}\n\nconst EXECUTE_MACHINE_DESCRIPTION = `Run an LLM-authored XState v5 state machine that orchestrates this server's tools.\n\nAuthor a module that default-exports a machine built with XState v5 setup(...).createMachine(...), and request tools with the toolCall action from '@astral-mcp/tools'. Read-only tools run immediately; every other tool pauses the machine and asks the user to approve that exact call before it runs, so handle TOOL_RESULT, TOOL_ERROR and TOOL_DENIED. Machine context must stay JSON-serializable, and invoke/fromPromise is rejected.\n\nCall discover_apis first for the tool types, the full authoring contract, and worked examples.`;\n\nconst DISCOVER_APIS_DESCRIPTION = `Return this server's tool type definitions, the machine authoring contract, and worked examples. Call this before authoring a machine for execute_machine.`;\n\n/**\n * Wrap an MCP server (an in-process instance or a connected client) into a\n * code-mode facade.\n */\nexport async function wrapMcpServer(\n source: McpServer | Client,\n options: WrapOptions,\n): Promise<ProjectionFacade> {\n const introspector = await createIntrospector({ [DEFAULT_SERVER_ALIAS]: source });\n const catalog = introspector.catalog.servers.get(DEFAULT_SERVER_ALIAS);\n if (catalog === undefined) {\n throw new ProjectionError(\n 'protocol',\n 'introspection produced no catalog for the wrapped server',\n {\n hint: 'Check that the wrapped server initialized successfully.',\n },\n );\n }\n\n const { dts, bridgeSource, overview } = generateToolTypes(catalog);\n const resources = buildResources(catalog, dts);\n const instructions = buildInstructions(catalog, options.codeModePreamble);\n\n return new Facade({\n introspector,\n catalog,\n dts,\n bridgeSource,\n overview,\n resources,\n instructions,\n options,\n });\n}\n\ninterface FacadeDeps {\n introspector: Introspector;\n catalog: ServerCatalog;\n dts: string;\n bridgeSource: string;\n overview: string;\n resources: ProjectionResource[];\n instructions: string;\n options: WrapOptions;\n}\n\nclass Facade implements ProjectionFacade {\n readonly catalog: ServerCatalog;\n readonly instructions: string;\n readonly dts: string;\n readonly resources: ProjectionResource[];\n readonly serverFactory: McpServerFactory;\n private readonly deps: FacadeDeps;\n\n constructor(deps: FacadeDeps) {\n this.deps = deps;\n this.catalog = deps.catalog;\n this.instructions = deps.instructions;\n this.dts = deps.dts;\n this.resources = deps.resources;\n // Bound so it can be handed to `createMcpHandler` detached.\n this.serverFactory = (ctx) => this.createServer(ctx);\n }\n\n executeMachine(args: ExecuteMachineArgs, era?: ProtocolEra): Promise<ToolCallResult> {\n const { options } = this.deps;\n return executeMachine(args, {\n catalog: this.deps.catalog,\n bridgeSource: this.deps.bridgeSource,\n executor: this.deps.introspector,\n blob: options.blob,\n ...(options.caps !== undefined ? { caps: options.caps } : {}),\n ...(options.policy !== undefined ? { policy: options.policy } : {}),\n ...(options.redact !== undefined ? { redact: options.redact } : {}),\n ...(era !== undefined ? { protocolEra: era } : {}),\n });\n }\n\n discoverApis(): CallToolResult {\n return discoverApis(this.deps.catalog, this.deps.overview);\n }\n\n /**\n * R29: `Server` accepts `instructions` only in its constructor, so the\n * code-mode preamble can be delivered from here and nowhere else. This is\n * also where the era arrives, which is why the factory shape is the\n * library's recommended entry point.\n */\n createServer(ctx?: RegisterOptions): McpServer {\n const server = new McpServer(\n this.deps.options.serverInfo ?? {\n name: `projection-${this.deps.catalog.alias}`,\n version: '0.1.0',\n },\n { instructions: this.instructions },\n );\n this.registerOn(server, ctx);\n return server;\n }\n\n registerOn(server: McpServer, options?: RegisterOptions): void {\n const era = options?.era;\n\n server.registerTool(\n 'execute_machine',\n {\n title: 'Execute a state machine',\n description: EXECUTE_MACHINE_DESCRIPTION,\n inputSchema: EXECUTE_MACHINE_INPUT_SCHEMA,\n },\n async (args, ctx) =>\n await this.executeMachine(\n {\n code: args.code,\n // `exactOptionalPropertyTypes`: an absent optional argument must\n // stay absent rather than becoming an explicit `undefined`.\n ...(args.lang !== undefined ? { lang: args.lang } : {}),\n ...(args.input !== undefined ? { input: args.input } : {}),\n // MRTR's retry fields are request params, not tool arguments:\n // the SDK lifts them off `params` before the handler runs, so\n // they are read from the context rather than from `args`. The\n // raw wire string is what we want — `openBlob` performs the full\n // R21 verification, including the `codeHash` binding that a\n // `requestState.verify` hook could not check (it never sees the\n // re-sent `code`).\n ...maybeRequestState(ctx.mcpReq.requestState<unknown>()),\n ...(ctx.mcpReq.inputResponses !== undefined\n ? { inputResponses: ctx.mcpReq.inputResponses }\n : {}),\n },\n era,\n ),\n );\n\n server.registerTool(\n 'discover_apis',\n {\n title: 'Discover the tool API',\n description: DISCOVER_APIS_DESCRIPTION,\n inputSchema: z.object({}),\n },\n () => this.discoverApis(),\n );\n\n for (const resource of this.resources) {\n server.registerResource(\n resource.name,\n resource.uri,\n { description: resource.description, mimeType: resource.mimeType },\n () => ({\n contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: resource.text }],\n }),\n );\n }\n }\n\n close(): Promise<void> {\n return this.deps.introspector.close();\n }\n}\n\n/**\n * `ctx.mcpReq.requestState()` is typed as a caller-asserted cast, so it is\n * read as `unknown` and narrowed here: without a configured\n * `ServerOptions.requestState.verify` hook the SDK hands back the raw wire\n * string, and anything else means someone wired a decoding hook Projection\n * does not own.\n */\nfunction maybeRequestState(state: unknown): { requestState?: string } {\n return typeof state === 'string' ? { requestState: state } : {};\n}\n\n/**\n * `execute_machine` arguments (R2).\n *\n * The MRTR retry fields are deliberately absent: `requestState` and\n * `inputResponses` are siblings of `arguments` in a `tools/call`, not\n * members of it, and the SDK surfaces them on the handler context.\n */\nconst EXECUTE_MACHINE_INPUT_SCHEMA = z.object({\n code: z.string().describe('The machine module source: a default-exported XState v5 machine.'),\n lang: z\n .enum(['ts', 'js'])\n .optional()\n .describe('Language of `code`. Defaults to TypeScript-compatible parsing.'),\n input: z.unknown().optional().describe('Passed to the machine as its `input`.'),\n});\n"],"mappings":";;;;;;;;;;;;;AAKA,IAAa,kBAAb,cAAqC,MAAM;CACzC;CACA;CACA;CACA;CAEA,YACE,OACA,SACA,UAA6F,CAAC,GAC9F;EACA,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,KAAA,CAAS;EACjF,KAAK,OAAO;EACZ,KAAK,QAAQ;EACb,KAAK,cAAc,QAAQ,eAAe,CAAC;EAC3C,KAAK,OAAO,QAAQ,QAAQ;EAC5B,KAAK,OAAO,QAAQ,QAAQ,CAAC;CAC/B;CAEA,eAAgC;EAC9B,OAAO;GACL,OAAO,KAAK;GACZ,SAAS,KAAK;GACd,aAAa,KAAK;GAClB,MAAM,KAAK;GACX,MAAM,KAAK;EACb;CACF;AACF;;AAGA,SAAgB,kBAAkB,KAAc,OAAmB,CAAC,GAAoB;CACtF,IAAI,eAAe,iBAAiB;EAClC,MAAM,aAAa,IAAI,aAAa;EACpC,OAAO;GAAE,GAAG;G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