@gpustack/loopwright 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +2083 -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 +1646 -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 +2605 -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 +7313 -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 +3021 -0
  476. package/package-lock.json +3021 -0
  477. package/package.json +52 -4
@@ -0,0 +1,2083 @@
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
+ return {
443
+ executable: '/usr/bin/bwrap',
444
+ args: [
445
+ '--ro-bind', '/', '/',
446
+ '--bind', options.scratchDir, options.scratchDir,
447
+ '--bind', options.tmpDir, options.tmpDir,
448
+ '--dev', '/dev',
449
+ '--proc', '/proc',
450
+ '--unshare-pid',
451
+ '--unshare-net',
452
+ '--die-with-parent',
453
+ '--chdir', options.scratchDir,
454
+ '--',
455
+ '/bin/bash', '-c', options.command,
456
+ ],
457
+ };
458
+ }
459
+ const landlockPython = canUseLinuxLandlock();
460
+ if (landlockPython !== null) {
461
+ const landlockConfig = JSON.stringify({
462
+ candidateDir: options.candidateDir,
463
+ scratchDir: options.scratchDir,
464
+ tmpDir: options.tmpDir,
465
+ deniedReadPaths: [`/proc/${process.pid}`, options.ownedRoot],
466
+ });
467
+ return {
468
+ executable: landlockPython,
469
+ args: ['-c', HOST_LANDLOCK_BOOTSTRAP_SCRIPT, landlockConfig, options.command],
470
+ };
471
+ }
472
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
473
+ }
474
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
475
+ }
476
+ async function birth(pid) {
477
+ try {
478
+ const result = await exec('/bin/ps', ['-p', String(pid), '-o', 'lstart='], {
479
+ timeout: 10000,
480
+ maxBuffer: 1024,
481
+ env: probeEnv,
482
+ });
483
+ const value = result.stdout.trim();
484
+ if (!value || value.length > 128 || result.stderr)
485
+ refuse('RECOVERY_REQUIRED');
486
+ return value;
487
+ }
488
+ catch (error) {
489
+ const value = error;
490
+ if (value.code === 1 && value.stdout === '' && value.stderr === '')
491
+ return null;
492
+ throw error;
493
+ }
494
+ }
495
+ async function boot() {
496
+ if (process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'x64')) {
497
+ let file = null;
498
+ try {
499
+ file = await open('/proc/sys/kernel/random/boot_id', constants.O_RDONLY | constants.O_NOFOLLOW);
500
+ const buffer = Buffer.alloc(64);
501
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, null);
502
+ const raw = buffer.subarray(0, bytesRead).toString('utf8');
503
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n$/.test(raw))
504
+ refuse('RECOVERY_REQUIRED');
505
+ return raw.trim();
506
+ }
507
+ catch {
508
+ refuse('RECOVERY_REQUIRED');
509
+ }
510
+ finally {
511
+ await file?.close();
512
+ }
513
+ }
514
+ if (process.platform === 'darwin' && process.arch === 'arm64') {
515
+ const result = await exec('/usr/sbin/sysctl', ['-n', 'kern.boottime'], {
516
+ timeout: 10000,
517
+ maxBuffer: 1024,
518
+ env: probeEnv,
519
+ });
520
+ if (!/^\{ sec = \d+, usec = \d+ \} [^\r\n]+\n$/.test(result.stdout) || result.stderr)
521
+ refuse('RECOVERY_REQUIRED');
522
+ return result.stdout.trim();
523
+ }
524
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
525
+ }
526
+ const hostLeases = new WeakMap();
527
+ class HostExecutionLease {
528
+ host;
529
+ input;
530
+ #fd = null;
531
+ #tail = Promise.resolve();
532
+ #released = false;
533
+ #releasing = null;
534
+ #children = new Map();
535
+ token = randomBytes(16).toString('hex');
536
+ path;
537
+ constructor(host, input) {
538
+ this.host = host;
539
+ this.input = input;
540
+ this.path = join(host.artifactsDirectory, 'pi-execution-' + digest(Buffer.from(canonical({
541
+ storeId: stateValue(host.store.inspect()).storeId,
542
+ runId: input.lock.spec.runId,
543
+ }))).hex + '.ndjson');
544
+ }
545
+ static async acquire(host, input) {
546
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch)) {
547
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
548
+ }
549
+ const root = await lstat(host.artifactsDirectory);
550
+ if (!root.isDirectory() ||
551
+ root.isSymbolicLink() ||
552
+ root.uid !== process.getuid?.() ||
553
+ root.mode & 0o022 ||
554
+ (await realpath(host.artifactsDirectory)) !== resolve(host.artifactsDirectory)) {
555
+ refuse('INPUT_INVALID');
556
+ }
557
+ const lease = new HostExecutionLease(host, input);
558
+ const born = await birth(process.pid);
559
+ const bootIdentity = await boot();
560
+ if (!born)
561
+ refuse('RECOVERY_REQUIRED');
562
+ try {
563
+ lease.#fd = await open(lease.path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
564
+ }
565
+ catch (error) {
566
+ if (error.code !== 'EEXIST')
567
+ throw error;
568
+ let recovery;
569
+ try {
570
+ recovery = await open(lease.path + '.recovery', constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
571
+ }
572
+ catch {
573
+ refuse('SESSION_BUSY');
574
+ }
575
+ try {
576
+ await lease.#recover(bootIdentity);
577
+ lease.#fd = await open(lease.path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
578
+ }
579
+ finally {
580
+ await recovery.close();
581
+ await unlink(lease.path + '.recovery');
582
+ }
583
+ }
584
+ try {
585
+ const view = stateValue(host.store.inspect());
586
+ stateValue(host.store.renew(host.authority));
587
+ await lease.#append({
588
+ type: 'owner',
589
+ version: 2,
590
+ daemon: { kind: 'host-process-group', platform: process.platform, arch: process.arch },
591
+ token: lease.token,
592
+ pid: process.pid,
593
+ birth: born,
594
+ boot: bootIdentity,
595
+ authority: host.authority,
596
+ storeId: view.storeId,
597
+ runId: view.runId,
598
+ lockHash: view.lockHash,
599
+ clockBasis: view.clock.basis,
600
+ });
601
+ await lease.#syncParent();
602
+ hostLeases.set(host, lease);
603
+ return lease;
604
+ }
605
+ catch (error) {
606
+ await lease.#fd?.close();
607
+ lease.#fd = null;
608
+ await unlink(lease.path);
609
+ throw error;
610
+ }
611
+ }
612
+ async #syncParent() {
613
+ const fd = await open(this.host.artifactsDirectory, constants.O_RDONLY | constants.O_NOFOLLOW);
614
+ try {
615
+ await fd.sync();
616
+ }
617
+ finally {
618
+ await fd.close();
619
+ }
620
+ }
621
+ async #append(value) {
622
+ if (!this.#fd || this.#released)
623
+ refuse('RECOVERY_REQUIRED');
624
+ const bytes = Buffer.from(JSON.stringify(value) + '\n');
625
+ if ((await this.#fd.stat()).size + bytes.length > 2097152)
626
+ refuse('OUTPUT_LIMIT');
627
+ await this.#fd.writeFile(bytes);
628
+ await this.#fd.sync();
629
+ }
630
+ async #recover(bootIdentity) {
631
+ const fd = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
632
+ let rows;
633
+ let inode;
634
+ try {
635
+ const info = await fd.stat();
636
+ inode = info.ino;
637
+ if (!info.isFile() || info.uid !== process.getuid?.() || info.mode & 0o077 || info.nlink !== 1 || info.size > 2097152) {
638
+ refuse('RECOVERY_REQUIRED');
639
+ }
640
+ const content = await fd.readFile('utf8');
641
+ if (!content.endsWith('\n'))
642
+ refuse('RECOVERY_REQUIRED');
643
+ rows = content.slice(0, -1).split('\n').map(row => parseBoundedJson(row));
644
+ }
645
+ finally {
646
+ await fd.close();
647
+ }
648
+ const first = rows[0];
649
+ if (!first || first.version !== 2)
650
+ refuse('RECOVERY_REQUIRED');
651
+ try {
652
+ object(first, ['type', 'version', 'daemon', 'token', 'pid', 'birth', 'boot', 'authority', 'storeId', 'runId', 'lockHash', 'clockBasis']);
653
+ }
654
+ catch {
655
+ refuse('RECOVERY_REQUIRED');
656
+ }
657
+ let daemon;
658
+ try {
659
+ daemon = object(first.daemon, ['kind', 'platform', 'arch']);
660
+ }
661
+ catch {
662
+ refuse('RECOVERY_REQUIRED');
663
+ }
664
+ if (daemon.kind !== 'host-process-group' ||
665
+ daemon.platform !== process.platform ||
666
+ daemon.arch !== process.arch ||
667
+ !isSupportedHostSessionPlatform(daemon.platform, daemon.arch)) {
668
+ refuse('RECOVERY_REQUIRED');
669
+ }
670
+ const view = stateValue(this.host.store.inspect());
671
+ if (first.type !== 'owner' ||
672
+ !Number.isSafeInteger(first.pid) ||
673
+ first.pid < 1 ||
674
+ typeof first.birth !== 'string' ||
675
+ typeof first.token !== 'string' ||
676
+ !/^[a-f0-9]{32}$/.test(first.token) ||
677
+ first.boot !== bootIdentity ||
678
+ first.storeId !== view.storeId ||
679
+ first.runId !== view.runId ||
680
+ !sameIdentity(first.lockHash, view.lockHash) ||
681
+ !sameIdentity(first.clockBasis, view.clock.basis)) {
682
+ refuse('RECOVERY_REQUIRED');
683
+ }
684
+ const authority = object(first.authority, ['storeId', 'runId', 'lockHash', 'ownerId', 'generation', 'nonce']);
685
+ if (authority.storeId !== view.storeId ||
686
+ authority.runId !== view.runId ||
687
+ !sameIdentity(authority.lockHash, view.lockHash) ||
688
+ !Number.isSafeInteger(authority.generation) ||
689
+ authority.generation > this.host.authority.generation) {
690
+ refuse('RECOVERY_REQUIRED');
691
+ }
692
+ const currentBirth = await birth(first.pid);
693
+ if (currentBirth !== null)
694
+ refuse(currentBirth === first.birth ? 'SESSION_BUSY' : 'RECOVERY_REQUIRED');
695
+ try {
696
+ process.kill(first.pid, 0);
697
+ refuse('RECOVERY_REQUIRED');
698
+ }
699
+ catch (error) {
700
+ if (error.code !== 'ESRCH')
701
+ throw error;
702
+ }
703
+ const intents = new Map();
704
+ const attaches = new Map();
705
+ const receipts = [];
706
+ for (const row of rows.slice(1)) {
707
+ if (row.type === 'child') {
708
+ const item = object(row, ['type', 'name', 'nonce', 'role', 'labels']);
709
+ if (typeof item.name !== 'string' ||
710
+ !/^lw-pi-(?:tool-)?[a-f0-9]{32}$/.test(item.name) ||
711
+ typeof item.nonce !== 'string' ||
712
+ !/^[a-f0-9]{32}$/.test(item.nonce) ||
713
+ (item.role !== 'sdk' && item.role !== 'tool')) {
714
+ refuse('RECOVERY_REQUIRED');
715
+ }
716
+ const labels = item.labels;
717
+ if (!labels ||
718
+ labels['org.loopwright.run'] !== view.runId ||
719
+ labels['org.loopwright.nonce'] !== item.nonce ||
720
+ labels['org.loopwright.generation'] !== String(authority.generation) ||
721
+ intents.has(item.nonce)) {
722
+ refuse('RECOVERY_REQUIRED');
723
+ }
724
+ intents.set(item.nonce, item);
725
+ }
726
+ else if (row.type === 'attach') {
727
+ object(row, ['type', 'nonce', 'pid', 'birth']);
728
+ if (typeof row.nonce !== 'string' ||
729
+ !intents.has(row.nonce) ||
730
+ attaches.has(row.nonce) ||
731
+ !Number.isSafeInteger(row.pid) ||
732
+ row.pid < 1 ||
733
+ typeof row.birth !== 'string' ||
734
+ !row.birth) {
735
+ refuse('RECOVERY_REQUIRED');
736
+ }
737
+ attaches.set(row.nonce, { pid: row.pid, birth: row.birth });
738
+ }
739
+ else if (row.type === 'exit') {
740
+ object(row, ['type', 'nonce']);
741
+ if (typeof row.nonce !== 'string' || !intents.delete(row.nonce))
742
+ refuse('RECOVERY_REQUIRED');
743
+ attaches.delete(row.nonce);
744
+ }
745
+ else {
746
+ refuse('RECOVERY_REQUIRED');
747
+ }
748
+ }
749
+ stateValue(this.host.store.renew(this.host.authority));
750
+ for (const intent of intents.values()) {
751
+ const attach = attaches.get(intent.nonce);
752
+ if (!attach) {
753
+ receipts.push({ name: intent.name, nonce: intent.nonce, absent: true, cli: null });
754
+ continue;
755
+ }
756
+ const observed = await birth(attach.pid);
757
+ if (observed !== null && observed !== attach.birth) {
758
+ refuse('CLEANUP_FAILED');
759
+ }
760
+ if (observed === attach.birth) {
761
+ killProcessGroup(attach.pid, true);
762
+ }
763
+ else if (observed === null) {
764
+ killProcessGroup(attach.pid, false);
765
+ }
766
+ const deadline = performance.now() + 2000;
767
+ for (;;) {
768
+ const current = await birth(attach.pid);
769
+ if (current === null) {
770
+ try {
771
+ process.kill(attach.pid, 0);
772
+ refuse('RECOVERY_REQUIRED');
773
+ }
774
+ catch (error) {
775
+ if (error.code !== 'ESRCH')
776
+ refuse('RECOVERY_REQUIRED');
777
+ }
778
+ break;
779
+ }
780
+ if (current !== attach.birth || performance.now() >= deadline)
781
+ refuse('CLEANUP_FAILED');
782
+ await new Promise(resolvePromise => setTimeout(resolvePromise, 50));
783
+ }
784
+ receipts.push({
785
+ name: intent.name,
786
+ nonce: intent.nonce,
787
+ removed: true,
788
+ cli: { pid: attach.pid, birth: attach.birth, deathConfirmed: true },
789
+ });
790
+ }
791
+ 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);
792
+ try {
793
+ await record.writeFile(JSON.stringify({
794
+ version: 1,
795
+ priorPid: first.pid,
796
+ priorBirth: first.birth,
797
+ boot: first.boot,
798
+ deathConfirmed: true,
799
+ receipts,
800
+ }));
801
+ await record.sync();
802
+ }
803
+ finally {
804
+ await record.close();
805
+ }
806
+ const now = await lstat(this.path);
807
+ if (now.ino !== inode || now.nlink !== 1)
808
+ refuse('RECOVERY_REQUIRED');
809
+ await unlink(this.path);
810
+ await this.#syncParent();
811
+ }
812
+ register(intent) {
813
+ const next = this.#tail.then(async () => {
814
+ stateValue(this.host.store.renew(this.host.authority));
815
+ if (this.#children.has(intent.nonce))
816
+ refuse('RECOVERY_REQUIRED');
817
+ await this.#append({ type: 'child', ...intent });
818
+ this.#children.set(intent.nonce, intent);
819
+ });
820
+ this.#tail = next.catch(() => { });
821
+ return next;
822
+ }
823
+ attach(nonce, pid, allowAlreadyExited = false) {
824
+ const next = this.#tail.then(async () => {
825
+ if (!this.#children.has(nonce))
826
+ refuse('RECOVERY_REQUIRED');
827
+ const born = await birth(pid);
828
+ if (!born) {
829
+ if (allowAlreadyExited)
830
+ return;
831
+ refuse('RECOVERY_REQUIRED');
832
+ }
833
+ await this.#append({ type: 'attach', nonce, pid, birth: born });
834
+ });
835
+ this.#tail = next.catch(() => { });
836
+ return next;
837
+ }
838
+ exit(nonce) {
839
+ const next = this.#tail.then(async () => {
840
+ if (!this.#children.has(nonce))
841
+ refuse('RECOVERY_REQUIRED');
842
+ await this.#append({ type: 'exit', nonce });
843
+ this.#children.delete(nonce);
844
+ });
845
+ this.#tail = next.catch(() => { });
846
+ return next;
847
+ }
848
+ release() {
849
+ return this.#releasing ??= this.#release();
850
+ }
851
+ async #release() {
852
+ await this.#tail;
853
+ if (this.#released)
854
+ return;
855
+ if (this.#children.size || !this.#fd)
856
+ refuse('CLEANUP_FAILED');
857
+ const fdStat = await this.#fd.stat();
858
+ const current = await lstat(this.path);
859
+ if (current.ino !== fdStat.ino || current.nlink !== 1)
860
+ refuse('RECOVERY_REQUIRED');
861
+ await this.#fd.close();
862
+ this.#fd = null;
863
+ await unlink(this.path);
864
+ await this.#syncParent();
865
+ this.#released = true;
866
+ hostLeases.delete(this.host);
867
+ }
868
+ }
869
+ async function registerChild(host, intent) {
870
+ const lease = hostLeases.get(host);
871
+ if (!lease)
872
+ refuse('RECOVERY_REQUIRED');
873
+ await lease.register(intent);
874
+ }
875
+ async function registerAttach(host, nonce, pid, allowAlreadyExited = false) {
876
+ const lease = hostLeases.get(host);
877
+ if (!lease || !pid)
878
+ refuse('RECOVERY_REQUIRED');
879
+ await lease.attach(nonce, pid, allowAlreadyExited);
880
+ }
881
+ async function exitChild(host, nonce) {
882
+ const lease = hostLeases.get(host);
883
+ if (!lease)
884
+ refuse('RECOVERY_REQUIRED');
885
+ await lease.exit(nonce);
886
+ }
887
+ function textResult(value) {
888
+ return {
889
+ content: value.content.map(block => {
890
+ if (block.type !== 'text')
891
+ refuse('TOOL_DENIED');
892
+ return { type: 'text', text: block.text };
893
+ }),
894
+ details: value.details ?? null,
895
+ ...(value.isError ? { isError: true } : {}),
896
+ ...(value.structuredContent === undefined ? {} : { structuredContent: value.structuredContent }),
897
+ };
898
+ }
899
+ class HostToolProcess {
900
+ host;
901
+ input;
902
+ directory;
903
+ candidate;
904
+ operationId;
905
+ signal;
906
+ nonce = randomBytes(16).toString('hex');
907
+ name;
908
+ labels;
909
+ #cancel = new AbortController();
910
+ #bootWork = null;
911
+ #closing = false;
912
+ #readyComplete = false;
913
+ #used = false;
914
+ #scratchDir = '';
915
+ #tmpDir = '';
916
+ #ownedRoot = '';
917
+ #seatbeltProfile = null;
918
+ #canonicalCandidate = '';
919
+ #activeChild = null;
920
+ #activeExit = null;
921
+ #registeredChild = false;
922
+ #exitCode = 0;
923
+ #receipt = null;
924
+ #closedWork = null;
925
+ #onAbort;
926
+ constructor(host, input, directory, candidate, operationId, signal) {
927
+ this.host = host;
928
+ this.input = input;
929
+ this.directory = directory;
930
+ this.candidate = candidate;
931
+ this.operationId = operationId;
932
+ this.signal = signal;
933
+ this.name = 'lw-pi-tool-' + this.nonce;
934
+ this.labels = Object.freeze({
935
+ 'org.loopwright.generation': String(host.authority.generation),
936
+ 'org.loopwright.run': input.lock.spec.runId,
937
+ 'org.loopwright.session': input.sessionId,
938
+ 'org.loopwright.nonce': this.nonce,
939
+ 'org.loopwright.role': 'tool',
940
+ 'org.loopwright.operation': operationId,
941
+ });
942
+ this.#onAbort = () => {
943
+ this.#cancel.abort();
944
+ const running = this.#activeChild !== null && this.#activeChild.exitCode === null && this.#activeChild.signalCode === null;
945
+ killProcessGroup(this.#activeChild?.pid, running);
946
+ };
947
+ signal.addEventListener('abort', this.#onAbort, { once: true });
948
+ }
949
+ ready() {
950
+ if (this.#bootWork || this.#closing)
951
+ refuse('SESSION_BUSY');
952
+ const work = this.#boot();
953
+ this.#bootWork = work;
954
+ return work;
955
+ }
956
+ async #boot() {
957
+ this.signal.throwIfAborted();
958
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch) || !/^v26\./.test(process.version)) {
959
+ refuse('RUNTIME_MISMATCH', '', { phase: 'tool' });
960
+ }
961
+ if (!sameIdentity(await profileIdentity(), this.input.policy.runtime.configDigest) ||
962
+ !sameIdentity(digest(await readFile(resolveLockfileUrl())), this.input.policy.runtime.graphDigest)) {
963
+ refuse('RUNTIME_MISMATCH', '', { phase: 'tool' });
964
+ }
965
+ const resolvedCandidate = await realpath(this.candidate);
966
+ if (resolvedCandidate !== resolve(this.candidate) || !(await stat(this.candidate)).isDirectory()) {
967
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
968
+ }
969
+ this.#canonicalCandidate = resolvedCandidate;
970
+ this.#ownedRoot = await canonicalDirectory(this.host.directory);
971
+ await mkdir(this.directory, { mode: 0o700 });
972
+ const canonicalToolDir = await canonicalDirectory(this.directory);
973
+ this.#scratchDir = join(canonicalToolDir, 'scratch');
974
+ this.#tmpDir = join(canonicalToolDir, 'tmp');
975
+ await mkdir(this.#scratchDir, { mode: 0o700 });
976
+ await mkdir(this.#tmpDir, { mode: 0o700 });
977
+ await symlink(this.#canonicalCandidate, join(this.#scratchDir, 'candidate'));
978
+ this.#seatbeltProfile = process.platform === 'darwin' && existsSync('/usr/bin/sandbox-exec')
979
+ ? buildDarwinSeatbeltProfile(this.#scratchDir, this.#tmpDir)
980
+ : null;
981
+ this.#readyComplete = true;
982
+ }
983
+ async execute(name, bytes, read, guard) {
984
+ if (!this.#readyComplete || this.#closing || this.#used)
985
+ refuse('RECOVERY_REQUIRED', '', { phase: 'tool' });
986
+ this.#used = true;
987
+ const fileBytes = integer(this.input.policy.limits.fileBytes, 1, OVERLAY_LIMITS.maxMaxBytes);
988
+ const readFileMaxBytes = Math.min(fileBytes, LIMITS.artifactBytes);
989
+ const resultBytes = integer(this.input.policy.limits.toolResultBytes, 1, 4194304);
990
+ const wallMs = integer(this.input.policy.limits.toolWallMs, 1, 1800000);
991
+ guard();
992
+ let produced = 0;
993
+ let overflow = false;
994
+ let code = null;
995
+ let rawResult;
996
+ try {
997
+ if (bytes.length > 4194304)
998
+ refuse('OUTPUT_LIMIT');
999
+ const args = parseBoundedJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes), { nodes: 262144, array: 4096, properties: 512 });
1000
+ if (name === 'read') {
1001
+ if (typeof read?.path !== 'string' ||
1002
+ !read.path ||
1003
+ !/^(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+$/.test(read.path) ||
1004
+ read.path.split('/').some(part => part === '.' || part === '..')) {
1005
+ refuse('TOOL_DENIED');
1006
+ }
1007
+ const expectedPath = join(this.#canonicalCandidate, read.path);
1008
+ const expectedDigest = read.digest;
1009
+ const check = async (targetPath) => {
1010
+ if (targetPath !== expectedPath)
1011
+ refuse('TOOL_DENIED');
1012
+ const info = await lstat(targetPath);
1013
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.size > readFileMaxBytes)
1014
+ refuse('TOOL_DENIED');
1015
+ };
1016
+ const readTool = createReadTool(this.#canonicalCandidate, {
1017
+ autoResizeImages: false,
1018
+ operations: {
1019
+ access: check,
1020
+ detectImageMimeType: async () => null,
1021
+ readFile: async (targetPath) => {
1022
+ await check(targetPath);
1023
+ const fd = await open(targetPath, constants.O_RDONLY | constants.O_NOFOLLOW);
1024
+ try {
1025
+ const info = await fd.stat();
1026
+ if (!info.isFile() || info.nlink !== 1 || info.size > readFileMaxBytes)
1027
+ refuse('TOOL_DENIED');
1028
+ const buf = Buffer.alloc(info.size + 1);
1029
+ let offset = 0;
1030
+ while (offset < buf.length) {
1031
+ const next = await fd.read(buf, offset, buf.length - offset, offset);
1032
+ if (!next.bytesRead)
1033
+ break;
1034
+ offset += next.bytesRead;
1035
+ }
1036
+ const data = buf.subarray(0, offset);
1037
+ if (offset !== info.size || digest(data).hex !== expectedDigest)
1038
+ refuse('RECOVERY_REQUIRED');
1039
+ new TextDecoder('utf-8', { fatal: true }).decode(data);
1040
+ return data;
1041
+ }
1042
+ finally {
1043
+ await fd.close();
1044
+ }
1045
+ },
1046
+ },
1047
+ });
1048
+ rawResult = clampToolResultBytes(textResult(await readTool.execute('owned-read', { ...args, path: read.path }, this.#cancel.signal)), resultBytes, { tool: 'read', offset: args.offset });
1049
+ }
1050
+ else if (name === 'bash') {
1051
+ const candidateDir = this.#canonicalCandidate;
1052
+ const scratchDir = this.#scratchDir;
1053
+ const tmpDir = this.#tmpDir;
1054
+ const ownedRoot = this.#ownedRoot;
1055
+ const seatbeltProfile = this.#seatbeltProfile;
1056
+ const cleanEnv = {
1057
+ PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin',
1058
+ HOME: scratchDir,
1059
+ TMPDIR: tmpDir,
1060
+ CANDIDATE_DIR: candidateDir,
1061
+ LANG: 'C.UTF-8',
1062
+ LC_ALL: 'C.UTF-8',
1063
+ TERM: 'dumb',
1064
+ };
1065
+ const outputAbort = new AbortController();
1066
+ const bashTool = createBashTool(scratchDir, {
1067
+ exposeSessionEnvironment: false,
1068
+ shellPath: '/bin/bash',
1069
+ operations: {
1070
+ exec: async (command, cwd, options) => {
1071
+ if (cwd !== scratchDir)
1072
+ refuse('TOOL_DENIED');
1073
+ const timeoutMs = options.timeout && options.timeout > 0 ? Math.min(wallMs, options.timeout * 1000) : wallMs;
1074
+ const wallTimeout = AbortSignal.timeout(timeoutMs);
1075
+ const combined = AbortSignal.any([
1076
+ this.signal,
1077
+ this.#cancel.signal,
1078
+ outputAbort.signal,
1079
+ wallTimeout,
1080
+ ...(options.signal ? [options.signal] : []),
1081
+ ]);
1082
+ combined.throwIfAborted();
1083
+ const spawnSpec = buildHostToolBashSpawnSpec({
1084
+ candidateDir,
1085
+ scratchDir,
1086
+ tmpDir,
1087
+ ownedRoot,
1088
+ seatbeltProfile,
1089
+ command,
1090
+ });
1091
+ await registerChild(this.host, { name: this.name, nonce: this.nonce, role: 'tool', labels: this.labels });
1092
+ this.#registeredChild = true;
1093
+ const child = spawn(spawnSpec.executable, spawnSpec.args, {
1094
+ cwd: scratchDir,
1095
+ env: cleanEnv,
1096
+ detached: true,
1097
+ stdio: ['ignore', 'pipe', 'pipe'],
1098
+ });
1099
+ this.#activeChild = child;
1100
+ let resolveExit;
1101
+ this.#activeExit = new Promise(resolvePromise => { resolveExit = resolvePromise; });
1102
+ const onData = (chunk) => {
1103
+ const prevProduced = produced;
1104
+ produced += chunk.length;
1105
+ if (prevProduced < resultBytes) {
1106
+ options.onData(produced > resultBytes ? chunk.subarray(0, resultBytes - prevProduced) : chunk);
1107
+ }
1108
+ if (produced > resultBytes * 4) {
1109
+ overflow = true;
1110
+ outputAbort.abort();
1111
+ killProcessGroup(child.pid, child.exitCode === null && child.signalCode === null);
1112
+ }
1113
+ };
1114
+ child.stdout.on('data', onData);
1115
+ child.stderr.on('data', onData);
1116
+ child.once('exit', () => {
1117
+ killProcessGroup(child.pid, false);
1118
+ });
1119
+ const closePromise = new Promise((resolveClose, rejectClose) => {
1120
+ child.once('error', err => {
1121
+ resolveExit();
1122
+ rejectClose(err);
1123
+ });
1124
+ child.once('close', exit => {
1125
+ resolveExit();
1126
+ resolveClose(exit);
1127
+ });
1128
+ });
1129
+ void closePromise.catch(() => { });
1130
+ const onAbort = () => {
1131
+ killProcessGroup(child.pid, child.exitCode === null && child.signalCode === null);
1132
+ };
1133
+ combined.addEventListener('abort', onAbort, { once: true });
1134
+ if (combined.aborted)
1135
+ onAbort();
1136
+ let exitCode;
1137
+ try {
1138
+ if (child.pid && child.exitCode === null && child.signalCode === null) {
1139
+ await registerAttach(this.host, this.nonce, child.pid, true);
1140
+ }
1141
+ exitCode = await closePromise;
1142
+ }
1143
+ catch (err) {
1144
+ killProcessGroup(child.pid, child.exitCode === null && child.signalCode === null);
1145
+ throw err;
1146
+ }
1147
+ finally {
1148
+ combined.removeEventListener('abort', onAbort);
1149
+ }
1150
+ killProcessGroup(child.pid, false);
1151
+ if (this.signal.aborted || this.#cancel.signal.aborted)
1152
+ refuse('CANCELLED');
1153
+ if (wallTimeout.aborted)
1154
+ refuse('CANCELLED');
1155
+ return { exitCode: overflow ? 0 : exitCode };
1156
+ },
1157
+ },
1158
+ });
1159
+ const executedBash = textResult(await bashTool.execute('owned-bash', args, this.#cancel.signal));
1160
+ const bashWithOverflowNote = produced > resultBytes
1161
+ ? {
1162
+ ...executedBash,
1163
+ content: [
1164
+ {
1165
+ type: 'text',
1166
+ text: executedBash.content.map(item => item.text).join('\n')
1167
+ + `\n\n[Command output (${produced} bytes)${overflow ? ' exceeded stream cap and was terminated early;' : ''} truncated to fit tool result byte limit.]`,
1168
+ },
1169
+ ],
1170
+ }
1171
+ : executedBash;
1172
+ rawResult = clampToolResultBytes(bashWithOverflowNote, resultBytes, { tool: 'bash' });
1173
+ }
1174
+ else {
1175
+ refuse('TOOL_DENIED');
1176
+ }
1177
+ if (Buffer.byteLength(canonical(rawResult)) > resultBytes || rawResult.content.some(item => item.type !== 'text')) {
1178
+ refuse('OUTPUT_LIMIT');
1179
+ }
1180
+ }
1181
+ catch (error) {
1182
+ if (error instanceof PiFailure && error.detail.code === 'CONTAINMENT_MISMATCH') {
1183
+ throw error;
1184
+ }
1185
+ code = overflow
1186
+ ? 'OUTPUT_LIMIT'
1187
+ : (this.signal.aborted || this.#cancel.signal.aborted)
1188
+ ? 'CANCELLED'
1189
+ : error instanceof PiFailure
1190
+ ? error.detail.code
1191
+ : 'TOOL_DENIED';
1192
+ rawResult = { content: [{ type: 'text', text: code }], isError: true, details: null };
1193
+ }
1194
+ if (code !== null && !['TOOL_DENIED', 'OUTPUT_LIMIT', 'CANCELLED', 'RECOVERY_REQUIRED'].includes(code)) {
1195
+ refuse('RECOVERY_REQUIRED', '', { phase: 'tool', effect: 'possible' });
1196
+ }
1197
+ const raw = rawResult;
1198
+ const keys = Object.keys(raw);
1199
+ if (!keys.includes('content') ||
1200
+ !keys.includes('details') ||
1201
+ keys.some(key => !['content', 'details', 'structuredContent', 'isError'].includes(key)) ||
1202
+ Buffer.byteLength(canonical(raw)) > resultBytes) {
1203
+ refuse('OUTPUT_LIMIT', '', { phase: 'tool', effect: 'possible' });
1204
+ }
1205
+ const validated = object(raw, keys);
1206
+ if (validated.isError !== undefined && typeof validated.isError !== 'boolean') {
1207
+ refuse('RECOVERY_REQUIRED', '', { phase: 'tool', effect: 'possible' });
1208
+ }
1209
+ const content = list(validated.content, 16, '/content').map(item => {
1210
+ const block = object(item, ['type', 'text']);
1211
+ if (block.type !== 'text' || typeof block.text !== 'string')
1212
+ refuse('TOOL_DENIED', '', { phase: 'tool' });
1213
+ return { type: 'text', text: block.text };
1214
+ });
1215
+ return {
1216
+ result: { ...validated, content, details: validated.details },
1217
+ code,
1218
+ produced,
1219
+ };
1220
+ }
1221
+ close() {
1222
+ if (this.#receipt)
1223
+ return Promise.resolve(this.#receipt);
1224
+ if (this.#closedWork)
1225
+ return this.#closedWork;
1226
+ const work = this.#cleanup();
1227
+ this.#closedWork = work;
1228
+ void work.catch(() => { this.#closedWork = null; });
1229
+ return work;
1230
+ }
1231
+ async #cleanup() {
1232
+ this.#closing = true;
1233
+ this.signal.removeEventListener('abort', this.#onAbort);
1234
+ this.#cancel.abort();
1235
+ await this.#bootWork?.catch(() => { });
1236
+ if (this.#activeChild) {
1237
+ const running = this.#activeChild.exitCode === null && this.#activeChild.signalCode === null;
1238
+ killProcessGroup(this.#activeChild.pid, running);
1239
+ }
1240
+ if (this.#activeExit) {
1241
+ let timer;
1242
+ try {
1243
+ await Promise.race([
1244
+ this.#activeExit,
1245
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Host tool process cleanup deadline')), 2000); }),
1246
+ ]);
1247
+ }
1248
+ finally {
1249
+ clearTimeout(timer);
1250
+ }
1251
+ killProcessGroup(this.#activeChild?.pid, false);
1252
+ }
1253
+ if (this.#registeredChild) {
1254
+ await exitChild(this.host, this.nonce);
1255
+ this.#registeredChild = false;
1256
+ }
1257
+ if (this.#scratchDir) {
1258
+ await unlink(join(this.#scratchDir, 'candidate')).catch(() => { });
1259
+ }
1260
+ if (!this.#readyComplete)
1261
+ return null;
1262
+ const receipt = {
1263
+ id: digest(Buffer.from(this.nonce)).hex,
1264
+ exitCode: this.#exitCode,
1265
+ removed: true,
1266
+ cli: { code: this.#exitCode, signal: null },
1267
+ };
1268
+ await writeFile(join(this.directory, 'cleanup.json'), JSON.stringify(receipt), { mode: 0o600 });
1269
+ this.#receipt = receipt;
1270
+ return receipt;
1271
+ }
1272
+ }
1273
+ class HostExecution extends Execution {
1274
+ candidateDir;
1275
+ onProgress;
1276
+ onToolEnd;
1277
+ onScrub;
1278
+ getConvergenceWarning;
1279
+ #gate = Promise.resolve();
1280
+ constructor(host, input, candidateDir, ports, onProgress, onToolEnd, onScrub, getConvergenceWarning) {
1281
+ super(host, input, candidateDir, { ...ports, softScopeErrors: true, softArgumentErrors: true });
1282
+ this.candidateDir = candidateDir;
1283
+ this.onProgress = onProgress;
1284
+ this.onToolEnd = onToolEnd;
1285
+ this.onScrub = onScrub;
1286
+ this.getConvergenceWarning = getConvergenceWarning;
1287
+ }
1288
+ #extractTargetPath(identity, bytes) {
1289
+ if (!this.input.policy.tools.includes(identity.name))
1290
+ return null;
1291
+ if (bytes.byteLength > this.input.policy.limits.toolArgsBytes)
1292
+ return null;
1293
+ try {
1294
+ const value = parseBoundedJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes), { nodes: 262144, array: 4096, properties: 512 });
1295
+ if (!value || typeof value !== 'object' || Array.isArray(value))
1296
+ return null;
1297
+ const args = object(value, Object.keys(value));
1298
+ if (typeof args.path !== 'string' || !args.path)
1299
+ return null;
1300
+ return this.candidate.normalize(args.path);
1301
+ }
1302
+ catch {
1303
+ return null;
1304
+ }
1305
+ }
1306
+ #summarizeToolArgs(identity, bytes) {
1307
+ if (!this.onProgress)
1308
+ return undefined;
1309
+ 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);
1310
+ }
1311
+ invoke(identity, bytes, signal, onOperation) {
1312
+ const emitProgress = (event) => {
1313
+ try {
1314
+ this.onProgress?.(event);
1315
+ }
1316
+ catch {
1317
+ // Progress observers must never perturb session execution.
1318
+ }
1319
+ };
1320
+ const summary = this.#summarizeToolArgs(identity, bytes);
1321
+ const wrapProgress = async (work) => {
1322
+ const started = performance.now();
1323
+ emitProgress({ kind: 'tool_start', name: identity.name, ...(summary !== undefined ? { summary } : {}) });
1324
+ try {
1325
+ const res = await work();
1326
+ const isError = res.isError === true;
1327
+ this.onToolEnd?.(identity.name, isError);
1328
+ emitProgress({
1329
+ kind: 'tool_end',
1330
+ name: identity.name,
1331
+ isError,
1332
+ elapsedMs: Math.max(1, Math.round(performance.now() - started)),
1333
+ ...(summary !== undefined ? { summary } : {}),
1334
+ });
1335
+ const warning = this.getConvergenceWarning?.() ?? null;
1336
+ if (warning !== null) {
1337
+ const content = res.content.length > 0
1338
+ ? res.content.map((item, idx) => idx === res.content.length - 1
1339
+ ? { ...item, text: item.text.length > 0 ? `${item.text}\n\n${warning}` : warning }
1340
+ : item)
1341
+ : [{ type: 'text', text: warning }];
1342
+ const annotated = { ...res, content };
1343
+ if (Buffer.byteLength(canonical(annotated)) <= this.input.policy.limits.toolResultBytes) {
1344
+ return annotated;
1345
+ }
1346
+ }
1347
+ return res;
1348
+ }
1349
+ catch (error) {
1350
+ const errorCode = error instanceof PiFailure ? error.detail.code : undefined;
1351
+ const errorPath = error instanceof PiFailure && error.detail.path.length > 0 ? error.detail.path : undefined;
1352
+ this.onToolEnd?.(identity.name, true);
1353
+ emitProgress({
1354
+ kind: 'tool_end',
1355
+ name: identity.name,
1356
+ isError: true,
1357
+ elapsedMs: Math.max(1, Math.round(performance.now() - started)),
1358
+ ...(summary !== undefined ? { summary } : {}),
1359
+ ...(errorCode !== undefined ? { errorCode } : {}),
1360
+ ...(errorPath !== undefined ? { errorPath } : {}),
1361
+ });
1362
+ throw error;
1363
+ }
1364
+ };
1365
+ if (identity.name !== 'write' && identity.name !== 'edit' && identity.name !== 'delete') {
1366
+ const plain = this.#gate.then(() => wrapProgress(() => super.invoke(identity, bytes, signal, onOperation)));
1367
+ this.#gate = plain.then(() => { }, () => { });
1368
+ return plain;
1369
+ }
1370
+ const mediated = this.#gate.then(async () => {
1371
+ const relPath = this.#extractTargetPath(identity, bytes);
1372
+ const writable = relPath !== null && this.candidate.isWritable(relPath);
1373
+ if (relPath === null || !writable) {
1374
+ return await wrapProgress(() => super.invoke(identity, bytes, signal, onOperation));
1375
+ }
1376
+ const segments = relPath.split('/').slice(0, -1);
1377
+ const chain = [this.candidateDir, ...segments.map((_, index) => join(this.candidateDir, ...segments.slice(0, index + 1)))];
1378
+ const unlockedDirs = [];
1379
+ const absentBeforeOp = new Set();
1380
+ let stoppedAtNonDir = false;
1381
+ let result;
1382
+ let opFailed = false;
1383
+ let opError;
1384
+ this.candidate.clearLastPrunedDirectories();
1385
+ try {
1386
+ for (let i = 0; i < chain.length; i++) {
1387
+ const dir = chain[i];
1388
+ let info;
1389
+ try {
1390
+ info = await lstat(dir);
1391
+ }
1392
+ catch (error) {
1393
+ if (error.code === 'ENOENT') {
1394
+ if (i === 0)
1395
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1396
+ if (identity.name === 'write') {
1397
+ for (let j = i; j < chain.length; j++)
1398
+ absentBeforeOp.add(chain[j]);
1399
+ }
1400
+ break;
1401
+ }
1402
+ throw error;
1403
+ }
1404
+ if (info.isSymbolicLink() || !info.isDirectory()) {
1405
+ if (i === 0)
1406
+ refuse('RECOVERY_REQUIRED', '/candidate', { phase: 'tool' });
1407
+ stoppedAtNonDir = true;
1408
+ break;
1409
+ }
1410
+ await chmod(dir, 0o755);
1411
+ unlockedDirs.push(dir);
1412
+ }
1413
+ result = await wrapProgress(() => super.invoke(identity, bytes, signal, onOperation));
1414
+ }
1415
+ catch (error) {
1416
+ opFailed = true;
1417
+ opError = error;
1418
+ }
1419
+ const prunedDirs = this.candidate.consumeLastPrunedDirectories();
1420
+ const toRelock = [...unlockedDirs, ...(stoppedAtNonDir ? [] : absentBeforeOp)];
1421
+ let relockError = null;
1422
+ for (let i = toRelock.length - 1; i >= 0; i--) {
1423
+ const dir = toRelock[i];
1424
+ try {
1425
+ await chmod(dir, 0o555);
1426
+ const verified = await lstat(dir);
1427
+ if (!verified.isDirectory() || verified.isSymbolicLink() || (verified.mode & 0o777) !== 0o555) {
1428
+ relockError ??= new PiFailure({ code: 'RECOVERY_REQUIRED', path: '/candidate', phase: 'tool', retryable: false, effect: 'possible', requestId: null, operationId: null, stateErrorCode: null });
1429
+ }
1430
+ }
1431
+ catch (error) {
1432
+ const isAbsent = error.code === 'ENOENT';
1433
+ const tolerateAbsent = isAbsent && dir !== this.candidateDir && ((identity.name === 'delete' && prunedDirs.has(resolve(dir)))
1434
+ || (identity.name === 'write' && absentBeforeOp.has(dir)));
1435
+ if (tolerateAbsent)
1436
+ continue;
1437
+ relockError ??= new PiFailure({ code: 'RECOVERY_REQUIRED', path: '/candidate', phase: 'tool', retryable: false, effect: 'possible', requestId: null, operationId: null, stateErrorCode: null });
1438
+ }
1439
+ }
1440
+ if (opFailed && (relockError === null || (opError instanceof PiFailure && opError.detail.code === 'RECOVERY_REQUIRED'))) {
1441
+ throw opError;
1442
+ }
1443
+ if (relockError !== null)
1444
+ throw relockError;
1445
+ if (opFailed)
1446
+ throw opError;
1447
+ return result;
1448
+ });
1449
+ this.#gate = mediated.then(() => { }, () => { });
1450
+ return mediated;
1451
+ }
1452
+ }
1453
+ class HostMcpProcess extends EventEmitter {
1454
+ input;
1455
+ candidateDir;
1456
+ #initialized = false;
1457
+ #readyState = false;
1458
+ #closed = false;
1459
+ #failed = false;
1460
+ #tail = Promise.resolve();
1461
+ #pending = 0;
1462
+ constructor(input, candidateDir) {
1463
+ super();
1464
+ this.input = input;
1465
+ this.candidateDir = candidateDir;
1466
+ }
1467
+ #fail() {
1468
+ if (!this.#closed && !this.#failed) {
1469
+ this.#failed = true;
1470
+ this.emit('failed');
1471
+ }
1472
+ }
1473
+ async ready(signal) {
1474
+ signal.throwIfAborted();
1475
+ if (this.#closed || this.#failed)
1476
+ refuse('MCP_FAILED', '', { phase: 'tool' });
1477
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch) || !/^v26\./.test(process.version)) {
1478
+ refuse('RUNTIME_MISMATCH', '', { phase: 'tool' });
1479
+ }
1480
+ if ((await realpath(this.candidateDir)) !== resolve(this.candidateDir) || !(await stat(this.candidateDir)).isDirectory()) {
1481
+ refuse('CONTAINMENT_MISMATCH', '', { phase: 'tool' });
1482
+ }
1483
+ }
1484
+ async send(message, guard) {
1485
+ if (this.#closed || this.#failed || this.#pending >= 32)
1486
+ refuse('MCP_FAILED', '', { phase: 'tool' });
1487
+ const serialized = canonical(message) + '\n';
1488
+ if (Buffer.byteLength(serialized) > 65536)
1489
+ refuse('OUTPUT_LIMIT', '', { phase: 'tool' });
1490
+ this.#pending++;
1491
+ const work = this.#tail.then(async () => {
1492
+ if (this.#closed || this.#failed)
1493
+ refuse('MCP_FAILED', '', { phase: 'tool' });
1494
+ guard();
1495
+ await this.#dispatch(message);
1496
+ });
1497
+ this.#tail = work.catch(() => { this.#fail(); });
1498
+ try {
1499
+ await work;
1500
+ }
1501
+ finally {
1502
+ this.#pending--;
1503
+ }
1504
+ }
1505
+ async #dispatch(value) {
1506
+ if (!('method' in value)) {
1507
+ this.#fail();
1508
+ return;
1509
+ }
1510
+ if (!('id' in value)) {
1511
+ if (value.method === 'notifications/initialized' && this.#initialized) {
1512
+ this.#readyState = true;
1513
+ }
1514
+ else if (value.method !== 'notifications/cancelled') {
1515
+ this.#fail();
1516
+ }
1517
+ return;
1518
+ }
1519
+ const emitReply = (payload) => {
1520
+ const bytes = Buffer.byteLength(canonical(payload)) + 1;
1521
+ if (bytes > 65536) {
1522
+ this.#fail();
1523
+ return;
1524
+ }
1525
+ queueMicrotask(() => {
1526
+ if (!this.#closed && !this.#failed)
1527
+ this.emit('message', payload);
1528
+ });
1529
+ };
1530
+ if (value.method === 'initialize' && !this.#initialized) {
1531
+ this.#initialized = true;
1532
+ emitReply({
1533
+ jsonrpc: '2.0',
1534
+ id: value.id,
1535
+ result: {
1536
+ protocolVersion: '2025-06-18',
1537
+ capabilities: { tools: {} },
1538
+ serverInfo: { name: 'loopwright-workspace', version: '1' },
1539
+ },
1540
+ });
1541
+ return;
1542
+ }
1543
+ if (!this.#readyState) {
1544
+ this.#fail();
1545
+ return;
1546
+ }
1547
+ if (value.method === 'tools/list') {
1548
+ emitReply({ jsonrpc: '2.0', id: value.id, result: { tools: [WORKSPACE_TOOL] } });
1549
+ return;
1550
+ }
1551
+ if (value.method !== 'tools/call') {
1552
+ emitReply({ jsonrpc: '2.0', id: value.id, error: { code: -32601, message: 'MCP_FAILED' } });
1553
+ return;
1554
+ }
1555
+ let result;
1556
+ try {
1557
+ const keys = Object.keys(value.params ?? {});
1558
+ const params = object(value.params, keys);
1559
+ if (keys.some(k => !['name', 'arguments', '_meta'].includes(k)) || params.name !== 'read_file') {
1560
+ refuse('TOOL_DENIED', '', { phase: 'tool' });
1561
+ }
1562
+ const args = object(params.arguments, ['path']);
1563
+ if (typeof args.path !== 'string')
1564
+ refuse('TOOL_DENIED', '', { phase: 'tool' });
1565
+ result = { content: [{ type: 'text', text: await readWorkspace(this.candidateDir, args.path, 65536) }] };
1566
+ if (Buffer.byteLength(canonical({ jsonrpc: '2.0', id: value.id, result })) + 1 > 65536) {
1567
+ refuse('OUTPUT_LIMIT', '', { phase: 'tool' });
1568
+ }
1569
+ }
1570
+ catch (error) {
1571
+ const code = error instanceof PiFailure ? error.detail.code : 'MCP_FAILED';
1572
+ result = { isError: true, content: [{ type: 'text', text: code }] };
1573
+ }
1574
+ emitReply({ jsonrpc: '2.0', id: value.id, result });
1575
+ }
1576
+ async close() {
1577
+ this.#closed = true;
1578
+ await this.#tail.catch(() => { });
1579
+ return null;
1580
+ }
1581
+ }
1582
+ class HostRuntimeSession {
1583
+ host;
1584
+ input;
1585
+ broker;
1586
+ directory;
1587
+ options;
1588
+ breaker;
1589
+ nonce = randomBytes(16).toString('hex');
1590
+ name = 'lw-pi-' + this.nonce;
1591
+ #process = null;
1592
+ #channel = null;
1593
+ #snapshots = null;
1594
+ #bootWork = null;
1595
+ #creationAttempted = false;
1596
+ #closing = null;
1597
+ #exited = null;
1598
+ #closed = false;
1599
+ #cleanupComplete = false;
1600
+ #failed = false;
1601
+ #pending = null;
1602
+ #invocationStartedMs = new Map();
1603
+ constructor(host, input, broker, directory, options, breaker) {
1604
+ this.host = host;
1605
+ this.input = input;
1606
+ this.broker = broker;
1607
+ this.directory = directory;
1608
+ this.options = options;
1609
+ this.breaker = breaker;
1610
+ }
1611
+ start() {
1612
+ if (this.#bootWork || this.#closed)
1613
+ refuse('SESSION_BUSY');
1614
+ const work = this.#boot();
1615
+ this.#bootWork = work;
1616
+ return work.catch(async (error) => {
1617
+ await this.close();
1618
+ throw error;
1619
+ });
1620
+ }
1621
+ async #boot() {
1622
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch)) {
1623
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
1624
+ }
1625
+ if (!/^v26\./.test(process.version)) {
1626
+ refuse('RUNTIME_MISMATCH', '/host/runtime');
1627
+ }
1628
+ if (!sameIdentity(await profileIdentity(), this.input.policy.runtime.configDigest)) {
1629
+ refuse('RUNTIME_MISMATCH', '/policy/runtime/configDigest');
1630
+ }
1631
+ const lockBytes = await readFile(resolveLockfileUrl());
1632
+ if (!sameIdentity(digest(lockBytes), this.input.policy.runtime.graphDigest)) {
1633
+ refuse('RUNTIME_MISMATCH', '/policy/runtime/graphDigest');
1634
+ }
1635
+ await mkdir(this.directory, { mode: 0o700 });
1636
+ const canonicalDir = await realpath(this.directory);
1637
+ const homeDir = join(canonicalDir, 'home');
1638
+ const tmpDir = join(canonicalDir, 'tmp');
1639
+ await mkdir(homeDir, { mode: 0o700 });
1640
+ await mkdir(tmpDir, { mode: 0o700 });
1641
+ const candidateDir = join(this.directory, 'candidate');
1642
+ await materializeCandidateDirectory(candidateDir, this.input);
1643
+ const labels = Object.freeze({
1644
+ 'org.loopwright.generation': String(this.host.authority.generation),
1645
+ 'org.loopwright.run': this.input.lock.spec.runId,
1646
+ 'org.loopwright.session': this.input.sessionId,
1647
+ 'org.loopwright.nonce': this.nonce,
1648
+ });
1649
+ await writeFile(join(this.directory, 'process-intent.json'), JSON.stringify({ version: 1, name: this.name, nonce: this.nonce, labels }), { flag: 'wx', mode: 0o600 });
1650
+ await registerChild(this.host, { name: this.name, nonce: this.nonce, role: 'sdk', labels });
1651
+ this.#creationAttempted = true;
1652
+ if (this.#closed)
1653
+ refuse('CANCELLED');
1654
+ const workerScript = fileURLToPath(new URL('./sdk-worker.js', import.meta.url));
1655
+ const child = spawn(process.execPath, [workerScript, this.nonce], {
1656
+ cwd: canonicalDir,
1657
+ detached: true,
1658
+ stdio: ['pipe', 'pipe', 'pipe'],
1659
+ env: {
1660
+ PATH: '/usr/local/bin:/usr/bin:/bin',
1661
+ HOME: homeDir,
1662
+ TMPDIR: tmpDir,
1663
+ PI_OFFLINE: '1',
1664
+ LOOPWRIGHT_HOST_SESSION: '1',
1665
+ LANG: 'C.UTF-8',
1666
+ LC_ALL: 'C.UTF-8',
1667
+ TERM: 'dumb',
1668
+ },
1669
+ });
1670
+ this.#process = child;
1671
+ this.#exited = new Promise(resolvePromise => {
1672
+ child.once('exit', (code, signal) => resolvePromise({ code, signal }));
1673
+ child.once('error', () => {
1674
+ this.#fail();
1675
+ resolvePromise({ code: null, signal: null });
1676
+ });
1677
+ });
1678
+ const diagnosticLimit = this.input.policy.limits.diagnosticBytes;
1679
+ const retainedLimit = Math.floor((diagnosticLimit - 64) * 3 / 4);
1680
+ let stderrBytes = 0;
1681
+ let retained = Buffer.alloc(0);
1682
+ child.stderr.on('data', (data) => {
1683
+ stderrBytes += data.length;
1684
+ const keep = Math.min(data.length, Math.max(0, retainedLimit - retained.length));
1685
+ if (keep)
1686
+ retained = Buffer.concat([retained, data.subarray(0, keep)]);
1687
+ try {
1688
+ if (this.input.policy.privateArtifacts) {
1689
+ writeFileSync(join(this.directory, 'private-sdk-stderr'), JSON.stringify({ encoding: 'base64', truncated: stderrBytes > retained.length, data: retained.toString('base64') }) + '\n', { mode: 0o600 });
1690
+ }
1691
+ }
1692
+ catch {
1693
+ this.#fail();
1694
+ }
1695
+ if (stderrBytes > diagnosticLimit) {
1696
+ this.broker.runtimeFault?.('OUTPUT_LIMIT');
1697
+ this.#fail();
1698
+ }
1699
+ });
1700
+ this.#channel = new Channel(this.nonce, child.stdout, child.stdin);
1701
+ this.#snapshots = new SnapshotTransfer(this.#channel);
1702
+ this.#channel.on('failed', () => this.#fail());
1703
+ this.#channel.on('message', (message) => {
1704
+ void this.#receive(message).catch(() => this.#fail());
1705
+ });
1706
+ await registerAttach(this.host, this.nonce, child.pid);
1707
+ const roleMcpAllowlist = resolveSessionMcpAllowlist(this.input, this.options);
1708
+ const permittedToolNames = roleMcpAllowlist.filterToolNames(this.input.policy.tools);
1709
+ const restored = await recoverSnapshot(this.host, this.input);
1710
+ if (restored) {
1711
+ const accepted = this.#wait('restore-ready');
1712
+ await Promise.all([
1713
+ this.#channel.send('restore-start', {
1714
+ selection: this.input.policy.selection,
1715
+ toolNames: permittedToolNames,
1716
+ sessionBytes: this.input.policy.limits.sessionBytes,
1717
+ }),
1718
+ accepted,
1719
+ ]);
1720
+ async function* chunks() {
1721
+ yield restored.native;
1722
+ }
1723
+ const complete = this.#wait('restore-complete', 90000);
1724
+ await Promise.all([
1725
+ this.#snapshots.send(1, chunks(), this.input.policy.limits.sessionBytes),
1726
+ complete,
1727
+ ]);
1728
+ }
1729
+ const ready = this.#wait('ready');
1730
+ const externalMcpTools = this.options?.mcpRegistry
1731
+ ? this.options.mcpRegistry
1732
+ .toolSchemasFor(permittedToolNames, this.options.allowedMcpServers)
1733
+ .filter(schema => roleMcpAllowlist.isToolAllowed(schema.name, schema.serverId))
1734
+ : [];
1735
+ const [, response] = await Promise.all([
1736
+ this.#channel.send('init', {
1737
+ selection: this.input.policy.selection,
1738
+ systemPrompt: systemPrompt(this.input),
1739
+ toolNames: permittedToolNames,
1740
+ mcp: this.input.policy.mcp,
1741
+ toolArgsBytes: this.input.policy.limits.toolArgsBytes,
1742
+ toolResultBytes: this.input.policy.limits.toolResultBytes,
1743
+ sessionBytes: this.input.policy.limits.sessionBytes,
1744
+ outputTokens: Math.min(this.input.lock.spec.contract.spec.budgets.perCallOutputTokens, this.input.policy.context.maxOutputTokens),
1745
+ contextPolicy: this.input.policy.context,
1746
+ ...(externalMcpTools.length > 0 ? { externalMcpTools } : {}),
1747
+ }),
1748
+ ready,
1749
+ ]);
1750
+ const facts = response;
1751
+ if (!sameIdentity(facts.selection, this.input.policy.selection) ||
1752
+ facts.thinkingLevel !== this.input.policy.selection.thinking ||
1753
+ !/^v26\./.test(process.version) ||
1754
+ facts.node !== process.version ||
1755
+ typeof facts.platform !== 'string' ||
1756
+ typeof facts.architecture !== 'string' ||
1757
+ !isSupportedHostSessionPlatform(facts.platform, facts.architecture)) {
1758
+ refuse('RUNTIME_MISMATCH');
1759
+ }
1760
+ return freeze({
1761
+ version: 1,
1762
+ policyDigest: digest(Buffer.from(canonical(this.input.policy))),
1763
+ runtime: this.input.policy.runtime,
1764
+ requested: this.input.policy.selection,
1765
+ catalogSupported: structuredClone(this.input.policy.selection),
1766
+ sessionEffective: structuredClone(this.input.policy.selection),
1767
+ outboundObserved: null,
1768
+ resources: this.input.policy.resources,
1769
+ accounting: 'soft_only',
1770
+ contextFit: 'unproven',
1771
+ defaultMode: 'proven_bound',
1772
+ liveProvenBoundAvailable: false,
1773
+ optInMode: 'estimated_guard',
1774
+ contextEstimator: { id: 'lw-pi-final-json-bytes-v1', version: 1, provenance: 'estimated' },
1775
+ toolExecution: { candidate: 'read_only', candidateWrites: 'mediated', scratch: 'per_call' },
1776
+ });
1777
+ }
1778
+ #wait(kind, timeoutMs = 10000, remaining) {
1779
+ if (this.#pending)
1780
+ refuse('SESSION_BUSY', '', { phase: 'session' });
1781
+ if (this.#failed)
1782
+ refuse('RECOVERY_REQUIRED', '', { phase: 'session' });
1783
+ return new Promise((resolvePromise, rejectPromise) => {
1784
+ let stop = () => { };
1785
+ const expires = performance.now() + timeoutMs;
1786
+ this.#pending = {
1787
+ kind,
1788
+ resolve: value => {
1789
+ stop();
1790
+ this.#pending = null;
1791
+ resolvePromise(value);
1792
+ },
1793
+ reject: error => {
1794
+ stop();
1795
+ this.#pending = null;
1796
+ rejectPromise(error);
1797
+ },
1798
+ };
1799
+ stop = scheduleDeadline(remaining ?? (() => expires - performance.now()), () => {
1800
+ this.#pending = null;
1801
+ rejectPromise(new PiFailure({
1802
+ code: 'DEADLINE',
1803
+ path: '',
1804
+ phase: 'session',
1805
+ retryable: false,
1806
+ effect: 'possible',
1807
+ requestId: null,
1808
+ operationId: null,
1809
+ stateErrorCode: null,
1810
+ }));
1811
+ this.#fail();
1812
+ });
1813
+ });
1814
+ }
1815
+ async #receive(message) {
1816
+ if (this.#closed)
1817
+ throw new Error('Closed SDK channel');
1818
+ if (await this.#snapshots.receive(message))
1819
+ return;
1820
+ if (message.kind === 'invoke' && message.body && typeof message.body === 'object') {
1821
+ const inv = message.body;
1822
+ if (typeof inv.invocation === 'number' && typeof inv.provider === 'string' && typeof inv.model === 'string') {
1823
+ const tripped = this.breaker?.onBeforeInvoke() ?? null;
1824
+ if (tripped !== null) {
1825
+ try {
1826
+ this.options?.onProgress?.({
1827
+ kind: 'circuit_breaker',
1828
+ reason: tripped.reason,
1829
+ turn: tripped.turn,
1830
+ message: tripped.message,
1831
+ });
1832
+ }
1833
+ catch {
1834
+ // Ignore observer errors.
1835
+ }
1836
+ }
1837
+ else {
1838
+ this.#invocationStartedMs.set(inv.invocation, performance.now());
1839
+ try {
1840
+ this.options?.onProgress?.({
1841
+ kind: 'request_start',
1842
+ turn: inv.invocation,
1843
+ provider: inv.provider,
1844
+ model: inv.model,
1845
+ });
1846
+ }
1847
+ catch {
1848
+ // Ignore observer errors.
1849
+ }
1850
+ }
1851
+ }
1852
+ }
1853
+ const handled = await receiveBrokerMessage(this.#channel, this.broker, message);
1854
+ if (handled) {
1855
+ if (message.kind === 'parsed' && message.body && typeof message.body === 'object') {
1856
+ const parsed = message.body;
1857
+ if (typeof parsed.invocation === 'number') {
1858
+ const startedAt = this.#invocationStartedMs.get(parsed.invocation);
1859
+ this.#invocationStartedMs.delete(parsed.invocation);
1860
+ if (!this.breaker?.tripped) {
1861
+ const inputTokens = (typeof parsed.usage?.input === 'number' ? parsed.usage.input : 0)
1862
+ + (typeof parsed.usage?.cacheRead === 'number' ? parsed.usage.cacheRead : 0)
1863
+ + (typeof parsed.usage?.cacheWrite === 'number' ? parsed.usage.cacheWrite : 0);
1864
+ const outputTokens = typeof parsed.usage?.output === 'number' ? parsed.usage.output : 0;
1865
+ const toolCallNames = Array.isArray(parsed.toolCalls)
1866
+ ? parsed.toolCalls.map(item => (typeof item?.name === 'string' ? item.name : '')).filter(Boolean)
1867
+ : [];
1868
+ this.breaker?.onRequestSettled(toolCallNames.length > 0);
1869
+ try {
1870
+ this.options?.onProgress?.({
1871
+ kind: 'request_settled',
1872
+ turn: parsed.invocation,
1873
+ stopReason: typeof parsed.stopReason === 'string' ? parsed.stopReason : 'stop',
1874
+ inputTokens,
1875
+ outputTokens,
1876
+ elapsedMs: Math.max(1, Math.round(performance.now() - (startedAt ?? performance.now()))),
1877
+ toolCallNames,
1878
+ });
1879
+ }
1880
+ catch {
1881
+ // Ignore observer errors.
1882
+ }
1883
+ }
1884
+ }
1885
+ }
1886
+ return;
1887
+ }
1888
+ if (message.kind === 'refused') {
1889
+ this.#snapshots?.close();
1890
+ const body = message.body;
1891
+ const code = body.code === 'MODEL_UNAVAILABLE' || body.code === 'THINKING_UNSUPPORTED'
1892
+ ? body.code
1893
+ : 'PROVIDER_RESPONSE_INVALID';
1894
+ this.#pending?.reject(new PiFailure({
1895
+ code,
1896
+ path: '/policy/selection',
1897
+ phase: 'session',
1898
+ retryable: false,
1899
+ effect: 'none',
1900
+ requestId: null,
1901
+ operationId: null,
1902
+ stateErrorCode: null,
1903
+ }));
1904
+ return;
1905
+ }
1906
+ if (!this.#pending || message.kind !== this.#pending.kind)
1907
+ throw new Error('Unrequested SDK result');
1908
+ this.#pending.resolve(message.body);
1909
+ }
1910
+ #fail() {
1911
+ if (!this.#closed) {
1912
+ this.#failed = true;
1913
+ this.#snapshots?.close();
1914
+ this.#pending?.reject(new Error('SDK channel failed'));
1915
+ }
1916
+ }
1917
+ async command(kind, body) {
1918
+ if (this.#closed || !this.#channel)
1919
+ refuse('CANCELLED', '', { phase: 'session' });
1920
+ const view = stateValue(this.host.store.inspect(), 'session');
1921
+ const remaining = view.clock.remainingTaskMs.safeValue;
1922
+ if (remaining === null || remaining <= 0)
1923
+ refuse('DEADLINE', '', { phase: 'session' });
1924
+ const rawRepair = kind === 'execute' && body && typeof body === 'object' && 'repair' in body
1925
+ ? body.repair
1926
+ : 'none';
1927
+ this.breaker?.beginDispatch(kind, rawRepair === 'format' || rawRepair === 'implementation' ? rawRepair : 'none');
1928
+ const pending = this.#wait('settled', undefined, () => {
1929
+ const current = this.host.store.inspect();
1930
+ return current.ok && current.value.clockStatus === 'trusted' ? current.value.clock.remainingTaskMs.safeValue : null;
1931
+ });
1932
+ const [, response] = await Promise.all([this.#channel.send(kind, body), pending]);
1933
+ verifyNativeCompletion(response.native, kind);
1934
+ return response;
1935
+ }
1936
+ async capture(sink) {
1937
+ if (this.#closed || !this.#channel || !this.#snapshots)
1938
+ refuse('CANCELLED');
1939
+ const view = stateValue(this.host.store.inspect(), 'restore');
1940
+ const remaining = view.clock.remainingTaskMs.safeValue;
1941
+ if (remaining === null || remaining <= 0)
1942
+ refuse('DEADLINE');
1943
+ const expected = this.#snapshots.expect(sink, this.input.policy.limits.sessionBytes, Math.min(90000, remaining));
1944
+ try {
1945
+ await this.#channel.send('capture', { query: expected.query });
1946
+ await expected.done;
1947
+ }
1948
+ catch (error) {
1949
+ this.#snapshots.close();
1950
+ if (error instanceof PiFailure && error.detail.code !== 'INPUT_INVALID')
1951
+ throw error;
1952
+ refuse('RECOVERY_REQUIRED', '', { phase: 'restore' });
1953
+ }
1954
+ }
1955
+ close() {
1956
+ if (this.#closing)
1957
+ return this.#closing;
1958
+ const attempt = this.#cleanup();
1959
+ this.#closing = attempt;
1960
+ void attempt.then(() => { this.#closing = null; }, () => { this.#closing = null; });
1961
+ return attempt;
1962
+ }
1963
+ async #cleanup() {
1964
+ if (this.#cleanupComplete)
1965
+ return;
1966
+ this.#closed = true;
1967
+ this.#snapshots?.close();
1968
+ this.#pending?.reject(new Error('closed'));
1969
+ await this.#bootWork?.catch(() => { });
1970
+ let leaderExited = false;
1971
+ try {
1972
+ if (this.#channel) {
1973
+ try {
1974
+ await this.#channel.send('close', null);
1975
+ }
1976
+ catch { /* process-group cleanup follows */ }
1977
+ this.#channel.close();
1978
+ }
1979
+ if (this.#exited && this.#process && this.#process.exitCode === null && this.#process.signalCode === null) {
1980
+ let timer;
1981
+ try {
1982
+ await Promise.race([this.#exited, new Promise(resolvePromise => { timer = setTimeout(resolvePromise, 500); })]);
1983
+ }
1984
+ finally {
1985
+ clearTimeout(timer);
1986
+ }
1987
+ }
1988
+ leaderExited = this.#process !== null && (this.#process.exitCode !== null || this.#process.signalCode !== null);
1989
+ if (!this.#creationAttempted) {
1990
+ if (existsSync(join(this.directory, 'candidate'))) {
1991
+ await setDirectoryTreeMode(join(this.directory, 'candidate'), 0o755).catch(() => { });
1992
+ }
1993
+ this.#cleanupComplete = true;
1994
+ return;
1995
+ }
1996
+ }
1997
+ finally {
1998
+ const exitedNow = leaderExited || (this.#process !== null && (this.#process.exitCode !== null || this.#process.signalCode !== null));
1999
+ killProcessGroup(this.#process?.pid, !exitedNow);
2000
+ this.#process?.stdin.destroy();
2001
+ this.#process?.stdout.destroy();
2002
+ this.#process?.stderr.destroy();
2003
+ }
2004
+ let exit = { code: null, signal: null };
2005
+ if (this.#exited) {
2006
+ let timer;
2007
+ try {
2008
+ exit = await Promise.race([
2009
+ this.#exited,
2010
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Host SDK worker cleanup deadline')), 2000); }),
2011
+ ]);
2012
+ }
2013
+ finally {
2014
+ clearTimeout(timer);
2015
+ }
2016
+ killProcessGroup(this.#process?.pid, false);
2017
+ }
2018
+ if (existsSync(join(this.directory, 'candidate'))) {
2019
+ await setDirectoryTreeMode(join(this.directory, 'candidate'), 0o755).catch(() => { });
2020
+ }
2021
+ await writeFile(join(this.directory, 'cleanup.json'), JSON.stringify({
2022
+ id: digest(Buffer.from(this.nonce)).hex,
2023
+ nonce: this.nonce,
2024
+ pid: this.#process?.pid ?? null,
2025
+ removed: true,
2026
+ absenceConfirmed: true,
2027
+ state: exit,
2028
+ }), { mode: 0o600 });
2029
+ await writeFile(join(this.directory, 'cli-exit.json'), JSON.stringify(exit), { mode: 0o600 });
2030
+ await exitChild(this.host, this.nonce);
2031
+ this.#cleanupComplete = true;
2032
+ }
2033
+ }
2034
+ async function environment(host) {
2035
+ if (!isSupportedHostSessionPlatform(process.platform, process.arch)) {
2036
+ refuse('RUNTIME_UNSUPPORTED', '/host/runtime');
2037
+ }
2038
+ try {
2039
+ await canonicalDirectory(host.directory);
2040
+ await canonicalDirectory(host.artifactsDirectory);
2041
+ }
2042
+ catch {
2043
+ refuse('CONTAINMENT_UNAVAILABLE');
2044
+ }
2045
+ }
2046
+ function createHostSessionPorts(options) {
2047
+ const breaker = new HostSessionCircuitBreaker();
2048
+ return Object.freeze({
2049
+ environment: async (host) => {
2050
+ validateAllowedMcpServers(options?.allowedMcpServers);
2051
+ breaker.configure(options?.circuitBreaker);
2052
+ await environment(host);
2053
+ },
2054
+ lease: (host, input) => HostExecutionLease.acquire(host, input),
2055
+ sender: (host, owned) => {
2056
+ breaker.bindBudgets(owned.lock.spec.contract.spec.budgets, owned.policy.limits.requests);
2057
+ return new Sender(host, owned, {
2058
+ fetch: globalThis.fetch,
2059
+ catalog: selectedCatalog(owned),
2060
+ beforeSend: () => breaker.assertBeforeSend(),
2061
+ });
2062
+ },
2063
+ execution: (host, owned, candidateDir) => {
2064
+ const roleMcpAllowlist = resolveSessionMcpAllowlist(owned, options);
2065
+ return new HostExecution(host, owned, candidateDir, {
2066
+ process: (operationId, signal) => new HostToolProcess(host, owned, join(host.directory, 'tool-' + operationId), candidateDir, operationId, signal),
2067
+ ...(options?.mcpRegistry !== undefined
2068
+ ? { mcpExecutor: createRoleScopedMcpExecutor(options.mcpRegistry, roleMcpAllowlist) }
2069
+ : {}),
2070
+ }, options?.onProgress, (name, isError) => breaker.recordToolEnd(name, isError), options?.scrub, () => breaker.convergenceWarning());
2071
+ },
2072
+ mcp: (_host, owned) => ({
2073
+ process: () => new HostMcpProcess(owned, join(_host.directory, 'sdk-' + owned.sessionId, 'candidate')),
2074
+ }),
2075
+ session: (host, owned, sender, directory) => new HostRuntimeSession(host, owned, sender, directory, options, breaker),
2076
+ });
2077
+ }
2078
+ export function openPiHostSessionAdapter(host, input, options) {
2079
+ return constructAdapter(host, input, createHostSessionPorts(options));
2080
+ }
2081
+ export function openPiHostSessionAdapterV2(host, input, options) {
2082
+ return constructAdapterV2(host, input, createHostSessionPorts(options));
2083
+ }