omp-fabric 0.85.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/agents/manager.d.ts.map +1 -1
  3. package/dist/agents/transports/process-transport.d.ts.map +1 -1
  4. package/dist/agents/transports/process-utils.d.ts +6 -1
  5. package/dist/agents/transports/process-utils.d.ts.map +1 -1
  6. package/dist/agents/types.d.ts +1 -0
  7. package/dist/agents/types.d.ts.map +1 -1
  8. package/dist/audit/details.d.ts +10 -0
  9. package/dist/audit/details.d.ts.map +1 -1
  10. package/dist/chunks/{chunk-GKOFZ76R.js → chunk-2LGLDM34.js} +22 -4
  11. package/dist/chunks/chunk-2LGLDM34.js.map +7 -0
  12. package/dist/chunks/{chunk-T6OAX4FO.js → chunk-3TWC6XOS.js} +37 -9
  13. package/dist/chunks/chunk-3TWC6XOS.js.map +7 -0
  14. package/dist/chunks/{chunk-ZNAJDPT7.js → chunk-B2SQR2JY.js} +32 -24
  15. package/dist/chunks/{chunk-ZNAJDPT7.js.map → chunk-B2SQR2JY.js.map} +2 -2
  16. package/dist/chunks/{chunk-SXMWV447.js → chunk-DOKANNFC.js} +206 -3
  17. package/dist/chunks/chunk-DOKANNFC.js.map +7 -0
  18. package/dist/chunks/{chunk-UPCARIJP.js → chunk-FFWALVBN.js} +20 -9
  19. package/dist/chunks/chunk-FFWALVBN.js.map +7 -0
  20. package/dist/chunks/{chunk-4LEDA76O.js → chunk-HAJPYJPY.js} +3 -3
  21. package/dist/chunks/{chunk-ROKMBLGN.js → chunk-IFNDRFW7.js} +34 -14
  22. package/dist/chunks/chunk-IFNDRFW7.js.map +7 -0
  23. package/dist/chunks/{chunk-ZTM45GH5.js → chunk-JZWLICMS.js} +125 -42
  24. package/dist/chunks/chunk-JZWLICMS.js.map +7 -0
  25. package/dist/chunks/{chunk-5GTPD4BA.js → chunk-L2FNMIOW.js} +66 -22
  26. package/dist/chunks/chunk-L2FNMIOW.js.map +7 -0
  27. package/dist/chunks/chunk-NX4SNIMR.js +226 -0
  28. package/dist/chunks/chunk-NX4SNIMR.js.map +7 -0
  29. package/dist/chunks/{chunk-YZZIKJX6.js → chunk-RBA54WC7.js} +1 -1
  30. package/dist/chunks/{chunk-YZZIKJX6.js.map → chunk-RBA54WC7.js.map} +1 -1
  31. package/dist/chunks/{chunk-OPTP4PSE.js → chunk-YPYVUGON.js} +3 -23
  32. package/dist/chunks/chunk-YPYVUGON.js.map +7 -0
  33. package/dist/chunks/{chunk-JP4LIZFT.js → chunk-Z6HEQPXX.js} +23 -6
  34. package/dist/chunks/chunk-Z6HEQPXX.js.map +7 -0
  35. package/dist/commands/fabric.d.ts.map +1 -1
  36. package/dist/core/action-registry.d.ts +2 -1
  37. package/dist/core/action-registry.d.ts.map +1 -1
  38. package/dist/core/action-registry.js +2 -2
  39. package/dist/core/compact-controller.d.ts +28 -3
  40. package/dist/core/compact-controller.d.ts.map +1 -1
  41. package/dist/core/compact-outcome-store.d.ts +3 -0
  42. package/dist/core/compact-outcome-store.d.ts.map +1 -0
  43. package/dist/entropy/index.js +2 -2
  44. package/dist/entropy/sessions.d.ts.map +1 -1
  45. package/dist/execution-service.d.ts.map +1 -1
  46. package/dist/fabric-exec-tool.d.ts.map +1 -1
  47. package/dist/fabric-runtime-state.d.ts.map +1 -1
  48. package/dist/fabric-runtime-state.js +883 -367
  49. package/dist/fabric-runtime-state.js.map +4 -4
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +116 -18
  52. package/dist/index.js.map +3 -3
  53. package/dist/memory/discovery.d.ts +28 -14
  54. package/dist/memory/discovery.d.ts.map +1 -1
  55. package/dist/memory/discovery.js +9 -5
  56. package/dist/protocol.d.ts +5 -0
  57. package/dist/protocol.d.ts.map +1 -1
  58. package/dist/protocol.js +1 -1
  59. package/dist/providers/mcp-descriptor-cache.d.ts +2 -0
  60. package/dist/providers/mcp-descriptor-cache.d.ts.map +1 -1
  61. package/dist/providers/mcp-provider.d.ts +4 -2
  62. package/dist/providers/mcp-provider.d.ts.map +1 -1
  63. package/dist/providers/memory-provider.d.ts.map +1 -1
  64. package/dist/providers/memory-provider.js +2 -2
  65. package/dist/providers/omp-tools-provider.d.ts +1 -0
  66. package/dist/providers/omp-tools-provider.d.ts.map +1 -1
  67. package/dist/residency/host.js +5 -5
  68. package/dist/residency/omp-entry.js +5 -5
  69. package/dist/runtime/core-override-guest-types.js +1 -1
  70. package/dist/runtime/guest-types.d.ts +2 -2
  71. package/dist/runtime/guest-types.d.ts.map +1 -1
  72. package/dist/runtime/guest-types.js +1 -1
  73. package/dist/runtime/node-process-child-source.d.ts.map +1 -1
  74. package/dist/runtime/node-process-runtime.d.ts.map +1 -1
  75. package/dist/runtime/node-process-runtime.js +4 -2
  76. package/dist/runtime/node-process-runtime.js.map +2 -2
  77. package/dist/runtime/quickjs-runtime.d.ts +6 -1
  78. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  79. package/dist/runtime/quickjs-runtime.js +1 -1
  80. package/dist/speculation/guest-args.d.ts +2 -0
  81. package/dist/speculation/guest-args.d.ts.map +1 -0
  82. package/dist/speculation/scanner.d.ts.map +1 -1
  83. package/dist/speculation/scanner.js +312 -14
  84. package/dist/speculation/scanner.js.map +3 -3
  85. package/dist/speculation/store.d.ts +2 -0
  86. package/dist/speculation/store.d.ts.map +1 -1
  87. package/dist/speculation/stream-tap.d.ts +1 -0
  88. package/dist/speculation/stream-tap.d.ts.map +1 -1
  89. package/dist/speculation/summary.d.ts +4 -0
  90. package/dist/speculation/summary.d.ts.map +1 -0
  91. package/dist/speculation/types.d.ts +4 -0
  92. package/dist/speculation/types.d.ts.map +1 -1
  93. package/dist/speculation/warmup.d.ts +17 -0
  94. package/dist/speculation/warmup.d.ts.map +1 -0
  95. package/dist/ui/settings.d.ts.map +1 -1
  96. package/dist/ui/settings.js +6 -6
  97. package/dist/ui/settings.js.map +2 -2
  98. package/docs/agents.md +1 -1
  99. package/docs/compaction.md +2 -2
  100. package/docs/configuration.md +26 -12
  101. package/docs/interface.md +2 -2
  102. package/docs/speculation.md +11 -6
  103. package/package.json +3 -2
  104. package/dist/chunks/chunk-5GTPD4BA.js.map +0 -7
  105. package/dist/chunks/chunk-7BIA5BJN.js +0 -112
  106. package/dist/chunks/chunk-7BIA5BJN.js.map +0 -7
  107. package/dist/chunks/chunk-GKOFZ76R.js.map +0 -7
  108. package/dist/chunks/chunk-JP4LIZFT.js.map +0 -7
  109. package/dist/chunks/chunk-OPTP4PSE.js.map +0 -7
  110. package/dist/chunks/chunk-ROKMBLGN.js.map +0 -7
  111. package/dist/chunks/chunk-SXMWV447.js.map +0 -7
  112. package/dist/chunks/chunk-T6OAX4FO.js.map +0 -7
  113. package/dist/chunks/chunk-UPCARIJP.js.map +0 -7
  114. package/dist/chunks/chunk-ZTM45GH5.js.map +0 -7
  115. /package/dist/chunks/{chunk-4LEDA76O.js.map → chunk-HAJPYJPY.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/agents/transports/process-utils.ts"],
4
+ "sourcesContent": ["import { execFile, spawn } from \"node:child_process\";\nimport {\n accessSync,\n closeSync,\n constants,\n mkdirSync,\n openSync,\n readSync,\n rmSync,\n statSync,\n writeSync,\n} from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface ExecFileResult {\n stdout: string;\n stderr: string;\n}\n\nexport const executeFile = (\n command: string,\n args: string[],\n options: { cwd?: string; timeoutMs?: number } = {},\n): Promise<ExecFileResult> =>\n new Promise((resolve, reject) => {\n execFile(\n command,\n args,\n {\n encoding: \"utf8\",\n maxBuffer: 10 * 1024 * 1024,\n ...(options.cwd ? { cwd: options.cwd } : {}),\n ...(options.timeoutMs ? { timeout: options.timeoutMs } : {}),\n },\n (error, stdout, stderr) => {\n if (error) {\n Object.assign(error, { stdout, stderr });\n reject(error);\n return;\n }\n resolve({ stdout, stderr });\n },\n );\n });\n\n// Resolve against the caller's own PATH. A shell probe cannot: `sh -lc` rebuilds\n// PATH from the login profile, which drops per-session managers (fnm, nvm, the\n// CI tool cache) and reports an installed runtime as missing.\nexport const commandAvailable = async (command: string): Promise<boolean> =>\n resolveCommandPath(command) !== undefined;\n\nconst resolveCommandPath = (\n command: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | undefined => {\n if (command.includes(\"/\") || command.includes(\"\\\\\")) {\n return isExecutableFile(command) ? command : undefined;\n }\n const extensions = process.platform === \"win32\"\n ? (env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\").split(\";\").filter(Boolean)\n : [\"\"];\n for (const directory of (env.PATH ?? \"\").split(path.delimiter)) {\n if (!directory) continue;\n for (const extension of extensions) {\n const candidate = path.join(directory, `${command}${extension}`);\n if (isExecutableFile(candidate)) return candidate;\n }\n }\n return undefined;\n};\n\nconst isExecutableFile = (candidate: string): boolean => {\n try {\n if (!statSync(candidate).isFile()) return false;\n } catch {\n return false;\n }\n if (process.platform === \"win32\") return true;\n try {\n accessSync(candidate, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n};\n\nconst shellQuote = (value: string): string => `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n\nexport const processIsAlive = (pid: number): boolean => {\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // On Windows, EPERM means the process exists but cannot be opened for\n // signaling; only ESRCH (or other errors) mean it is gone.\n return error instanceof Error && \"code\" in error && (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n};\n\nconst GENERIC_RUNTIME = /^(node|bun)(\\.exe)?$/;\n\ntype RuntimeFlavor = \"node\" | \"bun\";\n\nconst SCRIPT_RUNTIME_ORDER: readonly RuntimeFlavor[] = [\"bun\", \"node\"];\n\nexport interface ScriptRuntimeOptions {\n execPath?: string;\n env?: NodeJS.ProcessEnv;\n /** Require Node.js specifically; used by the Node-process executor whose\n * `--eval`/`--input-type=module` flags are Node-only. */\n requireNode?: boolean;\n /** Require Bun specifically; used by the Bun-process executor. */\n requireBun?: boolean;\n}\n\nconst runtimeOverride = (env: NodeJS.ProcessEnv): string | undefined => {\n const value = env.OMP_FABRIC_NODE_BINARY;\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n};\n\nconst isRuntimeFlavor = (execPath: string, flavor: RuntimeFlavor): boolean => {\n const name = path.basename(execPath).toLowerCase();\n return GENERIC_RUNTIME.test(name) && name.startsWith(flavor);\n};\n\nconst isGenericRuntime = (execPath: string, requireNode: boolean, requireBun = false): boolean => {\n const name = path.basename(execPath).toLowerCase();\n return GENERIC_RUNTIME.test(name)\n && (!requireNode || name.startsWith(\"node\"))\n && (!requireBun || name.startsWith(\"bun\"));\n};\n\nconst isWrongFlavorRuntime = (execPath: string, requireNode: boolean, requireBun: boolean): boolean => {\n const name = path.basename(execPath).toLowerCase();\n return GENERIC_RUNTIME.test(name)\n && ((requireNode && name.startsWith(\"bun\")) || (requireBun && name.startsWith(\"node\")));\n};\n\nconst missingRuntimeError = (execPath: string, requireNode: boolean, requireBun = false): Error => {\n const required = requireNode\n ? \"a Node.js runtime\"\n : requireBun\n ? \"a Bun runtime\"\n : \"a Bun or Node.js runtime\";\n const shape = requireNode ? \"(not node)\" : requireBun ? \"(not bun)\" : \"(not node/bun)\";\n return new Error(\n `Fabric requires ${required} to launch a JavaScript worker, but ` +\n `process.execPath is ${execPath} ${shape} and OMP_FABRIC_NODE_BINARY is unset. ` +\n \"Install Bun or Node.js, or set OMP_FABRIC_NODE_BINARY to the runtime binary.\",\n );\n};\n\nconst resolveScriptRuntimeCore = (\n options: ScriptRuntimeOptions,\n rejectWrongFlavorExecPath: boolean,\n): string => {\n const execPath = options.execPath ?? process.execPath;\n const env = options.env ?? process.env;\n const requireNode = options.requireNode === true;\n const requireBun = options.requireBun === true;\n if (requireNode || requireBun) {\n const flavor: RuntimeFlavor = requireNode ? \"node\" : \"bun\";\n if (isGenericRuntime(execPath, requireNode, requireBun)) return execPath;\n if (\n rejectWrongFlavorExecPath &&\n options.execPath !== undefined &&\n isWrongFlavorRuntime(execPath, requireNode, requireBun)\n ) {\n throw missingRuntimeError(execPath, requireNode, requireBun);\n }\n const override = runtimeOverride(env);\n if (override) return override;\n const resolved = resolveCommandPath(flavor, env);\n if (resolved) return resolved;\n throw missingRuntimeError(execPath, requireNode, requireBun);\n }\n const override = runtimeOverride(env);\n if (override) return override;\n for (const flavor of SCRIPT_RUNTIME_ORDER) {\n if (isRuntimeFlavor(execPath, flavor)) return execPath;\n const resolved = resolveCommandPath(flavor, env);\n if (resolved) return resolved;\n }\n throw missingRuntimeError(execPath, requireNode, requireBun);\n};\n\nconst resolveScriptRuntimeUncached = async (options: ScriptRuntimeOptions = {}): Promise<string> =>\n resolveScriptRuntimeCore(options, false);\n\nlet cachedDefaultRuntime: string | undefined;\nexport const resolveScriptRuntime = async (options?: ScriptRuntimeOptions): Promise<string> => {\n if (\n options &&\n (options.execPath !== undefined ||\n options.env !== undefined ||\n options.requireNode !== undefined ||\n options.requireBun !== undefined)\n ) {\n return resolveScriptRuntimeUncached(options);\n }\n if (cachedDefaultRuntime) return cachedDefaultRuntime;\n cachedDefaultRuntime = await resolveScriptRuntimeUncached();\n return cachedDefaultRuntime;\n};\n\nexport const resolveScriptRuntimeSync = (options: ScriptRuntimeOptions = {}): string =>\n resolveScriptRuntimeCore(options, true);\n\nexport const scriptSpawnArgs = async (\n workerPath: string,\n workerArguments: readonly string[],\n options?: ScriptRuntimeOptions,\n): Promise<string[]> => {\n const runtime = await resolveScriptRuntime(options);\n return [runtime, workerPath, ...workerArguments];\n};\n\nexport const workerCommand = async (\n workerPath: string,\n workerArguments: string[],\n): Promise<string> =>\n (await scriptSpawnArgs(workerPath, workerArguments)).map(shellQuote).join(\" \");\n\nconst TRANSPORT_STDERR_FILE = \"transport-stderr.log\";\nconst TRANSPORT_STDERR_TAIL_BYTES = 8 * 1024;\nconst TRANSPORT_STDERR_MAX_CHARS = 400;\nconst LAUNCH_MARKER = \"[fabric] launching worker with \";\n\nexport const transportStderrPath = (runDirectory: string): string =>\n path.join(runDirectory, TRANSPORT_STDERR_FILE);\n\nexport const readTransportStderrSummary = (runDirectory: string): string | undefined => {\n try {\n const file = transportStderrPath(runDirectory);\n const { size } = statSync(file);\n if (size <= 0) return undefined;\n const start = Math.max(0, size - TRANSPORT_STDERR_TAIL_BYTES);\n const length = size - start;\n const buffer = Buffer.allocUnsafe(length);\n const fd = openSync(file, \"r\");\n try {\n readSync(fd, buffer, 0, length, start);\n } finally {\n closeSync(fd);\n }\n const lines = buffer\n .toString(\"utf8\")\n .split(/\\r?\\n/)\n .map((line) => line.replace(/\\s+/g, \" \").trim())\n .filter((line) => line.length > 0);\n let runtime: string | undefined;\n const attempt: string[] = [];\n for (const line of lines) {\n if (line.startsWith(LAUNCH_MARKER)) {\n runtime = line.slice(LAUNCH_MARKER.length);\n attempt.length = 0;\n continue;\n }\n attempt.push(line);\n }\n const cause =\n attempt.find((line) => /^[\\w$.]*Error\\b/.test(line))\n ?? attempt.find((line) => /error|cannot|unsupported|not found|permission denied/i.test(line))\n ?? attempt.at(-1);\n if (!cause) return undefined;\n const detail = cause.slice(0, TRANSPORT_STDERR_MAX_CHARS);\n return runtime ? `${runtime}: ${detail}` : detail;\n } catch {\n return undefined;\n }\n};\n\nexport const clearTransportStderr = (runDirectory: string): void => {\n try {\n rmSync(transportStderrPath(runDirectory), { force: true });\n } catch { /* ignored */ }\n};\n\nconst openStderrSink = (file: string, runtime: string): number | undefined => {\n try {\n mkdirSync(path.dirname(file), { recursive: true });\n const fd = openSync(file, \"a\");\n try {\n writeSync(fd, `${LAUNCH_MARKER}${runtime}\\n`);\n } catch { /* ignored */ }\n return fd;\n } catch {\n return undefined;\n }\n};\n\nexport const spawnDetached = async (\n workerPath: string,\n workerArguments: string[],\n cwd: string,\n options: { stderrFile?: string } = {},\n): Promise<{ pid: number; stop(): Promise<void>; isAlive(): Promise<boolean> }> => {\n const runtime = await resolveScriptRuntime();\n const stderrFd = options.stderrFile ? openStderrSink(options.stderrFile, runtime) : undefined;\n try {\n const child = spawn(runtime, [workerPath, ...workerArguments], {\n cwd,\n detached: process.platform !== \"win32\",\n stdio: [\"ignore\", \"ignore\", stderrFd ?? \"ignore\"],\n });\n if (!child.pid) throw new Error(`Failed to launch Fabric worker process with ${runtime}`);\n const pid = child.pid;\n child.unref();\n return {\n pid,\n async stop() {\n try {\n process.kill(process.platform === \"win32\" ? pid : -pid, \"SIGTERM\");\n } catch { /* process group already exited */ }\n },\n async isAlive() {\n return processIsAlive(pid);\n },\n };\n } finally {\n if (stderrFd !== undefined) {\n try {\n closeSync(stderrFd);\n } catch { /* ignored */ }\n }\n }\n};\n"],
5
+ "mappings": ";AAAA,SAAS,UAAU,aAAa;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,OAAO,UAAU;AAOV,IAAM,cAAc,CACzB,SACA,MACA,UAAgD,CAAC,MAEjD,IAAI,QAAQ,CAAC,SAAS,WAAW;AAC/B;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,MACE,UAAU;AAAA,MACV,WAAW,KAAK,OAAO;AAAA,MACvB,GAAI,QAAQ,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;AAAA,MAC1C,GAAI,QAAQ,YAAY,EAAE,SAAS,QAAQ,UAAU,IAAI,CAAC;AAAA,IAC5D;AAAA,IACA,CAAC,OAAO,QAAQ,WAAW;AACzB,UAAI,OAAO;AACT,eAAO,OAAO,OAAO,EAAE,QAAQ,OAAO,CAAC;AACvC,eAAO,KAAK;AACZ;AAAA,MACF;AACA,cAAQ,EAAE,QAAQ,OAAO,CAAC;AAAA,IAC5B;AAAA,EACF;AACF,CAAC;AAKI,IAAM,mBAAmB,OAAO,YACrC,mBAAmB,OAAO,MAAM;AAElC,IAAM,qBAAqB,CACzB,SACA,MAAyB,QAAQ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,YAAwC;AAC5E,MAAI;AACF,cAAU,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AACjD,UAAM,KAAK,SAAS,MAAM,GAAG;AAC7B,QAAI;AACF,gBAAU,IAAI,GAAG,aAAa,GAAG,OAAO;AAAA,CAAI;AAAA,IAC9C,QAAQ;AAAA,IAAgB;AACxB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,IAAM,gBAAgB,OAC3B,YACA,iBACA,KACA,UAAmC,CAAC,MAC6C;AACjF,QAAM,UAAU,MAAM,qBAAqB;AAC3C,QAAM,WAAW,QAAQ,aAAa,eAAe,QAAQ,YAAY,OAAO,IAAI;AACpF,MAAI;AACF,UAAM,QAAQ,MAAM,SAAS,CAAC,YAAY,GAAG,eAAe,GAAG;AAAA,MAC7D;AAAA,MACA,UAAU,QAAQ,aAAa;AAAA,MAC/B,OAAO,CAAC,UAAU,UAAU,YAAY,QAAQ;AAAA,IAClD,CAAC;AACD,QAAI,CAAC,MAAM,IAAK,OAAM,IAAI,MAAM,+CAA+C,OAAO,EAAE;AACxF,UAAM,MAAM,MAAM;AAClB,UAAM,MAAM;AACZ,WAAO;AAAA,MACL;AAAA,MACA,MAAM,OAAO;AACX,YAAI;AACF,kBAAQ,KAAK,QAAQ,aAAa,UAAU,MAAM,CAAC,KAAK,SAAS;AAAA,QACnE,QAAQ;AAAA,QAAqC;AAAA,MAC/C;AAAA,MACA,MAAM,UAAU;AACd,eAAO,eAAe,GAAG;AAAA,MAC3B;AAAA,IACF;AAAA,EACF,UAAE;AACA,QAAI,aAAa,QAAW;AAC1B,UAAI;AACF,kBAAU,QAAQ;AAAA,MACpB,QAAQ;AAAA,MAAgB;AAAA,IAC1B;AAAA,EACF;AACF;",
6
+ "names": ["override"]
7
+ }
@@ -215,7 +215,7 @@ const __ompArgAliases = {
215
215
  expression: "pattern", text: "pattern",
216
216
  ic: "ignoreCase", caseInsensitive: "ignoreCase",
217
217
  globPattern: "glob",
218
- max: "limit", ctx: "context",
218
+ ctx: "context",
219
219
  },
