@gpustack/loopwright 0.0.0-stage → 0.0.3

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 (477) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +356 -2
  3. package/bin/loopwright.js +3 -0
  4. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.d.ts +9 -0
  5. package/node_modules/@loopwright/agent-pi/dist/adapter-v2.js +122 -0
  6. package/node_modules/@loopwright/agent-pi/dist/adapter.d.ts +30 -0
  7. package/node_modules/@loopwright/agent-pi/dist/adapter.js +340 -0
  8. package/node_modules/@loopwright/agent-pi/dist/admission.d.ts +25 -0
  9. package/node_modules/@loopwright/agent-pi/dist/admission.js +65 -0
  10. package/node_modules/@loopwright/agent-pi/dist/artifacts.d.ts +15 -0
  11. package/node_modules/@loopwright/agent-pi/dist/artifacts.js +76 -0
  12. package/node_modules/@loopwright/agent-pi/dist/boundary.d.ts +18 -0
  13. package/node_modules/@loopwright/agent-pi/dist/boundary.js +113 -0
  14. package/node_modules/@loopwright/agent-pi/dist/broker-channel.d.ts +4 -0
  15. package/node_modules/@loopwright/agent-pi/dist/broker-channel.js +121 -0
  16. package/node_modules/@loopwright/agent-pi/dist/candidate.d.ts +96 -0
  17. package/node_modules/@loopwright/agent-pi/dist/candidate.js +1712 -0
  18. package/node_modules/@loopwright/agent-pi/dist/capture.d.ts +39 -0
  19. package/node_modules/@loopwright/agent-pi/dist/capture.js +146 -0
  20. package/node_modules/@loopwright/agent-pi/dist/cas.d.ts +51 -0
  21. package/node_modules/@loopwright/agent-pi/dist/cas.js +836 -0
  22. package/node_modules/@loopwright/agent-pi/dist/catalog-api.d.ts +3 -0
  23. package/node_modules/@loopwright/agent-pi/dist/catalog-api.js +2 -0
  24. package/node_modules/@loopwright/agent-pi/dist/catalog.d.ts +39 -0
  25. package/node_modules/@loopwright/agent-pi/dist/catalog.js +280 -0
  26. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.d.ts +9 -0
  27. package/node_modules/@loopwright/agent-pi/dist/circuit-breaker-limits.js +12 -0
  28. package/node_modules/@loopwright/agent-pi/dist/containers.d.ts +29 -0
  29. package/node_modules/@loopwright/agent-pi/dist/containers.js +160 -0
  30. package/node_modules/@loopwright/agent-pi/dist/context.d.ts +56 -0
  31. package/node_modules/@loopwright/agent-pi/dist/context.js +351 -0
  32. package/node_modules/@loopwright/agent-pi/dist/daemon.d.ts +8 -0
  33. package/node_modules/@loopwright/agent-pi/dist/daemon.js +52 -0
  34. package/node_modules/@loopwright/agent-pi/dist/deadline.d.ts +6 -0
  35. package/node_modules/@loopwright/agent-pi/dist/deadline.js +18 -0
  36. package/node_modules/@loopwright/agent-pi/dist/decode-capture.d.ts +39 -0
  37. package/node_modules/@loopwright/agent-pi/dist/decode-capture.js +287 -0
  38. package/node_modules/@loopwright/agent-pi/dist/descriptor.d.ts +12 -0
  39. package/node_modules/@loopwright/agent-pi/dist/descriptor.js +17 -0
  40. package/node_modules/@loopwright/agent-pi/dist/docker-absence.d.ts +2 -0
  41. package/node_modules/@loopwright/agent-pi/dist/docker-absence.js +9 -0
  42. package/node_modules/@loopwright/agent-pi/dist/errors.d.ts +7 -0
  43. package/node_modules/@loopwright/agent-pi/dist/errors.js +19 -0
  44. package/node_modules/@loopwright/agent-pi/dist/event-sequence.d.ts +6 -0
  45. package/node_modules/@loopwright/agent-pi/dist/event-sequence.js +64 -0
  46. package/node_modules/@loopwright/agent-pi/dist/events.d.ts +19 -0
  47. package/node_modules/@loopwright/agent-pi/dist/events.js +132 -0
  48. package/node_modules/@loopwright/agent-pi/dist/execution-guard.d.ts +9 -0
  49. package/node_modules/@loopwright/agent-pi/dist/execution-guard.js +25 -0
  50. package/node_modules/@loopwright/agent-pi/dist/execution-lease.d.ts +24 -0
  51. package/node_modules/@loopwright/agent-pi/dist/execution-lease.js +316 -0
  52. package/node_modules/@loopwright/agent-pi/dist/execution.d.ts +32 -0
  53. package/node_modules/@loopwright/agent-pi/dist/execution.js +476 -0
  54. package/node_modules/@loopwright/agent-pi/dist/external-mcp.d.ts +87 -0
  55. package/node_modules/@loopwright/agent-pi/dist/external-mcp.js +526 -0
  56. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.d.ts +15 -0
  57. package/node_modules/@loopwright/agent-pi/dist/factory-bootstrap.js +74 -0
  58. package/node_modules/@loopwright/agent-pi/dist/host-session.d.ts +51 -0
  59. package/node_modules/@loopwright/agent-pi/dist/host-session.js +2094 -0
  60. package/node_modules/@loopwright/agent-pi/dist/http-mcp.d.ts +32 -0
  61. package/node_modules/@loopwright/agent-pi/dist/http-mcp.js +353 -0
  62. package/node_modules/@loopwright/agent-pi/dist/index.d.ts +7 -0
  63. package/node_modules/@loopwright/agent-pi/dist/index.js +4 -0
  64. package/node_modules/@loopwright/agent-pi/dist/lifecycle.d.ts +13 -0
  65. package/node_modules/@loopwright/agent-pi/dist/lifecycle.js +11 -0
  66. package/node_modules/@loopwright/agent-pi/dist/mcp-process.d.ts +35 -0
  67. package/node_modules/@loopwright/agent-pi/dist/mcp-process.js +92 -0
  68. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.d.ts +25 -0
  69. package/node_modules/@loopwright/agent-pi/dist/mcp-transport.js +63 -0
  70. package/node_modules/@loopwright/agent-pi/dist/mcp.d.ts +23 -0
  71. package/node_modules/@loopwright/agent-pi/dist/mcp.js +212 -0
  72. package/node_modules/@loopwright/agent-pi/dist/operation.d.ts +5 -0
  73. package/node_modules/@loopwright/agent-pi/dist/operation.js +28 -0
  74. package/node_modules/@loopwright/agent-pi/dist/policy-v2.d.ts +10 -0
  75. package/node_modules/@loopwright/agent-pi/dist/policy-v2.js +64 -0
  76. package/node_modules/@loopwright/agent-pi/dist/policy.d.ts +13 -0
  77. package/node_modules/@loopwright/agent-pi/dist/policy.js +260 -0
  78. package/node_modules/@loopwright/agent-pi/dist/preflight.d.ts +60 -0
  79. package/node_modules/@loopwright/agent-pi/dist/preflight.js +700 -0
  80. package/node_modules/@loopwright/agent-pi/dist/progress-summary.d.ts +1 -0
  81. package/node_modules/@loopwright/agent-pi/dist/progress-summary.js +119 -0
  82. package/node_modules/@loopwright/agent-pi/dist/protocol.d.ts +17 -0
  83. package/node_modules/@loopwright/agent-pi/dist/protocol.js +131 -0
  84. package/node_modules/@loopwright/agent-pi/dist/provider.d.ts +62 -0
  85. package/node_modules/@loopwright/agent-pi/dist/provider.js +217 -0
  86. package/node_modules/@loopwright/agent-pi/dist/receipt.d.ts +3 -0
  87. package/node_modules/@loopwright/agent-pi/dist/receipt.js +64 -0
  88. package/node_modules/@loopwright/agent-pi/dist/recovery.d.ts +6 -0
  89. package/node_modules/@loopwright/agent-pi/dist/recovery.js +188 -0
  90. package/node_modules/@loopwright/agent-pi/dist/resources.d.ts +13 -0
  91. package/node_modules/@loopwright/agent-pi/dist/resources.js +81 -0
  92. package/node_modules/@loopwright/agent-pi/dist/response.d.ts +20 -0
  93. package/node_modules/@loopwright/agent-pi/dist/response.js +259 -0
  94. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.d.ts +6 -0
  95. package/node_modules/@loopwright/agent-pi/dist/runtime-profile.js +37 -0
  96. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.d.ts +14 -0
  97. package/node_modules/@loopwright/agent-pi/dist/sdk-worker.js +633 -0
  98. package/node_modules/@loopwright/agent-pi/dist/sender.d.ts +46 -0
  99. package/node_modules/@loopwright/agent-pi/dist/sender.js +553 -0
  100. package/node_modules/@loopwright/agent-pi/dist/session-host.d.ts +21 -0
  101. package/node_modules/@loopwright/agent-pi/dist/session-host.js +315 -0
  102. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.d.ts +14 -0
  103. package/node_modules/@loopwright/agent-pi/dist/snapshot-transfer.js +102 -0
  104. package/node_modules/@loopwright/agent-pi/dist/snapshot.d.ts +19 -0
  105. package/node_modules/@loopwright/agent-pi/dist/snapshot.js +121 -0
  106. package/node_modules/@loopwright/agent-pi/dist/tool-process.d.ts +32 -0
  107. package/node_modules/@loopwright/agent-pi/dist/tool-process.js +85 -0
  108. package/node_modules/@loopwright/agent-pi/dist/tool-worker.d.ts +2 -0
  109. package/node_modules/@loopwright/agent-pi/dist/tool-worker.js +105 -0
  110. package/node_modules/@loopwright/agent-pi/dist/tools.d.ts +36 -0
  111. package/node_modules/@loopwright/agent-pi/dist/tools.js +128 -0
  112. package/node_modules/@loopwright/agent-pi/dist/types-v2.d.ts +71 -0
  113. package/node_modules/@loopwright/agent-pi/dist/types-v2.js +1 -0
  114. package/node_modules/@loopwright/agent-pi/dist/types.d.ts +314 -0
  115. package/node_modules/@loopwright/agent-pi/dist/types.js +1 -0
  116. package/node_modules/@loopwright/agent-pi/dist/usage.d.ts +18 -0
  117. package/node_modules/@loopwright/agent-pi/dist/usage.js +314 -0
  118. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.d.ts +27 -0
  119. package/node_modules/@loopwright/agent-pi/dist/workspace-mcp.js +142 -0
  120. package/node_modules/@loopwright/agent-pi/package.json +24 -0
  121. package/node_modules/@loopwright/agent-pi/runtime/Dockerfile +8 -0
  122. package/node_modules/@loopwright/agent-pi/runtime/seccomp.json +1 -0
  123. package/node_modules/@loopwright/cli/dist/arguments.d.ts +19 -0
  124. package/node_modules/@loopwright/cli/dist/arguments.js +358 -0
  125. package/node_modules/@loopwright/cli/dist/closure.d.ts +93 -0
  126. package/node_modules/@loopwright/cli/dist/closure.js +230 -0
  127. package/node_modules/@loopwright/cli/dist/draft.d.ts +9 -0
  128. package/node_modules/@loopwright/cli/dist/draft.js +106 -0
  129. package/node_modules/@loopwright/cli/dist/failure-matrix.d.ts +9 -0
  130. package/node_modules/@loopwright/cli/dist/failure-matrix.js +701 -0
  131. package/node_modules/@loopwright/cli/dist/index.d.ts +6 -0
  132. package/node_modules/@loopwright/cli/dist/index.js +5 -0
  133. package/node_modules/@loopwright/cli/dist/main.d.ts +22 -0
  134. package/node_modules/@loopwright/cli/dist/main.js +1855 -0
  135. package/node_modules/@loopwright/cli/package.json +16 -0
  136. package/node_modules/@loopwright/controller/dist/acceptance.d.ts +43 -0
  137. package/node_modules/@loopwright/controller/dist/acceptance.js +446 -0
  138. package/node_modules/@loopwright/controller/dist/benchmark-gate.d.ts +273 -0
  139. package/node_modules/@loopwright/controller/dist/benchmark-gate.js +3147 -0
  140. package/node_modules/@loopwright/controller/dist/budget-observations.d.ts +25 -0
  141. package/node_modules/@loopwright/controller/dist/budget-observations.js +139 -0
  142. package/node_modules/@loopwright/controller/dist/bundle.d.ts +26 -0
  143. package/node_modules/@loopwright/controller/dist/bundle.js +64 -0
  144. package/node_modules/@loopwright/controller/dist/capture.d.ts +89 -0
  145. package/node_modules/@loopwright/controller/dist/capture.js +587 -0
  146. package/node_modules/@loopwright/controller/dist/compile.d.ts +3 -0
  147. package/node_modules/@loopwright/controller/dist/compile.js +402 -0
  148. package/node_modules/@loopwright/controller/dist/config.d.ts +22 -0
  149. package/node_modules/@loopwright/controller/dist/config.js +255 -0
  150. package/node_modules/@loopwright/controller/dist/controller.d.ts +177 -0
  151. package/node_modules/@loopwright/controller/dist/controller.js +2135 -0
  152. package/node_modules/@loopwright/controller/dist/credentials.d.ts +29 -0
  153. package/node_modules/@loopwright/controller/dist/credentials.js +189 -0
  154. package/node_modules/@loopwright/controller/dist/deadlines.d.ts +18 -0
  155. package/node_modules/@loopwright/controller/dist/deadlines.js +71 -0
  156. package/node_modules/@loopwright/controller/dist/errors.d.ts +27 -0
  157. package/node_modules/@loopwright/controller/dist/errors.js +41 -0
  158. package/node_modules/@loopwright/controller/dist/events.d.ts +52 -0
  159. package/node_modules/@loopwright/controller/dist/events.js +228 -0
  160. package/node_modules/@loopwright/controller/dist/files.d.ts +51 -0
  161. package/node_modules/@loopwright/controller/dist/files.js +386 -0
  162. package/node_modules/@loopwright/controller/dist/finalize.d.ts +25 -0
  163. package/node_modules/@loopwright/controller/dist/finalize.js +32 -0
  164. package/node_modules/@loopwright/controller/dist/gate.d.ts +84 -0
  165. package/node_modules/@loopwright/controller/dist/gate.js +640 -0
  166. package/node_modules/@loopwright/controller/dist/git-objects.d.ts +11 -0
  167. package/node_modules/@loopwright/controller/dist/git-objects.js +59 -0
  168. package/node_modules/@loopwright/controller/dist/git-reader.d.ts +17 -0
  169. package/node_modules/@loopwright/controller/dist/git-reader.js +40 -0
  170. package/node_modules/@loopwright/controller/dist/handlers.d.ts +6 -0
  171. package/node_modules/@loopwright/controller/dist/handlers.js +45 -0
  172. package/node_modules/@loopwright/controller/dist/handoff.d.ts +71 -0
  173. package/node_modules/@loopwright/controller/dist/handoff.js +554 -0
  174. package/node_modules/@loopwright/controller/dist/index.d.ts +41 -0
  175. package/node_modules/@loopwright/controller/dist/index.js +21 -0
  176. package/node_modules/@loopwright/controller/dist/inspect.d.ts +30 -0
  177. package/node_modules/@loopwright/controller/dist/inspect.js +372 -0
  178. package/node_modules/@loopwright/controller/dist/interpolation.d.ts +9 -0
  179. package/node_modules/@loopwright/controller/dist/interpolation.js +79 -0
  180. package/node_modules/@loopwright/controller/dist/ownership.d.ts +41 -0
  181. package/node_modules/@loopwright/controller/dist/ownership.js +666 -0
  182. package/node_modules/@loopwright/controller/dist/parser.d.ts +5 -0
  183. package/node_modules/@loopwright/controller/dist/parser.js +200 -0
  184. package/node_modules/@loopwright/controller/dist/progress.d.ts +41 -0
  185. package/node_modules/@loopwright/controller/dist/progress.js +904 -0
  186. package/node_modules/@loopwright/controller/dist/publication.d.ts +60 -0
  187. package/node_modules/@loopwright/controller/dist/publication.js +329 -0
  188. package/node_modules/@loopwright/controller/dist/reconcile.d.ts +26 -0
  189. package/node_modules/@loopwright/controller/dist/reconcile.js +1378 -0
  190. package/node_modules/@loopwright/controller/dist/recovery.d.ts +10 -0
  191. package/node_modules/@loopwright/controller/dist/recovery.js +315 -0
  192. package/node_modules/@loopwright/controller/dist/refusal-record.d.ts +43 -0
  193. package/node_modules/@loopwright/controller/dist/refusal-record.js +150 -0
  194. package/node_modules/@loopwright/controller/dist/registry.d.ts +6 -0
  195. package/node_modules/@loopwright/controller/dist/registry.js +374 -0
  196. package/node_modules/@loopwright/controller/dist/repair.d.ts +31 -0
  197. package/node_modules/@loopwright/controller/dist/repair.js +102 -0
  198. package/node_modules/@loopwright/controller/dist/report.d.ts +64 -0
  199. package/node_modules/@loopwright/controller/dist/report.js +596 -0
  200. package/node_modules/@loopwright/controller/dist/retained.d.ts +284 -0
  201. package/node_modules/@loopwright/controller/dist/retained.js +193 -0
  202. package/node_modules/@loopwright/controller/dist/rules.d.ts +31 -0
  203. package/node_modules/@loopwright/controller/dist/rules.js +110 -0
  204. package/node_modules/@loopwright/controller/dist/run-eval.d.ts +115 -0
  205. package/node_modules/@loopwright/controller/dist/run-eval.js +959 -0
  206. package/node_modules/@loopwright/controller/dist/scheduler.d.ts +10 -0
  207. package/node_modules/@loopwright/controller/dist/scheduler.js +41 -0
  208. package/node_modules/@loopwright/controller/dist/schema.d.ts +17 -0
  209. package/node_modules/@loopwright/controller/dist/schema.js +78 -0
  210. package/node_modules/@loopwright/controller/dist/source.d.ts +69 -0
  211. package/node_modules/@loopwright/controller/dist/source.js +872 -0
  212. package/node_modules/@loopwright/controller/dist/step.d.ts +38 -0
  213. package/node_modules/@loopwright/controller/dist/step.js +1776 -0
  214. package/node_modules/@loopwright/controller/dist/storage.d.ts +90 -0
  215. package/node_modules/@loopwright/controller/dist/storage.js +1345 -0
  216. package/node_modules/@loopwright/controller/dist/submission.d.ts +51 -0
  217. package/node_modules/@loopwright/controller/dist/submission.js +292 -0
  218. package/node_modules/@loopwright/controller/dist/types.d.ts +585 -0
  219. package/node_modules/@loopwright/controller/dist/types.js +9 -0
  220. package/node_modules/@loopwright/controller/dist/verification.d.ts +124 -0
  221. package/node_modules/@loopwright/controller/dist/verification.js +1308 -0
  222. package/node_modules/@loopwright/controller/dist/verifier-protocol.d.ts +105 -0
  223. package/node_modules/@loopwright/controller/dist/verifier-protocol.js +1312 -0
  224. package/node_modules/@loopwright/controller/dist/verifier-worker.d.ts +1 -0
  225. package/node_modules/@loopwright/controller/dist/verifier-worker.js +33 -0
  226. package/node_modules/@loopwright/controller/package.json +12 -0
  227. package/node_modules/@loopwright/core/dist/acceptance.d.ts +108 -0
  228. package/node_modules/@loopwright/core/dist/acceptance.js +327 -0
  229. package/node_modules/@loopwright/core/dist/artifacts.d.ts +63 -0
  230. package/node_modules/@loopwright/core/dist/artifacts.js +356 -0
  231. package/node_modules/@loopwright/core/dist/boundary.d.ts +21 -0
  232. package/node_modules/@loopwright/core/dist/boundary.js +484 -0
  233. package/node_modules/@loopwright/core/dist/contracts.d.ts +287 -0
  234. package/node_modules/@loopwright/core/dist/contracts.js +694 -0
  235. package/node_modules/@loopwright/core/dist/diagnostics.d.ts +21 -0
  236. package/node_modules/@loopwright/core/dist/diagnostics.js +51 -0
  237. package/node_modules/@loopwright/core/dist/evidence.d.ts +92 -0
  238. package/node_modules/@loopwright/core/dist/evidence.js +85 -0
  239. package/node_modules/@loopwright/core/dist/graph.d.ts +8 -0
  240. package/node_modules/@loopwright/core/dist/graph.js +44 -0
  241. package/node_modules/@loopwright/core/dist/identity.d.ts +162 -0
  242. package/node_modules/@loopwright/core/dist/identity.js +80 -0
  243. package/node_modules/@loopwright/core/dist/index.d.ts +30 -0
  244. package/node_modules/@loopwright/core/dist/index.js +39 -0
  245. package/node_modules/@loopwright/core/dist/limits.d.ts +99 -0
  246. package/node_modules/@loopwright/core/dist/limits.js +59 -0
  247. package/node_modules/@loopwright/core/dist/results.d.ts +161 -0
  248. package/node_modules/@loopwright/core/dist/results.js +98 -0
  249. package/node_modules/@loopwright/core/dist/scope.d.ts +13 -0
  250. package/node_modules/@loopwright/core/dist/scope.js +154 -0
  251. package/node_modules/@loopwright/core/dist/scrubber.d.ts +13 -0
  252. package/node_modules/@loopwright/core/dist/scrubber.js +63 -0
  253. package/node_modules/@loopwright/core/dist/usage.d.ts +68 -0
  254. package/node_modules/@loopwright/core/dist/usage.js +56 -0
  255. package/node_modules/@loopwright/core/package.json +12 -0
  256. package/node_modules/@loopwright/decisions/dist/benchmark.d.ts +23 -0
  257. package/node_modules/@loopwright/decisions/dist/benchmark.js +337 -0
  258. package/node_modules/@loopwright/decisions/dist/client.d.ts +74 -0
  259. package/node_modules/@loopwright/decisions/dist/client.js +292 -0
  260. package/node_modules/@loopwright/decisions/dist/index.d.ts +15 -0
  261. package/node_modules/@loopwright/decisions/dist/index.js +8 -0
  262. package/node_modules/@loopwright/decisions/dist/nodes.d.ts +63 -0
  263. package/node_modules/@loopwright/decisions/dist/nodes.js +282 -0
  264. package/node_modules/@loopwright/decisions/dist/primitives.d.ts +36 -0
  265. package/node_modules/@loopwright/decisions/dist/primitives.js +300 -0
  266. package/node_modules/@loopwright/decisions/dist/redaction.d.ts +23 -0
  267. package/node_modules/@loopwright/decisions/dist/redaction.js +146 -0
  268. package/node_modules/@loopwright/decisions/dist/router.d.ts +55 -0
  269. package/node_modules/@loopwright/decisions/dist/router.js +248 -0
  270. package/node_modules/@loopwright/decisions/dist/schema.d.ts +25 -0
  271. package/node_modules/@loopwright/decisions/dist/schema.js +536 -0
  272. package/node_modules/@loopwright/decisions/dist/types.d.ts +394 -0
  273. package/node_modules/@loopwright/decisions/dist/types.js +80 -0
  274. package/node_modules/@loopwright/decisions/package.json +12 -0
  275. package/node_modules/@loopwright/github-app/dist/action.d.ts +90 -0
  276. package/node_modules/@loopwright/github-app/dist/action.js +2429 -0
  277. package/node_modules/@loopwright/github-app/dist/config.d.ts +23 -0
  278. package/node_modules/@loopwright/github-app/dist/config.js +297 -0
  279. package/node_modules/@loopwright/github-app/dist/digests.d.ts +1 -0
  280. package/node_modules/@loopwright/github-app/dist/digests.js +1 -0
  281. package/node_modules/@loopwright/github-app/dist/index.d.ts +14 -0
  282. package/node_modules/@loopwright/github-app/dist/index.js +13 -0
  283. package/node_modules/@loopwright/github-app/dist/models-config.d.ts +1 -0
  284. package/node_modules/@loopwright/github-app/dist/models-config.js +1 -0
  285. package/node_modules/@loopwright/github-app/dist/output-format.d.ts +1 -0
  286. package/node_modules/@loopwright/github-app/dist/output-format.js +1 -0
  287. package/node_modules/@loopwright/github-app/dist/preflight.d.ts +1 -0
  288. package/node_modules/@loopwright/github-app/dist/preflight.js +1 -0
  289. package/node_modules/@loopwright/github-app/dist/publisher.d.ts +58 -0
  290. package/node_modules/@loopwright/github-app/dist/publisher.js +1368 -0
  291. package/node_modules/@loopwright/github-app/dist/qualification.d.ts +1 -0
  292. package/node_modules/@loopwright/github-app/dist/qualification.js +1 -0
  293. package/node_modules/@loopwright/github-app/dist/sandbox.d.ts +1 -0
  294. package/node_modules/@loopwright/github-app/dist/sandbox.js +1 -0
  295. package/node_modules/@loopwright/github-app/dist/schema.d.ts +1 -0
  296. package/node_modules/@loopwright/github-app/dist/schema.js +1 -0
  297. package/node_modules/@loopwright/github-app/dist/service.d.ts +52 -0
  298. package/node_modules/@loopwright/github-app/dist/service.js +1658 -0
  299. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.d.ts +90 -0
  300. package/node_modules/@loopwright/github-app/dist/suite-pr-lookup.js +392 -0
  301. package/node_modules/@loopwright/github-app/dist/taskpack.d.ts +1 -0
  302. package/node_modules/@loopwright/github-app/dist/taskpack.js +1 -0
  303. package/node_modules/@loopwright/github-app/dist/tenant-queue.d.ts +44 -0
  304. package/node_modules/@loopwright/github-app/dist/tenant-queue.js +423 -0
  305. package/node_modules/@loopwright/github-app/dist/token-broker.d.ts +50 -0
  306. package/node_modules/@loopwright/github-app/dist/token-broker.js +262 -0
  307. package/node_modules/@loopwright/github-app/dist/turnkey-memory.d.ts +35 -0
  308. package/node_modules/@loopwright/github-app/dist/turnkey-memory.js +1654 -0
  309. package/node_modules/@loopwright/github-app/dist/turnkey.d.ts +16 -0
  310. package/node_modules/@loopwright/github-app/dist/turnkey.js +34 -0
  311. package/node_modules/@loopwright/github-app/dist/types.d.ts +220 -0
  312. package/node_modules/@loopwright/github-app/dist/types.js +14 -0
  313. package/node_modules/@loopwright/github-app/dist/upstreams.d.ts +13 -0
  314. package/node_modules/@loopwright/github-app/dist/upstreams.js +65 -0
  315. package/node_modules/@loopwright/github-app/dist/webhook.d.ts +34 -0
  316. package/node_modules/@loopwright/github-app/dist/webhook.js +241 -0
  317. package/node_modules/@loopwright/github-app/dist/yaml.d.ts +1 -0
  318. package/node_modules/@loopwright/github-app/dist/yaml.js +1 -0
  319. package/node_modules/@loopwright/github-app/package.json +12 -0
  320. package/node_modules/@loopwright/hardware-runner/dist/config.d.ts +48 -0
  321. package/node_modules/@loopwright/hardware-runner/dist/config.js +719 -0
  322. package/node_modules/@loopwright/hardware-runner/dist/evaluator.d.ts +230 -0
  323. package/node_modules/@loopwright/hardware-runner/dist/evaluator.js +3178 -0
  324. package/node_modules/@loopwright/hardware-runner/dist/index.d.ts +13 -0
  325. package/node_modules/@loopwright/hardware-runner/dist/index.js +9 -0
  326. package/node_modules/@loopwright/hardware-runner/dist/provenance.d.ts +128 -0
  327. package/node_modules/@loopwright/hardware-runner/dist/provenance.js +1500 -0
  328. package/node_modules/@loopwright/hardware-runner/dist/queue.d.ts +81 -0
  329. package/node_modules/@loopwright/hardware-runner/dist/queue.js +1081 -0
  330. package/node_modules/@loopwright/hardware-runner/dist/relay-server.d.ts +13 -0
  331. package/node_modules/@loopwright/hardware-runner/dist/relay-server.js +2997 -0
  332. package/node_modules/@loopwright/hardware-runner/dist/types.d.ts +239 -0
  333. package/node_modules/@loopwright/hardware-runner/dist/types.js +12 -0
  334. package/node_modules/@loopwright/hardware-runner/dist/worker.d.ts +49 -0
  335. package/node_modules/@loopwright/hardware-runner/dist/worker.js +1648 -0
  336. package/node_modules/@loopwright/hardware-runner/package.json +12 -0
  337. package/node_modules/@loopwright/memory/dist/cas.d.ts +21 -0
  338. package/node_modules/@loopwright/memory/dist/cas.js +510 -0
  339. package/node_modules/@loopwright/memory/dist/compaction.d.ts +18 -0
  340. package/node_modules/@loopwright/memory/dist/compaction.js +110 -0
  341. package/node_modules/@loopwright/memory/dist/finalizer.d.ts +23 -0
  342. package/node_modules/@loopwright/memory/dist/finalizer.js +538 -0
  343. package/node_modules/@loopwright/memory/dist/index.d.ts +9 -0
  344. package/node_modules/@loopwright/memory/dist/index.js +8 -0
  345. package/node_modules/@loopwright/memory/dist/schema.d.ts +36 -0
  346. package/node_modules/@loopwright/memory/dist/schema.js +510 -0
  347. package/node_modules/@loopwright/memory/dist/selector.d.ts +7 -0
  348. package/node_modules/@loopwright/memory/dist/selector.js +157 -0
  349. package/node_modules/@loopwright/memory/dist/store.d.ts +51 -0
  350. package/node_modules/@loopwright/memory/dist/store.js +554 -0
  351. package/node_modules/@loopwright/memory/dist/types.d.ts +442 -0
  352. package/node_modules/@loopwright/memory/dist/types.js +8 -0
  353. package/node_modules/@loopwright/memory/dist/verifier.d.ts +5 -0
  354. package/node_modules/@loopwright/memory/dist/verifier.js +328 -0
  355. package/node_modules/@loopwright/memory/package.json +12 -0
  356. package/node_modules/@loopwright/state/dist/admission.d.ts +321 -0
  357. package/node_modules/@loopwright/state/dist/admission.js +199 -0
  358. package/node_modules/@loopwright/state/dist/boundary.d.ts +53 -0
  359. package/node_modules/@loopwright/state/dist/boundary.js +194 -0
  360. package/node_modules/@loopwright/state/dist/checkpoint.d.ts +16 -0
  361. package/node_modules/@loopwright/state/dist/checkpoint.js +84 -0
  362. package/node_modules/@loopwright/state/dist/clock.d.ts +8 -0
  363. package/node_modules/@loopwright/state/dist/clock.js +27 -0
  364. package/node_modules/@loopwright/state/dist/connection.d.ts +55 -0
  365. package/node_modules/@loopwright/state/dist/connection.js +391 -0
  366. package/node_modules/@loopwright/state/dist/errors.d.ts +13 -0
  367. package/node_modules/@loopwright/state/dist/errors.js +34 -0
  368. package/node_modules/@loopwright/state/dist/index.d.ts +3 -0
  369. package/node_modules/@loopwright/state/dist/index.js +1 -0
  370. package/node_modules/@loopwright/state/dist/journal.d.ts +119 -0
  371. package/node_modules/@loopwright/state/dist/journal.js +72 -0
  372. package/node_modules/@loopwright/state/dist/model.d.ts +40 -0
  373. package/node_modules/@loopwright/state/dist/model.js +58 -0
  374. package/node_modules/@loopwright/state/dist/ownership.d.ts +14 -0
  375. package/node_modules/@loopwright/state/dist/ownership.js +45 -0
  376. package/node_modules/@loopwright/state/dist/pages.d.ts +11 -0
  377. package/node_modules/@loopwright/state/dist/pages.js +41 -0
  378. package/node_modules/@loopwright/state/dist/receipts.d.ts +33 -0
  379. package/node_modules/@loopwright/state/dist/receipts.js +97 -0
  380. package/node_modules/@loopwright/state/dist/schema.d.ts +28 -0
  381. package/node_modules/@loopwright/state/dist/schema.js +41 -0
  382. package/node_modules/@loopwright/state/dist/settlement.d.ts +10 -0
  383. package/node_modules/@loopwright/state/dist/settlement.js +129 -0
  384. package/node_modules/@loopwright/state/dist/store.d.ts +52 -0
  385. package/node_modules/@loopwright/state/dist/store.js +100 -0
  386. package/node_modules/@loopwright/state/dist/types.d.ts +315 -0
  387. package/node_modules/@loopwright/state/dist/types.js +1 -0
  388. package/node_modules/@loopwright/state/package.json +12 -0
  389. package/node_modules/@loopwright/taskpack/dist/baseline-align.d.ts +195 -0
  390. package/node_modules/@loopwright/taskpack/dist/baseline-align.js +1847 -0
  391. package/node_modules/@loopwright/taskpack/dist/digests.d.ts +61 -0
  392. package/node_modules/@loopwright/taskpack/dist/digests.js +715 -0
  393. package/node_modules/@loopwright/taskpack/dist/index.d.ts +18 -0
  394. package/node_modules/@loopwright/taskpack/dist/index.js +17 -0
  395. package/node_modules/@loopwright/taskpack/dist/models-config.d.ts +112 -0
  396. package/node_modules/@loopwright/taskpack/dist/models-config.js +1026 -0
  397. package/node_modules/@loopwright/taskpack/dist/output-format.d.ts +28 -0
  398. package/node_modules/@loopwright/taskpack/dist/output-format.js +157 -0
  399. package/node_modules/@loopwright/taskpack/dist/preflight.d.ts +130 -0
  400. package/node_modules/@loopwright/taskpack/dist/preflight.js +1497 -0
  401. package/node_modules/@loopwright/taskpack/dist/qualification.d.ts +23 -0
  402. package/node_modules/@loopwright/taskpack/dist/qualification.js +120 -0
  403. package/node_modules/@loopwright/taskpack/dist/sandbox.d.ts +121 -0
  404. package/node_modules/@loopwright/taskpack/dist/sandbox.js +2642 -0
  405. package/node_modules/@loopwright/taskpack/dist/schema.d.ts +197 -0
  406. package/node_modules/@loopwright/taskpack/dist/schema.js +4189 -0
  407. package/node_modules/@loopwright/taskpack/dist/scrubber.d.ts +47 -0
  408. package/node_modules/@loopwright/taskpack/dist/scrubber.js +283 -0
  409. package/node_modules/@loopwright/taskpack/dist/suite.d.ts +124 -0
  410. package/node_modules/@loopwright/taskpack/dist/suite.js +3256 -0
  411. package/node_modules/@loopwright/taskpack/dist/taskpack.d.ts +154 -0
  412. package/node_modules/@loopwright/taskpack/dist/taskpack.js +3634 -0
  413. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.d.ts +122 -0
  414. package/node_modules/@loopwright/taskpack/dist/turnkey-memory.js +483 -0
  415. package/node_modules/@loopwright/taskpack/dist/turnkey.d.ts +437 -0
  416. package/node_modules/@loopwright/taskpack/dist/turnkey.js +7335 -0
  417. package/node_modules/@loopwright/taskpack/dist/types.d.ts +1274 -0
  418. package/node_modules/@loopwright/taskpack/dist/types.js +99 -0
  419. package/node_modules/@loopwright/taskpack/dist/upstreams.d.ts +261 -0
  420. package/node_modules/@loopwright/taskpack/dist/upstreams.js +2242 -0
  421. package/node_modules/@loopwright/taskpack/dist/yaml.d.ts +18 -0
  422. package/node_modules/@loopwright/taskpack/dist/yaml.js +167 -0
  423. package/node_modules/@loopwright/taskpack/package.json +12 -0
  424. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.d.ts +137 -0
  425. package/node_modules/@loopwright/taskpack-runner/dist/compile-taskpack.js +474 -0
  426. package/node_modules/@loopwright/taskpack-runner/dist/corpus.d.ts +8 -0
  427. package/node_modules/@loopwright/taskpack-runner/dist/corpus.js +129 -0
  428. package/node_modules/@loopwright/taskpack-runner/dist/index.d.ts +13 -0
  429. package/node_modules/@loopwright/taskpack-runner/dist/index.js +7 -0
  430. package/node_modules/@loopwright/taskpack-runner/dist/intake.d.ts +149 -0
  431. package/node_modules/@loopwright/taskpack-runner/dist/intake.js +135 -0
  432. package/node_modules/@loopwright/taskpack-runner/dist/parity.d.ts +130 -0
  433. package/node_modules/@loopwright/taskpack-runner/dist/parity.js +927 -0
  434. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.d.ts +68 -0
  435. package/node_modules/@loopwright/taskpack-runner/dist/python-bridge.js +517 -0
  436. package/node_modules/@loopwright/taskpack-runner/dist/service.d.ts +149 -0
  437. package/node_modules/@loopwright/taskpack-runner/dist/service.js +1796 -0
  438. package/node_modules/@loopwright/taskpack-runner/dist/types.d.ts +29 -0
  439. package/node_modules/@loopwright/taskpack-runner/dist/types.js +11 -0
  440. package/node_modules/@loopwright/taskpack-runner/package.json +12 -0
  441. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/README.md +77 -0
  442. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/support-records.md +57 -0
  443. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/docs/supported-runners.md +98 -0
  444. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/manifest.json +205 -0
  445. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/expand_matrix.sh +273 -0
  446. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/matrix.yaml +280 -0
  447. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pack/resolve_dockerfile.sh +24 -0
  448. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/pyproject.toml +46 -0
  449. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/runtime_runner/runner.py.json +5270 -0
  450. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/discovery/legacy-support.md +86 -0
  451. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/github/service.py +401 -0
  452. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/analysis.json +95 -0
  453. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/fixtures/proposals/ready.json +109 -0
  454. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_assemble.py +263 -0
  455. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_check_draft.py +333 -0
  456. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_checks.py +1099 -0
  457. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_discovery.py +817 -0
  458. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_proposal.py +658 -0
  459. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_publish.py +987 -0
  460. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tests/auto_sync/test_summary.py +107 -0
  461. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/agent.py +610 -0
  462. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/assemble.py +84 -0
  463. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/check_draft.py +94 -0
  464. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/checks.py +1002 -0
  465. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/discovery.py +789 -0
  466. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/model.py +557 -0
  467. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/progress.py +174 -0
  468. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/analysis.md +40 -0
  469. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/proposal.md +65 -0
  470. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/prompts/repair.md +17 -0
  471. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/proposal.py +903 -0
  472. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/publish.py +997 -0
  473. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/summary.py +131 -0
  474. package/node_modules/@loopwright/taskpack-runner/vendor/runner-auto-sync/tools/auto_sync/tool-versions.json +133 -0
  475. package/node_modules/package-lock.json +3025 -0
  476. package/package-lock.json +3025 -0
  477. package/package.json +52 -4
