omp-fabric 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -0
  3. package/dist/agents/handoff.d.ts +1 -1
  4. package/dist/agents/handoff.d.ts.map +1 -1
  5. package/dist/agents/types.d.ts +1 -1
  6. package/dist/agents/types.d.ts.map +1 -1
  7. package/dist/chunks/{chunk-TLSJXU4F.js → chunk-5YGOVBOZ.js} +179 -10
  8. package/dist/chunks/chunk-5YGOVBOZ.js.map +7 -0
  9. package/dist/chunks/{chunk-CVLO4GNW.js → chunk-EQNNENN6.js} +3 -3
  10. package/dist/chunks/{chunk-YPYVUGON.js → chunk-JOWMM3EX.js} +6 -6
  11. package/dist/chunks/chunk-JOWMM3EX.js.map +7 -0
  12. package/dist/chunks/{chunk-L2FNMIOW.js → chunk-QNRGTJGE.js} +2 -1
  13. package/dist/chunks/chunk-QNRGTJGE.js.map +7 -0
  14. package/dist/chunks/{chunk-WXZP5VWP.js → chunk-TQL7FKMG.js} +3 -3
  15. package/dist/chunks/{chunk-Z6HEQPXX.js → chunk-WGFHMECI.js} +47 -1
  16. package/dist/chunks/{chunk-Z6HEQPXX.js.map → chunk-WGFHMECI.js.map} +2 -2
  17. package/dist/chunks/{chunk-EZPERYEG.js → chunk-XRJYPNTI.js} +56 -2
  18. package/dist/chunks/chunk-XRJYPNTI.js.map +7 -0
  19. package/dist/chunks/{chunk-KIREBD2V.js → chunk-ZP3S74LW.js} +2 -1
  20. package/dist/codemap/budget.d.ts +3 -0
  21. package/dist/codemap/budget.d.ts.map +1 -0
  22. package/dist/codemap/cascade.d.ts +3 -0
  23. package/dist/codemap/cascade.d.ts.map +1 -0
  24. package/dist/codemap/symbols.d.ts +3 -0
  25. package/dist/codemap/symbols.d.ts.map +1 -0
  26. package/dist/codemap/types.d.ts +58 -0
  27. package/dist/codemap/types.d.ts.map +1 -0
  28. package/dist/compaction/hook.js +1 -1
  29. package/dist/config.d.ts +11 -0
  30. package/dist/config.d.ts.map +1 -1
  31. package/dist/core/system-guidance.d.ts.map +1 -1
  32. package/dist/fabric-runtime-state.d.ts.map +1 -1
  33. package/dist/fabric-runtime-state.js +1605 -344
  34. package/dist/fabric-runtime-state.js.map +4 -4
  35. package/dist/index.js +7 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/prewalk/handoff.d.ts +2 -1
  38. package/dist/prewalk/handoff.d.ts.map +1 -1
  39. package/dist/prewalk/retirement.d.ts +35 -0
  40. package/dist/prewalk/retirement.d.ts.map +1 -0
  41. package/dist/providers/codemap-provider.d.ts +14 -0
  42. package/dist/providers/codemap-provider.d.ts.map +1 -0
  43. package/dist/residency/host.js +5 -5
  44. package/dist/residency/omp-entry.js +5 -5
  45. package/dist/runtime/core-override-guest-types.js +1 -1
  46. package/dist/runtime/guest-types.d.ts +1 -1
  47. package/dist/runtime/guest-types.d.ts.map +1 -1
  48. package/dist/runtime/guest-types.js +1 -1
  49. package/dist/runtime/node-process-runtime.js +1 -1
  50. package/dist/runtime/quickjs-runtime.d.ts +1 -1
  51. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  52. package/dist/runtime/quickjs-runtime.js +1 -1
  53. package/dist/ui/settings.d.ts.map +1 -1
  54. package/dist/ui/settings.js +90 -1
  55. package/dist/ui/settings.js.map +2 -2
  56. package/docs/architecture.md +1 -1
  57. package/docs/codemap.md +89 -0
  58. package/docs/configuration.md +1 -1
  59. package/package.json +4 -1
  60. package/dist/chunks/chunk-EZPERYEG.js.map +0 -7
  61. package/dist/chunks/chunk-L2FNMIOW.js.map +0 -7
  62. package/dist/chunks/chunk-TLSJXU4F.js.map +0 -7
  63. package/dist/chunks/chunk-YPYVUGON.js.map +0 -7
  64. /package/dist/chunks/{chunk-CVLO4GNW.js.map → chunk-EQNNENN6.js.map} +0 -0
  65. /package/dist/chunks/{chunk-WXZP5VWP.js.map → chunk-TQL7FKMG.js.map} +0 -0
  66. /package/dist/chunks/{chunk-KIREBD2V.js.map → chunk-ZP3S74LW.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/agents/thinking-transfer.ts", "../../src/agents/handoff.ts", "../../src/topology/peer-settle.ts"],
4
+ "sourcesContent": ["import type {\n SessionEntry,\n SessionMessageEntry,\n} from \"@oh-my-pi/pi-coding-agent\";\n\n// Cross-model thinking transfer for trajectory handoffs.\n//\n// OMP replays stored thinking blocks verbatim per provider: a Codex Responses\n// reasoning item rides as a provider-shaped `thinkingSignature` blob, and the\n// OpenAI-completions transform (pi-ai) uses that blob as the *request field\n// name* when the history is handed to a different provider \u2014 landing prior\n// deliberation in a junk field while the real `reasoning_content` stays\n// empty. Signature-sensitive families (Anthropic) reject foreign signatures\n// outright. This module applies a family-aware policy to the fabric-owned\n// child session at the handoff boundary, where rewriting is safe because the\n// source session (ground truth) is never touched:\n//\n// preserved \u2014 same provider and api family: native replay already works.\n// re-signed \u2014 openai-completions reasoning targets: thinking text is kept\n// and the signature normalized to \"reasoning_content\" so preserve-thinking\n// servers (Kimi, DeepSeek, \u2026) actually receive prior reasoning.\n// stripped \u2014 everything else: thinking blocks and foreign thought\n// signatures are removed so no bogus field or invalid signature is sent;\n// a bounded, entry-id-cited digest keeps continuity instead.\n\ninterface ThinkingTransferSource {\n provider: string;\n modelId: string;\n /** pi-ai transport api of the source model, when the registry resolves it. */\n api?: string | undefined;\n}\n\ninterface ThinkingTransferTarget {\n provider: string;\n modelId: string;\n api?: string | undefined;\n reasoning?: boolean | undefined;\n /** Model replays thinking as visible text; deliberation must not leak there. */\n requiresThinkingAsText?: boolean | undefined;\n}\n\nexport interface ThinkingTransferInput {\n source?: ThinkingTransferSource;\n target: ThinkingTransferTarget;\n}\n\nexport type ThinkingTransferPolicy = \"preserved\" | \"re-signed\" | \"stripped\";\n\nexport interface ThinkingTransferReport {\n policy: ThinkingTransferPolicy;\n translated: number;\n dropped: number;\n}\n\n// Field name pi-ai emits when a thinking block's signature is exactly this\n// string (the opencode-go \"reasoning\" \u2192 \"reasoning_content\" remap proves the\n// convention): the request then carries real prior reasoning content.\nexport const REASONING_CONTENT_SIGNATURE = \"reasoning_content\";\n\nconst OPENAI_COMPLETIONS_API = \"openai-completions\";\n\nexport const thinkingTransferPolicy = (\n input: ThinkingTransferInput,\n): ThinkingTransferPolicy => {\n const { source, target } = input;\n // Same provider with equal or unknown apis: native replay is provider-shipped\n // and the default experience; only an api-proof mismatch transfers.\n if (\n source &&\n source.provider === target.provider &&\n (source.api === undefined || target.api === undefined || source.api === target.api)\n ) {\n return \"preserved\";\n }\n if (\n target.api === OPENAI_COMPLETIONS_API &&\n target.reasoning === true &&\n target.requiresThinkingAsText !== true\n ) {\n return \"re-signed\";\n }\n return \"stripped\";\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isThinkingPart = (part: unknown): part is Record<string, unknown> =>\n isRecord(part) && part.type === \"thinking\";\n\n// Clone-and-rewrite walk over assistant content parts. Also clears foreign\n// `thoughtSignature` artifacts (Google-style reasoning_details), which are as\n// provider-bound as thinking signatures. Callers own the input; the original\n// entries are never mutated.\nexport const translateThinkingForExecutor = (\n entries: SessionEntry[],\n policy: ThinkingTransferPolicy,\n): { entries: SessionEntry[]; report: ThinkingTransferReport } => {\n if (policy === \"preserved\") {\n return { entries, report: { policy, translated: 0, dropped: 0 } };\n }\n const clone = structuredClone(entries);\n let translated = 0;\n let dropped = 0;\n for (const entry of clone) {\n if (entry.type !== \"message\") continue;\n const message = (entry as SessionMessageEntry).message as {\n role?: unknown;\n content?: unknown;\n };\n if (message.role !== \"assistant\" || !Array.isArray(message.content)) continue;\n const kept: unknown[] = [];\n for (const part of message.content as unknown[]) {\n if (isRecord(part) && part.type === \"toolCall\") {\n delete part.thoughtSignature;\n kept.push(part);\n continue;\n }\n if (!isThinkingPart(part)) {\n kept.push(part);\n continue;\n }\n const text = typeof part.thinking === \"string\" ? part.thinking : \"\";\n if (policy === \"re-signed\" && part.redacted !== true && text.trim().length > 0) {\n part.thinkingSignature = REASONING_CONTENT_SIGNATURE;\n translated += 1;\n kept.push(part);\n continue;\n }\n dropped += 1;\n }\n message.content = kept;\n }\n return { entries: clone, report: { policy, translated, dropped } };\n};\n\nexport const THINKING_DIGEST_CUSTOM_TYPE = \"omp-fabric-handoff-thinking\";\n\nconst MAX_DIGEST_BLOCKS = 8;\nconst MAX_DIGEST_LINE = 80;\nconst MAX_DIGEST_BYTES = 2048;\n\nexport interface ThinkingDigest {\n content: string;\n citedBlocks: number;\n}\n\nconst firstLineOf = (text: string): string => {\n const end = text.indexOf(\"\\n\");\n return end === -1 ? text : text.slice(0, end);\n};\n\nconst truncate = (text: string, max: number): string =>\n text.length > max ? text.slice(0, max) : text;\n\nconst clipUtf8 = (text: string, maxBytes: number): string => {\n if (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n let out = \"\";\n let bytes = 0;\n for (const char of text) {\n const size = Buffer.byteLength(char, \"utf8\");\n if (bytes + size > maxBytes) break;\n out += char;\n bytes += size;\n }\n return out;\n};\n\n// Bounded continuity bridge for executors whose reasoning channel cannot\n// accept prior thinking: the newest few first-lines, cited by stable entry id,\n// explicitly labeled as deliberation so they read as context, not style. The\n// full scratchpad remains addressable in the source session.\nexport const buildThinkingDigest = (\n entries: SessionEntry[],\n input: ThinkingTransferInput,\n): ThinkingDigest | undefined => {\n const blocks: Array<{ entryId: string; line: string }> = [];\n for (const entry of entries) {\n if (entry.type !== \"message\") continue;\n const message = (entry as SessionMessageEntry).message as {\n role?: unknown;\n content?: unknown;\n };\n if (message.role !== \"assistant\" || !Array.isArray(message.content)) continue;\n for (const part of message.content as unknown[]) {\n if (!isThinkingPart(part)) continue;\n const text = typeof part.thinking === \"string\" ? part.thinking : \"\";\n const line = truncate(firstLineOf(text).trim(), MAX_DIGEST_LINE);\n if (line) blocks.push({ entryId: entry.id, line });\n }\n }\n if (blocks.length === 0) return undefined;\n const recent = blocks.slice(-MAX_DIGEST_BLOCKS);\n const omitted = blocks.length - recent.length;\n const sourceId = input.source\n ? `${input.source.provider}/${input.source.modelId}`\n : \"the prior model\";\n const targetId = `${input.target.provider}/${input.target.modelId}`;\n const lines = [\n \"Prewalk handoff continuity digest (deliberation, not commitments).\",\n `Thinking from ${sourceId} was not transferred: ${targetId} cannot replay it (incompatible reasoning channels). Most recent lines:`,\n ...recent.map((block) => `- [entry ${block.entryId}] ${block.line}`),\n ];\n if (omitted > 0) lines.push(`(omitted ${omitted} older thinking blocks)`);\n lines.push(\"Full thinking remains addressable in the source session by entry id.\");\n return {\n content: clipUtf8(lines.join(\"\\n\"), MAX_DIGEST_BYTES),\n citedBlocks: recent.length,\n };\n};\n", "import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n CURRENT_SESSION_VERSION,\n SessionManager,\n type SessionEntry,\n type SessionMessageEntry,\n} from \"@oh-my-pi/pi-coding-agent\";\nimport { compileFabricSummary, rawContextTokens } from \"../compaction/hook.js\";\nimport {\n compactionRequestBoundsError,\n encodeCompactionRequest,\n} from \"../compaction/instructions.js\";\nimport type {\n AgentSessionSeed,\n AgentToolResultMessage,\n HandoffCompactionRequest,\n} from \"./types.js\";\nimport {\n buildThinkingDigest,\n THINKING_DIGEST_CUSTOM_TYPE,\n thinkingTransferPolicy,\n translateThinkingForExecutor,\n type ThinkingTransferInput,\n type ThinkingTransferReport,\n} from \"./thinking-transfer.js\";\n\ninterface HandoffSessionSource {\n getBranch(): SessionEntry[];\n getEntry(id: string): SessionEntry | undefined;\n getLeafId(): string | null;\n getSessionFile(): string | undefined;\n getSessionId(): string;\n}\n\ninterface CurrentModel {\n provider: string;\n id: string;\n}\n\ntype NativeAssistantMessage = Extract<\n SessionMessageEntry[\"message\"],\n { role: \"assistant\" }\n>;\ntype NativeAssistantEntry = SessionMessageEntry & {\n message: NativeAssistantMessage;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\ninterface HandoffCompactionOutcome {\n applied: boolean;\n reason?: string;\n sections?: string[];\n tokensBefore?: number;\n firstKeptEntryId?: string;\n}\n\n// Validate the model-facing agents.handoff `compact` option against the same\n// bounds as compact.request. Called both when the request is scheduled (inside\n// the guest) and when the boundary runner replays it.\nexport const checkedHandoffCompaction = (\n value: unknown,\n): HandoffCompactionRequest | undefined => {\n if (value === undefined || value === false) return undefined;\n const input = value === true ? {} : value;\n if (!isRecord(input)) {\n throw new Error(\n \"Invalid agents.handoff compact arguments: compact must be true or an object with instructions/preserve\",\n );\n }\n if (input.instructions !== undefined && typeof input.instructions !== \"string\") {\n throw new Error(\"Invalid agents.handoff compact arguments: instructions must be a string\");\n }\n if (\n input.preserve !== undefined &&\n (!Array.isArray(input.preserve) || input.preserve.some((item) => typeof item !== \"string\"))\n ) {\n throw new Error(\n \"Invalid agents.handoff compact arguments: preserve must be an array of strings\",\n );\n }\n const request: HandoffCompactionRequest = {\n ...(typeof input.instructions === \"string\" ? { instructions: input.instructions } : {}),\n ...(input.preserve !== undefined ? { preserve: input.preserve as string[] } : {}),\n };\n const boundsError = compactionRequestBoundsError(request);\n if (boundsError) {\n throw new Error(`Invalid agents.handoff compact arguments: ${boundsError.message}`);\n }\n return request;\n};\n\nconst isToolCall = (value: unknown): value is {\n type: \"toolCall\";\n id: string;\n name: string;\n arguments: Record<string, unknown>;\n} =>\n isRecord(value) &&\n value.type === \"toolCall\" &&\n typeof value.id === \"string\" &&\n typeof value.name === \"string\" &&\n isRecord(value.arguments);\n\nconst activeFabricTurn = (\n source: HandoffSessionSource,\n outerToolCallId: string,\n): NativeAssistantEntry => {\n const leafId = source.getLeafId();\n const entry = leafId ? source.getEntry(leafId) : undefined;\n if (entry?.type !== \"message\" || entry.message.role !== \"assistant\") {\n throw new Error(\n \"Trajectory handoff requires the active fabric_exec assistant turn to be the session leaf\",\n );\n }\n const content = Array.isArray(entry.message.content) ? entry.message.content : [];\n const toolCalls = content.filter(isToolCall);\n if (!toolCalls.some((call) => call.id === outerToolCallId)) {\n throw new Error(\n \"Trajectory handoff could not find the active fabric_exec assistant turn in the OMP session\",\n );\n }\n if (toolCalls.length !== 1 || toolCalls[0]?.name !== \"fabric_exec\") {\n throw new Error(\n \"Trajectory handoff requires fabric_exec to be the only top-level tool call in its assistant turn\",\n );\n }\n return entry as NativeAssistantEntry;\n};\n\nexport const snapshotHandoffSession = (\n source: HandoffSessionSource,\n currentModel: CurrentModel | undefined,\n outerToolResult: AgentToolResultMessage,\n outerToolCallId: string,\n carryBranch = false,\n): AgentSessionSeed => {\n if (\n outerToolResult.toolCallId !== outerToolCallId ||\n outerToolResult.toolName !== \"fabric_exec\"\n ) {\n throw new Error(\"Trajectory handoff requires the finalized outer fabric_exec result\");\n }\n const active = activeFabricTurn(source, outerToolCallId);\n const sourceSessionFile = source.getSessionFile();\n const branch = source.getBranch();\n let model = currentModel\n ? { provider: currentModel.provider, modelId: currentModel.id }\n : undefined;\n let thinkingLevel: string | undefined;\n for (let index = branch.length - 1; index >= 0; index--) {\n const entry = branch[index];\n if (!thinkingLevel && entry?.type === \"thinking_level_change\") {\n thinkingLevel = entry.thinkingLevel ?? undefined;\n }\n if (!model && entry?.type === \"model_change\") {\n const separator = entry.model.indexOf(\"/\");\n if (separator > 0 && separator < entry.model.length - 1) {\n model = { provider: entry.model.slice(0, separator), modelId: entry.model.slice(separator + 1) };\n }\n }\n if (model && thinkingLevel) break;\n }\n return {\n sourceSessionId: source.getSessionId(),\n ...(sourceSessionFile ? { sourceSessionFile } : {}),\n sourceBranchLeafId: active.id,\n ...(!sourceSessionFile || carryBranch ? { sourceBranch: structuredClone(branch) } : {}),\n ...(model ? { sourceModel: model } : {}),\n ...(thinkingLevel ? { sourceThinkingLevel: thinkingLevel } : {}),\n outerToolResult: structuredClone(outerToolResult),\n };\n};\n\nconst materializeBranch = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n): Promise<SessionManager> => {\n if (!seed.sourceBranch) {\n throw new Error(\"In-memory trajectory handoff is missing its source branch\");\n }\n const id = randomUUID();\n const sessionFile = path.join(directory, `handoff-${id}.jsonl`);\n const header = {\n type: \"session\" as const,\n version: CURRENT_SESSION_VERSION,\n id,\n timestamp: new Date().toISOString(),\n cwd,\n ...(seed.sourceSessionFile ? { parentSession: seed.sourceSessionFile } : {}),\n };\n fs.writeFileSync(\n sessionFile,\n `${[header, ...seed.sourceBranch].map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n`,\n { encoding: \"utf8\", mode: 0o600, flag: \"wx\" },\n );\n return SessionManager.open(sessionFile, directory, undefined, { initialCwd: cwd });\n};\n\nconst forkBranch = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n): Promise<SessionManager> => {\n if (!seed.sourceSessionFile) return materializeBranch(seed, cwd, directory);\n const fork = await SessionManager.open(seed.sourceSessionFile, directory, undefined, { initialCwd: cwd });\n if (!fork.getEntry(seed.sourceBranchLeafId)) {\n throw new Error(\n `Trajectory handoff branch point ${seed.sourceBranchLeafId} is missing from the persisted OMP session`,\n );\n }\n fork.createBranchedSession(seed.sourceBranchLeafId);\n const sessionFile = fork.getSessionFile();\n if (!sessionFile) {\n throw new Error(\"Trajectory handoff could not create a persisted OMP session branch\");\n }\n return SessionManager.open(sessionFile, directory, undefined, { initialCwd: cwd });\n};\n\n// File-backed read of the exact branch prefix, cloned so transfer translation\n// never mutates the source session's live entries. Used instead of\n// forkBranch when the executor's reasoning channel differs: createBranchedSession\n// copies raw lines and cannot rewrite foreign thinking signatures.\nconst persistedBranch = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n): Promise<SessionEntry[]> => {\n if (!seed.sourceSessionFile) {\n throw new Error(\"Persisted trajectory handoff is missing its source session file\");\n }\n const source = await SessionManager.open(seed.sourceSessionFile, directory, undefined, { initialCwd: cwd });\n if (!source.getEntry(seed.sourceBranchLeafId)) {\n throw new Error(\n `Trajectory handoff branch point ${seed.sourceBranchLeafId} is missing from the persisted OMP session`,\n );\n }\n return structuredClone(source.getBranch(seed.sourceBranchLeafId));\n};\n\nconst synchronizeSourceSettings = (\n session: SessionManager,\n seed: AgentSessionSeed,\n): void => {\n const context = session.buildSessionContext();\n const currentModel = context.models.default;\n const sourceModel = seed.sourceModel\n ? `${seed.sourceModel.provider}/${seed.sourceModel.modelId}`\n : undefined;\n if (sourceModel && currentModel !== sourceModel) session.appendModelChange(sourceModel);\n if (seed.sourceThinkingLevel && context.thinkingLevel !== seed.sourceThinkingLevel) {\n session.appendThinkingLevelChange(seed.sourceThinkingLevel);\n }\n};\n\nexport const writeHandoffSession = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n transfer?: ThinkingTransferInput,\n compaction?: HandoffCompactionRequest,\n): Promise<string> => {\n fs.mkdirSync(directory, { recursive: true, mode: 0o700 });\n const policy = transfer ? thinkingTransferPolicy(transfer) : \"preserved\";\n let session: SessionManager;\n let report: ThinkingTransferReport | undefined;\n let digest: { content: string; citedBlocks: number } | undefined;\n if (!transfer || policy === \"preserved\") {\n session = seed.sourceBranchRetired && seed.sourceBranch\n ? await materializeBranch(seed, cwd, directory)\n : await forkBranch(seed, cwd, directory);\n } else {\n const rawBranch = seed.sourceBranchRetired && seed.sourceBranch\n ? structuredClone(seed.sourceBranch)\n : seed.sourceSessionFile\n ? await persistedBranch(seed, cwd, directory)\n : structuredClone(seed.sourceBranch ?? (() => {\n throw new Error(\"Trajectory handoff transfer is missing its source branch\");\n })());\n if (policy === \"stripped\") digest = buildThinkingDigest(rawBranch, transfer);\n const translated = translateThinkingForExecutor(rawBranch, policy);\n report = translated.report;\n session = await materializeBranch({ ...seed, sourceBranch: translated.entries }, cwd, directory);\n }\n // Append the compaction entry before settings sync and the outer tool result\n // so the executor's context opens with the deterministic summary, followed\n // by the kept tail, then the boundary artifacts appended afterwards. The\n // file retains the full raw branch, mirroring OMP's append-only compaction.\n let compactionOutcome: HandoffCompactionOutcome | undefined;\n if (compaction) {\n const branchEntries = session.getBranch();\n const customInstructions = compaction.preserve\n ? encodeCompactionRequest({\n ...(compaction.instructions !== undefined\n ? { instructions: compaction.instructions }\n : {}),\n preserve: compaction.preserve,\n })\n : compaction.instructions;\n const tokensBefore = rawContextTokens(branchEntries);\n const compiled = compileFabricSummary(branchEntries, tokensBefore, undefined, customInstructions);\n if (\"cancel\" in compiled) {\n compactionOutcome = { applied: false, reason: compiled.reason };\n } else {\n session.appendCompaction(\n compiled.compaction.summary,\n undefined,\n compiled.compaction.firstKeptEntryId,\n tokensBefore,\n compiled.compaction.details\n ? { details: compiled.compaction.details, fromExtension: true }\n : { fromExtension: true },\n );\n compactionOutcome = {\n applied: true,\n sections: compiled.compaction.details?.sections ?? [],\n tokensBefore,\n firstKeptEntryId: compiled.compaction.firstKeptEntryId,\n };\n }\n }\n synchronizeSourceSettings(session, seed);\n session.appendMessage(seed.outerToolResult);\n if (digest) {\n session.appendCustomMessageEntry(THINKING_DIGEST_CUSTOM_TYPE, digest.content, false, {\n policy,\n citedBlocks: digest.citedBlocks,\n });\n }\n session.appendCustomEntry(\"omp-fabric-handoff\", {\n sourceSessionId: seed.sourceSessionId,\n boundary: \"fabric_exec_end\",\n ...(compactionOutcome\n ? {\n compaction: compactionOutcome.applied\n ? {\n applied: true,\n sections: compactionOutcome.sections,\n tokensBefore: compactionOutcome.tokensBefore,\n firstKeptEntryId: compactionOutcome.firstKeptEntryId,\n }\n : { applied: false, reason: compactionOutcome.reason },\n }\n : {}),\n ...(transfer && report\n ? {\n thinkingTransfer: {\n policy: report.policy,\n translated: report.translated,\n dropped: report.dropped,\n target: `${transfer.target.provider}/${transfer.target.modelId}`,\n },\n }\n : {}),\n });\n const sessionFile = session.getSessionFile();\n if (!sessionFile) throw new Error(\"Trajectory handoff did not produce an OMP session file\");\n fs.chmodSync(sessionFile, 0o600);\n return sessionFile;\n};\n", "import type { FabricPeerInfo } from \"./types.js\";\n\n/** Quiet window after a peer's last observed activity before it counts as settled. */\nconst DEFAULT_PEER_SETTLED_FOR_MS = 3_000;\nconst PEER_SETTLE_POLL_MS = 500;\n\n/**\n * Derive a Linear-style label prefix from a project path's basename:\n * \"pi-queue-steer\" -> \"PQS\", \"fabric\" -> \"FAB\". Falls back to \"P\".\n */\nexport const peerLabelPrefix = (cwd: string | undefined): string => {\n\tconst base = cwd?.split(/[\\\\/]/).filter(Boolean).at(-1) ?? \"\";\n\tconst words = base.split(/[^A-Za-z0-9]+/).filter(Boolean);\n\tif (words.length === 0) return \"P\";\n\t// Single-word projects borrow the first letters (\"fabric\" -> \"FAB\"),\n\t// multi-word projects take word initials (\"pi-queue-steer\" -> \"PQS\").\n\tif (words.length === 1) return words[0]!.slice(0, 3).toUpperCase();\n\treturn words\n\t\t.slice(0, 4)\n\t\t.map((word) => word[0]!.toUpperCase())\n\t\t.join(\"\");\n};\n\n/** Snapshot of one root peer session for pickers and status lines. */\nexport interface FabricPeerCard {\n\tid: string;\n\tlabel: string;\n\tstatus: \"idle\" | \"running\";\n\tmodel?: string;\n\tcwd?: string;\n\tstartedAt: number;\n\tupdatedAt: number;\n\tpendingMessages: boolean;\n}\n\n/** Labels are chronological, so creation order is simply label minting order. */\nexport const buildPeerCards = (peers: readonly FabricPeerInfo[]): FabricPeerCard[] =>\n\t[...peers]\n\t\t.sort((left, right) => left.startedAt - right.startedAt || left.id.localeCompare(right.id))\n\t\t.map((peer) => ({\n\t\t\tid: peer.id,\n\t\t\tlabel: peer.label ?? peer.name,\n\t\t\tstatus: peer.status,\n\t\t\t...(peer.model ? { model: peer.model } : {}),\n\t\t\t...(peer.cwd ? { cwd: peer.cwd } : {}),\n\t\t\tstartedAt: peer.startedAt,\n\t\t\tupdatedAt: peer.updatedAt,\n\t\t\tpendingMessages: peer.pendingMessages,\n\t\t}));\n\ninterface PeerSettleProgress {\n\twaiting: Array<{ label: string; status: \"idle\" | \"running\" }>;\n}\n\nexport type PeerSettleResult = { ok: true } | { ok: false; error: string };\n\nexport interface AwaitPeerSettleOptions {\n\t/** Fresh peer snapshot source (typically FabricRuntimeState.peerInfos()). */\n\tpoll: () => FabricPeerInfo[];\n\t/** Peer label (case-insensitive) or exact participant id. Omitted means all peers. */\n\tselector?: string;\n\tsettledForMs?: number;\n\tpollMs?: number;\n\tnow?: () => number;\n\tsignal?: AbortSignal;\n\tonUpdate?: (progress: PeerSettleProgress) => void;\n}\n\nconst matchesSelector = (peer: FabricPeerInfo, selector: string): boolean => {\n\tconst target = selector.trim().toLowerCase();\n\tif (!target) return false;\n\treturn (\n\t\tpeer.id.toLowerCase() === target ||\n\t\t(peer.label ?? \"\").toLowerCase() === target ||\n\t\tpeer.name.toLowerCase() === target\n\t);\n};\n\ninterface WatchedPeer {\n\tid: string;\n\tlabel: string;\n\trunning: boolean;\n\t/** Last time the peer was observed running; undefined when quiet since arming. */\n\tlastRunningAt: number | undefined;\n\tsettled: boolean;\n}\n\n/**\n * Wait until every watched peer has settled: only runs that started after\n * arming delay it (an idle-at-arm peer satisfies once the quiet window\n * passes), and a peer vanishing from the mesh counts as settled since it can\n * no longer conflict.\n */\nexport const awaitPeerSettle = (options: AwaitPeerSettleOptions): Promise<PeerSettleResult> => {\n\tconst now = options.now ?? (() => Date.now());\n\tconst settledFor = Math.max(0, options.settledForMs ?? DEFAULT_PEER_SETTLED_FOR_MS);\n\tconst pollMs = Math.max(10, options.pollMs ?? PEER_SETTLE_POLL_MS);\n\tconst armedAt = now();\n\tconst initial = options.poll();\n\tconst targets =\n\t\toptions.selector !== undefined\n\t\t\t? initial.filter((peer) => matchesSelector(peer, options.selector ?? \"\"))\n\t\t\t: [...initial];\n\tif (options.selector !== undefined && targets.length === 0) {\n\t\treturn Promise.resolve({\n\t\t\tok: false,\n\t\t\terror: `No Fabric peer matches \"${options.selector}\" on this project mesh`,\n\t\t});\n\t}\n\tif (targets.length === 0) return Promise.resolve({ ok: true });\n\n\tconst watched = new Map<string, WatchedPeer>();\n\tfor (const peer of targets) {\n\t\twatched.set(peer.id, {\n\t\t\tid: peer.id,\n\t\t\tlabel: peer.label ?? peer.name,\n\t\t\trunning: peer.status === \"running\",\n\t\t\tlastRunningAt: peer.status === \"running\" ? armedAt : undefined,\n\t\t\tsettled: false,\n\t\t});\n\t}\n\n\treturn new Promise<PeerSettleResult>((resolve) => {\n\t\tlet timer: ReturnType<typeof setInterval> | undefined;\n\t\tlet done = false;\n\t\tconst finish = (result: PeerSettleResult): void => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tif (timer) clearInterval(timer);\n\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve(result);\n\t\t};\n\t\tconst onAbort = (): void => finish({ ok: false, error: \"cancelled\" });\n\t\tconst tick = (): void => {\n\t\t\tconst snapshot = options.poll();\n\t\t\tconst byId = new Map(snapshot.map((peer) => [peer.id, peer] as const));\n\t\t\tconst current = now();\n\t\t\tfor (const entry of watched.values()) {\n\t\t\t\tif (entry.settled) continue;\n\t\t\t\tconst peer = byId.get(entry.id);\n\t\t\t\tif (!peer) {\n\t\t\t\t\tentry.settled = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tentry.label = peer.label ?? peer.name;\n\t\t\t\tconst running = peer.status === \"running\";\n\t\t\t\tif (running) {\n\t\t\t\t\tentry.lastRunningAt = current;\n\t\t\t\t\tentry.running = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tentry.running = false;\n\t\t\t\tconst quietSince = entry.lastRunningAt ?? armedAt;\n\t\t\t\tif (current - quietSince >= settledFor) entry.settled = true;\n\t\t\t}\n\t\t\tconst waiting = [...watched.values()]\n\t\t\t\t.filter((entry) => !entry.settled)\n\t\t\t\t.map((entry) => ({ label: entry.label, status: entry.running ? \"running\" : \"idle\" }) as const);\n\t\t\tif (waiting.length === 0) {\n\t\t\t\toptions.onUpdate?.({ waiting });\n\t\t\t\tfinish({ ok: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toptions.onUpdate?.({ waiting });\n\t\t};\n\t\tif (options.signal) {\n\t\t\tif (options.signal.aborted) {\n\t\t\t\tfinish({ ok: false, error: \"cancelled\" });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toptions.signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\t\ttimer = setInterval(tick, pollMs);\n\t\ttick();\n\t});\n};\n"],
5
+ "mappings": ";;;;;;;;AAyDO,IAAM,8BAA8B;AAE3C,IAAM,yBAAyB;AAExB,IAAM,yBAAyB,CACpC,UAC2B;AAC3B,QAAM,EAAE,QAAQ,OAAO,IAAI;AAG3B,MACE,UACA,OAAO,aAAa,OAAO,aAC1B,OAAO,QAAQ,UAAa,OAAO,QAAQ,UAAa,OAAO,QAAQ,OAAO,MAC/E;AACA,WAAO;AAAA,EACT;AACA,MACE,OAAO,QAAQ,0BACf,OAAO,cAAc,QACrB,OAAO,2BAA2B,MAClC;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,IAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAErE,IAAM,iBAAiB,CAAC,SACtB,SAAS,IAAI,KAAK,KAAK,SAAS;AAM3B,IAAM,+BAA+B,CAC1C,SACA,WACgE;AAChE,MAAI,WAAW,aAAa;AAC1B,WAAO,EAAE,SAAS,QAAQ,EAAE,QAAQ,YAAY,GAAG,SAAS,EAAE,EAAE;AAAA,EAClE;AACA,QAAM,QAAQ,gBAAgB,OAAO;AACrC,MAAI,aAAa;AACjB,MAAI,UAAU;AACd,aAAW,SAAS,OAAO;AACzB,QAAI,MAAM,SAAS,UAAW;AAC9B,UAAM,UAAW,MAA8B;AAI/C,QAAI,QAAQ,SAAS,eAAe,CAAC,MAAM,QAAQ,QAAQ,OAAO,EAAG;AACrE,UAAM,OAAkB,CAAC;AACzB,eAAW,QAAQ,QAAQ,SAAsB;AAC/C,UAAI,SAAS,IAAI,KAAK,KAAK,SAAS,YAAY;A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,UAAU;AAAA,MACzD;AACA,YAAM,UAAU,CAAC,GAAG,QAAQ,OAAO,CAAC,EAClC,OAAO,CAAC,UAAU,CAAC,MAAM,OAAO,EAChC,IAAI,CAAC,WAAW,EAAE,OAAO,MAAM,OAAO,QAAQ,MAAM,UAAU,YAAY,OAAO,EAAW;AAC9F,UAAI,QAAQ,WAAW,GAAG;AACzB,gBAAQ,WAAW,EAAE,QAAQ,CAAC;AAC9B,eAAO,EAAE,IAAI,KAAK,CAAC;AACnB;AAAA,MACD;AACA,cAAQ,WAAW,EAAE,QAAQ,CAAC;AAAA,IAC/B;AACA,QAAI,QAAQ,QAAQ;AACnB,UAAI,QAAQ,OAAO,SAAS;AAC3B,eAAO,EAAE,IAAI,OAAO,OAAO,YAAY,CAAC;AACxC;AAAA,MACD;AACA,cAAQ,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAAA,IACjE;AACA,YAAQ,YAAY,MAAM,MAAM;AAChC,SAAK;AAAA,EACN,CAAC;AACF;",
6
+ "names": ["isRecord"]
7
+ }
@@ -689,6 +689,7 @@ globalThis.state = __providerProxy("state");
689
689
  globalThis.schema = __providerProxy("schema");
