omp-fabric 1.26.13 → 1.26.15

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/chunks/{chunk-7KKE52AS.js → chunk-673LUJCK.js} +2 -2
  3. package/dist/chunks/{chunk-JHKOG5GS.js → chunk-BV3EDWSX.js} +50 -3
  4. package/dist/chunks/chunk-BV3EDWSX.js.map +7 -0
  5. package/dist/chunks/{chunk-RFTAEH2R.js → chunk-EZWJ5GBW.js} +93 -3
  6. package/dist/chunks/{chunk-RFTAEH2R.js.map → chunk-EZWJ5GBW.js.map} +2 -2
  7. package/dist/chunks/{chunk-AVSEXLZ7.js → chunk-O5SZML2M.js} +434 -3
  8. package/dist/chunks/chunk-O5SZML2M.js.map +7 -0
  9. package/dist/chunks/{chunk-2T6EHZ5G.js → chunk-S3URDR4K.js} +1 -1
  10. package/dist/fabric-runtime-state.js +124 -18
  11. package/dist/fabric-runtime-state.js.map +2 -2
  12. package/dist/index.js +60 -1
  13. package/dist/index.js.map +3 -3
  14. package/dist/providers/image-provider.d.ts +1 -0
  15. package/dist/providers/image-provider.d.ts.map +1 -1
  16. package/dist/residency/host.js +2 -2
  17. package/dist/residency/omp-entry.js +2 -2
  18. package/dist/runtime/core-override-guest-types.js +1 -1
  19. package/dist/runtime/guest-host-sync.d.ts +5 -0
  20. package/dist/runtime/guest-host-sync.d.ts.map +1 -0
  21. package/dist/runtime/guest-types.d.ts +1 -1
  22. package/dist/runtime/guest-types.d.ts.map +1 -1
  23. package/dist/runtime/guest-types.js +1 -1
  24. package/dist/runtime/guest-web-globals.d.ts +2 -0
  25. package/dist/runtime/guest-web-globals.d.ts.map +1 -0
  26. package/dist/runtime/node-process-child-source.d.ts.map +1 -1
  27. package/dist/runtime/node-process-runtime.js +12 -2
  28. package/dist/runtime/node-process-runtime.js.map +2 -2
  29. package/dist/runtime/quickjs-runtime.d.ts +1 -1
  30. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  31. package/dist/runtime/quickjs-runtime.js +2 -2
  32. package/dist/runtime/type-checker.d.ts.map +1 -1
  33. package/dist/runtime/type-checker.js +1 -1
  34. package/dist/type-error-guidance.d.ts.map +1 -1
  35. package/docs/architecture.md +1 -1
  36. package/docs/image.md +24 -3
  37. package/package.json +1 -1
  38. package/skills/fabric-exec/SKILL.md +4 -1
  39. package/dist/chunks/chunk-AVSEXLZ7.js.map +0 -7
  40. package/dist/chunks/chunk-JHKOG5GS.js.map +0 -7
  41. /package/dist/chunks/{chunk-7KKE52AS.js.map → chunk-673LUJCK.js.map} +0 -0
  42. /package/dist/chunks/{chunk-2T6EHZ5G.js.map → chunk-S3URDR4K.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/runtime/quickjs-runtime.ts", "../../src/runtime/guest-stack-map.ts", "../../src/runtime/guest-host-sync.ts", "../../src/runtime/guest-web-globals.ts"],
4
+ "sourcesContent": ["import releaseSyncVariant from \"@jitl/quickjs-singlefile-mjs-release-sync\";\nimport { newQuickJSWASMModuleFromVariant } from \"quickjs-emscripten-core\";\nimport ts from \"typescript\";\nimport { runAbortable, settleWithin } from \"../async-settlement.js\";\nimport { ompBashExitMetadata } from \"../core/omp-bash-error.js\";\nimport { createGuestStackMap, remapGuestErrorText } from \"./guest-stack-map.js\";\nimport { fabricSyncCall } from \"./guest-host-sync.js\";\nimport { GUEST_WEB_GLOBALS_SOURCE } from \"./guest-web-globals.js\";\nimport { OMP_GUEST_ENTRYPOINT, transpileFabricCodeWithSourceMap } from \"./type-checker.js\";\n\nexport type FabricSandboxTerminationReason =\n | \"completed\"\n | \"runtime_error\"\n | \"timed_out\"\n | \"aborted\";\n\nexport interface FabricGuestProxyNames {\n extensions?: string[];\n mcp?: Record<string, string[]>;\n}\n\nexport interface FabricSandboxResult {\n value: unknown;\n logs: string[];\n terminationReason: FabricSandboxTerminationReason;\n error?: string;\n}\n\nexport interface FabricSandboxOptions {\n timeoutMs: number;\n memoryLimitBytes: number;\n maxLogChars?: number;\n payloads?: Record<string, string>;\n proxyNames?: FabricGuestProxyNames;\n tokenBudget?: number;\n signal?: AbortSignal;\n minimumTimeoutMsForHostCall?(\n ref: string,\n args: Record<string, unknown>,\n ): number | undefined;\n transpiledCode?: string;\n transpiledSourceMap?: string;\n}\n\nexport type FabricHostCall = (\n ref: string,\n args: Record<string, unknown>,\n signal: AbortSignal,\n) => Promise<unknown>;\n\ntype QuickJsModule = Awaited<ReturnType<typeof newQuickJSWASMModuleFromVariant>>;\n\nlet quickJsModulePromise: Promise<QuickJsModule> | undefined;\n\n// Static payloads.<identifier> references (bracket access like payloads[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 referencedPayloadKeys = (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 === \"payloads\" &&\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// Reject up front when a referenced key is statically provable missing, before\n// QuickJS is even loaded.\nconst missingPayloadKeys = (\n code: string,\n payloads: Record<string, string> | undefined,\n): string[] => {\n const provided = payloads ?? {};\n return referencedPayloadKeys(code).filter((key) => !(key in provided));\n};\nconst quickJsModule = (): Promise<QuickJsModule> => {\n quickJsModulePromise ??= newQuickJSWASMModuleFromVariant(releaseSyncVariant);\n return quickJsModulePromise;\n};\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 __ompToolNames = [\"read\",\"bash\",\"edit\",\"write\",\"grep\",\"find\",\"ls\",\"wait\"];\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 omp.<name>, 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 (__ompToolNames.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 OMP core tool, call omp.\" + name + \"(args), e.g. omp.\" + name + \"({ ... }).\"\n );\n };\n }\n if (name in target || name === \"toJSON\") return target[property];\n return () => {\n throw new Error(\n \"tools.\" + name + \" is not a Fabric action. tools is discovery + generic calls only (providers/catalog/list/search/describe/call/models). Find a capability with tools.search('\" + name + \"') and call it through its ref, e.g. tools.call({ ref, args }); a host tool absent from tools.providers() (such as web_search or ask) is not reachable inside fabric_exec, so call it directly as its own tool.\"\n );\n };\n },\n set() { return true; },\n deleteProperty() { return true; },\n});\nconst __ompStringFields = { 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 __normalizeOmpArgs. 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 OmpToolsApi overloads in guest-types.ts so\n// the type-checker accepts the same spellings it coercion-handles at runtime.\nconst __ompArgAliases = {\n bash: {\n cmd: \"command\", shell: \"command\", cmdline: \"command\", script: \"command\",\n commandLine: \"command\",\n workdir: \"cwd\", directory: \"cwd\", workingDirectory: \"cwd\",\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 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. bash/ls stay\n// absent: their two-arg form is a bare string plus an options object, repaired\n// by the merge instead of a wrong-arity (2554) type error.\nconst __ompPositionalFields = {\n read: [\"path\", \"offset\", \"limit\"],\n grep: [\"pattern\", \"path\", \"skip\"],\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 OmpToolsApi overloads in guest-types.ts.\nconst __ompNumericFields = {\n read: [\"offset\", \"limit\"],\n bash: [\"timeout\"],\n grep: [\"skip\", \"context\", \"limit\"],\n find: [\"limit\"],\n ls: [\"limit\"],\n};\nconst __ompOptionalFields = {\n read: [\"offset\", \"limit\"],\n grep: [\"path\", \"glob\", \"ignoreCase\", \"literal\", \"context\", \"limit\"],\n find: [\"path\", \"limit\"],\n ls: [\"path\", \"limit\"],\n};\n// (primary, options) two-arg merge for the string-primary tools:\n// omp.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 __normalizeOmpArgs as any other options object.\nconst __positionalToArgs = (name, rest) => {\n const first = rest[0];\n const second = rest[1];\n const primaryField = __ompStringFields[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 = __ompPositionalFields[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 __normalizeOmpArgs = (name, args) => {\n const field = __ompStringFields[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 = __ompArgAliases[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 = __ompNumericFields[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 = __ompOptionalFields[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 = __ompArgAliases.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// 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 __ompEnvelopeTools = { bash: true, edit: true, write: true, wait: true };\nconst __ompEnvelopeStringTraps = 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 __ompEnvelopeGuard = (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 \"omp.\" + name + \"(...) resolves an envelope { ok, output, details }, which is not iterable. \" +\n \"Iterate the text instead: (await omp.\" + name + \"(...)).output.split('\\\\\\\\n')\"\n );\n }\n if (typeof property === \"string\" && __ompEnvelopeStringTraps.has(property)) {\n throw new TypeError(\n \"omp.\" + name + \"(...) resolves an envelope { ok, output, details }, not a string, so .\" + property +\n \" is unavailable on it. Read the text first: const out = (await omp.\" + 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 omp 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 __ompPositionalFields. 0/1 args preserve the\n// legacy (args = {}) default so existing programs are unchanged.\nglobalThis.omp = new Proxy({}, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n const name = String(property);\n // fabric_exec payload values are readable directly on the omp surface\n // (documented for skills as payloads.<key>), while core tool names stay\n // callables. Only shadow a payload key that actually exists.\n const payloadValues = (typeof globalThis[\"payloads\"] === \"object\" && globalThis[\"payloads\"] !== null)\n ? globalThis[\"payloads\"]\n : {};\n if (__ompToolNames.indexOf(name) < 0 && Object.prototype.hasOwnProperty.call(payloadValues, name)) {\n return payloadValues[name];\n }\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\" &&\n typeof args === \"object\" && args !== null && args.settle === true;\n const call = __call(\"omp.\" + name, __normalizeOmpArgs(name, args));\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 __ompEnvelopeTools[name] === true\n ? promise.then((value) => __ompEnvelopeGuard(name, value))\n : promise;\n };\n },\n});\nconst __payloads = (typeof globalThis[\"payloads\"] === \"object\" && globalThis[\"payloads\"] !== null) ? globalThis[\"payloads\"] : {};\nglobalThis[\"payloads\"] = new Proxy(__payloads, {\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 (__ompToolNames.indexOf(name) >= 0) {\n throw new Error(\n \"payloads.\" + name + \" is the payloads accessor, not a tool. For the OMP core tool, call omp.\" + name + \"(args).\"\n );\n }\n const provided = Object.keys(target);\n throw new Error(\n \"payloads.\" + name + \" is not defined. payloads only exposes keys from the fabric_exec payloads parameter\" +\n (provided.length ? \" (provided: \" + provided.join(\", \") + \")\" : \" (none provided)\") +\n \". Pass payloads: { \" + name + \": '...' } to use payloads.\" + name + \".\" +\n \" For large or quote-heavy content, keep it in top-level payloads and reference payloads.\" + 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 __proxyNames = (() => {\n const raw = globalThis.__fabricProxyNames;\n delete globalThis.__fabricProxyNames;\n return raw && typeof raw === \"object\" ? raw : {};\n})();\nconst __nameList = (value) =>\n Array.isArray(value) ? value.filter((name) => typeof name === \"string\") : [];\nconst __lazyNamespace = (names, resolve, 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 resolve(String(property));\n },\n ownKeys(target) {\n const own = Object.keys(target);\n return names.concat(own.filter((key) => names.indexOf(key) < 0));\n },\n getOwnPropertyDescriptor(target, property) {\n if (typeof property === \"symbol\") return undefined;\n const name = String(property);\n if (names.indexOf(name) < 0 && !Object.prototype.hasOwnProperty.call(target, name)) {\n return undefined;\n }\n const value = Object.prototype.hasOwnProperty.call(target, name)\n ? target[name]\n : resolve(name);\n return { value, writable: false, enumerable: true, configurable: true };\n },\n has(target, property) {\n if (typeof property === \"symbol\") return false;\n return names.indexOf(String(property)) >= 0\n || Object.prototype.hasOwnProperty.call(target, property);\n },\n});\nconst __providerProxy = (provider, local = {}, names = []) =>\n __lazyNamespace(names, (property) => (args = {}) => __call(provider + \".\" + property, args), local);\nconst __isAlnum = (char) => /[A-Za-z0-9]/.test(char);\nconst __mcpServerEnd = (rest, server) => {\n let i = 0;\n let j = 0;\n while (j < server.length) {\n const expected = server[j];\n if (__isAlnum(expected)) {\n if (rest[i] === undefined || rest[i].toLowerCase() !== expected.toLowerCase()) return -1;\n i += 1;\n j += 1;\n continue;\n }\n if (rest[i] === undefined || __isAlnum(rest[i])) return -1;\n i += 1;\n while (j < server.length && !__isAlnum(server[j])) j += 1;\n }\n if (rest[i] === undefined || __isAlnum(rest[i])) return -1;\n const toolStart = i + 1;\n if (toolStart >= rest.length || !__isAlnum(rest[toolStart])) return -1;\n return toolStart;\n};\nconst __mcpAlias = (name) => {\n if (name.indexOf(\"mcp__\") !== 0) return undefined;\n const rest = name.slice(5);\n const servers = Object.keys(__mcpServerTools);\n let best;\n let bestEnd = -1;\n let tied = false;\n for (const server of servers) {\n const end = __mcpServerEnd(rest, server);\n if (end < 1) continue;\n if (best === undefined || server.length > best.length) {\n best = server;\n bestEnd = end;\n tied = false;\n continue;\n }\n if (server.length === best.length) tied = true;\n }\n if (best === undefined || tied) return undefined;\n const available = __mcpServerTools[best] || [];\n return { server: best, tool: __resolveToolName(available, rest.slice(bestEnd)) };\n};\nconst __extensionBase = __providerProxy(\"extensions\", {}, __nameList(__proxyNames.extensions));\nglobalThis.extensions = new Proxy(__extensionBase, {\n get(target, property) {\n if (typeof property === \"symbol\") return target[property];\n const alias = __mcpAlias(String(property));\n if (alias && Object.prototype.hasOwnProperty.call(target, property) === false) {\n return (args = {}) => __call(\"mcp.\" + alias.server + \".\" + alias.tool, args);\n }\n return target[property];\n },\n});\nglobalThis.memory = __providerProxy(\"memory\", {\n walk: __memoryWalk,\n recall: (args = {}) => __call(\"memory.recall\", typeof args === \"string\" ? { query: args } : args),\n});\nglobalThis.state = __providerProxy(\"state\");\nglobalThis.schema = __providerProxy(\"schema\");\nglobalThis.components = __providerProxy(\"components\");\nglobalThis.compact = __providerProxy(\"compact\");\nglobalThis.codemap = __providerProxy(\"codemap\");\nglobalThis.judgment = __providerProxy(\"judgment\");\nconst __imagePromptArgs = (first, second) =>\n typeof first === \"string\" ? { prompt: first, ...(second ?? {}) } : { ...(first ?? {}) };\nconst __imageEditArgs = (first, second, third) => {\n if (typeof first === \"string\") {\n return { prompt: first, images: Array.isArray(second) ? second : [], ...(third ?? {}) };\n }\n const args = { ...(first ?? {}) };\n if (!Array.isArray(args.images)) args.images = Array.isArray(second) ? second : [];\n return args;\n};\nglobalThis.image = __providerProxy(\"image\", {\n generate: (first, second) => __call(\"image.generate\", __imagePromptArgs(first, second)),\n edit: (first, second, third) => __call(\"image.edit\", __imageEditArgs(first, second, third)),\n});\nconst __chunkBatchItems = (items, maxItems = 25, maxBytes = 49152) => {\n const chunks = [];\n let current = [];\n let currentBytes = 2;\n for (const item of items) {\n let serialized = \"\";\n try {\n serialized = JSON.stringify(item) ?? \"null\";\n } catch {\n serialized = JSON.stringify(String(item));\n }\n let stateItem = item;\n if (serialized.length > 40960) {\n stateItem = typeof item === \"string\"\n ? item.slice(0, 40000) + \" [truncated]\"\n : String(item).slice(0, 40000) + \" [truncated]\";\n serialized = JSON.stringify(stateItem);\n }\n const itemBytes = serialized.length + 1;\n if (current.length > 0 && (current.length >= maxItems || currentBytes + itemBytes > maxBytes)) {\n chunks.push(current);\n current = [];\n currentBytes = 2;\n }\n current.push({ item, stateItem });\n currentBytes += itemBytes;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n};\nconst __judgeAsk = (first, second) => {\n if (second !== undefined) {\n return globalThis.judgment.ask({ state: first, questions: second });\n }\n return globalThis.judgment.ask(first);\n};\nconst __judgeBool = async (state, instructions, options) => {\n try {\n const outcome = await globalThis.judgment.ask({\n state,\n questions: { q: { type: \"bool\", instructions: String(instructions) } },\n });\n if (outcome && outcome.ok && outcome.answers && outcome.answers.q && outcome.answers.q.type === \"bool\" && typeof outcome.answers.q.bool === \"number\") {\n return outcome.answers.q.bool;\n }\n } catch {}\n return options && typeof options.fallback === \"number\" ? options.fallback : undefined;\n};\nconst __judgeChoice = async (state, optionsListOrCriteria, instructions, config) => {\n let criteria = {};\n if (Array.isArray(optionsListOrCriteria)) {\n for (const opt of optionsListOrCriteria) criteria[String(opt)] = null;\n } else if (optionsListOrCriteria && typeof optionsListOrCriteria === \"object\") {\n criteria = optionsListOrCriteria;\n } else {\n throw new TypeError(\"judge.choice options must be an array or criteria object\");\n }\n if (Object.keys(criteria).length < 2) {\n throw new TypeError(\"judge.choice requires at least 2 unique options\");\n }\n try {\n const outcome = await globalThis.judgment.ask({\n state,\n questions: { q: { type: \"choice\", instructions: String(instructions), criteria } },\n });\n if (outcome && outcome.ok && outcome.answers && outcome.answers.q && outcome.answers.q.type === \"choice\" && typeof outcome.answers.q.choice === \"string\") {\n return outcome.answers.q.choice;\n }\n } catch {}\n return config && typeof config.fallback === \"string\" ? config.fallback : undefined;\n};\nconst __judgeScore = async (state, criteria, instructions, config) => {\n if (!Array.isArray(criteria) || criteria.length < 2) {\n throw new TypeError(\"judge.score requires at least 2 ordered criteria levels\");\n }\n try {\n const outcome = await globalThis.judgment.ask({\n state,\n questions: { q: { type: \"score\", instructions: String(instructions), criteria } },\n });\n if (outcome && outcome.ok && outcome.answers && outcome.answers.q && outcome.answers.q.type === \"score\" && typeof outcome.answers.q.score === \"number\") {\n return outcome.answers.q.score;\n }\n } catch {}\n return config && typeof config.fallback === \"number\" ? config.fallback : undefined;\n};\nconst __judgeFilter = async (items, instructions, options = {}) => {\n if (!Array.isArray(items) || items.length === 0) return [];\n const threshold = Number.isFinite(options.threshold) ? options.threshold : 0.7;\n const onFail = options.onFail || \"keep-all\";\n const chunks = __chunkBatchItems(items, options.maxItems || 25, options.maxBytes || 49152);\n const chunkPromises = chunks.map(async (chunk) => {\n const questions = {};\n chunk.forEach((_, idx) => {\n questions[\"item_\" + idx] = {\n type: \"bool\",\n instructions: \"Regarding items[\" + idx + \"]: \" + String(instructions),\n };\n });\n let outcome;\n try {\n outcome = await globalThis.judgment.ask({ state: { items: chunk.map((c) => c.stateItem) }, questions });\n } catch (err) {\n outcome = { ok: false, reason: \"failed\", detail: String(err && err.message ? err.message : err) };\n }\n if (!outcome || !outcome.ok) {\n if (onFail === \"throw\") {\n throw new Error(\"judge.filter failed: \" + (outcome && outcome.reason ? outcome.reason : \"unknown error\") + (outcome && outcome.detail ? \" (\" + outcome.detail + \")\" : \"\"));\n }\n return onFail === \"empty\" ? [] : chunk.map((c) => c.item);\n }\n return chunk\n .filter((_, idx) => {\n const ans = outcome.answers && outcome.answers[\"item_\" + idx];\n return ans && ans.type === \"bool\" && typeof ans.bool === \"number\" && ans.bool >= threshold;\n })\n .map((c) => c.item);\n });\n const results = await Promise.all(chunkPromises);\n return results.flat();\n};\nconst __judgeClassify = async (items, categories, instructions, options = {}) => {\n if (!Array.isArray(items) || items.length === 0) return [];\n if (!Array.isArray(categories) || categories.length < 2) {\n throw new TypeError(\"judge.classify requires at least 2 categories\");\n }\n const criteria = {};\n for (const cat of categories) criteria[String(cat)] = null;\n const onFail = options.onFail || \"keep-all\";\n const chunks = __chunkBatchItems(items, options.maxItems || 25, options.maxBytes || 49152);\n const chunkPromises = chunks.map(async (chunk) => {\n const questions = {};\n chunk.forEach((_, idx) => {\n questions[\"item_\" + idx] = {\n type: \"choice\",\n instructions: \"Regarding items[\" + idx + \"]: \" + String(instructions),\n criteria,\n };\n });\n let outcome;\n try {\n outcome = await globalThis.judgment.ask({ state: { items: chunk.map((c) => c.stateItem) }, questions });\n } catch (err) {\n outcome = { ok: false, reason: \"failed\", detail: String(err && err.message ? err.message : err) };\n }\n if (!outcome || !outcome.ok) {\n if (onFail === \"throw\") {\n throw new Error(\"judge.classify failed: \" + (outcome && outcome.reason ? outcome.reason : \"unknown error\") + (outcome && outcome.detail ? \" (\" + outcome.detail + \")\" : \"\"));\n }\n if (onFail === \"empty\") return [];\n return chunk.map((c) => ({ item: c.item, category: options.fallbackCategory, confidence: undefined }));\n }\n return chunk.map((c, idx) => {\n const ans = outcome.answers && outcome.answers[\"item_\" + idx];\n const category = ans && ans.type === \"choice\" && typeof ans.choice === \"string\" ? ans.choice : options.fallbackCategory;\n const confidence = ans && typeof ans.confidence === \"number\" ? ans.confidence : undefined;\n return { item: c.item, category, confidence };\n });\n });\n const results = await Promise.all(chunkPromises);\n return results.flat();\n};\nglobalThis.judge = Object.freeze({\n ask: __judgeAsk,\n bool: __judgeBool,\n choice: __judgeChoice,\n score: __judgeScore,\n filter: __judgeFilter,\n classify: __judgeClassify,\n});\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.\nconst __mcpServerTools = (() => {\n const raw = __proxyNames.mcp;\n const out = {};\n if (raw && typeof raw === \"object\") {\n for (const server of Object.keys(raw)) out[server] = __nameList(raw[server]);\n }\n return out;\n})();\nconst __mcpManagement = {\n servers: () => __call(\"mcp.$servers\", {}),\n reload: () => __call(\"mcp.$reload\", {}),\n register: (args) => __call(\"mcp.$register\", args),\n call: (args) => __call(\"mcp.$call\", args),\n};\nconst __nameKey = (name) => String(name).toLowerCase().replace(/[^a-z0-9]/g, \"\");\nconst __resolveToolName = (available, requested) => {\n const wanted = String(requested);\n if (available.indexOf(wanted) >= 0) return wanted;\n const key = __nameKey(wanted);\n const matches = available.filter((candidate) => __nameKey(candidate) === key);\n return matches.length === 1 ? matches[0] : wanted;\n};\nglobalThis.mcp = __lazyNamespace(\n Object.keys(__mcpServerTools).sort(),\n (server) => __lazyNamespace(\n __mcpServerTools[server] ? __mcpServerTools[server].slice().sort() : [],\n (tool) => (args = {}) => {\n const available = __mcpServerTools[server] ? __mcpServerTools[server] : [];\n return __call(\"mcp.\" + server + \".\" + __resolveToolName(available, tool), args);\n },\n ),\n __mcpManagement,\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 !== \"omp\") {\n throw new Error(\"rlm.query requires the OMP runner because recursive Fabric is unavailable in Claude Code\");\n }\n return __budgetedRun({ ...args, runner: \"omp\", 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); };\nconst __fabricSync = globalThis.__fabricSync;\ndelete globalThis.__fabricSync;\nconst __evaluate = eval;\nlet __webGlobalValues;\nfor (const name of [\"TextEncoder\", \"TextDecoder\", \"atob\", \"btoa\", \"URL\", \"URLSearchParams\", \"crypto\"]) {\n Object.defineProperty(globalThis, name, {\n get() {\n __webGlobalValues ??= __evaluate(__fabricSync(\"source\", \"\"))(__fabricSync);\n return __webGlobalValues[name];\n },\n set(value) {\n Object.defineProperty(globalThis, name, { value, writable: true, enumerable: false, configurable: true });\n },\n enumerable: false,\n configurable: true,\n });\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 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 = missingPayloadKeys(code, options.payloads);\n if (missingKeys.length > 0) {\n const provided = Object.keys(options.payloads ?? {});\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error:\n \"Pre-execution check: \" + missingKeys.map((key) => \"payloads.\" + 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 payloads.<key>.\"\n + \" For large or quote-heavy content, keep it in top-level payloads and reference payloads.<key> instead of escaping it inside code.\",\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();\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 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 (Date.now() <= executionDeadlineAt) return false;\n interruptedByDeadline = true;\n return true;\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(new Error(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 runtime.executePendingJobs();\n };\n\n const timeoutMessage = (): string =>\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 if (timeout) clearTimeout(timeout);\n timeout = setTimeout(expireDeadline, 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 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 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 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 const ms = Math.max(0, Number(args.ms ?? 0));\n const timer = setTimeout(() => {\n if (closing || promise.alive === false) return;\n promise.resolve(context.undefined);\n runtime.executePendingJobs();\n }, ms);\n timer.unref?.();\n pendingTimers.add(timer);\n void promise.settled.then(() => pendingTimers.delete(timer));\n return promise.handle;\n }\n const task = runAbortable(hostAbortController.signal, () =>\n hostCall(reference, args, hostAbortController.signal),\n )\n .then((value) => {\n if (closing || promise.alive === false) return;\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 const errorHandle = context.newError(\n error instanceof Error ? error.message : String(error),\n );\n const exit = reference === \"omp.bash\"\n ? ompBashExitMetadata(error)\n : undefined;\n if (exit) {\n const metadata = jsonHandle(context, jsonObject, jsonParse, exit);\n context.setProp(errorHandle, \"__fabricBashExit\", metadata);\n metadata.dispose();\n }\n promise.reject(errorHandle);\n errorHandle.dispose();\n })\n .finally(() => {\n if (!closing) runtime.executePendingJobs();\n });\n hostTasks.add(task);\n void task.finally(() => hostTasks.delete(task));\n return promise.handle;\n },\n );\n context.setProp(context.global, \"__fabricHostCall\", hostFunction);\n hostFunction.dispose();\n\n const syncFunction = context.newFunction(\n \"__fabricSync\",\n (operationHandle: any, argsHandle: any) => {\n const operation = context.getString(operationHandle);\n return context.newString(\n operation === \"source\" ? GUEST_WEB_GLOBALS_SOURCE : fabricSyncCall(operation, context.getString(argsHandle)),\n );\n },\n );\n context.setProp(context.global, \"__fabricSync\", syncFunction);\n syncFunction.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(\"[OMP 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 payloads = jsonHandle(context, jsonObject, jsonParse, options.payloads ?? {});\n context.setProp(context.global, \"payloads\", payloads);\n payloads.dispose();\n const proxyNames = jsonHandle(\n context,\n jsonObject,\n jsonParse,\n options.proxyNames ?? {},\n );\n context.setProp(context.global, \"__fabricProxyNames\", proxyNames);\n proxyNames.dispose();\n const tokenBudget = context.newNumber(options.tokenBudget ?? Number.POSITIVE_INFINITY);\n context.setProp(context.global, \"__fabricTokenBudget\", tokenBudget);\n tokenBudget.dispose();\n\n const setupResult = context.evalCode(GUEST_SETUP, \"omp-fabric-setup.js\");\n if (setupResult.error) {\n const deadlineExceeded = interruptedByDeadline || 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\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([${OMP_GUEST_ENTRYPOINT}(), globalThis.__fabricExecutionGate])`;\n const evaluation = context.evalCode(wrappedCode, \"omp-fabric-guest.js\");\n runtime.executePendingJobs();\n if (evaluation.error) {\n const deadlineExceeded = interruptedByDeadline || 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 pendingResolution = context.resolvePromise(activePromiseHandle);\n runtime.executePendingJobs();\n const resolution = await Promise.race([pendingResolution, deadline, cancellation]);\n pendingResolution = undefined;\n activePromiseHandle.dispose();\n activePromiseHandle = undefined;\n if (resolution.error) {\n const deadlineExceeded = timedOut || interruptedByDeadline || 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 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 const value = context.dump(resolution.value);\n resolution.value.dispose();\n return { value, logs, terminationReason: \"completed\" };\n } catch (error) {\n const deadlineExceeded = timedOut || interruptedByDeadline || 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 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 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 runtime.executePendingJobs();\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(new Error(cleanupMessage));\n rejectExecutionGate(cleanupMessage);\n const errorHandle = context.newError(cleanupMessage);\n for (const promise of pendingHostPromises) promise.reject(errorHandle);\n errorHandle.dispose();\n runtime.executePendingJobs();\n await new Promise((resolve) => setImmediate(resolve));\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 runtime.executePendingJobs();\n jsonParse.dispose();\n jsonObject.dispose();\n disposeQuickJsContext(context);\n }\n }\n}\n", "// Stack frames captured from the executed guest bundle reference the emitted\n// omp-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 = /omp-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(\"omp-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", "import * as nodeCrypto from \"node:crypto\";\nimport { runInThisContext } from \"node:vm\";\n\ntype FabricSyncCall = (operation: string, argsJson: string) => string;\n\nexport const FABRIC_SYNC_FACTORY_SOURCE = String.raw`((nodeCrypto) => {\n const digestNames = { \"SHA-1\": \"sha1\", \"SHA-256\": \"sha256\", \"SHA-384\": \"sha384\", \"SHA-512\": \"sha512\" };\n const urlProperties = [\"href\", \"protocol\", \"username\", \"password\", \"host\", \"hostname\", \"port\", \"pathname\", \"search\", \"hash\"];\n const failure = (name, message) => Object.assign(new Error(message), { name });\n const canonicalHash = (name) => {\n const canonical = String(name ?? \"\").toUpperCase();\n if (!Object.prototype.hasOwnProperty.call(digestNames, canonical)) {\n throw failure(\"NotSupportedError\", \"Unrecognized digest algorithm: \" + name + \". fabric_exec supports SHA-1, SHA-256, SHA-384 and SHA-512.\");\n }\n return canonical;\n };\n const bytes = (hex) => Buffer.from(typeof hex === \"string\" ? hex : \"\", \"hex\");\n const hmac = (hash, key, data) =>\n nodeCrypto.createHmac(digestNames[canonicalHash(hash)], bytes(key)).update(bytes(data)).digest();\n const urlParts = (url) => {\n const parts = { origin: url.origin };\n for (const property of urlProperties) parts[property] = url[property];\n return parts;\n };\n const operations = {\n random: ({ length }) => nodeCrypto.randomBytes(Math.min(Math.max(Math.trunc(Number(length)) || 0, 0), 65536)).toString(\"hex\"),\n uuid: () => nodeCrypto.randomUUID(),\n hashName: ({ algorithm }) => canonicalHash(algorithm),\n digest: ({ algorithm, data }) =>\n nodeCrypto.createHash(digestNames[canonicalHash(algorithm)]).update(bytes(data)).digest(\"hex\"),\n hmac: ({ hash, key, data }) => hmac(hash, key, data).toString(\"hex\"),\n hmacVerify: ({ hash, key, data, signature }) => {\n const expected = hmac(hash, key, data);\n const actual = bytes(signature);\n return expected.length === actual.length && nodeCrypto.timingSafeEqual(expected, actual);\n },\n utf8Encode: ({ text }) => Buffer.from(String(text), \"utf8\").toString(\"hex\"),\n utf8Decode: ({ data, fatal, ignoreBOM }) =>\n new TextDecoder(\"utf-8\", { fatal: fatal === true, ignoreBOM: ignoreBOM === true }).decode(bytes(data)),\n atob: ({ data }) => atob(data),\n btoa: ({ data }) => btoa(data),\n url: ({ input, base }) => urlParts(base === undefined ? new URL(input) : new URL(input, base)),\n urlSet: ({ href, property, value }) => {\n if (urlProperties.indexOf(property) < 0) throw new TypeError(\"URL has no settable property \" + property);\n const url = new URL(href);\n url[property] = value;\n return urlParts(url);\n },\n searchParse: ({ init }) => Array.from(new URLSearchParams(init)),\n searchSerialize: ({ pairs }) => new URLSearchParams(pairs).toString(),\n };\n return (operation, argsJson) => {\n try {\n if (!Object.prototype.hasOwnProperty.call(operations, operation)) {\n throw new TypeError(\"Unknown fabric sync operation \" + operation);\n }\n return JSON.stringify({ ok: true, value: operations[operation](JSON.parse(argsJson)) });\n } catch (error) {\n return JSON.stringify({\n ok: false,\n name: error && typeof error.name === \"string\" ? error.name : \"Error\",\n message: error && typeof error.message === \"string\" ? error.message : String(error),\n });\n }\n };\n})`;\n\nlet fabricSync: FabricSyncCall | undefined;\n\nexport const fabricSyncCall: FabricSyncCall = (operation, argsJson) => {\n fabricSync ??= (runInThisContext(FABRIC_SYNC_FACTORY_SOURCE) as (crypto: typeof nodeCrypto) => FabricSyncCall)(nodeCrypto);\n return fabricSync(operation, argsJson);\n};\n", "export const GUEST_WEB_GLOBALS_SOURCE = String.raw`(__fabricSync) => {\n const __namedError = (ErrorType, name, message) => {\n const error = new ErrorType(message);\n if (error.name !== name) error.name = name;\n return error;\n };\n const __syncCall = (operation, args) => {\n const reply = JSON.parse(__fabricSync(operation, JSON.stringify(args)));\n if (reply.ok) return reply.value;\n const ErrorType = reply.name === \"TypeError\" ? TypeError : reply.name === \"RangeError\" ? RangeError : Error;\n throw __namedError(ErrorType, reply.name, reply.message);\n };\n const __hexByte = Array.from({ length: 256 }, (_, value) => (value < 16 ? \"0\" : \"\") + value.toString(16));\n const __toHex = (bytes) => {\n const chunks = [];\n const parts = [];\n for (let start = 0; start < bytes.length; start += 8192) {\n const end = Math.min(start + 8192, bytes.length);\n parts.length = end - start;\n for (let index = start; index < end; index++) parts[index - start] = __hexByte[bytes[index]];\n chunks.push(parts.join(\"\"));\n }\n return chunks.join(\"\");\n };\n const __fromHex = (hex) => {\n const bytes = new Uint8Array(hex.length / 2);\n for (let index = 0; index < bytes.length; index++) bytes[index] = parseInt(hex.substr(index * 2, 2), 16);\n return bytes;\n };\n const __bufferBytes = (input, label) => {\n if (input instanceof ArrayBuffer) return new Uint8Array(input);\n if (ArrayBuffer.isView(input)) return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);\n throw new TypeError(label + \" must be an ArrayBuffer, a typed array or a DataView\");\n };\n const __utf8Write = (destination, offset, code) => {\n if (code < 0x80) {\n destination[offset] = code;\n } else if (code < 0x800) {\n destination[offset] = 0xc0 | (code >> 6);\n destination[offset + 1] = 0x80 | (code & 63);\n } else if (code < 0x10000) {\n destination[offset] = 0xe0 | (code >> 12);\n destination[offset + 1] = 0x80 | ((code >> 6) & 63);\n destination[offset + 2] = 0x80 | (code & 63);\n } else {\n destination[offset] = 0xf0 | (code >> 18);\n destination[offset + 1] = 0x80 | ((code >> 12) & 63);\n destination[offset + 2] = 0x80 | ((code >> 6) & 63);\n destination[offset + 3] = 0x80 | (code & 63);\n }\n };\n class TextEncoder {\n get encoding() { return \"utf-8\"; }\n encode(input = \"\") {\n return __fromHex(__syncCall(\"utf8Encode\", { text: String(input) }));\n }\n encodeInto(source, destination) {\n let read = 0;\n let written = 0;\n for (const char of String(source)) {\n const point = char.codePointAt(0);\n const code = point >= 0xd800 && point <= 0xdfff ? 0xfffd : point;\n const size = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;\n if (written + size > destination.length) break;\n __utf8Write(destination, written, code);\n written += size;\n read += char.length;\n }\n return { read, written };\n }\n }\n const __utf8Labels = [\"utf-8\", \"utf8\", \"unicode-1-1-utf-8\", \"unicode11utf8\", \"unicode20utf8\", \"x-unicode20utf8\"];\n const __decoderOptions = new WeakMap();\n class TextDecoder {\n constructor(label = \"utf-8\", options = {}) {\n if (__utf8Labels.indexOf(String(label).trim().toLowerCase()) < 0) {\n throw new RangeError(\"The encoding \" + String(label) + \" is not supported; fabric_exec TextDecoder decodes UTF-8 only\");\n }\n __decoderOptions.set(this, {\n fatal: Boolean(options && options.fatal),\n ignoreBOM: Boolean(options && options.ignoreBOM),\n });\n }\n get encoding() { return \"utf-8\"; }\n get fatal() { return __decoderOptions.get(this).fatal; }\n get ignoreBOM() { return __decoderOptions.get(this).ignoreBOM; }\n decode(input, options) {\n if (options && options.stream) {\n throw new TypeError(\"TextDecoder stream mode is not available in fabric_exec; decode the complete buffer\");\n }\n if (input === undefined) return \"\";\n const settings = __decoderOptions.get(this);\n return __syncCall(\"utf8Decode\", {\n data: __toHex(__bufferBytes(input, \"TextDecoder.decode input\")),\n fatal: settings.fatal,\n ignoreBOM: settings.ignoreBOM,\n });\n }\n }\n const atob = (data) => __syncCall(\"atob\", { data: String(data) });\n const btoa = (data) => __syncCall(\"btoa\", { data: String(data) });\n const __searchState = new WeakMap();\n const __searchList = (params) => __searchState.get(params).list;\n const __searchChanged = (params) => {\n const owner = __searchState.get(params).url;\n if (owner) owner.search = params.toString();\n };\n class URLSearchParams {\n constructor(init = \"\") {\n let list = [];\n if (init instanceof URLSearchParams) {\n list = __searchList(init).map((pair) => [pair[0], pair[1]]);\n } else if (typeof init === \"object\" && init !== null) {\n if (typeof init[Symbol.iterator] === \"function\") {\n for (const pair of init) {\n const items = Array.from(pair);\n if (items.length !== 2) throw new TypeError(\"Each URLSearchParams init pair must have exactly two items\");\n list.push([String(items[0]), String(items[1])]);\n }\n } else {\n for (const key of Object.keys(init)) list.push([key, String(init[key])]);\n }\n } else {\n list = __syncCall(\"searchParse\", { init: String(init) });\n }\n __searchState.set(this, { list, url: undefined });\n }\n get size() { return __searchList(this).length; }\n append(name, value) {\n __searchList(this).push([String(name), String(value)]);\n __searchChanged(this);\n }\n delete(name, value) {\n const key = String(name);\n const state = __searchState.get(this);\n state.list = state.list.filter((pair) => pair[0] !== key || (value !== undefined && pair[1] !== String(value)));\n __searchChanged(this);\n }\n get(name) {\n const key = String(name);\n const pair = __searchList(this).find((entry) => entry[0] === key);\n return pair ? pair[1] : null;\n }\n getAll(name) {\n const key = String(name);\n return __searchList(this).filter((pair) => pair[0] === key).map((pair) => pair[1]);\n }\n has(name, value) {\n const key = String(name);\n return __searchList(this).some((pair) => pair[0] === key && (value === undefined || pair[1] === String(value)));\n }\n set(name, value) {\n const key = String(name);\n const state = __searchState.get(this);\n const index = state.list.findIndex((pair) => pair[0] === key);\n if (index < 0) {\n state.list.push([key, String(value)]);\n } else {\n state.list[index] = [key, String(value)];\n state.list = state.list.filter((pair, position) => position <= index || pair[0] !== key);\n }\n __searchChanged(this);\n }\n sort() {\n __searchList(this).sort((left, right) => (left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0));\n __searchChanged(this);\n }\n forEach(callback, thisArg) {\n for (const pair of __searchList(this).slice()) callback.call(thisArg, pair[1], pair[0], this);\n }\n keys() { return __searchList(this).map((pair) => pair[0])[Symbol.iterator](); }\n values() { return __searchList(this).map((pair) => pair[1])[Symbol.iterator](); }\n entries() { return __searchList(this).map((pair) => [pair[0], pair[1]])[Symbol.iterator](); }\n [Symbol.iterator]() { return this.entries(); }\n toString() { return __syncCall(\"searchSerialize\", { pairs: __searchList(this) }); }\n }\n const __urlState = new WeakMap();\n const __urlApply = (url, parts) => {\n const state = __urlState.get(url);\n state.parts = parts;\n if (state.params) __searchState.get(state.params).list = __syncCall(\"searchParse\", { init: parts.search });\n };\n class URL {\n constructor(url, base) {\n const parts = __syncCall(\n \"url\",\n base === undefined ? { input: String(url) } : { input: String(url), base: String(base) },\n );\n __urlState.set(this, { parts, params: undefined });\n }\n static canParse(url, base) {\n try {\n new URL(url, base);\n return true;\n } catch {\n return false;\n }\n }\n get origin() { return __urlState.get(this).parts.origin; }\n get searchParams() {\n const state = __urlState.get(this);\n if (!state.params) {\n state.params = new URLSearchParams(state.parts.search);\n __searchState.get(state.params).url = this;\n }\n return state.params;\n }\n toString() { return this.href; }\n toJSON() { return this.href; }\n }\n for (const property of [\"href\", \"protocol\", \"username\", \"password\", \"host\", \"hostname\", \"port\", \"pathname\", \"search\", \"hash\"]) {\n Object.defineProperty(URL.prototype, property, {\n get() { return __urlState.get(this).parts[property]; },\n set(value) {\n __urlApply(this, __syncCall(\"urlSet\", { href: this.href, property, value: String(value) }));\n },\n enumerable: true,\n configurable: true,\n });\n }\n const __cryptoKeys = new WeakMap();\n const __settle = (run) => {\n try {\n return Promise.resolve(run());\n } catch (error) {\n return Promise.reject(error);\n }\n };\n const __algorithmName = (algorithm) =>\n typeof algorithm === \"string\" ? algorithm : algorithm && typeof algorithm.name === \"string\" ? algorithm.name : \"\";\n const __requireHmac = (algorithm) => {\n if (__algorithmName(algorithm).toUpperCase() !== \"HMAC\") {\n throw __namedError(Error, \"NotSupportedError\", \"fabric_exec crypto.subtle signs with HMAC only, got \" + __algorithmName(algorithm));\n }\n };\n const __hmacSecret = (key, usage) => {\n const secret = __cryptoKeys.get(key);\n if (secret === undefined) throw new TypeError(\"key must be a CryptoKey returned by crypto.subtle.importKey\");\n if (key.usages.indexOf(usage) < 0) {\n throw __namedError(Error, \"InvalidAccessError\", \"CryptoKey usages do not include \" + usage);\n }\n return secret;\n };\n const __unsupportedSubtle = (name) => () => Promise.reject(__namedError(\n Error,\n \"NotSupportedError\",\n \"crypto.subtle.\" + name + \" is not available in fabric_exec, which provides digest plus HMAC importKey, sign and verify; run other algorithms through omp.bash with openssl\",\n ));\n const __subtle = Object.freeze({\n digest: (algorithm, data) => __settle(() =>\n __fromHex(__syncCall(\"digest\", {\n algorithm: __algorithmName(algorithm),\n data: __toHex(__bufferBytes(data, \"crypto.subtle.digest data\")),\n })).buffer),\n importKey: (format, keyData, algorithm, extractable, keyUsages) => __settle(() => {\n if (format !== \"raw\") {\n throw __namedError(Error, \"NotSupportedError\", \"fabric_exec crypto.subtle.importKey accepts the raw format only, got \" + String(format));\n }\n __requireHmac(algorithm);\n const usages = Array.from(keyUsages ?? []);\n if (usages.length === 0) throw __namedError(Error, \"SyntaxError\", \"HMAC keys need at least one usage\");\n for (const usage of usages) {\n if (usage !== \"sign\" && usage !== \"verify\") {\n throw __namedError(Error, \"SyntaxError\", \"HMAC key usages must be sign or verify, got \" + String(usage));\n }\n }\n const bytes = __bufferBytes(keyData, \"crypto.subtle.importKey keyData\");\n if (bytes.length === 0) throw __namedError(Error, \"DataError\", \"HMAC key data must not be empty\");\n const hash = __syncCall(\"hashName\", { algorithm: __algorithmName(algorithm.hash) });\n const key = Object.freeze({\n type: \"secret\",\n extractable: Boolean(extractable),\n algorithm: Object.freeze({ name: \"HMAC\", hash: Object.freeze({ name: hash }), length: bytes.length * 8 }),\n usages: Object.freeze(usages),\n });\n __cryptoKeys.set(key, __toHex(bytes));\n return key;\n }),\n sign: (algorithm, key, data) => __settle(() => {\n __requireHmac(algorithm);\n return __fromHex(__syncCall(\"hmac\", {\n hash: key.algorithm.hash.name,\n key: __hmacSecret(key, \"sign\"),\n data: __toHex(__bufferBytes(data, \"crypto.subtle.sign data\")),\n })).buffer;\n }),\n verify: (algorithm, key, signature, data) => __settle(() => {\n __requireHmac(algorithm);\n return __syncCall(\"hmacVerify\", {\n hash: key.algorithm.hash.name,\n key: __hmacSecret(key, \"verify\"),\n signature: __toHex(__bufferBytes(signature, \"crypto.subtle.verify signature\")),\n data: __toHex(__bufferBytes(data, \"crypto.subtle.verify data\")),\n });\n }),\n encrypt: __unsupportedSubtle(\"encrypt\"),\n decrypt: __unsupportedSubtle(\"decrypt\"),\n generateKey: __unsupportedSubtle(\"generateKey\"),\n deriveKey: __unsupportedSubtle(\"deriveKey\"),\n deriveBits: __unsupportedSubtle(\"deriveBits\"),\n exportKey: __unsupportedSubtle(\"exportKey\"),\n wrapKey: __unsupportedSubtle(\"wrapKey\"),\n unwrapKey: __unsupportedSubtle(\"unwrapKey\"),\n });\n const __integerArray = (array) =>\n ArrayBuffer.isView(array)\n && !(array instanceof DataView)\n && !(array instanceof Float32Array)\n && !(array instanceof Float64Array);\n const crypto = Object.freeze({\n subtle: __subtle,\n randomUUID: () => __syncCall(\"uuid\", {}),\n getRandomValues: (array) => {\n if (!__integerArray(array)) {\n throw __namedError(TypeError, \"TypeMismatchError\", \"crypto.getRandomValues needs an integer typed array\");\n }\n if (array.byteLength > 65536) {\n throw __namedError(Error, \"QuotaExceededError\", \"crypto.getRandomValues fills at most 65536 bytes per call\");\n }\n new Uint8Array(array.buffer, array.byteOffset, array.byteLength)\n .set(__fromHex(__syncCall(\"random\", { length: array.byteLength })));\n return array;\n },\n });\n return { TextEncoder, TextDecoder, atob, btoa, URL, URLSearchParams, crypto };\n}`;\n"],
5
+ "mappings": ";;;;;;;;;;;;;AAAA,OAAO,wBAAwB;AAC/B,SAAS,uCAAuC;AAChD,OAAO,QAAQ;;;ACsBf,IAAM,iBAAiB,MAAM;AAC3B,QAAM,WAAW;AACjB,QAAM,QAAQ,oBAAI,IAAoB;AACtC,WAAS,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GAAG;AACvD,UAAM,IAAI,SAAS,KAAK,GAAa,KAAK;AAAA,EAC5C;AACA,SAAO;AACT,GAAG;AAEH,IAAM,mBAAmB,CAAC,YAA8B;AACtD,QAAM,SAAmB,CAAC;AAC1B,MAAI,QAAQ;AACZ,SAAO,QAAQ,QAAQ,QAAQ;AAC7B,QAAI,QAAQ;AACZ,QAAI,QAAQ;AACZ,QAAI,eAAe;AACnB,WAAO,cAAc;AACnB,YAAM,QAAQ,cAAc,IAAI,QAAQ,KAAK,CAAW;AACxD,UAAI,UAAU,OAAW,QAAO;AAChC,eAAS;AACT,sBAAgB,QAAQ,QAAQ;AAChC,gBAAU,QAAQ,MAAM,KAAK;AAC7B,eAAS;AAAA,IACX;AACA,WAAO,MAAM,QAAQ,OAAO,IAAI,EAAE,SAAS,KAAK,SA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W;AACrE,oBAAY,QAAQ;AACpB,gBAAQ,mBAAmB;AAC3B,cAAM,IAAI,QAAQ,CAAC,YAAY,aAAa,OAAO,CAAC;AACpD,cAAM,UAAU,MAAM,QAAQ,KAAU;AAAA,UACtC,oBAAoB,kBAAkB,MAAM,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,cAAQ,mBAAmB;AAC3B,gBAAU,QAAQ;AAClB,iBAAW,QAAQ;AACnB,4BAAsB,OAAO;AAAA,IAC/B;AAAA,EACF;AACF;",
6
+ "names": ["value"]
7
+ }
@@ -7004,4 +7004,4 @@ export {
7004
7004
  agentParticipantRecords,
7005
7005
  actorParticipantRecord
7006
7006
  };
