pi-fabric 0.72.0 → 0.74.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.
- package/dist/capture/interceptor.d.ts.map +1 -1
- package/dist/chunks/{chunk-2QWHMYR7.js → chunk-5OKJP5PD.js} +17 -6
- package/dist/chunks/chunk-5OKJP5PD.js.map +7 -0
- package/dist/chunks/{chunk-R7MJZJX2.js → chunk-6NYBEXUT.js} +25 -37
- package/dist/chunks/chunk-6NYBEXUT.js.map +7 -0
- package/dist/chunks/{chunk-KJ3XSDAH.js → chunk-FAVEJYQZ.js} +5 -2
- package/dist/chunks/{chunk-KJ3XSDAH.js.map → chunk-FAVEJYQZ.js.map} +2 -2
- package/dist/chunks/{chunk-GBSBDO2H.js → chunk-M5ANI67T.js} +3 -3
- package/dist/chunks/chunk-PAN6C3JM.js +42 -0
- package/dist/chunks/chunk-PAN6C3JM.js.map +7 -0
- package/dist/chunks/{chunk-TEGUENKB.js → chunk-SJYOKQJT.js} +1 -1
- package/dist/chunks/{chunk-TEGUENKB.js.map → chunk-SJYOKQJT.js.map} +2 -2
- package/dist/chunks/{chunk-D4P4UTH6.js → chunk-YYODET6T.js} +8 -391
- package/dist/chunks/chunk-YYODET6T.js.map +7 -0
- package/dist/chunks/{dashboard-RPCGC33N.js → dashboard-2RGAN2WT.js} +2 -2
- package/dist/chunks/{fabric-runtime-state-RTHTHOLE.js → fabric-runtime-state-FBDHAKPF.js} +549 -143
- package/dist/chunks/fabric-runtime-state-FBDHAKPF.js.map +7 -0
- package/dist/chunks/{node-process-runtime-7ZPXPYUM.js → node-process-runtime-AFV55TEV.js} +12 -4
- package/dist/chunks/node-process-runtime-AFV55TEV.js.map +7 -0
- package/dist/chunks/{quickjs-runtime-Q4VOPWNO.js → quickjs-runtime-C75KPH77.js} +3 -2
- package/dist/chunks/{settings-ILDKW6BG.js → settings-ISH7S23I.js} +31 -30
- package/dist/chunks/settings-ISH7S23I.js.map +7 -0
- package/dist/config.d.ts +9 -11
- package/dist/config.d.ts.map +1 -1
- package/dist/core/action-registry.d.ts.map +1 -1
- package/dist/core/action-registry.js +1 -1
- package/dist/core/pi-bash-error.d.ts +9 -0
- package/dist/core/pi-bash-error.d.ts.map +1 -0
- package/dist/core/system-guidance.d.ts +3 -2
- package/dist/core/system-guidance.d.ts.map +1 -1
- package/dist/execution-service.d.ts +4 -0
- package/dist/execution-service.d.ts.map +1 -1
- package/dist/fabric-exec-arguments.d.ts.map +1 -1
- package/dist/fabric-exec-tool.d.ts.map +1 -1
- package/dist/fabric-runtime-state.d.ts +3 -5
- package/dist/fabric-runtime-state.d.ts.map +1 -1
- package/dist/fabric-state.d.ts +3 -7
- package/dist/fabric-state.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +57 -751
- package/dist/index.js.map +4 -4
- package/dist/lifecycle/delivery-scheduler.d.ts +30 -0
- package/dist/lifecycle/delivery-scheduler.d.ts.map +1 -0
- package/dist/providers/agents-provider.d.ts +2 -0
- package/dist/providers/agents-provider.d.ts.map +1 -1
- package/dist/providers/captured-tools-provider.d.ts +2 -4
- package/dist/providers/captured-tools-provider.d.ts.map +1 -1
- package/dist/providers/mcp-provider.d.ts +0 -3
- package/dist/providers/mcp-provider.d.ts.map +1 -1
- package/dist/providers/pi-tools-provider.d.ts.map +1 -1
- package/dist/residency/host.js +2 -2
- package/dist/runtime/node-process-child-source.d.ts.map +1 -1
- package/dist/runtime/node-process-runtime.d.ts.map +1 -1
- package/dist/runtime/quickjs-runtime.d.ts +1 -1
- package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
- package/dist/ui/fabric-render.d.ts.map +1 -1
- package/dist/ui/row-balance.d.ts +1 -1
- package/dist/ui/row-balance.d.ts.map +1 -1
- package/dist/ui/settings.d.ts.map +1 -1
- package/docs/architecture.md +21 -0
- package/docs/components.md +1 -1
- package/docs/configuration.md +36 -4
- package/package.json +7 -2
- package/skills/fabric-exec/references/agents.md +4 -0
- package/dist/chunks/chunk-2QWHMYR7.js.map +0 -7
- package/dist/chunks/chunk-D4P4UTH6.js.map +0 -7
- package/dist/chunks/chunk-R7MJZJX2.js.map +0 -7
- package/dist/chunks/fabric-runtime-state-RTHTHOLE.js.map +0 -7
- package/dist/chunks/node-process-runtime-7ZPXPYUM.js.map +0 -7
- package/dist/chunks/settings-ILDKW6BG.js.map +0 -7
- package/dist/core/capability-advisory.d.ts +0 -39
- package/dist/core/capability-advisory.d.ts.map +0 -1
- package/dist/core/capability-fingerprint.d.ts +0 -26
- package/dist/core/capability-fingerprint.d.ts.map +0 -1
- package/dist/providers/mcp-advisory.d.ts +0 -10
- package/dist/providers/mcp-advisory.d.ts.map +0 -1
- package/docs/capability-combustion.md +0 -269
- /package/dist/chunks/{chunk-GBSBDO2H.js.map → chunk-M5ANI67T.js.map} +0 -0
- /package/dist/chunks/{dashboard-RPCGC33N.js.map → dashboard-2RGAN2WT.js.map} +0 -0
- /package/dist/chunks/{quickjs-runtime-Q4VOPWNO.js.map → quickjs-runtime-C75KPH77.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interceptor.d.ts","sourceRoot":"","sources":["../../src/capture/interceptor.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,eAAe,EAEf,cAAc,EACf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAyB,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAQnD,MAAM,WAAW,+BAA+B;IAC9C,SAAS,CAAC,MAAM,EAAE,uBAAuB,GAAG,IAAI,CAAC;IACjD,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,4BAA4B;IAC3C,gBAAgB,EAAE,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;IAChD,OAAO,EAAE,mBAAmB,CAAC;IAC7B,aAAa,CAAC,EAAE,uBAAuB,CAAC;IAOxC,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;CAC/B;
|
|
1
|
+
{"version":3,"file":"interceptor.d.ts","sourceRoot":"","sources":["../../src/capture/interceptor.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,eAAe,EAEf,cAAc,EACf,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAyB,KAAK,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAQnD,MAAM,WAAW,+BAA+B;IAC9C,SAAS,CAAC,MAAM,EAAE,uBAAuB,GAAG,IAAI,CAAC;IACjD,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,4BAA4B;IAC3C,gBAAgB,EAAE,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;IAChD,OAAO,EAAE,mBAAmB,CAAC;IAC7B,aAAa,CAAC,EAAE,uBAAuB,CAAC;IAOxC,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;CAC/B;AAyBD,KAAK,0BAA0B,GAAG;IAChC,SAAS,EAAE,eAAe,CAAC;CAC5B,CAAC;AAaF,eAAO,MAAM,iCAAiC,GAC5C,WAAW,MAAM,KAChB,OAAO,CAAC,0BAA0B,EAAE,CAuBtC,CAAC;AAmFF,eAAO,MAAM,4BAA4B,GACvC,SAAS,4BAA4B,KACpC,OAAO,CAAC,+BAA+B,CAuCzC,CAAC"}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
transpileFabricCodeWithSourceMap
|
|
3
3
|
} from "./chunk-UWMY7KQW.js";
|
|
4
|
+
import {
|
|
5
|
+
piBashExitMetadata
|
|
6
|
+
} from "./chunk-PAN6C3JM.js";
|
|
4
7
|
import {
|
|
5
8
|
runAbortable,
|
|
6
9
|
settleWithin
|
|
@@ -437,14 +440,16 @@ globalThis.pi = new Proxy({}, {
|
|
|
437
440
|
typeof args === "object" && args !== null && args.settle === true;
|
|
438
441
|
const call = __call("pi." + name, __normalizePiArgs(name, args));
|
|
439
442
|
const promise = settle ? call.catch((error) => {
|
|
440
|
-
|
|
441
|
-
const
|
|
442
|
-
|
|
443
|
+
// node-process bridge errors originate in a different VM realm.
|
|
444
|
+
const message = typeof error?.message === "string" ? error.message : String(error);
|
|
445
|
+
const exit = error?.__fabricBashExit;
|
|
446
|
+
if (!exit || !Number.isSafeInteger(exit.exitCode) || exit.exitCode <= 0 ||
|
|
447
|
+
typeof exit.output !== "string") throw error;
|
|
443
448
|
return {
|
|
444
449
|
ok: false,
|
|
445
|
-
output:
|
|
450
|
+
output: exit.output,
|
|
446
451
|
details: null,
|
|
447
|
-
exitCode:
|
|
452
|
+
exitCode: exit.exitCode,
|
|
448
453
|
error: message,
|
|
449
454
|
};
|
|
450
455
|
}) : call;
|
|
@@ -974,6 +979,12 @@ var QuickJsRuntime = class {
|
|
|
974
979
|
const errorHandle = context.newError(
|
|
975
980
|
error instanceof Error ? error.message : String(error)
|
|
976
981
|
);
|
|
982
|
+
const exit = reference === "pi.bash" ? piBashExitMetadata(error) : void 0;
|
|
983
|
+
if (exit) {
|
|
984
|
+
const metadata = jsonHandle(context, jsonObject, jsonParse, exit);
|
|
985
|
+
context.setProp(errorHandle, "__fabricBashExit", metadata);
|
|
986
|
+
metadata.dispose();
|
|
987
|
+
}
|
|
977
988
|
promise.reject(errorHandle);
|
|
978
989
|
errorHandle.dispose();
|
|
979
990
|
}).finally(() => {
|
|
@@ -1143,4 +1154,4 @@ export {
|
|
|
1143
1154
|
GUEST_SETUP,
|
|
1144
1155
|
QuickJsRuntime
|
|
1145
1156
|
};
|
|
1146
|
-
//# sourceMappingURL=chunk-
|
|
1157
|
+
//# sourceMappingURL=chunk-5OKJP5PD.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 { runAbortable, settleWithin } from \"../async-settlement.js\";\nimport { piBashExitMetadata } from \"../core/pi-bash-error.js\";\nimport { createGuestStackMap, remapGuestErrorText } from \"./guest-stack-map.js\";\nimport { transpileFabricCodeWithSourceMap } from \"./type-checker.js\";\n\nexport type FabricSandboxTerminationReason =\n | \"completed\"\n | \"runtime_error\"\n | \"timed_out\"\n | \"aborted\";\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 strings?: Record<string, string>;\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 \u03C0.<identifier> references (bracket access like \u03C0[k] is not provable).\nconst PI_REF_PATTERN = /(?:^|[^\\w$.])\u03C0\\.([A-Za-z_$][\\w$]*)/g;\n\n// Models routinely reference \u03C0.<key> without providing the strings parameter,\n// and the runtime error only lands after a full execution round trip (#68).\n// Reject up front when a referenced key is statically provable missing, before\n// QuickJS is even loaded.\nconst missingStringsKeys = (\n code: string,\n strings: Record<string, string> | undefined,\n): string[] => {\n const provided = strings ?? {};\n const missing: string[] = [];\n for (const match of code.matchAll(PI_REF_PATTERN)) {\n const key = match[1];\n if (key === undefined || key in provided) continue;\n if (!missing.includes(key)) missing.push(key);\n }\n return missing;\n};\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 __piToolNames = [\"read\",\"bash\",\"edit\",\"write\",\"grep\",\"find\",\"ls\"];\nconst __toolsBase = {\n providers: () => __call(\"fabric.$providers\", {}),\n catalog: (args = {}) => __call(\"fabric.$catalog\", args),\n list: (args = {}) => __call(\"fabric.$list\", args),\n search: (args) => __call(\n \"fabric.$search\",\n typeof args === \"string\" ? { query: args } : args,\n ),\n describe: (args) => __call(\"fabric.$describe\", args),\n call: (args) => __call(\"fabric.$call\", args),\n progress: (args) => __call(\"fabric.$progress\", args),\n models: () => __call(\"fabric.$models\", {}),\n};\n// tools is discovery + generic calls only. The proxy keeps the seven discovery\n// methods and turns a core-tool name (read/bash/edit/...) into an actionable\n// error pointing at pi.<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 (__piToolNames.indexOf(name) >= 0) {\n return () => {\n throw new Error(\n \"tools.\" + name + \" is not available on the discovery API. tools is discovery + generic calls only (providers/catalog/list/search/describe/call/models). For the Pi core tool, call pi.\" + name + \"(args), e.g. pi.\" + name + \"({ ... }).\"\n );\n };\n }\n return target[property];\n },\n set() { return true; },\n deleteProperty() { return true; },\n});\nconst __piStringFields = { bash: \"command\", read: \"path\", ls: \"path\", grep: \"pattern\", find: \"pattern\" };\n// Per-tool key aliases. The runtime normalizes them to the canonical form\n// before the host validates args; unit-converting aliases are handled separately\n// in __normalizePiArgs. This lets a model that writes { query, regex, ... }\n// or { file } instead of { pattern } / { path } still succeeds on the first\n// call. Keep these in sync with the PiToolsApi overloads in guest-types.ts so\n// the type-checker accepts the same spellings it coercion-handles at runtime.\nconst __piArgAliases = {\n bash: {\n cmd: \"command\", shell: \"command\", cmdline: \"command\", script: \"command\",\n commandLine: \"command\",\n 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 max: \"limit\", ctx: \"context\",\n },\n read: {\n file: \"path\", absolutePath: \"path\", file_path: \"path\", filePath: \"path\",\n filepath: \"path\", pathname: \"path\", target_file: \"path\", targetFile: \"path\",\n absolute_path: \"path\", fileAbsolutePath: \"path\",\n max: \"limit\", start: \"offset\",\n },\n ls: {\n dir: \"path\", file: \"path\", folder: \"path\", absolutePath: \"path\",\n file_path: \"path\", filePath: \"path\", filepath: \"path\", pathname: \"path\",\n target_file: \"path\", targetFile: \"path\", absolute_path: \"path\",\n fileAbsolutePath: \"path\", directory: \"path\", directoryPath: \"path\",\n max: \"limit\",\n },\n edit: {\n file: \"path\", absolutePath: \"path\", file_path: \"path\", filePath: \"path\",\n filepath: \"path\", pathname: \"path\", target_file: \"path\", targetFile: \"path\",\n absolute_path: \"path\", fileAbsolutePath: \"path\",\n old: \"oldText\", old_string: \"oldText\", oldString: \"oldText\",\n old_str: \"oldText\", oldStr: \"oldText\", from: \"oldText\",\n old_value: \"oldText\", old_text: \"oldText\", oldContent: \"oldText\",\n old_content: \"oldText\",\n new: \"newText\", replacement: \"newText\", new_string: \"newText\",\n newString: \"newText\", new_str: \"newText\", newStr: \"newText\",\n to: \"newText\", new_value: \"newText\", new_text: \"newText\",\n newContent: \"newText\", new_content: \"newText\",\n },\n write: {\n file: \"path\", absolutePath: \"path\", file_path: \"path\", filePath: \"path\",\n filepath: \"path\", pathname: \"path\", target_file: \"path\", targetFile: \"path\",\n absolute_path: \"path\", fileAbsolutePath: \"path\",\n contents: \"content\", body: \"content\", text: \"content\", data: \"content\",\n fileContent: \"content\",\n },\n};\n// Multi-arg positional order, used only when a call passes >= 2 args and the\n// (primary, options) merge in __positionalToArgs does not apply. One-field\n// tools (read/bash/ls) stay absent: their two-arg form is a bare string plus\n// an options object, repaired by the merge instead of a wrong-arity (2554)\n// type error; only a non-object second arg still fails 2554.\nconst __piPositionalFields = {\n grep: [\"pattern\", \"path\", \"limit\"],\n find: [\"pattern\", \"path\", \"limit\"],\n write: [\"path\", \"content\"],\n edit: [\"path\", \"oldText\", \"newText\"],\n};\n// Models often pass numbers as strings (\"20\"); coerce the known numeric\n// option fields so the host schema sees a number. Non-numeric strings pass\n// through untouched and fail host validation exactly as before. Kept in sync\n// with the numeric optionals in the PiToolsApi overloads in guest-types.ts.\nconst __piNumericFields = {\n read: [\"offset\", \"limit\"],\n grep: [\"limit\", \"context\"],\n find: [\"limit\"],\n ls: [\"limit\"],\n bash: [\"timeout\"],\n};\nconst __piOptionalFields = {\n read: [\"offset\", \"limit\"],\n grep: [\"path\", \"glob\", \"ignoreCase\", \"literal\", \"context\", \"limit\"],\n find: [\"path\", \"limit\"],\n ls: [\"path\", \"limit\"],\n bash: [\"timeout\"],\n};\n// (primary, options) two-arg merge for the string-primary tools:\n// pi.read(\"index.ts\", { limit: 120 }) becomes { path: \"index.ts\", limit: 120 }.\n// A plain-object second arg is never a valid positional value for these tools\n// (grep/find take (pattern, path, limit) strings/numbers), so merging is\n// unambiguous; the positional string wins the primary field on conflict. The\n// merged object flows through the same alias, unit, and numeric normalization\n// in __normalizePiArgs as any other options object.\nconst __positionalToArgs = (name, rest) => {\n const first = rest[0];\n const second = rest[1];\n const primaryField = __piStringFields[name];\n if (\n rest.length === 2 &&\n typeof first === \"string\" &&\n primaryField !== undefined &&\n second !== null && typeof second === \"object\" && !Array.isArray(second)\n ) {\n const merged = Object.assign({}, second);\n merged[primaryField] = first;\n return merged;\n }\n const order = __piPositionalFields[name];\n if (!order) return rest.length > 0 ? first : {};\n const out = {};\n for (let i = 0; i < rest.length && i < order.length; i++) {\n const v = rest[i];\n if (v !== undefined) out[order[i]] = v;\n }\n return out;\n};\nconst __normalizePiArgs = (name, args) => {\n const field = __piStringFields[name];\n if (typeof args === \"string\" && field) return { [field]: args };\n if (args === null || typeof args !== \"object\" || Array.isArray(args)) return args;\n const aliases = __piArgAliases[name];\n let out = args;\n if (name === \"bash\" && \"timeoutMs\" in out) {\n out = Object.assign({}, args);\n if (!(\"timeout\" in out)) {\n const timeoutMs = out.timeoutMs;\n if (timeoutMs !== null && timeoutMs !== undefined) {\n out.timeout = Number.isFinite(Number(timeoutMs)) ? Number(timeoutMs) / 1000 : timeoutMs;\n }\n }\n delete out.timeoutMs;\n }\n // settle is a guest-only directive (settles nonzero exits instead of\n // rejecting); strip it so it never reaches the host/bash schema.\n if (name === \"bash\" && \"settle\" in out) {\n if (out === args) out = Object.assign({}, args);\n delete out.settle;\n }\n if (aliases) {\n for (const alias in aliases) {\n const canonical = aliases[alias];\n if (alias in out) {\n if (out === args) out = Object.assign({}, args);\n if (!(canonical in out)) out[canonical] = out[alias];\n delete out[alias];\n }\n }\n }\n const numerics = __piNumericFields[name];\n if (numerics) {\n for (const key of numerics) {\n const value = out[key];\n if (typeof value === \"string\" && value.trim() !== \"\" && Number.isFinite(Number(value))) {\n if (out === args) out = Object.assign({}, args);\n out[key] = Number(value);\n }\n }\n }\n const optionalFields = __piOptionalFields[name];\n if (optionalFields) {\n for (const key of optionalFields) {\n if (out[key] !== null && out[key] !== undefined) continue;\n if (!(key in out)) continue;\n if (out === args) out = Object.assign({}, args);\n delete out[key];\n }\n }\n if (name === \"edit\" && Array.isArray(out.edits)) {\n let changed = false;\n const editAliases = __piArgAliases.edit;\n const edits = out.edits.map((entry) => {\n if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) return entry;\n let edit = entry;\n for (const alias in editAliases) {\n const canonical = editAliases[alias];\n if (canonical !== \"oldText\" && canonical !== \"newText\") continue;\n if (!(alias in edit)) continue;\n if (edit === entry) edit = Object.assign({}, entry);\n if (!(canonical in edit)) edit[canonical] = edit[alias];\n delete edit[alias];\n changed = true;\n }\n return edit;\n });\n if (changed) {\n if (out === args) out = Object.assign({}, args);\n out.edits = edits;\n }\n }\n if (name === \"edit\" && !Array.isArray(out.edits) && (\"oldText\" in out || \"newText\" in out)) {\n if (out === args) out = Object.assign({}, args);\n const edit = {};\n if (\"oldText\" in out) edit.oldText = out.oldText;\n if (\"newText\" in out) edit.newText = out.newText;\n out.edits = [edit];\n delete out.oldText;\n delete out.newText;\n }\n return out;\n};\n// bash/edit/write resolve envelope objects { ok, output, details }, and the\n// type-checker deliberately suppresses property-miss (2339) diagnostics, so\n// result.trim() on an envelope typechecks and then dies with QuickJS's terse\n// \"not a function\" \u2014 an error models cannot localize (observed: misdirected\n// debugging spirals probing unrelated globals). Guard envelopes with a proxy\n// that throws an actionable TypeError for string-method access and iteration,\n// naming the tool and the .output fix. Ordinary reads (ok/output/details/\n// exitCode/error), destructuring, 'in' checks, and JSON marshaling pass through.\nconst __piEnvelopeTools = { bash: true, edit: true, write: true };\nconst __piEnvelopeStringTraps = new Set([\n \"anchor\", \"at\", \"big\", \"blink\", \"bold\", \"charAt\", \"charCodeAt\", \"codePointAt\",\n \"concat\", \"endsWith\", \"fixed\", \"fontcolor\", \"fontsize\", \"includes\", \"indexOf\",\n \"italics\", \"lastIndexOf\", \"length\", \"link\", \"localeCompare\", \"match\", \"matchAll\",\n \"normalize\", \"padEnd\", \"padStart\", \"repeat\", \"replace\", \"replaceAll\", \"search\",\n \"slice\", \"small\", \"split\", \"startsWith\", \"strike\", \"sub\", \"substr\", \"substring\",\n \"sup\", \"toLocaleLowerCase\", \"toLocaleUpperCase\", \"toLowerCase\", \"toUpperCase\",\n \"trim\", \"trimEnd\", \"trimStart\",\n]);\nconst __piEnvelopeGuard = (name, value) => {\n if (value === null || typeof value !== \"object\" || typeof value.ok !== \"boolean\") return value;\n return new Proxy(value, {\n get(target, property, receiver) {\n if (property === Symbol.iterator || property === Symbol.asyncIterator) {\n throw new TypeError(\n \"pi.\" + name + \"(...) resolves an envelope { ok, output, details }, which is not iterable. \" +\n \"Iterate the text instead: (await pi.\" + name + \"(...)).output.split('\\\\\\\\n')\"\n );\n }\n if (typeof property === \"string\" && __piEnvelopeStringTraps.has(property)) {\n throw new TypeError(\n \"pi.\" + name + \"(...) resolves an envelope { ok, output, details }, not a string, so .\" + property +\n \" is unavailable on it. Read the text first: const out = (await pi.\" + name + \"(...)).output; then out.\" + property +\n \"(...). bash rejects on a nonzero exit \u2014 pass settle: true to receive an ok:false envelope instead.\"\n );\n }\n return Reflect.get(target, property, receiver);\n },\n });\n};\n// The pi proxy accepts: a bare string (primary field), an options object, a\n// (primary, options) two-arg merge for the string-primary tools, or a\n// positional spread mapped by __piPositionalFields. 0/1 args preserve the\n// legacy (args = {}) default so existing programs are unchanged.\nglobalThis.pi = new Proxy({}, {\n get(_target, property) {\n if (property === \"then\") return undefined;\n const name = String(property);\n return (...rest) => {\n let args;\n if (rest.length <= 1) {\n const first = rest.length === 1 ? rest[0] : undefined;\n args = first === undefined ? {} : first;\n } else {\n args = __positionalToArgs(name, rest);\n }\n // bash rejects on an ordinary nonzero exit; settle:true returns\n // {ok:false, exitCode, ...} instead (opt-in). Other failures still reject.\n const settle = name === \"bash\" &&\n typeof args === \"object\" && args !== null && args.settle === true;\n const call = __call(\"pi.\" + name, __normalizePiArgs(name, args));\n const promise = settle ? call.catch((error) => {\n // node-process bridge errors originate in a different VM realm.\n const message = typeof error?.message === \"string\" ? error.message : String(error);\n const exit = error?.__fabricBashExit;\n if (!exit || !Number.isSafeInteger(exit.exitCode) || exit.exitCode <= 0 ||\n typeof exit.output !== \"string\") throw error;\n return {\n ok: false,\n output: exit.output,\n details: null,\n exitCode: exit.exitCode,\n error: message,\n };\n }) : call;\n return __piEnvelopeTools[name] === true\n ? promise.then((value) => __piEnvelopeGuard(name, value))\n : promise;\n };\n },\n});\nconst __piStrings = (typeof globalThis[\"\u03C0\"] === \"object\" && globalThis[\"\u03C0\"] !== null) ? globalThis[\"\u03C0\"] : {};\nglobalThis[\"\u03C0\"] = new Proxy(__piStrings, {\n get(target, property) {\n if (typeof property === \"symbol\") return undefined;\n const name = String(property);\n if (name === \"then\" || name === \"toJSON\" || name === \"constructor\") return undefined;\n if (Object.prototype.hasOwnProperty.call(target, name)) return target[name];\n if (__piToolNames.indexOf(name) >= 0) {\n throw new Error(\n \"\u03C0.\" + name + \" is the strings accessor, not a tool. For the Pi core tool, call pi.\" + name + \"(args).\"\n );\n }\n const provided = Object.keys(target);\n throw new Error(\n \"\u03C0.\" + name + \" is not defined. \u03C0 only exposes keys from the fabric_exec strings parameter\" +\n (provided.length ? \" (provided: \" + provided.join(\", \") + \")\" : \" (none provided)\") +\n \". Pass strings: { \" + name + \": '...' } to use \u03C0.\" + name + \".\" +\n \" For large or quote-heavy content, keep it in top-level strings and reference \u03C0.\" + name + \" instead of escaping it inside code.\"\n );\n },\n ownKeys(target) { return Reflect.ownKeys(target); },\n getOwnPropertyDescriptor(target, prop) { return Reflect.getOwnPropertyDescriptor(target, prop); },\n has(target, prop) { return Object.prototype.hasOwnProperty.call(target, prop); }\n});\n// Stable providers share a lazy dispatch proxy; the guest declarations keep\n// their known actions typed while the registry remains the runtime authority.\n// extensions' per-tool surface is additionally rendered from the captured\n// catalog by guestTypeDeclarations (runtime/dynamic-guest-types.ts).\nconst __providerProxy = (provider) => new Proxy({}, {\n get(_target, property) {\n if (property === \"then\" || typeof property === \"symbol\") return undefined;\n return (args = {}) => __call(provider + \".\" + String(property), args);\n },\n});\nglobalThis.extensions = __providerProxy(\"extensions\");\nglobalThis.memory = __providerProxy(\"memory\");\nglobalThis.state = __providerProxy(\"state\");\nglobalThis.schema = __providerProxy(\"schema\");\nglobalThis.components = __providerProxy(\"components\");\nglobalThis.compact = __providerProxy(\"compact\");\nconst __createActor = async (args = {}) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n throw new TypeError(\"agents.create expects an options object\");\n }\n const request = { ...args };\n const validWhile = request.validWhile;\n if (validWhile !== undefined) {\n if (typeof validWhile !== \"function\") {\n throw new TypeError(\"agents.create validWhile must be a pure predicate function\");\n }\n const source = Function.prototype.toString.call(validWhile);\n if (source.trimStart().startsWith(\"async\")) {\n throw new TypeError(\"agents.create validWhile must be synchronous\");\n }\n request.validWhile = { version: 1, source };\n }\n return __call(\"agents.create\", request);\n};\nconst __handoff = async (args = {}) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) {\n throw new TypeError(\"agents.handoff expects an options object\");\n }\n const request = { ...args };\n const when = request.when;\n delete request.when;\n if (when !== undefined) {\n if (typeof when !== \"function\") {\n throw new TypeError(\"agents.handoff when must be a pure predicate function\");\n }\n const decision = when(__handoffFacts());\n if (decision && typeof decision.then === \"function\") {\n throw new TypeError(\"agents.handoff when must return a boolean synchronously\");\n }\n if (decision !== true) {\n throw new Error(\"agents.handoff predicate returned false; no agent was started\");\n }\n }\n return __call(\"agents.handoff\", request);\n};\nglobalThis.agents = Object.freeze({\n run: (args) => __call(\"agents.run\", args),\n handoff: __handoff,\n spawn: (args) => __call(\"agents.spawn\", args),\n wait: (args) => __call(\"agents.wait\", args),\n status: (args) => __call(\"agents.status\", args),\n list: (args = {}) => __call(\"agents.list\", args),\n members: (args = {}) => __call(\"agents.members\", args),\n self: () => __call(\"agents.self\", {}),\n main: () => __call(\"agents.main\", {}),\n peers: () => __call(\"agents.peers\", {}),\n subscribe: (args) => __call(\"agents.subscribe\", args),\n subscriptions: (args = {}) => __call(\"agents.subscriptions\", args),\n unsubscribe: (args) => __call(\"agents.unsubscribe\", args),\n models: (args = {}) => __call(\"agents.models\", args),\n stop: (args) => __call(\"agents.stop\", args),\n cleanup: (args) => __call(\"agents.cleanup\", args),\n create: __createActor,\n ask: (args) => __call(\"agents.ask\", args),\n tell: (args) => __call(\"agents.tell\", args),\n steer: (args) => __call(\"agents.steer\", args),\n followUp: (args) => __call(\"agents.followUp\", args),\n setSteeringMode: (args) => __call(\"agents.setSteeringMode\", args),\n setFollowUpMode: (args) => __call(\"agents.setFollowUpMode\", args),\n actorStatus: (args) => __call(\"agents.actorStatus\", args),\n setModel: (args) => __call(\"agents.setModel\", args),\n switchModel: (args) => __call(\"agents.switchModel\", args),\n setThinking: (args) => __call(\"agents.setThinking\", args),\n setEvents: (args) => __call(\"agents.setEvents\", args),\n setInstructions: (args) => __call(\"agents.setInstructions\", args),\n actors: () => __call(\"agents.actors\", {}),\n messages: (args) => __call(\"agents.messages\", args),\n remove: (args) => __call(\"agents.remove\", args),\n log: (args) => __call(\"agents.log\", args),\n});\nglobalThis.mesh = Object.freeze({\n self: () => __call(\"mesh.self\", {}),\n publish: (args) => __call(\"mesh.publish\", args),\n read: (args = {}) => __call(\"mesh.read\", args),\n members: (args = {}) => __call(\"mesh.members\", args),\n get: (args) => __call(\"mesh.get\", args),\n list: (args = {}) => __call(\"mesh.list\", args),\n put: (args) => __call(\"mesh.put\", args),\n delete: (args) => __call(\"mesh.delete\", args),\n});\n// The mcp proxy itself stays schema-less \u2014 the registry validates args at\n// dispatch \u2014 but guestTypeDeclarations renders per-server argument types from\n// the live descriptor cache (runtime/dynamic-guest-types.ts), so known tools\n// fail type-check on argument-shape mistakes before this proxy ever runs.\nglobalThis.mcp = new Proxy({}, {\n get(_target, server) {\n if (server === \"then\") return undefined;\n if (server === \"servers\") return () => __call(\"mcp.$servers\", {});\n if (server === \"reload\") return () => __call(\"mcp.$reload\", {});\n if (server === \"register\") return (args) => __call(\"mcp.$register\", args);\n if (server === \"call\") return (args) => __call(\"mcp.$call\", args);\n return new Proxy({}, {\n get(_serverTarget, tool) {\n if (tool === \"then\") return undefined;\n return (args = {}) => __call(\"mcp.\" + String(server) + \".\" + String(tool), args);\n },\n });\n },\n});\nlet __workflowSpentTokens = 0;\nconst __workflowBudgetTotal = Number.isFinite(globalThis.__fabricTokenBudget)\n ? Math.max(0, globalThis.__fabricTokenBudget)\n : Number.POSITIVE_INFINITY;\nconst __recordAgentUsage = (result) => {\n const usage = result && result.usage;\n if (usage) __workflowSpentTokens += Number(usage.input || 0) + Number(usage.output || 0);\n return result;\n};\nconst __workflowAgent = async (prompt, options = {}) => {\n if (__workflowSpentTokens >= __workflowBudgetTotal) {\n throw new Error(\"Fabric workflow token budget exhausted\");\n }\n const { label, ...agentOptions } = options;\n const workerName = String(label || agentOptions.name || \"Fabric workflow agent\");\n const result = __recordAgentUsage(await agents.run({\n ...agentOptions,\n ...(label && !agentOptions.name ? { name: label } : {}),\n task: prompt,\n }));\n if (!result || result.status !== \"completed\") {\n const reason = result && result.error ? result.error : \"agent did not complete\";\n throw new Error(workerName + \" failed: \" + reason);\n }\n return result.value !== undefined ? result.value : result.text;\n};\n// Budget-aware agents.run used by council.run and rlm.query so their usage is\n// counted in budget.spent() and the tokenBudget guard can preempt them, just\n// like workflow.agent(). Without this, councils bypass the budget entirely.\nconst __budgetedRun = async (args) => {\n if (__workflowSpentTokens >= __workflowBudgetTotal) {\n throw new Error(\"Fabric workflow token budget exhausted\");\n }\n return __recordAgentUsage(await agents.run(args));\n};\nlet __nextWorkflowSpanId = 0;\nconst __workflowSpanMetadata = (kind, items, options, stageCount) => {\n const itemCount = Array.isArray(items) ? items.length : undefined;\n let concurrency;\n if (kind === \"parallel\" && itemCount !== undefined) {\n if (itemCount === 0) concurrency = 0;\n else {\n const concurrencyOpt = typeof options === \"number\" ? { concurrency: options } : options ?? {};\n const requested = Number(concurrencyOpt.concurrency ?? itemCount);\n if (Number.isFinite(requested) && requested >= 1) {\n concurrency = Math.max(1, Math.min(itemCount, Math.floor(requested)));\n }\n }\n }\n return {\n kind,\n ...(itemCount !== undefined ? { itemCount } : {}),\n ...(stageCount !== undefined ? { stageCount } : {}),\n ...(concurrency !== undefined ? { concurrency } : {}),\n };\n};\nconst __withWorkflowSpan = async (metadata, body) => {\n const id = \"span-\" + __nextWorkflowSpanId++;\n await __call(\"fabric.$spanStart\", { id, ...metadata });\n try {\n const value = await body();\n await __call(\"fabric.$spanEnd\", { id, outcome: \"succeeded\" });\n return value;\n } catch (error) {\n try { await __call(\"fabric.$spanEnd\", { id, outcome: \"failed\" }); } catch { /* preserve the workflow error */ }\n throw error;\n }\n};\nconst __runParallel = async (thunks, options) => {\n if (!Array.isArray(thunks) || thunks.some((thunk) => typeof thunk !== \"function\")) {\n throw new TypeError(\"workflow.parallel expects an array of functions or (items, mapper)\");\n }\n if (thunks.length === 0) return [];\n const concurrencyOpt = typeof options === \"number\" ? { concurrency: options } : options ?? {};\n const requestedConcurrency = Number(concurrencyOpt.concurrency ?? thunks.length);\n if (!Number.isFinite(requestedConcurrency) || requestedConcurrency < 1) {\n throw new RangeError(\"workflow.parallel concurrency must be a positive finite number\");\n }\n const concurrency = Math.max(1, Math.min(thunks.length || 1, Math.floor(requestedConcurrency)));\n const results = new Array(thunks.length);\n let cursor = 0;\n await Promise.all(Array.from({ length: concurrency }, async () => {\n while (cursor < thunks.length) {\n const index = cursor++;\n results[index] = await thunks[index]();\n }\n }));\n return results;\n};\nconst __workflowParallel = async (items, arg2, arg3) => {\n const options = typeof arg2 === \"function\" ? arg3 : arg2;\n return __withWorkflowSpan(\n __workflowSpanMetadata(\"parallel\", items, options),\n async () => {\n if (typeof arg2 === \"function\") {\n if (!Array.isArray(items)) throw new TypeError(\"workflow.parallel expects an array as the first argument\");\n return __runParallel(items.map((item, index) => () => arg2(item, index)), arg3);\n }\n return __runParallel(items, arg2);\n },\n );\n};\nconst __workflowPipeline = async (items, ...stages) =>\n __withWorkflowSpan(\n __workflowSpanMetadata(\"pipeline\", items, undefined, stages.length),\n async () => {\n if (!Array.isArray(items) || stages.some((stage) => typeof stage !== \"function\")) {\n throw new TypeError(\"workflow.pipeline expects an array followed by stage functions\");\n }\n return __workflowParallel(items.map((original, index) => async () => {\n let value = original;\n for (const stage of stages) value = await stage(value, original, index);\n return value;\n }));\n },\n );\nglobalThis.workflow = Object.freeze({\n agent: __workflowAgent,\n parallel: __workflowParallel,\n pipeline: __workflowPipeline,\n configure: (args) => __call(\"fabric.$configure\", args),\n phase: (nameOrInput, options = {}) => {\n const input =\n nameOrInput && typeof nameOrInput === \"object\" && !Array.isArray(nameOrInput)\n ? { ...nameOrInput }\n : { ...options, name: nameOrInput };\n return __call(\"fabric.$phase\", input);\n },\n item: (args) => __call(\"fabric.$item\", args),\n event: (args) => __call(\"fabric.$event\", args),\n log: (...values) => print(...values),\n budget: Object.freeze({\n total: __workflowBudgetTotal,\n spent: () => __workflowSpentTokens,\n remaining: () => Math.max(0, __workflowBudgetTotal - __workflowSpentTokens),\n }),\n});\nglobalThis.agent = __workflowAgent;\nglobalThis.parallel = __workflowParallel;\nglobalThis.pipeline = __workflowPipeline;\nglobalThis.phase = workflow.phase;\nglobalThis.log = workflow.log;\nglobalThis.budget = workflow.budget;\nglobalThis.rlm = Object.freeze({\n query: (args) => {\n if (args && args.runner && args.runner !== \"pi\") {\n throw new Error(\"rlm.query requires the Pi runner because recursive Fabric is unavailable in Claude Code\");\n }\n return __budgetedRun({ ...args, runner: \"pi\", recursive: true });\n },\n});\nglobalThis.council = Object.freeze({\n async run(args) {\n const { task, roles, synthesize = true, ...agentOptions } = args;\n const results = await Promise.all(roles.map((role) => __budgetedRun({\n ...agentOptions,\n name: role,\n task: \"Act as the \" + role + \" council member. Independently analyze this task:\\\\n\\\\n\" + task,\n })));\n if (!synthesize) return results;\n return __budgetedRun({\n ...agentOptions,\n name: \"council-synthesizer\",\n task: \"Synthesize the council's independent reports into one decision. Preserve disagreements and cite which role raised each concern.\\\\n\\\\nTask:\\\\n\" + task + \"\\\\n\\\\nReports:\\\\n\" + JSON.stringify(results),\n });\n },\n});\nglobalThis.console = Object.freeze({ log: print, info: print, warn: print, error: print });\nconst __timerCallbacks = new Map();\nlet __nextTimerId = 1;\nglobalThis.setTimeout = (callback, ms = 0) => {\n const id = __nextTimerId++;\n __timerCallbacks.set(id, { callback, interval: false });\n __call(\"fabric.$timer\", { ms }).then(() => {\n const entry = __timerCallbacks.get(id);\n if (!entry) return;\n __timerCallbacks.delete(id);\n try { entry.callback(); } catch { /* swallow timer callback errors */ }\n });\n return id;\n};\nglobalThis.setInterval = (callback, ms = 0) => {\n const id = __nextTimerId++;\n __timerCallbacks.set(id, { callback, interval: true });\n const schedule = () => {\n __call(\"fabric.$timer\", { ms }).then(() => {\n const entry = __timerCallbacks.get(id);\n if (!entry) return;\n try { entry.callback(); } catch { /* swallow timer callback errors */ }\n if (__timerCallbacks.has(id)) schedule();\n });\n };\n schedule();\n return id;\n};\nglobalThis.clearTimeout = (id) => { __timerCallbacks.delete(id); };\nglobalThis.clearInterval = (id) => { __timerCallbacks.delete(id); };\n})();\n`;\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 = missingStringsKeys(code, options.strings);\n if (missingKeys.length > 0) {\n const provided = Object.keys(options.strings ?? {});\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error:\n \"Pre-execution check: \" + missingKeys.map((key) => \"\u03C0.\" + key).join(\", \")\n + (missingKeys.length === 1 ? \" is referenced in code but its key is missing from the strings parameter\"\n : \" are referenced in code but their keys are missing from the strings parameter\")\n + (provided.length ? \" (provided: \" + provided.join(\", \") + \")\" : \" (none provided)\")\n + \". Add strings: { \" + missingKeys.join(\": '...', \") + \": '...' } to the fabric_exec arguments, then reference the value as \u03C0.<key>.\"\n + \" For large or quote-heavy content, keep it in top-level strings and reference \u03C0.<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 === \"pi.bash\" ? piBashExitMetadata(error) : 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(\"[Pi Fabric log output truncated]\");\n logsTruncated = true;\n return;\n }\n logs.push(line);\n logChars += line.length;\n });\n context.setProp(context.global, \"print\", printFunction);\n printFunction.dispose();\n\n const strings = jsonHandle(context, jsonObject, jsonParse, options.strings ?? {});\n context.setProp(context.global, \"\u03C0\", strings);\n strings.dispose();\n const tokenBudget = context.newNumber(options.tokenBudget ?? Number.POSITIVE_INFINITY);\n context.setProp(context.global, \"__fabricTokenBudget\", tokenBudget);\n tokenBudget.dispose();\n\n const setupResult = context.evalCode(GUEST_SETUP, \"pi-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([__piFabricMain(), globalThis.__fabricExecutionGate])`;\n const evaluation = context.evalCode(wrappedCode, \"pi-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// pi-fabric-guest.js (wrapper header plus TypeScript printer layout), not the\n// author's program. These helpers decode the transpile source map and rewrite\n// error text so stack positions point back at the user-submitted code.\n\ninterface GuestSourcePosition {\n line: number;\n column: number;\n}\n\nexport interface GuestStackMap {\n lookup(line: number, column: number): GuestSourcePosition | undefined;\n}\n\ninterface GuestSourceMapJson {\n mappings?: unknown;\n}\n\ninterface MappingSegment {\n generatedColumn: number;\n sourceLine: number;\n sourceColumn: number;\n}\n\nconst BASE64_VALUES = (() => {\n const alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n const table = new Map<string, number>();\n for (let index = 0; index < alphabet.length; index += 1) {\n table.set(alphabet[index] as string, index);\n }\n return table;\n})();\n\nconst decodeVlqSegment = (segment: string): number[] => {\n const values: number[] = [];\n let index = 0;\n while (index < segment.length) {\n let value = 0;\n let shift = 0;\n let continuation = true;\n while (continuation) {\n const digit = BASE64_VALUES.get(segment[index] as string);\n if (digit === undefined) return values;\n index += 1;\n continuation = (digit & 32) !== 0;\n value += (digit & 31) * 2 ** shift;\n shift += 5;\n }\n values.push((value & 1) === 1 ? -(value >> 1) : value >> 1);\n }\n return values;\n};\n\nconst decodeMappings = (mappings: string): MappingSegment[][] => {\n const lines: MappingSegment[][] = [];\n let sourceLine = 0;\n let sourceColumn = 0;\n for (const line of mappings.split(\";\")) {\n const segments: MappingSegment[] = [];\n let generatedColumn = 0;\n for (const rawSegment of line.split(\",\")) {\n if (!rawSegment) continue;\n const values = decodeVlqSegment(rawSegment);\n // values[1] is the source index delta; single-source guest maps never\n // need it, so only generated column and source position accumulate.\n if (values.length < 4) continue;\n generatedColumn += values[0] as number;\n sourceLine += values[2] as number;\n sourceColumn += values[3] as number;\n segments.push({ generatedColumn, sourceLine, sourceColumn });\n }\n lines.push(segments);\n }\n return lines;\n};\n\nexport const createGuestStackMap = (\n sourceMapText: string | undefined,\n): GuestStackMap | undefined => {\n if (!sourceMapText) return undefined;\n let mappings: string;\n try {\n const parsed = JSON.parse(sourceMapText) as GuestSourceMapJson;\n if (typeof parsed.mappings !== \"string\") return undefined;\n mappings = parsed.mappings;\n } catch {\n return undefined;\n }\n // Validating the envelope above is cheap; decoding the VLQ mappings defers\n // to the first error lookup so clean executions pay almost nothing for\n // diagnostics they never render.\n let decoded: MappingSegment[][] | undefined;\n return {\n lookup(line, column) {\n decoded ??= decodeMappings(mappings);\n const segments = decoded[line - 1];\n if (!segments) return undefined;\n const target = column - 1;\n let best: MappingSegment | undefined;\n for (const segment of segments) {\n if (segment.generatedColumn > target) break;\n best = segment;\n }\n // Columns before the first segment point at line indentation; anchor\n // them to the first statement segment rather than leaving the frame\n // in emitted-file coordinates.\n best ??= segments[0];\n if (!best) return undefined;\n // The wrapper header occupies source line 1, so the zero-based source\n // line already equals the author's one-based program line.\n return { line: best.sourceLine, column: best.sourceColumn + 1 };\n },\n };\n};\n\nconst GUEST_FRAME_PATTERN = /pi-fabric-guest\\.js:(\\d+):(\\d+)/g;\n\nexport const remapGuestErrorText = (\n text: string,\n stackMap: GuestStackMap | undefined,\n guestLineCount?: number,\n): string => {\n if (!stackMap || !text.includes(\"pi-fabric-guest.js:\")) return text;\n return text.replace(GUEST_FRAME_PATTERN, (match, lineText, columnText) => {\n const line = Number(lineText);\n const mapped = stackMap.lookup(line, Number(columnText));\n if (mapped) return `guest code:${mapped.line}:${mapped.column}`;\n // Both runtimes append their driver call after the emitted bundle, so\n // frames beyond it can only be harness machinery, never user statements.\n if (guestLineCount !== undefined && line > guestLineCount) return \"fabric driver\";\n return match;\n });\n};\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;AAAA,OAAO,wBAAwB;AAC/B,SAAS,uCAAuC;;;ACuBhD,IAAM,iBAAiB,MAAM;AAC3B,QAAM,WAAW;AACjB,QAAM,QAAQ,oBAAI,IAAoB;AACtC,WAAS,QAAQ,GAAG,QAAQ,SAAS,QAAQ,SAAS,GAAG;AACvD,UAAM,IAAI,SAAS,KAAK,GAAa,KAAK;AAAA,EAC5C;AACA,SAAO;AACT,GAAG;AAEH,IAAM,mBAAmB,CAAC,YAA8B;AACtD,QAAM,SAAmB,CAAC;AAC1B,MAAI,QAAQ;AACZ,SAAO,QAAQ,QAAQ,QAAQ;AAC7B,QAAI,QAAQ;AACZ,QAAI,QAAQ;AACZ,QAAI,eAAe;AACnB,WAAO,cAAc;AACnB,YAAM,QAAQ,cAAc,IAAI,QAAQ,KAAK,CAAW;AACxD,UAAI,UAAU,OAAW,QAAO;AAChC,eAAS;AACT,sBAAgB,QAAQ,QAAQ;AAChC,gBAAU,QAAQ,MAAM,KAAK;AAC7B,eAAS;AAAA,IACX;AACA,WAAO,MAAM,QAAQ,OAAO,IAAI,EAAE,SAAS,KAAK,SAAS,CAAC;AAAA,EAC5D;AACA,SAAO;AACT;AAEA,IAAM,iBAAiB,CAAC,aAAyC;AAC/D,QAAM,QAA4B,CAAC;AACnC,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,aAAW,QAAQ,SAAS,MAAM,GAAG,GAAG;AACtC,UAAM,WAA6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AA,UACtC,oBAAoB,kBAAkB,MAAM,MAAM,MAAS,IAAI,QAAQ,QAAQ,MAAS;AAAA,UACxF,IAAI,QAAmB,CAAC,YAAY;AAClC,kBAAM,QAAQ,WAAW,MAAM,QAAQ,MAAS,GAAG,GAAK;AACxD,kBAAM,QAAQ;AAAA,UAChB,CAAC;AAAA,QACH,CAAC;AACD,YAAI,SAAS,MAAO,SAAQ,MAAM,QAAQ;AAC1C,YAAI,SAAS,MAAO,SAAQ,MAAM,QAAQ;AAC1C,mBAAW,WAAW,qBAAqB;AACzC,cAAI,QAAQ,UAAU,MAAO,SAAQ,QAAQ;AAAA,QAC/C;AAAA,MACF;AACA,UAAI,qBAAqB,UAAU,MAAO,sBAAqB,QAAQ;AACvE,UAAI,eAAe,UAAU,MAAO,gBAAe,QAAQ;AAC3D,cAAQ,mBAAmB;AAC3B,gBAAU,QAAQ;AAClB,iBAAW,QAAQ;AACnB,4BAAsB,OAAO;AAAA,IAC/B;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["value"]
|
|
7
|
+
}
|
|
@@ -360,6 +360,7 @@ var clampCompactionRatioThreshold = (value) => Math.min(
|
|
|
360
360
|
MAX_COMPACTION_RATIO_THRESHOLD,
|
|
361
361
|
Math.max(MIN_COMPACTION_RATIO_THRESHOLD, value)
|
|
362
362
|
);
|
|
363
|
+
var MAX_EXECUTOR_TIMEOUT_MS = 24 * 36e5;
|
|
363
364
|
var MIN_AGENT_TIMEOUT_MS = 1e3;
|
|
364
365
|
var DEFAULT_AGENT_TIMEOUT_MS = 36e5;
|
|
365
366
|
var MAX_AGENT_TIMEOUT_MS = 24 * 36e5;
|
|
@@ -374,6 +375,8 @@ var DEFAULT_FABRIC_CONFIG = {
|
|
|
374
375
|
executor: {
|
|
375
376
|
runtime: "quickjs",
|
|
376
377
|
timeoutMs: 12e4,
|
|
378
|
+
maxTimeoutMs: 9e5,
|
|
379
|
+
hostCallTimeouts: {},
|
|
377
380
|
memoryLimitBytes: 64 * 1024 * 1024,
|
|
378
381
|
maxOutputChars: 5e4,
|
|
379
382
|
maxNestedResultChars: 2e6,
|
|
@@ -395,8 +398,7 @@ var DEFAULT_FABRIC_CONFIG = {
|
|
|
395
398
|
enabled: true,
|
|
396
399
|
revalidate: "changed",
|
|
397
400
|
revalidateBudgetMs: 6e4
|
|
398
|
-
}
|
|
399
|
-
advisory: true
|
|
401
|
+
}
|
|
400
402
|
},
|
|
401
403
|
prewalk: {
|
|
402
404
|
mode: "in-place",
|
|
@@ -442,13 +444,6 @@ var DEFAULT_FABRIC_CONFIG = {
|
|
|
442
444
|
fovea_focus: "read",
|
|
443
445
|
fovea_dwell: "read",
|
|
444
446
|
fovea_impact: "read"
|
|
445
|
-
},
|
|
446
|
-
advisory: {
|
|
447
|
-
mode: "enabled",
|
|
448
|
-
threshold: 0.9,
|
|
449
|
-
// 2τ − 1 with the advisory's patience scale τ = 2 (see docs/capability-combustion.md).
|
|
450
|
-
maxPerSession: 3,
|
|
451
|
-
budget: 512
|
|
452
447
|
}
|
|
453
448
|
},
|
|
454
449
|
ui: {
|
|
@@ -567,11 +562,16 @@ var resultFormatValue = (value, fallback) => value === "auto" || value === "yaml
|
|
|
567
562
|
var compactionEngineValue = (value, fallback) => value === "pi" || value === "fabric" ? value : fallback;
|
|
568
563
|
var actorScopeValue = (value, fallback) => value === "project" || value === "session" ? value : fallback;
|
|
569
564
|
var schemaModeValue = (value, fallback) => value === "off" || value === "audit" || value === "enforce" ? value : fallback;
|
|
570
|
-
var advisoryModeValue = (value, fallback) => value === "enabled" || value === "hidden" || value === "disabled" ? value : fallback;
|
|
571
565
|
var mcpRevalidatePolicyValue = (value, fallback) => value === "changed" || value === "all" || value === "off" ? value : fallback;
|
|
572
566
|
var riskValue = (value, fallback) => value === "read" || value === "write" || value === "execute" || value === "network" || value === "agent" ? value : fallback;
|
|
573
567
|
var normalizeFabricConfig = (input) => {
|
|
574
568
|
const executor = objectValue(input.executor);
|
|
569
|
+
const executorMaxTimeoutMs = boundedInteger(
|
|
570
|
+
executor.maxTimeoutMs,
|
|
571
|
+
DEFAULT_FABRIC_CONFIG.executor.maxTimeoutMs,
|
|
572
|
+
1e3,
|
|
573
|
+
MAX_EXECUTOR_TIMEOUT_MS
|
|
574
|
+
);
|
|
575
575
|
const approvals = objectValue(input.approvals);
|
|
576
576
|
const mcp = objectValue(input.mcp);
|
|
577
577
|
const mcpCache = objectValue(mcp.cache);
|
|
@@ -646,7 +646,6 @@ var normalizeFabricConfig = (input) => {
|
|
|
646
646
|
...DEFAULT_FABRIC_CONFIG.capture.risks,
|
|
647
647
|
...objectValue(capture.risks)
|
|
648
648
|
};
|
|
649
|
-
const configuredAdvisory = objectValue(capture.advisory);
|
|
650
649
|
const trustedCommands = Object.fromEntries(
|
|
651
650
|
Object.entries(objectValue(schema.trustedCommands)).flatMap(([name, raw]) => {
|
|
652
651
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(name)) return [];
|
|
@@ -670,11 +669,22 @@ var normalizeFabricConfig = (input) => {
|
|
|
670
669
|
fullCodeMode: booleanValue(input.fullCodeMode, DEFAULT_FABRIC_CONFIG.fullCodeMode),
|
|
671
670
|
executor: {
|
|
672
671
|
runtime: executorRuntime,
|
|
672
|
+
maxTimeoutMs: boundedInteger(
|
|
673
|
+
executor.maxTimeoutMs,
|
|
674
|
+
DEFAULT_FABRIC_CONFIG.executor.maxTimeoutMs,
|
|
675
|
+
1e3,
|
|
676
|
+
MAX_EXECUTOR_TIMEOUT_MS
|
|
677
|
+
),
|
|
678
|
+
hostCallTimeouts: Object.fromEntries(
|
|
679
|
+
Object.entries(objectValue(executor.hostCallTimeouts)).filter(
|
|
680
|
+
([ref, value]) => typeof ref === "string" && Boolean(ref.trim()) && typeof value === "number" && Number.isFinite(value) && value >= 1
|
|
681
|
+
).map(([ref, value]) => [ref, boundedInteger(value, 1e3, 1e3, executorMaxTimeoutMs)])
|
|
682
|
+
),
|
|
673
683
|
timeoutMs: boundedInteger(
|
|
674
684
|
executor.timeoutMs,
|
|
675
685
|
DEFAULT_FABRIC_CONFIG.executor.timeoutMs,
|
|
676
686
|
1e3,
|
|
677
|
-
|
|
687
|
+
executorMaxTimeoutMs
|
|
678
688
|
),
|
|
679
689
|
memoryLimitBytes: boundedInteger(
|
|
680
690
|
executor.memoryLimitBytes,
|
|
@@ -733,8 +743,7 @@ var normalizeFabricConfig = (input) => {
|
|
|
733
743
|
1e3,
|
|
734
744
|
6e5
|
|
735
745
|
)
|
|
736
|
-
}
|
|
737
|
-
advisory: booleanValue(mcp.advisory, DEFAULT_FABRIC_CONFIG.mcp.advisory)
|
|
746
|
+
}
|
|
738
747
|
},
|
|
739
748
|
prewalk: {
|
|
740
749
|
...prewalk.enabled === false ? { enabled: false } : {},
|
|
@@ -828,28 +837,7 @@ var normalizeFabricConfig = (input) => {
|
|
|
828
837
|
),
|
|
829
838
|
keepVisible: [...new Set(configuredVisible)],
|
|
830
839
|
defaultRisk: riskValue(capture.defaultRisk, DEFAULT_FABRIC_CONFIG.capture.defaultRisk),
|
|
831
|
-
risks
|
|
832
|
-
advisory: {
|
|
833
|
-
mode: advisoryModeValue(configuredAdvisory.mode, DEFAULT_FABRIC_CONFIG.capture.advisory.mode),
|
|
834
|
-
threshold: boundedFloat(
|
|
835
|
-
configuredAdvisory.threshold,
|
|
836
|
-
DEFAULT_FABRIC_CONFIG.capture.advisory.threshold,
|
|
837
|
-
0,
|
|
838
|
-
1e3
|
|
839
|
-
),
|
|
840
|
-
maxPerSession: boundedInteger(
|
|
841
|
-
configuredAdvisory.maxPerSession,
|
|
842
|
-
DEFAULT_FABRIC_CONFIG.capture.advisory.maxPerSession,
|
|
843
|
-
1,
|
|
844
|
-
50
|
|
845
|
-
),
|
|
846
|
-
budget: boundedInteger(
|
|
847
|
-
configuredAdvisory.budget,
|
|
848
|
-
DEFAULT_FABRIC_CONFIG.capture.advisory.budget,
|
|
849
|
-
128,
|
|
850
|
-
8192
|
|
851
|
-
)
|
|
852
|
-
}
|
|
840
|
+
risks
|
|
853
841
|
},
|
|
854
842
|
ui: {
|
|
855
843
|
enabled: booleanValue(ui.enabled, DEFAULT_FABRIC_CONFIG.ui.enabled),
|
|
@@ -1257,4 +1245,4 @@ export {
|
|
|
1257
1245
|
loadFabricConfig,
|
|
1258
1246
|
saveFabricConfig
|
|
1259
1247
|
};
|
|
1260
|
-
//# sourceMappingURL=chunk-
|
|
1248
|
+
//# sourceMappingURL=chunk-6NYBEXUT.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/core/atomic-write.ts", "../../src/config.ts", "../../src/core/model-resolution.ts", "../../src/config-migrations.ts"],
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface AtomicWriteOptions {\n // File mode for the committed file (default 0o600) and for mkdir -p of its\n // parent directory (default 0o700).\n mode?: number;\n dirMode?: number;\n // Windows transiently rejects rename() with EPERM/EACCES/EEXIST/EBUSY while\n // an antivirus scan, indexer, or sibling reader probes the destination \u2014\n // milliseconds of contention, not a policy failure. Retry a bounded number\n // of times with linear backoff before surfacing the error.\n renameRetries?: number;\n renameRetryDelayMs?: number;\n}\n\nconst RETRYABLE_RENAME_CODES = new Set([\"EPERM\", \"EACCES\", \"EEXIST\", \"EBUSY\"]);\n\nconst errorCode = (error: unknown): string | undefined =>\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n\n// Portable synchronous sleep for the retry window (Atomics.wait is legal on\n// the Node main thread). If unavailable, retries proceed immediately \u2014 still\n// correct, just less cooperative under contention.\nconst syncSleep = (() => {\n try {\n const buffer = new Int32Array(new SharedArrayBuffer(4));\n return (ms: number): void => {\n Atomics.wait(buffer, 0, 0, ms);\n };\n } catch {\n return (): void => undefined;\n }\n})();\n\nexport const renameAtomic = (\n source: string,\n target: string,\n options?: AtomicWriteOptions,\n): void => {\n const attempts = Math.max(1, options?.renameRetries ?? 8);\n const delay = options?.renameRetryDelayMs ?? 25;\n for (let attempt = 1; attempt <= attempts; attempt++) {\n try {\n fs.renameSync(source, target);\n return;\n } catch (error) {\n const code = errorCode(error);\n if (attempt === attempts || code === undefined || !RETRYABLE_RENAME_CODES.has(code)) {\n throw error;\n }\n syncSleep(delay * attempt);\n }\n }\n};\n\nexport const writeFileAtomic = (\n filePath: string,\n contents: string,\n options?: AtomicWriteOptions,\n): void => {\n fs.mkdirSync(path.dirname(filePath), {\n recursive: true,\n mode: options?.dirMode ?? 0o700,\n });\n const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;\n try {\n fs.writeFileSync(temporary, contents, {\n encoding: \"utf8\",\n mode: options?.mode ?? 0o600,\n });\n renameAtomic(temporary, filePath, options);\n } finally {\n // No-op right after a successful rename; removes the temp on failure.\n fs.rmSync(temporary, { force: true });\n }\n};\n\nexport interface AtomicJsonOptions extends AtomicWriteOptions {\n // Pretty-print indent for JSON.stringify (default: compact).\n space?: number;\n // Some on-disk formats expect a trailing newline (schema state files).\n newline?: boolean;\n}\n\nexport const writeJsonAtomic = (\n filePath: string,\n value: unknown,\n options?: AtomicJsonOptions,\n): void => {\n const space = options?.space;\n const serialized =\n JSON.stringify(value, null, space) + (options?.newline === true ? \"\\n\" : \"\");\n writeFileAtomic(filePath, serialized, options);\n};\n", "import fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { renameAtomic } from \"./core/atomic-write.js\";\nimport { normalizeModelAliases } from \"./core/model-resolution.js\";\nimport { PI_CORE_TOOL_NAME_SET } from \"./core/pi-tools.js\";\nimport {\n CURRENT_FABRIC_CONFIG_VERSION,\n migrateFabricConfigDocument,\n} from \"./config-migrations.js\";\nimport type { FabricComponentEntry } from \"./components/types.js\";\nimport type { FabricRisk } from \"./protocol.js\";\nimport { DEFAULT_FABRIC_THINKING, isFabricThinking, type FabricThinking } from \"./thinking.js\";\nimport {\n defaultCodePreviewSettings,\n normalizeCodePreviewSettings,\n type CodePreviewSettings,\n} from \"./ui/code-preview.js\";\n\ntype FabricApprovalMode = \"allow\" | \"ask\" | \"auto\" | \"deny\";\nexport type FabricAgentTransport =\n | \"auto\"\n | \"process\"\n | \"tmux\"\n | \"screen\"\n | \"localterm\"\n | \"herdr\";\nexport type FabricAgentRunner = \"pi\" | \"claude\" | \"veda\";\nexport type FabricUiWidgetMode = \"auto\" | \"always\" | \"hidden\";\ntype FabricToolDisplayMode = \"full\" | \"compact\";\nexport type FabricResultFormat = \"auto\" | \"yaml\" | \"json\" | \"text\";\nexport type FabricPrewalkMode = \"in-place\" | \"trajectory\";\nexport type FabricExecutorRuntime = \"quickjs\" | \"node-process\" | \"bun-process\";\nexport type FabricConfigScope = \"global\" | \"project\";\ntype FabricCompactionEngine = \"pi\" | \"fabric\";\ntype FabricActorScope = \"project\" | \"session\";\n\ninterface FabricExecutorConfig {\n runtime: FabricExecutorRuntime;\n timeoutMs: number;\n /** Policy maximum for any executor deadline, including per-invocation\n * requests and per-ref floors. Values above this are visibly normalized. */\n maxTimeoutMs: number;\n /** Exact-ref deadline floors (ms) for known long-running host calls, e.g.\n * \"extensions.subagent\". Keys are exact refs; no wildcard matching. */\n hostCallTimeouts: Record<string, number>;\n memoryLimitBytes: number;\n maxOutputChars: number;\n maxNestedResultChars: number;\n resultFormat: FabricResultFormat;\n}\n\nexport interface FabricApprovalConfig {\n read: FabricApprovalMode;\n write: FabricApprovalMode;\n execute: FabricApprovalMode;\n network: FabricApprovalMode;\n agent: FabricApprovalMode;\n model?: string;\n}\n\n/** Session-start background revalidation scope for the MCP descriptor cache:\n * \"changed\" lists only added/reconfigured servers, \"all\" re-lists every known\n * server, \"off\" never spawns servers in the background. */\ntype FabricMcpRevalidatePolicy = \"changed\" | \"all\" | \"off\";\n\ninterface FabricMcpCacheConfig {\n /** Serve MCP tool metadata from the on-disk descriptor cache instead of\n * connecting to every configured server on first discovery each session. */\n enabled: boolean;\n revalidate: FabricMcpRevalidatePolicy;\n /** Wall-clock budget for one session-start background revalidation pass. */\n revalidateBudgetMs: number;\n}\n\nexport interface FabricMcpConfig {\n enabled: boolean;\n configPath?: string;\n disableOAuth: boolean;\n allowDynamicServers: boolean;\n callTimeoutMs: number;\n cache: FabricMcpCacheConfig;\n}\n\ninterface FabricClaudeRunnerConfig {\n binary: string;\n model?: string;\n}\n\n/** Veda CLI options for the `veda` agent runner. The Veda CLI wraps external\n * backends (agy, codex, claude-code, droid, pi, and any backend registered by\n * the installed Veda build); the backend is selected here and the persona\n * controls read-only vs write-capable behavior. */\ninterface FabricVedaRunnerConfig {\n binary: string;\n /** Veda backend to drive. Defaults to the Antigravity CLI (agy). */\n backend: string;\n /** Optional backend-specific model or Veda model alias. */\n model?: string;\n /** Veda persona: navigator-plan, navigator-chat, reviewer, or worker. */\n persona: string;\n}\n\ninterface FabricPrewalkConfig {\n // Master switch, persisted by /fabric prewalk --disable|--enable or the\n // settings UI (absent means enabled). Manual arming, session auto-arm, and\n // boundary claims all gate on it.\n enabled?: boolean;\n mode: FabricPrewalkMode;\n model?: string;\n alwaysRearm: boolean;\n // Compact with the configured engine just before restoring Main's boundary\n // model after an in-place continuation settles.\n compactOnReturn: boolean;\n // Filesystem fallback trigger: when an armed boundary ran a successful\n // pi.bash without an audited mutation, claim on stat-manifest drift so\n // shell heredocs / sed -i / formatter writes also hand off.\n detectShellWrites: boolean;\n // Reasoning effort for the trajectory executor; unset inherits agents.thinking.\n thinking?: FabricThinking;\n}\n\nexport interface FabricAgentConfig {\n enabled: boolean;\n runner: FabricAgentRunner;\n transport: FabricAgentTransport;\n model?: string;\n claude: FabricClaudeRunnerConfig;\n veda: FabricVedaRunnerConfig;\n thinking: FabricThinking;\n maxConcurrent: number;\n maxPerExecution: number;\n maxDepth: number;\n timeoutMs: number;\n extensions: boolean;\n defaultTools: string[];\n retainRuns: boolean;\n notifyOnComplete: boolean;\n budgetUsd: number;\n maxTokensPerChild: number;\n /** Write usage-only pi-format session files per agent run for external trackers. */\n sessionExport: boolean;\n /** Export store root override; PI_FABRIC_AGENT_DIR wins. Empty = ~/.pi-fabric/agent. */\n sessionExportDir: string;\n}\n\nexport interface FabricToolCaptureConfig {\n enabled: boolean;\n hideFromModel: boolean;\n keepVisible: string[];\n defaultRisk: FabricRisk;\n risks: Record<string, FabricRisk>;\n}\n\nexport type FabricSchemaMode = \"off\" | \"audit\" | \"enforce\";\n\nexport interface FabricSchemaTrustedCommand {\n command: string;\n args: string[];\n shell: boolean;\n timeoutMs: number;\n}\n\nexport interface FabricSchemaConfig {\n mode: FabricSchemaMode;\n certificateTtlMs: number;\n maxFiles: number;\n maxBytes: number;\n trustedCommands: Record<string, FabricSchemaTrustedCommand>;\n}\n\ninterface FabricUiConfig {\n enabled: boolean;\n widget: FabricUiWidgetMode;\n maxRows: number;\n refreshMs: number;\n eventHistory: number;\n haltOnEscape: boolean;\n showAgentToolPreview: boolean;\n toolDisplay: FabricToolDisplayMode;\n updateDebounceMs: number;\n}\n\ninterface FabricCompactionConfig {\n engine: FabricCompactionEngine;\n targetContextRatio: number;\n thresholds: Record<string, number>;\n tokenThresholds: Record<string, number>;\n}\n\nexport const MIN_COMPACTION_TOKEN_THRESHOLD = 1_000;\nexport const MAX_COMPACTION_TOKEN_THRESHOLD = 100_000_000;\nexport const MIN_COMPACTION_RATIO_THRESHOLD = 0.25;\nexport const MAX_COMPACTION_RATIO_THRESHOLD = 0.95;\n\nexport const clampCompactionTokenThreshold = (value: number): number =>\n Math.min(\n MAX_COMPACTION_TOKEN_THRESHOLD,\n Math.max(MIN_COMPACTION_TOKEN_THRESHOLD, Math.round(value)),\n );\n\nexport const clampCompactionRatioThreshold = (value: number): number =>\n Math.min(\n MAX_COMPACTION_RATIO_THRESHOLD,\n Math.max(MIN_COMPACTION_RATIO_THRESHOLD, value),\n );\n\nexport interface FabricRetentionConfig {\n orphanedTempRunMs: number;\n oneShotRunMs: number;\n actorRunArchiveMs: number;\n}\n\nexport interface FabricMeshConfig {\n enabled: boolean;\n root?: string;\n actorScope: FabricActorScope;\n maxEventBytes: number;\n maxReadEvents: number;\n actorPollMs: number;\n actorQueueLimit: number;\n eventContextChars: number;\n actorContextEntries: number;\n}\n\nexport interface FabricMemoryConfig {\n enabled: boolean;\n indexDir?: string;\n maxSessions: number;\n maxEntryChars: number;\n indexThinking: boolean;\n indexToolOutput: boolean;\n hotSessions?: number;\n digestTerms?: number;\n maxColdVocabularyBytes?: number;\n maxColdCacheBytes?: number;\n maxSyncSessions?: number;\n maxSyncSourceBytes?: number;\n maxCacheCleanupFiles?: number;\n regexMaxPatternBytes?: number;\n regexMaxHaystackTerms?: number;\n regexMaxHaystackBytes?: number;\n regexTimeoutMs?: number;\n}\n\nexport interface FabricSpeculationConfig {\n /** Master switch for speculative programmatic tool calling during streaming. */\n enabled: boolean;\n /** Maximum simultaneously in-flight speculative calls; excess candidates are dropped. */\n maxConcurrent: number;\n /** Maximum retained unserved speculation entries per turn. */\n maxEntries: number;\n /** Per-stream cap on buffered partial tool-call arguments while extracting the `code` field. */\n maxBufferBytes: number;\n /** Unserved speculation entries older than this are aborted and discarded. */\n entryTtlMs: number;\n /**\n * Tier B: MCP tools that may be speculated despite risk \"network\". Entries\n * are `server.tool` or `server.*` and match the ref after the `mcp.` prefix.\n * Only enable for tools the operator knows are read-only; cached MCP\n * annotations with destructiveHint=true always refuse.\n */\n mcpAllowlist: string[];\n}\n\n\nexport interface FabricModelsConfig {\n /** Alias name \u2192 ordered provider/model fallback chain, first available wins. */\n aliases: Record<string, string[]>;\n}\n\nexport interface FabricConfig {\n fullCodeMode: boolean;\n executor: FabricExecutorConfig;\n approvals: FabricApprovalConfig;\n mcp: FabricMcpConfig;\n prewalk: FabricPrewalkConfig;\n agents: FabricAgentConfig;\n models: FabricModelsConfig;\n components: FabricComponentEntry[];\n capture: FabricToolCaptureConfig;\n ui: FabricUiConfig;\n compaction: FabricCompactionConfig;\n retention: FabricRetentionConfig;\n mesh: FabricMeshConfig;\n memory: FabricMemoryConfig;\n schema: FabricSchemaConfig;\n speculation: FabricSpeculationConfig;\n codePreview: CodePreviewSettings;\n}\n\n/** Hard implementation maximum for any executor deadline. Policy ceilings\n * (executor.maxTimeoutMs) may be raised up to this value by administrators. */\nexport const MAX_EXECUTOR_TIMEOUT_MS = 24 * 3_600_000;\n\nexport const MIN_AGENT_TIMEOUT_MS = 1_000;\nconst DEFAULT_AGENT_TIMEOUT_MS = 3_600_000;\nexport const MAX_AGENT_TIMEOUT_MS = 24 * 3_600_000;\nexport const QUICKJS_MAX_MEMORY_LIMIT_BYTES = 0xffff_ffff;\nexport const MAX_EXECUTOR_MEMORY_LIMIT_BYTES = Math.max(\n 8 * 1024 * 1024,\n Math.min(Number.MAX_SAFE_INTEGER, Math.floor(os.totalmem())),\n);\n\nexport const maxExecutorMemoryLimitBytes = (runtime: FabricExecutorRuntime): number =>\n runtime === \"quickjs\"\n ? Math.min(QUICKJS_MAX_MEMORY_LIMIT_BYTES, MAX_EXECUTOR_MEMORY_LIMIT_BYTES)\n : MAX_EXECUTOR_MEMORY_LIMIT_BYTES;\n\nexport const DEFAULT_FABRIC_CONFIG: FabricConfig = {\n fullCodeMode: true,\n executor: {\n runtime: \"quickjs\",\n timeoutMs: 120_000,\n maxTimeoutMs: 900_000,\n hostCallTimeouts: {},\n memoryLimitBytes: 64 * 1024 * 1024,\n maxOutputChars: 50_000,\n maxNestedResultChars: 2_000_000,\n resultFormat: \"auto\",\n },\n approvals: {\n read: \"allow\",\n write: \"allow\",\n execute: \"allow\",\n network: \"allow\",\n agent: \"allow\",\n },\n mcp: {\n enabled: true,\n disableOAuth: true,\n allowDynamicServers: true,\n callTimeoutMs: 120_000,\n cache: {\n enabled: true,\n revalidate: \"changed\",\n revalidateBudgetMs: 60_000,\n },\n },\n prewalk: {\n mode: \"in-place\",\n alwaysRearm: false,\n compactOnReturn: true,\n detectShellWrites: true,\n },\n agents: {\n enabled: true,\n runner: \"pi\",\n transport: \"process\",\n claude: { binary: \"claude\" },\n veda: { binary: \"veda\", backend: \"agy\", persona: \"navigator-chat\" },\n thinking: DEFAULT_FABRIC_THINKING,\n maxConcurrent: 4,\n maxPerExecution: 100,\n maxDepth: 2,\n timeoutMs: DEFAULT_AGENT_TIMEOUT_MS,\n extensions: true,\n defaultTools: [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"],\n retainRuns: false,\n notifyOnComplete: true,\n budgetUsd: 0,\n maxTokensPerChild: 0,\n sessionExport: true,\n sessionExportDir: \"\",\n },\n components: [],\n capture: {\n enabled: true,\n hideFromModel: true,\n keepVisible: [\"fabric_exec\"],\n defaultRisk: \"execute\",\n risks: {\n read: \"read\",\n grep: \"read\",\n find: \"read\",\n ls: \"read\",\n edit: \"write\",\n write: \"write\",\n bash: \"execute\",\n fovea_sketch: \"read\",\n fovea_focus: \"read\",\n fovea_dwell: \"read\",\n fovea_impact: \"read\",\n },\n },\n ui: {\n enabled: true,\n widget: \"auto\",\n maxRows: 6,\n refreshMs: 500,\n eventHistory: 80,\n haltOnEscape: true,\n showAgentToolPreview: true,\n toolDisplay: \"compact\",\n updateDebounceMs: 100,\n },\n compaction: {\n engine: \"fabric\",\n targetContextRatio: 0.65,\n thresholds: {},\n tokenThresholds: {},\n },\n retention: {\n orphanedTempRunMs: 6 * 60 * 60 * 1_000,\n oneShotRunMs: 24 * 60 * 60 * 1_000,\n actorRunArchiveMs: 7 * 24 * 60 * 60 * 1_000,\n },\n mesh: {\n enabled: true,\n actorScope: \"project\",\n maxEventBytes: 256 * 1024,\n maxReadEvents: 500,\n actorPollMs: 250,\n actorQueueLimit: 32,\n eventContextChars: 40_000,\n actorContextEntries: 14,\n },\n models: {\n aliases: {},\n },\n memory: {\n enabled: true,\n maxSessions: 500,\n maxEntryChars: 2_000,\n indexThinking: false,\n indexToolOutput: true,\n hotSessions: 50,\n digestTerms: 200,\n maxColdVocabularyBytes: 512 * 1024,\n maxColdCacheBytes: 1024 * 1024,\n maxSyncSessions: 10_000,\n maxSyncSourceBytes: 512 * 1024 * 1024,\n maxCacheCleanupFiles: 100_000,\n regexMaxPatternBytes: 1_024,\n regexMaxHaystackTerms: 20_000,\n regexMaxHaystackBytes: 2 * 1024 * 1024,\n regexTimeoutMs: 250,\n },\n schema: {\n mode: \"off\",\n certificateTtlMs: 30_000,\n maxFiles: 100,\n maxBytes: 10 * 1024 * 1024,\n trustedCommands: {},\n },\n speculation: {\n enabled: true,\n maxConcurrent: 4,\n maxEntries: 64,\n maxBufferBytes: 2 * 1024 * 1024,\n entryTtlMs: 180_000,\n mcpAllowlist: [],\n },\n codePreview: defaultCodePreviewSettings(),\n};\n\ninterface JsonObjectFile {\n document: Record<string, unknown>;\n source: string;\n}\n\nconst readJsonObjectFile = (filePath: string): JsonObjectFile | undefined => {\n try {\n const source = fs.readFileSync(filePath, \"utf8\");\n const parsed: unknown = JSON.parse(source);\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(\"configuration root must be an object\");\n }\n return { document: parsed as Record<string, unknown>, source };\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") return undefined;\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read ${filePath}: ${message}`);\n }\n};\n\nconst readJsonObject = (filePath: string): Record<string, unknown> | undefined =>\n readJsonObjectFile(filePath)?.document;\n\nconst mergeObjects = (\n base: Record<string, unknown>,\n override: Record<string, unknown>,\n): Record<string, unknown> => {\n const merged = { ...base };\n for (const [key, value] of Object.entries(override)) {\n const baseValue = merged[key];\n if (\n typeof baseValue === \"object\" &&\n baseValue !== null &&\n !Array.isArray(baseValue) &&\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n ) {\n merged[key] = mergeObjects(\n baseValue as Record<string, unknown>,\n value as Record<string, unknown>,\n );\n } else {\n merged[key] = value;\n }\n }\n return merged;\n};\n\nconst approvalMode = (value: unknown, fallback: FabricApprovalMode): FabricApprovalMode =>\n value === \"allow\" || value === \"ask\" || value === \"auto\" || value === \"deny\"\n ? value\n : fallback;\n\nconst booleanValue = (value: unknown, fallback: boolean): boolean =>\n typeof value === \"boolean\" ? value : fallback;\n\nconst boundedInteger = (value: unknown, fallback: number, min: number, max: number): number =>\n typeof value === \"number\" && Number.isInteger(value)\n ? Math.max(min, Math.min(max, value))\n : fallback;\n\nconst boundedFloat = (value: unknown, fallback: number, min: number, max: number): number =>\n typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(min, Math.min(max, value))\n : fallback;\n\nconst stringValue = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() ? value : undefined;\n\nconst runnerValue = (value: unknown, fallback: FabricAgentRunner): FabricAgentRunner =>\n value === \"pi\" || value === \"claude\" || value === \"veda\" ? value : fallback;\n\nconst prewalkModeValue = (\n value: unknown,\n fallback: FabricPrewalkMode,\n): FabricPrewalkMode =>\n value === \"in-place\" || value === \"trajectory\" ? value : fallback;\n\nconst transportValue = (\n value: unknown,\n fallback: FabricAgentTransport,\n): FabricAgentTransport =>\n value === \"auto\" ||\n value === \"process\" ||\n value === \"tmux\" ||\n value === \"screen\" ||\n value === \"localterm\" ||\n value === \"herdr\"\n ? value\n : fallback;\n\nconst thinkingValue = (value: unknown, fallback: FabricThinking): FabricThinking =>\n isFabricThinking(value) ? value : fallback;\n\nconst objectValue = (value: unknown): Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n\nconst widgetModeValue = (value: unknown, fallback: FabricUiWidgetMode): FabricUiWidgetMode =>\n value === \"auto\" || value === \"always\" || value === \"hidden\" ? value : fallback;\n\nconst toolDisplayModeValue = (\n value: unknown,\n fallback: FabricToolDisplayMode,\n): FabricToolDisplayMode => value === \"full\" || value === \"compact\" ? value : fallback;\n\nconst executorRuntimeValue = (\n value: unknown,\n fallback: FabricExecutorRuntime,\n): FabricExecutorRuntime =>\n value === \"quickjs\" || value === \"node-process\" || value === \"bun-process\" ? value : fallback;\n\nconst resultFormatValue = (\n value: unknown,\n fallback: FabricResultFormat,\n): FabricResultFormat =>\n value === \"auto\" || value === \"yaml\" || value === \"json\" || value === \"text\"\n ? value\n : fallback;\n\nconst compactionEngineValue = (\n value: unknown,\n fallback: FabricCompactionEngine,\n): FabricCompactionEngine =>\n value === \"pi\" || value === \"fabric\" ? value : fallback;\n\nconst actorScopeValue = (value: unknown, fallback: FabricActorScope): FabricActorScope =>\n value === \"project\" || value === \"session\" ? value : fallback;\n\nconst schemaModeValue = (value: unknown, fallback: FabricSchemaMode): FabricSchemaMode =>\n value === \"off\" || value === \"audit\" || value === \"enforce\" ? value : fallback;\n\nconst mcpRevalidatePolicyValue = (\n value: unknown,\n fallback: FabricMcpRevalidatePolicy,\n): FabricMcpRevalidatePolicy =>\n value === \"changed\" || value === \"all\" || value === \"off\" ? value : fallback;\n\nconst riskValue = (value: unknown, fallback: FabricRisk): FabricRisk =>\n value === \"read\" ||\n value === \"write\" ||\n value === \"execute\" ||\n value === \"network\" ||\n value === \"agent\"\n ? value\n : fallback;\n\nexport const normalizeFabricConfig = (input: Record<string, unknown>): FabricConfig => {\n const executor = objectValue(input.executor);\n const executorMaxTimeoutMs = boundedInteger(\n executor.maxTimeoutMs,\n DEFAULT_FABRIC_CONFIG.executor.maxTimeoutMs,\n 1_000,\n MAX_EXECUTOR_TIMEOUT_MS,\n );\n const approvals = objectValue(input.approvals);\n const mcp = objectValue(input.mcp);\n const mcpCache = objectValue(mcp.cache);\n const prewalk = objectValue(input.prewalk);\n const agents = objectValue(input.agents);\n const claude = objectValue(agents.claude);\n const veda = objectValue(agents.veda);\n const capture = objectValue(input.capture);\n const ui = objectValue(input.ui);\n const compaction = objectValue(input.compaction);\n const retention = objectValue(input.retention);\n const mesh = objectValue(input.mesh);\n const memory = objectValue(input.memory);\n const modelsSection = objectValue(input.models);\n const schema = objectValue(input.schema);\n const schemaMode = schemaModeValue(schema.mode, DEFAULT_FABRIC_CONFIG.schema.mode);\n const speculation = objectValue(input.speculation);\n const configuredExecutorRuntime = executorRuntimeValue(\n executor.runtime,\n DEFAULT_FABRIC_CONFIG.executor.runtime,\n );\n const executorRuntime = schemaMode === \"enforce\" ? \"quickjs\" : configuredExecutorRuntime;\n const configuredTools = Array.isArray(agents.defaultTools)\n ? agents.defaultTools.filter(\n (tool): tool is string => typeof tool === \"string\" && Boolean(tool),\n )\n : DEFAULT_FABRIC_CONFIG.agents.defaultTools;\n const approvalModel = stringValue(approvals.model);\n const configPath = stringValue(mcp.configPath);\n const meshRoot = stringValue(mesh.root);\n const memoryIndexDir = stringValue(memory.indexDir);\n const compactionThresholds = Object.fromEntries(\n Object.entries(objectValue(compaction.thresholds))\n .filter(([model, threshold]) =>\n model.includes(\"/\")\n && typeof threshold === \"number\"\n && Number.isFinite(threshold),\n )\n .map(([model, threshold]) => [\n model,\n clampCompactionRatioThreshold(threshold as number),\n ]),\n );\n const compactionTokenThresholds = Object.fromEntries(\n Object.entries(objectValue(compaction.tokenThresholds))\n .filter(([model, tokens]) =>\n model.includes(\"/\")\n && typeof tokens === \"number\"\n && Number.isFinite(tokens),\n )\n .map(([model, tokens]) => [\n model,\n clampCompactionTokenThreshold(tokens as number),\n ]),\n );\n const prewalkModel = stringValue(prewalk.model);\n const prewalkThinking = isFabricThinking(prewalk.thinking) ? prewalk.thinking : undefined;\n const agentModel = stringValue(agents.model);\n const claudeBinary = stringValue(claude.binary);\n const claudeModel = stringValue(claude.model);\n const vedaBinary = stringValue(veda.binary);\n const vedaBackend = stringValue(veda.backend);\n const vedaModel = stringValue(veda.model);\n const vedaPersona = stringValue(veda.persona);\n const agentThinking = thinkingValue(agents.thinking, DEFAULT_FABRIC_CONFIG.agents.thinking);\n const configuredComponents: FabricComponentEntry[] = Array.isArray(input.components)\n ? input.components.flatMap((raw) => {\n const componentEntry = objectValue(raw);\n const id = stringValue(componentEntry.id);\n const component = stringValue(componentEntry.component);\n if (!id || !component) return [];\n return [{\n id,\n component,\n ...(Object.prototype.hasOwnProperty.call(componentEntry, \"config\")\n ? { config: componentEntry.config }\n : {}),\n ...(typeof componentEntry.disabled === \"boolean\"\n ? { disabled: componentEntry.disabled }\n : {}),\n }];\n }).slice(0, 256)\n : DEFAULT_FABRIC_CONFIG.components;\n const configuredVisible = Array.isArray(capture.keepVisible)\n ? capture.keepVisible.filter(\n (name): name is string => typeof name === \"string\" && Boolean(name.trim()),\n )\n : DEFAULT_FABRIC_CONFIG.capture.keepVisible;\n const configuredRisks = {\n ...DEFAULT_FABRIC_CONFIG.capture.risks,\n ...objectValue(capture.risks),\n };\n const trustedCommands = Object.fromEntries(\n Object.entries(objectValue(schema.trustedCommands)).flatMap(([name, raw]) => {\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(name)) return [];\n const command = objectValue(raw);\n const executable = stringValue(command.command);\n if (!executable) return [];\n const shell = booleanValue(command.shell, false);\n const args = !shell && Array.isArray(command.args)\n ? command.args.filter((arg): arg is string => typeof arg === \"string\").slice(0, 64)\n : [];\n return [[name, {\n command: executable,\n args,\n shell,\n timeoutMs: boundedInteger(command.timeoutMs, 30_000, 1, 300_000),\n } satisfies FabricSchemaTrustedCommand]];\n }),\n );\n const risks = Object.fromEntries(\n Object.entries(configuredRisks)\n .filter(([name]) => Boolean(name.trim()))\n .map(([name, risk]) => [name, riskValue(risk, DEFAULT_FABRIC_CONFIG.capture.defaultRisk)]),\n );\n\n return {\n fullCodeMode: booleanValue(input.fullCodeMode, DEFAULT_FABRIC_CONFIG.fullCodeMode),\n executor: {\n runtime: executorRuntime,\n maxTimeoutMs: boundedInteger(\n executor.maxTimeoutMs,\n DEFAULT_FABRIC_CONFIG.executor.maxTimeoutMs,\n 1_000,\n MAX_EXECUTOR_TIMEOUT_MS,\n ),\n hostCallTimeouts: Object.fromEntries(\n Object.entries(objectValue(executor.hostCallTimeouts))\n .filter(([ref, value]) =>\n typeof ref === \"string\" &&\n Boolean(ref.trim()) &&\n typeof value === \"number\" &&\n Number.isFinite(value) &&\n value >= 1,\n )\n .map(([ref, value]) => [ref, boundedInteger(value, 1_000, 1_000, executorMaxTimeoutMs)]),\n ),\n timeoutMs: boundedInteger(\n executor.timeoutMs,\n DEFAULT_FABRIC_CONFIG.executor.timeoutMs,\n 1_000,\n executorMaxTimeoutMs,\n ),\n memoryLimitBytes: boundedInteger(\n executor.memoryLimitBytes,\n DEFAULT_FABRIC_CONFIG.executor.memoryLimitBytes,\n 8 * 1024 * 1024,\n maxExecutorMemoryLimitBytes(executorRuntime),\n ),\n maxOutputChars: boundedInteger(\n executor.maxOutputChars,\n DEFAULT_FABRIC_CONFIG.executor.maxOutputChars,\n 1_000,\n 1_000_000,\n ),\n maxNestedResultChars: boundedInteger(\n executor.maxNestedResultChars,\n DEFAULT_FABRIC_CONFIG.executor.maxNestedResultChars,\n 10_000,\n 20_000_000,\n ),\n resultFormat: resultFormatValue(\n executor.resultFormat,\n DEFAULT_FABRIC_CONFIG.executor.resultFormat,\n ),\n },\n approvals: {\n read: approvalMode(approvals.read, DEFAULT_FABRIC_CONFIG.approvals.read),\n write: approvalMode(approvals.write, DEFAULT_FABRIC_CONFIG.approvals.write),\n execute: approvalMode(approvals.execute, DEFAULT_FABRIC_CONFIG.approvals.execute),\n network: approvalMode(approvals.network, DEFAULT_FABRIC_CONFIG.approvals.network),\n agent: approvalMode(approvals.agent, DEFAULT_FABRIC_CONFIG.approvals.agent),\n ...(approvalModel ? { model: approvalModel } : {}),\n },\n mcp: {\n enabled: booleanValue(mcp.enabled, DEFAULT_FABRIC_CONFIG.mcp.enabled),\n ...(configPath ? { configPath } : {}),\n disableOAuth: booleanValue(mcp.disableOAuth, DEFAULT_FABRIC_CONFIG.mcp.disableOAuth),\n allowDynamicServers: booleanValue(\n mcp.allowDynamicServers,\n DEFAULT_FABRIC_CONFIG.mcp.allowDynamicServers,\n ),\n callTimeoutMs: boundedInteger(\n mcp.callTimeoutMs,\n DEFAULT_FABRIC_CONFIG.mcp.callTimeoutMs,\n 1_000,\n 900_000,\n ),\n cache: {\n enabled: booleanValue(mcpCache.enabled, DEFAULT_FABRIC_CONFIG.mcp.cache.enabled),\n revalidate: mcpRevalidatePolicyValue(\n mcpCache.revalidate,\n DEFAULT_FABRIC_CONFIG.mcp.cache.revalidate,\n ),\n revalidateBudgetMs: boundedInteger(\n mcpCache.revalidateBudgetMs,\n DEFAULT_FABRIC_CONFIG.mcp.cache.revalidateBudgetMs,\n 1_000,\n 600_000,\n ),\n },\n },\n prewalk: {\n ...(prewalk.enabled === false ? { enabled: false } : {}),\n mode: prewalkModeValue(prewalk.mode, DEFAULT_FABRIC_CONFIG.prewalk.mode),\n ...(prewalkModel ? { model: prewalkModel } : {}),\n ...(prewalkThinking ? { thinking: prewalkThinking } : {}),\n alwaysRearm: booleanValue(\n prewalk.alwaysRearm,\n DEFAULT_FABRIC_CONFIG.prewalk.alwaysRearm,\n ),\n compactOnReturn: booleanValue(\n prewalk.compactOnReturn,\n DEFAULT_FABRIC_CONFIG.prewalk.compactOnReturn,\n ),\n detectShellWrites: booleanValue(\n prewalk.detectShellWrites,\n DEFAULT_FABRIC_CONFIG.prewalk.detectShellWrites,\n ),\n },\n agents: {\n enabled: booleanValue(agents.enabled, DEFAULT_FABRIC_CONFIG.agents.enabled),\n runner: runnerValue(agents.runner, DEFAULT_FABRIC_CONFIG.agents.runner),\n transport: transportValue(agents.transport, DEFAULT_FABRIC_CONFIG.agents.transport),\n ...(agentModel ? { model: agentModel } : {}),\n claude: {\n binary: claudeBinary ?? DEFAULT_FABRIC_CONFIG.agents.claude.binary,\n ...(claudeModel ? { model: claudeModel } : {}),\n },\n veda: {\n binary: vedaBinary ?? DEFAULT_FABRIC_CONFIG.agents.veda.binary,\n backend: vedaBackend ?? DEFAULT_FABRIC_CONFIG.agents.veda.backend,\n ...(vedaModel ? { model: vedaModel } : {}),\n persona: vedaPersona ?? DEFAULT_FABRIC_CONFIG.agents.veda.persona,\n },\n thinking: agentThinking,\n maxConcurrent: boundedInteger(\n agents.maxConcurrent,\n DEFAULT_FABRIC_CONFIG.agents.maxConcurrent,\n 1,\n 32,\n ),\n maxPerExecution: boundedInteger(\n agents.maxPerExecution,\n DEFAULT_FABRIC_CONFIG.agents.maxPerExecution,\n 1,\n 1_000,\n ),\n maxDepth: boundedInteger(\n agents.maxDepth,\n DEFAULT_FABRIC_CONFIG.agents.maxDepth,\n 0,\n Number.MAX_SAFE_INTEGER,\n ),\n timeoutMs: boundedInteger(\n agents.timeoutMs,\n DEFAULT_FABRIC_CONFIG.agents.timeoutMs,\n MIN_AGENT_TIMEOUT_MS,\n MAX_AGENT_TIMEOUT_MS,\n ),\n extensions: booleanValue(agents.extensions, DEFAULT_FABRIC_CONFIG.agents.extensions),\n defaultTools: configuredTools,\n retainRuns: booleanValue(agents.retainRuns, DEFAULT_FABRIC_CONFIG.agents.retainRuns),\n notifyOnComplete: booleanValue(\n agents.notifyOnComplete,\n DEFAULT_FABRIC_CONFIG.agents.notifyOnComplete,\n ),\n budgetUsd: boundedFloat(\n agents.budgetUsd,\n DEFAULT_FABRIC_CONFIG.agents.budgetUsd,\n 0,\n 1_000_000,\n ),\n maxTokensPerChild: boundedInteger(\n agents.maxTokensPerChild,\n DEFAULT_FABRIC_CONFIG.agents.maxTokensPerChild,\n 0,\n 100_000_000,\n ),\n sessionExport: booleanValue(\n agents.sessionExport,\n DEFAULT_FABRIC_CONFIG.agents.sessionExport,\n ),\n sessionExportDir:\n typeof agents.sessionExportDir === \"string\"\n ? agents.sessionExportDir\n : DEFAULT_FABRIC_CONFIG.agents.sessionExportDir,\n },\n components: configuredComponents.map((entry) => structuredClone(entry)),\n capture: {\n enabled: booleanValue(capture.enabled, DEFAULT_FABRIC_CONFIG.capture.enabled),\n hideFromModel: booleanValue(\n capture.hideFromModel,\n DEFAULT_FABRIC_CONFIG.capture.hideFromModel,\n ),\n keepVisible: [...new Set(configuredVisible)],\n defaultRisk: riskValue(capture.defaultRisk, DEFAULT_FABRIC_CONFIG.capture.defaultRisk),\n risks,\n },\n ui: {\n enabled: booleanValue(ui.enabled, DEFAULT_FABRIC_CONFIG.ui.enabled),\n widget: widgetModeValue(ui.widget, DEFAULT_FABRIC_CONFIG.ui.widget),\n maxRows: boundedInteger(ui.maxRows, DEFAULT_FABRIC_CONFIG.ui.maxRows, 1, 20),\n refreshMs: boundedInteger(ui.refreshMs, DEFAULT_FABRIC_CONFIG.ui.refreshMs, 100, 10_000),\n eventHistory: boundedInteger(\n ui.eventHistory,\n DEFAULT_FABRIC_CONFIG.ui.eventHistory,\n 1,\n 500,\n ),\n haltOnEscape: booleanValue(ui.haltOnEscape, DEFAULT_FABRIC_CONFIG.ui.haltOnEscape),\n // Renamed from ui.showNestedToolCalls; the v2 migration rewrites persisted\n // files, and this fallback covers configs normalized without migration.\n showAgentToolPreview: booleanValue(\n ui.showAgentToolPreview ?? ui.showNestedToolCalls,\n DEFAULT_FABRIC_CONFIG.ui.showAgentToolPreview,\n ),\n toolDisplay: toolDisplayModeValue(\n ui.toolDisplay,\n DEFAULT_FABRIC_CONFIG.ui.toolDisplay,\n ),\n // Renamed from ui.nestedToolDebounceMs (v3): the window coalesces every\n // live fabric_exec card update \u2014 nested calls, progress, agent previews.\n updateDebounceMs: boundedInteger(\n ui.updateDebounceMs ?? ui.nestedToolDebounceMs,\n DEFAULT_FABRIC_CONFIG.ui.updateDebounceMs,\n 0,\n 2_000,\n ),\n },\n compaction: {\n engine: compactionEngineValue(compaction.engine, DEFAULT_FABRIC_CONFIG.compaction.engine),\n targetContextRatio: boundedFloat(\n compaction.targetContextRatio,\n DEFAULT_FABRIC_CONFIG.compaction.targetContextRatio,\n 0.25,\n 0.85,\n ),\n thresholds: compactionThresholds,\n tokenThresholds: compactionTokenThresholds,\n },\n retention: {\n orphanedTempRunMs: boundedInteger(\n retention.orphanedTempRunMs,\n DEFAULT_FABRIC_CONFIG.retention.orphanedTempRunMs,\n 60 * 60 * 1_000,\n 365 * 24 * 60 * 60 * 1_000,\n ),\n oneShotRunMs: boundedInteger(\n retention.oneShotRunMs,\n DEFAULT_FABRIC_CONFIG.retention.oneShotRunMs,\n 60 * 60 * 1_000,\n 365 * 24 * 60 * 60 * 1_000,\n ),\n actorRunArchiveMs: boundedInteger(\n retention.actorRunArchiveMs,\n DEFAULT_FABRIC_CONFIG.retention.actorRunArchiveMs,\n 60 * 60 * 1_000,\n 365 * 24 * 60 * 60 * 1_000,\n ),\n },\n mesh: {\n enabled: booleanValue(mesh.enabled, DEFAULT_FABRIC_CONFIG.mesh.enabled),\n ...(meshRoot ? { root: meshRoot } : {}),\n actorScope: actorScopeValue(mesh.actorScope, DEFAULT_FABRIC_CONFIG.mesh.actorScope),\n maxEventBytes: boundedInteger(\n mesh.maxEventBytes,\n DEFAULT_FABRIC_CONFIG.mesh.maxEventBytes,\n 1_024,\n 4 * 1024 * 1024,\n ),\n maxReadEvents: boundedInteger(\n mesh.maxReadEvents,\n DEFAULT_FABRIC_CONFIG.mesh.maxReadEvents,\n 1,\n 10_000,\n ),\n actorPollMs: boundedInteger(\n mesh.actorPollMs,\n DEFAULT_FABRIC_CONFIG.mesh.actorPollMs,\n 50,\n 10_000,\n ),\n actorQueueLimit: boundedInteger(\n mesh.actorQueueLimit,\n DEFAULT_FABRIC_CONFIG.mesh.actorQueueLimit,\n 1,\n 1_000,\n ),\n eventContextChars: boundedInteger(\n mesh.eventContextChars,\n DEFAULT_FABRIC_CONFIG.mesh.eventContextChars,\n 1_000,\n 1_000_000,\n ),\n actorContextEntries: boundedInteger(\n mesh.actorContextEntries,\n DEFAULT_FABRIC_CONFIG.mesh.actorContextEntries,\n 1,\n 100,\n ),\n },\n models: {\n aliases: normalizeModelAliases(modelsSection.aliases),\n },\n memory: {\n enabled: booleanValue(memory.enabled, DEFAULT_FABRIC_CONFIG.memory.enabled),\n ...(memoryIndexDir ? { indexDir: memoryIndexDir } : {}),\n maxSessions: boundedInteger(\n memory.maxSessions,\n DEFAULT_FABRIC_CONFIG.memory.maxSessions,\n 1,\n 100_000,\n ),\n maxEntryChars: boundedInteger(\n memory.maxEntryChars,\n DEFAULT_FABRIC_CONFIG.memory.maxEntryChars,\n 100,\n 1_000_000,\n ),\n indexThinking: booleanValue(\n memory.indexThinking,\n DEFAULT_FABRIC_CONFIG.memory.indexThinking ?? false,\n ),\n indexToolOutput: booleanValue(\n memory.indexToolOutput,\n DEFAULT_FABRIC_CONFIG.memory.indexToolOutput ?? true,\n ),\n hotSessions: boundedInteger(\n memory.hotSessions,\n DEFAULT_FABRIC_CONFIG.memory.hotSessions ?? 50,\n 0,\n 100_000,\n ),\n digestTerms: boundedInteger(\n memory.digestTerms,\n DEFAULT_FABRIC_CONFIG.memory.digestTerms ?? 200,\n 1,\n 10_000,\n ),\n maxColdVocabularyBytes: boundedInteger(\n memory.maxColdVocabularyBytes,\n DEFAULT_FABRIC_CONFIG.memory.maxColdVocabularyBytes ?? 512 * 1024,\n 2,\n 64 * 1024 * 1024,\n ),\n maxColdCacheBytes: boundedInteger(\n memory.maxColdCacheBytes,\n DEFAULT_FABRIC_CONFIG.memory.maxColdCacheBytes ?? 1024 * 1024,\n 512,\n 128 * 1024 * 1024,\n ),\n maxSyncSessions: boundedInteger(\n memory.maxSyncSessions,\n DEFAULT_FABRIC_CONFIG.memory.maxSyncSessions ?? 10_000,\n 1,\n 1_000_000,\n ),\n maxSyncSourceBytes: boundedInteger(\n memory.maxSyncSourceBytes,\n DEFAULT_FABRIC_CONFIG.memory.maxSyncSourceBytes ?? 512 * 1024 * 1024,\n 1_024,\n 8 * 1024 * 1024 * 1024,\n ),\n maxCacheCleanupFiles: boundedInteger(\n memory.maxCacheCleanupFiles,\n DEFAULT_FABRIC_CONFIG.memory.maxCacheCleanupFiles ?? 100_000,\n 1,\n 1_000_000,\n ),\n regexMaxPatternBytes: boundedInteger(\n memory.regexMaxPatternBytes,\n DEFAULT_FABRIC_CONFIG.memory.regexMaxPatternBytes ?? 1_024,\n 1,\n 64 * 1024,\n ),\n regexMaxHaystackTerms: boundedInteger(\n memory.regexMaxHaystackTerms,\n DEFAULT_FABRIC_CONFIG.memory.regexMaxHaystackTerms ?? 20_000,\n 1,\n 1_000_000,\n ),\n regexMaxHaystackBytes: boundedInteger(\n memory.regexMaxHaystackBytes,\n DEFAULT_FABRIC_CONFIG.memory.regexMaxHaystackBytes ?? 2 * 1024 * 1024,\n 1_024,\n 128 * 1024 * 1024,\n ),\n regexTimeoutMs: boundedInteger(\n memory.regexTimeoutMs,\n DEFAULT_FABRIC_CONFIG.memory.regexTimeoutMs ?? 250,\n 10,\n 10_000,\n ),\n },\n schema: {\n mode: schemaMode,\n certificateTtlMs: boundedInteger(\n schema.certificateTtlMs,\n DEFAULT_FABRIC_CONFIG.schema.certificateTtlMs,\n 1_000,\n 10 * 60_000,\n ),\n maxFiles: boundedInteger(\n schema.maxFiles,\n DEFAULT_FABRIC_CONFIG.schema.maxFiles,\n 1,\n 1_000,\n ),\n maxBytes: boundedInteger(\n schema.maxBytes,\n DEFAULT_FABRIC_CONFIG.schema.maxBytes,\n 1_024,\n 100 * 1024 * 1024,\n ),\n trustedCommands,\n },\n speculation: {\n enabled: booleanValue(\n speculation.enabled,\n DEFAULT_FABRIC_CONFIG.speculation.enabled,\n ),\n maxConcurrent: boundedInteger(\n speculation.maxConcurrent,\n DEFAULT_FABRIC_CONFIG.speculation.maxConcurrent,\n 1,\n 32,\n ),\n maxEntries: boundedInteger(\n speculation.maxEntries,\n DEFAULT_FABRIC_CONFIG.speculation.maxEntries,\n 1,\n 1_024,\n ),\n maxBufferBytes: boundedInteger(\n speculation.maxBufferBytes,\n DEFAULT_FABRIC_CONFIG.speculation.maxBufferBytes,\n 64 * 1024,\n 64 * 1024 * 1024,\n ),\n entryTtlMs: boundedInteger(\n speculation.entryTtlMs,\n DEFAULT_FABRIC_CONFIG.speculation.entryTtlMs,\n 5_000,\n 30 * 60_000,\n ),\n mcpAllowlist: [\n ...new Set(\n (Array.isArray(speculation.mcpAllowlist) ? speculation.mcpAllowlist : [])\n .filter(\n (entry): entry is string =>\n typeof entry === \"string\" && entry.trim().length > 0,\n )\n .map((entry) => entry.trim().slice(0, 256)),\n ),\n ].slice(0, 256),\n },\n codePreview: normalizeCodePreviewSettings(input.codePreview),\n };\n};\n\nexport const effectiveToolCaptureConfig = (\n config: Pick<FabricConfig, \"fullCodeMode\" | \"capture\"> & Partial<Pick<FabricConfig, \"schema\">>,\n): FabricToolCaptureConfig =>\n config.schema?.mode === \"enforce\"\n ? {\n ...config.capture,\n enabled: true,\n hideFromModel: true,\n keepVisible: [\"fabric_exec\"],\n risks: { ...config.capture.risks },\n }\n : config.fullCodeMode\n ? {\n ...config.capture,\n keepVisible: config.capture.keepVisible.filter(\n (name) => !PI_CORE_TOOL_NAME_SET.has(name),\n ),\n risks: { ...config.capture.risks },\n }\n : {\n ...config.capture,\n enabled: false,\n hideFromModel: false,\n keepVisible: [...config.capture.keepVisible],\n risks: { ...config.capture.risks },\n };\n\ninterface FabricConfigFilePlan {\n path: string;\n document: Record<string, unknown>;\n source: string;\n changed: boolean;\n}\n\nconst planConfigFile = (filePath: string): FabricConfigFilePlan | undefined => {\n const input = readJsonObjectFile(filePath);\n if (!input) return undefined;\n const migration = migrateFabricConfigDocument(input.document);\n return {\n path: filePath,\n document: migration.document,\n source: input.source,\n changed: migration.changed,\n };\n};\n\nconst writeJsonAtomic = (\n filePath: string,\n document: Record<string, unknown>,\n expectedSource?: string,\n): void => {\n const resolvedPath = fs.existsSync(filePath) ? fs.realpathSync(filePath) : filePath;\n const directory = path.dirname(resolvedPath);\n if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true });\n const mode = fs.existsSync(resolvedPath) ? fs.statSync(resolvedPath).mode & 0o777 : 0o600;\n const temporaryPath = path.join(\n directory,\n `.${path.basename(resolvedPath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,\n );\n let descriptor: number | undefined;\n try {\n descriptor = fs.openSync(temporaryPath, \"wx\", mode);\n fs.writeFileSync(descriptor, `${JSON.stringify(document, null, 2)}\\n`, \"utf8\");\n fs.fsyncSync(descriptor);\n fs.closeSync(descriptor);\n descriptor = undefined;\n if (expectedSource !== undefined) {\n let currentSource: string;\n try {\n currentSource = fs.readFileSync(resolvedPath, \"utf8\");\n } catch (error) {\n throw new Error(`Fabric configuration changed while updating ${filePath}`, { cause: error });\n }\n if (currentSource !== expectedSource) {\n throw new Error(`Fabric configuration changed while updating ${filePath}`);\n }\n }\n renameAtomic(temporaryPath, resolvedPath);\n try {\n const directoryDescriptor = fs.openSync(directory, \"r\");\n try {\n fs.fsyncSync(directoryDescriptor);\n } finally {\n fs.closeSync(directoryDescriptor);\n }\n } catch (error) {\n const code = error instanceof Error && \"code\" in error ? error.code : undefined;\n if (code !== \"EINVAL\" && code !== \"ENOTSUP\" && code !== \"EISDIR\" && code !== \"EPERM\") throw error;\n }\n } catch (error) {\n if (descriptor !== undefined) fs.closeSync(descriptor);\n fs.rmSync(temporaryPath, { force: true });\n throw error;\n }\n};\n\nconst resolveFabricConfig = (\n options: {\n cwd: string;\n agentDir: string;\n },\n includeProject: boolean,\n): FabricConfig => {\n let merged = structuredClone(DEFAULT_FABRIC_CONFIG) as unknown as Record<string, unknown>;\n const plans = [\n planConfigFile(path.join(options.agentDir, \"fabric.json\")),\n ...(includeProject\n ? [planConfigFile(path.join(options.cwd, \".pi\", \"fabric.json\"))]\n : []),\n ].filter((plan): plan is FabricConfigFilePlan => plan !== undefined);\n for (const plan of plans) {\n if (plan.changed) writeJsonAtomic(plan.path, plan.document, plan.source);\n merged = mergeObjects(merged, plan.document);\n }\n const inheritedFullCodeMode = process.env.PI_FABRIC_FULL_CODE_MODE;\n if (inheritedFullCodeMode === \"true\" || inheritedFullCodeMode === \"false\") {\n merged.fullCodeMode = inheritedFullCodeMode === \"true\";\n }\n return normalizeFabricConfig(merged);\n};\n\nexport const loadFabricConfigForScope = (\n options: {\n cwd: string;\n agentDir: string;\n projectTrusted: boolean;\n },\n scope: FabricConfigScope,\n): FabricConfig => {\n if (scope === \"project\" && !options.projectTrusted) {\n throw new Error(\"Cannot load project Fabric configuration for an untrusted project\");\n }\n return resolveFabricConfig(options, scope === \"project\");\n};\n\nexport const loadFabricConfig = (options: {\n cwd: string;\n agentDir: string;\n projectTrusted: boolean;\n}): FabricConfig => {\n const config = resolveFabricConfig(options, options.projectTrusted);\n if (config.compaction.engine === \"fabric\") {\n process.env.PI_FABRIC_COMPACTION_ENGINE = \"fabric\";\n } else {\n delete process.env.PI_FABRIC_COMPACTION_ENGINE;\n }\n return config;\n};\n\nexport const saveFabricConfig = (\n options: {\n cwd: string;\n agentDir: string;\n projectTrusted: boolean;\n scope?: FabricConfigScope;\n },\n partial: Record<string, unknown>,\n): { scope: FabricConfigScope; path: string } => {\n const scope = options.scope ?? (options.projectTrusted ? \"project\" : \"global\");\n if (scope === \"project\" && !options.projectTrusted) {\n throw new Error(\"Cannot save project Fabric configuration for an untrusted project\");\n }\n const targetPath = scope === \"project\"\n ? path.join(options.cwd, \".pi\", \"fabric.json\")\n : path.join(options.agentDir, \"fabric.json\");\n if (Object.hasOwn(partial, \"configVersion\") || Object.hasOwn(partial, \"subagents\")) {\n throw new Error(\"Fabric configuration updates must use the current schema\");\n }\n const input = readJsonObjectFile(targetPath);\n const existing = migrateFabricConfigDocument(input?.document ?? {}).document;\n const merged = mergeObjects(existing, partial) as Record<string, unknown>;\n // Never stamp down: preserve version markers written by newer builds.\n merged.configVersion = Math.max(\n typeof merged.configVersion === \"number\" ? merged.configVersion : 0,\n CURRENT_FABRIC_CONFIG_VERSION,\n );\n writeJsonAtomic(targetPath, merged, input?.source);\n return { scope, path: targetPath };\n};\n", "const PROVIDER_MODEL_RE = /^[^\\s/]+\\/[^\\s/]+$/;\n\n/** Minimal model view needed for resolution; satisfied by pi Model entries. */\nexport interface FabricModelCandidate {\n provider: string;\n id: string;\n name?: string;\n}\n\nexport type FabricModelResolution =\n | { kind: \"resolved\"; model: FabricModelCandidate; via?: string }\n | { kind: \"already-active\"; model: FabricModelCandidate }\n | { kind: \"ambiguous\"; query: string; candidates: FabricModelCandidate[] }\n | { kind: \"not-found\"; query: string; tried?: string[] };\n\n/** Markers reported in `via` when an inexact selector is fuzzy-resolved. */\nexport const FUZZY_RESOLUTION_MARKERS = [\"closest\", \"recent\", \"latest\"] as const;\n\nconst modelKey = (model: FabricModelCandidate): string => `${model.provider}/${model.id}`;\n\nconst sameModel = (\n left: FabricModelCandidate,\n right: FabricModelCandidate | undefined,\n): boolean =>\n right !== undefined &&\n left.provider.toLowerCase() === right.provider.toLowerCase() &&\n left.id.toLowerCase() === right.id.toLowerCase();\n\n/**\n * Normalize raw `models.aliases` config into alias name \u2192 ordered targets.\n * String targets degrade to one-element fallback chains. Entries whose name,\n * target list, or any `provider/model` target string is malformed are\n * dropped entirely, matching the lenient fallback style of the other config\n * normalizers (no partial alias survives with a silently missing target).\n */\nexport const normalizeModelAliases = (input: unknown): Record<string, string[]> => {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return {};\n const aliases: Record<string, string[]> = {};\n for (const [rawName, rawValue] of Object.entries(input as Record<string, unknown>)) {\n const name = rawName.trim();\n if (!name) continue;\n const values = typeof rawValue === \"string\" ? [rawValue] : rawValue;\n if (!Array.isArray(values) || values.length === 0) continue;\n const targets: string[] = [];\n let valid = true;\n for (const candidate of values) {\n if (typeof candidate !== \"string\") {\n valid = false;\n break;\n }\n const target = candidate.trim();\n if (!PROVIDER_MODEL_RE.test(target)) {\n valid = false;\n break;\n }\n if (!targets.includes(target)) targets.push(target);\n }\n if (valid && targets.length > 0) aliases[name] = targets;\n }\n return aliases;\n};\n\nconst FUZZY_MIN_QUERY_LENGTH = 4;\nconst FUZZY_LEVENSHTEIN_MIN_RATIO = 0.55;\n\n/**\n * Span covered when every character of `needle` appears in `haystack` in\n * order (first to last matched index), or Infinity when it does not. A tight\n * span keeps abbreviated selectors honest: \"gmni\" spans 6 chars in\n * \"gemini-2.5-pro\" but 10 in \"gpt-5-mini\", so only the former reads as the\n * same token with letters dropped.\n */\nconst subsequenceSpan = (needle: string, haystack: string): number => {\n let index = 0;\n let first = -1;\n let last = -1;\n for (let i = 0; i < haystack.length && index < needle.length; i += 1) {\n if (haystack[i] === needle[index]) {\n if (first === -1) first = i;\n last = i;\n index += 1;\n }\n }\n return index === needle.length ? last - first + 1 : Number.POSITIVE_INFINITY;\n};\n\n/** Normalized Levenshtein similarity in [0, 1]; 1 means identical. */\nconst levenshteinRatio = (left: string, right: string): number => {\n if (left === right) return 1;\n if (left.length === 0 || right.length === 0) return 0;\n let previous = Array.from({ length: right.length + 1 }, (_, column) => column);\n for (let i = 0; i < left.length; i += 1) {\n const current: number[] = [i + 1];\n for (let j = 0; j < right.length; j += 1) {\n current.push(Math.min(\n previous[j]! + 1,\n current[j]! + 1,\n previous[j]! + (left[i] === right[j] ? 0 : 1),\n ));\n }\n previous = current;\n }\n return 1 - previous[right.length]! / Math.max(left.length, right.length);\n};\n\n/**\n * Closeness score for an inexact selector against one candidate. Tiered so a\n * substring hit always outranks a subsequence hit, which always outranks a\n * typo-level Levenshtein resemblance; coverage bonuses reward selectors that\n * span most of the target id name. Zero means no resemblance at all.\n */\nconst closenessScore = (query: string, model: FabricModelCandidate): number => {\n const id = model.id.toLowerCase();\n const name = model.name?.toLowerCase();\n if (id.startsWith(query)) return 60 + (query.length / id.length) * 20;\n if (id.includes(query)) return 50 + (query.length / id.length) * 15;\n if (name?.startsWith(query) === true) return 45 + (query.length / name.length) * 15;\n if (name?.includes(query) === true) return 40 + (query.length / name.length) * 10;\n if (model.provider.toLowerCase().includes(query)) return 25;\n if (\n query.length >= 3 &&\n query[0] === id[0] &&\n subsequenceSpan(query, id) <= query.length + 2\n ) {\n return 18 + (query.length / id.length) * 6;\n }\n if (query.length >= FUZZY_MIN_QUERY_LENGTH) {\n const idRatio = levenshteinRatio(query, id);\n if (idRatio >= FUZZY_LEVENSHTEIN_MIN_RATIO) return 8 + idRatio * 10;\n if (name !== undefined) {\n const nameRatio = levenshteinRatio(query, name);\n if (nameRatio >= FUZZY_LEVENSHTEIN_MIN_RATIO) return 6 + nameRatio * 8;\n }\n }\n return 0;\n};\n\nexport type FabricModelUsage = Record<string, number>;\n\n/**\n * Pick the closest candidate for an inexact selector. Ranking is closeness\n * first; equal-closeness ties fall to the most recently used model (recency\n * timestamps such as pi-model-sort's extensions/pi-model-sort.json under the\n * agent dir, keyed by provider/id), then to the highest-sorting key, mirroring\n * pi's convention that the newest alias/versioned id sorts last.\n */\nconst pickClosestCandidate = (\n query: string,\n pool: readonly FabricModelCandidate[],\n lastUsed: FabricModelUsage | undefined,\n): { model: FabricModelCandidate; via: \"closest\" | \"recent\" | \"latest\" } | undefined => {\n const usage: FabricModelUsage = {};\n for (const [key, value] of Object.entries(lastUsed ?? {})) {\n usage[key.toLowerCase()] = value;\n }\n const recency = (model: FabricModelCandidate): number =>\n usage[`${model.provider}/${model.id}`.toLowerCase()] ?? 0;\n let best: FabricModelCandidate | undefined;\n let bestScore = 0;\n let tied = false;\n for (const model of pool) {\n const score = closenessScore(query, model);\n if (score <= 0) continue;\n if (best === undefined || score > bestScore) {\n best = model;\n bestScore = score;\n tied = false;\n continue;\n }\n if (score === bestScore) {\n tied = true;\n const bestRecent = recency(best);\n const nextRecent = recency(model);\n if (nextRecent > bestRecent || (nextRecent === bestRecent && modelKey(model) > modelKey(best))) {\n best = model;\n }\n }\n }\n if (best === undefined) return undefined;\n const runnersUp = pool.filter(\n (model) => model !== best && closenessScore(query, model) === bestScore,\n );\n const wonOnRecency = tied\n && runnersUp.some((model) => recency(model) !== recency(best));\n return {\n model: best,\n via: !tied ? \"closest\" : wonOnRecency ? \"recent\" : \"latest\",\n };\n};\n\n/**\n * Resolve a model selector against aliases and the available (authenticated)\n * registry. Order: alias lookup first so a configured name always wins, then\n * exact provider/id, exact id, then fuzzy selection. A lone partial match is\n * returned directly; broader candidate pools are ranked by closeness, with\n * equal-closeness ties falling to the most recently used model (when usage\n * timestamps are supplied, e.g. from pi-model-sort) and then to the\n * highest-sorting key, mirroring pi's newest-alias convention. Only a pool\n * with no resemblance at all stays not-found; `ambiguous` is retained for\n * defensive completeness but the ranker always produces a deterministic pick.\n */\nexport const resolveFabricModel = (\n query: string,\n options: {\n aliases: Record<string, string[]>;\n available: readonly FabricModelCandidate[];\n current?: FabricModelCandidate;\n provider?: string;\n lastUsed?: FabricModelUsage;\n },\n): FabricModelResolution => {\n const normalized = query.trim().toLowerCase();\n if (!normalized) return { kind: \"not-found\", query };\n const providerFilter = options.provider?.trim().toLowerCase();\n const available = providerFilter\n ? options.available.filter((model) => model.provider.toLowerCase() === providerFilter)\n : [...options.available];\n if (available.length === 0) return { kind: \"not-found\", query };\n\n const aliasKey = Object.keys(options.aliases).find(\n (key) => key.toLowerCase() === normalized,\n );\n const tried: string[] = [];\n if (aliasKey !== undefined) {\n const chain = options.aliases[aliasKey] ?? [];\n for (const target of chain) {\n tried.push(target);\n const separator = target.indexOf(\"/\");\n const provider = target.slice(0, separator);\n const id = target.slice(separator + 1);\n const match = available.find(\n (model) =>\n model.provider.toLowerCase() === provider.toLowerCase() &&\n model.id.toLowerCase() === id.toLowerCase(),\n );\n if (match) {\n return sameModel(match, options.current)\n ? { kind: \"already-active\", model: match }\n : { kind: \"resolved\", model: match, via: aliasKey };\n }\n }\n return { kind: \"not-found\", query, tried };\n }\n\n const exact = available.find((model) => modelKey(model).toLowerCase() === normalized)\n ?? available.find((model) => model.id.toLowerCase() === normalized);\n if (exact) {\n return sameModel(exact, options.current)\n ? { kind: \"already-active\", model: exact }\n : { kind: \"resolved\", model: exact };\n }\n\n const candidates = available.filter(\n (model) =>\n model.id.toLowerCase().includes(normalized) ||\n (model.name !== undefined && model.name.toLowerCase().includes(normalized)) ||\n model.provider.toLowerCase().includes(normalized),\n );\n if (candidates.length === 1) {\n const match = candidates[0];\n if (match === undefined) return { kind: \"not-found\", query };\n return sameModel(match, options.current)\n ? { kind: \"already-active\", model: match }\n : { kind: \"resolved\", model: match };\n }\n const pool = candidates.length > 1 ? candidates : available;\n const picked = pickClosestCandidate(normalized, pool, options.lastUsed);\n if (picked) {\n return sameModel(picked.model, options.current)\n ? { kind: \"already-active\", model: picked.model }\n : { kind: \"resolved\", model: picked.model, via: picked.via };\n }\n if (candidates.length > 1) return { kind: \"ambiguous\", query, candidates };\n return { kind: \"not-found\", query };\n};\n", "export const CURRENT_FABRIC_CONFIG_VERSION = 3;\n\nexport interface FabricConfigMigrationResult {\n document: Record<string, unknown>;\n fromVersion: number;\n toVersion: number;\n appliedVersions: number[];\n changed: boolean;\n // True when the document was written by a newer pi-fabric build. The document\n // is accepted as-is (newer builds only add semantics older builds can safely\n // ignore) and is never rewritten or version-stamped down.\n forwardCompatible: boolean;\n}\n\ninterface FabricConfigMigration {\n from: number;\n to: number;\n migrate(document: Readonly<Record<string, unknown>>): Record<string, unknown>;\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst mergeObjects = (\n base: Record<string, unknown>,\n override: Record<string, unknown>,\n): Record<string, unknown> => {\n const merged = { ...base };\n for (const [key, value] of Object.entries(override)) {\n const current = merged[key];\n merged[key] = isObject(current) && isObject(value) ? mergeObjects(current, value) : value;\n }\n return merged;\n};\n\nconst migrations: readonly FabricConfigMigration[] = [\n {\n from: 0,\n to: 1,\n migrate(document) {\n const migrated = { ...document };\n const legacy = migrated.subagents;\n const canonical = migrated.agents;\n if (legacy !== undefined) {\n if (canonical !== undefined && isObject(legacy) !== isObject(canonical)) {\n throw new Error(\n \"Fabric configuration cannot merge legacy subagents with a malformed agents section\",\n );\n }\n migrated.agents = isObject(legacy) && isObject(canonical)\n ? mergeObjects(legacy, canonical)\n : canonical ?? legacy;\n }\n delete migrated.subagents;\n return migrated;\n },\n },\n {\n from: 1,\n to: 2,\n migrate(document) {\n const migrated = { ...document };\n const ui = migrated.ui;\n if (isObject(ui) && Object.hasOwn(ui, \"showNestedToolCalls\")) {\n const renamed = { ...ui };\n if (!Object.hasOwn(renamed, \"showAgentToolPreview\")) {\n renamed.showAgentToolPreview = renamed.showNestedToolCalls;\n }\n delete renamed.showNestedToolCalls;\n migrated.ui = renamed;\n }\n return migrated;\n },\n },\n {\n from: 2,\n to: 3,\n migrate(document) {\n const migrated = { ...document };\n const ui = migrated.ui;\n if (isObject(ui) && Object.hasOwn(ui, \"nestedToolDebounceMs\")) {\n const renamed = { ...ui };\n if (!Object.hasOwn(renamed, \"updateDebounceMs\")) {\n renamed.updateDebounceMs = renamed.nestedToolDebounceMs;\n }\n delete renamed.nestedToolDebounceMs;\n migrated.ui = renamed;\n }\n return migrated;\n },\n },\n];\n\nconst configVersion = (document: Readonly<Record<string, unknown>>): number => {\n const value = document.configVersion;\n if (value === undefined) return 0;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n throw new Error(\"Fabric configuration configVersion must be a non-negative integer\");\n }\n return value;\n};\n\nexport const migrateFabricConfigDocument = (\n input: Readonly<Record<string, unknown>>,\n): FabricConfigMigrationResult => {\n const fromVersion = configVersion(input);\n if (fromVersion > CURRENT_FABRIC_CONFIG_VERSION) {\n // Written by a newer build: accept as-is instead of bricking the\n // extension. Legacy-shape checks (e.g. the removed subagents key) apply to\n // supported versions only \u2014 newer semantics are unknown here.\n return {\n document: structuredClone(input) as Record<string, unknown>,\n fromVersion,\n toVersion: fromVersion,\n appliedVersions: [],\n changed: false,\n forwardCompatible: true,\n };\n }\n let version = fromVersion;\n let document = structuredClone(input) as Record<string, unknown>;\n const appliedVersions: number[] = [];\n\n while (version < CURRENT_FABRIC_CONFIG_VERSION) {\n const migration = migrations.find((candidate) => candidate.from === version);\n if (!migration || migration.to !== version + 1) {\n throw new Error(`No Fabric configuration migration exists for version ${version}`);\n }\n document = migration.migrate(document);\n version = migration.to;\n document.configVersion = version;\n appliedVersions.push(version);\n }\n\n if (Object.hasOwn(document, \"subagents\")) {\n throw new Error(\"Current Fabric configuration contains removed key subagents\");\n }\n\n return {\n document,\n fromVersion,\n toVersion: version,\n appliedVersions,\n changed: appliedVersions.length > 0,\n forwardCompatible: false,\n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