220
220
  read: {
221
221
  file: "path", absolutePath: "path", file_path: "path", filePath: "path",
@@ -257,7 +257,7 @@ const __ompArgAliases = {
257
257
  // an options object, repaired by the merge instead of a wrong-arity (2554)
258
258
  // type error; only a non-object second arg still fails 2554.
259
259
  const __ompPositionalFields = {
260
- grep: ["pattern", "path", "limit"],
260
+ grep: ["pattern", "path", "skip"],
261
261
  find: ["pattern", "path", "limit"],
262
262
  write: ["path", "content"],
263
263
  edit: ["path", "oldText", "newText"],
@@ -269,7 +269,7 @@ const __ompPositionalFields = {
269
269
  const __ompNumericFields = {
270
270
  read: ["offset", "limit"],
271
271
  bash: ["timeout"],
272
- grep: ["limit", "context"],
272
+ grep: ["skip", "context"],
273
273
  find: ["limit"],
274
274
  ls: ["limit"],
275
275
  };
@@ -647,14 +647,43 @@ const __memoryWalk = async (args, visitor) => {
647
647
  }
648
648
  };
649
649
 
650
- const __providerProxy = (provider, local = {}) => new Proxy(local, {
650
+ const __proxyNames = (() => {
651
+ const raw = globalThis.__fabricProxyNames;
652
+ delete globalThis.__fabricProxyNames;
653
+ return raw && typeof raw === "object" ? raw : {};
654
+ })();
655
+ const __nameList = (value) =>
656
+ Array.isArray(value) ? value.filter((name) => typeof name === "string") : [];
657
+ const __lazyNamespace = (names, resolve, local = {}) => new Proxy(local, {
651
658
  get(target, property) {
652
659
  if (property === "then" || typeof property === "symbol") return undefined;
653
660
  if (Object.prototype.hasOwnProperty.call(target, property)) return target[property];
654
- return (args = {}) => __call(provider + "." + String(property), args);
661
+ return resolve(String(property));
662
+ },
663
+ ownKeys(target) {
664
+ const own = Object.keys(target);
665
+ return names.concat(own.filter((key) => names.indexOf(key) < 0));
666
+ },
667
+ getOwnPropertyDescriptor(target, property) {
668
+ if (typeof property === "symbol") return undefined;
669
+ const name = String(property);
670
+ if (names.indexOf(name) < 0 && !Object.prototype.hasOwnProperty.call(target, name)) {
671
+ return undefined;
672
+ }
673
+ const value = Object.prototype.hasOwnProperty.call(target, name)
674
+ ? target[name]
675
+ : resolve(name);
676
+ return { value, writable: false, enumerable: true, configurable: true };
677
+ },
678
+ has(target, property) {
679
+ if (typeof property === "symbol") return false;
680
+ return names.indexOf(String(property)) >= 0
681
+ || Object.prototype.hasOwnProperty.call(target, property);
655
682
  },
656
683
  });
657
- globalThis.extensions = __providerProxy("extensions");
684
+ const __providerProxy = (provider, local = {}, names = []) =>
685
+ __lazyNamespace(names, (property) => (args = {}) => __call(provider + "." + property, args), local);
686
+ globalThis.extensions = __providerProxy("extensions", {}, __nameList(__proxyNames.extensions));
658
687
  globalThis.memory = __providerProxy("memory", { walk: __memoryWalk });
659
688
  globalThis.state = __providerProxy("state");
660
689
  globalThis.schema = __providerProxy("schema");
@@ -748,21 +777,28 @@ globalThis.mesh = Object.freeze({
748
777
  // dispatch \u2014 but guestTypeDeclarations renders per-server argument types from
749
778
  // the live descriptor cache (runtime/dynamic-guest-types.ts), so known tools
750
779
  // fail type-check on argument-shape mistakes before this proxy ever runs.
751
- globalThis.mcp = new Proxy({}, {
752
- get(_target, server) {
753
- if (server === "then") return undefined;
754
- if (server === "servers") return () => __call("mcp.$servers", {});
755
- if (server === "reload") return () => __call("mcp.$reload", {});
756
- if (server === "register") return (args) => __call("mcp.$register", args);
757
- if (server === "call") return (args) => __call("mcp.$call", args);
758
- return new Proxy({}, {
759
- get(_serverTarget, tool) {
760
- if (tool === "then") return undefined;
761
- return (args = {}) => __call("mcp." + String(server) + "." + String(tool), args);
762
- },
763
- });
764
- },
765
- });
780
+ const __mcpServerTools = (() => {
781
+ const raw = __proxyNames.mcp;
782
+ const out = {};
783
+ if (raw && typeof raw === "object") {
784
+ for (const server of Object.keys(raw)) out[server] = __nameList(raw[server]);
785
+ }
786
+ return out;
787
+ })();
788
+ const __mcpManagement = {
789
+ servers: () => __call("mcp.$servers", {}),
790
+ reload: () => __call("mcp.$reload", {}),
791
+ register: (args) => __call("mcp.$register", args),
792
+ call: (args) => __call("mcp.$call", args),
793
+ };
794
+ globalThis.mcp = __lazyNamespace(
795
+ Object.keys(__mcpServerTools).sort(),
796
+ (server) => __lazyNamespace(
797
+ __mcpServerTools[server] ? __mcpServerTools[server].slice().sort() : [],
798
+ (tool) => (args = {}) => __call("mcp." + server + "." + tool, args),
799
+ ),
800
+ __mcpManagement,
801
+ );
766
802
  let __workflowSpentTokens = 0;
767
803
  const __workflowBudgetTotal = Number.isFinite(globalThis.__fabricTokenBudget)
768
804
  ? Math.max(0, globalThis.__fabricTokenBudget)
@@ -1176,6 +1212,14 @@ var QuickJsRuntime = class {
1176
1212
  const payloads = jsonHandle(context, jsonObject, jsonParse, options.payloads ?? {});
1177
1213
  context.setProp(context.global, "payloads", payloads);
1178
1214
  payloads.dispose();
1215
+ const proxyNames = jsonHandle(
1216
+ context,
1217
+ jsonObject,
1218
+ jsonParse,
1219
+ options.proxyNames ?? {}
1220
+ );
1221
+ context.setProp(context.global, "__fabricProxyNames", proxyNames);
1222
+ proxyNames.dispose();
1179
1223
  const tokenBudget = context.newNumber(options.tokenBudget ?? Number.POSITIVE_INFINITY);
1180
1224
  context.setProp(context.global, "__fabricTokenBudget", tokenBudget);
1181
1225
  tokenBudget.dispose();
@@ -1315,4 +1359,4 @@ export {
1315
1359
  GUEST_SETUP,
1316
1360
  QuickJsRuntime
1317
1361
  };
1318
- //# sourceMappingURL=chunk-5GTPD4BA.js.map
1362
+ //# sourceMappingURL=chunk-L2FNMIOW.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/runtime/quickjs-runtime.ts", "../../src/runtime/guest-stack-map.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 { 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\"];\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 return target[property];\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. One-field\n// tools (read/bash/ls) stay absent: their two-arg form is a bare string plus\n// an options object, repaired by the merge instead of a wrong-arity (2554)\n// type error; only a non-object second arg still fails 2554.\nconst __ompPositionalFields = {\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\"],\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 };\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);\nglobalThis.extensions = __providerProxy(\"extensions\", {}, __nameList(__proxyNames.extensions));\nglobalThis.memory = __providerProxy(\"memory\", { walk: __memoryWalk });\nglobalThis.state = __providerProxy(\"state\");\nglobalThis.schema = __providerProxy(\"schema\");\nglobalThis.components = __providerProxy(\"components\");\nglobalThis.compact = __providerProxy(\"compact\");\nconst __createActor = async (args = {}) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n throw new TypeError(\"agents.create expects an options object\");\n }\n const request = { ...args };\n const validWhile = request.validWhile;\n if (validWhile !== undefined) {\n if (typeof validWhile !== \"function\") {\n throw new TypeError(\"agents.create validWhile must be a pure predicate function\");\n }\n const source = Function.prototype.toString.call(validWhile);\n if (source.trimStart().startsWith(\"async\")) {\n throw new TypeError(\"agents.create validWhile must be synchronous\");\n }\n request.validWhile = { version: 1, source };\n }\n return __call(\"agents.create\", request);\n};\nconst __handoff = async (args = {}) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n throw new TypeError(\"agents.handoff expects an options object\");\n }\n const request = { ...args };\n const when = request.when;\n delete request.when;\n if (when !== undefined) {\n if (typeof when !== \"function\") {\n throw new TypeError(\"agents.handoff when must be a pure predicate function\");\n }\n const decision = when(__handoffFacts());\n if (decision && typeof decision.then === \"function\") {\n throw new TypeError(\"agents.handoff when must return a boolean synchronously\");\n }\n if (decision !== true) {\n throw new Error(\"agents.handoff predicate returned false; no agent was started\");\n }\n }\n return __call(\"agents.handoff\", request);\n};\nglobalThis.agents = Object.freeze({\n run: (args) => __call(\"agents.run\", args),\n handoff: __handoff,\n spawn: (args) => __call(\"agents.spawn\", args),\n wait: (args) => __call(\"agents.wait\", args),\n status: (args) => __call(\"agents.status\", args),\n list: (args = {}) => __call(\"agents.list\", args),\n members: (args = {}) => __call(\"agents.members\", args),\n self: () => __call(\"agents.self\", {}),\n main: () => __call(\"agents.main\", {}),\n peers: () => __call(\"agents.peers\", {}),\n subscribe: (args) => __call(\"agents.subscribe\", args),\n subscriptions: (args = {}) => __call(\"agents.subscriptions\", args),\n unsubscribe: (args) => __call(\"agents.unsubscribe\", args),\n models: (args = {}) => __call(\"agents.models\", args),\n stop: (args) => __call(\"agents.stop\", args),\n cleanup: (args) => __call(\"agents.cleanup\", args),\n create: __createActor,\n ask: (args) => __call(\"agents.ask\", args),\n tell: (args) => __call(\"agents.tell\", args),\n steer: (args) => __call(\"agents.steer\", args),\n followUp: (args) => __call(\"agents.followUp\", args),\n setSteeringMode: (args) => __call(\"agents.setSteeringMode\", args),\n setFollowUpMode: (args) => __call(\"agents.setFollowUpMode\", args),\n actorStatus: (args) => __call(\"agents.actorStatus\", args),\n setModel: (args) => __call(\"agents.setModel\", args),\n switchModel: (args) => __call(\"agents.switchModel\", args),\n setThinking: (args) => __call(\"agents.setThinking\", args),\n setEvents: (args) => __call(\"agents.setEvents\", args),\n setInstructions: (args) => __call(\"agents.setInstructions\", args),\n actors: () => __call(\"agents.actors\", {}),\n messages: (args) => __call(\"agents.messages\", args),\n remove: (args) => __call(\"agents.remove\", args),\n log: (args) => __call(\"agents.log\", args),\n});\nglobalThis.mesh = Object.freeze({\n self: () => __call(\"mesh.self\", {}),\n publish: (args) => __call(\"mesh.publish\", args),\n read: (args = {}) => __call(\"mesh.read\", args),\n members: (args = {}) => __call(\"mesh.members\", args),\n get: (args) => __call(\"mesh.get\", args),\n list: (args = {}) => __call(\"mesh.list\", args),\n put: (args) => __call(\"mesh.put\", args),\n delete: (args) => __call(\"mesh.delete\", args),\n});\n// The mcp proxy itself stays schema-less \u2014 the registry validates args at\n// dispatch \u2014 but guestTypeDeclarations renders per-server argument types from\n// the live descriptor cache (runtime/dynamic-guest-types.ts), so known tools\n// fail type-check on argument-shape mistakes before this proxy ever runs.\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};\nglobalThis.mcp = __lazyNamespace(\n Object.keys(__mcpServerTools).sort(),\n (server) => __lazyNamespace(\n __mcpServerTools[server] ? __mcpServerTools[server].slice().sort() : [],\n (tool) => (args = {}) => __call(\"mcp.\" + server + \".\" + tool, args),\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); };\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 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"],
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,SAAS,CAAC;AAAA,EAC5D;AACA,SAAO;AACT;AAEA,IAAM,iBAAiB,CAAC,aAAyC;AAC/D,QAAM,QAA4B,CAAC;AACnC,MAAI,aAAa;AACjB,MAA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AC7B;AACA,gBAAU;AACV,UAAI,YAAY,aAAa,oBAAoB,OAAO,GAAG;AACzD,cAAM,iBAAiB,YACnB,wBACA,WACE,eAAe,IACf;AACN,YAAI,CAAC,oBAAoB,OAAO,QAAS,qBAAoB,MAAM,IAAI,MAAM,cAAc,CAAC;AAC5F,4BAAoB,cAAc;AAClC,cAAM,cAAc,QAAQ,SAAS,cAAc;AACnD,mBAAW,WAAW,oBAAqB,SAAQ,OAAO,WAAW;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
+ }
@@ -0,0 +1,226 @@
1
+ import {
2
+ readSessionHeader
3
+ } from "./chunk-6QBPSZJ5.js";
4
+
5
+ // src/memory/discovery.ts
6
+ import crypto from "node:crypto";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { getSessionsDir, resolveEquivalentPath } from "@oh-my-pi/pi-utils";
11
+ var SESSION_SCOPE_PREFIX = "session:";
12
+ var PROJECT_SESSION_DIR_MISSING = "project_session_dir_missing";
13
+ var isJsonlFile = (name) => name.endsWith(".jsonl");
14
+ var isWithinRoot = (relative) => relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
15
+ var encodeRelativeDirName = (prefix, relative) => {
16
+ const encoded = relative.replace(/[/\\:]/g, "-");
17
+ if (!encoded) return prefix;
18
+ return prefix.endsWith("-") ? `${prefix}${encoded}` : `${prefix}-${encoded}`;
19
+ };
20
+ var encodeAbsoluteDirName = (absolute) => `--${absolute.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
21
+ var encodeHashedDirName = (canonicalCwd, scope) => {
22
+ const readable = path.basename(canonicalCwd).replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(-80);
23
+ const digest = crypto.createHash("sha256").update(canonicalCwd.replaceAll("\\", "/")).digest("hex");
24
+ return `${scope}-${readable || "project"}-${digest}`;
25
+ };
26
+ var sessionDirNamesForCwd = (cwd) => {
27
+ const resolved = path.resolve(cwd);
28
+ const canonicalCwd = resolveEquivalentPath(resolved);
29
+ const homeRelative = path.relative(resolveEquivalentPath(os.homedir()), canonicalCwd);
30
+ const tempRelative = path.relative(resolveEquivalentPath(os.tmpdir()), canonicalCwd);
31
+ let canonical;
32
+ let scope;
33
+ if (isWithinRoot(homeRelative)) {
34
+ canonical = encodeRelativeDirName("-", homeRelative);
35
+ scope = "home";
36
+ } else if (isWithinRoot(tempRelative)) {
37
+ canonical = encodeRelativeDirName("-tmp", tempRelative);
38
+ scope = "tmp";
39
+ } else {
40
+ canonical = encodeAbsoluteDirName(canonicalCwd);
41
+ scope = "abs";
42
+ }
43
+ const legacy = [];
44
+ for (const name of [
45
+ encodeAbsoluteDirName(canonicalCwd),
46
+ encodeAbsoluteDirName(resolved),
47
+ encodeHashedDirName(canonicalCwd, scope)
48
+ ]) {
49
+ if (name !== canonical && !legacy.includes(name)) legacy.push(name);
50
+ }
51
+ return { canonical, legacy };
52
+ };
53
+ var listJsonlInDir = (dir) => {
54
+ try {
55
+ return fs.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && isJsonlFile(entry.name)).map((entry) => path.join(dir, entry.name));
56
+ } catch {
57
+ return [];
58
+ }
59
+ };
60
+ var statMtime = (file) => {
61
+ try {
62
+ return fs.statSync(file).mtimeMs;
63
+ } catch {
64
+ return 0;
65
+ }
66
+ };
67
+ var refFromFile = (file) => {
68
+ const header = readSessionHeader(file);
69
+ return {
70
+ id: header?.sessionId ?? path.basename(file, ".jsonl"),
71
+ file,
72
+ cwd: header?.cwd ?? "",
73
+ mtime: statMtime(file)
74
+ };
75
+ };
76
+ var sessionsDirRoot = (agentDir) => getSessionsDir(agentDir);
77
+ var isDirectory = (dir) => {
78
+ try {
79
+ return fs.statSync(dir).isDirectory();
80
+ } catch {
81
+ return false;
82
+ }
83
+ };
84
+ var sessionDirsForCwd = (cwd, agentDir) => {
85
+ const root = sessionsDirRoot(agentDir);
86
+ const names = sessionDirNamesForCwd(cwd);
87
+ const dirs = [];
88
+ for (const name of [names.canonical, ...names.legacy]) {
89
+ const dir = path.join(root, name);
90
+ if (isDirectory(dir)) dirs.push(dir);
91
+ }
92
+ return dirs;
93
+ };
94
+ var compareRefsByRecency = (left, right) => {
95
+ if (right.mtime !== left.mtime) return right.mtime - left.mtime;
96
+ return left.file < right.file ? -1 : left.file > right.file ? 1 : 0;
97
+ };
98
+ var overrideSessionDir = (sessionFile) => {
99
+ if (!sessionFile) return void 0;
100
+ const dir = path.dirname(path.resolve(sessionFile));
101
+ return isDirectory(dir) ? dir : void 0;
102
+ };
103
+ var enumerateAllSessions = (agentDir, maxSessions, sessionDir) => {
104
+ const files = /* @__PURE__ */ new Set();
105
+ const root = sessionsDirRoot(agentDir);
106
+ try {
107
+ for (const entry of fs.readdirSync(root, { withFileTypes: true }).filter(
108
+ (candidate) => candidate.isDirectory()
109
+ )) {
110
+ for (const file of listJsonlInDir(path.join(root, entry.name))) files.add(file);
111
+ }
112
+ } catch {
113
+ }
114
+ if (sessionDir !== void 0) {
115
+ for (const file of listJsonlInDir(sessionDir)) files.add(file);
116
+ }
117
+ return [...files].map(refFromFile).sort(compareRefsByRecency).slice(0, Math.max(1, maxSessions));
118
+ };
119
+ var AmbiguousSessionError = class extends Error {
120
+ constructor(session, candidates) {
121
+ super(`Session id ${JSON.stringify(session)} is ambiguous; use an exact session file path.`);
122
+ this.session = session;
123
+ this.candidates = candidates;
124
+ this.name = "AmbiguousSessionError";
125
+ }
126
+ code = "ambiguous_session";
127
+ };
128
+ var resolveSessionTarget = (agentDir, target, sessionDir) => {
129
+ if (target.endsWith(".jsonl") && fs.existsSync(target)) {
130
+ return refFromFile(path.resolve(target));
131
+ }
132
+ const all = enumerateAllSessions(agentDir, Number.MAX_SAFE_INTEGER, sessionDir);
133
+ const byId = all.filter((ref) => ref.id === target);
134
+ if (byId.length > 1) throw new AmbiguousSessionError(target, byId.map((ref) => ref.file));
135
+ if (byId.length === 1) return byId[0];
136
+ const byStem = all.filter((ref) => path.basename(ref.file, ".jsonl") === target);
137
+ if (byStem.length > 1) throw new AmbiguousSessionError(target, byStem.map((ref) => ref.file));
138
+ return byStem[0] ?? null;
139
+ };
140
+ var sameProjectCwd = (candidate, cwd) => candidate.length > 0 && resolveEquivalentPath(candidate) === resolveEquivalentPath(cwd);
141
+ var projectSessions = (input) => {
142
+ const root = sessionsDirRoot(input.agentDir);
143
+ const names = sessionDirNamesForCwd(input.cwd);
144
+ const candidateDirs = [names.canonical, ...names.legacy].map((name) => path.join(root, name));
145
+ const searchedDirs = candidateDirs.filter(isDirectory);
146
+ const refs = [];
147
+ const seen = /* @__PURE__ */ new Set();
148
+ for (const dir of searchedDirs) {
149
+ for (const file of listJsonlInDir(dir)) {
150
+ if (seen.has(file)) continue;
151
+ seen.add(file);
152
+ refs.push(refFromFile(file));
153
+ }
154
+ }
155
+ const override = overrideSessionDir(input.sessionFile);
156
+ if (override !== void 0 && !searchedDirs.includes(override)) {
157
+ candidateDirs.push(override);
158
+ searchedDirs.push(override);
159
+ for (const file of listJsonlInDir(override)) {
160
+ if (seen.has(file)) continue;
161
+ const ref = refFromFile(file);
162
+ if (!sameProjectCwd(ref.cwd, input.cwd)) continue;
163
+ seen.add(file);
164
+ refs.push(ref);
165
+ }
166
+ }
167
+ refs.sort(compareRefsByRecency);
168
+ return { refs, candidateDirs, searchedDirs };
169
+ };
170
+ var resolveScope = (input) => {
171
+ const scope = input.scope?.trim() ?? "";
172
+ const sessionDir = overrideSessionDir(input.sessionFile);
173
+ if (scope.startsWith(SESSION_SCOPE_PREFIX)) {
174
+ const target = scope.slice(SESSION_SCOPE_PREFIX.length).trim();
175
+ const ref = resolveSessionTarget(input.agentDir, target, sessionDir);
176
+ return { refs: ref ? [ref] : [], reasons: [], candidateDirs: [], searchedDirs: [] };
177
+ }
178
+ if (scope === "global") {
179
+ const root = sessionsDirRoot(input.agentDir);
180
+ const roots = [root, ...sessionDir !== void 0 && sessionDir !== root ? [sessionDir] : []];
181
+ return {
182
+ refs: enumerateAllSessions(input.agentDir, input.maxSessions, sessionDir),
183
+ reasons: [],
184
+ candidateDirs: roots,
185
+ searchedDirs: roots.filter(isDirectory)
186
+ };
187
+ }
188
+ if (scope === "project") {
189
+ const found2 = projectSessions(input);
190
+ return {
191
+ refs: found2.refs.slice(0, Math.max(1, input.maxSessions)),
192
+ reasons: found2.searchedDirs.length === 0 ? [PROJECT_SESSION_DIR_MISSING] : [],
193
+ candidateDirs: found2.candidateDirs,
194
+ searchedDirs: found2.searchedDirs
195
+ };
196
+ }
197
+ if (input.sessionFile) {
198
+ return {
199
+ refs: [refFromFile(input.sessionFile)],
200
+ reasons: [],
201
+ candidateDirs: [],
202
+ searchedDirs: []
203
+ };
204
+ }
205
+ const found = projectSessions(input);
206
+ const newest = found.refs[0];
207
+ return {
208
+ refs: newest ? [newest] : [],
209
+ reasons: found.searchedDirs.length === 0 ? [PROJECT_SESSION_DIR_MISSING] : [],
210
+ candidateDirs: found.candidateDirs,
211
+ searchedDirs: found.searchedDirs
212
+ };
213
+ };
214
+
215
+ export {
216
+ PROJECT_SESSION_DIR_MISSING,
217
+ sessionDirNamesForCwd,
218
+ sessionsDirRoot,
219
+ sessionDirsForCwd,
220
+ overrideSessionDir,
221
+ enumerateAllSessions,
222
+ AmbiguousSessionError,
223
+ resolveSessionTarget,
224
+ resolveScope
225
+ };
226
+ //# sourceMappingURL=chunk-NX4SNIMR.js.map