@e4779/pi-fabric 0.105.0-fork.18 → 0.109.2-fork.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/README.md +3 -1
  2. package/dist/actors/global-registry.d.ts.map +1 -1
  3. package/dist/agents/manager.d.ts.map +1 -1
  4. package/dist/agents/result.d.ts.map +1 -1
  5. package/dist/agents/result.js +1 -1
  6. package/dist/agents/runner-registry.d.ts +1 -1
  7. package/dist/agents/runner-registry.d.ts.map +1 -1
  8. package/dist/agents.js +5 -5
  9. package/dist/chunks/{chunk-5MNLVHF5.js → chunk-3DUKKQHN.js} +28 -13
  10. package/dist/chunks/chunk-3DUKKQHN.js.map +7 -0
  11. package/dist/chunks/{chunk-GJVPP3NN.js → chunk-3SHUUBZJ.js} +4 -4
  12. package/dist/chunks/chunk-3SHUUBZJ.js.map +7 -0
  13. package/dist/chunks/{chunk-VON4TSO3.js → chunk-CZPQTISQ.js} +27 -2
  14. package/dist/chunks/chunk-CZPQTISQ.js.map +7 -0
  15. package/dist/chunks/{chunk-WLLXKS6I.js → chunk-DU6ZA44F.js} +4 -4
  16. package/dist/chunks/{chunk-QLFDPXK7.js → chunk-DV2JZSCI.js} +153 -27
  17. package/dist/chunks/chunk-DV2JZSCI.js.map +7 -0
  18. package/dist/chunks/{chunk-KQ6R5EWR.js → chunk-FRPNQZV2.js} +24 -22
  19. package/dist/chunks/chunk-FRPNQZV2.js.map +7 -0
  20. package/dist/chunks/{chunk-W7X4XEQU.js → chunk-GC2AUXG6.js} +2 -2
  21. package/dist/chunks/chunk-K6QXUGS5.js +30 -0
  22. package/dist/chunks/chunk-K6QXUGS5.js.map +7 -0
  23. package/dist/chunks/{chunk-VPRJOD4Y.js → chunk-LEDY5G2V.js} +2 -2
  24. package/dist/chunks/{chunk-OVBKQCYL.js → chunk-N2VKKA7O.js} +2 -2
  25. package/dist/chunks/{chunk-N5GUXC6F.js → chunk-P4KH4S4S.js} +2 -1
  26. package/dist/chunks/chunk-P4KH4S4S.js.map +7 -0
  27. package/dist/chunks/{chunk-TFFZVLR2.js → chunk-PF27MQY5.js} +55 -4
  28. package/dist/chunks/chunk-PF27MQY5.js.map +7 -0
  29. package/dist/chunks/{chunk-CGL7QP4A.js → chunk-PK4NIJEV.js} +10 -1
  30. package/dist/chunks/{chunk-CGL7QP4A.js.map → chunk-PK4NIJEV.js.map} +2 -2
  31. package/dist/chunks/{chunk-YRDCJZZW.js → chunk-RUO6L7RM.js} +1 -1
  32. package/dist/chunks/{chunk-YRDCJZZW.js.map → chunk-RUO6L7RM.js.map} +1 -1
  33. package/dist/chunks/{chunk-4RTHQGES.js → chunk-ST36EYHN.js} +4 -4
  34. package/dist/chunks/chunk-ST36EYHN.js.map +7 -0
  35. package/dist/chunks/{chunk-R5F6CHW2.js → chunk-UXEMIWYI.js} +12 -7
  36. package/dist/chunks/chunk-UXEMIWYI.js.map +7 -0
  37. package/dist/chunks/{chunk-SGFH5PYA.js → chunk-V2SKDVQX.js} +10 -9
  38. package/dist/chunks/chunk-V2SKDVQX.js.map +7 -0
  39. package/dist/chunks/{chunk-KYXZJNV6.js → chunk-VTK2FEH7.js} +3 -1
  40. package/dist/chunks/{chunk-KYXZJNV6.js.map → chunk-VTK2FEH7.js.map} +2 -2
  41. package/dist/chunks/{chunk-3QECYQGA.js → chunk-VYQV5JRT.js} +13 -1
  42. package/dist/chunks/chunk-VYQV5JRT.js.map +7 -0
  43. package/dist/chunks/{chunk-3KDUMDPZ.js → chunk-X3CHSIL2.js} +5 -5
  44. package/dist/chunks/{chunk-6VXPACGC.js → chunk-YJX27XBO.js} +100 -22
  45. package/dist/chunks/chunk-YJX27XBO.js.map +7 -0
  46. package/dist/components/configuration.js +2 -2
  47. package/dist/config.d.ts +16 -1
  48. package/dist/config.d.ts.map +1 -1
  49. package/dist/core/action-registry.d.ts +1 -1
  50. package/dist/core/action-registry.d.ts.map +1 -1
  51. package/dist/core/action-registry.js +2 -2
  52. package/dist/core/media-sanitize.d.ts.map +1 -1
  53. package/dist/core/native-tool-names.d.ts +9 -0
  54. package/dist/core/native-tool-names.d.ts.map +1 -0
  55. package/dist/core/native-tool-result.d.ts +11 -0
  56. package/dist/core/native-tool-result.d.ts.map +1 -0
  57. package/dist/core/system-guidance.d.ts +3 -3
  58. package/dist/core/system-guidance.d.ts.map +1 -1
  59. package/dist/durable/agent.d.ts +77 -0
  60. package/dist/durable/agent.d.ts.map +1 -0
  61. package/dist/durable/session.d.ts +19 -0
  62. package/dist/durable/session.d.ts.map +1 -0
  63. package/dist/durable/storage.d.ts +7 -0
  64. package/dist/durable/storage.d.ts.map +1 -0
  65. package/dist/durable/worker-host.d.ts +13 -0
  66. package/dist/durable/worker-host.d.ts.map +1 -0
  67. package/dist/durable/worker-host.js +1149 -0
  68. package/dist/durable/worker-host.js.map +7 -0
  69. package/dist/durable/worker-options.d.ts +17 -0
  70. package/dist/durable/worker-options.d.ts.map +1 -0
  71. package/dist/durable/worker.d.ts +3 -0
  72. package/dist/durable/worker.d.ts.map +1 -0
  73. package/dist/durable/worker.js +110 -0
  74. package/dist/durable/worker.js.map +7 -0
  75. package/dist/durable-controls.d.ts +27 -0
  76. package/dist/durable-controls.d.ts.map +1 -0
  77. package/dist/durable-input.d.ts +13 -0
  78. package/dist/durable-input.d.ts.map +1 -0
  79. package/dist/durable.d.ts +6 -0
  80. package/dist/durable.d.ts.map +1 -1
  81. package/dist/durable.js +194 -24
  82. package/dist/durable.js.map +4 -4
  83. package/dist/execution-service.d.ts +4 -0
  84. package/dist/execution-service.d.ts.map +1 -1
  85. package/dist/extension-bootstrap.js +5 -5
  86. package/dist/extension.d.ts.map +1 -1
  87. package/dist/fabric-exec-arguments.d.ts.map +1 -1
  88. package/dist/fabric-exec-tool.d.ts.map +1 -1
  89. package/dist/fabric-runtime-state.d.ts.map +1 -1
  90. package/dist/fabric-runtime-state.js +633 -291
  91. package/dist/fabric-runtime-state.js.map +4 -4
  92. package/dist/index.js +5 -5
  93. package/dist/jev/observation.js +2 -2
  94. package/dist/jev.js +3 -3
  95. package/dist/mcp.js +1 -1
  96. package/dist/memory/extractive-history.d.ts +29 -0
  97. package/dist/memory/extractive-history.d.ts.map +1 -0
  98. package/dist/memory/extractive-history.js +340 -0
  99. package/dist/memory/extractive-history.js.map +7 -0
  100. package/dist/memory/extractive-index.d.ts +46 -0
  101. package/dist/memory/extractive-index.d.ts.map +1 -0
  102. package/dist/native-codemode.d.ts +34 -0
  103. package/dist/native-codemode.d.ts.map +1 -0
  104. package/dist/native-discovery.d.ts +16 -0
  105. package/dist/native-discovery.d.ts.map +1 -0
  106. package/dist/native-discovery.js +19 -0
  107. package/dist/native-discovery.js.map +7 -0
  108. package/dist/native-image-artifacts.d.ts +4 -0
  109. package/dist/native-image-artifacts.d.ts.map +1 -0
  110. package/dist/native-image-artifacts.js +18 -0
  111. package/dist/native-image-artifacts.js.map +7 -0
  112. package/dist/native-tool-catalog.d.ts +21 -0
  113. package/dist/native-tool-catalog.d.ts.map +1 -0
  114. package/dist/native-tool-catalog.js +71 -0
  115. package/dist/native-tool-catalog.js.map +7 -0
  116. package/dist/protocol.d.ts +2 -0
  117. package/dist/protocol.d.ts.map +1 -1
  118. package/dist/protocol.js +1 -1
  119. package/dist/providers/agents-provider.d.ts.map +1 -1
  120. package/dist/providers/captured-tools-provider.d.ts +1 -1
  121. package/dist/providers/captured-tools-provider.d.ts.map +1 -1
  122. package/dist/providers/jev-provider.js +3 -3
  123. package/dist/providers/mcp-provider.d.ts +1 -1
  124. package/dist/providers/mcp-provider.d.ts.map +1 -1
  125. package/dist/providers/pi-native-mcp.d.ts.map +1 -1
  126. package/dist/providers/pi-tools-provider.d.ts.map +1 -1
  127. package/dist/residency/host.js +7 -7
  128. package/dist/residency/pi-entry.js +7 -7
  129. package/dist/runners.js +1 -1
  130. package/dist/runtime/core-override-guest-types.js +2 -2
  131. package/dist/runtime/dynamic-guest-types.d.ts +2 -0
  132. package/dist/runtime/dynamic-guest-types.d.ts.map +1 -1
  133. package/dist/runtime/dynamic-guest-types.js +5 -3
  134. package/dist/runtime/guest-types.d.ts +1 -1
  135. package/dist/runtime/guest-types.d.ts.map +1 -1
  136. package/dist/runtime/guest-types.js +1 -1
  137. package/dist/runtime/kernel.d.ts +5 -0
  138. package/dist/runtime/kernel.d.ts.map +1 -1
  139. package/dist/runtime/monty-runtime.js +1 -1
  140. package/dist/runtime/native-codemode-guest.d.ts +2 -0
  141. package/dist/runtime/native-codemode-guest.d.ts.map +1 -0
  142. package/dist/runtime/native-codemode-types.d.ts +2 -0
  143. package/dist/runtime/native-codemode-types.d.ts.map +1 -0
  144. package/dist/runtime/node-process-child-source.d.ts.map +1 -1
  145. package/dist/runtime/node-process-runtime.d.ts.map +1 -1
  146. package/dist/runtime/node-process-runtime.js +3 -3
  147. package/dist/runtime/quickjs-runtime.d.ts +1 -1
  148. package/dist/runtime/quickjs-runtime.d.ts.map +1 -1
  149. package/dist/runtime/quickjs-runtime.js +3 -2
  150. package/dist/runtime/type-checker.d.ts +2 -0
  151. package/dist/runtime/type-checker.d.ts.map +1 -1
  152. package/dist/runtime/type-checker.js +5 -3
  153. package/dist/runtime/typescript-kernel.d.ts +1 -1
  154. package/dist/runtime/typescript-kernel.d.ts.map +1 -1
  155. package/dist/runtime/typescript-kernel.js +13 -11
  156. package/dist/runtime/typescript-kernel.js.map +2 -2
  157. package/dist/runtime-state-speculation.d.ts +4 -1
  158. package/dist/runtime-state-speculation.d.ts.map +1 -1
  159. package/dist/speculation/python-scanner.js +1 -1
  160. package/dist/speculation/python-scanner.js.map +2 -2
  161. package/dist/speculation/scanner.d.ts +2 -0
  162. package/dist/speculation/scanner.d.ts.map +1 -1
  163. package/dist/speculation/scanner.js +18 -4
  164. package/dist/speculation/scanner.js.map +2 -2
  165. package/dist/speculation/types.d.ts +1 -0
  166. package/dist/speculation/types.d.ts.map +1 -1
  167. package/dist/type-error-guidance.js +1 -1
  168. package/dist/ui/border-status-editor.d.ts +3 -0
  169. package/dist/ui/border-status-editor.d.ts.map +1 -1
  170. package/dist/ui/controller.d.ts.map +1 -1
  171. package/dist/ui/conversation.d.ts +1 -0
  172. package/dist/ui/conversation.d.ts.map +1 -1
  173. package/dist/ui/conversation.js +28 -5
  174. package/dist/ui/conversation.js.map +2 -2
  175. package/dist/ui/dashboard.d.ts +2 -0
  176. package/dist/ui/dashboard.d.ts.map +1 -1
  177. package/dist/ui/dashboard.js +20 -7
  178. package/dist/ui/dashboard.js.map +2 -2
  179. package/dist/ui/settings-section-context.d.ts +2 -0
  180. package/dist/ui/settings-section-context.d.ts.map +1 -1
  181. package/dist/ui/settings-sections-execution.d.ts.map +1 -1
  182. package/dist/ui/settings-sections-lifecycle.d.ts +1 -0
  183. package/dist/ui/settings-sections-lifecycle.d.ts.map +1 -1
  184. package/dist/ui/settings-sections.d.ts +2 -0
  185. package/dist/ui/settings-sections.d.ts.map +1 -1
  186. package/dist/ui/settings-values.d.ts +4 -1
  187. package/dist/ui/settings-values.d.ts.map +1 -1
  188. package/dist/ui/settings.d.ts.map +1 -1
  189. package/dist/ui/settings.js +61 -2
  190. package/dist/ui/settings.js.map +2 -2
  191. package/dist/worker/model-control.d.ts.map +1 -1
  192. package/dist/worker/model-control.js.map +2 -2
  193. package/dist/worker/options.d.ts.map +1 -1
  194. package/dist/worker/options.js +4 -3
  195. package/dist/worker/options.js.map +2 -2
  196. package/dist/worker/result.js +12 -0
  197. package/dist/worker/result.js.map +2 -2
  198. package/dist/worker.js +95 -8
  199. package/dist/worker.js.map +2 -2
  200. package/docs/agents.md +5 -5
  201. package/docs/codemode-parity.md +97 -0
  202. package/docs/configuration.md +31 -2
  203. package/docs/durable-pi.md +166 -38
  204. package/docs/extractive-history.md +171 -0
  205. package/docs/interface.md +1 -1
  206. package/docs/speculation.md +12 -3
  207. package/package.json +7 -16
  208. package/skillsets/typescript/fabric-exec/SKILL.md +4 -4
  209. package/dist/chunks/chunk-3QECYQGA.js.map +0 -7
  210. package/dist/chunks/chunk-4RTHQGES.js.map +0 -7
  211. package/dist/chunks/chunk-5MNLVHF5.js.map +0 -7
  212. package/dist/chunks/chunk-6VXPACGC.js.map +0 -7
  213. package/dist/chunks/chunk-GJVPP3NN.js.map +0 -7
  214. package/dist/chunks/chunk-KQ6R5EWR.js.map +0 -7
  215. package/dist/chunks/chunk-N5GUXC6F.js.map +0 -7
  216. package/dist/chunks/chunk-QLFDPXK7.js.map +0 -7
  217. package/dist/chunks/chunk-R5F6CHW2.js.map +0 -7
  218. package/dist/chunks/chunk-SGFH5PYA.js.map +0 -7
  219. package/dist/chunks/chunk-TFFZVLR2.js.map +0 -7
  220. package/dist/chunks/chunk-VON4TSO3.js.map +0 -7
  221. /package/dist/chunks/{chunk-WLLXKS6I.js.map → chunk-DU6ZA44F.js.map} +0 -0
  222. /package/dist/chunks/{chunk-W7X4XEQU.js.map → chunk-GC2AUXG6.js.map} +0 -0
  223. /package/dist/chunks/{chunk-VPRJOD4Y.js.map → chunk-LEDY5G2V.js.map} +0 -0
  224. /package/dist/chunks/{chunk-OVBKQCYL.js.map → chunk-N2VKKA7O.js.map} +0 -0
  225. /package/dist/chunks/{chunk-3KDUMDPZ.js.map → chunk-X3CHSIL2.js.map} +0 -0
