export type FabricSandboxTerminationReason = "completed" | "runtime_error" | "timed_out" | "aborted"; export interface FabricSandboxResult { value: unknown; logs: string[]; terminationReason: FabricSandboxTerminationReason; error?: string; } export interface FabricSandboxOptions { timeoutMs: number; memoryLimitBytes: number; maxLogChars?: number; strings?: Record; tokenBudget?: number; signal?: AbortSignal; minimumTimeoutMsForHostCall?(ref: string, args: Record): number | undefined; transpiledCode?: string; transpiledSourceMap?: string; } export type FabricHostCall = (ref: string, args: Record, signal: AbortSignal) => Promise; export declare const GUEST_SETUP = "\n(() => {\nconst __fabricBridge = globalThis.__fabricHostCall;\ndelete globalThis.__fabricHostCall;\nconst __successfulCalls = [];\nconst __resolvedCallRef = (ref, args) =>\n ref === \"fabric.$call\" && args && typeof args.ref === \"string\" ? args.ref : ref;\nconst __recordSuccessfulCall = (ref, args) => {\n __successfulCalls.push(Object.freeze({ ref: __resolvedCallRef(ref, args) }));\n};\nconst __handoffFacts = () => {\n const calls = Object.freeze(__successfulCalls.slice());\n const count = (ref) => {\n if (ref === undefined) return calls.length;\n const refs = new Set(Array.isArray(ref) ? ref : [ref]);\n return calls.reduce((total, call) => total + (refs.has(call.ref) ? 1 : 0), 0);\n };\n return Object.freeze({ calls, count });\n};\nconst __call = async (ref, args) => {\n const normalizedArgs = args ?? {};\n const value = await __fabricBridge(ref, normalizedArgs);\n __recordSuccessfulCall(ref, normalizedArgs);\n return value;\n};\nconst __piToolNames = [\"read\",\"bash\",\"edit\",\"write\",\"grep\",\"find\",\"ls\"];\nconst __toolsBase = {\n providers: () => __call(\"fabric.$providers\", {}),\n catalog: (args = {}) => __call(\"fabric.$catalog\", args),\n list: (args = {}) => __call(\"fabric.$list\", args),\n search: (args) => __call(\n \"fabric.$search\",\n typeof args === \"string\" ? { query: args } : args,\n ),\n describe: (args) => __call(\"fabric.$describe\", args),\n call: (args) => __call(\"fabric.$call\", args),\n progress: (args) => __call(\"fabric.$progress\", args),\n models: () => __call(\"fabric.$models\", {}),\n};\n// tools is discovery + generic calls only. The proxy keeps the seven discovery\n// methods and turns a core-tool name (read/bash/edit/...) into an actionable\n// error pointing at pi., so a model that writes tools.read(...) learns\n// the fix in one turn instead of looping on \"tools.read is not a function\".\nglobalThis.tools = new Proxy(__toolsBase, {\n get(target, property) {\n if (property === \"then\" || typeof property === \"symbol\") return undefined;\n const name = String(property);\n if (__piToolNames.indexOf(name) >= 0) {\n return () => {\n throw new Error(\n \"tools.\" + name + \" is not available on the discovery API. tools is discovery + generic calls only (providers/catalog/list/search/describe/call/models). For the Pi core tool, call pi.\" + name + \"(args), e.g. pi.\" + name + \"({ ... }).\"\n );\n };\n }\n return target[property];\n },\n set() { return true; },\n deleteProperty() { return true; },\n});\nconst __piStringFields = { bash: \"command\", read: \"path\", ls: \"path\", grep: \"pattern\", find: \"pattern\" };\n// Per-tool key aliases. The runtime normalizes them to the canonical form\n// before the host validates args; unit-converting aliases are handled separately\n// in __normalizePiArgs. This lets a model that writes { query, regex, ... }\n// or { file } instead of { pattern } / { path } still succeeds on the first\n// call. Keep these in sync with the PiToolsApi overloads in guest-types.ts so\n// the type-checker accepts the same spellings it coercion-handles at runtime.\nconst __piArgAliases = {\n bash: {\n cmd: \"command\", shell: \"command\", cmdline: \"command\", script: \"command\",\n commandLine: \"command\",\n },\n find: {\n query: \"pattern\", regex: \"pattern\", search: \"pattern\", name: \"pattern\",\n filename: \"pattern\", glob: \"pattern\", expression: \"pattern\", include: \"pattern\",\n max: \"limit\",\n },\n grep: {\n query: \"pattern\", regex: \"pattern\", search: \"pattern\", q: \"pattern\",\n expression: \"pattern\", text: \"pattern\",\n ic: \"ignoreCase\", caseInsensitive: \"ignoreCase\",\n globPattern: \"glob\",\n max: \"limit\", ctx: \"context\",\n },\n read: {\n file: \"path\", absolutePath: \"path\", file_path: \"path\", filePath: \"path\",\n filepath: \"path\", pathname: \"path\", target_file: \"path\", targetFile: \"path\",\n absolute_path: \"path\", fileAbsolutePath: \"path\",\n max: \"limit\", start: \"offset\",\n },\n ls: {\n dir: \"path\", file: \"path\", folder: \"path\", absolutePath: \"path\",\n file_path: \"path\", filePath: \"path\", filepath: \"path\", pathname: \"path\",\n target_file: \"path\", targetFile: \"path\", absolute_path: \"path\",\n fileAbsolutePath: \"path\", directory: \"path\", directoryPath: \"path\",\n max: \"limit\",\n },\n edit: {\n file: \"path\", absolutePath: \"path\", file_path: \"path\", filePath: \"path\",\n filepath: \"path\", pathname: \"path\", target_file: \"path\", targetFile: \"path\",\n absolute_path: \"path\", fileAbsolutePath: \"path\",\n old: \"oldText\", old_string: \"oldText\", oldString: \"oldText\",\n old_str: \"oldText\", oldStr: \"oldText\", from: \"oldText\",\n old_value: \"oldText\", old_text: \"oldText\", oldContent: \"oldText\",\n old_content: \"oldText\",\n new: \"newText\", replacement: \"newText\", new_string: \"newText\",\n newString: \"newText\", new_str: \"newText\", newStr: \"newText\",\n to: \"newText\", new_value: \"newText\", new_text: \"newText\",\n newContent: \"newText\", new_content: \"newText\",\n },\n write: {\n file: \"path\", absolutePath: \"path\", file_path: \"path\", filePath: \"path\",\n filepath: \"path\", pathname: \"path\", target_file: \"path\", targetFile: \"path\",\n absolute_path: \"path\", fileAbsolutePath: \"path\",\n contents: \"content\", body: \"content\", text: \"content\", data: \"content\",\n fileContent: \"content\",\n },\n};\n// Multi-arg positional order, used only when a call passes >= 2 args and the\n// (primary, options) merge in __positionalToArgs does not apply. One-field\n// tools (read/bash/ls) stay absent: their two-arg form is a bare string plus\n// an options object, repaired by the merge instead of a wrong-arity (2554)\n// type error; only a non-object second arg still fails 2554.\nconst __piPositionalFields = {\n grep: [\"pattern\", \"path\", \"limit\"],\n find: [\"pattern\", \"path\", \"limit\"],\n write: [\"path\", \"content\"],\n edit: [\"path\", \"oldText\", \"newText\"],\n};\n// Models often pass numbers as strings (\"20\"); coerce the known numeric\n// option fields so the host schema sees a number. Non-numeric strings pass\n// through untouched and fail host validation exactly as before. Kept in sync\n// with the numeric optionals in the PiToolsApi overloads in guest-types.ts.\nconst __piNumericFields = {\n read: [\"offset\", \"limit\"],\n grep: [\"limit\", \"context\"],\n find: [\"limit\"],\n ls: [\"limit\"],\n bash: [\"timeout\"],\n};\nconst __piOptionalFields = {\n read: [\"offset\", \"limit\"],\n grep: [\"path\", \"glob\", \"ignoreCase\", \"literal\", \"context\", \"limit\"],\n find: [\"path\", \"limit\"],\n ls: [\"path\", \"limit\"],\n bash: [\"timeout\"],\n};\n// (primary, options) two-arg merge for the string-primary tools:\n// pi.read(\"index.ts\", { limit: 120 }) becomes { path: \"index.ts\", limit: 120 }.\n// A plain-object second arg is never a valid positional value for these tools\n// (grep/find take (pattern, path, limit) strings/numbers), so merging is\n// unambiguous; the positional string wins the primary field on conflict. The\n// merged object flows through the same alias, unit, and numeric normalization\n// in __normalizePiArgs as any other options object.\nconst __positionalToArgs = (name, rest) => {\n const first = rest[0];\n const second = rest[1];\n const primaryField = __piStringFields[name];\n if (\n rest.length === 2 &&\n typeof first === \"string\" &&\n primaryField !== undefined &&\n second !== null && typeof second === \"object\" && !Array.isArray(second)\n ) {\n const merged = Object.assign({}, second);\n merged[primaryField] = first;\n return merged;\n }\n const order = __piPositionalFields[name];\n if (!order) return rest.length > 0 ? first : {};\n const out = {};\n for (let i = 0; i < rest.length && i < order.length; i++) {\n const v = rest[i];\n if (v !== undefined) out[order[i]] = v;\n }\n return out;\n};\nconst __normalizePiArgs = (name, args) => {\n const field = __piStringFields[name];\n if (typeof args === \"string\" && field) return { [field]: args };\n if (args === null || typeof args !== \"object\" || Array.isArray(args)) return args;\n const aliases = __piArgAliases[name];\n let out = args;\n if (name === \"bash\" && \"timeoutMs\" in out) {\n out = Object.assign({}, args);\n if (!(\"timeout\" in out)) {\n const timeoutMs = out.timeoutMs;\n if (timeoutMs !== null && timeoutMs !== undefined) {\n out.timeout = Number.isFinite(Number(timeoutMs)) ? Number(timeoutMs) / 1000 : timeoutMs;\n }\n }\n delete out.timeoutMs;\n }\n // settle is a guest-only directive (settles nonzero exits instead of\n // rejecting); strip it so it never reaches the host/bash schema.\n if (name === \"bash\" && \"settle\" in out) {\n if (out === args) out = Object.assign({}, args);\n delete out.settle;\n }\n if (aliases) {\n for (const alias in aliases) {\n const canonical = aliases[alias];\n if (alias in out) {\n if (out === args) out = Object.assign({}, args);\n if (!(canonical in out)) out[canonical] = out[alias];\n delete out[alias];\n }\n }\n }\n const numerics = __piNumericFields[name];\n if (numerics) {\n for (const key of numerics) {\n const value = out[key];\n if (typeof value === \"string\" && value.trim() !== \"\" && Number.isFinite(Number(value))) {\n if (out === args) out = Object.assign({}, args);\n out[key] = Number(value);\n }\n }\n }\n const optionalFields = __piOptionalFields[name];\n if (optionalFields) {\n for (const key of optionalFields) {\n if (out[key] !== null && out[key] !== undefined) continue;\n if (!(key in out)) continue;\n if (out === args) out = Object.assign({}, args);\n delete out[key];\n }\n }\n if (name === \"edit\" && Array.isArray(out.edits)) {\n let changed = false;\n const editAliases = __piArgAliases.edit;\n const edits = out.edits.map((entry) => {\n if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) return entry;\n let edit = entry;\n for (const alias in editAliases) {\n const canonical = editAliases[alias];\n if (canonical !== \"oldText\" && canonical !== \"newText\") continue;\n if (!(alias in edit)) continue;\n if (edit === entry) edit = Object.assign({}, entry);\n if (!(canonical in edit)) edit[canonical] = edit[alias];\n delete edit[alias];\n changed = true;\n }\n return edit;\n });\n if (changed) {\n if (out === args) out = Object.assign({}, args);\n out.edits = edits;\n }\n }\n if (name === \"edit\" && !Array.isArray(out.edits) && (\"oldText\" in out || \"newText\" in out)) {\n if (out === args) out = Object.assign({}, args);\n const edit = {};\n if (\"oldText\" in out) edit.oldText = out.oldText;\n if (\"newText\" in out) edit.newText = out.newText;\n out.edits = [edit];\n delete out.oldText;\n delete out.newText;\n }\n return out;\n};\n// bash/edit/write resolve envelope objects { ok, output, details }, and the\n// type-checker deliberately suppresses property-miss (2339) diagnostics, so\n// result.trim() on an envelope typechecks and then dies with QuickJS's terse\n// \"not a function\" \u2014 an error models cannot localize (observed: misdirected\n// debugging spirals probing unrelated globals). Guard envelopes with a proxy\n// that throws an actionable TypeError for string-method access and iteration,\n// naming the tool and the .output fix. Ordinary reads (ok/output/details/\n// exitCode/error), destructuring, 'in' checks, and JSON marshaling pass through.\nconst __piEnvelopeTools = { bash: true, edit: true, write: true };\nconst __piEnvelopeStringTraps = new Set([\n \"anchor\", \"at\", \"big\", \"blink\", \"bold\", \"charAt\", \"charCodeAt\", \"codePointAt\",\n \"concat\", \"endsWith\", \"fixed\", \"fontcolor\", \"fontsize\", \"includes\", \"indexOf\",\n \"italics\", \"lastIndexOf\", \"length\", \"link\", \"localeCompare\", \"match\", \"matchAll\",\n \"normalize\", \"padEnd\", \"padStart\", \"repeat\", \"replace\", \"replaceAll\", \"search\",\n \"slice\", \"small\", \"split\", \"startsWith\", \"strike\", \"sub\", \"substr\", \"substring\",\n \"sup\", \"toLocaleLowerCase\", \"toLocaleUpperCase\", \"toLowerCase\", \"toUpperCase\",\n \"trim\", \"trimEnd\", \"trimStart\",\n]);\nconst __piEnvelopeGuard = (name, value) => {\n if (value === null || typeof value !== \"object\" || typeof value.ok !== \"boolean\") return value;\n return new Proxy(value, {\n get(target, property, receiver) {\n if (property === Symbol.iterator || property === Symbol.asyncIterator) {\n throw new TypeError(\n \"pi.\" + name + \"(...) resolves an envelope { ok, output, details }, which is not iterable. \" +\n \"Iterate the text instead: (await pi.\" + name + \"(...)).output.split('\\\\n')\"\n );\n }\n if (typeof property === \"string\" && __piEnvelopeStringTraps.has(property)) {\n throw new TypeError(\n \"pi.\" + name + \"(...) resolves an envelope { ok, output, details }, not a string, so .\" + property +\n \" is unavailable on it. Read the text first: const out = (await pi.\" + name + \"(...)).output; then out.\" + property +\n \"(...). bash rejects on a nonzero exit \u2014 pass settle: true to receive an ok:false envelope instead.\"\n );\n }\n return Reflect.get(target, property, receiver);\n },\n });\n};\n// The pi proxy accepts: a bare string (primary field), an options object, a\n// (primary, options) two-arg merge for the string-primary tools, or a\n// positional spread mapped by __piPositionalFields. 0/1 args preserve the\n// legacy (args = {}) default so existing programs are unchanged.\nglobalThis.pi = new Proxy({}, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n const name = String(property);\n return (...rest) => {\n let args;\n if (rest.length <= 1) {\n const first = rest.length === 1 ? rest[0] : undefined;\n args = first === undefined ? {} : first;\n } else {\n args = __positionalToArgs(name, rest);\n }\n // bash rejects on an ordinary nonzero exit; settle:true returns\n // {ok:false, exitCode, ...} instead (opt-in). Other failures still reject.\n const settle = name === \"bash\" &&\n typeof args === \"object\" && args !== null && args.settle === true;\n const call = __call(\"pi.\" + name, __normalizePiArgs(name, args));\n const promise = settle ? call.catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n const match = /(?:^|\\n\\n)Command exited with code (\\d+)$/.exec(message);\n if (!match) throw error;\n return {\n ok: false,\n output: message.slice(0, match.index),\n details: null,\n exitCode: Number(match[1]),\n error: message,\n };\n }) : call;\n return __piEnvelopeTools[name] === true\n ? promise.then((value) => __piEnvelopeGuard(name, value))\n : promise;\n };\n },\n});\nconst __piStrings = (typeof globalThis[\"\u03C0\"] === \"object\" && globalThis[\"\u03C0\"] !== null) ? globalThis[\"\u03C0\"] : {};\nglobalThis[\"\u03C0\"] = new Proxy(__piStrings, {\n get(target, property) {\n if (typeof property === \"symbol\") return undefined;\n const name = String(property);\n if (name === \"then\" || name === \"toJSON\" || name === \"constructor\") return undefined;\n if (Object.prototype.hasOwnProperty.call(target, name)) return target[name];\n if (__piToolNames.indexOf(name) >= 0) {\n throw new Error(\n \"\u03C0.\" + name + \" is the strings accessor, not a tool. For the Pi core tool, call pi.\" + name + \"(args).\"\n );\n }\n const provided = Object.keys(target);\n throw new Error(\n \"\u03C0.\" + name + \" is not defined. \u03C0 only exposes keys from the fabric_exec strings parameter\" +\n (provided.length ? \" (provided: \" + provided.join(\", \") + \")\" : \" (none provided)\") +\n \". Pass strings: { \" + name + \": '...' } to use \u03C0.\" + name + \".\"\n );\n },\n ownKeys(target) { return Reflect.ownKeys(target); },\n getOwnPropertyDescriptor(target, prop) { return Reflect.getOwnPropertyDescriptor(target, prop); },\n has(target, prop) { return Object.prototype.hasOwnProperty.call(target, prop); }\n});\n// Stable providers share a lazy dispatch proxy; the guest declarations keep\n// their known actions typed while the registry remains the runtime authority.\n// extensions' per-tool surface is additionally rendered from the captured\n// catalog by guestTypeDeclarations (runtime/dynamic-guest-types.ts).\nconst __providerProxy = (provider) => new Proxy({}, {\n get(_target, property) {\n if (property === \"then\" || typeof property === \"symbol\") return undefined;\n return (args = {}) => __call(provider + \".\" + String(property), args);\n },\n});\nglobalThis.extensions = __providerProxy(\"extensions\");\nglobalThis.memory = __providerProxy(\"memory\");\nglobalThis.state = __providerProxy(\"state\");\nglobalThis.schema = __providerProxy(\"schema\");\nglobalThis.components = __providerProxy(\"components\");\nglobalThis.compact = __providerProxy(\"compact\");\nconst __createActor = async (args = {}) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n throw new TypeError(\"agents.create expects an options object\");\n }\n const request = { ...args };\n const validWhile = request.validWhile;\n if (validWhile !== undefined) {\n if (typeof validWhile !== \"function\") {\n throw new TypeError(\"agents.create validWhile must be a pure predicate function\");\n }\n const source = Function.prototype.toString.call(validWhile);\n if (source.trimStart().startsWith(\"async\")) {\n throw new TypeError(\"agents.create validWhile must be synchronous\");\n }\n request.validWhile = { version: 1, source };\n }\n return __call(\"agents.create\", request);\n};\nconst __handoff = async (args = {}) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n throw new TypeError(\"agents.handoff expects an options object\");\n }\n const request = { ...args };\n const when = request.when;\n delete request.when;\n if (when !== undefined) {\n if (typeof when !== \"function\") {\n throw new TypeError(\"agents.handoff when must be a pure predicate function\");\n }\n const decision = when(__handoffFacts());\n if (decision && typeof decision.then === \"function\") {\n throw new TypeError(\"agents.handoff when must return a boolean synchronously\");\n }\n if (decision !== true) {\n throw new Error(\"agents.handoff predicate returned false; no agent was started\");\n }\n }\n return __call(\"agents.handoff\", request);\n};\nglobalThis.agents = Object.freeze({\n run: (args) => __call(\"agents.run\", args),\n handoff: __handoff,\n spawn: (args) => __call(\"agents.spawn\", args),\n wait: (args) => __call(\"agents.wait\", args),\n status: (args) => __call(\"agents.status\", args),\n list: (args = {}) => __call(\"agents.list\", args),\n members: (args = {}) => __call(\"agents.members\", args),\n self: () => __call(\"agents.self\", {}),\n main: () => __call(\"agents.main\", {}),\n peers: () => __call(\"agents.peers\", {}),\n subscribe: (args) => __call(\"agents.subscribe\", args),\n subscriptions: (args = {}) => __call(\"agents.subscriptions\", args),\n unsubscribe: (args) => __call(\"agents.unsubscribe\", args),\n models: (args = {}) => __call(\"agents.models\", args),\n stop: (args) => __call(\"agents.stop\", args),\n cleanup: (args) => __call(\"agents.cleanup\", args),\n create: __createActor,\n ask: (args) => __call(\"agents.ask\", args),\n tell: (args) => __call(\"agents.tell\", args),\n steer: (args) => __call(\"agents.steer\", args),\n followUp: (args) => __call(\"agents.followUp\", args),\n setSteeringMode: (args) => __call(\"agents.setSteeringMode\", args),\n setFollowUpMode: (args) => __call(\"agents.setFollowUpMode\", args),\n actorStatus: (args) => __call(\"agents.actorStatus\", args),\n setModel: (args) => __call(\"agents.setModel\", args),\n switchModel: (args) => __call(\"agents.switchModel\", args),\n setThinking: (args) => __call(\"agents.setThinking\", args),\n setEvents: (args) => __call(\"agents.setEvents\", args),\n setInstructions: (args) => __call(\"agents.setInstructions\", args),\n actors: () => __call(\"agents.actors\", {}),\n messages: (args) => __call(\"agents.messages\", args),\n remove: (args) => __call(\"agents.remove\", args),\n log: (args) => __call(\"agents.log\", args),\n});\nglobalThis.mesh = Object.freeze({\n self: () => __call(\"mesh.self\", {}),\n publish: (args) => __call(\"mesh.publish\", args),\n read: (args = {}) => __call(\"mesh.read\", args),\n members: (args = {}) => __call(\"mesh.members\", args),\n get: (args) => __call(\"mesh.get\", args),\n list: (args = {}) => __call(\"mesh.list\", args),\n put: (args) => __call(\"mesh.put\", args),\n delete: (args) => __call(\"mesh.delete\", args),\n});\n// The mcp proxy itself stays schema-less \u2014 the registry validates args at\n// dispatch \u2014 but guestTypeDeclarations renders per-server argument types from\n// the live descriptor cache (runtime/dynamic-guest-types.ts), so known tools\n// fail type-check on argument-shape mistakes before this proxy ever runs.\nglobalThis.mcp = new Proxy({}, {\n get(_target, server) {\n if (server === \"then\") return undefined;\n if (server === \"servers\") return () => __call(\"mcp.$servers\", {});\n if (server === \"reload\") return () => __call(\"mcp.$reload\", {});\n if (server === \"register\") return (args) => __call(\"mcp.$register\", args);\n if (server === \"call\") return (args) => __call(\"mcp.$call\", args);\n return new Proxy({}, {\n get(_serverTarget, tool) {\n if (tool === \"then\") return undefined;\n return (args = {}) => __call(\"mcp.\" + String(server) + \".\" + String(tool), args);\n },\n });\n },\n});\nlet __workflowSpentTokens = 0;\nconst __workflowBudgetTotal = Number.isFinite(globalThis.__fabricTokenBudget)\n ? Math.max(0, globalThis.__fabricTokenBudget)\n : Number.POSITIVE_INFINITY;\nconst __recordAgentUsage = (result) => {\n const usage = result && result.usage;\n if (usage) __workflowSpentTokens += Number(usage.input || 0) + Number(usage.output || 0);\n return result;\n};\nconst __workflowAgent = async (prompt, options = {}) => {\n if (__workflowSpentTokens >= __workflowBudgetTotal) {\n throw new Error(\"Fabric workflow token budget exhausted\");\n }\n const { label, ...agentOptions } = options;\n const workerName = String(label || agentOptions.name || \"Fabric workflow agent\");\n const result = __recordAgentUsage(await agents.run({\n ...agentOptions,\n ...(label && !agentOptions.name ? { name: label } : {}),\n task: prompt,\n }));\n if (!result || result.status !== \"completed\") {\n const reason = result && result.error ? result.error : \"agent did not complete\";\n throw new Error(workerName + \" failed: \" + reason);\n }\n return result.value !== undefined ? result.value : result.text;\n};\n// Budget-aware agents.run used by council.run and rlm.query so their usage is\n// counted in budget.spent() and the tokenBudget guard can preempt them, just\n// like workflow.agent(). Without this, councils bypass the budget entirely.\nconst __budgetedRun = async (args) => {\n if (__workflowSpentTokens >= __workflowBudgetTotal) {\n throw new Error(\"Fabric workflow token budget exhausted\");\n }\n return __recordAgentUsage(await agents.run(args));\n};\nlet __nextWorkflowSpanId = 0;\nconst __workflowSpanMetadata = (kind, items, options, stageCount) => {\n const itemCount = Array.isArray(items) ? items.length : undefined;\n let concurrency;\n if (kind === \"parallel\" && itemCount !== undefined) {\n if (itemCount === 0) concurrency = 0;\n else {\n const concurrencyOpt = typeof options === \"number\" ? { concurrency: options } : options ?? {};\n const requested = Number(concurrencyOpt.concurrency ?? itemCount);\n if (Number.isFinite(requested) && requested >= 1) {\n concurrency = Math.max(1, Math.min(itemCount, Math.floor(requested)));\n }\n }\n }\n return {\n kind,\n ...(itemCount !== undefined ? { itemCount } : {}),\n ...(stageCount !== undefined ? { stageCount } : {}),\n ...(concurrency !== undefined ? { concurrency } : {}),\n };\n};\nconst __withWorkflowSpan = async (metadata, body) => {\n const id = \"span-\" + __nextWorkflowSpanId++;\n await __call(\"fabric.$spanStart\", { id, ...metadata });\n try {\n const value = await body();\n await __call(\"fabric.$spanEnd\", { id, outcome: \"succeeded\" });\n return value;\n } catch (error) {\n try { await __call(\"fabric.$spanEnd\", { id, outcome: \"failed\" }); } catch { /* preserve the workflow error */ }\n throw error;\n }\n};\nconst __runParallel = async (thunks, options) => {\n if (!Array.isArray(thunks) || thunks.some((thunk) => typeof thunk !== \"function\")) {\n throw new TypeError(\"workflow.parallel expects an array of functions or (items, mapper)\");\n }\n if (thunks.length === 0) return [];\n const concurrencyOpt = typeof options === \"number\" ? { concurrency: options } : options ?? {};\n const requestedConcurrency = Number(concurrencyOpt.concurrency ?? thunks.length);\n if (!Number.isFinite(requestedConcurrency) || requestedConcurrency < 1) {\n throw new RangeError(\"workflow.parallel concurrency must be a positive finite number\");\n }\n const concurrency = Math.max(1, Math.min(thunks.length || 1, Math.floor(requestedConcurrency)));\n const results = new Array(thunks.length);\n let cursor = 0;\n await Promise.all(Array.from({ length: concurrency }, async () => {\n while (cursor < thunks.length) {\n const index = cursor++;\n results[index] = await thunks[index]();\n }\n }));\n return results;\n};\nconst __workflowParallel = async (items, arg2, arg3) => {\n const options = typeof arg2 === \"function\" ? arg3 : arg2;\n return __withWorkflowSpan(\n __workflowSpanMetadata(\"parallel\", items, options),\n async () => {\n if (typeof arg2 === \"function\") {\n if (!Array.isArray(items)) throw new TypeError(\"workflow.parallel expects an array as the first argument\");\n return __runParallel(items.map((item, index) => () => arg2(item, index)), arg3);\n }\n return __runParallel(items, arg2);\n },\n );\n};\nconst __workflowPipeline = async (items, ...stages) =>\n __withWorkflowSpan(\n __workflowSpanMetadata(\"pipeline\", items, undefined, stages.length),\n async () => {\n if (!Array.isArray(items) || stages.some((stage) => typeof stage !== \"function\")) {\n throw new TypeError(\"workflow.pipeline expects an array followed by stage functions\");\n }\n return __workflowParallel(items.map((original, index) => async () => {\n let value = original;\n for (const stage of stages) value = await stage(value, original, index);\n return value;\n }));\n },\n );\nglobalThis.workflow = Object.freeze({\n agent: __workflowAgent,\n parallel: __workflowParallel,\n pipeline: __workflowPipeline,\n configure: (args) => __call(\"fabric.$configure\", args),\n phase: (nameOrInput, options = {}) => {\n const input =\n nameOrInput && typeof nameOrInput === \"object\" && !Array.isArray(nameOrInput)\n ? { ...nameOrInput }\n : { ...options, name: nameOrInput };\n return __call(\"fabric.$phase\", input);\n },\n item: (args) => __call(\"fabric.$item\", args),\n event: (args) => __call(\"fabric.$event\", args),\n log: (...values) => print(...values),\n budget: Object.freeze({\n total: __workflowBudgetTotal,\n spent: () => __workflowSpentTokens,\n remaining: () => Math.max(0, __workflowBudgetTotal - __workflowSpentTokens),\n }),\n});\nglobalThis.agent = __workflowAgent;\nglobalThis.parallel = __workflowParallel;\nglobalThis.pipeline = __workflowPipeline;\nglobalThis.phase = workflow.phase;\nglobalThis.log = workflow.log;\nglobalThis.budget = workflow.budget;\nglobalThis.rlm = Object.freeze({\n query: (args) => {\n if (args && args.runner && args.runner !== \"pi\") {\n throw new Error(\"rlm.query requires the Pi runner because recursive Fabric is unavailable in Claude Code\");\n }\n return __budgetedRun({ ...args, runner: \"pi\", recursive: true });\n },\n});\nglobalThis.council = Object.freeze({\n async run(args) {\n const { task, roles, synthesize = true, ...agentOptions } = args;\n const results = await Promise.all(roles.map((role) => __budgetedRun({\n ...agentOptions,\n name: role,\n task: \"Act as the \" + role + \" council member. Independently analyze this task:\\n\\n\" + task,\n })));\n if (!synthesize) return results;\n return __budgetedRun({\n ...agentOptions,\n name: \"council-synthesizer\",\n task: \"Synthesize the council's independent reports into one decision. Preserve disagreements and cite which role raised each concern.\\n\\nTask:\\n\" + task + \"\\n\\nReports:\\n\" + JSON.stringify(results),\n });\n },\n});\nglobalThis.console = Object.freeze({ log: print, info: print, warn: print, error: print });\nconst __timerCallbacks = new Map();\nlet __nextTimerId = 1;\nglobalThis.setTimeout = (callback, ms = 0) => {\n const id = __nextTimerId++;\n __timerCallbacks.set(id, { callback, interval: false });\n __call(\"fabric.$timer\", { ms }).then(() => {\n const entry = __timerCallbacks.get(id);\n if (!entry) return;\n __timerCallbacks.delete(id);\n try { entry.callback(); } catch { /* swallow timer callback errors */ }\n });\n return id;\n};\nglobalThis.setInterval = (callback, ms = 0) => {\n const id = __nextTimerId++;\n __timerCallbacks.set(id, { callback, interval: true });\n const schedule = () => {\n __call(\"fabric.$timer\", { ms }).then(() => {\n const entry = __timerCallbacks.get(id);\n if (!entry) return;\n try { entry.callback(); } catch { /* swallow timer callback errors */ }\n if (__timerCallbacks.has(id)) schedule();\n });\n };\n schedule();\n return id;\n};\nglobalThis.clearTimeout = (id) => { __timerCallbacks.delete(id); };\nglobalThis.clearInterval = (id) => { __timerCallbacks.delete(id); };\n})();\n"; export declare class QuickJsRuntime { execute(code: string, hostCall: FabricHostCall, options: FabricSandboxOptions): Promise; } //# sourceMappingURL=quickjs-runtime.d.ts.map