pi-fabric 0.135.1 → 0.135.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents.js +1 -1
- package/dist/chunks/{chunk-FMEOJJ6Y.js → chunk-4XKQVJJK.js} +5 -4
- package/dist/chunks/chunk-4XKQVJJK.js.map +7 -0
- package/dist/chunks/{chunk-T7T5W3OP.js → chunk-6XEFPCVA.js} +88 -2
- package/dist/chunks/{chunk-T7T5W3OP.js.map → chunk-6XEFPCVA.js.map} +3 -3
- package/dist/chunks/{chunk-YO5UIWDY.js → chunk-AVZOQWTX.js} +6 -5
- package/dist/chunks/chunk-AVZOQWTX.js.map +7 -0
- package/dist/chunks/{chunk-WPDITWQU.js → chunk-FJ7KCI4I.js} +2 -2
- package/dist/chunks/{chunk-DN4JTM4I.js → chunk-J7ENLC46.js} +1 -1
- package/dist/chunks/{chunk-Q5ICW2VE.js → chunk-OS74LCBU.js} +1 -1
- package/dist/chunks/{chunk-XOBLUZMB.js → chunk-UIVMSMSQ.js} +10 -1
- package/dist/chunks/chunk-UIVMSMSQ.js.map +7 -0
- package/dist/chunks/{chunk-MBNTQOBU.js → chunk-VWVA6CYI.js} +2 -2
- package/dist/chunks/chunk-VWVA6CYI.js.map +7 -0
- package/dist/core/control-abort.d.ts +3 -0
- package/dist/core/control-abort.d.ts.map +1 -0
- package/dist/core/crash-guard.d.ts +15 -0
- package/dist/core/crash-guard.d.ts.map +1 -0
- package/dist/core/shell-jobs.d.ts +11 -0
- package/dist/core/shell-jobs.d.ts.map +1 -1
- package/dist/durable-extension.js +1 -1
- package/dist/durable-extension.js.map +1 -1
- package/dist/extension-bootstrap.d.ts.map +1 -1
- package/dist/extension-bootstrap.js +1 -1
- package/dist/extension.d.ts.map +1 -1
- package/dist/fabric-runtime-state.js +113 -36
- package/dist/fabric-runtime-state.js.map +4 -4
- package/dist/index.js +1 -1
- package/dist/jev.js +1 -1
- package/dist/providers/jev-provider.js +1 -1
- package/dist/providers/pi-read-operations.d.ts +24 -0
- package/dist/providers/pi-read-operations.d.ts.map +1 -0
- package/dist/providers/pi-tools-provider.d.ts.map +1 -1
- package/dist/residency/host.js +2 -2
- package/dist/residency/pi-entry.js +2 -2
- package/dist/runtime/cpython-runtime.d.ts.map +1 -1
- package/dist/runtime/cpython-runtime.js +6 -5
- package/dist/runtime/cpython-runtime.js.map +2 -2
- package/dist/runtime/monty-runtime.d.ts.map +1 -1
- package/dist/runtime/monty-runtime.js +4 -3
- package/dist/runtime/monty-runtime.js.map +2 -2
- package/dist/runtime/node-process-runtime.d.ts.map +1 -1
- package/dist/runtime/node-process-runtime.js +3 -3
- package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
- package/dist/runtime/quickjs-runtime.js +2 -2
- package/dist/runtime/typescript-kernel.js +3 -3
- package/dist/speculation/store.d.ts.map +1 -1
- package/dist/ui/shell-tasks.js +1 -1
- package/dist/ui/shell-tasks.js.map +2 -2
- package/docs/background-tasks.md +7 -4
- package/package.json +1 -1
- package/skillsets/typescript/fabric-exec/SKILL.md +1 -1
- package/dist/chunks/chunk-FMEOJJ6Y.js.map +0 -7
- package/dist/chunks/chunk-MBNTQOBU.js.map +0 -7
- package/dist/chunks/chunk-XOBLUZMB.js.map +0 -7
- package/dist/chunks/chunk-YO5UIWDY.js.map +0 -7
- /package/dist/chunks/{chunk-WPDITWQU.js.map → chunk-FJ7KCI4I.js.map} +0 -0
- /package/dist/chunks/{chunk-DN4JTM4I.js.map → chunk-J7ENLC46.js.map} +0 -0
- /package/dist/chunks/{chunk-Q5ICW2VE.js.map → chunk-OS74LCBU.js.map} +0 -0
package/dist/agents.js
CHANGED
|
@@ -8,8 +8,9 @@ import {
|
|
|
8
8
|
PI_ARGUMENT_NORMALIZATION_SOURCE
|
|
9
9
|
} from "./chunk-6KO2LEOO.js";
|
|
10
10
|
import {
|
|
11
|
+
fabricControlAbort,
|
|
11
12
|
piBashExitMetadata
|
|
12
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-UIVMSMSQ.js";
|
|
13
14
|
import {
|
|
14
15
|
providerGlobalNames
|
|
15
16
|
} from "./chunk-35EEGOH3.js";
|
|
@@ -1123,7 +1124,7 @@ var QuickJsRuntime = class {
|
|
|
1123
1124
|
const hostAbortController = new AbortController();
|
|
1124
1125
|
const abortHostCalls = (reason) => {
|
|
1125
1126
|
if (!hostAbortController.signal.aborted) {
|
|
1126
|
-
hostAbortController.abort(
|
|
1127
|
+
hostAbortController.abort(fabricControlAbort(reason));
|
|
1127
1128
|
}
|
|
1128
1129
|
};
|
|
1129
1130
|
const rejectExecutionGate = (message) => {
|
|
@@ -1563,7 +1564,7 @@ Promise.race([globalThis.__fabricRun(__piFabricMain), globalThis.__fabricExecuti
|
|
|
1563
1564
|
closing = true;
|
|
1564
1565
|
if (timedOut || cancelled || pendingHostPromises.size > 0) {
|
|
1565
1566
|
const cleanupMessage = cancelled ? "Execution cancelled" : timedOut ? timeoutMessage() : "Fabric guest execution ended before its host calls settled";
|
|
1566
|
-
if (!hostAbortController.signal.aborted) hostAbortController.abort(
|
|
1567
|
+
if (!hostAbortController.signal.aborted) hostAbortController.abort(fabricControlAbort(cleanupMessage));
|
|
1567
1568
|
rejectExecutionGate(cleanupMessage);
|
|
1568
1569
|
const errorHandle = context.newError(cleanupMessage);
|
|
1569
1570
|
for (const promise of pendingHostPromises) promise.reject(errorHandle);
|
|
@@ -1605,4 +1606,4 @@ export {
|
|
|
1605
1606
|
GUEST_SETUP,
|
|
1606
1607
|
QuickJsRuntime
|
|
1607
1608
|
};
|
|
1608
|
-
//# sourceMappingURL=chunk-
|
|
1609
|
+
//# sourceMappingURL=chunk-4XKQVJJK.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/runtime/quickjs-runtime.ts", "../../src/runtime/guest-stack-map.ts", "../../src/runtime/native-codemode-guest.ts"],
|
|
4
|
+
"sourcesContent": ["import releaseSyncVariant from \"@jitl/quickjs-singlefile-mjs-release-sync\";\nimport { newQuickJSWASMModuleFromVariant, newVariant } from \"quickjs-emscripten-core\";\nimport ts from \"typescript\";\nimport { runAbortable, settleWithin } from \"../async-settlement.js\";\nimport { fabricControlAbort } from \"../core/control-abort.js\";\nimport { piBashExitMetadata } from \"../core/pi-bash-error.js\";\nimport { PI_ARGUMENT_NORMALIZATION_SOURCE } from \"../core/pi-arguments.js\";\nimport { PI_CORE_TOOL_NAMES } from \"../core/pi-tools.js\";\nimport { providerGlobalNames } from \"../provider-globals.js\";\nimport { HumanWaitDeadlinePause } from \"./deadline-pause.js\";\nimport { createGuestStackMap, remapGuestErrorText } from \"./guest-stack-map.js\";\nimport { transpileFabricCodeWithSourceMap } from \"./transpile.js\";\n\nimport type {\n FabricHostCall,\n FabricJournalDriver,\n FabricJournalOutcome,\n FabricSandboxOptions,\n FabricSandboxResult,\n FabricSandboxTerminationReason,\n} from \"./kernel.js\";\n// Preserve existing import paths for runtime consumers.\nexport type {\n FabricHostCall,\n FabricSandboxOptions,\n FabricSandboxResult,\n FabricSandboxTerminationReason,\n} from \"./kernel.js\";\n\ntype QuickJsModule = Awaited<ReturnType<typeof newQuickJSWASMModuleFromVariant>>;\n\nlet quickJsModulePromise: Promise<QuickJsModule> | undefined;\n\n// Static \u03C0.<identifier> references (bracket access like \u03C0[k] is not provable).\n// Parse instead of scanning text so examples inside strings and comments do not\n// become false missing-payload failures.\nconst referencedPiKeys = (code: string): string[] => {\n const source = ts.createSourceFile(\n \"fabric-exec.ts\",\n `async function __fabricProgram() {\\n${code}\\n}`,\n ts.ScriptTarget.Latest,\n false,\n ts.ScriptKind.TS,\n );\n const keys: string[] = [];\n const visit = (node: ts.Node): void => {\n if (\n ts.isPropertyAccessExpression(node) &&\n ts.isIdentifier(node.expression) &&\n node.expression.text === \"\u03C0\" &&\n !keys.includes(node.name.text)\n ) {\n keys.push(node.name.text);\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return keys;\n};\n\n// Models routinely reference \u03C0.<key> without providing the payloads parameter,\n// and the runtime error only lands after a full execution round trip (#68).\n// Reject up front when a referenced key is statically provable missing, before\n// QuickJS is even loaded.\nconst missingStringsKeys = (\n code: string,\n strings: Record<string, string> | undefined,\n): string[] => {\n const provided = strings ?? {};\n return referencedPiKeys(code).filter((key) => !(key in provided));\n};\n\nconst precompiledModules = new WeakMap<WebAssembly.Module, Promise<QuickJsModule>>();\n// The bundled variant compiles its inlined wasm bytes; hosts that forbid that\n// (Cloudflare Workers) pass a precompiled WebAssembly.Module of the same build.\nconst quickJsModule = (wasmModule?: WebAssembly.Module): Promise<QuickJsModule> => {\n if (wasmModule === undefined) {\n quickJsModulePromise ??= newQuickJSWASMModuleFromVariant(releaseSyncVariant);\n return quickJsModulePromise;\n }\n let loaded = precompiledModules.get(wasmModule);\n if (loaded === undefined) {\n loaded = newQuickJSWASMModuleFromVariant(newVariant(releaseSyncVariant, { wasmModule }));\n precompiledModules.set(wasmModule, loaded);\n }\n return loaded;\n};\n\n/** One macrotask turn; setImmediate is Node/Bun only, Workers have setTimeout. */\nconst nextMacrotask = (): Promise<void> => new Promise((resolve) => {\n if (typeof setImmediate === \"function\") setImmediate(() => resolve());\n else setTimeout(resolve, 0);\n});\n\nexport interface QuickJsRuntimeOptions {\n /** A precompiled QuickJS wasm module (the `@jitl/quickjs-singlefile-mjs-release-sync` build), for hosts that cannot compile wasm from bytes. */\n readonly wasmModule?: WebAssembly.Module;\n}\n\nexport const guestSetupSource = (fields?: Record<string, string[]>, nativeStoreEnabled = false, profile = \"additive\", nativeToolsEnabled = false, providerGlobals: readonly string[] = []): string =>\n `const __piCanonicalFields = ${JSON.stringify(fields ?? {})}; const __nativeStoreEnabled = ${nativeStoreEnabled}; const __nativeProfile = ${profile === \"native\"}; const __nativeToolsEnabled = ${nativeToolsEnabled}; const __providerGlobals = ${JSON.stringify(providerGlobalNames(providerGlobals))};\\n${GUEST_SETUP}`;\n\nimport { NATIVE_CODEMODE_GUEST } from \"./native-codemode-guest.js\";\n\nexport 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 __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${NATIVE_CODEMODE_GUEST}\nconst __nativeToolNames = new Set();\nlet __nativeCatalogReady = false;\nglobalThis.nativeTools = new Proxy(Object.create(null), {\n get(_target, property) {\n if (typeof property === \"symbol\" || (__nativeCatalogReady ? !__nativeToolNames.has(property) : property === \"then\")) return undefined;\n return args => __call(\"fabric.$nativeTool\", { name: String(property), args: args === undefined ? {} : args });\n },\n ownKeys() { return [...__nativeToolNames]; },\n getOwnPropertyDescriptor(_target, property) { return __nativeToolNames.has(property) ? {enumerable:true, configurable:true} : undefined; },\n set() { return true; },\n deleteProperty() { return true; },\n});\nconst __fabricTools = new Proxy(__toolsBase, {\n get(target, property) {\n if (property === \"then\" || typeof property === \"symbol\") return undefined;\n return Object.prototype.hasOwnProperty.call(target, property) ? target[property] : globalThis.nativeTools[property];\n },\n set() { return true; },\n deleteProperty() { return true; },\n});\nglobalThis.fabric = Object.freeze({ tools: __fabricTools });\nglobalThis.tools = typeof __nativeProfile !== \"undefined\" && __nativeProfile ? globalThis.nativeTools : __fabricTools;\nconst __piStringFields = { bash: \"command\", powershell: \"command\", read: \"path\", ls: \"path\", grep: \"pattern\", find: \"pattern\" };\n// Object aliases and coercions are shared with host preparation in core/pi-arguments.ts.\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\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 = { ...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};\n${PI_ARGUMENT_NORMALIZATION_SOURCE}\n// shell/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, powershell: 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 \"(...). Shell commands reject 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 // Shell tools reject on an ordinary nonzero exit; settle:true returns\n // {ok:false, exitCode, ...} instead (opt-in). Other failures still reject.\n const settle = (name === \"bash\" || name === \"powershell\") &&\n typeof args === \"object\" && args !== null && args.settle === true;\n const call = __call(\"pi.\" + name, __normalizePiArgs(name, args, typeof __piCanonicalFields === \"undefined\" ? undefined : __piCanonicalFields[name]));\n const promise = settle ? call.catch((error) => {\n // node-process bridge errors originate in a different VM realm.\n const message = typeof error?.message === \"string\" ? error.message : String(error);\n const exit = error?.__fabricBashExit;\n if (!exit || !Number.isSafeInteger(exit.exitCode) || exit.exitCode <= 0 ||\n typeof exit.output !== \"string\") throw error;\n return {\n ok: false,\n output: exit.output,\n details: null,\n exitCode: exit.exitCode,\n error: message,\n };\n }) : call;\n return __piEnvelopeTools[name] === true\n ? promise.then((value) => __piEnvelopeGuard(name, value))\n : promise;\n };\n },\n});\nconst __piToolNames = ${JSON.stringify(PI_CORE_TOOL_NAMES)};\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 payloads parameter\" +\n (provided.length ? \" (provided: \" + provided.join(\", \") + \")\" : \" (none provided)\") +\n \". Pass payloads: { \" + name + \": '...' } to use \u03C0.\" + name + \".\" +\n \" For large or quote-heavy content, keep it in top-level payloads and reference \u03C0.\" + name + \" instead of escaping it inside code.\"\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 __memorySelectionKeys = [\n \"indices\",\n \"entryIds\",\n \"operationAddresses\",\n \"entryRange\",\n \"index\",\n \"entry_ids\",\n \"operation_addresses\",\n \"entry_range\",\n];\nconst __hasMemorySelection = (args) => __memorySelectionKeys.some((key) => {\n const value = args[key];\n if (Array.isArray(value)) return value.length > 0;\n return value !== undefined && value !== null;\n});\nconst __memoryWalk = async (args, visitor) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n throw new TypeError(\"memory.walk expects an expansion options object\");\n }\n if (typeof visitor !== \"function\") {\n throw new TypeError(\"memory.walk expects a visitor function as its second argument\");\n }\n\n let request = { ...args };\n if (Number(request.textOffset ?? request.text_offset ?? 0) !== 0) {\n throw new TypeError(\"memory.walk must start at text offset 0 to yield complete entries\");\n }\n if (!__hasMemorySelection(request)) {\n if (request.entryOffset !== undefined || request.entry_offset !== undefined ||\n request.textOffset !== undefined || request.text_offset !== undefined) {\n throw new TypeError(\"memory.walk continuation offsets require an explicit selection\");\n }\n if (Number(request.before ?? 0) > 0 || Number(request.after ?? 0) > 0) {\n throw new TypeError(\"memory.walk before/after requires an explicit selection\");\n }\n const head = await __call(\"memory.expand\", request);\n if (!head || typeof head !== \"object\") {\n throw new Error(\"memory.expand returned an invalid metadata response\");\n }\n if (head.error) return { visited: 0, stopped: false, error: head.error };\n if (!Number.isSafeInteger(head.entryCount) || head.entryCount < 0) {\n throw new Error(\"memory.expand metadata omitted a valid entryCount\");\n }\n if (head.entryCount === 0) return { visited: 0, stopped: false };\n request = {\n ...request,\n session: head.session ?? request.session,\n expectedSourceHash: head.sourceHash,\n expectedLineageFingerprint: head.lineageFingerprint,\n branches: head.branches,\n entryRange: { first: 0, last: head.entryCount - 1 },\n };\n }\n\n let visited = 0;\n let pending = null;\n let pendingStart = 0;\n let pendingEnd = 0;\n let pendingTotal = 0;\n const seen = new Set([JSON.stringify({ ref: \"memory.expand\", args: request })]);\n let page = await __call(\"memory.expand\", request);\n\n while (true) {\n if (!page || typeof page !== \"object\") {\n throw new Error(\"memory.expand returned an invalid page\");\n }\n if (page.error) return { visited, stopped: false, error: page.error };\n if (!Array.isArray(page.entries)) {\n throw new Error(\"memory.expand page omitted entries\");\n }\n\n for (const chunk of page.entries) {\n if (!chunk || typeof chunk !== \"object\" || typeof chunk.text !== \"string\") {\n throw new Error(\"memory.expand returned an invalid entry chunk\");\n }\n const range = chunk.textRange;\n if (!range || typeof range !== \"object\" ||\n !Number.isSafeInteger(range.start) || !Number.isSafeInteger(range.end) ||\n !Number.isSafeInteger(range.total) || range.start < 0 ||\n range.end < range.start || range.total < range.end) {\n throw new Error(\"memory.expand returned an invalid textRange\");\n }\n if (chunk.text.length !== range.end - range.start) {\n throw new Error(\"memory.expand entry chunk disagrees with textRange\");\n }\n\n if (pending === null) {\n pending = { ...chunk, text: \"\" };\n pendingStart = range.start;\n pendingEnd = range.start;\n pendingTotal = range.total;\n } else if (pending.index !== chunk.index) {\n throw new Error(\"memory.expand advanced before completing an entry\");\n }\n if (range.start !== pendingEnd || range.total !== pendingTotal) {\n throw new Error(\"memory.expand returned discontinuous entry chunks\");\n }\n for (const key of Object.keys(chunk)) {\n if (pending[key] === undefined) pending[key] = chunk[key];\n }\n pending.text += chunk.text;\n pendingEnd = range.end;\n\n if (range.complete) {\n pending.textRange = {\n start: pendingStart,\n end: pendingEnd,\n total: pendingTotal,\n complete: true,\n };\n const entry = pending;\n pending = null;\n const keepGoing = await visitor(entry, visited);\n visited += 1;\n if (keepGoing === false) return { visited, stopped: true };\n }\n }\n\n if (page.next === null || page.next === undefined) {\n if (pending !== null) {\n throw new Error(\"memory.expand ended before completing an entry\");\n }\n return { visited, stopped: false };\n }\n if (page.next.ref !== \"memory.expand\" || !page.next.args ||\n typeof page.next.args !== \"object\" || Array.isArray(page.next.args)) {\n throw new Error(\"memory.expand returned an invalid continuation\");\n }\n const continuationKey = JSON.stringify(page.next);\n if (seen.has(continuationKey)) {\n throw new Error(\"memory.expand returned a cyclic continuation\");\n }\n seen.add(continuationKey);\n page = await __call(page.next.ref, page.next.args);\n }\n};\n\nconst __providerProxy = (provider, local = {}) => new Proxy(local, {\n get(target, property) {\n if (property === \"then\" || typeof property === \"symbol\") return undefined;\n if (Object.prototype.hasOwnProperty.call(target, property)) return target[property];\n return (args = {}) => __call(provider + \".\" + String(property), args);\n },\n});\nglobalThis.extensions = __providerProxy(\"extensions\");\nglobalThis.memory = __providerProxy(\"memory\", { walk: __memoryWalk });\nglobalThis.state = __providerProxy(\"state\");\nglobalThis.schema = __providerProxy(\"schema\");\nglobalThis.components = __providerProxy(\"components\");\nglobalThis.compact = __providerProxy(\"compact\");\nglobalThis.cache = __providerProxy(\"cache\");\nglobalThis.thinking = __providerProxy(\"thinking\");\nglobalThis.decisions = __providerProxy(\"decisions\");\nglobalThis.programs = __providerProxy(\"programs\");\nglobalThis.prewalk = __providerProxy(\"prewalk\");\nglobalThis.jev = __providerProxy(\"jev\");\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 observe: (args) => __call(\"agents.observe\", args),\n wait: (args) => __call(\"agents.wait\", args),\n join: (args) => __call(\"agents.join\", 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 sessions: () => __call(\"agents.sessions\", {}),\n peers: () => __call(\"agents.peers\", {}),\n departed: (args = {}) => __call(\"agents.departed\", args),\n definitions: () => __call(\"agents.definitions\", {}),\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 sleep: (args) => __call(\"agents.sleep\", args),\n wake: (args) => __call(\"agents.wake\", 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 compact: (args) => __call(\"agents.compact\", 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 setTools: (args) => __call(\"agents.setTools\", args),\n setEvents: (args) => __call(\"agents.setEvents\", args),\n setDeliveryPolicy: (args) => __call(\"agents.setDeliveryPolicy\", args),\n clearMessages: (args) => __call(\"agents.clearMessages\", args),\n setInstructions: (args) => __call(\"agents.setInstructions\", args),\n actors: (args = {}) => __call(\"agents.actors\", args),\n messages: (args) => __call(\"agents.messages\", args),\n remove: (args) => __call(\"agents.remove\", args),\n // Keyword keys for the actor-template routes, spelled as the provider,\n // audit projection, and docs already spell them.\n \"import\": (args) => __call(\"agents.import\", args),\n \"export\": (args) => __call(\"agents.export\", 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 scheduled: (args = {}) => __call(\"mesh.scheduled\", args),\n unschedule: (args) => __call(\"mesh.unschedule\", args),\n grant: (args) => __call(\"mesh.grant\", args),\n revoke: (args) => __call(\"mesh.revoke\", args),\n grants: () => __call(\"mesh.grants\", {}),\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\" && args.runner !== \"pi-durable\") {\n throw new Error(\"rlm.query requires a Pi runner (pi-durable or pi) for recursive Fabric\");\n }\n return __budgetedRun({ ...args, runner: args?.runner ?? \"pi-durable\", 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, debug: 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// Providers other extensions register, as globals named after them. The host\n// lists only names src/provider-globals.ts accepts; installing last, and only\n// where no global exists, keeps every Fabric and language global intact.\n// Each call is tools.call, so it takes the same host path, policy and limits.\nconst __providerGlobal = (provider) => new Proxy(Object.create(null), {\n get(_target, property) {\n if (typeof property === \"symbol\" || property === \"then\" || property === \"toJSON\") return undefined;\n const ref = provider + \".\" + property;\n return (args = {}) => {\n if (args === null || typeof args !== \"object\" || Array.isArray(args)) {\n return Promise.reject(new TypeError(ref + \" takes one argument object\"));\n }\n return __call(\"fabric.$call\", { ref, args });\n };\n },\n set() { return false; },\n defineProperty() { return false; },\n deleteProperty() { return false; },\n});\nfor (const __name of (typeof __providerGlobals === \"undefined\" ? [] : __providerGlobals)) {\n if (typeof __name !== \"string\" || !/^[a-z][a-z0-9_]{0,63}$/.test(__name) || __name in globalThis) continue;\n globalThis[__name] = __providerGlobal(__name);\n}\n})();\n`;\n\nconst formatValue = (value: unknown): string => {\n if (typeof value === \"string\") return value;\n if (value instanceof Error) return value.stack ?? value.message;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n};\n\nconst jsonText = (value: unknown): string => {\n const serialized = JSON.stringify(value);\n if (serialized === undefined) return \"null\";\n return serialized;\n};\n\nconst jsonHandle = (\n context: any,\n jsonObject: any,\n jsonParse: any,\n value: unknown,\n): any => {\n if (value === undefined) return context.undefined;\n if (value === null) return context.null;\n if (typeof value === \"string\") return context.newString(value);\n if (typeof value === \"boolean\") return value ? context.true : context.false;\n if (typeof value === \"number\") {\n return Number.isFinite(value) ? context.newNumber(value) : context.null;\n }\n const serialized = context.newString(jsonText(value));\n try {\n return context.unwrapResult(context.callFunction(jsonParse, jsonObject, serialized));\n } finally {\n serialized.dispose();\n }\n};\n\nconst HOST_TASK_SETTLE_GRACE_MS = 250;\n\n// The release-sync WASM variant otherwise exhausts the host stack before\n// QuickJS can throw its guest-catchable InternalError.\nconst QUICKJS_MAX_STACK_SIZE_BYTES = 256 * 1024;\nconst QUICKJS_GC_LIST_ASSERTION = \"list_empty(&rt->gc_obj_list)\";\n\n// Preserve an already-computed result for this known Emscripten teardown\n// assertion while allowing every unrelated disposal failure to escape.\nconst disposeQuickJsContext = (context: any): void => {\n try {\n context.dispose();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes(QUICKJS_GC_LIST_ASSERTION) && message.includes(\"JS_FreeRuntime\")) return;\n throw error;\n }\n};\n\nexport class QuickJsRuntime {\n readonly #wasmModule: WebAssembly.Module | undefined;\n constructor(options: QuickJsRuntimeOptions = {}) {\n this.#wasmModule = options.wasmModule;\n }\n\n async execute(\n code: string,\n hostCall: FabricHostCall,\n options: FabricSandboxOptions,\n ): Promise<FabricSandboxResult> {\n if (options.signal?.aborted) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"aborted\",\n error: \"Execution cancelled\",\n };\n }\n const missingKeys = missingStringsKeys(code, options.strings);\n if (missingKeys.length > 0) {\n const provided = Object.keys(options.strings ?? {});\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error:\n \"Pre-execution check: \" + missingKeys.map((key) => \"\u03C0.\" + key).join(\", \")\n + (missingKeys.length === 1 ? \" is referenced in code but its key is missing from the payloads parameter\"\n : \" are referenced in code but their keys are missing from the payloads parameter\")\n + (provided.length ? \" (provided: \" + provided.join(\", \") + \")\" : \" (none provided)\")\n + \". Add payloads: { \" + missingKeys.join(\": '...', \") + \": '...' } to the fabric_exec arguments, then reference the value as \u03C0.<key>.\"\n + \" For large or quote-heavy content, keep it in top-level payloads and reference \u03C0.<key> instead of escaping it inside code.\",\n };\n }\n if (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 1) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error: \"QuickJS timeout must be positive\",\n };\n }\n if (options.maxLogChars !== undefined && (!Number.isSafeInteger(options.maxLogChars) || options.maxLogChars < 0)) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error: \"QuickJS log limit must be a nonnegative safe integer\",\n };\n }\n if (\n !Number.isSafeInteger(options.memoryLimitBytes) ||\n options.memoryLimitBytes < 1 ||\n options.memoryLimitBytes > 0xffff_ffff\n ) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error: \"QuickJS memory limit must be an integer between 1 byte and 4294967295 bytes (WASM32 maximum)\",\n };\n }\n const module = await quickJsModule(this.#wasmModule);\n const context = module.newContext();\n const runtime = context.runtime;\n const jsonObject = context.getProp(context.global, \"JSON\");\n const jsonParse = context.getProp(jsonObject, \"parse\");\n const executionStartedAt = Date.now();\n let effectiveTimeoutMs = options.timeoutMs;\n let executionDeadlineAt = executionStartedAt + effectiveTimeoutMs;\n let interruptedByDeadline = false;\n let interruptedByCpu = false;\n let cpuDeadlineAt = Infinity;\n const pumpJobs = () => {\n cpuDeadlineAt = Date.now() + (options.maxCpuSliceMs ?? Infinity);\n return runtime.executePendingJobs();\n };\n runtime.setMemoryLimit(options.memoryLimitBytes);\n runtime.setMaxStackSize(QUICKJS_MAX_STACK_SIZE_BYTES);\n runtime.setInterruptHandler(() => {\n if (options.signal?.aborted === true) return true;\n if (interruptedByCpu || Date.now() > cpuDeadlineAt) {\n interruptedByCpu = true;\n return true;\n }\n if (Date.now() <= executionDeadlineAt) return false;\n interruptedByDeadline = true;\n return true;\n });\n const emittedSnapshot = (): unknown[] => {\n try {\n const handle = context.getProp(context.global, \"__fabricEmitted\");\n try { const value = context.dump(handle); return Array.isArray(value) ? value : []; }\n finally { handle.dispose(); }\n } catch { return []; }\n };\n const logs: string[] = [];\n const maxLogChars = options.maxLogChars ?? 100_000;\n let logChars = 0;\n let logsTruncated = false;\n const pendingHostPromises = new Set<any>();\n const hostTasks = new Set<Promise<void>>();\n const pendingTimers = new Set<NodeJS.Timeout>();\n let closing = false;\n let cancelled = false;\n let timedOut = false;\n let timeout: NodeJS.Timeout | undefined;\n let rejectDeadline: ((error: Error) => void) | undefined;\n let abortHandler: (() => void) | undefined;\n let activePromiseHandle: any;\n let executionGate: any;\n let pendingResolution: Promise<any> | undefined;\n const hostAbortController = new AbortController();\n const abortHostCalls = (reason: string): void => {\n if (!hostAbortController.signal.aborted) {\n hostAbortController.abort(fabricControlAbort(reason));\n }\n };\n\n const rejectExecutionGate = (message: string): void => {\n if (!executionGate || executionGate.alive === false) return;\n const errorHandle = context.newError(message);\n executionGate.reject(errorHandle);\n errorHandle.dispose();\n pumpJobs();\n };\n\n const timeoutMessage = (): string =>\n interruptedByCpu\n ? `Guest exceeded ${options.maxCpuSliceMs}ms uninterrupted CPU; await host work or program.sleep() in loops`\n : `Execution timed out after ${effectiveTimeoutMs}ms`;\n const expireDeadline = (): void => {\n if (closing || cancelled || timedOut) return;\n timedOut = true;\n const message = timeoutMessage();\n abortHostCalls(message);\n rejectExecutionGate(message);\n rejectDeadline?.(new Error(message));\n };\n const scheduleDeadline = (): void => {\n if (!rejectDeadline || closing || cancelled || timedOut) return;\n clearTimeout(timeout);\n options.onDeadline?.(Number.isFinite(executionDeadlineAt) ? executionDeadlineAt : undefined);\n if (!Number.isFinite(executionDeadlineAt)) return;\n timeout = setTimeout(expireDeadline, Math.min(2_147_483_647, Math.max(0, executionDeadlineAt - Date.now())));\n };\n const extendExecutionTimeout = (\n ref: string,\n args: Record<string, unknown>,\n ): void => {\n const requestedTimeoutMs = options.minimumTimeoutMsForHostCall?.(ref, args);\n if (\n typeof requestedTimeoutMs !== \"number\" ||\n !Number.isFinite(requestedTimeoutMs)\n ) {\n return;\n }\n const requestedDurationMs = Math.max(1, Math.floor(requestedTimeoutMs));\n if (humanWait.paused) {\n humanWait.raise(requestedDurationMs);\n return;\n }\n const nextDeadlineAt = Date.now() + requestedDurationMs;\n const nextTimeoutMs = nextDeadlineAt - executionStartedAt;\n if (nextDeadlineAt <= executionDeadlineAt) return;\n effectiveTimeoutMs = nextTimeoutMs;\n executionDeadlineAt = nextDeadlineAt;\n scheduleDeadline();\n };\n\n const humanWait = new HumanWaitDeadlinePause({\n remainingMs: () => executionDeadlineAt - Date.now(),\n suspend: () => {\n clearTimeout(timeout);\n executionDeadlineAt = Infinity;\n options.onDeadline?.(undefined);\n },\n resume: (remainingMs) => {\n executionDeadlineAt = Date.now() + remainingMs;\n scheduleDeadline();\n },\n });\n\n // Journal mode (see exec-journal.ts). Each host call gets an issue number,\n // each result is recorded before the guest sees it, and results reach the\n // guest one at a time. On resume, calls wait in `held` until the recorded\n // results are served. The guest clock is the time of the latest result.\n const journal = options.journal;\n let issued = 0;\n let replaying = journal?.resuming === true;\n let logicalNow = journal?.startedAt ?? 0;\n let timerCount = 0;\n const held = new Map<number, { ref: string; args: Record<string, unknown>; promise: any }>();\n let stopReport: string | undefined;\n let journalFailure: string | undefined;\n const failJournal = (error: unknown): void => {\n if (journalFailure !== undefined) return;\n journalFailure = `Fabric could not write its journal: ${error instanceof Error ? error.message : String(error)}`;\n abortHostCalls(journalFailure);\n rejectExecutionGate(journalFailure);\n };\n const errorOutcome = (reference: string, error: unknown): FabricJournalOutcome => {\n const exit = reference === \"pi.bash\" || reference === \"pi.powershell\"\n ? piBashExitMetadata(error)\n : undefined;\n const fields = guestErrorFields(error);\n return {\n ok: false,\n message: error instanceof Error ? error.message : String(error),\n ...(exit ? { bashExit: exit } : {}),\n ...(fields.length > 0 ? { fields } : {}),\n };\n };\n const deliverOutcome = (promise: any, outcome: FabricJournalOutcome): void => {\n if (outcome.ok) {\n const handle = outcome.json === undefined\n ? context.undefined\n : jsonHandle(context, jsonObject, jsonParse, JSON.parse(outcome.json));\n promise.resolve(handle);\n handle.dispose();\n return;\n }\n const errorHandle = context.newError(outcome.message);\n if (outcome.bashExit) {\n const metadata = jsonHandle(context, jsonObject, jsonParse, outcome.bashExit);\n context.setProp(errorHandle, \"__fabricBashExit\", metadata);\n metadata.dispose();\n }\n for (const [key, value] of outcome.fields ?? []) {\n const field = context.newNumber(value);\n context.setProp(errorHandle, key, field);\n field.dispose();\n }\n promise.reject(errorHandle);\n errorHandle.dispose();\n };\n // Record a result, hand it to the guest, and let the guest run to idle\n // before any other result arrives. A driver whose complete() returns a\n // promise is waited for: the guest sees the result only after it is saved,\n // and results reach the guest in the order complete() was called.\n let journalTail: Promise<void> | undefined;\n const journalStopped = (promise: any): boolean =>\n closing || promise.alive === false || journalFailure !== undefined || hostAbortController.signal.aborted;\n const recordAndDeliver = (\n seq: number,\n reference: string,\n args: Record<string, unknown>,\n promise: any,\n value: unknown,\n outcome: () => FabricJournalOutcome,\n ): void | Promise<void> => {\n // An aborted call is in flight when the run ends; it is never recorded.\n if (journalStopped(promise)) return;\n let result: FabricJournalOutcome;\n try {\n result = outcome();\n } catch (error) {\n result = errorOutcome(reference, error);\n }\n const deliver = (at: number): void => {\n if (journalStopped(promise)) return;\n logicalNow = at;\n cpuDeadlineAt = Date.now() + (options.maxCpuSliceMs ?? Infinity);\n deliverOutcome(promise, result);\n pumpJobs();\n };\n let saved: number | Promise<number>;\n try {\n saved = journal!.complete(seq, reference, args, value, result);\n } catch (error) {\n failJournal(error);\n return;\n }\n if (typeof saved === \"number\") {\n deliver(saved);\n return;\n }\n return saved.then(deliver, failJournal);\n };\n const settleJournaled = (\n seq: number,\n reference: string,\n args: Record<string, unknown>,\n promise: any,\n value: unknown,\n outcome: () => FabricJournalOutcome,\n ): void | Promise<void> => {\n const run = (): void | Promise<void> => recordAndDeliver(seq, reference, args, promise, value, outcome);\n const pending = journalTail ? journalTail.then(run) : run();\n if (pending === undefined) return;\n const tail: Promise<void> = pending.catch(failJournal).finally(() => {\n if (journalTail === tail) journalTail = undefined;\n });\n journalTail = tail;\n hostTasks.add(tail);\n void tail.finally(() => hostTasks.delete(tail));\n return tail;\n };\n const startTimer = (seq: number, args: Record<string, unknown>, promise: any): void => {\n const ms = Math.max(0, Number(args.ms ?? 0));\n const timer = setTimeout(() => {\n if (closing || promise.alive === false) return;\n if (journal) {\n settleJournaled(seq, \"fabric.$timer\", args, promise, undefined, () => ({ ok: true }));\n return;\n }\n promise.resolve(context.undefined);\n pumpJobs();\n }, ms);\n timer.unref?.();\n pendingTimers.add(timer);\n void promise.settled.then(() => pendingTimers.delete(timer));\n };\n const startHostCall = (\n seq: number,\n reference: string,\n args: Record<string, unknown>,\n promise: any,\n ): void => {\n const waitsForHuman = options.isHumanWaitHostCall?.(reference, args) === true;\n if (waitsForHuman) humanWait.enter();\n const call = runAbortable(hostAbortController.signal, () =>\n journal\n ? hostCall(reference, args, hostAbortController.signal, (wait) => humanWait.run(wait), { seq })\n : hostCall(reference, args, hostAbortController.signal, (wait) => humanWait.run(wait)),\n )\n .finally(() => {\n if (waitsForHuman) humanWait.leave();\n });\n const task = journal\n ? call\n .then(\n (value) => settleJournaled(seq, reference, args, promise, value, () => ({\n ok: true,\n ...(value === undefined ? {} : { json: jsonText(value) }),\n })),\n (error) => settleJournaled(seq, reference, args, promise, undefined, () => errorOutcome(reference, error)),\n )\n .catch(failJournal)\n : call\n .then((value) => {\n if (closing || promise.alive === false) return;\n cpuDeadlineAt = Date.now() + (options.maxCpuSliceMs ?? Infinity);\n const handle = jsonHandle(context, jsonObject, jsonParse, value);\n promise.resolve(handle);\n handle.dispose();\n })\n .catch((error) => {\n if (closing || promise.alive === false) return;\n deliverOutcome(promise, errorOutcome(reference, error));\n })\n .finally(() => {\n if (!closing) pumpJobs();\n });\n hostTasks.add(task);\n void task.finally(() => hostTasks.delete(task));\n };\n // Ask whether a call that may have run should run again. Only a yes repeats\n // it; a no, a dismissal, a failure, or a stopped program keeps the stop.\n const confirmRepeat = async (question: string): Promise<boolean> => {\n const confirm = options.confirmRepeat;\n if (!confirm) return false;\n if (confirm.pausesDeadline) humanWait.enter();\n try {\n return await confirm.ask(question, hostAbortController.signal) === true;\n } catch {\n return false;\n } finally {\n if (confirm.pausesDeadline) humanWait.leave();\n }\n };\n // Serve recorded results in their recorded order, then decide the calls\n // still waiting: a stop ends the program, otherwise they run live.\n const replayJournal = async (driver: FabricJournalDriver): Promise<string | undefined> => {\n for (const delivery of driver.replay) {\n if (cancelled || timedOut || closing) return undefined;\n const call = held.get(delivery.seq);\n if (!call || call.ref !== delivery.ref || driver.digest(call.args) !== delivery.digest) {\n const actual = call ?? [...held.entries()].sort(([left], [right]) => left - right)[0]?.[1];\n return driver.diverged(delivery, actual ? { ref: actual.ref, args: actual.args } : undefined);\n }\n held.delete(delivery.seq);\n try {\n await runAbortable(hostAbortController.signal, () => driver.served(delivery, call.args, hostAbortController.signal));\n } catch (error) {\n // A failed restore stops the run like a divergence: nothing after it runs.\n return error instanceof Error ? error.message : String(error);\n }\n if (cancelled || timedOut || closing || call.promise.alive === false) return undefined;\n logicalNow = delivery.at;\n cpuDeadlineAt = Date.now() + (options.maxCpuSliceMs ?? Infinity);\n deliverOutcome(call.promise, delivery.outcome);\n pumpJobs();\n }\n if (cancelled || timedOut || closing) return undefined;\n const waiting = [...held.entries()].sort(([left], [right]) => left - right);\n const stop = driver.frontier(waiting.map(([seq, call]) => ({ seq, ref: call.ref, args: call.args })));\n if (stop !== undefined) {\n // A stopped run keeps holding: no call it issues from here reaches the host.\n if (stop.question === undefined || !(await confirmRepeat(stop.question))) return stop.report;\n if (cancelled || timedOut || closing) return undefined;\n }\n if (cancelled || timedOut || closing) return undefined;\n replaying = false;\n held.clear();\n for (const [seq, call] of waiting) {\n if (call.ref === \"fabric.$timer\") startTimer(seq, call.args, call.promise);\n else startHostCall(seq, call.ref, call.args, call.promise);\n }\n return undefined;\n };\n\n try {\n const hostFunction = context.newFunction(\n \"__fabricHostCall\",\n (referenceHandle: any, argsHandle: any) => {\n const reference = context.getString(referenceHandle);\n const dumpedArgs = context.dump(argsHandle);\n const args =\n typeof dumpedArgs === \"object\" && dumpedArgs !== null && !Array.isArray(dumpedArgs)\n ? (dumpedArgs as Record<string, unknown>)\n : {};\n const seq = journal ? issued++ : -1;\n extendExecutionTimeout(reference, args);\n const promise = context.newPromise();\n pendingHostPromises.add(promise);\n void promise.settled.then(() => pendingHostPromises.delete(promise));\n if (reference === \"fabric.$timer\") {\n if (timerCount >= (options.maxPendingTimers ?? Infinity)) {\n const errorHandle = context.newError(\"Guest pending timer limit exceeded\");\n promise.reject(errorHandle);\n errorHandle.dispose();\n return promise.handle;\n }\n timerCount++;\n void promise.settled.then(() => {\n timerCount--;\n });\n if (replaying || journalFailure !== undefined) held.set(seq, { ref: reference, args, promise });\n else startTimer(seq, args, promise);\n return promise.handle;\n }\n if (replaying || journalFailure !== undefined) {\n held.set(seq, { ref: reference, args, promise });\n return promise.handle;\n }\n startHostCall(seq, reference, args, promise);\n return promise.handle;\n },\n );\n context.setProp(context.global, \"__fabricHostCall\", hostFunction);\n hostFunction.dispose();\n\n const printFunction = context.newFunction(\"print\", (...handles: any[]) => {\n if (logsTruncated) return;\n const line = handles.map((handle) => formatValue(context.dump(handle))).join(\" \");\n const remaining = maxLogChars - logChars;\n if (line.length > remaining) {\n if (remaining > 0) logs.push(line.slice(0, remaining));\n logs.push(\"[Pi Fabric log output truncated]\");\n logsTruncated = true;\n return;\n }\n logs.push(line);\n logChars += line.length;\n });\n context.setProp(context.global, \"print\", printFunction);\n printFunction.dispose();\n\n const strings = jsonHandle(context, jsonObject, jsonParse, options.strings ?? {});\n context.setProp(context.global, \"\u03C0\", strings);\n strings.dispose();\n const tokenBudget = context.newNumber(options.tokenBudget ?? Number.POSITIVE_INFINITY);\n context.setProp(context.global, \"__fabricTokenBudget\", tokenBudget);\n tokenBudget.dispose();\n\n cpuDeadlineAt = Date.now() + (options.maxCpuSliceMs ?? Infinity);\n const setupResult = context.evalCode(guestSetupSource(options.piToolCanonicalFields, options.nativeStoreEnabled, options.codemodeProfile, options.nativeToolsEnabled, options.providerGlobals), \"pi-fabric-setup.js\");\n if (setupResult.error) {\n const deadlineExceeded = interruptedByDeadline || interruptedByCpu || Date.now() > executionDeadlineAt;\n if (deadlineExceeded) timedOut = true;\n const error = options.signal?.aborted\n ? \"Execution cancelled\"\n : deadlineExceeded\n ? timeoutMessage()\n : formatValue(context.dump(setupResult.error));\n setupResult.error.dispose();\n abortHostCalls(error);\n return {\n value: undefined,\n logs,\n terminationReason: options.signal?.aborted\n ? \"aborted\"\n : deadlineExceeded\n ? \"timed_out\"\n : \"runtime_error\",\n error,\n };\n }\n setupResult.value.dispose();\n if (journal) {\n // Pin the clock, Math.random, and the time zone so a resume reproduces\n // the program's calls. The guest clock reads `logicalNow`.\n const journalNow = context.newFunction(\"__fabricJournalNow\", () => context.newNumber(logicalNow));\n context.setProp(context.global, \"__fabricJournalNow\", journalNow);\n journalNow.dispose();\n const shim = context.evalCode(journal.shim, \"pi-fabric-journal-shim.js\");\n if (shim.error) {\n const message = formatValue(context.dump(shim.error));\n shim.error.dispose();\n throw new Error(`Fabric journal shim failed: ${message}`);\n }\n shim.value.dispose();\n }\n\n executionGate = context.newPromise();\n context.setProp(context.global, \"__fabricExecutionGate\", executionGate.handle);\n const guestBundle = options.transpiledCode === undefined\n ? transpileFabricCodeWithSourceMap(code)\n : { code: options.transpiledCode, sourceMap: options.transpiledSourceMap };\n const guestStackMap = createGuestStackMap(guestBundle.sourceMap);\n const guestLineCount = guestBundle.code.split(\"\\n\").length;\n const wrappedCode = `${guestBundle.code}\\nPromise.race([globalThis.__fabricRun(__piFabricMain), globalThis.__fabricExecutionGate])`;\n cpuDeadlineAt = Date.now() + (options.maxCpuSliceMs ?? Infinity);\n const evaluation = context.evalCode(wrappedCode, \"pi-fabric-guest.js\");\n pumpJobs();\n if (evaluation.error) {\n const deadlineExceeded = interruptedByDeadline || interruptedByCpu || Date.now() > executionDeadlineAt;\n if (deadlineExceeded) timedOut = true;\n const error = options.signal?.aborted\n ? \"Execution cancelled\"\n : deadlineExceeded\n ? timeoutMessage()\n : remapGuestErrorText(formatValue(context.dump(evaluation.error)), guestStackMap, guestLineCount);\n evaluation.error.dispose();\n abortHostCalls(error);\n return {\n value: undefined,\n logs,\n terminationReason: options.signal?.aborted\n ? \"aborted\"\n : deadlineExceeded\n ? \"timed_out\"\n : \"runtime_error\",\n error,\n };\n }\n\n activePromiseHandle = evaluation.value;\n const cancellation = new Promise<never>((_resolve, reject) => {\n abortHandler = () => {\n cancelled = true;\n hostAbortController.abort(options.signal?.reason);\n rejectExecutionGate(\"Execution cancelled\");\n reject(new Error(\"Execution cancelled\"));\n };\n if (options.signal?.aborted) abortHandler();\n else options.signal?.addEventListener(\"abort\", abortHandler, { once: true });\n });\n void cancellation.catch(() => undefined);\n const deadline = new Promise<never>((_resolve, reject) => {\n rejectDeadline = reject;\n scheduleDeadline();\n });\n // A resume can expire before the race below attaches its handler.\n void deadline.catch(() => undefined);\n pendingResolution = context.resolvePromise(activePromiseHandle);\n pumpJobs();\n // Restoration is execution too: a stalled hook must not hold the caller\n // past cancellation/deadline, nor touch QuickJS after its context closes.\n const execution = (async () => {\n if (journal?.resuming) {\n const report = await replayJournal(journal);\n if (report !== undefined && !cancelled && !timedOut && !closing) {\n stopReport = report;\n abortHostCalls(report);\n rejectExecutionGate(report);\n }\n }\n return pendingResolution;\n })();\n const resolution = await Promise.race([execution, deadline, cancellation]);\n pendingResolution = undefined;\n activePromiseHandle.dispose();\n activePromiseHandle = undefined;\n const stopped = stopReport ?? journalFailure;\n if (stopped !== undefined) {\n if (resolution.error) resolution.error.dispose();\n else resolution.value.dispose();\n return {\n value: undefined,\n logs,\n emitted: emittedSnapshot(),\n terminationReason: \"runtime_error\",\n error: stopped,\n };\n }\n if (resolution.error) {\n const deadlineExceeded = timedOut || interruptedByDeadline || interruptedByCpu || Date.now() > executionDeadlineAt;\n if (deadlineExceeded) timedOut = true;\n const error = options.signal?.aborted\n ? \"Execution cancelled\"\n : deadlineExceeded\n ? timeoutMessage()\n : remapGuestErrorText(formatValue(context.dump(resolution.error)), guestStackMap, guestLineCount);\n resolution.error.dispose();\n const emittedHandle = context.getProp(context.global, \"__fabricEmitted\");\n const emitted = context.dump(emittedHandle) as unknown[];\n emittedHandle.dispose();\n abortHostCalls(error);\n return {\n value: undefined,\n logs,\n emitted,\n terminationReason: options.signal?.aborted\n ? \"aborted\"\n : deadlineExceeded\n ? \"timed_out\"\n : \"runtime_error\",\n error,\n };\n }\n const value = context.dump(resolution.value);\n resolution.value.dispose();\n const emittedHandle = context.getProp(context.global, \"__fabricEmitted\");\n const emitted = context.dump(emittedHandle) as unknown[];\n emittedHandle.dispose();\n return { value, logs, emitted, terminationReason: \"completed\" };\n } catch (error) {\n const deadlineExceeded = timedOut || interruptedByDeadline || interruptedByCpu || Date.now() > executionDeadlineAt;\n if (deadlineExceeded) timedOut = true;\n abortHostCalls(error instanceof Error ? error.message : String(error));\n return {\n value: undefined,\n logs,\n emitted: emittedSnapshot(),\n terminationReason: cancelled ? \"aborted\" : deadlineExceeded ? \"timed_out\" : \"runtime_error\",\n error: cancelled\n ? \"Execution cancelled\"\n : deadlineExceeded\n ? timeoutMessage()\n : error instanceof Error\n ? error.message\n : String(error),\n };\n } finally {\n if (timeout) clearTimeout(timeout);\n for (const timer of pendingTimers) clearTimeout(timer);\n if (abortHandler) options.signal?.removeEventListener(\"abort\", abortHandler);\n if (hostTasks.size > 0) {\n abortHostCalls(\"Fabric guest execution ended before its host calls settled\");\n const settled = await settleWithin(hostTasks, HOST_TASK_SETTLE_GRACE_MS);\n if (!settled) {\n abortHostCalls(\"Fabric guest execution ended before its host calls settled\");\n await settleWithin(hostTasks, HOST_TASK_SETTLE_GRACE_MS);\n }\n pumpJobs();\n }\n closing = true;\n if (timedOut || cancelled || pendingHostPromises.size > 0) {\n const cleanupMessage = cancelled\n ? \"Execution cancelled\"\n : timedOut\n ? timeoutMessage()\n : \"Fabric guest execution ended before its host calls settled\";\n if (!hostAbortController.signal.aborted) hostAbortController.abort(fabricControlAbort(cleanupMessage));\n rejectExecutionGate(cleanupMessage);\n const errorHandle = context.newError(cleanupMessage);\n for (const promise of pendingHostPromises) promise.reject(errorHandle);\n errorHandle.dispose();\n pumpJobs();\n await nextMacrotask();\n const settled = await Promise.race<any>([\n pendingResolution ? pendingResolution.catch(() => undefined) : Promise.resolve(undefined),\n new Promise<undefined>((resolve) => {\n const timer = setTimeout(() => resolve(undefined), 1_000);\n timer.unref?.();\n }),\n ]);\n if (settled?.error) settled.error.dispose();\n if (settled?.value) settled.value.dispose();\n for (const promise of pendingHostPromises) {\n if (promise.alive !== false) promise.dispose();\n }\n }\n if (activePromiseHandle?.alive !== false) activePromiseHandle?.dispose();\n if (executionGate?.alive !== false) executionGate?.dispose();\n pumpJobs();\n jsonParse.dispose();\n jsonObject.dispose();\n disposeQuickJsContext(context);\n }\n }\n}\n\n/**\n * Finite numeric fields a host error opts to expose on the guest's error\n * object (for example a Jev HTTP status), never its message internals.\n */\nfunction guestErrorFields(error: unknown): Array<[string, number]> {\n const fields = error instanceof Error ? (error as { guestFields?: unknown }).guestFields : undefined;\n if (typeof fields !== \"object\" || fields === null) return [];\n return Object.entries(fields).filter((entry): entry is [string, number] =>\n /^[a-z][A-Za-z]{0,31}$/.test(entry[0]) && ![\"message\", \"name\", \"stack\", \"cause\"].includes(entry[0]) &&\n typeof entry[1] === \"number\" && Number.isFinite(entry[1])).slice(0, 8);\n}\n", "// Stack frames captured from the executed guest bundle reference the emitted\n// pi-fabric-guest.js (wrapper header plus TypeScript printer layout), not the\n// author's program. These helpers decode the transpile source map and rewrite\n// error text so stack positions point back at the user-submitted code.\n\ninterface GuestSourcePosition {\n line: number;\n column: number;\n}\n\nexport interface GuestStackMap {\n lookup(line: number, column: number): GuestSourcePosition | undefined;\n}\n\ninterface GuestSourceMapJson {\n mappings?: unknown;\n}\n\ninterface MappingSegment {\n generatedColumn: number;\n sourceLine: number;\n sourceColumn: number;\n}\n\nconst BASE64_VALUES = (() => {\n const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n const table = new Map<string, number>();\n for (let index = 0; index < alphabet.length; index += 1) {\n table.set(alphabet[index] as string, index);\n }\n return table;\n})();\n\nconst decodeVlqSegment = (segment: string): number[] => {\n const values: number[] = [];\n let index = 0;\n while (index < segment.length) {\n let value = 0;\n let shift = 0;\n let continuation = true;\n while (continuation) {\n const digit = BASE64_VALUES.get(segment[index] as string);\n if (digit === undefined) return values;\n index += 1;\n continuation = (digit & 32) !== 0;\n value += (digit & 31) * 2 ** shift;\n shift += 5;\n }\n values.push((value & 1) === 1 ? -(value >> 1) : value >> 1);\n }\n return values;\n};\n\nconst decodeMappings = (mappings: string): MappingSegment[][] => {\n const lines: MappingSegment[][] = [];\n let sourceLine = 0;\n let sourceColumn = 0;\n for (const line of mappings.split(\";\")) {\n const segments: MappingSegment[] = [];\n let generatedColumn = 0;\n for (const rawSegment of line.split(\",\")) {\n if (!rawSegment) continue;\n const values = decodeVlqSegment(rawSegment);\n // values[1] is the source index delta; single-source guest maps never\n // need it, so only generated column and source position accumulate.\n if (values.length < 4) continue;\n generatedColumn += values[0] as number;\n sourceLine += values[2] as number;\n sourceColumn += values[3] as number;\n segments.push({ generatedColumn, sourceLine, sourceColumn });\n }\n lines.push(segments);\n }\n return lines;\n};\n\nexport const createGuestStackMap = (\n sourceMapText: string | undefined,\n): GuestStackMap | undefined => {\n if (!sourceMapText) return undefined;\n let mappings: string;\n try {\n const parsed = JSON.parse(sourceMapText) as GuestSourceMapJson;\n if (typeof parsed.mappings !== \"string\") return undefined;\n mappings = parsed.mappings;\n } catch {\n return undefined;\n }\n // Validating the envelope above is cheap; decoding the VLQ mappings defers\n // to the first error lookup so clean executions pay almost nothing for\n // diagnostics they never render.\n let decoded: MappingSegment[][] | undefined;\n return {\n lookup(line, column) {\n decoded ??= decodeMappings(mappings);\n const segments = decoded[line - 1];\n if (!segments) return undefined;\n const target = column - 1;\n let best: MappingSegment | undefined;\n for (const segment of segments) {\n if (segment.generatedColumn > target) break;\n best = segment;\n }\n // Columns before the first segment point at line indentation; anchor\n // them to the first statement segment rather than leaving the frame\n // in emitted-file coordinates.\n best ??= segments[0];\n if (!best) return undefined;\n // The wrapper header occupies source line 1, so the zero-based source\n // line already equals the author's one-based program line.\n return { line: best.sourceLine, column: best.sourceColumn + 1 };\n },\n };\n};\n\nconst GUEST_FRAME_PATTERN = /pi-fabric-guest\\.js:(\\d+):(\\d+)/g;\n\nexport const remapGuestErrorText = (\n text: string,\n stackMap: GuestStackMap | undefined,\n guestLineCount?: number,\n): string => {\n if (!stackMap || !text.includes(\"pi-fabric-guest.js:\")) return text;\n return text.replace(GUEST_FRAME_PATTERN, (match, lineText, columnText) => {\n const line = Number(lineText);\n const mapped = stackMap.lookup(line, Number(columnText));\n if (mapped) return `guest code:${mapped.line}:${mapped.column}`;\n // Both runtimes append their driver call after the emitted bundle, so\n // frames beyond it can only be harness machinery, never user statements.\n if (guestLineCount !== undefined && line > guestLineCount) return \"fabric driver\";\n return match;\n });\n};\n", "// Shared by QuickJS and the trusted Node/Bun executor. No host dependencies.\nexport const NATIVE_CODEMODE_GUEST = String.raw`\nconst __nativeModels = Object.assign(() => __call(\"fabric.$models\", {}), {\n getModelsOfType: (type, provider) => __call(\"native.getModelsOfType\", { type, provider }),\n getAvailableOfType: (type, provider) => __call(\"native.getAvailableOfType\", { type, provider }),\n getModelOfType: (type, provider, id) => __call(\"native.getModelOfType\", { type, provider, id }),\n classify: (model, context) => __call(\"native.classify\", { model: { provider: model.provider, id: model.id }, context }),\n generateImages: (model, context) => __call(\"native.generateImages\", { model: { provider: model.provider, id: model.id }, context }),\n});\n__toolsBase.models = Object.freeze(__nativeModels);\nglobalThis.models = __toolsBase.models;\nglobalThis.ALL_TOOLS = Object.freeze([]);\nglobalThis.searchTools = (query, options = {}) => __call(\"fabric.$nativeSearch\", { query, ...options });\nglobalThis.describeTool = name => __call(\"fabric.$nativeDescribe\", { name });\nglobalThis.describeNamespace = name => __call(\"fabric.$describeNamespace\", { name });\nlet __nativeAllTools = Object.freeze([]);\nglobalThis.nativeDiscovery = Object.freeze({\n get ALL_TOOLS() { return __nativeAllTools; },\n searchTools: (query, options = {}) => __call(\"fabric.$piSearch\", { query, ...options }),\n describeTool: name => __call(\"fabric.$piDescribe\", { name }),\n describeNamespace: name => __call(\"fabric.$piNamespace\", { name }),\n});\nif (typeof __nativeProfile !== \"undefined\" && __nativeProfile) {\n globalThis.searchTools = globalThis.nativeDiscovery.searchTools;\n globalThis.describeTool = globalThis.nativeDiscovery.describeTool;\n globalThis.describeNamespace = globalThis.nativeDiscovery.describeNamespace;\n}\nconst __exit = Object.freeze({});\nlet __storeValues;\nlet __storeDirty = false;\nlet __storeError;\nconst __cloneJson = value => JSON.parse(JSON.stringify(value));\nglobalThis.load = key => {\n if (typeof key !== \"string\") throw new Error(\"load key must be a string\");\n if (!__storeValues) throw (__storeError ?? new Error(\"Script store is unavailable in this runtime\"));\n return Object.prototype.hasOwnProperty.call(__storeValues, key) ? __cloneJson(__storeValues[key]) : undefined;\n};\nglobalThis.store = (key, value) => {\n if (typeof key !== \"string\") throw new Error(\"store key must be a string\");\n if (!__storeValues) throw (__storeError ?? new Error(\"Script store is unavailable in this runtime\"));\n const next = Object.assign(Object.create(null), __storeValues);\n if (value === undefined) delete next[key];\n else {\n const json = JSON.stringify(value);\n if (json === undefined) throw new Error(\"Script store values must be JSON\");\n if (json.length > 262144) throw new Error(\"Script store value exceeds 262144 characters\");\n next[key] = JSON.parse(json);\n }\n if (Object.values(next).reduce((sum, item) => sum + JSON.stringify(item).length, 0) > 1048576) throw new Error(\"Script store exceeds 1048576 characters\");\n __storeValues = next;\n __storeDirty = true;\n};\nconst __emitted = [];\nObject.defineProperty(globalThis, \"__fabricEmitted\", { value: __emitted });\nlet __emittedChars = 0;\nlet __emittedCalls = 0;\nconst __countOutput = chars => {\n __emittedChars += chars;\n if (++__emittedCalls > 100000 || __emittedChars > 16777216) throw new Error(\"Script output limit exceeded\");\n};\nglobalThis.text = value => {\n const text = typeof value === \"string\" ? value : JSON.stringify(value);\n __countOutput((text ?? \"\").length);\n print(text);\n};\nglobalThis.image = value => {\n if (value && typeof value === \"object\" && \"image_url\" in value) value = typeof value.image_url === \"string\" ? value.image_url : value.image_url?.url;\n if (typeof value === \"string\") {\n const match = /^data:(image\\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/=\\s]+)$/.exec(value);\n if (!match) throw new Error(\"image() requires a local base64 PNG, JPEG, GIF or WebP; remote URLs are unsupported\");\n value = { type: \"image\", mimeType: match[1], data: match[2].replace(/\\s/g, \"\") };\n }\n if (!value || value.type !== \"image\" || !/^image\\/(png|jpeg|gif|webp)$/.test(value.mimeType) || typeof value.data !== \"string\" || !/^[A-Za-z0-9+/=\\s]+$/.test(value.data)) throw new Error(\"Invalid image block\");\n __countOutput(value.data.length);\n const block = { type: \"image\", mimeType: value.mimeType, data: value.data };\n __emitted.push(block);\n if (typeof globalThis.__fabricEmitImage === \"function\") globalThis.__fabricEmitImage(block);\n};\nglobalThis.exit = () => { throw __exit; };\nglobalThis.__fabricRun = async (main) => {\n if (typeof __nativeToolsEnabled !== \"undefined\" && __nativeToolsEnabled) {\n __nativeAllTools = Object.freeze(await __call(\"fabric.$piAllTools\", {}));\n // A host may also give a tool's identifier (jsName: my-tool -> my_tool) so tools.my_tool reaches it.\n for (const tool of __nativeAllTools) { __nativeToolNames.add(tool.name); if (typeof tool.jsName === \"string\") __nativeToolNames.add(tool.jsName); }\n __nativeCatalogReady = true;\n if (__nativeProfile) globalThis.ALL_TOOLS = __nativeAllTools;\n }\n if (typeof __nativeStoreEnabled !== \"undefined\" && __nativeStoreEnabled) {\n if (!(typeof __nativeProfile !== \"undefined\" && __nativeProfile)) globalThis.ALL_TOOLS = Object.freeze(await __call(\"fabric.$allTools\", {}));\n try { __storeValues = Object.assign(Object.create(null), await __call(\"native.load\", {})); }\n catch (error) { __storeError = error; }\n }\n let value;\n try { value = await main(); } catch (error) { if (error !== __exit) throw error; }\n if (__storeDirty) await __call(\"native.store\", { values: __storeValues });\n return value;\n};\n`;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,wBAAwB;AAC/B,SAAS,iCAAiC,kBAAkB;AAC5D,OAAO,QAAQ;;;ACsBf,IAAM,iBAAiB,MAAM;AAC3B,QAAM,WAAW;AACjB,QAAM,QAAQ,oBAAI,IAAoB;AACtC,WAAS,QAAQ,GAAG,QA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AAM,MAAM,MAAS,IAAI,QAAQ,QAAQ,MAAS;AAAA,UACxF,IAAI,QAAmB,CAAC,YAAY;AAClC,kBAAM,QAAQ,WAAW,MAAM,QAAQ,MAAS,GAAG,GAAK;AACxD,kBAAM,QAAQ;AAAA,UAChB,CAAC;AAAA,QACH,CAAC;AACD,YAAI,SAAS,MAAO,SAAQ,MAAM,QAAQ;AAC1C,YAAI,SAAS,MAAO,SAAQ,MAAM,QAAQ;AAC1C,mBAAW,WAAW,qBAAqB;AACzC,cAAI,QAAQ,UAAU,MAAO,SAAQ,QAAQ;AAAA,QAC/C;AAAA,MACF;AACA,UAAI,qBAAqB,UAAU,MAAO,sBAAqB,QAAQ;AACvE,UAAI,eAAe,UAAU,MAAO,gBAAe,QAAQ;AAC3D,eAAS;AACT,gBAAU,QAAQ;AAClB,iBAAW,QAAQ;AACnB,4BAAsB,OAAO;AAAA,IAC/B;AAAA,EACF;AACF;AAMA,SAAS,iBAAiB,OAAyC;AACjE,QAAM,SAAS,iBAAiB,QAAS,MAAoC,cAAc;AAC3F,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO,CAAC;AAC3D,SAAO,OAAO,QAAQ,MAAM,EAAE,OAAO,CAAC,UACpC,wBAAwB,KAAK,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,WAAW,QAAQ,SAAS,OAAO,EAAE,SAAS,MAAM,CAAC,CAAC,KAClG,OAAO,MAAM,CAAC,MAAM,YAAY,OAAO,SAAS,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC;AACzE;",
|
|
6
|
+
"names": ["emittedHandle", "emitted"]
|
|
7
|
+
}
|
|
@@ -5864,7 +5864,7 @@ function installFabricShellHangKeys(context, options) {
|
|
|
5864
5864
|
halted: () => false,
|
|
5865
5865
|
halt: () => {
|
|
5866
5866
|
let count = 0;
|
|
5867
|
-
for (const job of options.jobs()?.live() ?? []) if (job.
|
|
5867
|
+
for (const job of options.jobs()?.live() ?? []) if (job.monitorActive && job.stop("Main interrupted")) count++;
|
|
5868
5868
|
return count;
|
|
5869
5869
|
}
|
|
5870
5870
|
});
|
|
@@ -6092,6 +6092,91 @@ var installTerminalTitle = (pi, title) => {
|
|
|
6092
6092
|
// src/extension.ts
|
|
6093
6093
|
import path8 from "node:path";
|
|
6094
6094
|
import { fileURLToPath } from "node:url";
|
|
6095
|
+
|
|
6096
|
+
// src/core/crash-guard.ts
|
|
6097
|
+
var CONTROL_ABORT = Symbol.for("pi-fabric.control-abort");
|
|
6098
|
+
var GUARD = Symbol.for("pi-fabric.crash-guard");
|
|
6099
|
+
var causes = function* (value) {
|
|
6100
|
+
const seen = /* @__PURE__ */ new Set();
|
|
6101
|
+
for (let current = value, depth = 0; current !== void 0 && current !== null && depth < 8; depth++) {
|
|
6102
|
+
if (seen.has(current)) return;
|
|
6103
|
+
seen.add(current);
|
|
6104
|
+
yield current;
|
|
6105
|
+
if (typeof current !== "object") return;
|
|
6106
|
+
current = current.cause;
|
|
6107
|
+
}
|
|
6108
|
+
};
|
|
6109
|
+
var isFabricControlAbort = (value) => {
|
|
6110
|
+
for (const item of causes(value)) {
|
|
6111
|
+
if (typeof item === "object" && Reflect.get(item, CONTROL_ABORT) === true) return true;
|
|
6112
|
+
}
|
|
6113
|
+
return false;
|
|
6114
|
+
};
|
|
6115
|
+
var normalize = (file) => file.replaceAll("\\", "/");
|
|
6116
|
+
var raisedByFabric = (value, roots) => {
|
|
6117
|
+
for (const item of causes(value)) {
|
|
6118
|
+
const stack = item instanceof Error && typeof item.stack === "string" ? normalize(item.stack) : "";
|
|
6119
|
+
if (!stack) continue;
|
|
6120
|
+
for (const root of roots) {
|
|
6121
|
+
if (stack.includes(`${root}/dist/`) || stack.includes(`${root}/src/`)) return true;
|
|
6122
|
+
}
|
|
6123
|
+
}
|
|
6124
|
+
return false;
|
|
6125
|
+
};
|
|
6126
|
+
var fabricOwnsFailure = (value, roots = guardState()?.roots ?? /* @__PURE__ */ new Set()) => isFabricControlAbort(value) || raisedByFabric(value, roots);
|
|
6127
|
+
var unhandledRejectionMode = () => {
|
|
6128
|
+
const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? "").split(/\s+/)];
|
|
6129
|
+
let mode = "throw";
|
|
6130
|
+
for (const flag of flags) {
|
|
6131
|
+
const match = /^--unhandled-rejections=(.+)$/.exec(flag);
|
|
6132
|
+
if (match) mode = match[1];
|
|
6133
|
+
}
|
|
6134
|
+
return mode;
|
|
6135
|
+
};
|
|
6136
|
+
var describe = (value) => {
|
|
6137
|
+
if (value instanceof Error) return `${value.name}: ${value.message}`;
|
|
6138
|
+
try {
|
|
6139
|
+
return String(value);
|
|
6140
|
+
} catch {
|
|
6141
|
+
return "unprintable value";
|
|
6142
|
+
}
|
|
6143
|
+
};
|
|
6144
|
+
var guardState = () => globalThis[GUARD];
|
|
6145
|
+
function installFabricCrashGuard(packageRoot, log = (line) => console.warn(`[pi-fabric] ${line}`)) {
|
|
6146
|
+
const existing = guardState();
|
|
6147
|
+
if (existing) {
|
|
6148
|
+
existing.roots.add(normalize(packageRoot).replace(/\/+$/, ""));
|
|
6149
|
+
return;
|
|
6150
|
+
}
|
|
6151
|
+
const state = {
|
|
6152
|
+
roots: /* @__PURE__ */ new Set([normalize(packageRoot).replace(/\/+$/, "")]),
|
|
6153
|
+
log,
|
|
6154
|
+
listener: (reason) => {
|
|
6155
|
+
if (fabricOwnsFailure(reason, state.roots)) {
|
|
6156
|
+
try {
|
|
6157
|
+
state.log(`detached work failed: ${describe(reason)}`);
|
|
6158
|
+
} catch {
|
|
6159
|
+
}
|
|
6160
|
+
return;
|
|
6161
|
+
}
|
|
6162
|
+
if (process.listenerCount("unhandledRejection") > 1) return;
|
|
6163
|
+
const mode = unhandledRejectionMode();
|
|
6164
|
+
if (mode === "warn" || mode === "warn-with-error-code" || mode === "none") {
|
|
6165
|
+
if (mode !== "none") process.emitWarning(`Unhandled promise rejection: ${describe(reason)}`, "UnhandledPromiseRejectionWarning");
|
|
6166
|
+
if (mode === "warn-with-error-code") process.exitCode = 1;
|
|
6167
|
+
return;
|
|
6168
|
+
}
|
|
6169
|
+
if (reason instanceof Error) throw reason;
|
|
6170
|
+
const error = new Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${describe(reason)}".`);
|
|
6171
|
+
error.code = "ERR_UNHANDLED_REJECTION";
|
|
6172
|
+
throw error;
|
|
6173
|
+
}
|
|
6174
|
+
};
|
|
6175
|
+
globalThis[GUARD] = state;
|
|
6176
|
+
process.on("unhandledRejection", state.listener);
|
|
6177
|
+
}
|
|
6178
|
+
|
|
6179
|
+
// src/extension.ts
|
|
6095
6180
|
var FABRIC_MANAGED_HOST_VERSION = 2;
|
|
6096
6181
|
var userPromptText = (event) => event.messageType === "custom" || typeof event.prompt !== "string" ? void 0 : event.prompt;
|
|
6097
6182
|
function createFabricExtension(entryUrl) {
|
|
@@ -6133,6 +6218,7 @@ function createFabricExtension(entryUrl) {
|
|
|
6133
6218
|
);
|
|
6134
6219
|
return;
|
|
6135
6220
|
}
|
|
6221
|
+
installFabricCrashGuard(path8.resolve(FABRIC_ENTRY_DIR, ".."));
|
|
6136
6222
|
if (!options.managedHost) registerJevAuth(pi);
|
|
6137
6223
|
pi.on("input", async (event, context) => {
|
|
6138
6224
|
if (event.source !== "interactive" || !event.text.includes("pi-clipboard-")) return;
|
|
@@ -7168,4 +7254,4 @@ export {
|
|
|
7168
7254
|
FABRIC_MANAGED_HOST_VERSION,
|
|
7169
7255
|
createFabricExtension
|
|
7170
7256
|
};
|
|
7171
|
-
//# sourceMappingURL=chunk-
|
|
7257
|
+
//# sourceMappingURL=chunk-6XEFPCVA.js.map
|