@@ -62,7 +62,7 @@ ActionRegistry.speculate() src/core/action-registry.ts
62
62
  │ resolve → gate → prepareArguments → validate → provider.invoke
63
63
  ▼
64
64
  FabricSpeculationStore src/speculation/store.ts
65
- │ keyed by (parentToolCallId, ref, stableJsonHash(preparedArgs));
65
+ │ keyed by (parentToolCallId, ref, stableJsonHash(preparedArgs), bindingToken);
66
66
  │ per-entry AbortController, freshness checker, side-channel replay sink
67
67
  ▼
68
68
  ActionRegistry.invoke() serve-or-reexecute at the real call site
@@ -74,7 +74,7 @@ ActionRegistry.invoke() serve-or-reexecute at the real call site
74
74
  refs that are `risk: "read"` with `effect.kind: "none"`, never prompt for
75
75
  approval, and cost nothing when wasted (`pi.read`/`grep`/`find`/`ls`,
76
76
  `memory.recall`/`expand`/`sessions`, `state.get`/`history`/`complexity`,
77
- `schema.status`, `compact.status`, `thinking.status`, `decisions.list`,
77
+ `mesh.scheduled`, `schema.status`, `compact.status`/`pressure`, `thinking.status`, `decisions.list`,
78
78
  `programs.list`/`get`, `components.list`/`status`/`graph`).