@@ -0,0 +1,2094 @@
1
+ import { execFile, spawn, spawnSync } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { EventEmitter } from 'node:events';
4
+ import { constants, existsSync, writeFileSync } from 'node:fs';
5
+ import { chmod, lstat, mkdir, open, readFile, realpath, stat, symlink, unlink, writeFile } from 'node:fs/promises';
6
+ import { join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { promisify } from 'node:util';
9
+ import { createBashTool, createReadTool } from '@earendil-works/pi-coding-agent';
10
+ import { LIMITS, OVERLAY_LIMITS } from '@loopwright/core';
11
+ import { constructAdapterV2 } from './adapter-v2.js';
12
+ import { constructAdapter } from './adapter.js';
13
+ import { stateValue } from './admission.js';
14
+ import { canonical, digest, freeze, integer, list, object } from './boundary.js';
15
+ import { receiveBrokerMessage } from './broker-channel.js';
16
+ import { materializeCandidateDirectory, setDirectoryTreeMode } from './candidate.js';
17
+ import { selectedCatalog } from './catalog.js';
18
+ import { parseBoundedJson } from './context.js';
19
+ import { scheduleDeadline } from './deadline.js';
20
+ import { PiFailure, refuse } from './errors.js';
21
+ import { DEFAULT_MAX_DISPATCH_TURNS, DEFAULT_MAX_REPAIR_DISPATCH_TURNS, deriveDefaultCircuitBreakerLimits, } from './circuit-breaker-limits.js';
22
+ import { summarizeToolProgressArgs } from './progress-summary.js';
23
+ import { Execution } from './execution.js';
24
+ import { verifyNativeCompletion } from './lifecycle.js';
25
+ import { sameIdentity } from './policy.js';
26
+ import { Channel } from './protocol.js';
27
+ import { recoverSnapshot } from './recovery.js';
28
+ import { systemPrompt } from './resources.js';
29
+ import { profileIdentity } from './runtime-profile.js';
30
+ import { Sender } from './sender.js';
31
+ import { canonicalDirectory } from './session-host.js';
32
+ import { SnapshotTransfer } from './snapshot-transfer.js';
33
+ import { clampToolResultBytes } from './tools.js';
34
+ import { createRoleMcpAllowlist, createRoleScopedMcpExecutor, EXTERNAL_MCP_TOOL_NAME_PATTERN, validateAllowedMcpServers, } from './external-mcp.js';
35
+ import { WORKSPACE_TOOL, readWorkspace } from './workspace-mcp.js';
36
+ const DEFAULT_MAX_CONSECUTIVE_ERROR_TURNS = 8;
37
+ const DEFAULT_MAX_REPAIR_NO_PROGRESS_TURNS = 10;
38
+ const CONVERGENCE_WARNING_TURNS = 3;
39
+ const SUMMARY_MAX_ARGS_BYTES = 65536;
40
+ const MUTATING_TOOLS = new Set(['write', 'edit', 'delete']);
41
+ const MUTATING_MCP_VERBS = new Set([
42
+ 'write', 'edit', 'delete', 'remove', 'create', 'update', 'patch',
43
+ 'put', 'post', 'set', 'apply', 'replace', 'append', 'insert',
44
+ 'upsert', 'modify', 'move', 'rename', 'mkdir', 'commit', 'push', 'merge',
45
+ ]);
46
+ function isMutatingExternalMcpTool(toolName) {
47
+ const match = EXTERNAL_MCP_TOOL_NAME_PATTERN.exec(toolName);
48
+ if (!match)
49
+ return false;
50
+ const serverId = match[1];
51
+ const upstreamName = match[2];
52
+ if (!serverId || serverId === 'workspace' || !upstreamName)
53
+ return false;
54
+ const stripped = upstreamName.replace(/^_+/, '');
55
+ const firstToken = stripped.split(/[_-]|(?<=[a-z0-9])(?=[A-Z])/)[0]?.toLowerCase() ?? '';
56
+ return MUTATING_MCP_VERBS.has(firstToken);
57
+ }
58
+ function resolveBreakerLimit(value, fallback, path) {
59
+ if (value === undefined)
60
+ return fallback;
61
+ if (!Number.isSafeInteger(value) || value < 1)
62
+ refuse('INPUT_INVALID', path);
63
+ return value;
64
+ }
65
+ class HostSessionCircuitBreaker {
66
+ #explicitMaxTurns = undefined;
67
+ #explicitMaxRepairTurns = undefined;
68
+ #maxTurns = DEFAULT_MAX_DISPATCH_TURNS;
69
+ #maxRepairTurns = DEFAULT_MAX_REPAIR_DISPATCH_TURNS;
70
+ #maxConsecutiveErrorTurns = DEFAULT_MAX_CONSECUTIVE_ERROR_TURNS;
71
+ #maxRepairNoProgressTurns = DEFAULT_MAX_REPAIR_NO_PROGRESS_TURNS;
72
+ #active = false;
73
+ #repair = 'none';
74
+ #completedTurns = 0;
75
+ #consecutiveErrorTurns = 0;
76
+ #consecutiveNoMutationTurns = 0;
77
+ #turnHadToolCalls = false;
78
+ #turnToolCount = 0;
79
+ #turnToolErrorCount = 0;
80
+ #turnSucceededMutation = false;
81
+ #lastWarnedTurn = 0;
82
+ #tripped = null;
83
+ configure(options) {
84
+ this.#explicitMaxTurns = options?.maxTurns === undefined
85
+ ? undefined
86
+ : resolveBreakerLimit(options.maxTurns, DEFAULT_MAX_DISPATCH_TURNS, '/circuitBreaker/maxTurns');
87
+ this.#explicitMaxRepairTurns = options?.maxRepairTurns === undefined
88
+ ? undefined
89
+ : resolveBreakerLimit(options.maxRepairTurns, DEFAULT_MAX_REPAIR_DISPATCH_TURNS, '/circuitBreaker/maxRepairTurns');
90
+ this.#maxTurns = this.#explicitMaxTurns ?? DEFAULT_MAX_DISPATCH_TURNS;
91
+ this.#maxRepairTurns = this.#explicitMaxRepairTurns ?? DEFAULT_MAX_REPAIR_DISPATCH_TURNS;
92
+ this.#maxConsecutiveErrorTurns = resolveBreakerLimit(options?.maxConsecutiveErrorTurns, DEFAULT_MAX_CONSECUTIVE_ERROR_TURNS, '/circuitBreaker/maxConsecutiveErrorTurns');
93
+ this.#maxRepairNoProgressTurns = resolveBreakerLimit(options?.maxRepairNoProgressTurns, DEFAULT_MAX_REPAIR_NO_PROGRESS_TURNS, '/circuitBreaker/maxRepairNoProgressTurns');
94
+ }
95
+ bindBudgets(budgets, policyRequests) {
96
+ const derived = deriveDefaultCircuitBreakerLimits(budgets, policyRequests);
97
+ if (this.#explicitMaxTurns === undefined) {
98
+ this.#maxTurns = derived.maxTurns;
99
+ }
100
+ if (this.#explicitMaxRepairTurns === undefined) {
101
+ this.#maxRepairTurns = derived.maxRepairTurns;
102
+ }
103
+ }
104
+ get tripped() {
105
+ return this.#tripped;
106
+ }
107
+ beginDispatch(kind, repair) {
108
+ this.#active = kind === 'execute';
109
+ this.#repair = repair;
110
+ this.#completedTurns = 0;
111
+ this.#consecutiveErrorTurns = 0;
112
+ this.#consecutiveNoMutationTurns = 0;
113
+ this.#turnHadToolCalls = false;
114
+ this.#turnToolCount = 0;
115
+ this.#turnToolErrorCount = 0;
116
+ this.#turnSucceededMutation = false;
117
+ this.#lastWarnedTurn = 0;
118
+ this.#tripped = null;
119
+ }
120
+ onRequestSettled(hasToolCalls) {
121
+ if (!this.#active || this.#tripped !== null)
122
+ return;
123
+ this.#completedTurns += 1;
124
+ this.#turnHadToolCalls = hasToolCalls;
125
+ }
126
+ recordToolEnd(toolName, isError) {
127
+ if (!this.#active || this.#tripped !== null)
128
+ return;
129
+ this.#turnToolCount += 1;
130
+ if (isError) {
131
+ this.#turnToolErrorCount += 1;
132
+ }
133
+ else if (MUTATING_TOOLS.has(toolName) || isMutatingExternalMcpTool(toolName)) {
134
+ this.#turnSucceededMutation = true;
135
+ }
136
+ }
137
+ convergenceWarning() {
138
+ if (!this.#active || this.#tripped !== null || this.#completedTurns <= 0)
139
+ return null;
140
+ if (this.#lastWarnedTurn === this.#completedTurns)
141
+ return null;
142
+ const turnLimit = this.#repair === 'implementation' ? this.#maxRepairTurns : this.#maxTurns;
143
+ const repairSuffix = this.#repair === 'implementation' ? ', repair=implementation' : '';
144
+ const remaining = turnLimit - this.#completedTurns;
145
+ if (turnLimit >= 2 && remaining >= 1 && remaining <= CONVERGENCE_WARNING_TURNS) {
146
+ this.#lastWarnedTurn = this.#completedTurns;
147
+ if (remaining === 1) {
148
+ return `[loopwright budget notice: 1 turn remaining in this dispatch (turn ${this.#completedTurns}/${turnLimit}${repairSuffix}). Your next assistant response is the FINAL turn: do NOT issue any more tool calls; emit only your final structured submission JSON now so your workspace changes are captured and verified.]`;
149
+ }
150
+ return `[loopwright budget notice: ${remaining} turns remaining in this dispatch (turn ${this.#completedTurns}/${turnLimit}${repairSuffix}). Stop further exploration, finalize deterministic edits or mark blocked, and prepare your final structured submission JSON.]`;
151
+ }
152
+ if (this.#repair === 'implementation' && !this.#turnSucceededMutation && this.#maxRepairNoProgressTurns >= 2) {
153
+ const projectedNoMutation = this.#consecutiveNoMutationTurns + 1;
154
+ if (this.#maxRepairNoProgressTurns - projectedNoMutation === 1) {
155
+ this.#lastWarnedTurn = this.#completedTurns;
156
+ return `[loopwright budget notice: 1 implementation-repair turn remaining before no-progress stop (${projectedNoMutation}/${this.#maxRepairNoProgressTurns} turns without a successful write/edit/delete). Apply a concrete fix or emit your final structured submission JSON now.]`;
157
+ }
158
+ }
159
+ return null;
160
+ }
161
+ onBeforeInvoke() {
162
+ if (!this.#active)
163
+ return null;
164
+ if (this.#tripped !== null)
165
+ return this.#tripped;
166
+ if (this.#completedTurns === 0)
167
+ return null;
168
+ if (this.#turnToolCount > 0) {
169
+ if (this.#turnToolErrorCount > 0 && this.#turnToolErrorCount === this.#turnToolCount) {
170
+ this.#consecutiveErrorTurns += 1;
171
+ }
172
+ else {
173
+ this.#consecutiveErrorTurns = 0;
174
+ }
175
+ }
176
+ if (this.#repair === 'implementation' && (this.#turnHadToolCalls || this.#turnToolCount > 0)) {
177
+ if (!this.#turnSucceededMutation) {
178
+ this.#consecutiveNoMutationTurns += 1;
179
+ }
180
+ else {
181
+ this.#consecutiveNoMutationTurns = 0;
182
+ }
183
+ }
184
+ this.#turnHadToolCalls = false;
185
+ this.#turnToolCount = 0;
186
+ this.#turnToolErrorCount = 0;
187
+ this.#turnSucceededMutation = false;
188
+ const turnLimit = this.#repair === 'implementation' ? this.#maxRepairTurns : this.#maxTurns;
189
+ if (this.#completedTurns >= turnLimit) {
190
+ this.#tripped = {
191
+ reason: 'max_turns',
192
+ turn: this.#completedTurns,
193
+ path: '/circuit-breaker/maxTurns',
194
+ message: `circuit breaker: stopped after ${this.#completedTurns} turns (limit=${turnLimit}${this.#repair === 'implementation' ? ', repair=implementation' : ''})`,
195
+ };
196
+ }
197
+ else if (this.#consecutiveErrorTurns >= this.#maxConsecutiveErrorTurns) {
198
+ this.#tripped = {
199
+ reason: 'consecutive_tool_errors',
200
+ turn: this.#completedTurns,
201
+ path: '/circuit-breaker/consecutiveToolErrors',
202
+ message: `circuit breaker: stopped after ${this.#completedTurns} turns (${this.#consecutiveErrorTurns} consecutive tool-error turns)`,
203
+ };
204
+ }
205
+ else if (this.#repair === 'implementation' && this.#consecutiveNoMutationTurns >= this.#maxRepairNoProgressTurns) {
206
+ this.#tripped = {
207
+ reason: 'no_progress',
208
+ turn: this.#completedTurns,
209
+ path: '/circuit-breaker/repairNoProgress',
210
+ message: `circuit breaker: stopped after ${this.#completedTurns} turns (${this.#consecutiveNoMutationTurns} consecutive implementation-repair turns without successful write/edit)`,
211
+ };
212
+ }
213
+ return this.#tripped;
214
+ }
215
+ assertBeforeSend() {
216
+ if (this.#tripped !== null) {
217
+ refuse('REQUEST_REFUSED', this.#tripped.path, { phase: 'admission', stateErrorCode: 'BUDGET_EXHAUSTED' });
218
+ }
219
+ }
220
+ }
221
+ function resolveSessionMcpAllowlist(input, options) {
222
+ const role = input.lock.spec.contract.spec.roles.find(item => item.id === input.roleId);
223
+ if (!role)
224
+ refuse('BINDING_MISMATCH', '/roleId');
225
+ return createRoleMcpAllowlist({
226
+ roleTools: role.tools,
227
+ policyTools: input.policy.tools,
228
+ allowedServers: options?.allowedMcpServers,
229
+ });
230
+ }
231
+ const exec = promisify(execFile);
232
+ const probeEnv = { PATH: '/usr/bin:/bin:/usr/sbin', LANG: 'C' };
233
+ export function isSupportedHostSessionPlatform(platform = process.platform, arch = process.arch) {
234
+ return (platform === 'darwin' && arch === 'arm64') || (platform === 'linux' && (arch === 'arm64' || arch === 'x64'));
235
+ }
236
+ function resolveLockfileUrl() {
237
+ const direct = new URL('../../../package-lock.json', import.meta.url);
238
+ return existsSync(direct) ? direct : new URL('../../../../package-lock.json', import.meta.url);
239
+ }
240
+ function killProcessGroup(pid, includeLeader = true) {
241
+ if (pid && pid > 1) {
242
+ try {
243
+ process.kill(-pid, 'SIGKILL');
244
+ }
245
+ catch { /* already exited */ }
246
+ if (includeLeader) {
247
+ try {
248
+ process.kill(pid, 'SIGKILL');
249
+ }
250
+ catch { /* already exited */ }
251
+ }
252
+ }
253
+ }
254
+ function escapeSeatbeltString(value) {
255
+ if (/[\0\r\n]/.test(value))
256
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
257
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
258
+ }
259
+ function buildDarwinSeatbeltProfile(canonicalScratchDir, canonicalTmpDir) {
260
+ const scratch = escapeSeatbeltString(canonicalScratchDir);
261
+ const tmp = escapeSeatbeltString(canonicalTmpDir);
262
+ return [
263
+ '(version 1)',
264
+ '(allow default)',
265
+ '(deny network*)',
266
+ '(deny file-write*)',
267
+ `(allow file-write* (subpath "${scratch}") (subpath "${tmp}") (literal "/dev/null") (literal "/dev/zero") (literal "/dev/tty"))`,
268
+ ].join('\n');
269
+ }
270
+ let linuxBwrapSupported = null;
271
+ let linuxLandlockPythonPath = undefined;
272
+ const HOST_LANDLOCK_PROBE_SCRIPT = [
273
+ 'import ctypes, sys',
274
+ 'libc = ctypes.CDLL(None, use_errno=True)',
275
+ 'abi = libc.syscall(444, None, 0, 1)',
276
+ 'sys.exit(0 if abi >= 1 else 1)',
277
+ ].join('; ');
278
+ const HOST_LANDLOCK_BOOTSTRAP_SCRIPT = `import ctypes, json, os, signal, sys
279
+
280
+ libc = ctypes.CDLL(None, use_errno=True)
281
+ PR_SET_PDEATHSIG = 1
282
+ PR_SET_NO_NEW_PRIVS = 38
283
+ SYS_landlock_create_ruleset = 444
284
+ SYS_landlock_add_rule = 445
285
+ SYS_landlock_restrict_self = 446
286
+ LANDLOCK_CREATE_RULESET_VERSION = 1 << 0
287
+ LANDLOCK_RULE_PATH_BENEATH = 1
288
+
289
+ class RulesetAttrFsOnly(ctypes.Structure):
290
+ _fields_ = [("handled_access_fs", ctypes.c_uint64)]
291
+
292
+ class RulesetAttrWithNet(ctypes.Structure):
293
+ _fields_ = [("handled_access_fs", ctypes.c_uint64), ("handled_access_net", ctypes.c_uint64)]
294
+
295
+ class PathBeneathAttr(ctypes.Structure):
296
+ _pack_ = 1
297
+ _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]
298
+
299
+ cfg = json.loads(sys.argv[1])
300
+ cmd = sys.argv[2]
301
+
302
+ libc.prctl(PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0)
303
+ if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0:
304
+ sys.exit(126)
305
+
306
+ abi = libc.syscall(SYS_landlock_create_ruleset, None, 0, LANDLOCK_CREATE_RULESET_VERSION)
307
+ if abi < 1:
308
+ sys.exit(126)
309
+
310
+ FS_EXECUTE = 1 << 0
311
+ FS_WRITE_FILE = 1 << 1
312
+ FS_READ_FILE = 1 << 2
313
+ FS_READ_DIR = 1 << 3
314
+ FS_REMOVE_DIR = 1 << 4
315
+ FS_REMOVE_FILE = 1 << 5
316
+ FS_MAKE_CHAR = 1 << 6
317
+ FS_MAKE_DIR = 1 << 7
318
+ FS_MAKE_REG = 1 << 8
319
+ FS_MAKE_SOCK = 1 << 9
320
+ FS_MAKE_FIFO = 1 << 10
321
+ FS_MAKE_BLOCK = 1 << 11
322
+ FS_MAKE_SYM = 1 << 12
323
+ FS_REFER = 1 << 13 if abi >= 2 else 0
324
+ FS_TRUNCATE = 1 << 14 if abi >= 3 else 0
325
+
326
+ READ_ACCESS = FS_EXECUTE | FS_READ_FILE | FS_READ_DIR
327
+ WRITE_FILE_ACCESS = FS_WRITE_FILE | FS_TRUNCATE
328
+ WRITE_DIR_ACCESS = (
329
+ FS_WRITE_FILE | FS_REMOVE_DIR | FS_REMOVE_FILE | FS_MAKE_CHAR |
330
+ FS_MAKE_DIR | FS_MAKE_REG | FS_MAKE_SOCK | FS_MAKE_FIFO |
331
+ FS_MAKE_BLOCK | FS_MAKE_SYM | FS_REFER | FS_TRUNCATE
332
+ )
333
+ HANDLED_FS = READ_ACCESS | WRITE_DIR_ACCESS
334
+ HANDLED_NET = ((1 << 0) | (1 << 1)) if abi >= 4 else 0
335
+
336
+ attr = RulesetAttrWithNet(HANDLED_FS, HANDLED_NET) if abi >= 4 else RulesetAttrFsOnly(HANDLED_FS)
337
+ ruleset_fd = libc.syscall(SYS_landlock_create_ruleset, ctypes.byref(attr), ctypes.sizeof(attr), 0)
338
+ if ruleset_fd < 0:
339
+ sys.exit(126)
340
+
341
+ O_PATH = getattr(os, "O_PATH", 0o10000000)
342
+
343
+ def add_path_rule(path, access, required=False):
344
+ try:
345
+ fd = os.open(path, O_PATH | os.O_CLOEXEC)
346
+ except OSError:
347
+ if required:
348
+ sys.exit(126)
349
+ return
350
+ try:
351
+ actual = access if os.path.isdir(path) else (access & (FS_EXECUTE | FS_READ_FILE | WRITE_FILE_ACCESS))
352
+ if actual == 0:
353
+ return
354
+ rule = PathBeneathAttr(actual, fd)
355
+ if libc.syscall(SYS_landlock_add_rule, ruleset_fd, LANDLOCK_RULE_PATH_BENEATH, ctypes.byref(rule), 0) != 0 and required:
356
+ sys.exit(126)
357
+ finally:
358
+ os.close(fd)
359
+
360
+ def is_same_or_child(candidate, parent):
361
+ if parent == "/":
362
+ return True
363
+ return candidate == parent or candidate.startswith(parent + "/")
364
+
365
+ def grant_tree(current, excluded_set, access):
366
+ if current in excluded_set:
367
+ return
368
+ needs_split = any(ex != current and is_same_or_child(ex, current) for ex in excluded_set)
369
+ if not needs_split or not os.path.isdir(current) or os.path.islink(current):
370
+ add_path_rule(current, access)
371
+ return
372
+ try:
373
+ entries = os.listdir(current)
374
+ except OSError:
375
+ return
376
+ for name in entries:
377
+ child = "/" + name if current == "/" else current + "/" + name
378
+ grant_tree(child, excluded_set, access)
379
+
380
+ denied_reads = {p for p in cfg.get("deniedReadPaths", []) if os.path.exists(p)}
381
+ grant_tree("/", denied_reads, READ_ACCESS)
382
+
383
+ for dev in ("/dev/null", "/dev/zero", "/dev/tty"):
384
+ add_path_rule(dev, READ_ACCESS | WRITE_FILE_ACCESS)
385
+
386
+ add_path_rule(cfg["candidateDir"], READ_ACCESS, required=True)
387
+
388
+ for wp in (cfg["scratchDir"], cfg["tmpDir"]):
389
+ add_path_rule(wp, READ_ACCESS | WRITE_DIR_ACCESS, required=True)
390
+
391
+ if libc.syscall(SYS_landlock_restrict_self, ruleset_fd, 0) != 0:
392
+ os.close(ruleset_fd)
393
+ sys.exit(126)
394
+ os.close(ruleset_fd)
395
+
396
+ os.chdir(cfg["scratchDir"])
397
+ os.execvp("/bin/bash", ["/bin/bash", "-c", cmd])
398
+ `;
399
+ function canUseLinuxBwrap() {
400
+ if (process.platform !== 'linux')
401
+ return false;
402
+ if (linuxBwrapSupported !== null)
403
+ return linuxBwrapSupported;
404
+ if (!existsSync('/usr/bin/bwrap')) {
405
+ linuxBwrapSupported = false;
406
+ return false;
407
+ }
408
+ const probe = spawnSync('/usr/bin/bwrap', ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--unshare-pid', '--unshare-net', '--', '/bin/true'], { timeout: 2000, env: probeEnv, stdio: 'ignore' });
409
+ linuxBwrapSupported = probe.status === 0;
410
+ return linuxBwrapSupported;
411
+ }
412
+ function canUseLinuxLandlock() {
413
+ if (process.platform !== 'linux')
414
+ return null;
415
+ if (linuxLandlockPythonPath !== undefined)
416
+ return linuxLandlockPythonPath;
417
+ const python3 = existsSync('/usr/bin/python3')
418
+ ? '/usr/bin/python3'
419
+ : existsSync('/bin/python3')
420
+ ? '/bin/python3'
421
+ : null;
422
+ if (python3 === null) {
423
+ linuxLandlockPythonPath = null;
424
+ return null;
425
+ }
426
+ const probe = spawnSync(python3, ['-c', HOST_LANDLOCK_PROBE_SCRIPT], { timeout: 2000, env: probeEnv, stdio: 'ignore' });
427
+ linuxLandlockPythonPath = probe.status === 0 ? python3 : null;
428
+ return linuxLandlockPythonPath;
429
+ }
430
+ function buildHostToolBashSpawnSpec(options) {
431
+ if (process.env['LOOPWRIGHT_TEST_DISABLE_HOST_CONFINEMENT'] === '1') {
432
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
433
+ }
434
+ if (process.platform === 'darwin') {
435
+ if (options.seatbeltProfile !== null && existsSync('/usr/bin/sandbox-exec')) {
436
+ return { executable: '/usr/bin/sandbox-exec', args: ['-p', options.seatbeltProfile, '/bin/bash', '-c', options.command] };
437
+ }
438
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
439
+ }
440
+ if (process.platform === 'linux') {
441
+ if (canUseLinuxBwrap()) {
442
+ const stripTrailingSlashes = (rawPath) => rawPath.replace(/\/+$/, '');
443
+ const isUnderDevShm = (rawPath) => {
444
+ const normalized = stripTrailingSlashes(rawPath);
445
+ return normalized === '/dev/shm' || normalized.startsWith('/dev/shm/');
446
+ };
447
+ const hasWritableShmRoot = [options.scratchDir, options.tmpDir].some(rawPath => stripTrailingSlashes(rawPath) === '/dev/shm');
448
+ const isolateDevShm = [options.candidateDir, options.scratchDir, options.tmpDir].some(isUnderDevShm)
449
+ && !hasWritableShmRoot;
450
+ return {
451
+ executable: '/usr/bin/bwrap',
452
+ args: [
453
+ '--ro-bind', '/', '/',
454
+ '--dev', '/dev',
455
+ '--proc', '/proc',
456
+ ...(isolateDevShm ? ['--tmpfs', '/dev/shm'] : []),
457
+ '--ro-bind', options.candidateDir, options.candidateDir,
458
+ '--bind', options.scratchDir, options.scratchDir,
459
+ '--bind', options.tmpDir, options.tmpDir,
460
+ ...(isolateDevShm ? ['--remount-ro', '/dev/shm'] : []),
461
+ '--unshare-pid',
462
+ '--unshare-net',
463
+ '--die-with-parent',
464
+ '--chdir', options.scratchDir,
465
+ '--',
466
+ '/bin/bash', '-c', options.command,
467
+ ],
468
+ };
469
+ }
470
+ const landlockPython = canUseLinuxLandlock();
471
+ if (landlockPython !== null) {
472
+ const landlockConfig = JSON.stringify({
473
+ candidateDir: options.candidateDir,
474
+ scratchDir: options.scratchDir,
475
+ tmpDir: options.tmpDir,
476
+ deniedReadPaths: [`/proc/${process.pid}`, options.ownedRoot],
477
+ });
478
+ return {
479
+ executable: landlockPython,
480
+ args: ['-c', HOST_LANDLOCK_BOOTSTRAP_SCRIPT, landlockConfig, options.command],
481
+ };
482
+ }
483
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
484
+ }
485
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
486
+ }
487
+ async function birth(pid) {
488
+ try {
489
+ const result = await exec('/bin/ps', ['-p', String(pid), '-o', 'lstart='], {
490
+ timeout: 10000,
491
+ maxBuffer: 1024,
492
+ env: probeEnv,
493
+ });
494
+ const value = result.stdout.trim();
495
+ if (!value || value.length > 128 || result.stderr)
496
+ refuse('RECOVERY_REQUIRED');
497
+ return value;
498
+ }
499
+ catch (error) {
500
+ const value = error;
501
+ if (value.code === 1 && value.stdout === '' && value.stderr === '')
502
+ return null;
503
+ throw error;
504
+ }
505
+ }
506
+ async function boot() {
507
+ if (process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'x64')) {
508
+ let file = null;
509
+ try {
510
+ file = await open('/proc/sys/kernel/random/boot_id', constants.O_RDONLY | constants.O_NOFOLLOW);
511
+ const buffer = Buffer.alloc(64);
512
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
513
+ const raw = buffer.subarray(0, bytesRead).toString('utf8');
514
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n$/.test(raw))
515
+ refuse('RECOVERY_REQUIRED');
516
+ return raw.trim();
517
+ }
518
+ catch {
519
+ refuse('RECOVERY_REQUIRED');
520
+ }
521
+ finally {
522
+ await file?.close();
523
+ }
524
+ }
525
+ if (process.platform === 'darwin' && process.arch === 'arm64') {
526
+ const result = await exec('/usr/sbin/sysctl', ['-n', 'kern.boottime'], {
527
+ timeout: 10000,
528
+ maxBuffer: 1024,
529
+ env: probeEnv,
530
+ });
531
+ if (!/^\{ sec = \d+, usec = \d+ \} [^\r\n]+\n$/.test(result.stdout) || result.stderr)
532
+ refuse('RECOVERY_REQUIRED');
533
+ return result.stdout.trim();
534
+ }
535
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
536
+ }
537
+ const hostLeases = new WeakMap();
538
+ class HostExecutionLease {
539
+ host;
540
+ input;
541
+ #fd = null;
542
+ #tail = Promise.resolve();
543
+ #released = false;
544
+ #releasing = null;
545
+ #children = new Map();
546
+ token = randomBytes(16).toString('hex');
547
+ path;
548
+ constructor(host, input) {
549
+ this.host = host;
550
+ this.input = input;
551
+ this.path = join(host.artifactsDirectory, 'pi-execution-' + digest(Buffer.from(canonical({
552
+ storeId: stateValue(host.store.inspect()).storeId,
553
+ runId: input.lock.spec.runId,
554
+ }))).hex + '.ndjson');
555
+ }
556
+ static async acquire(host, input) {
557
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch)) {
558
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
559
+ }
560
+ const root = await lstat(host.artifactsDirectory);
561
+ if (!root.isDirectory() ||
562
+ root.isSymbolicLink() ||
563
+ root.uid !== process.getuid?.() ||
564
+ root.mode & 0o022 ||
565
+ (await realpath(host.artifactsDirectory)) !== resolve(host.artifactsDirectory)) {
566
+ refuse('INPUT_INVALID');
567
+ }
568
+ const lease = new HostExecutionLease(host, input);
569
+ const born = await birth(process.pid);
570
+ const bootIdentity = await boot();
571
+ if (!born)
572
+ refuse('RECOVERY_REQUIRED');
573
+ try {
574
+ lease.#fd = await open(lease.path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
575
+ }
576
+ catch (error) {
577
+ if (error.code !== 'EEXIST')
578
+ throw error;
579
+ let recovery;
580
+ try {
581
+ recovery = await open(lease.path + '.recovery', constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
582
+ }
583
+ catch {
584
+ refuse('SESSION_BUSY');
585
+ }
586
+ try {
587
+ await lease.#recover(bootIdentity);
588
+ lease.#fd = await open(lease.path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
589
+ }
590
+ finally {
591
+ await recovery.close();
592
+ await unlink(lease.path + '.recovery');
593
+ }
594
+ }
595
+ try {
596
+ const view = stateValue(host.store.inspect());
597
+ stateValue(host.store.renew(host.authority));
598
+ await lease.#append({
599
+ type: 'owner',
600
+ version: 2,
601
+ daemon: { kind: 'host-process-group', platform: process.platform, arch: process.arch },
602
+ token: lease.token,
603
+ pid: process.pid,
604
+ birth: born,
605
+ boot: bootIdentity,
606
+ authority: host.authority,
607
+ storeId: view.storeId,
608
+ runId: view.runId,
609
+ lockHash: view.lockHash,
610
+ clockBasis: view.clock.basis,
611
+ });
612
+ await lease.#syncParent();
613
+ hostLeases.set(host, lease);
614
+ return lease;
615
+ }
616
+ catch (error) {
617
+ await lease.#fd?.close();
618
+ lease.#fd = null;
619
+ await unlink(lease.path);
620
+ throw error;
621
+ }
622
+ }
623
+ async #syncParent() {
624
+ const fd = await open(this.host.artifactsDirectory, constants.O_RDONLY | constants.O_NOFOLLOW);
625
+ try {
626
+ await fd.sync();
627
+ }
628
+ finally {
629
+ await fd.close();
630
+ }
631
+ }
632
+ async #append(value) {
633
+ if (!this.#fd || this.#released)
634
+ refuse('RECOVERY_REQUIRED');
635
+ const bytes = Buffer.from(JSON.stringify(value) + '\n');
636
+ if ((await this.#fd.stat()).size + bytes.length > 2097152)
637
+ refuse('OUTPUT_LIMIT');
638
+ await this.#fd.writeFile(bytes);
639
+ await this.#fd.sync();
640
+ }
641
+ async #recover(bootIdentity) {
642
+ const fd = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
643
+ let rows;
644
+ let inode;
645
+ try {
646
+ const info = await fd.stat();
647
+ inode = info.ino;
648
+ if (!info.isFile() || info.uid !== process.getuid?.() || info.mode & 0o077 || info.nlink !== 1 || info.size > 2097152) {
649
+ refuse('RECOVERY_REQUIRED');
650
+ }
651
+ const content = await fd.readFile('utf8');
652
+ if (!content.endsWith('\n'))
653
+ refuse('RECOVERY_REQUIRED');
654
+ rows = content.slice(0, -1).split('\n').map(row => parseBoundedJson(row));
655
+ }
656
+ finally {
657
+ await fd.close();
658
+ }
659
+ const first = rows[0];
660
+ if (!first || first.version !== 2)
661
+ refuse('RECOVERY_REQUIRED');
662
+ try {
663
+ object(first, ['type', 'version', 'daemon', 'token', 'pid', 'birth', 'boot', 'authority', 'storeId', 'runId', 'lockHash', 'clockBasis']);
664
+ }
665
+ catch {
666
+ refuse('RECOVERY_REQUIRED');
667
+ }
668
+ let daemon;
669
+ try {
670
+ daemon = object(first.daemon, ['kind', 'platform', 'arch']);
671
+ }
672
+ catch {
673
+ refuse('RECOVERY_REQUIRED');
674
+ }
675
+ if (daemon.kind !== 'host-process-group' ||
676
+ daemon.platform !== process.platform ||
677
+ daemon.arch !== process.arch ||
678
+ !isSupportedHostSessionPlatform(daemon.platform, daemon.arch)) {
679
+ refuse('RECOVERY_REQUIRED');
680
+ }
681
+ const view = stateValue(this.host.store.inspect());
682
+ if (first.type !== 'owner' ||
683
+ !Number.isSafeInteger(first.pid) ||
684
+ first.pid < 1 ||
685
+ typeof first.birth !== 'string' ||
686
+ typeof first.token !== 'string' ||
687
+ !/^[a-f0-9]{32}$/.test(first.token) ||
688
+ first.boot !== bootIdentity ||
689
+ first.storeId !== view.storeId ||
690
+ first.runId !== view.runId ||
691
+ !sameIdentity(first.lockHash, view.lockHash) ||
692
+ !sameIdentity(first.clockBasis, view.clock.basis)) {
693
+ refuse('RECOVERY_REQUIRED');
694
+ }
695
+ const authority = object(first.authority, ['storeId', 'runId', 'lockHash', 'ownerId', 'generation', 'nonce']);
696
+ if (authority.storeId !== view.storeId ||
697
+ authority.runId !== view.runId ||
698
+ !sameIdentity(authority.lockHash, view.lockHash) ||
699
+ !Number.isSafeInteger(authority.generation) ||
700
+ authority.generation > this.host.authority.generation) {
701
+ refuse('RECOVERY_REQUIRED');
702
+ }
703
+ const currentBirth = await birth(first.pid);
704
+ if (currentBirth !== null)
705
+ refuse(currentBirth === first.birth ? 'SESSION_BUSY' : 'RECOVERY_REQUIRED');
706
+ try {
707
+ process.kill(first.pid, 0);
708
+ refuse('RECOVERY_REQUIRED');
709
+ }
710
+ catch (error) {
711
+ if (error.code !== 'ESRCH')
712
+ throw error;
713
+ }
714
+ const intents = new Map();
715
+ const attaches = new Map();
716
+ const receipts = [];
717
+ for (const row of rows.slice(1)) {
718
+ if (row.type === 'child') {
719
+ const item = object(row, ['type', 'name', 'nonce', 'role', 'labels']);
720
+ if (typeof item.name !== 'string' ||
721
+ !/^lw-pi-(?:tool-)?[a-f0-9]{32}$/.test(item.name) ||
722
+ typeof item.nonce !== 'string' ||
723
+ !/^[a-f0-9]{32}$/.test(item.nonce) ||
724
+ (item.role !== 'sdk' && item.role !== 'tool')) {
725
+ refuse('RECOVERY_REQUIRED');
726
+ }
727
+ const labels = item.labels;
728
+ if (!labels ||
729
+ labels['org.loopwright.run'] !== view.runId ||
730
+ labels['org.loopwright.nonce'] !== item.nonce ||
731
+ labels['org.loopwright.generation'] !== String(authority.generation) ||
732
+ intents.has(item.nonce)) {
733
+ refuse('RECOVERY_REQUIRED');
734
+ }
735
+ intents.set(item.nonce, item);
736
+ }
737
+ else if (row.type === 'attach') {
738
+ object(row, ['type', 'nonce', 'pid', 'birth']);
739
+ if (typeof row.nonce !== 'string' ||
740
+ !intents.has(row.nonce) ||
741
+ attaches.has(row.nonce) ||
742
+ !Number.isSafeInteger(row.pid) ||
743
+ row.pid < 1 ||
744
+ typeof row.birth !== 'string' ||
745
+ !row.birth) {
746
+ refuse('RECOVERY_REQUIRED');
747
+ }
748
+ attaches.set(row.nonce, { pid: row.pid, birth: row.birth });
749
+ }
750
+ else if (row.type === 'exit') {
751
+ object(row, ['type', 'nonce']);
752
+ if (typeof row.nonce !== 'string' || !intents.delete(row.nonce))
753
+ refuse('RECOVERY_REQUIRED');
754
+ attaches.delete(row.nonce);
755
+ }
756
+ else {
757
+ refuse('RECOVERY_REQUIRED');
758
+ }
759
+ }
760
+ stateValue(this.host.store.renew(this.host.authority));
761
+ for (const intent of intents.values()) {
762
+ const attach = attaches.get(intent.nonce);
763
+ if (!attach) {
764
+ receipts.push({ name: intent.name, nonce: intent.nonce, absent: true, cli: null });
765
+ continue;
766
+ }
767
+ const observed = await birth(attach.pid);
768
+ if (observed !== null && observed !== attach.birth) {
769
+ refuse('CLEANUP_FAILED');
770
+ }
771
+ if (observed === attach.birth) {
772
+ killProcessGroup(attach.pid, true);
773
+ }
774
+ else if (observed === null) {
775
+ killProcessGroup(attach.pid, false);
776
+ }
777
+ const deadline = performance.now() + 2000;
778
+ for (;;) {
779
+ const current = await birth(attach.pid);
780
+ if (current === null) {
781
+ try {
782
+ process.kill(attach.pid, 0);
783
+ refuse('RECOVERY_REQUIRED');
784
+ }
785
+ catch (error) {
786
+ if (error.code !== 'ESRCH')
787
+ refuse('RECOVERY_REQUIRED');
788
+ }
789
+ break;
790
+ }
791
+ if (current !== attach.birth || performance.now() >= deadline)
792
+ refuse('CLEANUP_FAILED');
793
+ await new Promise(resolvePromise => setTimeout(resolvePromise, 50));
794
+ }
795
+ receipts.push({
796
+ name: intent.name,
797
+ nonce: intent.nonce,
798
+ removed: true,
799
+ cli: { pid: attach.pid, birth: attach.birth, deathConfirmed: true },
800
+ });
801
+ }
802
+ const record = await open(join(this.host.artifactsDirectory, 'pi-recovery-' + first.token + '.json'), constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
803
+ try {
804
+ await record.writeFile(JSON.stringify({
805
+ version: 1,
806
+ priorPid: first.pid,
807
+ priorBirth: first.birth,
808
+ boot: first.boot,
809
+ deathConfirmed: true,
810
+ receipts,
811
+ }));
812
+ await record.sync();
813
+ }
814
+ finally {
815
+ await record.close();
816
+ }
817
+ const now = await lstat(this.path);
818
+ if (now.ino !== inode || now.nlink !== 1)
819
+ refuse('RECOVERY_REQUIRED');
820
+ await unlink(this.path);
821
+ await this.#syncParent();
822
+ }
823
+ register(intent) {
824
+ const next = this.#tail.then(async () => {
825
+ stateValue(this.host.store.renew(this.host.authority));
826
+ if (this.#children.has(intent.nonce))
827
+ refuse('RECOVERY_REQUIRED');
828
+ await this.#append({ type: 'child', ...intent });
829
+ this.#children.set(intent.nonce, intent);
830
+ });
831
+ this.#tail = next.catch(() => { });
832
+ return next;
833
+ }
834
+ attach(nonce, pid, allowAlreadyExited = false) {
835
+ const next = this.#tail.then(async () => {
836
+ if (!this.#children.has(nonce))
837
+ refuse('RECOVERY_REQUIRED');
838
+ const born = await birth(pid);
839
+ if (!born) {
840
+ if (allowAlreadyExited)
841
+ return;
842
+ refuse('RECOVERY_REQUIRED');
843
+ }
844
+ await this.#append({ type: 'attach', nonce, pid, birth: born });
845
+ });
846
+ this.#tail = next.catch(() => { });
847
+ return next;
848
+ }
849
+ exit(nonce) {
850
+ const next = this.#tail.then(async () => {
851
+ if (!this.#children.has(nonce))
852
+ refuse('RECOVERY_REQUIRED');
853
+ await this.#append({ type: 'exit', nonce });
854
+ this.#children.delete(nonce);
855
+ });
856
+ this.#tail = next.catch(() => { });
857
+ return next;
858
+ }
859
+ release() {
860
+ return this.#releasing ??= this.#release();
861
+ }
862
+ async #release() {
863
+ await this.#tail;
864
+ if (this.#released)
865
+ return;
866
+ if (this.#children.size || !this.#fd)
867
+ refuse('CLEANUP_FAILED');
868
+ const fdStat = await this.#fd.stat();
869
+ const current = await lstat(this.path);
870
+ if (current.ino !== fdStat.ino || current.nlink !== 1)
871
+ refuse('RECOVERY_REQUIRED');
872
+ await this.#fd.close();
873
+ this.#fd = null;
874
+ await unlink(this.path);
875
+ await this.#syncParent();
876
+ this.#released = true;
877
+ hostLeases.delete(this.host);
878
+ }
879
+ }
880
+ async function registerChild(host, intent) {
881
+ const lease = hostLeases.get(host);
882
+ if (!lease)
883
+ refuse('RECOVERY_REQUIRED');
884
+ await lease.register(intent);
885
+ }
886
+ async function registerAttach(host, nonce, pid, allowAlreadyExited = false) {
887
+ const lease = hostLeases.get(host);
888
+ if (!lease || !pid)
889
+ refuse('RECOVERY_REQUIRED');
890
+ await lease.attach(nonce, pid, allowAlreadyExited);
891
+ }
892
+ async function exitChild(host, nonce) {
893
+ const lease = hostLeases.get(host);
894
+ if (!lease)
895
+ refuse('RECOVERY_REQUIRED');
896
+ await lease.exit(nonce);
897
+ }
898
+ function textResult(value) {
899
+ return {
900
+ content: value.content.map(block => {
901
+ if (block.type !== 'text')
902
+ refuse('TOOL_DENIED');
903
+ return { type: 'text', text: block.text };
904
+ }),
905
+ details: value.details ?? null,
906
+ ...(value.isError ? { isError: true } : {}),
907
+ ...(value.structuredContent === undefined ? {} : { structuredContent: value.structuredContent }),
908
+ };
909
+ }
910
+ class HostToolProcess {
911
+ host;
912
+ input;
913
+ directory;
914
+ candidate;
915
+ operationId;
916
+ signal;
917
+ nonce = randomBytes(16).toString('hex');
918
+ name;
919
+ labels;
920
+ #cancel = new AbortController();
921
+ #bootWork = null;
922
+ #closing = false;
923
+ #readyComplete = false;
924
+ #used = false;
925
+ #scratchDir = '';
926
+ #tmpDir = '';
927
+ #ownedRoot = '';
928
+ #seatbeltProfile = null;
929
+ #canonicalCandidate = '';
930
+ #activeChild = null;
931
+ #activeExit = null;
932
+ #registeredChild = false;
933
+ #exitCode = 0;
934
+ #receipt = null;
935
+ #closedWork = null;
936
+ #onAbort;
937
+ constructor(host, input, directory, candidate, operationId, signal) {
938
+ this.host = host;
939
+ this.input = input;
940
+ this.directory = directory;
941
+ this.candidate = candidate;
942
+ this.operationId = operationId;
943
+ this.signal = signal;
944
+ this.name = 'lw-pi-tool-' + this.nonce;
945
+ this.labels = Object.freeze({
946
+ 'org.loopwright.generation': String(host.authority.generation),
947
+ 'org.loopwright.run': input.lock.spec.runId,
948
+ 'org.loopwright.session': input.sessionId,
949
+ 'org.loopwright.nonce': this.nonce,
950
+ 'org.loopwright.role': 'tool',
951
+ 'org.loopwright.operation': operationId,
952
+ });
953
+ this.#onAbort = () => {
954
+ this.#cancel.abort();
955
+ const running = this.#activeChild !== null && this.#activeChild.exitCode === null && this.#activeChild.signalCode === null;
956
+ killProcessGroup(this.#activeChild?.pid, running);
957
+ };
958
+ signal.addEventListener('abort', this.#onAbort, { once: true });
959
+ }
960
+ ready() {
961
+ if (this.#bootWork || this.#closing)
962
+ refuse('SESSION_BUSY');
963
+ const work = this.#boot();
964
+ this.#bootWork = work;
965
+ return work;
966
+ }
967
+ async #boot() {
968
+ this.signal.throwIfAborted();
969
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch) || !/^v26\./.test(process.version)) {
970
+ refuse('RUNTIME_MISMATCH', '', { phase: 'tool' });
971
+ }
972
+ if (!sameIdentity(await profileIdentity(), this.input.policy.runtime.configDigest) ||
973
+ !sameIdentity(digest(await readFile(resolveLockfileUrl())), this.input.policy.runtime.graphDigest)) {
974
+ refuse('RUNTIME_MISMATCH', '', { phase: 'tool' });
975
+ }
976
+ const resolvedCandidate = await realpath(this.candidate);
977
+ if (resolvedCandidate !== resolve(this.candidate) || !(await stat(this.candidate)).isDirectory()) {
978
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
979
+ }
980
+ this.#canonicalCandidate = resolvedCandidate;
981
+ this.#ownedRoot = await canonicalDirectory(this.host.directory);
982
+ await mkdir(this.directory, { mode: 0o700 });
983
+ const canonicalToolDir = await canonicalDirectory(this.directory);
984
+ this.#scratchDir = join(canonicalToolDir, 'scratch');
985
+ this.#tmpDir = join(canonicalToolDir, 'tmp');
986
+ await mkdir(this.#scratchDir, { mode: 0o700 });
987
+ await mkdir(this.#tmpDir, { mode: 0o700 });
988
+ await symlink(this.#canonicalCandidate, join(this.#scratchDir, 'candidate'));
989
+ this.#seatbeltProfile = process.platform === 'darwin' && existsSync('/usr/bin/sandbox-exec')
990
+ ? buildDarwinSeatbeltProfile(this.#scratchDir, this.#tmpDir)
991
+ : null;
992
+ this.#readyComplete = true;
993
+ }
994
+ async execute(name, bytes, read, guard) {
995
+ if (!this.#readyComplete || this.#closing || this.#used)
996
+ refuse('RECOVERY_REQUIRED', '', { phase: 'tool' });
997
+ this.#used = true;
998
+ const fileBytes = integer(this.input.policy.limits.fileBytes, 1, OVERLAY_LIMITS.maxMaxBytes);
999
+ const readFileMaxBytes = Math.min(fileBytes, LIMITS.artifactBytes);
1000
+ const resultBytes = integer(this.input.policy.limits.toolResultBytes, 1, 4194304);
1001
+ const wallMs = integer(this.input.policy.limits.toolWallMs, 1, 1800000);
1002
+ guard();
1003
+ let produced = 0;
1004
+ let overflow = false;
1005
+ let code = null;
1006
+ let rawResult;
1007
+ try {
1008
+ if (bytes.length > 4194304)
1009
+ refuse('OUTPUT_LIMIT');
1010
+ const args = parseBoundedJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes), { nodes: 262144, array: 4096, properties: 512 });
1011
+ if (name === 'read') {
1012
+ if (typeof read?.path !== 'string' ||
1013
+ !read.path ||
1014
+ !/^(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/.test(read.path) ||
1015
+ read.path.split('/').some(part => part === '.' || part === '..')) {
1016
+ refuse('TOOL_DENIED');
1017
+ }
1018
+ const expectedPath = join(this.#canonicalCandidate, read.path);
1019
+ const expectedDigest = read.digest;
1020
+ const check = async (targetPath) => {
1021
+ if (targetPath !== expectedPath)
1022
+ refuse('TOOL_DENIED');
1023
+ const info = await lstat(targetPath);
1024
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > readFileMaxBytes)
1025
+ refuse('TOOL_DENIED');
1026
+ };
1027
+ const readTool = createReadTool(this.#canonicalCandidate, {
1028
+ autoResizeImages: false,
1029
+ operations: {
1030
+ access: check,
1031
+ detectImageMimeType: async () => null,
1032
+ readFile: async (targetPath) => {
1033
+ await check(targetPath);
1034
+ const fd = await open(targetPath, constants.O_RDONLY | constants.O_NOFOLLOW);
1035
+ try {
1036
+ const info = await fd.stat();
1037
+ if (!info.isFile() || info.nlink !== 1 || info.size > readFileMaxBytes)
1038
+ refuse('TOOL_DENIED');
1039
+ const buf = Buffer.alloc(info.size + 1);
1040
+ let offset = 0;
1041
+ while (offset < buf.length) {
1042
+ const next = await fd.read(buf, offset, buf.length - offset, offset);
1043
+ if (!next.bytesRead)
1044
+ break;
1045
+ offset += next.bytesRead;
1046
+ }
1047
+ const data = buf.subarray(0, offset);
1048
+ if (offset !== info.size || digest(data).hex !== expectedDigest)
1049
+ refuse('RECOVERY_REQUIRED');
1050
+ new TextDecoder('utf-8', { fatal: true }).decode(data);
1051
+ return data;
1052
+ }
1053
+ finally {
1054
+ await fd.close();
1055
+ }
1056
+ },
1057
+ },
1058
+ });
1059
+ rawResult = clampToolResultBytes(textResult(await readTool.execute('owned-read', { ...args, path: read.path }, this.#cancel.signal)), resultBytes, { tool: 'read', offset: args.offset });
1060
+ }
1061
+ else if (name === 'bash') {
1062
+ const candidateDir = this.#canonicalCandidate;
1063
+ const scratchDir = this.#scratchDir;
1064
+ const tmpDir = this.#tmpDir;
1065
+ const ownedRoot = this.#ownedRoot;
1066
+ const seatbeltProfile = this.#seatbeltProfile;
1067
+ const cleanEnv = {
1068
+ PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin',
1069
+ HOME: scratchDir,
1070
+ TMPDIR: tmpDir,
1071
+ CANDIDATE_DIR: candidateDir,
1072
+ LANG: 'C.UTF-8',
1073
+ LC_ALL: 'C.UTF-8',
1074
+ TERM: 'dumb',
1075
+ };
1076
+ const outputAbort = new AbortController();
1077
+ const bashTool = createBashTool(scratchDir, {
1078
+ exposeSessionEnvironment: false,
1079
+ shellPath: '/bin/bash',
1080
+ operations: {
1081
+ exec: async (command, cwd, options) => {
1082
+ if (cwd !== scratchDir)
1083
+ refuse('TOOL_DENIED');
1084
+ const timeoutMs = options.timeout && options.timeout > 0 ? Math.min(wallMs, options.timeout * 1000) : wallMs;
1085
+ const wallTimeout = AbortSignal.timeout(timeoutMs);
1086
+ const combined = AbortSignal.any([
1087
+ this.signal,
1088
+ this.#cancel.signal,
1089
+ outputAbort.signal,
1090
+ wallTimeout,
1091
+ ...(options.signal ? [options.signal] : []),
1092
+ ]);
1093
+ combined.throwIfAborted();
1094
+ const spawnSpec = buildHostToolBashSpawnSpec({
1095
+ candidateDir,
1096
+ scratchDir,
1097
+ tmpDir,
1098
+ ownedRoot,
1099
+ seatbeltProfile,
1100
+ command,
1101
+ });
1102
+ await registerChild(this.host, { name: this.name, nonce: this.nonce, role: 'tool', labels: this.labels });
1103
+ this.#registeredChild = true;
1104
+ const child = spawn(spawnSpec.executable, spawnSpec.args, {
1105
+ cwd: scratchDir,
1106
+ env: cleanEnv,
1107
+ detached: true,
1108
+ stdio: ['ignore', 'pipe', 'pipe'],
1109
+ });
1110
+ this.#activeChild = child;
1111
+ let resolveExit;
1112
+ this.#activeExit = new Promise(resolvePromise => { resolveExit = resolvePromise; });
1113
+ const onData = (chunk) => {
1114
+ const prevProduced = produced;
1115
+ produced += chunk.length;
1116
+ if (prevProduced < resultBytes) {
1117
+ options.onData(produced > resultBytes ? chunk.subarray(0, resultBytes - prevProduced) : chunk);
1118
+ }
1119
+ if (produced > resultBytes * 4) {
1120
+ overflow = true;
1121
+ outputAbort.abort();
1122
+ killProcessGroup(child.pid, child.exitCode === null && child.signalCode === null);
1123
+ }
1124
+ };
1125
+ child.stdout.on('data', onData);
1126
+ child.stderr.on('data', onData);
1127
+ child.once('exit', () => {
1128
+ killProcessGroup(child.pid, false);
1129
+ });
1130
+ const closePromise = new Promise((resolveClose, rejectClose) => {
1131
+ child.once('error', err => {
1132
+ resolveExit();
1133
+ rejectClose(err);
1134
+ });
1135
+ child.once('close', exit => {
1136
+ resolveExit();
1137
+ resolveClose(exit);
1138
+ });
1139
+ });
1140
+ void closePromise.catch(() => { });
1141
+ const onAbort = () => {
1142
+ killProcessGroup(child.pid, child.exitCode === null && child.signalCode === null);
1143
+ };
1144
+ combined.addEventListener('abort', onAbort, { once: true });
1145
+ if (combined.aborted)
1146
+ onAbort();
1147
+ let exitCode;
1148
+ try {
1149
+ if (child.pid && child.exitCode === null && child.signalCode === null) {
1150
+ await registerAttach(this.host, this.nonce, child.pid, true);
1151
+ }
1152
+ exitCode = await closePromise;
1153
+ }
1154
+ catch (err) {
1155
+ killProcessGroup(child.pid, child.exitCode === null && child.signalCode === null);
1156
+ throw err;
1157
+ }
1158
+ finally {
1159
+ combined.removeEventListener('abort', onAbort);
1160
+ }
1161
+ killProcessGroup(child.pid, false);
1162
+ if (this.signal.aborted || this.#cancel.signal.aborted)
1163
+ refuse('CANCELLED');
1164
+ if (wallTimeout.aborted)
1165
+ refuse('CANCELLED');
1166
+ return { exitCode: overflow ? 0 : exitCode };
1167
+ },
1168
+ },
1169
+ });
1170
+ const executedBash = textResult(await bashTool.execute('owned-bash', args, this.#cancel.signal));
1171
+ const bashWithOverflowNote = produced > resultBytes
1172
+ ? {
1173
+ ...executedBash,
1174
+ content: [
1175
+ {
1176
+ type: 'text',
1177
+ text: executedBash.content.map(item => item.text).join('\n')
1178
+ + `\n\n[Command output (${produced} bytes)${overflow ? ' exceeded stream cap and was terminated early;' : ''} truncated to fit tool result byte limit.]`,
1179
+ },
1180
+ ],
1181
+ }
1182
+ : executedBash;
1183
+ rawResult = clampToolResultBytes(bashWithOverflowNote, resultBytes, { tool: 'bash' });
1184
+ }
1185
+ else {
1186
+ refuse('TOOL_DENIED');
1187
+ }
1188
+ if (Buffer.byteLength(canonical(rawResult)) > resultBytes || rawResult.content.some(item => item.type !== 'text')) {
1189
+ refuse('OUTPUT_LIMIT');
1190
+ }
1191
+ }
1192
+ catch (error) {
1193
+ if (error instanceof PiFailure && error.detail.code === 'CONTAINMENT_MISMATCH') {
1194
+ throw error;
1195
+ }
1196
+ code = overflow
1197
+ ? 'OUTPUT_LIMIT'
1198
+ : (this.signal.aborted || this.#cancel.signal.aborted)
1199
+ ? 'CANCELLED'
1200
+ : error instanceof PiFailure
1201
+ ? error.detail.code
1202
+ : 'TOOL_DENIED';
1203
+ rawResult = { content: [{ type: 'text', text: code }], isError: true, details: null };
1204
+ }
1205
+ if (code !== null && !['TOOL_DENIED', 'OUTPUT_LIMIT', 'CANCELLED', 'RECOVERY_REQUIRED'].includes(code)) {
1206
+ refuse('RECOVERY_REQUIRED', '', { phase: 'tool', effect: 'possible' });
1207
+ }
1208
+ const raw = rawResult;
1209
+ const keys = Object.keys(raw);
1210
+ if (!keys.includes('content') ||
1211
+ !keys.includes('details') ||
1212
+ keys.some(key => !['content', 'details', 'structuredContent', 'isError'].includes(key)) ||
1213
+ Buffer.byteLength(canonical(raw)) > resultBytes) {
1214
+ refuse('OUTPUT_LIMIT', '', { phase: 'tool', effect: 'possible' });
1215
+ }
1216
+ const validated = object(raw, keys);
1217
+ if (validated.isError !== undefined && typeof validated.isError !== 'boolean') {
1218
+ refuse('RECOVERY_REQUIRED', '', { phase: 'tool', effect: 'possible' });
1219
+ }
1220
+ const content = list(validated.content, 16, '/content').map(item => {
1221
+ const block = object(item, ['type', 'text']);
1222
+ if (block.type !== 'text' || typeof block.text !== 'string')
1223
+ refuse('TOOL_DENIED', '', { phase: 'tool' });
1224
+ return { type: 'text', text: block.text };
1225
+ });
1226
+ return {
1227
+ result: { ...validated, content, details: validated.details },
1228
+ code,
1229
+ produced,
1230
+ };
1231
+ }
1232
+ close() {
1233
+ if (this.#receipt)
1234
+ return Promise.resolve(this.#receipt);
1235
+ if (this.#closedWork)
1236
+ return this.#closedWork;
1237
+ const work = this.#cleanup();
1238
+ this.#closedWork = work;
1239
+ void work.catch(() => { this.#closedWork = null; });
1240
+ return work;
1241
+ }
1242
+ async #cleanup() {
1243
+ this.#closing = true;
1244
+ this.signal.removeEventListener('abort', this.#onAbort);
1245
+ this.#cancel.abort();
1246
+ await this.#bootWork?.catch(() => { });
1247
+ if (this.#activeChild) {
1248
+ const running = this.#activeChild.exitCode === null && this.#activeChild.signalCode === null;
1249
+ killProcessGroup(this.#activeChild.pid, running);
1250
+ }
1251
+ if (this.#activeExit) {
1252
+ let timer;
1253
+ try {
1254
+ await Promise.race([
1255
+ this.#activeExit,
1256
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Host tool process cleanup deadline')), 2000); }),
1257
+ ]);
1258
+ }
1259
+ finally {
1260
+ clearTimeout(timer);
1261
+ }
1262
+ killProcessGroup(this.#activeChild?.pid, false);
1263
+ }
1264
+ if (this.#registeredChild) {
1265
+ await exitChild(this.host, this.nonce);
1266
+ this.#registeredChild = false;
1267
+ }
1268
+ if (this.#scratchDir) {
1269
+ await unlink(join(this.#scratchDir, 'candidate')).catch(() => { });
1270
+ }
1271
+ if (!this.#readyComplete)
1272
+ return null;
1273
+ const receipt = {
1274
+ id: digest(Buffer.from(this.nonce)).hex,
1275
+ exitCode: this.#exitCode,
1276
+ removed: true,
1277
+ cli: { code: this.#exitCode, signal: null },
1278
+ };
1279
+ await writeFile(join(this.directory, 'cleanup.json'), JSON.stringify(receipt), { mode: 0o600 });
1280
+ this.#receipt = receipt;
1281
+ return receipt;
1282
+ }
1283
+ }
1284
+ class HostExecution extends Execution {
1285
+ candidateDir;
1286
+ onProgress;
1287
+ onToolEnd;
1288
+ onScrub;
1289
+ getConvergenceWarning;
1290
+ #gate = Promise.resolve();
1291
+ constructor(host, input, candidateDir, ports, onProgress, onToolEnd, onScrub, getConvergenceWarning) {
1292
+ super(host, input, candidateDir, { ...ports, softScopeErrors: true, softArgumentErrors: true });
1293
+ this.candidateDir = candidateDir;
1294
+ this.onProgress = onProgress;
1295
+ this.onToolEnd = onToolEnd;
1296
+ this.onScrub = onScrub;
1297
+ this.getConvergenceWarning = getConvergenceWarning;
1298
+ }
1299
+ #extractTargetPath(identity, bytes) {
1300
+ if (!this.input.policy.tools.includes(identity.name))
1301
+ return null;
1302
+ if (bytes.byteLength > this.input.policy.limits.toolArgsBytes)
1303
+ return null;
1304
+ try {
1305
+ const value = parseBoundedJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes), { nodes: 262144, array: 4096, properties: 512 });
1306
+ if (!value || typeof value !== 'object' || Array.isArray(value))
1307
+ return null;
1308
+ const args = object(value, Object.keys(value));
1309
+ if (typeof args.path !== 'string' || !args.path)
1310
+ return null;
1311
+ return this.candidate.normalize(args.path);
1312
+ }
1313
+ catch {
1314
+ return null;
1315
+ }
1316
+ }
1317
+ #summarizeToolArgs(identity, bytes) {
1318
+ if (!this.onProgress)
1319
+ return undefined;
1320
+ return summarizeToolProgressArgs(identity.name, bytes, Math.min(this.input.policy.limits.toolArgsBytes, SUMMARY_MAX_ARGS_BYTES), raw => this.candidate.enforceHardPathInvariants(raw, { allowRootAlias: identity.name === 'read' }), this.onScrub);
1321
+ }
1322
+ invoke(identity, bytes, signal, onOperation) {
1323
+ const emitProgress = (event) => {
1324
+ try {
1325
+ this.onProgress?.(event);
1326
+ }
1327
+ catch {
1328
+ // Progress observers must never perturb session execution.
1329
+ }
1330
+ };
1331
+ const summary = this.#summarizeToolArgs(identity, bytes);
1332
+ const wrapProgress = async (work) => {
1333
+ const started = performance.now();
1334
+ emitProgress({ kind: 'tool_start', name: identity.name, ...(summary !== undefined ? { summary } : {}) });
1335
+ try {
1336
+ const res = await work();
1337
+ const isError = res.isError === true;
1338
+ this.onToolEnd?.(identity.name, isError);
1339
+ emitProgress({
1340
+ kind: 'tool_end',
1341
+ name: identity.name,
1342
+ isError,
1343
+ elapsedMs: Math.max(1, Math.round(performance.now() - started)),
1344
+ ...(summary !== undefined ? { summary } : {}),
1345
+ });
1346
+ const warning = this.getConvergenceWarning?.() ?? null;
1347
+ if (warning !== null) {
1348
+ const content = res.content.length > 0
1349
+ ? res.content.map((item, idx) => idx === res.content.length - 1
1350
+ ? { ...item, text: item.text.length > 0 ? `${item.text}\n\n${warning}` : warning }
1351
+ : item)
1352
+ : [{ type: 'text', text: warning }];
1353
+ const annotated = { ...res, content };
1354
+ if (Buffer.byteLength(canonical(annotated)) <= this.input.policy.limits.toolResultBytes) {
1355
+ return annotated;
1356
+ }
1357
+ }
1358
+ return res;
1359
+ }
1360
+ catch (error) {
1361
+ const errorCode = error instanceof PiFailure ? error.detail.code : undefined;
1362
+ const errorPath = error instanceof PiFailure && error.detail.path.length > 0 ? error.detail.path : undefined;
1363
+ this.onToolEnd?.(identity.name, true);
1364
+ emitProgress({
1365
+ kind: 'tool_end',
1366
+ name: identity.name,
1367
+ isError: true,
1368
+ elapsedMs: Math.max(1, Math.round(performance.now() - started)),
1369
+ ...(summary !== undefined ? { summary } : {}),
1370
+ ...(errorCode !== undefined ? { errorCode } : {}),
1371
+ ...(errorPath !== undefined ? { errorPath } : {}),
1372
+ });
1373
+ throw error;
1374
+ }
1375
+ };
1376
+ if (identity.name !== 'write' && identity.name !== 'edit' && identity.name !== 'delete') {
1377
+ const plain = this.#gate.then(() => wrapProgress(() => super.invoke(identity, bytes, signal, onOperation)));
1378
+ this.#gate = plain.then(() => { }, () => { });
1379
+ return plain;
1380
+ }
1381
+ const mediated = this.#gate.then(async () => {
1382
+ const relPath = this.#extractTargetPath(identity, bytes);
1383
+ const writable = relPath !== null && this.candidate.isWritable(relPath);
1384
+ if (relPath === null || !writable) {
1385
+ return await wrapProgress(() => super.invoke(identity, bytes, signal, onOperation));
1386
+ }
1387
+ const segments = relPath.split('/').slice(0, -1);
1388
+ const chain = [this.candidateDir, ...segments.map((_, index) => join(this.candidateDir, ...segments.slice(0, index + 1)))];
1389
+ const unlockedDirs = [];
1390
+ const absentBeforeOp = new Set();
1391
+ let stoppedAtNonDir = false;
1392
+ let result;
1393
+ let opFailed = false;
1394
+ let opError;
1395
+ this.candidate.clearLastPrunedDirectories();
1396
+ try {
1397
+ for (let i = 0; i < chain.length; i++) {
1398
+ const dir = chain[i];
1399
+ let info;
1400
+ try {
1401
+ info = await lstat(dir);
1402
+ }
1403
+ catch (error) {
1404
+ if (error.code === 'ENOENT') {
1405
+ if (i === 0)
1406
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1407
+ if (identity.name === 'write') {
1408
+ for (let j = i; j < chain.length; j++)
1409
+ absentBeforeOp.add(chain[j]);
1410
+ }
1411
+ break;
1412
+ }
1413
+ throw error;
1414
+ }
1415
+ if (info.isSymbolicLink() || !info.isDirectory()) {
1416
+ if (i === 0)
1417
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1418
+ stoppedAtNonDir = true;
1419
+ break;
1420
+ }
1421
+ await chmod(dir, 0o755);
1422
+ unlockedDirs.push(dir);
1423
+ }
1424
+ result = await wrapProgress(() => super.invoke(identity, bytes, signal, onOperation));
1425
+ }
1426
+ catch (error) {
1427
+ opFailed = true;
1428
+ opError = error;
1429
+ }
1430
+ const prunedDirs = this.candidate.consumeLastPrunedDirectories();
1431
+ const toRelock = [...unlockedDirs, ...(stoppedAtNonDir ? [] : absentBeforeOp)];
1432
+ let relockError = null;
1433
+ for (let i = toRelock.length - 1; i >= 0; i--) {
1434
+ const dir = toRelock[i];
1435
+ try {
1436
+ await chmod(dir, 0o555);
1437
+ const verified = await lstat(dir);
1438
+ if (!verified.isDirectory() || verified.isSymbolicLink() || (verified.mode & 0o777) !== 0o555) {
1439
+ relockError ??= new PiFailure({ code: 'RECOVERY_REQUIRED', path: '/candidate', phase: 'tool', retryable: false, effect: 'possible', requestId: null, operationId: null, stateErrorCode: null });
1440
+ }
1441
+ }
1442
+ catch (error) {
1443
+ const isAbsent = error.code === 'ENOENT';
1444
+ const tolerateAbsent = isAbsent && dir !== this.candidateDir && ((identity.name === 'delete' && prunedDirs.has(resolve(dir)))
1445
+ || (identity.name === 'write' && absentBeforeOp.has(dir)));
1446
+ if (tolerateAbsent)
1447
+ continue;
1448
+ relockError ??= new PiFailure({ code: 'RECOVERY_REQUIRED', path: '/candidate', phase: 'tool', retryable: false, effect: 'possible', requestId: null, operationId: null, stateErrorCode: null });
1449
+ }
1450
+ }
1451
+ if (opFailed && (relockError === null || (opError instanceof PiFailure && opError.detail.code === 'RECOVERY_REQUIRED'))) {
1452
+ throw opError;
1453
+ }
1454
+ if (relockError !== null)
1455
+ throw relockError;
1456
+ if (opFailed)
1457
+ throw opError;
1458
+ return result;
1459
+ });
1460
+ this.#gate = mediated.then(() => { }, () => { });
1461
+ return mediated;
1462
+ }
1463
+ }
1464
+ class HostMcpProcess extends EventEmitter {
1465
+ input;
1466
+ candidateDir;
1467
+ #initialized = false;
1468
+ #readyState = false;
1469
+ #closed = false;
1470
+ #failed = false;
1471
+ #tail = Promise.resolve();
1472
+ #pending = 0;
1473
+ constructor(input, candidateDir) {
1474
+ super();
1475
+ this.input = input;
1476
+ this.candidateDir = candidateDir;
1477
+ }
1478
+ #fail() {
1479
+ if (!this.#closed && !this.#failed) {
1480
+ this.#failed = true;
1481
+ this.emit('failed');
1482
+ }
1483
+ }
1484
+ async ready(signal) {
1485
+ signal.throwIfAborted();
1486
+ if (this.#closed || this.#failed)
1487
+ refuse('MCP_FAILED', '', { phase: 'tool' });
1488
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch) || !/^v26\./.test(process.version)) {
1489
+ refuse('RUNTIME_MISMATCH', '', { phase: 'tool' });
1490
+ }
1491
+ if ((await realpath(this.candidateDir)) !== resolve(this.candidateDir) || !(await stat(this.candidateDir)).isDirectory()) {
1492
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
1493
+ }
1494
+ }
1495
+ async send(message, guard) {
1496
+ if (this.#closed || this.#failed || this.#pending >= 32)
1497
+ refuse('MCP_FAILED', '', { phase: 'tool' });
1498
+ const serialized = canonical(message) + '\n';
1499
+ if (Buffer.byteLength(serialized) > 65536)
1500
+ refuse('OUTPUT_LIMIT', '', { phase: 'tool' });
1501
+ this.#pending++;
1502
+ const work = this.#tail.then(async () => {
1503
+ if (this.#closed || this.#failed)
1504
+ refuse('MCP_FAILED', '', { phase: 'tool' });
1505
+ guard();
1506
+ await this.#dispatch(message);
1507
+ });
1508
+ this.#tail = work.catch(() => { this.#fail(); });
1509
+ try {
1510
+ await work;
1511
+ }
1512
+ finally {
1513
+ this.#pending--;
1514
+ }
1515
+ }
1516
+ async #dispatch(value) {
1517
+ if (!('method' in value)) {
1518
+ this.#fail();
1519
+ return;
1520
+ }
1521
+ if (!('id' in value)) {
1522
+ if (value.method === 'notifications/initialized' && this.#initialized) {
1523
+ this.#readyState = true;
1524
+ }
1525
+ else if (value.method !== 'notifications/cancelled') {
1526
+ this.#fail();
1527
+ }
1528
+ return;
1529
+ }
1530
+ const emitReply = (payload) => {
1531
+ const bytes = Buffer.byteLength(canonical(payload)) + 1;
1532
+ if (bytes > 65536) {
1533
+ this.#fail();
1534
+ return;
1535
+ }
1536
+ queueMicrotask(() => {
1537
+ if (!this.#closed && !this.#failed)
1538
+ this.emit('message', payload);
1539
+ });
1540
+ };
1541
+ if (value.method === 'initialize' && !this.#initialized) {
1542
+ this.#initialized = true;
1543
+ emitReply({
1544
+ jsonrpc: '2.0',
1545
+ id: value.id,
1546
+ result: {
1547
+ protocolVersion: '2025-06-18',
1548
+ capabilities: { tools: {} },
1549
+ serverInfo: { name: 'loopwright-workspace', version: '1' },
1550
+ },
1551
+ });
1552
+ return;
1553
+ }
1554
+ if (!this.#readyState) {
1555
+ this.#fail();
1556
+ return;
1557
+ }
1558
+ if (value.method === 'tools/list') {
1559
+ emitReply({ jsonrpc: '2.0', id: value.id, result: { tools: [WORKSPACE_TOOL] } });
1560
+ return;
1561
+ }
1562
+ if (value.method !== 'tools/call') {
1563
+ emitReply({ jsonrpc: '2.0', id: value.id, error: { code: -32601, message: 'MCP_FAILED' } });
1564
+ return;
1565
+ }
1566
+ let result;
1567
+ try {
1568
+ const keys = Object.keys(value.params ?? {});
1569
+ const params = object(value.params, keys);
1570
+ if (keys.some(k => !['name', 'arguments', '_meta'].includes(k)) || params.name !== 'read_file') {
1571
+ refuse('TOOL_DENIED', '', { phase: 'tool' });
1572
+ }
1573
+ const args = object(params.arguments, ['path']);
1574
+ if (typeof args.path !== 'string')
1575
+ refuse('TOOL_DENIED', '', { phase: 'tool' });
1576
+ result = { content: [{ type: 'text', text: await readWorkspace(this.candidateDir, args.path, 65536) }] };
1577
+ if (Buffer.byteLength(canonical({ jsonrpc: '2.0', id: value.id, result })) + 1 > 65536) {
1578
+ refuse('OUTPUT_LIMIT', '', { phase: 'tool' });
1579
+ }
1580
+ }
1581
+ catch (error) {
1582
+ const code = error instanceof PiFailure ? error.detail.code : 'MCP_FAILED';
1583
+ result = { isError: true, content: [{ type: 'text', text: code }] };
1584
+ }
1585
+ emitReply({ jsonrpc: '2.0', id: value.id, result });
1586
+ }
1587
+ async close() {
1588
+ this.#closed = true;
1589
+ await this.#tail.catch(() => { });
1590
+ return null;
1591
+ }
1592
+ }
1593
+ class HostRuntimeSession {
1594
+ host;
1595
+ input;
1596
+ broker;
1597
+ directory;
1598
+ options;
1599
+ breaker;
1600
+ nonce = randomBytes(16).toString('hex');
1601
+ name = 'lw-pi-' + this.nonce;
1602
+ #process = null;
1603
+ #channel = null;
1604
+ #snapshots = null;
1605
+ #bootWork = null;
1606
+ #creationAttempted = false;
1607
+ #closing = null;
1608
+ #exited = null;
1609
+ #closed = false;
1610
+ #cleanupComplete = false;
1611
+ #failed = false;
1612
+ #pending = null;
1613
+ #invocationStartedMs = new Map();
1614
+ constructor(host, input, broker, directory, options, breaker) {
1615
+ this.host = host;
1616
+ this.input = input;
1617
+ this.broker = broker;
1618
+ this.directory = directory;
1619
+ this.options = options;
1620
+ this.breaker = breaker;
1621
+ }
1622
+ start() {
1623
+ if (this.#bootWork || this.#closed)
1624
+ refuse('SESSION_BUSY');
1625
+ const work = this.#boot();
1626
+ this.#bootWork = work;
1627
+ return work.catch(async (error) => {
1628
+ await this.close();
1629
+ throw error;
1630
+ });
1631
+ }
1632
+ async #boot() {
1633
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch)) {
1634
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
1635
+ }
1636
+ if (!/^v26\./.test(process.version)) {
1637
+ refuse('RUNTIME_MISMATCH', '/host/runtime');
1638
+ }
1639
+ if (!sameIdentity(await profileIdentity(), this.input.policy.runtime.configDigest)) {
1640
+ refuse('RUNTIME_MISMATCH', '/policy/runtime/configDigest');
1641
+ }
1642
+ const lockBytes = await readFile(resolveLockfileUrl());
1643
+ if (!sameIdentity(digest(lockBytes), this.input.policy.runtime.graphDigest)) {
1644
+ refuse('RUNTIME_MISMATCH', '/policy/runtime/graphDigest');
1645
+ }
1646
+ await mkdir(this.directory, { mode: 0o700 });
1647
+ const canonicalDir = await realpath(this.directory);
1648
+ const homeDir = join(canonicalDir, 'home');
1649
+ const tmpDir = join(canonicalDir, 'tmp');
1650
+ await mkdir(homeDir, { mode: 0o700 });
1651
+ await mkdir(tmpDir, { mode: 0o700 });
1652
+ const candidateDir = join(this.directory, 'candidate');
1653
+ await materializeCandidateDirectory(candidateDir, this.input);
1654
+ const labels = Object.freeze({
1655
+ 'org.loopwright.generation': String(this.host.authority.generation),
1656
+ 'org.loopwright.run': this.input.lock.spec.runId,
1657
+ 'org.loopwright.session': this.input.sessionId,
1658
+ 'org.loopwright.nonce': this.nonce,
1659
+ });
1660
+ await writeFile(join(this.directory, 'process-intent.json'), JSON.stringify({ version: 1, name: this.name, nonce: this.nonce, labels }), { flag: 'wx', mode: 0o600 });
1661
+ await registerChild(this.host, { name: this.name, nonce: this.nonce, role: 'sdk', labels });
1662
+ this.#creationAttempted = true;
1663
+ if (this.#closed)
1664
+ refuse('CANCELLED');
1665
+ const workerScript = fileURLToPath(new URL('./sdk-worker.js', import.meta.url));
1666
+ const child = spawn(process.execPath, [workerScript, this.nonce], {
1667
+ cwd: canonicalDir,
1668
+ detached: true,
1669
+ stdio: ['pipe', 'pipe', 'pipe'],
1670
+ env: {
1671
+ PATH: '/usr/local/bin:/usr/bin:/bin',
1672
+ HOME: homeDir,
1673
+ TMPDIR: tmpDir,
1674
+ PI_OFFLINE: '1',
1675
+ LOOPWRIGHT_HOST_SESSION: '1',
1676
+ LANG: 'C.UTF-8',
1677
+ LC_ALL: 'C.UTF-8',
1678
+ TERM: 'dumb',
1679
+ },
1680
+ });
1681
+ this.#process = child;
1682
+ this.#exited = new Promise(resolvePromise => {
1683
+ child.once('exit', (code, signal) => resolvePromise({ code, signal }));
1684
+ child.once('error', () => {
1685
+ this.#fail();
1686
+ resolvePromise({ code: null, signal: null });
1687
+ });
1688
+ });
1689
+ const diagnosticLimit = this.input.policy.limits.diagnosticBytes;
1690
+ const retainedLimit = Math.floor((diagnosticLimit - 64) * 3 / 4);
1691
+ let stderrBytes = 0;
1692
+ let retained = Buffer.alloc(0);
1693
+ child.stderr.on('data', (data) => {
1694
+ stderrBytes += data.length;
1695
+ const keep = Math.min(data.length, Math.max(0, retainedLimit - retained.length));
1696
+ if (keep)
1697
+ retained = Buffer.concat([retained, data.subarray(0, keep)]);
1698
+ try {
1699
+ if (this.input.policy.privateArtifacts) {
1700
+ writeFileSync(join(this.directory, 'private-sdk-stderr'), JSON.stringify({ encoding: 'base64', truncated: stderrBytes > retained.length, data: retained.toString('base64') }) + '\n', { mode: 0o600 });
1701
+ }
1702
+ }
1703
+ catch {
1704
+ this.#fail();
1705
+ }
1706
+ if (stderrBytes > diagnosticLimit) {
1707
+ this.broker.runtimeFault?.('OUTPUT_LIMIT');
1708
+ this.#fail();
1709
+ }
1710
+ });
1711
+ this.#channel = new Channel(this.nonce, child.stdout, child.stdin);
1712
+ this.#snapshots = new SnapshotTransfer(this.#channel);
1713
+ this.#channel.on('failed', () => this.#fail());
1714
+ this.#channel.on('message', (message) => {
1715
+ void this.#receive(message).catch(() => this.#fail());
1716
+ });
1717
+ await registerAttach(this.host, this.nonce, child.pid);
1718
+ const roleMcpAllowlist = resolveSessionMcpAllowlist(this.input, this.options);
1719
+ const permittedToolNames = roleMcpAllowlist.filterToolNames(this.input.policy.tools);
1720
+ const restored = await recoverSnapshot(this.host, this.input);
1721
+ if (restored) {
1722
+ const accepted = this.#wait('restore-ready');
1723
+ await Promise.all([
1724
+ this.#channel.send('restore-start', {
1725
+ selection: this.input.policy.selection,
1726
+ toolNames: permittedToolNames,
1727
+ sessionBytes: this.input.policy.limits.sessionBytes,
1728
+ }),
1729
+ accepted,
1730
+ ]);
1731
+ async function* chunks() {
1732
+ yield restored.native;
1733
+ }
1734
+ const complete = this.#wait('restore-complete', 90000);
1735
+ await Promise.all([
1736
+ this.#snapshots.send(1, chunks(), this.input.policy.limits.sessionBytes),
1737
+ complete,
1738
+ ]);
1739
+ }
1740
+ const ready = this.#wait('ready');
1741
+ const externalMcpTools = this.options?.mcpRegistry
1742
+ ? this.options.mcpRegistry
1743
+ .toolSchemasFor(permittedToolNames, this.options.allowedMcpServers)
1744
+ .filter(schema => roleMcpAllowlist.isToolAllowed(schema.name, schema.serverId))
1745
+ : [];
1746
+ const [, response] = await Promise.all([
1747
+ this.#channel.send('init', {
1748
+ selection: this.input.policy.selection,
1749
+ systemPrompt: systemPrompt(this.input),
1750
+ toolNames: permittedToolNames,
1751
+ mcp: this.input.policy.mcp,
1752
+ toolArgsBytes: this.input.policy.limits.toolArgsBytes,
1753
+ toolResultBytes: this.input.policy.limits.toolResultBytes,
1754
+ sessionBytes: this.input.policy.limits.sessionBytes,
1755
+ outputTokens: Math.min(this.input.lock.spec.contract.spec.budgets.perCallOutputTokens, this.input.policy.context.maxOutputTokens),
1756
+ contextPolicy: this.input.policy.context,
1757
+ ...(externalMcpTools.length > 0 ? { externalMcpTools } : {}),
1758
+ }),
1759
+ ready,
1760
+ ]);
1761
+ const facts = response;
1762
+ if (!sameIdentity(facts.selection, this.input.policy.selection) ||
1763
+ facts.thinkingLevel !== this.input.policy.selection.thinking ||
1764
+ !/^v26\./.test(process.version) ||
1765
+ facts.node !== process.version ||
1766
+ typeof facts.platform !== 'string' ||
1767
+ typeof facts.architecture !== 'string' ||
1768
+ !isSupportedHostSessionPlatform(facts.platform, facts.architecture)) {
1769
+ refuse('RUNTIME_MISMATCH');
1770
+ }
1771
+ return freeze({
1772
+ version: 1,
1773
+ policyDigest: digest(Buffer.from(canonical(this.input.policy))),
1774
+ runtime: this.input.policy.runtime,
1775
+ requested: this.input.policy.selection,
1776
+ catalogSupported: structuredClone(this.input.policy.selection),
1777
+ sessionEffective: structuredClone(this.input.policy.selection),
1778
+ outboundObserved: null,
1779
+ resources: this.input.policy.resources,
1780
+ accounting: 'soft_only',
1781
+ contextFit: 'unproven',
1782
+ defaultMode: 'proven_bound',
1783
+ liveProvenBoundAvailable: false,
1784
+ optInMode: 'estimated_guard',
1785
+ contextEstimator: { id: 'lw-pi-final-json-bytes-v1', version: 1, provenance: 'estimated' },
1786
+ toolExecution: { candidate: 'read_only', candidateWrites: 'mediated', scratch: 'per_call' },
1787
+ });
1788
+ }
1789
+ #wait(kind, timeoutMs = 10000, remaining) {
1790
+ if (this.#pending)
1791
+ refuse('SESSION_BUSY', '', { phase: 'session' });
1792
+ if (this.#failed)
1793
+ refuse('RECOVERY_REQUIRED', '', { phase: 'session' });
1794
+ return new Promise((resolvePromise, rejectPromise) => {
1795
+ let stop = () => { };
1796
+ const expires = performance.now() + timeoutMs;
1797
+ this.#pending = {
1798
+ kind,
1799
+ resolve: value => {
1800
+ stop();
1801
+ this.#pending = null;
1802
+ resolvePromise(value);
1803
+ },
1804
+ reject: error => {
1805
+ stop();
1806
+ this.#pending = null;
1807
+ rejectPromise(error);
1808
+ },
1809
+ };
1810
+ stop = scheduleDeadline(remaining ?? (() => expires - performance.now()), () => {
1811
+ this.#pending = null;
1812
+ rejectPromise(new PiFailure({
1813
+ code: 'DEADLINE',
1814
+ path: '',
1815
+ phase: 'session',
1816
+ retryable: false,
1817
+ effect: 'possible',
1818
+ requestId: null,
1819
+ operationId: null,
1820
+ stateErrorCode: null,
1821
+ }));
1822
+ this.#fail();
1823
+ });
1824
+ });
1825
+ }
1826
+ async #receive(message) {
1827
+ if (this.#closed)
1828
+ throw new Error('Closed SDK channel');
1829
+ if (await this.#snapshots.receive(message))
1830
+ return;
1831
+ if (message.kind === 'invoke' && message.body && typeof message.body === 'object') {
1832
+ const inv = message.body;
1833
+ if (typeof inv.invocation === 'number' && typeof inv.provider === 'string' && typeof inv.model === 'string') {
1834
+ const tripped = this.breaker?.onBeforeInvoke() ?? null;
1835
+ if (tripped !== null) {
1836
+ try {
1837
+ this.options?.onProgress?.({
1838
+ kind: 'circuit_breaker',
1839
+ reason: tripped.reason,
1840
+ turn: tripped.turn,
1841
+ message: tripped.message,
1842
+ });
1843
+ }
1844
+ catch {
1845
+ // Ignore observer errors.
1846
+ }
1847
+ }
1848
+ else {
1849
+ this.#invocationStartedMs.set(inv.invocation, performance.now());
1850
+ try {
1851
+ this.options?.onProgress?.({
1852
+ kind: 'request_start',
1853
+ turn: inv.invocation,
1854
+ provider: inv.provider,
1855
+ model: inv.model,
1856
+ });
1857
+ }
1858
+ catch {
1859
+ // Ignore observer errors.
1860
+ }
1861
+ }
1862
+ }
1863
+ }
1864
+ const handled = await receiveBrokerMessage(this.#channel, this.broker, message);
1865
+ if (handled) {
1866
+ if (message.kind === 'parsed' && message.body && typeof message.body === 'object') {
1867
+ const parsed = message.body;
1868
+ if (typeof parsed.invocation === 'number') {
1869
+ const startedAt = this.#invocationStartedMs.get(parsed.invocation);
1870
+ this.#invocationStartedMs.delete(parsed.invocation);
1871
+ if (!this.breaker?.tripped) {
1872
+ const inputTokens = (typeof parsed.usage?.input === 'number' ? parsed.usage.input : 0)
1873
+ + (typeof parsed.usage?.cacheRead === 'number' ? parsed.usage.cacheRead : 0)
1874
+ + (typeof parsed.usage?.cacheWrite === 'number' ? parsed.usage.cacheWrite : 0);
1875
+ const outputTokens = typeof parsed.usage?.output === 'number' ? parsed.usage.output : 0;
1876
+ const toolCallNames = Array.isArray(parsed.toolCalls)
1877
+ ? parsed.toolCalls.map(item => (typeof item?.name === 'string' ? item.name : '')).filter(Boolean)
1878
+ : [];
1879
+ this.breaker?.onRequestSettled(toolCallNames.length > 0);
1880
+ try {
1881
+ this.options?.onProgress?.({
1882
+ kind: 'request_settled',
1883
+ turn: parsed.invocation,
1884
+ stopReason: typeof parsed.stopReason === 'string' ? parsed.stopReason : 'stop',
1885
+ inputTokens,
1886
+ outputTokens,
1887
+ elapsedMs: Math.max(1, Math.round(performance.now() - (startedAt ?? performance.now()))),
1888
+ toolCallNames,
1889
+ });
1890
+ }
1891
+ catch {
1892
+ // Ignore observer errors.
1893
+ }
1894
+ }
1895
+ }
1896
+ }
1897
+ return;
1898
+ }
1899
+ if (message.kind === 'refused') {
1900
+ this.#snapshots?.close();
1901
+ const body = message.body;
1902
+ const code = body.code === 'MODEL_UNAVAILABLE' || body.code === 'THINKING_UNSUPPORTED'
1903
+ ? body.code
1904
+ : 'PROVIDER_RESPONSE_INVALID';
1905
+ this.#pending?.reject(new PiFailure({
1906
+ code,
1907
+ path: '/policy/selection',
1908
+ phase: 'session',
1909
+ retryable: false,
1910
+ effect: 'none',
1911
+ requestId: null,
1912
+ operationId: null,
1913
+ stateErrorCode: null,
1914
+ }));
1915
+ return;
1916
+ }
1917
+ if (!this.#pending || message.kind !== this.#pending.kind)
1918
+ throw new Error('Unrequested SDK result');
1919
+ this.#pending.resolve(message.body);
1920
+ }
1921
+ #fail() {
1922
+ if (!this.#closed) {
1923
+ this.#failed = true;
1924
+ this.#snapshots?.close();
1925
+ this.#pending?.reject(new Error('SDK channel failed'));
1926
+ }
1927
+ }
1928
+ async command(kind, body) {
1929
+ if (this.#closed || !this.#channel)
1930
+ refuse('CANCELLED', '', { phase: 'session' });
1931
+ const view = stateValue(this.host.store.inspect(), 'session');
1932
+ const remaining = view.clock.remainingTaskMs.safeValue;
1933
+ if (remaining === null || remaining <= 0)
1934
+ refuse('DEADLINE', '', { phase: 'session' });
1935
+ const rawRepair = kind === 'execute' && body && typeof body === 'object' && 'repair' in body
1936
+ ? body.repair
1937
+ : 'none';
1938
+ this.breaker?.beginDispatch(kind, rawRepair === 'format' || rawRepair === 'implementation' ? rawRepair : 'none');
1939
+ const pending = this.#wait('settled', undefined, () => {
1940
+ const current = this.host.store.inspect();
1941
+ return current.ok && current.value.clockStatus === 'trusted' ? current.value.clock.remainingTaskMs.safeValue : null;
1942
+ });
1943
+ const [, response] = await Promise.all([this.#channel.send(kind, body), pending]);
1944
+ verifyNativeCompletion(response.native, kind);
1945
+ return response;
1946
+ }
1947
+ async capture(sink) {
1948
+ if (this.#closed || !this.#channel || !this.#snapshots)
1949
+ refuse('CANCELLED');
1950
+ const view = stateValue(this.host.store.inspect(), 'restore');
1951
+ const remaining = view.clock.remainingTaskMs.safeValue;
1952
+ if (remaining === null || remaining <= 0)
1953
+ refuse('DEADLINE');
1954
+ const expected = this.#snapshots.expect(sink, this.input.policy.limits.sessionBytes, Math.min(90000, remaining));
1955
+ try {
1956
+ await this.#channel.send('capture', { query: expected.query });
1957
+ await expected.done;
1958
+ }
1959
+ catch (error) {
1960
+ this.#snapshots.close();
1961
+ if (error instanceof PiFailure && error.detail.code !== 'INPUT_INVALID')
1962
+ throw error;
1963
+ refuse('RECOVERY_REQUIRED', '', { phase: 'restore' });
1964
+ }
1965
+ }
1966
+ close() {
1967
+ if (this.#closing)
1968
+ return this.#closing;
1969
+ const attempt = this.#cleanup();
1970
+ this.#closing = attempt;
1971
+ void attempt.then(() => { this.#closing = null; }, () => { this.#closing = null; });
1972
+ return attempt;
1973
+ }
1974
+ async #cleanup() {
1975
+ if (this.#cleanupComplete)
1976
+ return;
1977
+ this.#closed = true;
1978
+ this.#snapshots?.close();
1979
+ this.#pending?.reject(new Error('closed'));
1980
+ await this.#bootWork?.catch(() => { });
1981
+ let leaderExited = false;
1982
+ try {
1983
+ if (this.#channel) {
1984
+ try {
1985
+ await this.#channel.send('close', null);
1986
+ }
1987
+ catch { /* process-group cleanup follows */ }
1988
+ this.#channel.close();
1989
+ }
1990
+ if (this.#exited && this.#process && this.#process.exitCode === null && this.#process.signalCode === null) {
1991
+ let timer;
1992
+ try {
1993
+ await Promise.race([this.#exited, new Promise(resolvePromise => { timer = setTimeout(resolvePromise, 500); })]);
1994
+ }
1995
+ finally {
1996
+ clearTimeout(timer);
1997
+ }
1998
+ }
1999
+ leaderExited = this.#process !== null && (this.#process.exitCode !== null || this.#process.signalCode !== null);
2000
+ if (!this.#creationAttempted) {
2001
+ if (existsSync(join(this.directory, 'candidate'))) {
2002
+ await setDirectoryTreeMode(join(this.directory, 'candidate'), 0o755).catch(() => { });
2003
+ }
2004
+ this.#cleanupComplete = true;
2005
+ return;
2006
+ }
2007
+ }
2008
+ finally {
2009
+ const exitedNow = leaderExited || (this.#process !== null && (this.#process.exitCode !== null || this.#process.signalCode !== null));
2010
+ killProcessGroup(this.#process?.pid, !exitedNow);
2011
+ this.#process?.stdin.destroy();
2012
+ this.#process?.stdout.destroy();
2013
+ this.#process?.stderr.destroy();
2014
+ }
2015
+ let exit = { code: null, signal: null };
2016
+ if (this.#exited) {
2017
+ let timer;
2018
+ try {
2019
+ exit = await Promise.race([
2020
+ this.#exited,
2021
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Host SDK worker cleanup deadline')), 2000); }),
2022
+ ]);
2023
+ }
2024
+ finally {
2025
+ clearTimeout(timer);
2026
+ }
2027
+ killProcessGroup(this.#process?.pid, false);
2028
+ }
2029
+ if (existsSync(join(this.directory, 'candidate'))) {
2030
+ await setDirectoryTreeMode(join(this.directory, 'candidate'), 0o755).catch(() => { });
2031
+ }
2032
+ await writeFile(join(this.directory, 'cleanup.json'), JSON.stringify({
2033
+ id: digest(Buffer.from(this.nonce)).hex,
2034
+ nonce: this.nonce,
2035
+ pid: this.#process?.pid ?? null,
2036
+ removed: true,
2037
+ absenceConfirmed: true,
2038
+ state: exit,
2039
+ }), { mode: 0o600 });
2040
+ await writeFile(join(this.directory, 'cli-exit.json'), JSON.stringify(exit), { mode: 0o600 });
2041
+ await exitChild(this.host, this.nonce);
2042
+ this.#cleanupComplete = true;
2043
+ }
2044
+ }
2045
+ async function environment(host) {
2046
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch)) {
2047
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
2048
+ }
2049
+ try {
2050
+ await canonicalDirectory(host.directory);
2051
+ await canonicalDirectory(host.artifactsDirectory);
2052
+ }
2053
+ catch {
2054
+ refuse('CONTAINMENT_UNAVAILABLE');
2055
+ }
2056
+ }
2057
+ function createHostSessionPorts(options) {
2058
+ const breaker = new HostSessionCircuitBreaker();
2059
+ return Object.freeze({
2060
+ environment: async (host) => {
2061
+ validateAllowedMcpServers(options?.allowedMcpServers);
2062
+ breaker.configure(options?.circuitBreaker);
2063
+ await environment(host);
2064
+ },
2065
+ lease: (host, input) => HostExecutionLease.acquire(host, input),
2066
+ sender: (host, owned) => {
2067
+ breaker.bindBudgets(owned.lock.spec.contract.spec.budgets, owned.policy.limits.requests);
2068
+ return new Sender(host, owned, {
2069
+ fetch: globalThis.fetch,
2070
+ catalog: selectedCatalog(owned),
2071
+ beforeSend: () => breaker.assertBeforeSend(),
2072
+ });
2073
+ },
2074
+ execution: (host, owned, candidateDir) => {
2075
+ const roleMcpAllowlist = resolveSessionMcpAllowlist(owned, options);
2076
+ return new HostExecution(host, owned, candidateDir, {
2077
+ process: (operationId, signal) => new HostToolProcess(host, owned, join(host.directory, 'tool-' + operationId), candidateDir, operationId, signal),
2078
+ ...(options?.mcpRegistry !== undefined
2079
+ ? { mcpExecutor: createRoleScopedMcpExecutor(options.mcpRegistry, roleMcpAllowlist) }
2080
+ : {}),
2081
+ }, options?.onProgress, (name, isError) => breaker.recordToolEnd(name, isError), options?.scrub, () => breaker.convergenceWarning());
2082
+ },
2083
+ mcp: (_host, owned) => ({
2084
+ process: () => new HostMcpProcess(owned, join(_host.directory, 'sdk-' + owned.sessionId, 'candidate')),
2085
+ }),
2086
+ session: (host, owned, sender, directory) => new HostRuntimeSession(host, owned, sender, directory, options, breaker),
2087
+ });
2088
+ }
2089
+ export function openPiHostSessionAdapter(host, input, options) {
2090
+ return constructAdapter(host, input, createHostSessionPorts(options));
2091
+ }
2092
+ export function openPiHostSessionAdapterV2(host, input, options) {
2093
+ return constructAdapterV2(host, input, createHostSessionPorts(options));
2094
+ }