7007
- //# sourceMappingURL=chunk-2T6EHZ5G.js.map
7007
+ //# sourceMappingURL=chunk-S3URDR4K.js.map
@@ -97,7 +97,7 @@ import {
97
97
  resolveAgentCwd,
98
98
  resolveOmpBinary,
99
99
  validateAgentCwdRequest
100
- } from "./chunks/chunk-2T6EHZ5G.js";
100
+ } from "./chunks/chunk-S3URDR4K.js";
101
101
  import "./chunks/chunk-VPPIJRNZ.js";
102
102
  import {
103
103
  executeFile,
@@ -8504,6 +8504,43 @@ import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
8504
8504
  import os from "node:os";
8505
8505
  import path10 from "node:path";
8506
8506
  var IMAGE_MODEL_API = /image|imagen|dall-e|flux|stable-diffusion|sdxl|seedream|kolors|wanx|cogview|recraft|ideogram|midjourney|horde|banana/i;
8507
+ var MUSE_IMAGE = /(^|\/)muse-image/i;
8508
+ var MUSE_MAX_COUNT = 10;
8509
+ var DEFAULT_MAX_COUNT = 4;
8510
+ var MUSE_OUTPUT_FORMATS = ["png", "jpeg", "webp"];
8511
+ var MUSE_REASONING_STRENGTHS = ["low", "high"];
8512
+ var MUSE_TOOL_SWITCHES = {
8513
+ imageSearch: "enable_image_search",
8514
+ webSearch: "enable_web_search",
8515
+ shell: "enable_shell"
8516
+ };
8517
+ var sizeProperty = {
8518
+ type: "string",
8519
+ pattern: "^[1-9][0-9]*x[1-9][0-9]*$",
8520
+ description: "Pixel size WxH for gateways that accept an images-API size field. gpt-image takes 1024x1024, 1536x1024 or 1024x1536; Muse (muse-image-*) keeps only the ratio and renders at its own resolution."
8521
+ };
8522
+ var museProperties = {
8523
+ outputFormat: {
8524
+ type: "string",
8525
+ enum: [...MUSE_OUTPUT_FORMATS],
8526
+ description: "Muse only: encoding of the returned image. Muse defaults to webp."
8527
+ },
8528
+ reasoningStrength: {
8529
+ type: "string",
8530
+ enum: [...MUSE_REASONING_STRENGTHS],
8531
+ description: "Muse only: low returns after one pass; high, the Muse default, refines over several passes."
8532
+ },
8533
+ toolEnablement: {
8534
+ type: "object",
8535
+ additionalProperties: false,
8536
+ properties: {
8537
+ imageSearch: { type: "boolean", description: "Muse image search for visual references." },
8538
+ webSearch: { type: "boolean", description: "Muse web search for current facts." },
8539
+ shell: { type: "boolean", description: "Muse code execution for charts and layouts." }
8540
+ },
8541
+ description: "Muse only: set a switch to false to turn that built-in tool off. Omitted switches stay on."
8542
+ }
8543
+ };
8507
8544
  var generateSchema = {
8508
8545
  type: "object",
8509
8546
  additionalProperties: false,
@@ -8516,15 +8553,15 @@ var generateSchema = {
8516
8553
  },
8517
8554
  aspectRatio: {
8518
8555
  type: "string",
8519
- description: "Aspect ratio forwarded as aspect_ratio or imageConfig.aspectRatio, e.g. 1:1, 16:9, 9:16."
8556
+ description: "Aspect ratio such as 1:1, 16:9, 9:16. Forwarded as aspect_ratio or imageConfig.aspectRatio; Muse receives it as a WxH size."
8520
8557
  },
8521
- size: {
8522
- type: "string",
8523
- enum: ["1024x1024", "1536x1024", "1024x1536"],
8524
- description: "Pixel size for gateways that accept an images-API size field."
8558
+ size: sizeProperty,
8559
+ count: {
8560
+ type: "number",
8561
+ description: "Images to request from one model: up to 10 for Muse, up to 4 elsewhere. Only the images API honours more than one."
8525
8562
  },
8526
- count: { type: "number", description: "Images to request from one model; only the images API honours more than one." },
8527
- saveTo: { type: "string", description: "Absolute or cwd-relative file path for a single image." }
8563
+ saveTo: { type: "string", description: "Absolute or cwd-relative file path for a single image." },
8564
+ ...museProperties
8528
8565
  }
8529
8566
  };
8530
8567
  var editSchema = {
@@ -8540,13 +8577,13 @@ var editSchema = {
8540
8577
  items: { type: "string" }
8541
8578
  },
8542
8579
  model: { type: "string", description: "Optional provider/id to try first." },
8543
- aspectRatio: { type: "string", description: "Aspect ratio forwarded to the backend." },
8544
- size: {
8580
+ aspectRatio: {
8545
8581
  type: "string",
8546
- enum: ["1024x1024", "1536x1024", "1024x1536"],
8547
- description: "Pixel size for gateways that accept an images-API size field."
8582
+ description: "Aspect ratio forwarded to the backend; Muse receives it as a WxH size."
8548
8583
  },
8549
- saveTo: { type: "string", description: "Absolute or cwd-relative file path for a single image." }
8584
+ size: sizeProperty,
8585
+ saveTo: { type: "string", description: "Absolute or cwd-relative file path for a single image." },
8586
+ ...museProperties
8550
8587
  }
8551
8588
  };
8552
8589
  var modelsSchema = { type: "object", additionalProperties: false, properties: {} };
@@ -8559,7 +8596,7 @@ var descriptors2 = [
8559
8596
  },
8560
8597
  {
8561
8598
  name: "edit",
8562
- description: "Edit existing images with a prompt. Tries each configured model in priority order and returns the first success or { ok: false, reason, failures }. Source images travel in the shape each dialect expects: input_references or image/images for the images API, image_url parts for chat, input_image for responses, inlineData for gemini.",
8599
+ description: "Edit existing images with a prompt. Tries each configured model in priority order and returns the first success or { ok: false, reason, failures }. Source images travel in the shape each dialect expects: input_references or image/images for the images API, images[].image_url for Muse, image_url parts for chat, input_image for responses, inlineData for gemini.",
8563
8600
  inputSchema: editSchema,
8564
8601
  risk: "write"
8565
8602
  },
@@ -8579,6 +8616,7 @@ var splitModelSelector = (selector) => {
8579
8616
  var inferImageDialect = (api, modelId) => {
8580
8617
  if (api === "openai-images" || api === "openrouter-images") return "images";
8581
8618
  if (api === "google-generative-ai") return "gemini";
8619
+ if (MUSE_IMAGE.test(modelId)) return "images";
8582
8620
  if (api === "openai-responses" || api === "openai-codex-responses") {
8583
8621
  return IMAGE_MODEL_API.test(modelId) ? "images" : "responses";
8584
8622
  }
@@ -8809,7 +8847,46 @@ var resolveImageSize = (aspectRatio, size) => {
8809
8847
  return void 0;
8810
8848
  }
8811
8849
  };
8850
+ var MUSE_LONG_SIDE = 1024;
8851
+ var museSizeForRatio = (aspectRatio) => {
8852
+ const match = /^\s*(\d+(?:\.\d+)?)\s*:\s*(\d+(?:\.\d+)?)\s*$/.exec(aspectRatio);
8853
+ if (!match) return void 0;
8854
+ const width = Number(match[1]);
8855
+ const height = Number(match[2]);
8856
+ if (!(width > 0 && height > 0)) return void 0;
8857
+ if (width >= height) return `${MUSE_LONG_SIDE}x${Math.max(1, Math.round(MUSE_LONG_SIDE * height / width))}`;
8858
+ return `${Math.max(1, Math.round(MUSE_LONG_SIDE * width / height))}x${MUSE_LONG_SIDE}`;
8859
+ };
8860
+ var resolveMuseSize = (aspectRatio, size) => {
8861
+ if (size !== void 0) return size;
8862
+ return aspectRatio === void 0 ? void 0 : museSizeForRatio(aspectRatio);
8863
+ };
8864
+ var SIZE_PATTERN = /^(\d+)x(\d+)$/;
8865
+ var ratioHonoured = (requested, width, height) => {
8866
+ const match = SIZE_PATTERN.exec(requested);
8867
+ if (!match || height === 0) return false;
8868
+ const wanted = Number(match[1]) / Number(match[2]);
8869
+ return Math.abs(width / height - wanted) <= wanted * 0.01;
8870
+ };
8871
+ var requestMuse = async (env, model, options) => {
8872
+ const body = {
8873
+ model: model.id,
8874
+ prompt: options.prompt,
8875
+ n: options.count,
8876
+ response_format: "b64_json"
8877
+ };
8878
+ const size = resolveMuseSize(options.aspectRatio, options.size);
8879
+ if (size !== void 0) body.size = size;
8880
+ if (options.outputFormat !== void 0) body.output_format = options.outputFormat;
8881
+ if (options.reasoningStrength !== void 0) body.reasoning_strength = options.reasoningStrength;
8882
+ if (options.toolEnablement !== void 0) body.tool_enablement = options.toolEnablement;
8883
+ const editing = options.inputImages.length > 0;
8884
+ if (editing) body.images = options.inputImages.map((image) => ({ image_url: dataUrl(image) }));
8885
+ const { payload } = await postJson(env, joinUrl(env.baseUrl, editing ? "/images/edits" : "/images/generations"), body);
8886
+ return parseImagesApiPayload(payload);
8887
+ };
8812
8888
  var requestImages = async (env, model, options) => {
8889
+ if (model.muse) return requestMuse(env, model, options);
8813
8890
  const openrouter = model.api === "openrouter-images";
8814
8891
  const body = { model: model.id, prompt: options.prompt, n: options.count };
8815
8892
  if (!model.gptImage) body.response_format = "b64_json";
@@ -8962,11 +9039,27 @@ var ignoredParams = (input) => {
8962
9039
  if (input.size !== void 0) ignored.push("size");
8963
9040
  } else if (input.dialect === "responses" && input.aspectRatio !== void 0 && resolveImageSize(input.aspectRatio, void 0) === void 0) {
8964
9041
  ignored.push("aspectRatio");
9042
+ } else if (input.muse && input.size === void 0 && input.aspectRatio !== void 0 && museSizeForRatio(input.aspectRatio) === void 0) {
9043
+ ignored.push("aspectRatio");
8965
9044
  }
8966
9045
  if (input.dialect !== "images" && input.count > 1) ignored.push("count");
9046
+ if (!input.muse) {
9047
+ if (input.outputFormat !== void 0) ignored.push("outputFormat");
9048
+ if (input.reasoningStrength !== void 0) ignored.push("reasoningStrength");
9049
+ if (input.toolEnablement !== void 0) ignored.push("toolEnablement");
9050
+ }
8967
9051
  if (input.saveTo !== void 0 && input.returned > 1) ignored.push("saveTo");
8968
9052
  return ignored;
8969
9053
  };
9054
+ var museToolEnablement = (value) => {
9055
+ if (!isRecord3(value)) return void 0;
9056
+ const switches = {};
9057
+ for (const [name, field] of Object.entries(MUSE_TOOL_SWITCHES)) {
9058
+ const setting = value[name];
9059
+ if (typeof setting === "boolean") switches[field] = setting;
9060
+ }
9061
+ return Object.keys(switches).length > 0 ? switches : void 0;
9062
+ };
8970
9063
  var transient = (error) => {
8971
9064
  const status = error?.status;
8972
9065
  if (typeof status === "number") return status >= 500 || status === 408 || status === 409 || status === 429;
@@ -9029,7 +9122,8 @@ var ImageProvider = class {
9029
9122
  baseUrl,
9030
9123
  gptImage: GPT_IMAGE_FAMILY.test(parsed.id),
9031
9124
  codex: api === "openai-codex-responses",
9032
- xai: parsed.provider === "xai" || parsed.provider === "xai-oauth" || parsed.provider.startsWith("xai-")
9125
+ xai: parsed.provider === "xai" || parsed.provider === "xai-oauth" || parsed.provider.startsWith("xai-"),
9126
+ muse: MUSE_IMAGE.test(parsed.id)
9033
9127
  };
9034
9128
  }
9035
9129
  dialectFor(model) {
@@ -9094,9 +9188,12 @@ var ImageProvider = class {
9094
9188
  if (selectors.length === 0) {
9095
9189
  return { ok: false, reason: "no image models configured (image.models is empty)" };
9096
9190
  }
9097
- const count = typeof args.count === "number" && Number.isFinite(args.count) && args.count > 0 ? Math.min(Math.floor(args.count), 4) : 1;
9191
+ const requestedCount = typeof args.count === "number" && Number.isFinite(args.count) && args.count >= 1 ? Math.floor(args.count) : 1;
9098
9192
  const aspectRatio = typeof args.aspectRatio === "string" ? args.aspectRatio : void 0;
9099
9193
  const size = typeof args.size === "string" ? args.size : void 0;
9194
+ const outputFormat = MUSE_OUTPUT_FORMATS.includes(args.outputFormat) ? args.outputFormat : void 0;
9195
+ const reasoningStrength = MUSE_REASONING_STRENGTHS.includes(args.reasoningStrength) ? args.reasoningStrength : void 0;
9196
+ const toolEnablement = museToolEnablement(args.toolEnablement);
9100
9197
  const saveTo = typeof args.saveTo === "string" && args.saveTo.trim().length > 0 ? args.saveTo.trim() : void 0;
9101
9198
  const sources = action === "edit" ? Array.isArray(args.images) ? args.images.filter((entry) => typeof entry === "string") : [] : [];
9102
9199
  if (action === "edit" && sources.length === 0) {
@@ -9122,6 +9219,8 @@ var ImageProvider = class {
9122
9219
  continue;
9123
9220
  }
9124
9221
  const dialect = this.dialectFor(model);
9222
+ const muse = model.muse && dialect === "images";
9223
+ const count = Math.min(requestedCount, muse ? MUSE_MAX_COUNT : DEFAULT_MAX_COUNT);
9125
9224
  let apiKey;
9126
9225
  let extraHeaders = {};
9127
9226
  try {
@@ -9152,6 +9251,9 @@ var ImageProvider = class {
9152
9251
  prompt,
9153
9252
  aspectRatio,
9154
9253
  size,
9254
+ outputFormat,
9255
+ reasoningStrength,
9256
+ toolEnablement,
9155
9257
  count,
9156
9258
  inputImages,
9157
9259
  signal: env.signal
@@ -9177,15 +9279,19 @@ ${written.map((entry) => ` ${entry.path} (${entry.bytes} bytes)`).join("\n")}`
9177
9279
  );
9178
9280
  const ignored = ignoredParams({
9179
9281
  dialect,
9282
+ muse,
9180
9283
  aspectRatio,
9181
9284
  size,
9285
+ outputFormat,
9286
+ reasoningStrength,
9287
+ toolEnablement,
9182
9288
  count,
9183
9289
  saveTo,
9184
9290
  returned: written.length
9185
9291
  });
9186
- const requestedSize = resolveImageSize(aspectRatio, size);
9292
+ const requestedSize = muse ? resolveMuseSize(aspectRatio, size) : resolveImageSize(aspectRatio, size);
9187
9293
  const first = written[0];
9188
- const mismatch = requestedSize !== void 0 && first?.width !== void 0 && first.height !== void 0 && requestedSize !== `${first.width}x${first.height}`;
9294
+ const mismatch = requestedSize !== void 0 && first?.width !== void 0 && first.height !== void 0 && (muse ? !ratioHonoured(requestedSize, first.width, first.height) : requestedSize !== `${first.width}x${first.height}`);
9189
9295
  return {
9190
9296
  ok: true,
9191
9297
  model: `${model.provider}/${model.id}`,