79
79
  The gate re-runs against the resolved descriptor at launch, so a provider
80
80
  or config change that reclassifies a ref closes speculation off.
@@ -114,6 +114,12 @@ Observable differences show up only in observability surfaces: audits record
114
114
  the speculative invoke (`attachMedia`, `updateArguments`, `attachPreview`) are
115
115
  replayed into the real audit.
116
116
 
117
+ ## Native codemode aliases
118
+
119
+ Both `executor.codemodeProfile` values support literal native reads through `tools` and `nativeTools`. The scanner resolves core aliases and known Pi MCP registration identifiers to their canonical Fabric refs before eligibility checks. Unknown or ambiguous aliases skip speculation; the actual call still uses normal dispatch. Native facade aliasing/mutation conservatively taints that root.
120
+
121
+ The binding token includes the result projection (`native` versus Fabric), alongside provider generation, descriptor, capability view and scope. Identical arguments can therefore warm both views without crossing their result or side-channel contracts. Native reads repeat the same live policy gates at launch and serve; model calls and writes do not become eligible through another spelling. Profile changes reset the cache and streaming state, like kernel/policy changes.
122
+
117
123
  ## Entropy compile interplay
118
124
 
119
125
  The compiled entropy surface participates at both ends of the pipeline. On
@@ -134,7 +140,10 @@ tool through config: `speculation.mcpAllowlist: ["exa.*", "github.get_file"]`
134
140
  (matched against the ref after the `mcp.` prefix). Cached MCP tool
135
141
  annotations, when the runtime surfaces them, override the allowlist in one
136
142
  direction only: `destructiveHint: true` or `readOnlyHint: false` refuses even
137
- an allowlisted tool. Networked results carry no freshness guarantee. The
143
+ an allowlisted tool. The live allowlist and policy gate are checked at both
144
+ launch and replay; removing an entry cannot serve an already-warmed result.
145
+ MCP descriptors keep their conservative network/effect classification rather
146
+ than being relabeled as local reads. Networked results carry no freshness guarantee. The
138
147
  epoch still covers in-program effects, yet the world can change behind a
139
148
  read; keep the allowlist to stable, idempotent reads.
140
149
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@e4779/pi-fabric",
3
- "version": "0.105.0-fork.18",
3
+ "version": "0.109.2-fork.23",
4
4
  "description": "A programmable tool and agent runtime for Pi",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -75,7 +75,7 @@
75
75
  "test:jev:dist": "node scripts/smoke-jev.mjs",
76
76
  "test:changed": "node scripts/test-affected.mjs",
77
77
  "test:affected": "node scripts/test-affected.mjs --base $PI_TEST_BASE",
78
- "test:smoke": "vitest run tests/optional-preview-startup.test.ts tests/script-runtime.test.ts tests/pi-binary.test.ts tests/host-compatibility.test.ts tests/output-budget.test.ts tests/actor-mesh-monitor.test.ts tests/handoff.test.ts tests/config-migrations.test.ts tests/monty-payload-preflight.test.ts tests/bundled-binary-spawn.test.ts tests/worker-installation.test.ts tests/conversation-native-reader-suspension.test.ts",
78
+ "test:smoke": "vitest run tests/optional-preview-startup.test.ts tests/script-runtime.test.ts tests/pi-binary.test.ts tests/host-compatibility.test.ts tests/output-budget.test.ts tests/actor-mesh-monitor.test.ts tests/handoff.test.ts tests/config-migrations.test.ts tests/monty-payload-preflight.test.ts tests/bundled-binary-spawn.test.ts tests/worker-installation.test.ts tests/durable-worker-installation.test.ts tests/conversation-native-reader-suspension.test.ts",
79
79
  "test:related": "vitest related --run",
80
80
  "check:fast": "bun run typecheck && bun run test:changed",
81
81
  "certify:context": "bun run build && node scripts/certify-context.mjs",
@@ -133,6 +133,8 @@
133
133
  "image": "https://raw.githubusercontent.com/fabric-runtime/pi-fabric/main/media/banner.svg"
134
134
  },
135
135
  "dependencies": {
136
+ "@earendil-works/chord": "1.0.0",
137
+ "@earendil-works/pi-durable": "1.0.0",
136
138
  "@jitl/quickjs-singlefile-mjs-release-sync": "^0.32.0",
137
139
  "@lezer/common": "^1.5.2",
138
140
  "@lezer/python": "^1.1.19",
@@ -142,33 +144,22 @@
142
144
  "cross-spawn": "^7.0.6",
143
145
  "diff": "^9.0.0",
144
146
  "mcporter": "^0.12.3",
147
+ "pi-fabric-worker-sdk": "npm:@earendil-works/pi-coding-agent@1.0.0",
145
148
  "quickjs-emscripten-core": "^0.32.0",
146
149
  "shiki": "4.4.3",
147
150
  "typescript": "^6.0.3",
148
151
  "yaml": "^2.9.0"
149
152
  },
150
153
  "peerDependencies": {
151
- "@earendil-works/chord": "1.0.0",
152
- "@earendil-works/pi-durable": "1.0.0",
153
- "@earendil-works/pi-ai": "*",
154
154
  "@earendil-works/pi-agent-core": "*",
155
+ "@earendil-works/pi-ai": "*",
155
156
  "@earendil-works/pi-coding-agent": "*",
156
157
  "@earendil-works/pi-tui": "*",
157
158
  "typebox": "*"
158
159
  },