690
690
  globalThis.components = __providerProxy("components");
691
691
  globalThis.compact = __providerProxy("compact");
692
+ globalThis.codemap = __providerProxy("codemap");
692
693
  const __createActor = async (args = {}) => {
693
694
  if (!args || typeof args !== "object" || Array.isArray(args)) {
694
695
  throw new TypeError("agents.create expects an options object");
@@ -1359,4 +1360,4 @@ export {
1359
1360
  GUEST_SETUP,
1360
1361
  QuickJsRuntime
1361
1362
  };
1362
- //# sourceMappingURL=chunk-L2FNMIOW.js.map
1363
+ //# sourceMappingURL=chunk-QNRGTJGE.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\");\nglobalThis.codemap = __providerProxy(\"codemap\");\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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
6
+ "names": ["value"]
7
+ }
@@ -21,13 +21,13 @@ import {
21
21
  import {
22
22
  peerLabelPrefix,
23
23
  writeHandoffSession
24
- } from "./chunk-YPYVUGON.js";
24
+ } from "./chunk-JOWMM3EX.js";
25
25
  import {
26
26
  DEFAULT_FABRIC_CONFIG,
27
27
  MAX_AGENT_TIMEOUT_MS,
28
28
  MIN_AGENT_TIMEOUT_MS,
29
29
  resolveAgentDir
30
- } from "./chunk-EZPERYEG.js";
30
+ } from "./chunk-XRJYPNTI.js";
31
31
  import {
32
32
  FABRIC_ACTOR_HOST_EVENTS,
33
33
  readJsonlPage
@@ -6635,4 +6635,4 @@ export {
6635
6635
  agentParticipantRecords,
6636
6636
  actorParticipantRecord
6637
6637
  };
6638
- //# sourceMappingURL=chunk-WXZP5VWP.js.map
6638
+ //# sourceMappingURL=chunk-TQL7FKMG.js.map
@@ -1223,6 +1223,51 @@ interface FabricCompactApi {
1223
1223
  cancel(): Promise<{ cancelled: true }>;
1224
1224
  }
1225
1225
 
1226
+ interface FabricCodemapSymbolCounts {
1227
+ files: number;
1228
+ symbols: number;
1229
+ languages: Record<string, number>;
1230
+ fallbackFiles: number;
1231
+ truncated: boolean;
1232
+ elapsedMs: number;
1233
+ }
1234
+ interface FabricCodemapCascadeEdge {
1235
+ file: string;
1236
+ score: number;
1237
+ commits: number;
1238
+ }
1239
+ interface FabricCodemapCascade {
1240
+ seeds: string[];
1241
+ edges: FabricCodemapCascadeEdge[];
1242
+ commitsScanned: number;
1243
+ truncated: boolean;
1244
+ unavailable?: string;
1245
+ }
1246
+ interface FabricCodemapApi {
1247
+ map(args?: {
1248
+ maxTokens?: number;
1249
+ glob?: string;
1250
+ focus?: string;
1251
+ seeds?: string[];
1252
+ refresh?: boolean;
1253
+ }): Promise<{
1254
+ text: string;
1255
+ tokensEstimated: number;
1256
+ filesShown: number;
1257
+ symbolsShown: number;
1258
+ omittedFiles: number;
1259
+ omittedSymbols: number;
1260
+ truncated: boolean;
1261
+ indexed: FabricCodemapSymbolCounts;
1262
+ cascade?: FabricCodemapCascade;
1263
+ }>;
1264
+ cascade(args: {
1265
+ seeds: string[];
1266
+ limit?: number;
1267
+ maxCommits?: number;
1268
+ }): Promise<FabricCodemapCascade>;
1269
+ }
1270
+
1226
1271
  interface FabricWorkflowAgentOptions extends Omit<FabricAgentRequest, "task"> {
1227
1272
  label?: string;
1228
1273
  }
@@ -1276,6 +1321,7 @@ declare const state: FabricStateApi;
1276
1321
  declare const schema: FabricSchemaApi;
1277
1322
  declare const components: FabricComponentsApi;
1278
1323
  declare const compact: FabricCompactApi;
1324
+ declare const codemap: FabricCodemapApi;
1279
1325
  declare const council: FabricCouncilApi;
1280
1326
  declare const workflow: FabricWorkflowApi;
1281
1327
  declare function agent<T = string>(prompt: string, options?: FabricWorkflowAgentOptions): Promise<T>;
@@ -1348,4 +1394,4 @@ export {
1348
1394
  GUEST_TYPE_DECLARATIONS,
1349
1395
  guestTypeDeclarations
1350
1396
  };
1351
- //# sourceMappingURL=chunk-Z6HEQPXX.js.map
1397
+ //# sourceMappingURL=chunk-WGFHMECI.js.map