159
- "peerDependenciesMeta": {
160
- "@earendil-works/chord": {
161
- "optional": true
162
- },
163
- "@earendil-works/pi-durable": {
164
- "optional": true
165
- }
166
- },
167
160
  "devDependencies": {
168
- "@earendil-works/chord": "1.0.0",
169
- "@earendil-works/pi-durable": "1.0.0",
170
- "@earendil-works/pi-ai": "1.0.0",
171
161
  "@earendil-works/pi-agent-core": "1.0.0",
162
+ "@earendil-works/pi-ai": "1.0.0",
172
163
  "@earendil-works/pi-coding-agent": "1.0.0",
173
164
  "@earendil-works/pi-tui": "1.0.0",
174
165
  "typebox": "1.3.27",
@@ -9,9 +9,9 @@ description: >-
9
9
 
10
10
  # fabric_exec — core reference
11
11
 
12
- One program in the **TypeScript kernel**. Write TypeScript only in `code`. There is **no per-call kernel selector**, language autodetection, or fallback. Only the `return` value reaches the model; `print()` goes to activity logs. `π` is payload data, not a tool.
12
+ One program in the **TypeScript kernel**. Write TypeScript only in `code`. There is **no per-call kernel selector**, language autodetection, or fallback. Returned values and explicitly emitted `print()`/`console` output reach the model; intermediate values stay in the sandbox. `π` is payload data, not a tool.
13
13
 
14
- QuickJS is isolated by default and receives static type checking; native Node/Bun is an explicit trusted-code escape hatch. Do not switch interpreters through shell commands to perform Fabric orchestration. Only the returned value reaches the model; logs go to activity output.
14
+ QuickJS is isolated by default and receives static type checking; native Node/Bun is an explicit trusted-code escape hatch. Do not switch interpreters through shell commands to perform Fabric orchestration. Prefer one compact return value. Explicit log output is also included in the bounded tool result, so do not print raw intermediate payloads.
15
15
 
16
16
  ## `pi` core tools (full code mode only)
17
17
  `pi.<tool>(arg)` — single arg: bare string (primary field) or options object, or a two-arg `(primary, options)` merge for the string-primary tools (`read`/`bash`/`powershell`/`ls`/`grep`/`find`): `pi.read('index.ts', { limit: 120 })` becomes `{ path: 'index.ts', limit: 120 }`, the positional string winning the primary field on conflict; a non-object second arg on those is still a type error. Positional tuple calls are accepted for `grep`/`find` (`pattern, path, limit`), `write` (`path, content`), and `edit` (`path, oldText, newText`).
@@ -144,7 +144,7 @@ Stable-provider arguments normalize near-miss spellings the way `pi.*` does: kno
144
144
  The guest TypeScript declarations contain the complete argument and return contracts. For a discovered or dynamic action, use `tools.describe({ref})`; inspect `outputSchema` when supplied, otherwise treat the result as `unknown`.
145
145
 
146
146
  ## `tools` — discovery & generic calls
147
- Refs are namespaced (`pi.grep`, `extensions.<tool>`, `mcp.<server>.<tool>`, `schema.<action>`, `components.<action>`); bare names are rejected. `tools.providers()`→`[{name,description}]` · `tools.catalog({provider?,limit?})`→current provider/action head tree (navigation metadata, not session evidence) · `tools.search({query,limit?,searchMode?})`→`FabricAction[]` or, with `searchMode:"semantic"` (opt-in in /fabric settings → MCP), `{kind:"pi-fabric.action-search",actions,backend}` · `tools.describe({ref})`→full `FabricAction` (read `inputSchema` first) · `tools.call({ref,args?})` · `tools.list({provider?,namespace?,query?,limit?})` · `tools.models()`→Pi `[{provider,id,name,key}]`; `agents.models({runner:"claude"})`→Claude Code runtime models with canonical `claude/<value>` keys. Use `tools.call()` for refs discovered or computed at runtime, or names that cannot use property access—not as the default for known actions. Calling a core-tool name on `tools` (e.g. `tools.read(...)`) throws with a hint to use `pi.read(...)`.
147
+ Refs are namespaced (`pi.grep`, `extensions.<tool>`, `mcp.<server>.<tool>`, `schema.<action>`, `components.<action>`); bare names are rejected. `tools.providers()`→`[{name,description}]` · `tools.catalog({provider?,limit?})`→current provider/action head tree (navigation metadata, not session evidence) · `tools.search({query,limit?,searchMode?})`→`FabricAction[]` or, with `searchMode:"semantic"` (opt-in in /fabric settings → MCP), `{kind:"pi-fabric.action-search",actions,backend}` · `tools.describe({ref})`→full `FabricAction` (read `inputSchema` first) · `tools.call({ref,args?})` · `tools.list({provider?,namespace?,query?,limit?})` · `tools.models()`→Pi `[{provider,id,name,key}]`; `agents.models({runner:"claude"})`→Claude Code runtime models with canonical `claude/<value>` keys. Use `tools.call()` for refs discovered or computed at runtime, or names that cannot use property access—not as the default for known actions. In the default additive profile, nonconflicting `tools.<name>` members and `nativeTools.<name>` call native Pi tools. Native results differ from Fabric: schema-backed structured output (including structured errors), native bash `exit_code` without nonzero rejection, text for unstructured tools. `pi.*`, `mcp.*`, and `extensions.*` keep the contracts above. `fabric.tools` always provides Fabric discovery. With `executor.codemodeProfile: "native"`, `tools` is exclusively native, including colliding names; write JavaScript async function bodies without TypeScript-only syntax. Native globals return callable identifiers (`ALL_TOOLS`, `searchTools`), strings (`describeTool`), and namespace tool-name arrays. In additive mode those globals keep Fabric shapes; use `nativeDiscovery` for native discovery in either profile. Native mode opts into Pi's `codemode-store` entries; additive mode keeps Fabric's separate store. See [codemode compatibility](../../../docs/codemode-parity.md).
148
148
 
149
149
  ## Error recovery: read, describe, retry
150
150
  Read the line-numbered error → `await tools.describe({ref})` for the schema → match `inputSchema`, rerun (don't guess). Common mistakes: bare ref (`grep`→`pi.grep`); a non-object second arg on `read`/`bash`/`powershell`/`ls` (`(primary, optionsObject)` already merges on the string-primary tools; positional tuples exist only for `grep`/`find`/`write`/`edit`).
@@ -166,7 +166,7 @@ For an explicit implementation handoff, `agents.handoff({ model, task?, when? })
166
166
 
167
167
  Persistent actors may declare `requires: ["provider.action", { ref: "provider.optional", optional: true }]`. Each run records and verifies a closed-world descriptor commitment; missing required refs fail the activation instead of widening authority.
168
168
 
169
- Agent requests and persistent actors accept `runner: "pi" | "claude"`. Pi is the default and is required for `recursive: true`, `rlm.query()`, and actors that must call Fabric or mesh APIs themselves. Claude invokes the official `claude -p` harness; it supports mapped Claude Code tools and host-managed persistent actors, but not recursive/direct Fabric APIs. Use `agents.models({ runner: "claude" })` for runtime-enumerated `claude/<value>` model keys.
169
+ Agent requests and persistent actors accept `runner: "pi-durable" | "pi" | "claude"`. `pi-durable` is the default isolated Pi host; explicit `pi` selects the legacy CLI. Both support `recursive: true`, `rlm.query()`, and actors that call Fabric or mesh APIs. Durable checkpoints do not restore arbitrary in-flight `fabric_exec` continuations. Claude invokes the official `claude -p` harness; it supports mapped Claude Code tools and host-managed persistent actors, but not recursive/direct Fabric APIs. Use `agents.models({ runner: "claude" })` for runtime-enumerated `claude/<value>` model keys.
170
170
 
171
171
  For Pi model selection, copy `key` from `agents.models({ runner: "pi" })`, reuse a successful handle's `model`, or use a configured alias. Never infer a model's version from an agent name or another model's version. Exact provider/model matches win; near-miss IDs resolve to the closest available model on that same provider. Check the returned handle's canonical `model`. Unknown providers and unrelated names still fail. For independent launches, await `Promise.allSettled` and inspect every result: an uncaught `Promise.all` rejection ends the program and can abort still-pending siblings. Preserve successful handles when retrying failures.
172
172
 
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/agents/result.ts"],
4
- "sourcesContent": ["import { Value } from \"typebox/value\";\n\nconst extractBalancedJson = (text: string, start: number): string | null => {\n const open = text[start];\n if (open !== \"{\" && open !== \"[\") return null;\n const close = open === \"{\" ? \"}\" : \"]\";\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let i = start; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === \"\\\\\") escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') inString = true;\n else if (ch === open) depth++;\n else if (ch === close) {\n depth--;\n if (depth === 0) return text.slice(start, i + 1);\n }\n }\n return null;\n};\n\nexport const parseStructuredValue = (text: string): unknown => {\n const trimmed = text.trim();\n try {\n return JSON.parse(trimmed);\n } catch {\n // Whole text is not JSON; try extraction below.\n }\n const fenced = trimmed.match(/```(?:json)?\\s*\\n([\\s\\S]*?)\\n```/i);\n if (fenced?.[1]) {\n try {\n return JSON.parse(fenced[1].trim());\n } catch {\n // Fenced block is not JSON; try balanced extraction below.\n }\n }\n const start = trimmed.search(/[{\\[]/);\n if (start >= 0) {\n const balanced = extractBalancedJson(trimmed, start);\n if (balanced) return JSON.parse(balanced);\n }\n return JSON.parse(trimmed);\n};\n\nexport function validateAgentResult<T extends { status: string; text: string; value?: unknown; error?: string }>(record: T, schema?: Record<string, unknown>): T {\n if (record.status !== \"completed\" || !schema) return record;\n try {\n const value = record.value ?? parseStructuredValue(record.text);\n if (!Value.Check(schema, value)) {\n const errors = [...Value.Errors(schema, value)].slice(0, 5).map((error) => error.message).join(\"; \");\n throw new Error(errors || \"value does not match schema\");\n }\n record.value = value;\n } catch (error) {\n record.status = \"failed\";\n const reason = error instanceof Error ? error.message : String(error);\n const output = record.text.trim();\n const snippet = output.slice(0, 200);\n record.error = `Structured agent output was invalid: ${reason}${snippet ? ` (output: ${snippet}${output.length > 200 ? \"\u2026\" : \"\"})` : \"\"}`;\n }\n return record;\n}\n"],
5
- "mappings": ";AAAA,SAAS,aAAa;AAEtB,IAAM,sBAAsB,CAAC,MAAc,UAAiC;AAC1E,QAAM,OAAO,KAAK,KAAK;AACvB,MAAI,SAAS,OAAO,SAAS,IAAK,QAAO;AACzC,QAAM,QAAQ,SAAS,MAAM,MAAM;AACnC,MAAI,QAAQ;AACZ,MAAI,WAAW;AACf,MAAI,UAAU;AACd,WAAS,IAAI,OAAO,IAAI,KAAK,QAAQ,KAAK;AACxC,UAAM,KAAK,KAAK,CAAC;AACjB,QAAI,UAAU;AACZ,UAAI,QAAS,WAAU;AAAA,eACd,OAAO,KAAM,WAAU;AAAA,eACvB,OAAO,IAAK,YAAW;AAChC;AAAA,IACF;AACA,QAAI,OAAO,IAAK,YAAW;AAA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;AACnC,WAAO,QAAQ,wCAAwC,MAAM,GAAG,UAAU,aAAa,OAAO,GAAG,OAAO,SAAS,MAAM,WAAM,EAAE,MAAM,EAAE;AAAA,EACzI;AACA,SAAO;AACT;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/agents/runner-registry.ts"],
4
- "sourcesContent": ["import type { ImageContent } from \"@earendil-works/pi-ai\";\nimport type { FabricScope } from \"../protocol.js\";\nimport type { FabricKernel } from \"../runtime/kernel.js\";\nimport type { FabricThinking } from \"../thinking.js\";\nimport type { FabricAgentLineage, FabricWritePolicy } from \"./child-env.js\";\nimport type { AgentChildQuestionResponse, AgentUsage } from \"./types.js\";\n\nexport type BuiltInFabricAgentRunner = \"pi\" | \"claude\" | \"veda\";\n\n/**\n * What a runner honors. Fabric refuses a request that needs an undeclared\n * capability before admission, budget, or worktree side effects.\n */\nexport interface FabricRunnerCapabilities {\n /** The child runs Fabric itself (`recursive: true`, fabric_exec in full code mode). */\n recursiveFabric: boolean;\n steer: boolean;\n followUp: boolean;\n /** Long-lived sessions for persistent actors. */\n persistentSessions: boolean;\n /** Explicit `kernel` choices. */\n kernels: boolean;\n /** Session seeds: trajectory handoff and `seed: \"branch\"`. */\n handoff: boolean;\n modelDiscovery: boolean;\n imageInput: boolean;\n compaction: boolean;\n /** Routed child dialogs (`agents.childQuestions: \"route\"`). */\n questions: boolean;\n /** Hosted runs that can park and resume (`sleep`/`wake`). */\n sleep: boolean;\n /** Write confinement (`readOnly`, `writableRoots`, `shell`). */\n writePolicy: boolean;\n}\n\nconst FABRIC_RUNNER_CAPABILITY_NAMES = [\n \"recursiveFabric\",\n \"steer\",\n \"followUp\",\n \"persistentSessions\",\n \"kernels\",\n \"handoff\",\n \"modelDiscovery\",\n \"imageInput\",\n \"compaction\",\n \"questions\",\n \"sleep\",\n \"writePolicy\",\n] as const satisfies readonly (keyof FabricRunnerCapabilities)[];\n\nexport interface FabricRunnerModelInfo {\n runner: string;\n provider: string;\n id: string;\n name: string;\n key: string;\n [key: string]: unknown;\n}\n\nexport interface FabricRunnerModelContext {\n cwd: string;\n refresh: boolean;\n}\n\n/** Launch facts shared by worker and hosted runners. All values are JSON. */\nexport interface FabricRunnerLaunchContext {\n /** Fabric run id. Hosted runners use it as the idempotency key. */\n id: string;\n name: string;\n task: string;\n cwd: string;\n runDirectory: string;\n residency: \"session\" | \"durable\";\n /** Run deadline in epoch milliseconds. */\n deadlineAt: number;\n depth: number;\n lineage: FabricAgentLineage;\n tools: readonly string[];\n model?: string;\n thinking?: FabricThinking;\n kernel?: FabricKernel;\n recursive?: boolean;\n /** Present only for runners declaring `imageInput`. */\n images?: readonly ImageContent[];\n schema?: Record<string, unknown>;\n systemPrompt?: string;\n /** Pi session file seeding the run; present only for runners declaring `handoff`. */\n sessionFile?: string;\n /** Effective confinement; present only for runners declaring `writePolicy`. */\n writePolicy?: FabricWritePolicy;\n actorId?: string;\n actorName?: string;\n /** Host-issued scope narrowed for this run (`pi-fabric/scope`); absent for unscoped sessions. */\n scope?: Readonly<FabricScope>;\n}\n\nexport interface FabricWorkerLaunchContext extends FabricRunnerLaunchContext {\n files: {\n taskFile: string;\n statusFile: string;\n lifecycleFile: string;\n logFile: string;\n steerFile: string;\n schemaFile?: string;\n imagesFile?: string;\n };\n /** Fabric's own Pi/Claude/Veda worker launch, for adapters that wrap it. */\n fabricWorker: { workerPath: string; workerArguments: readonly string[] };\n}\n\nexport interface FabricWorkerLaunch {\n workerPath: string;\n workerArguments: string[];\n}\n\nexport interface FabricHostedRunContext extends FabricRunnerLaunchContext {\n /** Equal to `id`; submitting twice with one key must start at most one run. */\n idempotencyKey: string;\n}\n\nexport type FabricHostedLiveness =\n | \"running\"\n | \"sleeping\"\n | \"settled\"\n | \"cancelled\"\n | \"interrupted\"\n | \"unknown\";\n\nexport type FabricRunStopReason = \"requested\" | \"timeout\" | \"shutdown\";\n\nexport interface FabricHostedProgress {\n turns?: number;\n toolCalls?: number;\n /** null clears the current tool. */\n currentTool?: string | null;\n /** Latest assistant text; Fabric keeps a bounded tail. */\n text?: string;\n}\n\n/** Events appended to the run's transcript log (`events.jsonl`). */\nexport type FabricTranscriptEvent =\n | {\n type: \"message_end\";\n message: {\n role: \"user\" | \"assistant\";\n content: string | Array<{ type: \"text\"; text: string }>;\n };\n }\n | { type: \"tool_execution_start\"; toolCallId?: string; toolName: string; args?: unknown }\n | {\n type: \"tool_execution_end\";\n toolCallId?: string;\n toolName: string;\n result?: unknown;\n isError?: boolean;\n }\n | { type: \"extension_error\"; error: string };\n\nexport interface FabricRunnerQuestion {\n method: \"select\" | \"confirm\" | \"input\" | \"editor\";\n title: string;\n message?: string;\n options?: string[];\n placeholder?: string;\n prefill?: string;\n timeoutMs?: number;\n}\n\nexport type FabricRunnerAnswer = AgentChildQuestionResponse;\n\nexport interface FabricHostedReporter {\n progress(update: FabricHostedProgress): void;\n /** Cumulative usage for the whole run; Fabric records the increase. */\n usage(total: AgentUsage): void;\n transcript(event: FabricTranscriptEvent): void;\n /** Routed like a Pi child dialog: direct UI when available, else a decision. */\n question(question: FabricRunnerQuestion): Promise<FabricRunnerAnswer>;\n finish(result: {\n status: \"completed\" | \"failed\" | \"stopped\";\n output: string;\n structured?: unknown;\n }): void;\n /** Fabric never retries; `retryable` is reported to the caller only. */\n fail(failure: { error: string; retryable?: boolean }): void;\n}\n\ninterface FabricRunnerBase {\n readonly id: string;\n readonly label: string;\n readonly capabilities: Readonly<FabricRunnerCapabilities>;\n /**\n * Absolute path of an ES module that registers this adapter when imported.\n * Required for `residency: \"durable\"`: the resident host imports it before\n * launching or re-attaching the run.\n */\n readonly residentModule?: string;\n models?(context: FabricRunnerModelContext): readonly FabricRunnerModelInfo[] | Promise<readonly FabricRunnerModelInfo[]>;\n defaultModel?(): string | undefined;\n normalizeModel?(model: string): string | Promise<string>;\n mapTools?(tools: readonly string[]): readonly string[] | Promise<readonly string[]>;\n}\n\n/** Fabric spawns `workerPath` under the selected transport; see \"Worker protocol\". */\nexport interface FabricWorkerRunner extends FabricRunnerBase {\n readonly kind: \"worker\";\n launch(context: FabricWorkerLaunchContext): FabricWorkerLaunch | Promise<FabricWorkerLaunch>;\n /** Called before the transport kills the process. */\n stop?(run: { id: string; runDirectory: string }): void | Promise<void>;\n}\n\n/** The adapter owns execution (for example a daemon); Fabric spawns no process. */\nexport interface FabricHostedRunner extends FabricRunnerBase {\n readonly kind: \"hosted\";\n /** Pure: returns a JSON locator (at most 8 KiB) that Fabric persists before `start`. */\n prepare(context: FabricHostedRunContext): unknown;\n start(locator: unknown, context: FabricHostedRunContext, reporter: FabricHostedReporter): void | Promise<void>;\n attach(locator: unknown, context: FabricHostedRunContext, reporter: FabricHostedReporter): void | Promise<void>;\n liveness(locator: unknown): FabricHostedLiveness | Promise<FabricHostedLiveness>;\n stop(locator: unknown, reason: FabricRunStopReason): { confirmed: boolean } | Promise<{ confirmed: boolean }>;\n abort?(locator: unknown, reason: FabricRunStopReason): void | Promise<void>;\n sleep?(locator: unknown): void | Promise<void>;\n wake?(locator: unknown): void | Promise<void>;\n steer?(locator: unknown, message: string, data?: unknown): void | Promise<void>;\n followUp?(locator: unknown, message: string, data?: unknown): void | Promise<void>;\n}\n\nexport type FabricRunnerAdapter = FabricWorkerRunner | FabricHostedRunner;\n\n/** Canonical built-in runner ids; src/config.ts inlines the same set. */\nexport const BUILT_IN_RUNNER_IDS: ReadonlySet<string> = new Set([\"pi\", \"claude\", \"veda\"]);\n/** Canonical runner id syntax; eager modules inline an identical copy. */\nexport const RUNNER_ID_PATTERN = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;\nconst MAX_RUNNER_ID_CHARS = 64;\nconst MAX_LABEL_CHARS = 80;\n\nexport const isFabricRunnerId = (value: unknown): value is string =>\n typeof value === \"string\" && value.length <= MAX_RUNNER_ID_CHARS && RUNNER_ID_PATTERN.test(value);\n\n// A globalThis singleton: a second copy of this module (another installed\n// pi-fabric, or a runner extension's own dependency) shares registrations.\nconst REGISTRY_SYMBOL = Symbol.for(\"pi-fabric.runnerRegistry.v1\");\nconst registryHost = globalThis as unknown as Record<symbol, Map<string, FabricRunnerAdapter> | undefined>;\nconst adapters: Map<string, FabricRunnerAdapter> =\n registryHost[REGISTRY_SYMBOL] ?? (registryHost[REGISTRY_SYMBOL] = new Map());\n\nconst fabricWorkerLaunch = (context: FabricWorkerLaunchContext): FabricWorkerLaunch => ({\n workerPath: context.fabricWorker.workerPath,\n workerArguments: [...context.fabricWorker.workerArguments],\n});\n\nconst builtIn = (\n id: BuiltInFabricAgentRunner,\n label: string,\n capabilities: FabricRunnerCapabilities,\n): FabricWorkerRunner => Object.freeze({\n kind: \"worker\" as const,\n id,\n label,\n capabilities: Object.freeze(capabilities),\n launch: fabricWorkerLaunch,\n});\n\n// Built-ins keep their model and tool handling in the manager; this table\n// carries only the capability facts checked uniformly for every runner.\nfor (const adapter of [\n builtIn(\"pi\", \"Pi\", {\n recursiveFabric: true,\n steer: true,\n followUp: true,\n persistentSessions: true,\n kernels: true,\n handoff: true,\n modelDiscovery: true,\n imageInput: true,\n compaction: true,\n questions: true,\n sleep: false,\n writePolicy: true,\n }),\n builtIn(\"claude\", \"Claude\", {\n recursiveFabric: false,\n steer: true,\n followUp: true,\n persistentSessions: true,\n kernels: false,\n handoff: false,\n modelDiscovery: true,\n imageInput: true,\n compaction: false,\n questions: false,\n sleep: false,\n writePolicy: false,\n }),\n builtIn(\"veda\", \"Veda\", {\n recursiveFabric: false,\n steer: false,\n followUp: false,\n persistentSessions: false,\n kernels: false,\n handoff: false,\n modelDiscovery: false,\n // Veda has always accepted (and dropped) image blocks; refusing them now\n // would change built-in behavior.\n imageInput: true,\n compaction: false,\n questions: false,\n sleep: false,\n writePolicy: false,\n }),\n]) {\n if (!adapters.has(adapter.id)) adapters.set(adapter.id, adapter);\n}\n\nconst requireFunction = (adapter: Record<string, unknown>, id: string, name: string): void => {\n if (typeof adapter[name] !== \"function\") {\n throw new Error(`Fabric runner ${id} must implement ${name}()`);\n }\n};\n\nconst optionalFunction = (adapter: Record<string, unknown>, id: string, name: string): void => {\n if (adapter[name] !== undefined && typeof adapter[name] !== \"function\") {\n throw new Error(`Fabric runner ${id}: ${name} must be a function`);\n }\n};\n\n// Hosted runs have no Fabric child process, so these cannot be honored.\nconst HOSTED_UNSUPPORTED: readonly (keyof FabricRunnerCapabilities)[] = [\n \"recursiveFabric\",\n \"kernels\",\n \"compaction\",\n \"persistentSessions\",\n];\n\nconst validateAdapter = (value: unknown): FabricRunnerAdapter => {\n if (!value || typeof value !== \"object\") throw new Error(\"Fabric runner adapter must be an object\");\n const adapter = value as Record<string, unknown>;\n const id = adapter.id;\n if (!isFabricRunnerId(id)) throw new Error(`Invalid Fabric runner id: ${JSON.stringify(id)}`);\n if (BUILT_IN_RUNNER_IDS.has(id)) throw new Error(`Cannot replace built-in Fabric runner: ${id}`);\n if (typeof adapter.label !== \"string\" || !adapter.label.trim() || adapter.label.length > MAX_LABEL_CHARS) {\n throw new Error(`Fabric runner ${id} needs a label of 1-${MAX_LABEL_CHARS} characters`);\n }\n if (adapter.kind !== \"worker\" && adapter.kind !== \"hosted\") {\n throw new Error(`Fabric runner ${id} must declare kind \"worker\" or \"hosted\"`);\n }\n const capabilities = adapter.capabilities as Record<string, unknown> | undefined;\n const missing = FABRIC_RUNNER_CAPABILITY_NAMES.filter(\n (name) => typeof capabilities?.[name] !== \"boolean\",\n );\n if (missing.length > 0) {\n throw new Error(`Fabric runner ${id} must declare boolean capabilities: ${missing.join(\", \")}`);\n }\n const caps = capabilities as unknown as FabricRunnerCapabilities;\n if (adapter.residentModule !== undefined) {\n if (\n typeof adapter.residentModule !== \"string\" ||\n !/^(?:\\/|[A-Za-z]:[\\\\/]|file:)/.test(adapter.residentModule) ||\n adapter.residentModule.length > 4_096\n ) {\n throw new Error(`Fabric runner ${id}: residentModule must be an absolute path or file: URL`);\n }\n }\n for (const name of [\"models\", \"defaultModel\", \"normalizeModel\", \"mapTools\"]) {\n optionalFunction(adapter, id, name);\n }\n if (caps.modelDiscovery) requireFunction(adapter, id, \"models\");\n if (adapter.kind === \"worker\") {\n requireFunction(adapter, id, \"launch\");\n optionalFunction(adapter, id, \"stop\");\n if (caps.sleep) throw new Error(`Fabric runner ${id}: sleep is available to hosted runners only`);\n } else {\n for (const name of [\"prepare\", \"start\", \"attach\", \"liveness\", \"stop\"]) requireFunction(adapter, id, name);\n for (const name of [\"abort\", \"sleep\", \"wake\", \"steer\", \"followUp\"]) optionalFunction(adapter, id, name);\n const unsupported = HOSTED_UNSUPPORTED.filter((name) => caps[name]);\n if (unsupported.length > 0) {\n throw new Error(`Fabric runner ${id}: hosted runners cannot declare ${unsupported.join(\", \")}`);\n }\n if (caps.steer) requireFunction(adapter, id, \"steer\");\n if (caps.followUp) requireFunction(adapter, id, \"followUp\");\n if (caps.sleep) {\n requireFunction(adapter, id, \"sleep\");\n requireFunction(adapter, id, \"wake\");\n }\n }\n return value as FabricRunnerAdapter;\n};\n\nconst bound = <T>(adapter: Record<string, unknown>, name: string): T | undefined =>\n typeof adapter[name] === \"function\"\n ? ((adapter[name] as (...args: unknown[]) => unknown).bind(adapter) as T)\n : undefined;\n\n/**\n * Register a runner for this process. Registration is process-local: a durable\n * run needs the adapter registered in the resident host too (`residentModule`).\n * Returns an unregister function.\n */\nexport const registerAgentRunner = (adapter: FabricRunnerAdapter): (() => void) => {\n const checked = validateAdapter(adapter);\n if (adapters.has(checked.id)) throw new Error(`Fabric runner already registered: ${checked.id}`);\n const source = checked as unknown as Record<string, unknown>;\n const methods = checked.kind === \"worker\"\n ? [\"launch\", \"stop\"]\n : [\"prepare\", \"start\", \"attach\", \"liveness\", \"stop\", \"abort\", \"sleep\", \"wake\", \"steer\", \"followUp\"];\n const registered = Object.freeze(Object.fromEntries([\n [\"kind\", checked.kind],\n [\"id\", checked.id],\n [\"label\", checked.label],\n [\"capabilities\", Object.freeze(Object.fromEntries(\n FABRIC_RUNNER_CAPABILITY_NAMES.map((name) => [name, checked.capabilities[name]]),\n ))],\n ...(checked.residentModule ? [[\"residentModule\", checked.residentModule]] : []),\n ...[\"models\", \"defaultModel\", \"normalizeModel\", \"mapTools\", ...methods]\n .map((name) => [name, bound(source, name)])\n .filter(([, method]) => method !== undefined),\n ])) as unknown as FabricRunnerAdapter;\n adapters.set(checked.id, registered);\n return () => {\n if (adapters.get(checked.id) === registered) adapters.delete(checked.id);\n };\n};\n\nexport const getAgentRunner = (id: string): FabricRunnerAdapter | undefined => adapters.get(id);\n\nexport const listAgentRunners = (): readonly FabricRunnerAdapter[] => [...adapters.values()];\n\nexport const requireAgentRunner = (id: unknown): FabricRunnerAdapter => {\n const adapter = typeof id === \"string\" ? adapters.get(id) : undefined;\n if (!adapter) {\n throw new Error(\n `Unsupported Fabric agent runner: ${JSON.stringify(id)}. Register it with registerAgentRunner() from pi-fabric/runners before use.`,\n );\n }\n return adapter;\n};\n"],
5
- "mappings": ";AAmCA,IAAM,iCAAiC;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAqLO,IAAM,sBAA2C,oBAAI,IAAI,CAAC,MAAM,UAAU,MAAM,CAAC;AAEjF,IAAM,oBAAoB;AACjC,IAAM,sBAAsB;AAC5B,IAAM,kBAAkB;AAEjB,IAAM,mBAAmB,CAAC,UAC/B,OAAO,UAAU,YAAY,MAAM,UAAU,uBAAuB,kBAAkB,KAAK,KAAK;AAIlG,IAAM,kBAAkB,OAAO,IAAI,6BAA6B;AAChE,IAAM,eAAe;AACrB,IAAM,WACJ,aAAa,eAAe,MAAM,aAAa,eAAe,IAAI,oBAAI,IAAI;AAE5E,IAAM,qBAAqB,CAAC,aAA4D;AAAA,EACtF,YAAY,QAAQ,aAAa;AAAA,EACjC,iBAAiB,CAAC,GAAG,QAAQ,aAAa,eAAe;AAC3D;AAEA,IAAM,UAAU,CACd,IACA,OACA,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ACF;AACA,SAAO;AACT;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/runtime/node-process-runtime.ts", "../../src/runtime/node-process-child-source.ts"],
4
- "sourcesContent": ["import { spawn, type ChildProcess } from \"node:child_process\";\nimport { runAbortable, settleWithin } from \"../async-settlement.js\";\nimport { piBashExitMetadata } from \"../core/pi-bash-error.js\";\nimport { isPiShellRef } from \"../core/pi-tools.js\";\nimport { HumanWaitDeadlinePause } from \"./deadline-pause.js\";\nimport { guestSetupSource } from \"./quickjs-runtime.js\";\nimport type { FabricHostCall, FabricSandboxOptions, FabricSandboxResult } from \"./kernel.js\";\nimport { NODE_PROCESS_CHILD_SOURCE } from \"./node-process-child-source.js\";\nimport { createGuestStackMap, remapGuestErrorText } from \"./guest-stack-map.js\";\nimport { transpileFabricCodeWithSourceMap } from \"./type-checker.js\";\nimport {\n resolveScriptRuntime,\n resolveScriptRuntimeSync,\n} from \"../agents/transports/process-utils.js\";\n\ninterface ChildCallMessage {\n type: \"call\";\n id: number;\n ref: string;\n args: Record<string, unknown>;\n}\n\ninterface ChildResultMessage {\n type: \"result\";\n result: FabricSandboxResult;\n}\n\ntype ChildMessage = ChildCallMessage | ChildResultMessage;\n\nconst HOST_TASK_SETTLE_GRACE_MS = 250;\n\nconst send = (child: ChildProcess, message: any): void => {\n if (!child.connected) return;\n child.send(message, () => undefined);\n};\n\nexport class NodeProcessRuntime {\n readonly #interpreter: \"node\" | \"bun\";\n\n constructor(interpreter: \"node\" | \"bun\" = \"node\") {\n this.#interpreter = interpreter;\n }\n\n async execute(\n code: string,\n hostCall: FabricHostCall,\n options: FabricSandboxOptions,\n ): Promise<FabricSandboxResult> {\n if (options.signal?.aborted) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"aborted\",\n error: \"Execution cancelled\",\n };\n }\n if (!Number.isSafeInteger(options.memoryLimitBytes) || options.memoryLimitBytes < 1) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error: \"Process memory limit must be a positive safe integer\",\n };\n }\n if (!Number.isFinite(options.timeoutMs) || options.timeoutMs < 1) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error: \"Process timeout must be positive\",\n };\n }\n\n // Bun evaluates --eval input as ESM and ignores V8 heap flags, so the\n // Bun child gets the guest source bare; Node needs the module + heap flags.\n // Bun resolution stays async: Pi may legitimately run under Node while bun\n // is only available on PATH, and the sync variant does no PATH lookup.\n const runtimeOptions = this.#interpreter === \"bun\" ? { requireBun: true } : { requireNode: true };\n const interpreterPath = this.#interpreter === \"bun\"\n ? await resolveScriptRuntime(runtimeOptions)\n : resolveScriptRuntimeSync(runtimeOptions);\n const child = spawn(\n interpreterPath,\n this.#interpreter === \"bun\"\n ? [\"--eval\", NODE_PROCESS_CHILD_SOURCE]\n : [\n // Guest import() through importModuleDynamically needs the vm\n // modules flag; Bun's vm ignores the option (see __fabricImport).\n \"--experimental-vm-modules\",\n `--max-old-space-size=${Math.max(16, Math.floor(options.memoryLimitBytes / (1024 * 1024)))}`,\n \"--input-type=module\",\n \"--eval\",\n NODE_PROCESS_CHILD_SOURCE,\n ],\n { stdio: [\"ignore\", \"ignore\", \"ignore\", \"ipc\"] },\n );\n // Bun resolution is async, so the signal may have aborted while resolving.\n if (options.signal?.aborted) {\n return {\n value: undefined,\n logs: [],\n terminationReason: \"aborted\",\n error: \"Execution cancelled\",\n };\n }\n const hostAbortController = new AbortController();\n const startedAt = Date.now();\n let effectiveTimeoutMs = options.timeoutMs;\n let deadlineAt = startedAt + effectiveTimeoutMs;\n let deadline: NodeJS.Timeout | undefined;\n let abortHandler: (() => void) | undefined;\n let settled = false;\n let finishing = false;\n const hostTasks = new Set<Promise<void>>();\n\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\n return new Promise<FabricSandboxResult>((resolve) => {\n const finish = (result: FabricSandboxResult): void => {\n if (settled) return;\n settled = true;\n if (deadline) clearTimeout(deadline);\n if (abortHandler) options.signal?.removeEventListener(\"abort\", abortHandler);\n if (!hostAbortController.signal.aborted && hostTasks.size > 0) {\n hostAbortController.abort(new Error(result.error ?? \"Process execution stopped\"));\n }\n child.removeAllListeners();\n if (child.connected) child.disconnect();\n if (child.exitCode === null && child.signalCode === null) child.kill(\"SIGKILL\");\n resolve(result);\n };\n const scheduleDeadline = (): void => {\n clearTimeout(deadline);\n if (settled || finishing || !Number.isFinite(deadlineAt)) return;\n deadline = setTimeout(() => {\n const error = `Execution timed out after ${effectiveTimeoutMs}ms`;\n finish({ value: undefined, logs: [], terminationReason: \"timed_out\", error });\n }, Math.min(2_147_483_647, Math.max(0, deadlineAt - Date.now())));\n deadline.unref?.();\n };\n const extendDeadline = (ref: string, args: Record<string, unknown>): void => {\n const requested = options.minimumTimeoutMsForHostCall?.(ref, args);\n if (typeof requested !== \"number\" || !Number.isFinite(requested)) return;\n if (humanWait.paused) {\n humanWait.raise(requested);\n return;\n }\n const nextDeadlineAt = Date.now() + Math.max(1, Math.floor(requested));\n if (nextDeadlineAt <= deadlineAt) return;\n deadlineAt = nextDeadlineAt;\n effectiveTimeoutMs = deadlineAt - startedAt;\n scheduleDeadline();\n };\n\n const humanWait = new HumanWaitDeadlinePause({\n remainingMs: () => deadlineAt - Date.now(),\n suspend: () => {\n clearTimeout(deadline);\n deadlineAt = Infinity;\n },\n resume: (remainingMs) => {\n deadlineAt = Date.now() + remainingMs;\n scheduleDeadline();\n },\n });\n\n abortHandler = () => {\n finish({\n value: undefined,\n logs: [],\n terminationReason: \"aborted\",\n error: \"Execution cancelled\",\n });\n };\n options.signal?.addEventListener(\"abort\", abortHandler, { once: true });\n\n child.on(\"message\", (raw: unknown) => {\n if (settled || finishing || typeof raw !== \"object\" || raw === null) return;\n const message = raw as ChildMessage;\n if (message.type === \"result\") {\n finishing = true;\n if (deadline) clearTimeout(deadline);\n if (message.result.terminationReason !== \"completed\" && !hostAbortController.signal.aborted) {\n hostAbortController.abort(new Error(message.result.error ?? \"Process execution stopped\"));\n }\n void (async () => {\n const completed = await settleWithin(hostTasks, HOST_TASK_SETTLE_GRACE_MS);\n if (!completed && !hostAbortController.signal.aborted) {\n hostAbortController.abort(\n new Error(\"Fabric guest execution ended before its host calls settled\"),\n );\n await settleWithin(hostTasks, HOST_TASK_SETTLE_GRACE_MS);\n }\n finish(\n message.result.error === undefined\n ? message.result\n : {\n ...message.result,\n error: remapGuestErrorText(message.result.error, guestStackMap, guestLineCount),\n },\n );\n })();\n return;\n }\n if (message.type !== \"call\") return;\n extendDeadline(message.ref, message.args);\n if (message.ref === \"fabric.$timer\") {\n const ms = Math.max(0, Number(message.args?.ms ?? 0));\n let timer: NodeJS.Timeout | undefined;\n const timerTask = new Promise<void>((resolveTask) => {\n timer = setTimeout(() => {\n if (!settled && !finishing) {\n send(child, { type: \"response\", id: message.id, ok: true, value: undefined });\n }\n resolveTask();\n }, ms);\n timer!.unref?.();\n });\n hostTasks.add(timerTask);\n void timerTask.finally(() => {\n hostTasks.delete(timerTask);\n if (timer) clearTimeout(timer);\n });\n return;\n }\n const waitsForHuman = options.isHumanWaitHostCall?.(message.ref, message.args) === true;\n if (waitsForHuman) humanWait.enter();\n const task = runAbortable(hostAbortController.signal, () =>\n hostCall(message.ref, message.args, hostAbortController.signal),\n ).finally(() => {\n if (waitsForHuman) humanWait.leave();\n }).then(\n (value) => send(child, { type: \"response\", id: message.id, ok: true, value }),\n (error) =>\n send(child, {\n type: \"response\",\n id: message.id,\n ok: false,\n error: error instanceof Error ? error.message : String(error),\n bashExit: isPiShellRef(message.ref) ? piBashExitMetadata(error) : undefined,\n }),\n );\n hostTasks.add(task);\n void task.finally(() => hostTasks.delete(task));\n });\n child.once(\"error\", (error) => {\n finish({\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error: `Process executor failed: ${error.message}`,\n });\n });\n child.once(\"exit\", (exitCode, signal) => {\n if (settled) return;\n const detail = signal ? `signal ${signal}` : `exit code ${exitCode ?? \"unknown\"}`;\n finish({\n value: undefined,\n logs: [],\n terminationReason: \"runtime_error\",\n error: `Process executor exited before returning a result (${detail}); it may have exceeded its memory limit`,\n });\n });\n\n scheduleDeadline();\n send(child, {\n type: \"execute\",\n setup: guestSetupSource(options.piToolCanonicalFields),\n code: guestBundle.code,\n strings: options.strings ?? {},\n tokenBudget: options.tokenBudget,\n maxLogChars: options.maxLogChars ?? 100_000,\n });\n });\n }\n}\n\nexport class BunProcessRuntime extends NodeProcessRuntime {\n constructor() {\n super(\"bun\");\n }\n}\n", "export const NODE_PROCESS_CHILD_SOURCE = String.raw`\nimport vm from \"node:vm\";\n\nconst pending = new Map();\nlet nextCallId = 0;\n\nconst send = (message) => {\n if (process.connected) process.send?.(message);\n};\n\nconst formatValue = (value) => {\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 jsonCompatible = (value) => {\n if (value === undefined) return undefined;\n const serialized = JSON.stringify(value);\n return serialized === undefined ? undefined : JSON.parse(serialized);\n};\n\nconst run = async (message) => {\n const logs = [];\n let logChars = 0;\n let logsTruncated = false;\n const hostCall = (ref, args) => {\n const id = nextCallId++;\n return new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject });\n send({\n type: \"call\",\n id,\n ref: String(ref),\n args:\n typeof args === \"object\" && args !== null && !Array.isArray(args)\n ? args\n : {},\n });\n });\n };\n const print = (...values) => {\n if (logsTruncated) return;\n const line = values.map(formatValue).join(\" \");\n const remaining = message.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\n // Bun module namespace for the guest. The child resolves the specifier in\n // its own module context; under the node runtime it fails and the binding\n // stays undefined. Namespace objects come from this realm, so instanceof\n // against guest-realm classes fails (same caveat as other sandbox bridges).\n const __bun = await import(\"bun\").catch(() => undefined);\n const sandbox = {\n __fabricHostCall: hostCall,\n __fabricTokenBudget: message.tokenBudget ?? Number.POSITIVE_INFINITY,\n // Native-module bridge for guests whose vm lacks the dynamic-import\n // callback. Bun >= 1.4 honors importModuleDynamically on runInContext\n // (natural import() works there), so this is mostly a fallback and an\n // explicit escape hatch. Cross-realm caveat: namespaces come from this\n // realm, so instanceof against guest-realm classes fails.\n __fabricImport: (specifier) => import(specifier),\n // Resolved above; undefined under the node runtime.\n __bun,\n print,\n \u03C0: jsonCompatible(message.strings),\n };\n const context = vm.createContext(sandbox, {\n name: \"pi-fabric-node-process\",\n codeGeneration: { strings: true, wasm: false },\n });\n\n try {\n vm.runInContext(message.setup, context, { filename: \"pi-fabric-setup.js\" });\n const promise = vm.runInContext(message.code + \"\\n__piFabricMain()\", context, {\n filename: \"pi-fabric-guest.js\",\n // Node requires --experimental-vm-modules (set at spawn). Bun >= 1.4\n // honors this option on runInContext (unlike on createContext), so\n // natural guest import() works there; __fabricImport is a fallback.\n importModuleDynamically: (specifier) => import(specifier),\n });\n const value = jsonCompatible(await promise);\n send({ type: \"result\", result: { value, logs, terminationReason: \"completed\" } });\n } catch (error) {\n send({\n type: \"result\",\n result: {\n logs,\n terminationReason: \"runtime_error\",\n error: error?.stack ?? error?.message ?? String(error),\n },\n });\n }\n};\n\nprocess.on(\"message\", (message) => {\n if (typeof message !== \"object\" || message === null) return;\n if (message.type === \"execute\") {\n void run(message);\n return;\n }\n if (message.type !== \"response\") return;\n const operation = pending.get(message.id);\n if (!operation) return;\n pending.delete(message.id);\n if (message.ok) operation.resolve(message.value);\n else {\n const error = new Error(message.error ?? \"Host call failed\");\n if (message.bashExit) error.__fabricBashExit = message.bashExit;\n operation.reject(error);\n }\n});\n`;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;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