@tickernelz/wardmote-adapter-utils 0.0.0 → 2026.1108.1

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 (2040) hide show
  1. package/README.md +47 -5
  2. package/dist/acpx-engine/cli.d.ts +2 -0
  3. package/dist/acpx-engine/cli.d.ts.map +1 -0
  4. package/dist/acpx-engine/cli.js +128 -0
  5. package/dist/acpx-engine/cli.js.map +1 -0
  6. package/dist/acpx-engine/composed-run-characterization.test.d.ts +2 -0
  7. package/dist/acpx-engine/composed-run-characterization.test.d.ts.map +1 -0
  8. package/dist/acpx-engine/composed-run-characterization.test.js +720 -0
  9. package/dist/acpx-engine/composed-run-characterization.test.js.map +1 -0
  10. package/dist/acpx-engine/constants.d.ts +10 -0
  11. package/dist/acpx-engine/constants.d.ts.map +1 -0
  12. package/dist/acpx-engine/constants.js +25 -0
  13. package/dist/acpx-engine/constants.js.map +1 -0
  14. package/dist/acpx-engine/ephemeral-session-environment.d.ts +4 -0
  15. package/dist/acpx-engine/ephemeral-session-environment.d.ts.map +1 -0
  16. package/dist/acpx-engine/ephemeral-session-environment.js +29 -0
  17. package/dist/acpx-engine/ephemeral-session-environment.js.map +1 -0
  18. package/dist/acpx-engine/ephemeral-session-environment.test.d.ts +2 -0
  19. package/dist/acpx-engine/ephemeral-session-environment.test.d.ts.map +1 -0
  20. package/dist/acpx-engine/ephemeral-session-environment.test.js +177 -0
  21. package/dist/acpx-engine/ephemeral-session-environment.test.js.map +1 -0
  22. package/dist/acpx-engine/execute-identity.test.d.ts +2 -0
  23. package/dist/acpx-engine/execute-identity.test.d.ts.map +1 -0
  24. package/dist/acpx-engine/execute-identity.test.js +218 -0
  25. package/dist/acpx-engine/execute-identity.test.js.map +1 -0
  26. package/dist/acpx-engine/execute.d.ts +322 -0
  27. package/dist/acpx-engine/execute.d.ts.map +1 -0
  28. package/dist/acpx-engine/execute.js +4671 -0
  29. package/dist/acpx-engine/execute.js.map +1 -0
  30. package/dist/acpx-engine/execute.test.d.ts +2 -0
  31. package/dist/acpx-engine/execute.test.d.ts.map +1 -0
  32. package/dist/acpx-engine/execute.test.js +7282 -0
  33. package/dist/acpx-engine/execute.test.js.map +1 -0
  34. package/dist/acpx-engine/filesystem-protocol.test.d.ts +2 -0
  35. package/dist/acpx-engine/filesystem-protocol.test.d.ts.map +1 -0
  36. package/dist/acpx-engine/filesystem-protocol.test.js +99 -0
  37. package/dist/acpx-engine/filesystem-protocol.test.js.map +1 -0
  38. package/dist/acpx-engine/index.d.ts +6 -0
  39. package/dist/acpx-engine/index.d.ts.map +1 -0
  40. package/dist/acpx-engine/index.js +6 -0
  41. package/dist/acpx-engine/index.js.map +1 -0
  42. package/dist/acpx-engine/local-process-control.d.ts +5 -0
  43. package/dist/acpx-engine/local-process-control.d.ts.map +1 -0
  44. package/dist/acpx-engine/local-process-control.js +39 -0
  45. package/dist/acpx-engine/local-process-control.js.map +1 -0
  46. package/dist/acpx-engine/local-process-control.test.d.ts +2 -0
  47. package/dist/acpx-engine/local-process-control.test.d.ts.map +1 -0
  48. package/dist/acpx-engine/local-process-control.test.js +38 -0
  49. package/dist/acpx-engine/local-process-control.test.js.map +1 -0
  50. package/dist/acpx-engine/operator-stop.test.d.ts +2 -0
  51. package/dist/acpx-engine/operator-stop.test.d.ts.map +1 -0
  52. package/dist/acpx-engine/operator-stop.test.js +107 -0
  53. package/dist/acpx-engine/operator-stop.test.js.map +1 -0
  54. package/dist/acpx-engine/read-only-permissions.test.d.ts +2 -0
  55. package/dist/acpx-engine/read-only-permissions.test.d.ts.map +1 -0
  56. package/dist/acpx-engine/read-only-permissions.test.js +33 -0
  57. package/dist/acpx-engine/read-only-permissions.test.js.map +1 -0
  58. package/dist/acpx-engine/remote-spawn-smoke.test.d.ts +2 -0
  59. package/dist/acpx-engine/remote-spawn-smoke.test.d.ts.map +1 -0
  60. package/dist/acpx-engine/remote-spawn-smoke.test.js +151 -0
  61. package/dist/acpx-engine/remote-spawn-smoke.test.js.map +1 -0
  62. package/dist/acpx-engine/run-contracts.d.ts +415 -0
  63. package/dist/acpx-engine/run-contracts.d.ts.map +1 -0
  64. package/dist/acpx-engine/run-contracts.js +20 -0
  65. package/dist/acpx-engine/run-contracts.js.map +1 -0
  66. package/dist/acpx-engine/run-contracts.test.d.ts +2 -0
  67. package/dist/acpx-engine/run-contracts.test.d.ts.map +1 -0
  68. package/dist/acpx-engine/run-contracts.test.js +57 -0
  69. package/dist/acpx-engine/run-contracts.test.js.map +1 -0
  70. package/dist/acpx-engine/run-coordinator.d.ts +57 -0
  71. package/dist/acpx-engine/run-coordinator.d.ts.map +1 -0
  72. package/dist/acpx-engine/run-coordinator.js +63 -0
  73. package/dist/acpx-engine/run-coordinator.js.map +1 -0
  74. package/dist/acpx-engine/run-coordinator.test.d.ts +2 -0
  75. package/dist/acpx-engine/run-coordinator.test.d.ts.map +1 -0
  76. package/dist/acpx-engine/run-coordinator.test.js +160 -0
  77. package/dist/acpx-engine/run-coordinator.test.js.map +1 -0
  78. package/dist/acpx-engine/run-fault-matrix.test.d.ts +2 -0
  79. package/dist/acpx-engine/run-fault-matrix.test.d.ts.map +1 -0
  80. package/dist/acpx-engine/run-fault-matrix.test.js +829 -0
  81. package/dist/acpx-engine/run-fault-matrix.test.js.map +1 -0
  82. package/dist/acpx-engine/run-resource-ledger.d.ts +30 -0
  83. package/dist/acpx-engine/run-resource-ledger.d.ts.map +1 -0
  84. package/dist/acpx-engine/run-resource-ledger.js +148 -0
  85. package/dist/acpx-engine/run-resource-ledger.js.map +1 -0
  86. package/dist/acpx-engine/run-resource-ledger.test.d.ts +2 -0
  87. package/dist/acpx-engine/run-resource-ledger.test.d.ts.map +1 -0
  88. package/dist/acpx-engine/run-resource-ledger.test.js +154 -0
  89. package/dist/acpx-engine/run-resource-ledger.test.js.map +1 -0
  90. package/dist/acpx-engine/run-site-host.d.ts +73 -0
  91. package/dist/acpx-engine/run-site-host.d.ts.map +1 -0
  92. package/dist/acpx-engine/run-site-host.js +65 -0
  93. package/dist/acpx-engine/run-site-host.js.map +1 -0
  94. package/dist/acpx-engine/run-site-host.test.d.ts +2 -0
  95. package/dist/acpx-engine/run-site-host.test.d.ts.map +1 -0
  96. package/dist/acpx-engine/run-site-host.test.js +98 -0
  97. package/dist/acpx-engine/run-site-host.test.js.map +1 -0
  98. package/dist/acpx-engine/run-site-sandbox.d.ts +142 -0
  99. package/dist/acpx-engine/run-site-sandbox.d.ts.map +1 -0
  100. package/dist/acpx-engine/run-site-sandbox.js +278 -0
  101. package/dist/acpx-engine/run-site-sandbox.js.map +1 -0
  102. package/dist/acpx-engine/run-site-sandbox.test.d.ts +2 -0
  103. package/dist/acpx-engine/run-site-sandbox.test.d.ts.map +1 -0
  104. package/dist/acpx-engine/run-site-sandbox.test.js +275 -0
  105. package/dist/acpx-engine/run-site-sandbox.test.js.map +1 -0
  106. package/dist/acpx-engine/session-codec.d.ts +3 -0
  107. package/dist/acpx-engine/session-codec.d.ts.map +1 -0
  108. package/dist/acpx-engine/session-codec.js +50 -0
  109. package/dist/acpx-engine/session-codec.js.map +1 -0
  110. package/dist/acpx-engine/session-reuse-store.d.ts +62 -0
  111. package/dist/acpx-engine/session-reuse-store.d.ts.map +1 -0
  112. package/dist/acpx-engine/session-reuse-store.js +134 -0
  113. package/dist/acpx-engine/session-reuse-store.js.map +1 -0
  114. package/dist/acpx-engine/session-reuse-store.test.d.ts +2 -0
  115. package/dist/acpx-engine/session-reuse-store.test.d.ts.map +1 -0
  116. package/dist/acpx-engine/session-reuse-store.test.js +134 -0
  117. package/dist/acpx-engine/session-reuse-store.test.js.map +1 -0
  118. package/dist/acpx-engine/settlement-characterization.test.d.ts +2 -0
  119. package/dist/acpx-engine/settlement-characterization.test.d.ts.map +1 -0
  120. package/dist/acpx-engine/settlement-characterization.test.js +966 -0
  121. package/dist/acpx-engine/settlement-characterization.test.js.map +1 -0
  122. package/dist/acpx-engine/settlement-sequence.d.ts +77 -0
  123. package/dist/acpx-engine/settlement-sequence.d.ts.map +1 -0
  124. package/dist/acpx-engine/settlement-sequence.js +119 -0
  125. package/dist/acpx-engine/settlement-sequence.js.map +1 -0
  126. package/dist/acpx-engine/settlement-sequence.test.d.ts +2 -0
  127. package/dist/acpx-engine/settlement-sequence.test.d.ts.map +1 -0
  128. package/dist/acpx-engine/settlement-sequence.test.js +272 -0
  129. package/dist/acpx-engine/settlement-sequence.test.js.map +1 -0
  130. package/dist/acpx-engine/spawn-smoke.test.d.ts +2 -0
  131. package/dist/acpx-engine/spawn-smoke.test.d.ts.map +1 -0
  132. package/dist/acpx-engine/spawn-smoke.test.js +193 -0
  133. package/dist/acpx-engine/spawn-smoke.test.js.map +1 -0
  134. package/dist/acpx-engine/startup-cancellation.d.ts +9 -0
  135. package/dist/acpx-engine/startup-cancellation.d.ts.map +1 -0
  136. package/dist/acpx-engine/startup-cancellation.js +97 -0
  137. package/dist/acpx-engine/startup-cancellation.js.map +1 -0
  138. package/dist/acpx-engine/startup-cancellation.test.d.ts +2 -0
  139. package/dist/acpx-engine/startup-cancellation.test.d.ts.map +1 -0
  140. package/dist/acpx-engine/startup-cancellation.test.js +115 -0
  141. package/dist/acpx-engine/startup-cancellation.test.js.map +1 -0
  142. package/dist/acpx-engine/startup-characterization.test.d.ts +2 -0
  143. package/dist/acpx-engine/startup-characterization.test.d.ts.map +1 -0
  144. package/dist/acpx-engine/startup-characterization.test.js +742 -0
  145. package/dist/acpx-engine/startup-characterization.test.js.map +1 -0
  146. package/dist/acpx-engine/startup-timing.d.ts +419 -0
  147. package/dist/acpx-engine/startup-timing.d.ts.map +1 -0
  148. package/dist/acpx-engine/startup-timing.js +616 -0
  149. package/dist/acpx-engine/startup-timing.js.map +1 -0
  150. package/dist/acpx-engine/startup-timing.test.d.ts +2 -0
  151. package/dist/acpx-engine/startup-timing.test.d.ts.map +1 -0
  152. package/dist/acpx-engine/startup-timing.test.js +619 -0
  153. package/dist/acpx-engine/startup-timing.test.js.map +1 -0
  154. package/dist/acpx-engine/terminal-session-failure.d.ts +18 -0
  155. package/dist/acpx-engine/terminal-session-failure.d.ts.map +1 -0
  156. package/dist/acpx-engine/terminal-session-failure.js +106 -0
  157. package/dist/acpx-engine/terminal-session-failure.js.map +1 -0
  158. package/dist/acpx-engine/terminal-session-failure.test.d.ts +2 -0
  159. package/dist/acpx-engine/terminal-session-failure.test.d.ts.map +1 -0
  160. package/dist/acpx-engine/terminal-session-failure.test.js +139 -0
  161. package/dist/acpx-engine/terminal-session-failure.test.js.map +1 -0
  162. package/dist/acpx-engine/turn-characterization.test.d.ts +2 -0
  163. package/dist/acpx-engine/turn-characterization.test.d.ts.map +1 -0
  164. package/dist/acpx-engine/turn-characterization.test.js +567 -0
  165. package/dist/acpx-engine/turn-characterization.test.js.map +1 -0
  166. package/dist/acpx-engine/turn-sequence.d.ts +54 -0
  167. package/dist/acpx-engine/turn-sequence.d.ts.map +1 -0
  168. package/dist/acpx-engine/turn-sequence.js +75 -0
  169. package/dist/acpx-engine/turn-sequence.js.map +1 -0
  170. package/dist/acpx-engine/turn-sequence.test.d.ts +2 -0
  171. package/dist/acpx-engine/turn-sequence.test.d.ts.map +1 -0
  172. package/dist/acpx-engine/turn-sequence.test.js +177 -0
  173. package/dist/acpx-engine/turn-sequence.test.js.map +1 -0
  174. package/dist/acpx-engine/ui.d.ts +3 -0
  175. package/dist/acpx-engine/ui.d.ts.map +1 -0
  176. package/dist/acpx-engine/ui.js +162 -0
  177. package/dist/acpx-engine/ui.js.map +1 -0
  178. package/dist/adapter-steer-registry.d.ts +24 -0
  179. package/dist/adapter-steer-registry.d.ts.map +1 -0
  180. package/dist/adapter-steer-registry.js +65 -0
  181. package/dist/adapter-steer-registry.js.map +1 -0
  182. package/dist/adapter-steer-registry.test.d.ts +2 -0
  183. package/dist/adapter-steer-registry.test.d.ts.map +1 -0
  184. package/dist/adapter-steer-registry.test.js +121 -0
  185. package/dist/adapter-steer-registry.test.js.map +1 -0
  186. package/dist/agent-todo.d.ts +2 -0
  187. package/dist/agent-todo.d.ts.map +1 -0
  188. package/dist/agent-todo.js +2 -0
  189. package/dist/agent-todo.js.map +1 -0
  190. package/dist/billing.d.ts +9 -0
  191. package/dist/billing.d.ts.map +1 -0
  192. package/dist/billing.js +39 -0
  193. package/dist/billing.js.map +1 -0
  194. package/dist/billing.test.d.ts +2 -0
  195. package/dist/billing.test.d.ts.map +1 -0
  196. package/dist/billing.test.js +30 -0
  197. package/dist/billing.test.js.map +1 -0
  198. package/dist/bridge-transport-contract.d.ts +43 -0
  199. package/dist/bridge-transport-contract.d.ts.map +1 -0
  200. package/dist/bridge-transport-contract.js +33 -0
  201. package/dist/bridge-transport-contract.js.map +1 -0
  202. package/dist/chat-file-delivery.d.ts +10 -0
  203. package/dist/chat-file-delivery.d.ts.map +1 -0
  204. package/dist/chat-file-delivery.js +39 -0
  205. package/dist/chat-file-delivery.js.map +1 -0
  206. package/dist/chat-file-delivery.test.d.ts +2 -0
  207. package/dist/chat-file-delivery.test.d.ts.map +1 -0
  208. package/dist/chat-file-delivery.test.js +92 -0
  209. package/dist/chat-file-delivery.test.js.map +1 -0
  210. package/dist/command-managed-runtime.d.ts +165 -0
  211. package/dist/command-managed-runtime.d.ts.map +1 -0
  212. package/dist/command-managed-runtime.js +460 -0
  213. package/dist/command-managed-runtime.js.map +1 -0
  214. package/dist/command-managed-runtime.test.d.ts +2 -0
  215. package/dist/command-managed-runtime.test.d.ts.map +1 -0
  216. package/dist/command-managed-runtime.test.js +908 -0
  217. package/dist/command-managed-runtime.test.js.map +1 -0
  218. package/dist/command-redaction.d.ts +17 -0
  219. package/dist/command-redaction.d.ts.map +1 -0
  220. package/dist/command-redaction.js +107 -0
  221. package/dist/command-redaction.js.map +1 -0
  222. package/dist/command-redaction.test.d.ts +2 -0
  223. package/dist/command-redaction.test.d.ts.map +1 -0
  224. package/dist/command-redaction.test.js +99 -0
  225. package/dist/command-redaction.test.js.map +1 -0
  226. package/dist/connection-failure.d.ts +23 -0
  227. package/dist/connection-failure.d.ts.map +1 -0
  228. package/dist/connection-failure.js +36 -0
  229. package/dist/connection-failure.js.map +1 -0
  230. package/dist/connection-failure.test.d.ts +2 -0
  231. package/dist/connection-failure.test.d.ts.map +1 -0
  232. package/dist/connection-failure.test.js +85 -0
  233. package/dist/connection-failure.test.js.map +1 -0
  234. package/dist/directory-merge-lock.test.d.ts +2 -0
  235. package/dist/directory-merge-lock.test.d.ts.map +1 -0
  236. package/dist/directory-merge-lock.test.js +168 -0
  237. package/dist/directory-merge-lock.test.js.map +1 -0
  238. package/dist/duplex-frame-codec.d.ts +124 -0
  239. package/dist/duplex-frame-codec.d.ts.map +1 -0
  240. package/dist/duplex-frame-codec.js +134 -0
  241. package/dist/duplex-frame-codec.js.map +1 -0
  242. package/dist/duplex-frame-codec.test.d.ts +2 -0
  243. package/dist/duplex-frame-codec.test.d.ts.map +1 -0
  244. package/dist/duplex-frame-codec.test.js +172 -0
  245. package/dist/duplex-frame-codec.test.js.map +1 -0
  246. package/dist/duplex-observability.d.ts +220 -0
  247. package/dist/duplex-observability.d.ts.map +1 -0
  248. package/dist/duplex-observability.js +248 -0
  249. package/dist/duplex-observability.js.map +1 -0
  250. package/dist/duplex-observability.test.d.ts +2 -0
  251. package/dist/duplex-observability.test.d.ts.map +1 -0
  252. package/dist/duplex-observability.test.js +55 -0
  253. package/dist/duplex-observability.test.js.map +1 -0
  254. package/dist/env-aliases-run.test.d.ts +2 -0
  255. package/dist/env-aliases-run.test.d.ts.map +1 -0
  256. package/dist/env-aliases-run.test.js +49 -0
  257. package/dist/env-aliases-run.test.js.map +1 -0
  258. package/dist/env-bindings.d.ts +17 -0
  259. package/dist/env-bindings.d.ts.map +1 -0
  260. package/dist/env-bindings.js +98 -0
  261. package/dist/env-bindings.js.map +1 -0
  262. package/dist/env-bindings.test.d.ts +2 -0
  263. package/dist/env-bindings.test.d.ts.map +1 -0
  264. package/dist/env-bindings.test.js +66 -0
  265. package/dist/env-bindings.test.js.map +1 -0
  266. package/dist/exclude-patterns.d.ts +4 -0
  267. package/dist/exclude-patterns.d.ts.map +1 -0
  268. package/dist/exclude-patterns.js +26 -0
  269. package/dist/exclude-patterns.js.map +1 -0
  270. package/dist/execution-phase.d.ts +10 -0
  271. package/dist/execution-phase.d.ts.map +1 -0
  272. package/dist/execution-phase.js +27 -0
  273. package/dist/execution-phase.js.map +1 -0
  274. package/dist/execution-phase.test.d.ts +2 -0
  275. package/dist/execution-phase.test.d.ts.map +1 -0
  276. package/dist/execution-phase.test.js +26 -0
  277. package/dist/execution-phase.test.js.map +1 -0
  278. package/dist/execution-target-sandbox.test.d.ts +2 -0
  279. package/dist/execution-target-sandbox.test.d.ts.map +1 -0
  280. package/dist/execution-target-sandbox.test.js +6792 -0
  281. package/dist/execution-target-sandbox.test.js.map +1 -0
  282. package/dist/execution-target-stdin-race.test.d.ts +2 -0
  283. package/dist/execution-target-stdin-race.test.d.ts.map +1 -0
  284. package/dist/execution-target-stdin-race.test.js +2085 -0
  285. package/dist/execution-target-stdin-race.test.js.map +1 -0
  286. package/dist/execution-target.d.ts +553 -0
  287. package/dist/execution-target.d.ts.map +1 -0
  288. package/dist/execution-target.js +3973 -0
  289. package/dist/execution-target.js.map +1 -0
  290. package/dist/execution-target.test.d.ts +2 -0
  291. package/dist/execution-target.test.d.ts.map +1 -0
  292. package/dist/execution-target.test.js +346 -0
  293. package/dist/execution-target.test.js.map +1 -0
  294. package/dist/git-workspace-sync.d.ts +203 -0
  295. package/dist/git-workspace-sync.d.ts.map +1 -0
  296. package/dist/git-workspace-sync.js +938 -0
  297. package/dist/git-workspace-sync.js.map +1 -0
  298. package/dist/git-workspace-sync.test.d.ts +2 -0
  299. package/dist/git-workspace-sync.test.d.ts.map +1 -0
  300. package/dist/git-workspace-sync.test.js +1183 -0
  301. package/dist/git-workspace-sync.test.js.map +1 -0
  302. package/dist/github-launcher-environment.test.d.ts +2 -0
  303. package/dist/github-launcher-environment.test.d.ts.map +1 -0
  304. package/dist/github-launcher-environment.test.js +322 -0
  305. package/dist/github-launcher-environment.test.js.map +1 -0
  306. package/dist/github-launcher.d.ts +8 -0
  307. package/dist/github-launcher.d.ts.map +1 -0
  308. package/dist/github-launcher.js +142 -0
  309. package/dist/github-launcher.js.map +1 -0
  310. package/dist/github-launcher.test.d.ts +2 -0
  311. package/dist/github-launcher.test.d.ts.map +1 -0
  312. package/dist/github-launcher.test.js +199 -0
  313. package/dist/github-launcher.test.js.map +1 -0
  314. package/dist/http2-bridge-server.d.ts +465 -0
  315. package/dist/http2-bridge-server.d.ts.map +1 -0
  316. package/dist/http2-bridge-server.js +1087 -0
  317. package/dist/http2-bridge-server.js.map +1 -0
  318. package/dist/http2-bridge-server.test.d.ts +2 -0
  319. package/dist/http2-bridge-server.test.d.ts.map +1 -0
  320. package/dist/http2-bridge-server.test.js +2129 -0
  321. package/dist/http2-bridge-server.test.js.map +1 -0
  322. package/dist/index.d.ts +22 -0
  323. package/dist/index.d.ts.map +1 -0
  324. package/dist/index.js +13 -0
  325. package/dist/index.js.map +1 -0
  326. package/dist/live-stdin-channel.d.ts +11 -0
  327. package/dist/live-stdin-channel.d.ts.map +1 -0
  328. package/dist/live-stdin-channel.js +56 -0
  329. package/dist/live-stdin-channel.js.map +1 -0
  330. package/dist/live-stdin-reachability.test.d.ts +2 -0
  331. package/dist/live-stdin-reachability.test.d.ts.map +1 -0
  332. package/dist/live-stdin-reachability.test.js +25 -0
  333. package/dist/live-stdin-reachability.test.js.map +1 -0
  334. package/dist/local-process-sandbox.d.ts +41 -0
  335. package/dist/local-process-sandbox.d.ts.map +1 -0
  336. package/dist/local-process-sandbox.js +432 -0
  337. package/dist/local-process-sandbox.js.map +1 -0
  338. package/dist/local-process-sandbox.test.d.ts +2 -0
  339. package/dist/local-process-sandbox.test.d.ts.map +1 -0
  340. package/dist/local-process-sandbox.test.js +399 -0
  341. package/dist/local-process-sandbox.test.js.map +1 -0
  342. package/dist/log-redaction.d.ts +9 -0
  343. package/dist/log-redaction.d.ts.map +1 -0
  344. package/dist/log-redaction.js +88 -0
  345. package/dist/log-redaction.js.map +1 -0
  346. package/dist/login-capability.d.ts +88 -0
  347. package/dist/login-capability.d.ts.map +1 -0
  348. package/dist/login-capability.js +78 -0
  349. package/dist/login-capability.js.map +1 -0
  350. package/dist/login-capability.test.d.ts +2 -0
  351. package/dist/login-capability.test.d.ts.map +1 -0
  352. package/dist/login-capability.test.js +78 -0
  353. package/dist/login-capability.test.js.map +1 -0
  354. package/dist/login-pty-transport.d.ts +80 -0
  355. package/dist/login-pty-transport.d.ts.map +1 -0
  356. package/dist/login-pty-transport.js +75 -0
  357. package/dist/login-pty-transport.js.map +1 -0
  358. package/dist/login-pty-transport.test.d.ts +2 -0
  359. package/dist/login-pty-transport.test.d.ts.map +1 -0
  360. package/dist/login-pty-transport.test.js +185 -0
  361. package/dist/login-pty-transport.test.js.map +1 -0
  362. package/dist/login-runner-lifecycle.d.ts +70 -0
  363. package/dist/login-runner-lifecycle.d.ts.map +1 -0
  364. package/dist/login-runner-lifecycle.js +52 -0
  365. package/dist/login-runner-lifecycle.js.map +1 -0
  366. package/dist/login-runner-lifecycle.test.d.ts +2 -0
  367. package/dist/login-runner-lifecycle.test.d.ts.map +1 -0
  368. package/dist/login-runner-lifecycle.test.js +122 -0
  369. package/dist/login-runner-lifecycle.test.js.map +1 -0
  370. package/dist/mcp-isolation.integration.test.d.ts +2 -0
  371. package/dist/mcp-isolation.integration.test.d.ts.map +1 -0
  372. package/dist/mcp-isolation.integration.test.js +202 -0
  373. package/dist/mcp-isolation.integration.test.js.map +1 -0
  374. package/dist/paperclip-mcp-mount.d.ts +36 -0
  375. package/dist/paperclip-mcp-mount.d.ts.map +1 -0
  376. package/dist/paperclip-mcp-mount.js +101 -0
  377. package/dist/paperclip-mcp-mount.js.map +1 -0
  378. package/dist/paperclip-mcp.d.ts +53 -0
  379. package/dist/paperclip-mcp.d.ts.map +1 -0
  380. package/dist/paperclip-mcp.js +149 -0
  381. package/dist/paperclip-mcp.js.map +1 -0
  382. package/dist/paperclip-mcp.test.d.ts +2 -0
  383. package/dist/paperclip-mcp.test.d.ts.map +1 -0
  384. package/dist/paperclip-mcp.test.js +133 -0
  385. package/dist/paperclip-mcp.test.js.map +1 -0
  386. package/dist/paperclip-runner-permissions.d.ts +148 -0
  387. package/dist/paperclip-runner-permissions.d.ts.map +1 -0
  388. package/dist/paperclip-runner-permissions.js +184 -0
  389. package/dist/paperclip-runner-permissions.js.map +1 -0
  390. package/dist/paperclip-runner-permissions.test.d.ts +2 -0
  391. package/dist/paperclip-runner-permissions.test.d.ts.map +1 -0
  392. package/dist/paperclip-runner-permissions.test.js +80 -0
  393. package/dist/paperclip-runner-permissions.test.js.map +1 -0
  394. package/dist/prompt-sections.test.d.ts +2 -0
  395. package/dist/prompt-sections.test.d.ts.map +1 -0
  396. package/dist/prompt-sections.test.js +53 -0
  397. package/dist/prompt-sections.test.js.map +1 -0
  398. package/dist/provider-models/claude.d.ts +10 -0
  399. package/dist/provider-models/claude.d.ts.map +1 -0
  400. package/dist/provider-models/claude.js +49 -0
  401. package/dist/provider-models/claude.js.map +1 -0
  402. package/dist/provider-models/codex.d.ts +23 -0
  403. package/dist/provider-models/codex.d.ts.map +1 -0
  404. package/dist/provider-models/codex.js +160 -0
  405. package/dist/provider-models/codex.js.map +1 -0
  406. package/dist/provider-models/gemini.d.ts +6 -0
  407. package/dist/provider-models/gemini.d.ts.map +1 -0
  408. package/dist/provider-models/gemini.js +17 -0
  409. package/dist/provider-models/gemini.js.map +1 -0
  410. package/dist/provider-models/grok.d.ts +7 -0
  411. package/dist/provider-models/grok.d.ts.map +1 -0
  412. package/dist/provider-models/grok.js +13 -0
  413. package/dist/provider-models/grok.js.map +1 -0
  414. package/dist/provider-models/opencode.d.ts +8 -0
  415. package/dist/provider-models/opencode.d.ts.map +1 -0
  416. package/dist/provider-models/opencode.js +71 -0
  417. package/dist/provider-models/opencode.js.map +1 -0
  418. package/dist/provider-stopped-boundary.d.ts +7 -0
  419. package/dist/provider-stopped-boundary.d.ts.map +1 -0
  420. package/dist/provider-stopped-boundary.js +22 -0
  421. package/dist/provider-stopped-boundary.js.map +1 -0
  422. package/dist/provider-stopped-boundary.test.d.ts +2 -0
  423. package/dist/provider-stopped-boundary.test.d.ts.map +1 -0
  424. package/dist/provider-stopped-boundary.test.js +76 -0
  425. package/dist/provider-stopped-boundary.test.js.map +1 -0
  426. package/dist/published-exports.test.d.ts +2 -0
  427. package/dist/published-exports.test.d.ts.map +1 -0
  428. package/dist/published-exports.test.js +17 -0
  429. package/dist/published-exports.test.js.map +1 -0
  430. package/dist/remote-execution-env.d.ts +2 -0
  431. package/dist/remote-execution-env.d.ts.map +1 -0
  432. package/dist/remote-execution-env.js +46 -0
  433. package/dist/remote-execution-env.js.map +1 -0
  434. package/dist/remote-managed-runtime.d.ts +47 -0
  435. package/dist/remote-managed-runtime.d.ts.map +1 -0
  436. package/dist/remote-managed-runtime.js +201 -0
  437. package/dist/remote-managed-runtime.js.map +1 -0
  438. package/dist/remote-managed-runtime.test.d.ts +2 -0
  439. package/dist/remote-managed-runtime.test.d.ts.map +1 -0
  440. package/dist/remote-managed-runtime.test.js +319 -0
  441. package/dist/remote-managed-runtime.test.js.map +1 -0
  442. package/dist/run-oom-score.d.ts +16 -0
  443. package/dist/run-oom-score.d.ts.map +1 -0
  444. package/dist/run-oom-score.js +29 -0
  445. package/dist/run-oom-score.js.map +1 -0
  446. package/dist/run-oom-score.test.d.ts +2 -0
  447. package/dist/run-oom-score.test.d.ts.map +1 -0
  448. package/dist/run-oom-score.test.js +78 -0
  449. package/dist/run-oom-score.test.js.map +1 -0
  450. package/dist/runner-connectivity.d.ts +61 -0
  451. package/dist/runner-connectivity.d.ts.map +1 -0
  452. package/dist/runner-connectivity.js +81 -0
  453. package/dist/runner-connectivity.js.map +1 -0
  454. package/dist/runner-connectivity.test.d.ts +2 -0
  455. package/dist/runner-connectivity.test.d.ts.map +1 -0
  456. package/dist/runner-connectivity.test.js +183 -0
  457. package/dist/runner-connectivity.test.js.map +1 -0
  458. package/dist/runtime-progress.d.ts +48 -0
  459. package/dist/runtime-progress.d.ts.map +1 -0
  460. package/dist/runtime-progress.js +99 -0
  461. package/dist/runtime-progress.js.map +1 -0
  462. package/dist/runtime-progress.test.d.ts +2 -0
  463. package/dist/runtime-progress.test.d.ts.map +1 -0
  464. package/dist/runtime-progress.test.js +240 -0
  465. package/dist/runtime-progress.test.js.map +1 -0
  466. package/dist/sandbox-callback-bridge-body.d.ts +12 -0
  467. package/dist/sandbox-callback-bridge-body.d.ts.map +1 -0
  468. package/dist/sandbox-callback-bridge-body.js +39 -0
  469. package/dist/sandbox-callback-bridge-body.js.map +1 -0
  470. package/dist/sandbox-callback-bridge-body.test.d.ts +2 -0
  471. package/dist/sandbox-callback-bridge-body.test.d.ts.map +1 -0
  472. package/dist/sandbox-callback-bridge-body.test.js +31 -0
  473. package/dist/sandbox-callback-bridge-body.test.js.map +1 -0
  474. package/dist/sandbox-callback-bridge.d.ts +270 -0
  475. package/dist/sandbox-callback-bridge.d.ts.map +1 -0
  476. package/dist/sandbox-callback-bridge.js +2382 -0
  477. package/dist/sandbox-callback-bridge.js.map +1 -0
  478. package/dist/sandbox-callback-bridge.test.d.ts +2 -0
  479. package/dist/sandbox-callback-bridge.test.d.ts.map +1 -0
  480. package/dist/sandbox-callback-bridge.test.js +3453 -0
  481. package/dist/sandbox-callback-bridge.test.js.map +1 -0
  482. package/dist/sandbox-file-sync.test.d.ts +2 -0
  483. package/dist/sandbox-file-sync.test.d.ts.map +1 -0
  484. package/dist/sandbox-file-sync.test.js +419 -0
  485. package/dist/sandbox-file-sync.test.js.map +1 -0
  486. package/dist/sandbox-install-command.d.ts +2 -0
  487. package/dist/sandbox-install-command.d.ts.map +1 -0
  488. package/dist/sandbox-install-command.js +47 -0
  489. package/dist/sandbox-install-command.js.map +1 -0
  490. package/dist/sandbox-install-command.test.d.ts +2 -0
  491. package/dist/sandbox-install-command.test.d.ts.map +1 -0
  492. package/dist/sandbox-install-command.test.js +22 -0
  493. package/dist/sandbox-install-command.test.js.map +1 -0
  494. package/dist/sandbox-managed-runtime.d.ts +423 -0
  495. package/dist/sandbox-managed-runtime.d.ts.map +1 -0
  496. package/dist/sandbox-managed-runtime.js +1425 -0
  497. package/dist/sandbox-managed-runtime.js.map +1 -0
  498. package/dist/sandbox-managed-runtime.test.d.ts +2 -0
  499. package/dist/sandbox-managed-runtime.test.d.ts.map +1 -0
  500. package/dist/sandbox-managed-runtime.test.js +4044 -0
  501. package/dist/sandbox-managed-runtime.test.js.map +1 -0
  502. package/dist/sandbox-run-log-stream.d.ts +44 -0
  503. package/dist/sandbox-run-log-stream.d.ts.map +1 -0
  504. package/dist/sandbox-run-log-stream.js +203 -0
  505. package/dist/sandbox-run-log-stream.js.map +1 -0
  506. package/dist/sandbox-shell.d.ts +3 -0
  507. package/dist/sandbox-shell.d.ts.map +1 -0
  508. package/dist/sandbox-shell.js +7 -0
  509. package/dist/sandbox-shell.js.map +1 -0
  510. package/dist/server-utils-env.test.d.ts +2 -0
  511. package/dist/server-utils-env.test.d.ts.map +1 -0
  512. package/dist/server-utils-env.test.js +23 -0
  513. package/dist/server-utils-env.test.js.map +1 -0
  514. package/dist/server-utils.d.ts +676 -0
  515. package/dist/server-utils.d.ts.map +1 -0
  516. package/dist/server-utils.js +3450 -0
  517. package/dist/server-utils.js.map +1 -0
  518. package/dist/server-utils.test.d.ts +2 -0
  519. package/dist/server-utils.test.d.ts.map +1 -0
  520. package/dist/server-utils.test.js +3367 -0
  521. package/dist/server-utils.test.js.map +1 -0
  522. package/dist/session-compaction.d.ts +25 -0
  523. package/dist/session-compaction.d.ts.map +1 -0
  524. package/dist/session-compaction.js +115 -0
  525. package/dist/session-compaction.js.map +1 -0
  526. package/dist/skill-library-manifest.d.ts +6 -0
  527. package/dist/skill-library-manifest.d.ts.map +1 -0
  528. package/dist/skill-library-manifest.js +53 -0
  529. package/dist/skill-library-manifest.js.map +1 -0
  530. package/dist/skill-library-manifest.test.d.ts +2 -0
  531. package/dist/skill-library-manifest.test.d.ts.map +1 -0
  532. package/dist/skill-library-manifest.test.js +84 -0
  533. package/dist/skill-library-manifest.test.js.map +1 -0
  534. package/dist/skills-staging-follow-symlinks.test.d.ts +2 -0
  535. package/dist/skills-staging-follow-symlinks.test.d.ts.map +1 -0
  536. package/dist/skills-staging-follow-symlinks.test.js +97 -0
  537. package/dist/skills-staging-follow-symlinks.test.js.map +1 -0
  538. package/dist/ssh-fixture.test.d.ts +2 -0
  539. package/dist/ssh-fixture.test.d.ts.map +1 -0
  540. package/dist/ssh-fixture.test.js +1026 -0
  541. package/dist/ssh-fixture.test.js.map +1 -0
  542. package/dist/ssh.d.ts +131 -0
  543. package/dist/ssh.d.ts.map +1 -0
  544. package/dist/ssh.js +1785 -0
  545. package/dist/ssh.js.map +1 -0
  546. package/dist/sync-operation-schedule.d.ts +17 -0
  547. package/dist/sync-operation-schedule.d.ts.map +1 -0
  548. package/dist/sync-operation-schedule.js +66 -0
  549. package/dist/sync-operation-schedule.js.map +1 -0
  550. package/dist/sync-operation-schedule.test.d.ts +2 -0
  551. package/dist/sync-operation-schedule.test.d.ts.map +1 -0
  552. package/dist/sync-operation-schedule.test.js +130 -0
  553. package/dist/sync-operation-schedule.test.js.map +1 -0
  554. package/dist/test-fixtures/prompt-context.d.ts +54 -0
  555. package/dist/test-fixtures/prompt-context.d.ts.map +1 -0
  556. package/dist/test-fixtures/prompt-context.js +55 -0
  557. package/dist/test-fixtures/prompt-context.js.map +1 -0
  558. package/dist/test-support/mcp-isolation-harness.d.ts +23 -0
  559. package/dist/test-support/mcp-isolation-harness.d.ts.map +1 -0
  560. package/dist/test-support/mcp-isolation-harness.js +67 -0
  561. package/dist/test-support/mcp-isolation-harness.js.map +1 -0
  562. package/dist/tool-profile.d.ts +5 -0
  563. package/dist/tool-profile.d.ts.map +1 -0
  564. package/dist/tool-profile.js +5 -0
  565. package/dist/tool-profile.js.map +1 -0
  566. package/dist/types.d.ts +867 -0
  567. package/dist/types.d.ts.map +1 -0
  568. package/dist/types.js +5 -0
  569. package/dist/types.js.map +1 -0
  570. package/dist/usage-checkpoint.d.ts +11 -0
  571. package/dist/usage-checkpoint.d.ts.map +1 -0
  572. package/dist/usage-checkpoint.js +165 -0
  573. package/dist/usage-checkpoint.js.map +1 -0
  574. package/dist/usage-checkpoint.test.d.ts +2 -0
  575. package/dist/usage-checkpoint.test.d.ts.map +1 -0
  576. package/dist/usage-checkpoint.test.js +131 -0
  577. package/dist/usage-checkpoint.test.js.map +1 -0
  578. package/dist/workspace-git-stream.d.ts +19 -0
  579. package/dist/workspace-git-stream.d.ts.map +1 -0
  580. package/dist/workspace-git-stream.js +99 -0
  581. package/dist/workspace-git-stream.js.map +1 -0
  582. package/dist/workspace-git-stream.test.d.ts +2 -0
  583. package/dist/workspace-git-stream.test.d.ts.map +1 -0
  584. package/dist/workspace-git-stream.test.js +71 -0
  585. package/dist/workspace-git-stream.test.js.map +1 -0
  586. package/dist/workspace-manifest.d.ts +61 -0
  587. package/dist/workspace-manifest.d.ts.map +1 -0
  588. package/dist/workspace-manifest.js +257 -0
  589. package/dist/workspace-manifest.js.map +1 -0
  590. package/dist/workspace-manifest.test.d.ts +2 -0
  591. package/dist/workspace-manifest.test.d.ts.map +1 -0
  592. package/dist/workspace-manifest.test.js +160 -0
  593. package/dist/workspace-manifest.test.js.map +1 -0
  594. package/dist/workspace-restore-diagnostics.d.ts +41 -0
  595. package/dist/workspace-restore-diagnostics.d.ts.map +1 -0
  596. package/dist/workspace-restore-diagnostics.js +265 -0
  597. package/dist/workspace-restore-diagnostics.js.map +1 -0
  598. package/dist/workspace-restore-diagnostics.test.d.ts +2 -0
  599. package/dist/workspace-restore-diagnostics.test.d.ts.map +1 -0
  600. package/dist/workspace-restore-diagnostics.test.js +288 -0
  601. package/dist/workspace-restore-diagnostics.test.js.map +1 -0
  602. package/dist/workspace-restore-merge.d.ts +118 -0
  603. package/dist/workspace-restore-merge.d.ts.map +1 -0
  604. package/dist/workspace-restore-merge.js +664 -0
  605. package/dist/workspace-restore-merge.js.map +1 -0
  606. package/dist/workspace-restore-merge.test.d.ts +2 -0
  607. package/dist/workspace-restore-merge.test.d.ts.map +1 -0
  608. package/dist/workspace-restore-merge.test.js +687 -0
  609. package/dist/workspace-restore-merge.test.js.map +1 -0
  610. package/dist/workspace-restore-result.d.ts +6 -0
  611. package/dist/workspace-restore-result.d.ts.map +1 -0
  612. package/dist/workspace-restore-result.js +72 -0
  613. package/dist/workspace-restore-result.js.map +1 -0
  614. package/dist/workspace-restore-result.test.d.ts +2 -0
  615. package/dist/workspace-restore-result.test.d.ts.map +1 -0
  616. package/dist/workspace-restore-result.test.js +74 -0
  617. package/dist/workspace-restore-result.test.js.map +1 -0
  618. package/dist/workspace-restore-teardown.d.ts +29 -0
  619. package/dist/workspace-restore-teardown.d.ts.map +1 -0
  620. package/dist/workspace-restore-teardown.js +36 -0
  621. package/dist/workspace-restore-teardown.js.map +1 -0
  622. package/dist/workspace-restore-teardown.test.d.ts +2 -0
  623. package/dist/workspace-restore-teardown.test.d.ts.map +1 -0
  624. package/dist/workspace-restore-teardown.test.js +95 -0
  625. package/dist/workspace-restore-teardown.test.js.map +1 -0
  626. package/node_modules/@agentclientprotocol/sdk/LICENSE +191 -0
  627. package/node_modules/@agentclientprotocol/sdk/README.md +77 -0
  628. package/node_modules/@agentclientprotocol/sdk/dist/acp.d.ts +1637 -0
  629. package/node_modules/@agentclientprotocol/sdk/dist/acp.js +1729 -0
  630. package/node_modules/@agentclientprotocol/sdk/dist/acp.js.map +1 -0
  631. package/node_modules/@agentclientprotocol/sdk/dist/acp.test.d.ts +1 -0
  632. package/node_modules/@agentclientprotocol/sdk/dist/acp.test.js +5093 -0
  633. package/node_modules/@agentclientprotocol/sdk/dist/acp.test.js.map +1 -0
  634. package/node_modules/@agentclientprotocol/sdk/dist/connection.d.ts +277 -0
  635. package/node_modules/@agentclientprotocol/sdk/dist/connection.js +898 -0
  636. package/node_modules/@agentclientprotocol/sdk/dist/connection.js.map +1 -0
  637. package/node_modules/@agentclientprotocol/sdk/dist/connection.test.d.ts +1 -0
  638. package/node_modules/@agentclientprotocol/sdk/dist/connection.test.js +666 -0
  639. package/node_modules/@agentclientprotocol/sdk/dist/connection.test.js.map +1 -0
  640. package/node_modules/@agentclientprotocol/sdk/dist/cookie-store.d.ts +26 -0
  641. package/node_modules/@agentclientprotocol/sdk/dist/cookie-store.js +96 -0
  642. package/node_modules/@agentclientprotocol/sdk/dist/cookie-store.js.map +1 -0
  643. package/node_modules/@agentclientprotocol/sdk/dist/cookie-store.test.d.ts +1 -0
  644. package/node_modules/@agentclientprotocol/sdk/dist/cookie-store.test.js +77 -0
  645. package/node_modules/@agentclientprotocol/sdk/dist/cookie-store.test.js.map +1 -0
  646. package/node_modules/@agentclientprotocol/sdk/dist/examples/agent.d.ts +2 -0
  647. package/node_modules/@agentclientprotocol/sdk/dist/examples/agent.js +232 -0
  648. package/node_modules/@agentclientprotocol/sdk/dist/examples/agent.js.map +1 -0
  649. package/node_modules/@agentclientprotocol/sdk/dist/examples/client.d.ts +2 -0
  650. package/node_modules/@agentclientprotocol/sdk/dist/examples/client.js +132 -0
  651. package/node_modules/@agentclientprotocol/sdk/dist/examples/client.js.map +1 -0
  652. package/node_modules/@agentclientprotocol/sdk/dist/examples/dual-version-agent.d.ts +9 -0
  653. package/node_modules/@agentclientprotocol/sdk/dist/examples/dual-version-agent.js +229 -0
  654. package/node_modules/@agentclientprotocol/sdk/dist/examples/dual-version-agent.js.map +1 -0
  655. package/node_modules/@agentclientprotocol/sdk/dist/examples/http-client.d.ts +2 -0
  656. package/node_modules/@agentclientprotocol/sdk/dist/examples/http-client.js +86 -0
  657. package/node_modules/@agentclientprotocol/sdk/dist/examples/http-client.js.map +1 -0
  658. package/node_modules/@agentclientprotocol/sdk/dist/examples/http-server.d.ts +2 -0
  659. package/node_modules/@agentclientprotocol/sdk/dist/examples/http-server.js +117 -0
  660. package/node_modules/@agentclientprotocol/sdk/dist/examples/http-server.js.map +1 -0
  661. package/node_modules/@agentclientprotocol/sdk/dist/examples/ws-client.d.ts +2 -0
  662. package/node_modules/@agentclientprotocol/sdk/dist/examples/ws-client.js +88 -0
  663. package/node_modules/@agentclientprotocol/sdk/dist/examples/ws-client.js.map +1 -0
  664. package/node_modules/@agentclientprotocol/sdk/dist/http-stream.d.ts +35 -0
  665. package/node_modules/@agentclientprotocol/sdk/dist/http-stream.js +473 -0
  666. package/node_modules/@agentclientprotocol/sdk/dist/http-stream.js.map +1 -0
  667. package/node_modules/@agentclientprotocol/sdk/dist/http-stream.test.d.ts +1 -0
  668. package/node_modules/@agentclientprotocol/sdk/dist/http-stream.test.js +1380 -0
  669. package/node_modules/@agentclientprotocol/sdk/dist/http-stream.test.js.map +1 -0
  670. package/node_modules/@agentclientprotocol/sdk/dist/jsonrpc.d.ts +604 -0
  671. package/node_modules/@agentclientprotocol/sdk/dist/jsonrpc.js +1082 -0
  672. package/node_modules/@agentclientprotocol/sdk/dist/jsonrpc.js.map +1 -0
  673. package/node_modules/@agentclientprotocol/sdk/dist/jsonrpc.test.d.ts +1 -0
  674. package/node_modules/@agentclientprotocol/sdk/dist/jsonrpc.test.js +917 -0
  675. package/node_modules/@agentclientprotocol/sdk/dist/jsonrpc.test.js.map +1 -0
  676. package/node_modules/@agentclientprotocol/sdk/dist/line-buffer.d.ts +24 -0
  677. package/node_modules/@agentclientprotocol/sdk/dist/line-buffer.js +71 -0
  678. package/node_modules/@agentclientprotocol/sdk/dist/line-buffer.js.map +1 -0
  679. package/node_modules/@agentclientprotocol/sdk/dist/line-buffer.test.d.ts +1 -0
  680. package/node_modules/@agentclientprotocol/sdk/dist/line-buffer.test.js +45 -0
  681. package/node_modules/@agentclientprotocol/sdk/dist/line-buffer.test.js.map +1 -0
  682. package/node_modules/@agentclientprotocol/sdk/dist/nes/acp.d.ts +563 -0
  683. package/node_modules/@agentclientprotocol/sdk/dist/nes/acp.js +106 -0
  684. package/node_modules/@agentclientprotocol/sdk/dist/nes/acp.js.map +1 -0
  685. package/node_modules/@agentclientprotocol/sdk/dist/nes/schema/types.gen.d.ts +1261 -0
  686. package/node_modules/@agentclientprotocol/sdk/dist/nes/schema/types.gen.js +4 -0
  687. package/node_modules/@agentclientprotocol/sdk/dist/nes/schema/types.gen.js.map +1 -0
  688. package/node_modules/@agentclientprotocol/sdk/dist/nes/schema/zod.gen.d.ts +962 -0
  689. package/node_modules/@agentclientprotocol/sdk/dist/nes/schema/zod.gen.js +526 -0
  690. package/node_modules/@agentclientprotocol/sdk/dist/nes/schema/zod.gen.js.map +1 -0
  691. package/node_modules/@agentclientprotocol/sdk/dist/node-adapter.d.ts +17 -0
  692. package/node_modules/@agentclientprotocol/sdk/dist/node-adapter.js +457 -0
  693. package/node_modules/@agentclientprotocol/sdk/dist/node-adapter.js.map +1 -0
  694. package/node_modules/@agentclientprotocol/sdk/dist/node-adapter.test.d.ts +1 -0
  695. package/node_modules/@agentclientprotocol/sdk/dist/node-adapter.test.js +586 -0
  696. package/node_modules/@agentclientprotocol/sdk/dist/node-adapter.test.js.map +1 -0
  697. package/node_modules/@agentclientprotocol/sdk/dist/protocol-router.d.ts +43 -0
  698. package/node_modules/@agentclientprotocol/sdk/dist/protocol-router.js +467 -0
  699. package/node_modules/@agentclientprotocol/sdk/dist/protocol-router.js.map +1 -0
  700. package/node_modules/@agentclientprotocol/sdk/dist/protocol-router.test.d.ts +1 -0
  701. package/node_modules/@agentclientprotocol/sdk/dist/protocol-router.test.js +592 -0
  702. package/node_modules/@agentclientprotocol/sdk/dist/protocol-router.test.js.map +1 -0
  703. package/node_modules/@agentclientprotocol/sdk/dist/protocol.d.ts +11 -0
  704. package/node_modules/@agentclientprotocol/sdk/dist/protocol.js +60 -0
  705. package/node_modules/@agentclientprotocol/sdk/dist/protocol.js.map +1 -0
  706. package/node_modules/@agentclientprotocol/sdk/dist/protocol.test.d.ts +1 -0
  707. package/node_modules/@agentclientprotocol/sdk/dist/protocol.test.js +72 -0
  708. package/node_modules/@agentclientprotocol/sdk/dist/protocol.test.js.map +1 -0
  709. package/node_modules/@agentclientprotocol/sdk/dist/schema/guards.gen.d.ts +305 -0
  710. package/node_modules/@agentclientprotocol/sdk/dist/schema/guards.gen.js +355 -0
  711. package/node_modules/@agentclientprotocol/sdk/dist/schema/guards.gen.js.map +1 -0
  712. package/node_modules/@agentclientprotocol/sdk/dist/schema/index.d.ts +39 -0
  713. package/node_modules/@agentclientprotocol/sdk/dist/schema/index.js +40 -0
  714. package/node_modules/@agentclientprotocol/sdk/dist/schema/index.js.map +1 -0
  715. package/node_modules/@agentclientprotocol/sdk/dist/schema/types.gen.d.ts +5438 -0
  716. package/node_modules/@agentclientprotocol/sdk/dist/schema/types.gen.js +3 -0
  717. package/node_modules/@agentclientprotocol/sdk/dist/schema/types.gen.js.map +1 -0
  718. package/node_modules/@agentclientprotocol/sdk/dist/schema/zod.gen.d.ts +15955 -0
  719. package/node_modules/@agentclientprotocol/sdk/dist/schema/zod.gen.js +2827 -0
  720. package/node_modules/@agentclientprotocol/sdk/dist/schema/zod.gen.js.map +1 -0
  721. package/node_modules/@agentclientprotocol/sdk/dist/schema-deserialize.d.ts +31 -0
  722. package/node_modules/@agentclientprotocol/sdk/dist/schema-deserialize.js +117 -0
  723. package/node_modules/@agentclientprotocol/sdk/dist/schema-deserialize.js.map +1 -0
  724. package/node_modules/@agentclientprotocol/sdk/dist/schema-deserialize.test.d.ts +1 -0
  725. package/node_modules/@agentclientprotocol/sdk/dist/schema-deserialize.test.js +93 -0
  726. package/node_modules/@agentclientprotocol/sdk/dist/schema-deserialize.test.js.map +1 -0
  727. package/node_modules/@agentclientprotocol/sdk/dist/server-permission.test.d.ts +1 -0
  728. package/node_modules/@agentclientprotocol/sdk/dist/server-permission.test.js +261 -0
  729. package/node_modules/@agentclientprotocol/sdk/dist/server-permission.test.js.map +1 -0
  730. package/node_modules/@agentclientprotocol/sdk/dist/server-session-sse.test.d.ts +1 -0
  731. package/node_modules/@agentclientprotocol/sdk/dist/server-session-sse.test.js +536 -0
  732. package/node_modules/@agentclientprotocol/sdk/dist/server-session-sse.test.js.map +1 -0
  733. package/node_modules/@agentclientprotocol/sdk/dist/server-sse.d.ts +7 -0
  734. package/node_modules/@agentclientprotocol/sdk/dist/server-sse.js +136 -0
  735. package/node_modules/@agentclientprotocol/sdk/dist/server-sse.js.map +1 -0
  736. package/node_modules/@agentclientprotocol/sdk/dist/server-sse.test.d.ts +1 -0
  737. package/node_modules/@agentclientprotocol/sdk/dist/server-sse.test.js +106 -0
  738. package/node_modules/@agentclientprotocol/sdk/dist/server-sse.test.js.map +1 -0
  739. package/node_modules/@agentclientprotocol/sdk/dist/server-websocket-upgrade.test.d.ts +1 -0
  740. package/node_modules/@agentclientprotocol/sdk/dist/server-websocket-upgrade.test.js +1310 -0
  741. package/node_modules/@agentclientprotocol/sdk/dist/server-websocket-upgrade.test.js.map +1 -0
  742. package/node_modules/@agentclientprotocol/sdk/dist/server.d.ts +82 -0
  743. package/node_modules/@agentclientprotocol/sdk/dist/server.js +414 -0
  744. package/node_modules/@agentclientprotocol/sdk/dist/server.js.map +1 -0
  745. package/node_modules/@agentclientprotocol/sdk/dist/server.test.d.ts +1 -0
  746. package/node_modules/@agentclientprotocol/sdk/dist/server.test.js +1646 -0
  747. package/node_modules/@agentclientprotocol/sdk/dist/server.test.js.map +1 -0
  748. package/node_modules/@agentclientprotocol/sdk/dist/sse.d.ts +6 -0
  749. package/node_modules/@agentclientprotocol/sdk/dist/sse.js +114 -0
  750. package/node_modules/@agentclientprotocol/sdk/dist/sse.js.map +1 -0
  751. package/node_modules/@agentclientprotocol/sdk/dist/sse.test.d.ts +1 -0
  752. package/node_modules/@agentclientprotocol/sdk/dist/sse.test.js +126 -0
  753. package/node_modules/@agentclientprotocol/sdk/dist/sse.test.js.map +1 -0
  754. package/node_modules/@agentclientprotocol/sdk/dist/stream-limits.d.ts +15 -0
  755. package/node_modules/@agentclientprotocol/sdk/dist/stream-limits.js +58 -0
  756. package/node_modules/@agentclientprotocol/sdk/dist/stream-limits.js.map +1 -0
  757. package/node_modules/@agentclientprotocol/sdk/dist/stream.d.ts +38 -0
  758. package/node_modules/@agentclientprotocol/sdk/dist/stream.js +119 -0
  759. package/node_modules/@agentclientprotocol/sdk/dist/stream.js.map +1 -0
  760. package/node_modules/@agentclientprotocol/sdk/dist/stream.test.d.ts +1 -0
  761. package/node_modules/@agentclientprotocol/sdk/dist/stream.test.js +195 -0
  762. package/node_modules/@agentclientprotocol/sdk/dist/stream.test.js.map +1 -0
  763. package/node_modules/@agentclientprotocol/sdk/dist/test-support/streams.d.ts +8 -0
  764. package/node_modules/@agentclientprotocol/sdk/dist/test-support/streams.js +51 -0
  765. package/node_modules/@agentclientprotocol/sdk/dist/test-support/streams.js.map +1 -0
  766. package/node_modules/@agentclientprotocol/sdk/dist/test-support/test-agent.d.ts +24 -0
  767. package/node_modules/@agentclientprotocol/sdk/dist/test-support/test-agent.js +163 -0
  768. package/node_modules/@agentclientprotocol/sdk/dist/test-support/test-agent.js.map +1 -0
  769. package/node_modules/@agentclientprotocol/sdk/dist/test-support/test-http-server.d.ts +9 -0
  770. package/node_modules/@agentclientprotocol/sdk/dist/test-support/test-http-server.js +74 -0
  771. package/node_modules/@agentclientprotocol/sdk/dist/test-support/test-http-server.js.map +1 -0
  772. package/node_modules/@agentclientprotocol/sdk/dist/test-support/until.d.ts +5 -0
  773. package/node_modules/@agentclientprotocol/sdk/dist/test-support/until.js +14 -0
  774. package/node_modules/@agentclientprotocol/sdk/dist/test-support/until.js.map +1 -0
  775. package/node_modules/@agentclientprotocol/sdk/dist/v2/acp.d.ts +961 -0
  776. package/node_modules/@agentclientprotocol/sdk/dist/v2/acp.js +1451 -0
  777. package/node_modules/@agentclientprotocol/sdk/dist/v2/acp.js.map +1 -0
  778. package/node_modules/@agentclientprotocol/sdk/dist/v2/acp.test.d.ts +1 -0
  779. package/node_modules/@agentclientprotocol/sdk/dist/v2/acp.test.js +1423 -0
  780. package/node_modules/@agentclientprotocol/sdk/dist/v2/acp.test.js.map +1 -0
  781. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/guards.gen.d.ts +1084 -0
  782. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/guards.gen.js +1157 -0
  783. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/guards.gen.js.map +1 -0
  784. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/index.d.ts +30 -0
  785. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/index.js +31 -0
  786. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/index.js.map +1 -0
  787. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/types.gen.d.ts +5672 -0
  788. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/types.gen.js +3 -0
  789. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/types.gen.js.map +1 -0
  790. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/zod.gen.d.ts +37653 -0
  791. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/zod.gen.js +2952 -0
  792. package/node_modules/@agentclientprotocol/sdk/dist/v2/schema/zod.gen.js.map +1 -0
  793. package/node_modules/@agentclientprotocol/sdk/dist/ws-server.d.ts +14 -0
  794. package/node_modules/@agentclientprotocol/sdk/dist/ws-server.js +485 -0
  795. package/node_modules/@agentclientprotocol/sdk/dist/ws-server.js.map +1 -0
  796. package/node_modules/@agentclientprotocol/sdk/dist/ws-stream.d.ts +54 -0
  797. package/node_modules/@agentclientprotocol/sdk/dist/ws-stream.js +253 -0
  798. package/node_modules/@agentclientprotocol/sdk/dist/ws-stream.js.map +1 -0
  799. package/node_modules/@agentclientprotocol/sdk/dist/ws-stream.test.d.ts +1 -0
  800. package/node_modules/@agentclientprotocol/sdk/dist/ws-stream.test.js +836 -0
  801. package/node_modules/@agentclientprotocol/sdk/dist/ws-stream.test.js.map +1 -0
  802. package/node_modules/@agentclientprotocol/sdk/dist/ws-utils.d.ts +19 -0
  803. package/node_modules/@agentclientprotocol/sdk/dist/ws-utils.js +78 -0
  804. package/node_modules/@agentclientprotocol/sdk/dist/ws-utils.js.map +1 -0
  805. package/node_modules/@agentclientprotocol/sdk/dist/ws-utils.test.d.ts +1 -0
  806. package/node_modules/@agentclientprotocol/sdk/dist/ws-utils.test.js +42 -0
  807. package/node_modules/@agentclientprotocol/sdk/dist/ws-utils.test.js.map +1 -0
  808. package/node_modules/@agentclientprotocol/sdk/package.json +110 -0
  809. package/node_modules/@agentclientprotocol/sdk/schema/schema.json +7852 -0
  810. package/node_modules/@agentclientprotocol/sdk/schema/v2/schema.unstable.json +8814 -0
  811. package/node_modules/@clack/core/LICENSE +9 -0
  812. package/node_modules/@clack/core/README.md +22 -0
  813. package/node_modules/@clack/core/dist/index.d.mts +503 -0
  814. package/node_modules/@clack/core/dist/index.mjs +1003 -0
  815. package/node_modules/@clack/core/package.json +63 -0
  816. package/node_modules/@clack/prompts/LICENSE +9 -0
  817. package/node_modules/@clack/prompts/README.md +396 -0
  818. package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
  819. package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
  820. package/node_modules/@clack/prompts/package.json +67 -0
  821. package/node_modules/acpx/LICENSE +21 -0
  822. package/node_modules/acpx/README.md +424 -0
  823. package/node_modules/acpx/dist/cli-CxsS1XQp.js +197 -0
  824. package/node_modules/acpx/dist/cli-CxsS1XQp.js.map +1 -0
  825. package/node_modules/acpx/dist/cli.d.ts +14 -0
  826. package/node_modules/acpx/dist/cli.d.ts.map +1 -0
  827. package/node_modules/acpx/dist/cli.js +2683 -0
  828. package/node_modules/acpx/dist/cli.js.map +1 -0
  829. package/node_modules/acpx/dist/client-DwNyFauq.d.ts +192 -0
  830. package/node_modules/acpx/dist/client-DwNyFauq.d.ts.map +1 -0
  831. package/node_modules/acpx/dist/flags-Bjq_XQ4-.js +260 -0
  832. package/node_modules/acpx/dist/flags-Bjq_XQ4-.js.map +1 -0
  833. package/node_modules/acpx/dist/flows-Db_LZKu9.js +1920 -0
  834. package/node_modules/acpx/dist/flows-Db_LZKu9.js.map +1 -0
  835. package/node_modules/acpx/dist/flows.d.ts +318 -0
  836. package/node_modules/acpx/dist/flows.d.ts.map +1 -0
  837. package/node_modules/acpx/dist/flows.js +2 -0
  838. package/node_modules/acpx/dist/live-checkpoint-ClPCSdrW.js +6214 -0
  839. package/node_modules/acpx/dist/live-checkpoint-ClPCSdrW.js.map +1 -0
  840. package/node_modules/acpx/dist/output-CjdF5rHk.js +4593 -0
  841. package/node_modules/acpx/dist/output-CjdF5rHk.js.map +1 -0
  842. package/node_modules/acpx/dist/runtime.d.ts +472 -0
  843. package/node_modules/acpx/dist/runtime.d.ts.map +1 -0
  844. package/node_modules/acpx/dist/runtime.js +1711 -0
  845. package/node_modules/acpx/dist/runtime.js.map +1 -0
  846. package/node_modules/acpx/dist/session-options-jkYbBxGE.d.ts +278 -0
  847. package/node_modules/acpx/dist/session-options-jkYbBxGE.d.ts.map +1 -0
  848. package/node_modules/acpx/package.json +129 -0
  849. package/node_modules/acpx/skills/acpx/SKILL.md +617 -0
  850. package/node_modules/b4a/LICENSE +201 -0
  851. package/node_modules/b4a/README.md +153 -0
  852. package/node_modules/b4a/browser.js +546 -0
  853. package/node_modules/b4a/index.d.ts +144 -0
  854. package/node_modules/b4a/index.js +193 -0
  855. package/node_modules/b4a/lib/ascii.js +31 -0
  856. package/node_modules/b4a/lib/base64.js +64 -0
  857. package/node_modules/b4a/lib/hex.js +51 -0
  858. package/node_modules/b4a/lib/latin1.js +31 -0
  859. package/node_modules/b4a/lib/utf16le.js +40 -0
  860. package/node_modules/b4a/lib/utf8.js +144 -0
  861. package/node_modules/b4a/package.json +54 -0
  862. package/node_modules/b4a/react-native.js +5 -0
  863. package/node_modules/b4a/runtime.d.ts +14 -0
  864. package/node_modules/bare-buffer/CMakeLists.txt +30 -0
  865. package/node_modules/bare-buffer/LICENSE +201 -0
  866. package/node_modules/bare-buffer/README.md +26 -0
  867. package/node_modules/bare-buffer/binding.c +2041 -0
  868. package/node_modules/bare-buffer/binding.js +1 -0
  869. package/node_modules/bare-buffer/global.d.ts +21 -0
  870. package/node_modules/bare-buffer/global.js +6 -0
  871. package/node_modules/bare-buffer/index.d.ts +769 -0
  872. package/node_modules/bare-buffer/index.js +1339 -0
  873. package/node_modules/bare-buffer/lib/ascii.js +36 -0
  874. package/node_modules/bare-buffer/lib/base64.js +25 -0
  875. package/node_modules/bare-buffer/lib/base64url.js +25 -0
  876. package/node_modules/bare-buffer/lib/checked.js +23 -0
  877. package/node_modules/bare-buffer/lib/constants.d.ts +7 -0
  878. package/node_modules/bare-buffer/lib/constants.js +3 -0
  879. package/node_modules/bare-buffer/lib/hex.js +20 -0
  880. package/node_modules/bare-buffer/lib/latin1.js +14 -0
  881. package/node_modules/bare-buffer/lib/utf16le.js +20 -0
  882. package/node_modules/bare-buffer/lib/utf8.js +18 -0
  883. package/node_modules/bare-buffer/package.json +59 -0
  884. package/node_modules/bare-buffer/prebuilds/android-arm/bare-buffer.bare +0 -0
  885. package/node_modules/bare-buffer/prebuilds/android-arm64/bare-buffer.bare +0 -0
  886. package/node_modules/bare-buffer/prebuilds/android-ia32/bare-buffer.bare +0 -0
  887. package/node_modules/bare-buffer/prebuilds/android-x64/bare-buffer.bare +0 -0
  888. package/node_modules/bare-buffer/prebuilds/darwin-arm64/bare-buffer.bare +0 -0
  889. package/node_modules/bare-buffer/prebuilds/darwin-x64/bare-buffer.bare +0 -0
  890. package/node_modules/bare-buffer/prebuilds/ios-arm64/bare-buffer.bare +0 -0
  891. package/node_modules/bare-buffer/prebuilds/ios-arm64-simulator/bare-buffer.bare +0 -0
  892. package/node_modules/bare-buffer/prebuilds/ios-x64-simulator/bare-buffer.bare +0 -0
  893. package/node_modules/bare-buffer/prebuilds/linux-arm64/bare-buffer.bare +0 -0
  894. package/node_modules/bare-buffer/prebuilds/linux-x64/bare-buffer.bare +0 -0
  895. package/node_modules/bare-buffer/prebuilds/win32-arm64/bare-buffer.bare +0 -0
  896. package/node_modules/bare-buffer/prebuilds/win32-x64/bare-buffer.bare +0 -0
  897. package/node_modules/bare-events/LICENSE +201 -0
  898. package/node_modules/bare-events/README.md +25 -0
  899. package/node_modules/bare-events/global.d.ts +15 -0
  900. package/node_modules/bare-events/global.js +5 -0
  901. package/node_modules/bare-events/index.d.ts +89 -0
  902. package/node_modules/bare-events/index.js +397 -0
  903. package/node_modules/bare-events/lib/errors.js +23 -0
  904. package/node_modules/bare-events/package.json +63 -0
  905. package/node_modules/bare-events/web.d.ts +79 -0
  906. package/node_modules/bare-events/web.js +417 -0
  907. package/node_modules/bare-fs/CMakeLists.txt +13 -0
  908. package/node_modules/bare-fs/LICENSE +201 -0
  909. package/node_modules/bare-fs/README.md +33 -0
  910. package/node_modules/bare-fs/binding.c +2942 -0
  911. package/node_modules/bare-fs/binding.js +1 -0
  912. package/node_modules/bare-fs/index.d.ts +1504 -0
  913. package/node_modules/bare-fs/index.js +2888 -0
  914. package/node_modules/bare-fs/lib/constants.d.ts +50 -0
  915. package/node_modules/bare-fs/lib/constants.js +49 -0
  916. package/node_modules/bare-fs/lib/errors.d.ts +13 -0
  917. package/node_modules/bare-fs/lib/errors.js +55 -0
  918. package/node_modules/bare-fs/package.json +75 -0
  919. package/node_modules/bare-fs/prebuilds/android-arm/bare-fs.bare +0 -0
  920. package/node_modules/bare-fs/prebuilds/android-arm64/bare-fs.bare +0 -0
  921. package/node_modules/bare-fs/prebuilds/android-ia32/bare-fs.bare +0 -0
  922. package/node_modules/bare-fs/prebuilds/android-x64/bare-fs.bare +0 -0
  923. package/node_modules/bare-fs/prebuilds/darwin-arm64/bare-fs.bare +0 -0
  924. package/node_modules/bare-fs/prebuilds/darwin-x64/bare-fs.bare +0 -0
  925. package/node_modules/bare-fs/prebuilds/ios-arm64/bare-fs.bare +0 -0
  926. package/node_modules/bare-fs/prebuilds/ios-arm64-simulator/bare-fs.bare +0 -0
  927. package/node_modules/bare-fs/prebuilds/ios-x64-simulator/bare-fs.bare +0 -0
  928. package/node_modules/bare-fs/prebuilds/linux-arm64/bare-fs.bare +0 -0
  929. package/node_modules/bare-fs/prebuilds/linux-x64/bare-fs.bare +0 -0
  930. package/node_modules/bare-fs/prebuilds/win32-arm64/bare-fs.bare +0 -0
  931. package/node_modules/bare-fs/prebuilds/win32-x64/bare-fs.bare +0 -0
  932. package/node_modules/bare-fs/promises.d.ts +480 -0
  933. package/node_modules/bare-fs/promises.js +119 -0
  934. package/node_modules/bare-path/CMakeLists.txt +13 -0
  935. package/node_modules/bare-path/LICENSE +201 -0
  936. package/node_modules/bare-path/NOTICE +28 -0
  937. package/node_modules/bare-path/README.md +19 -0
  938. package/node_modules/bare-path/binding.c +106 -0
  939. package/node_modules/bare-path/binding.js +1 -0
  940. package/node_modules/bare-path/index.d.ts +27 -0
  941. package/node_modules/bare-path/index.js +9 -0
  942. package/node_modules/bare-path/lib/constants.js +11 -0
  943. package/node_modules/bare-path/lib/posix.js +263 -0
  944. package/node_modules/bare-path/lib/shared.js +81 -0
  945. package/node_modules/bare-path/lib/win32.js +564 -0
  946. package/node_modules/bare-path/package.json +47 -0
  947. package/node_modules/bare-path/prebuilds/android-arm/bare-path.bare +0 -0
  948. package/node_modules/bare-path/prebuilds/android-arm64/bare-path.bare +0 -0
  949. package/node_modules/bare-path/prebuilds/android-ia32/bare-path.bare +0 -0
  950. package/node_modules/bare-path/prebuilds/android-x64/bare-path.bare +0 -0
  951. package/node_modules/bare-path/prebuilds/darwin-arm64/bare-path.bare +0 -0
  952. package/node_modules/bare-path/prebuilds/darwin-x64/bare-path.bare +0 -0
  953. package/node_modules/bare-path/prebuilds/ios-arm64/bare-path.bare +0 -0
  954. package/node_modules/bare-path/prebuilds/ios-arm64-simulator/bare-path.bare +0 -0
  955. package/node_modules/bare-path/prebuilds/ios-x64-simulator/bare-path.bare +0 -0
  956. package/node_modules/bare-path/prebuilds/linux-arm64/bare-path.bare +0 -0
  957. package/node_modules/bare-path/prebuilds/linux-x64/bare-path.bare +0 -0
  958. package/node_modules/bare-path/prebuilds/win32-arm64/bare-path.bare +0 -0
  959. package/node_modules/bare-path/prebuilds/win32-x64/bare-path.bare +0 -0
  960. package/node_modules/bare-stream/LICENSE +201 -0
  961. package/node_modules/bare-stream/README.md +354 -0
  962. package/node_modules/bare-stream/global.d.ts +31 -0
  963. package/node_modules/bare-stream/global.js +15 -0
  964. package/node_modules/bare-stream/index.d.ts +235 -0
  965. package/node_modules/bare-stream/index.js +493 -0
  966. package/node_modules/bare-stream/package.json +75 -0
  967. package/node_modules/bare-stream/promises.js +3 -0
  968. package/node_modules/bare-stream/web.d.ts +152 -0
  969. package/node_modules/bare-stream/web.js +607 -0
  970. package/node_modules/bare-url/CMakeLists.txt +36 -0
  971. package/node_modules/bare-url/LICENSE +201 -0
  972. package/node_modules/bare-url/README.md +37 -0
  973. package/node_modules/bare-url/binding.c +422 -0
  974. package/node_modules/bare-url/binding.js +1 -0
  975. package/node_modules/bare-url/global.d.ts +24 -0
  976. package/node_modules/bare-url/global.js +2 -0
  977. package/node_modules/bare-url/index.d.ts +99 -0
  978. package/node_modules/bare-url/index.js +700 -0
  979. package/node_modules/bare-url/lib/errors.d.ts +10 -0
  980. package/node_modules/bare-url/lib/errors.js +37 -0
  981. package/node_modules/bare-url/lib/url-search-params.d.ts +66 -0
  982. package/node_modules/bare-url/lib/url-search-params.js +291 -0
  983. package/node_modules/bare-url/package.json +55 -0
  984. package/node_modules/bare-url/prebuilds/android-arm/bare-url.bare +0 -0
  985. package/node_modules/bare-url/prebuilds/android-arm64/bare-url.bare +0 -0
  986. package/node_modules/bare-url/prebuilds/android-ia32/bare-url.bare +0 -0
  987. package/node_modules/bare-url/prebuilds/android-x64/bare-url.bare +0 -0
  988. package/node_modules/bare-url/prebuilds/darwin-arm64/bare-url.bare +0 -0
  989. package/node_modules/bare-url/prebuilds/darwin-x64/bare-url.bare +0 -0
  990. package/node_modules/bare-url/prebuilds/ios-arm64/bare-url.bare +0 -0
  991. package/node_modules/bare-url/prebuilds/ios-arm64-simulator/bare-url.bare +0 -0
  992. package/node_modules/bare-url/prebuilds/ios-x64-simulator/bare-url.bare +0 -0
  993. package/node_modules/bare-url/prebuilds/linux-arm64/bare-url.bare +0 -0
  994. package/node_modules/bare-url/prebuilds/linux-x64/bare-url.bare +0 -0
  995. package/node_modules/bare-url/prebuilds/win32-arm64/bare-url.bare +0 -0
  996. package/node_modules/bare-url/prebuilds/win32-x64/bare-url.bare +0 -0
  997. package/node_modules/commander/LICENSE +22 -0
  998. package/node_modules/commander/Readme.md +1146 -0
  999. package/node_modules/commander/index.js +21 -0
  1000. package/node_modules/commander/lib/argument.js +147 -0
  1001. package/node_modules/commander/lib/command.js +2803 -0
  1002. package/node_modules/commander/lib/error.js +36 -0
  1003. package/node_modules/commander/lib/help.js +735 -0
  1004. package/node_modules/commander/lib/option.js +377 -0
  1005. package/node_modules/commander/lib/suggestSimilar.js +99 -0
  1006. package/node_modules/commander/package-support.json +19 -0
  1007. package/node_modules/commander/package.json +65 -0
  1008. package/node_modules/commander/typings/index.d.ts +1116 -0
  1009. package/node_modules/esbuild/LICENSE.md +21 -0
  1010. package/node_modules/esbuild/README.md +3 -0
  1011. package/node_modules/esbuild/bin/esbuild +223 -0
  1012. package/node_modules/esbuild/install.js +300 -0
  1013. package/node_modules/esbuild/lib/main.d.ts +720 -0
  1014. package/node_modules/esbuild/lib/main.js +2536 -0
  1015. package/node_modules/esbuild/package.json +74 -0
  1016. package/node_modules/events-universal/LICENSE +201 -0
  1017. package/node_modules/events-universal/README.md +17 -0
  1018. package/node_modules/events-universal/bare.js +1 -0
  1019. package/node_modules/events-universal/default.js +1 -0
  1020. package/node_modules/events-universal/index.js +1 -0
  1021. package/node_modules/events-universal/package.json +39 -0
  1022. package/node_modules/events-universal/react-native.js +1 -0
  1023. package/node_modules/fast-fifo/LICENSE +21 -0
  1024. package/node_modules/fast-fifo/README.md +78 -0
  1025. package/node_modules/fast-fifo/fixed-size.js +39 -0
  1026. package/node_modules/fast-fifo/index.js +48 -0
  1027. package/node_modules/fast-fifo/package.json +28 -0
  1028. package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
  1029. package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
  1030. package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
  1031. package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
  1032. package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
  1033. package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
  1034. package/node_modules/fast-string-truncated-width/license +21 -0
  1035. package/node_modules/fast-string-truncated-width/package.json +35 -0
  1036. package/node_modules/fast-string-truncated-width/readme.md +59 -0
  1037. package/node_modules/fast-string-width/dist/index.d.ts +4 -0
  1038. package/node_modules/fast-string-width/dist/index.js +14 -0
  1039. package/node_modules/fast-string-width/license +21 -0
  1040. package/node_modules/fast-string-width/package.json +34 -0
  1041. package/node_modules/fast-string-width/readme.md +42 -0
  1042. package/node_modules/fast-wrap-ansi/LICENSE +23 -0
  1043. package/node_modules/fast-wrap-ansi/README.md +26 -0
  1044. package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
  1045. package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
  1046. package/node_modules/fast-wrap-ansi/package.json +51 -0
  1047. package/node_modules/sisteransi/license +21 -0
  1048. package/node_modules/sisteransi/package.json +34 -0
  1049. package/node_modules/sisteransi/readme.md +113 -0
  1050. package/node_modules/sisteransi/src/index.js +58 -0
  1051. package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
  1052. package/node_modules/skillflag/LICENSE +21 -0
  1053. package/node_modules/skillflag/README.md +44 -0
  1054. package/node_modules/skillflag/dist/bin/skill-install.d.ts +3 -0
  1055. package/node_modules/skillflag/dist/bin/skill-install.d.ts.map +1 -0
  1056. package/node_modules/skillflag/dist/bin/skill-install.js +6 -0
  1057. package/node_modules/skillflag/dist/bin/skill-install.js.map +1 -0
  1058. package/node_modules/skillflag/dist/bin/skillflag.d.ts +3 -0
  1059. package/node_modules/skillflag/dist/bin/skillflag.d.ts.map +1 -0
  1060. package/node_modules/skillflag/dist/bin/skillflag.js +25 -0
  1061. package/node_modules/skillflag/dist/bin/skillflag.js.map +1 -0
  1062. package/node_modules/skillflag/dist/core/digest.d.ts +2 -0
  1063. package/node_modules/skillflag/dist/core/digest.d.ts.map +1 -0
  1064. package/node_modules/skillflag/dist/core/digest.js +15 -0
  1065. package/node_modules/skillflag/dist/core/digest.js.map +1 -0
  1066. package/node_modules/skillflag/dist/core/errors.d.ts +6 -0
  1067. package/node_modules/skillflag/dist/core/errors.d.ts.map +1 -0
  1068. package/node_modules/skillflag/dist/core/errors.js +13 -0
  1069. package/node_modules/skillflag/dist/core/errors.js.map +1 -0
  1070. package/node_modules/skillflag/dist/core/export.d.ts +2 -0
  1071. package/node_modules/skillflag/dist/core/export.d.ts.map +1 -0
  1072. package/node_modules/skillflag/dist/core/export.js +28 -0
  1073. package/node_modules/skillflag/dist/core/export.js.map +1 -0
  1074. package/node_modules/skillflag/dist/core/list.d.ts +21 -0
  1075. package/node_modules/skillflag/dist/core/list.d.ts.map +1 -0
  1076. package/node_modules/skillflag/dist/core/list.js +71 -0
  1077. package/node_modules/skillflag/dist/core/list.js.map +1 -0
  1078. package/node_modules/skillflag/dist/core/paths.d.ts +15 -0
  1079. package/node_modules/skillflag/dist/core/paths.d.ts.map +1 -0
  1080. package/node_modules/skillflag/dist/core/paths.js +149 -0
  1081. package/node_modules/skillflag/dist/core/paths.js.map +1 -0
  1082. package/node_modules/skillflag/dist/core/show.d.ts +2 -0
  1083. package/node_modules/skillflag/dist/core/show.d.ts.map +1 -0
  1084. package/node_modules/skillflag/dist/core/show.js +8 -0
  1085. package/node_modules/skillflag/dist/core/show.js.map +1 -0
  1086. package/node_modules/skillflag/dist/core/skillflag.d.ts +3 -0
  1087. package/node_modules/skillflag/dist/core/skillflag.d.ts.map +1 -0
  1088. package/node_modules/skillflag/dist/core/skillflag.js +2 -0
  1089. package/node_modules/skillflag/dist/core/skillflag.js.map +1 -0
  1090. package/node_modules/skillflag/dist/core/tar.d.ts +16 -0
  1091. package/node_modules/skillflag/dist/core/tar.d.ts.map +1 -0
  1092. package/node_modules/skillflag/dist/core/tar.js +140 -0
  1093. package/node_modules/skillflag/dist/core/tar.js.map +1 -0
  1094. package/node_modules/skillflag/dist/index.d.ts +5 -0
  1095. package/node_modules/skillflag/dist/index.d.ts.map +1 -0
  1096. package/node_modules/skillflag/dist/index.js +3 -0
  1097. package/node_modules/skillflag/dist/index.js.map +1 -0
  1098. package/node_modules/skillflag/dist/install/cli.d.ts +57 -0
  1099. package/node_modules/skillflag/dist/install/cli.d.ts.map +1 -0
  1100. package/node_modules/skillflag/dist/install/cli.js +653 -0
  1101. package/node_modules/skillflag/dist/install/cli.js.map +1 -0
  1102. package/node_modules/skillflag/dist/install/copy.d.ts +2 -0
  1103. package/node_modules/skillflag/dist/install/copy.d.ts.map +1 -0
  1104. package/node_modules/skillflag/dist/install/copy.js +19 -0
  1105. package/node_modules/skillflag/dist/install/copy.js.map +1 -0
  1106. package/node_modules/skillflag/dist/install/errors.d.ts +6 -0
  1107. package/node_modules/skillflag/dist/install/errors.d.ts.map +1 -0
  1108. package/node_modules/skillflag/dist/install/errors.js +13 -0
  1109. package/node_modules/skillflag/dist/install/errors.js.map +1 -0
  1110. package/node_modules/skillflag/dist/install/extract.d.ts +3 -0
  1111. package/node_modules/skillflag/dist/install/extract.d.ts.map +1 -0
  1112. package/node_modules/skillflag/dist/install/extract.js +76 -0
  1113. package/node_modules/skillflag/dist/install/extract.js.map +1 -0
  1114. package/node_modules/skillflag/dist/install/install.d.ts +21 -0
  1115. package/node_modules/skillflag/dist/install/install.d.ts.map +1 -0
  1116. package/node_modules/skillflag/dist/install/install.js +35 -0
  1117. package/node_modules/skillflag/dist/install/install.js.map +1 -0
  1118. package/node_modules/skillflag/dist/install/resolve.d.ts +12 -0
  1119. package/node_modules/skillflag/dist/install/resolve.d.ts.map +1 -0
  1120. package/node_modules/skillflag/dist/install/resolve.js +119 -0
  1121. package/node_modules/skillflag/dist/install/resolve.js.map +1 -0
  1122. package/node_modules/skillflag/dist/install/validate.d.ts +7 -0
  1123. package/node_modules/skillflag/dist/install/validate.d.ts.map +1 -0
  1124. package/node_modules/skillflag/dist/install/validate.js +28 -0
  1125. package/node_modules/skillflag/dist/install/validate.js.map +1 -0
  1126. package/node_modules/skillflag/dist/shared/frontmatter.d.ts +2 -0
  1127. package/node_modules/skillflag/dist/shared/frontmatter.d.ts.map +1 -0
  1128. package/node_modules/skillflag/dist/shared/frontmatter.js +28 -0
  1129. package/node_modules/skillflag/dist/shared/frontmatter.js.map +1 -0
  1130. package/node_modules/skillflag/dist/skillflag.d.ts +29 -0
  1131. package/node_modules/skillflag/dist/skillflag.d.ts.map +1 -0
  1132. package/node_modules/skillflag/dist/skillflag.js +230 -0
  1133. package/node_modules/skillflag/dist/skillflag.js.map +1 -0
  1134. package/node_modules/skillflag/dist/utils/collections.d.ts +3 -0
  1135. package/node_modules/skillflag/dist/utils/collections.d.ts.map +1 -0
  1136. package/node_modules/skillflag/dist/utils/collections.js +18 -0
  1137. package/node_modules/skillflag/dist/utils/collections.js.map +1 -0
  1138. package/node_modules/skillflag/package.json +78 -0
  1139. package/node_modules/skillflag/skills/skillflag/SKILL.md +144 -0
  1140. package/node_modules/streamx/LICENSE +21 -0
  1141. package/node_modules/streamx/README.md +550 -0
  1142. package/node_modules/streamx/index.d.ts +198 -0
  1143. package/node_modules/streamx/index.js +1314 -0
  1144. package/node_modules/streamx/lib/errors.d.ts +13 -0
  1145. package/node_modules/streamx/lib/errors.js +47 -0
  1146. package/node_modules/streamx/package.json +51 -0
  1147. package/node_modules/streamx/runtime.d.ts +55 -0
  1148. package/node_modules/tar-stream/LICENSE +21 -0
  1149. package/node_modules/tar-stream/README.md +183 -0
  1150. package/node_modules/tar-stream/constants.js +14 -0
  1151. package/node_modules/tar-stream/extract.js +418 -0
  1152. package/node_modules/tar-stream/headers.js +322 -0
  1153. package/node_modules/tar-stream/index.d.ts +60 -0
  1154. package/node_modules/tar-stream/index.js +2 -0
  1155. package/node_modules/tar-stream/pack.js +287 -0
  1156. package/node_modules/tar-stream/package.json +50 -0
  1157. package/node_modules/teex/LICENSE +21 -0
  1158. package/node_modules/teex/README.md +31 -0
  1159. package/node_modules/teex/example.js +16 -0
  1160. package/node_modules/teex/index.js +52 -0
  1161. package/node_modules/teex/package.json +26 -0
  1162. package/node_modules/teex/test.js +68 -0
  1163. package/node_modules/text-decoder/LICENSE +201 -0
  1164. package/node_modules/text-decoder/README.md +36 -0
  1165. package/node_modules/text-decoder/index.js +64 -0
  1166. package/node_modules/text-decoder/lib/pass-through-decoder.js +19 -0
  1167. package/node_modules/text-decoder/lib/utf8-decoder.js +185 -0
  1168. package/node_modules/text-decoder/package.json +39 -0
  1169. package/node_modules/tsx/LICENSE +21 -0
  1170. package/node_modules/tsx/README.md +32 -0
  1171. package/node_modules/tsx/dist/cjs/api/index.cjs +2 -0
  1172. package/node_modules/tsx/dist/cjs/api/index.d.cts +35 -0
  1173. package/node_modules/tsx/dist/cjs/api/index.d.mts +35 -0
  1174. package/node_modules/tsx/dist/cjs/api/index.mjs +2 -0
  1175. package/node_modules/tsx/dist/cjs/index.cjs +1 -0
  1176. package/node_modules/tsx/dist/cli.mjs +55 -0
  1177. package/node_modules/tsx/dist/client-XItNFmsq.cjs +1 -0
  1178. package/node_modules/tsx/dist/esm/api/index.cjs +2 -0
  1179. package/node_modules/tsx/dist/esm/api/index.d.cts +37 -0
  1180. package/node_modules/tsx/dist/esm/api/index.d.mts +37 -0
  1181. package/node_modules/tsx/dist/esm/api/index.mjs +2 -0
  1182. package/node_modules/tsx/dist/esm/index.mjs +2 -0
  1183. package/node_modules/tsx/dist/index-Bqjv9TxC.mjs +1 -0
  1184. package/node_modules/tsx/dist/index-DE3OBZuV.mjs +14 -0
  1185. package/node_modules/tsx/dist/lexer-CGfpMDSb.cjs +3 -0
  1186. package/node_modules/tsx/dist/lexer-CanA6ArK.mjs +3 -0
  1187. package/node_modules/tsx/dist/loader.mjs +2 -0
  1188. package/node_modules/tsx/dist/package-Dj0mHsMt.mjs +1 -0
  1189. package/node_modules/tsx/dist/patch-repl.cjs +1 -0
  1190. package/node_modules/tsx/dist/preflight.cjs +1 -0
  1191. package/node_modules/tsx/dist/register-B1c7OH6V.cjs +23 -0
  1192. package/node_modules/tsx/dist/register-nyXW-TH3.mjs +2 -0
  1193. package/node_modules/tsx/dist/repl.mjs +4 -0
  1194. package/node_modules/tsx/dist/require-CBjy4Foe.mjs +10 -0
  1195. package/node_modules/tsx/dist/require-CVaYn9z3.cjs +1 -0
  1196. package/node_modules/tsx/dist/suppress-warnings.cjs +1 -0
  1197. package/node_modules/tsx/dist/temporary-directory-Du7LpLp9.mjs +1 -0
  1198. package/node_modules/tsx/package.json +70 -0
  1199. package/node_modules/zod/LICENSE +21 -0
  1200. package/node_modules/zod/README.md +218 -0
  1201. package/node_modules/zod/compile.cjs +96 -0
  1202. package/node_modules/zod/compile.d.cts +1 -0
  1203. package/node_modules/zod/compile.d.ts +1 -0
  1204. package/node_modules/zod/compile.js +52 -0
  1205. package/node_modules/zod/index.cjs +52 -0
  1206. package/node_modules/zod/index.d.cts +3 -0
  1207. package/node_modules/zod/index.d.ts +3 -0
  1208. package/node_modules/zod/index.js +7 -0
  1209. package/node_modules/zod/locales/index.cjs +36 -0
  1210. package/node_modules/zod/locales/index.d.cts +1 -0
  1211. package/node_modules/zod/locales/index.d.ts +1 -0
  1212. package/node_modules/zod/locales/index.js +1 -0
  1213. package/node_modules/zod/locales/package.json +7 -0
  1214. package/node_modules/zod/mini/index.cjs +51 -0
  1215. package/node_modules/zod/mini/index.d.cts +3 -0
  1216. package/node_modules/zod/mini/index.d.ts +3 -0
  1217. package/node_modules/zod/mini/index.js +3 -0
  1218. package/node_modules/zod/mini/package.json +7 -0
  1219. package/node_modules/zod/package.json +147 -0
  1220. package/node_modules/zod/src/compile.ts +56 -0
  1221. package/node_modules/zod/src/index.ts +7 -0
  1222. package/node_modules/zod/src/locales/index.ts +1 -0
  1223. package/node_modules/zod/src/mini/index.ts +3 -0
  1224. package/node_modules/zod/src/v3/ZodError.ts +340 -0
  1225. package/node_modules/zod/src/v3/benchmarks/datetime.ts +58 -0
  1226. package/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +80 -0
  1227. package/node_modules/zod/src/v3/benchmarks/index.ts +59 -0
  1228. package/node_modules/zod/src/v3/benchmarks/ipv4.ts +57 -0
  1229. package/node_modules/zod/src/v3/benchmarks/object.ts +69 -0
  1230. package/node_modules/zod/src/v3/benchmarks/primitives.ts +162 -0
  1231. package/node_modules/zod/src/v3/benchmarks/realworld.ts +63 -0
  1232. package/node_modules/zod/src/v3/benchmarks/string.ts +55 -0
  1233. package/node_modules/zod/src/v3/benchmarks/union.ts +80 -0
  1234. package/node_modules/zod/src/v3/errors.ts +13 -0
  1235. package/node_modules/zod/src/v3/external.ts +6 -0
  1236. package/node_modules/zod/src/v3/helpers/enumUtil.ts +17 -0
  1237. package/node_modules/zod/src/v3/helpers/errorUtil.ts +8 -0
  1238. package/node_modules/zod/src/v3/helpers/parseUtil.ts +176 -0
  1239. package/node_modules/zod/src/v3/helpers/partialUtil.ts +34 -0
  1240. package/node_modules/zod/src/v3/helpers/typeAliases.ts +2 -0
  1241. package/node_modules/zod/src/v3/helpers/util.ts +224 -0
  1242. package/node_modules/zod/src/v3/index.ts +4 -0
  1243. package/node_modules/zod/src/v3/locales/en.ts +124 -0
  1244. package/node_modules/zod/src/v3/standard-schema.ts +113 -0
  1245. package/node_modules/zod/src/v3/tests/Mocker.ts +54 -0
  1246. package/node_modules/zod/src/v3/tests/all-errors.test.ts +157 -0
  1247. package/node_modules/zod/src/v3/tests/anyunknown.test.ts +28 -0
  1248. package/node_modules/zod/src/v3/tests/array.test.ts +71 -0
  1249. package/node_modules/zod/src/v3/tests/async-parsing.test.ts +388 -0
  1250. package/node_modules/zod/src/v3/tests/async-refinements.test.ts +46 -0
  1251. package/node_modules/zod/src/v3/tests/base.test.ts +29 -0
  1252. package/node_modules/zod/src/v3/tests/bigint.test.ts +55 -0
  1253. package/node_modules/zod/src/v3/tests/branded.test.ts +53 -0
  1254. package/node_modules/zod/src/v3/tests/catch.test.ts +220 -0
  1255. package/node_modules/zod/src/v3/tests/coerce.test.ts +133 -0
  1256. package/node_modules/zod/src/v3/tests/complex.test.ts +70 -0
  1257. package/node_modules/zod/src/v3/tests/custom.test.ts +31 -0
  1258. package/node_modules/zod/src/v3/tests/date.test.ts +32 -0
  1259. package/node_modules/zod/src/v3/tests/deepmasking.test.ts +186 -0
  1260. package/node_modules/zod/src/v3/tests/default.test.ts +112 -0
  1261. package/node_modules/zod/src/v3/tests/description.test.ts +33 -0
  1262. package/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +315 -0
  1263. package/node_modules/zod/src/v3/tests/enum.test.ts +80 -0
  1264. package/node_modules/zod/src/v3/tests/error.test.ts +586 -0
  1265. package/node_modules/zod/src/v3/tests/firstparty.test.ts +87 -0
  1266. package/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +21 -0
  1267. package/node_modules/zod/src/v3/tests/function.test.ts +261 -0
  1268. package/node_modules/zod/src/v3/tests/generics.test.ts +48 -0
  1269. package/node_modules/zod/src/v3/tests/instanceof.test.ts +37 -0
  1270. package/node_modules/zod/src/v3/tests/intersection.test.ts +128 -0
  1271. package/node_modules/zod/src/v3/tests/language-server.source.ts +76 -0
  1272. package/node_modules/zod/src/v3/tests/language-server.test.ts +206 -0
  1273. package/node_modules/zod/src/v3/tests/literal.test.ts +36 -0
  1274. package/node_modules/zod/src/v3/tests/map.test.ts +110 -0
  1275. package/node_modules/zod/src/v3/tests/masking.test.ts +4 -0
  1276. package/node_modules/zod/src/v3/tests/mocker.test.ts +19 -0
  1277. package/node_modules/zod/src/v3/tests/nan.test.ts +24 -0
  1278. package/node_modules/zod/src/v3/tests/nativeEnum.test.ts +87 -0
  1279. package/node_modules/zod/src/v3/tests/nullable.test.ts +42 -0
  1280. package/node_modules/zod/src/v3/tests/number.test.ts +176 -0
  1281. package/node_modules/zod/src/v3/tests/object-augmentation.test.ts +29 -0
  1282. package/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +29 -0
  1283. package/node_modules/zod/src/v3/tests/object.test.ts +431 -0
  1284. package/node_modules/zod/src/v3/tests/optional.test.ts +42 -0
  1285. package/node_modules/zod/src/v3/tests/parseUtil.test.ts +23 -0
  1286. package/node_modules/zod/src/v3/tests/parser.test.ts +41 -0
  1287. package/node_modules/zod/src/v3/tests/partials.test.ts +243 -0
  1288. package/node_modules/zod/src/v3/tests/pickomit.test.ts +111 -0
  1289. package/node_modules/zod/src/v3/tests/pipeline.test.ts +29 -0
  1290. package/node_modules/zod/src/v3/tests/preprocess.test.ts +186 -0
  1291. package/node_modules/zod/src/v3/tests/primitive.test.ts +440 -0
  1292. package/node_modules/zod/src/v3/tests/promise.test.ts +90 -0
  1293. package/node_modules/zod/src/v3/tests/readonly.test.ts +114 -0
  1294. package/node_modules/zod/src/v3/tests/record.test.ts +171 -0
  1295. package/node_modules/zod/src/v3/tests/recursive.test.ts +197 -0
  1296. package/node_modules/zod/src/v3/tests/refine.test.ts +313 -0
  1297. package/node_modules/zod/src/v3/tests/safeparse.test.ts +27 -0
  1298. package/node_modules/zod/src/v3/tests/set.test.ts +142 -0
  1299. package/node_modules/zod/src/v3/tests/standard-schema.test.ts +83 -0
  1300. package/node_modules/zod/src/v3/tests/string.test.ts +922 -0
  1301. package/node_modules/zod/src/v3/tests/transformer.test.ts +233 -0
  1302. package/node_modules/zod/src/v3/tests/tuple.test.ts +90 -0
  1303. package/node_modules/zod/src/v3/tests/unions.test.ts +57 -0
  1304. package/node_modules/zod/src/v3/tests/validations.test.ts +133 -0
  1305. package/node_modules/zod/src/v3/tests/void.test.ts +15 -0
  1306. package/node_modules/zod/src/v3/types.ts +5138 -0
  1307. package/node_modules/zod/src/v4/classic/checks.ts +33 -0
  1308. package/node_modules/zod/src/v4/classic/coerce.ts +27 -0
  1309. package/node_modules/zod/src/v4/classic/compat.ts +78 -0
  1310. package/node_modules/zod/src/v4/classic/deep-partial.ts +76 -0
  1311. package/node_modules/zod/src/v4/classic/errors.ts +97 -0
  1312. package/node_modules/zod/src/v4/classic/external.ts +57 -0
  1313. package/node_modules/zod/src/v4/classic/from-json-schema.ts +944 -0
  1314. package/node_modules/zod/src/v4/classic/in-out.ts +45 -0
  1315. package/node_modules/zod/src/v4/classic/index.ts +5 -0
  1316. package/node_modules/zod/src/v4/classic/iso.ts +20 -0
  1317. package/node_modules/zod/src/v4/classic/parse.ts +88 -0
  1318. package/node_modules/zod/src/v4/classic/schemas.ts +2937 -0
  1319. package/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +26 -0
  1320. package/node_modules/zod/src/v4/classic/tests/apply.test.ts +86 -0
  1321. package/node_modules/zod/src/v4/classic/tests/array.test.ts +291 -0
  1322. package/node_modules/zod/src/v4/classic/tests/assignability.test.ts +402 -0
  1323. package/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +381 -0
  1324. package/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +68 -0
  1325. package/node_modules/zod/src/v4/classic/tests/base.test.ts +7 -0
  1326. package/node_modules/zod/src/v4/classic/tests/bigint.test.ts +89 -0
  1327. package/node_modules/zod/src/v4/classic/tests/brand.test.ts +106 -0
  1328. package/node_modules/zod/src/v4/classic/tests/catch.test.ts +604 -0
  1329. package/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +20 -0
  1330. package/node_modules/zod/src/v4/classic/tests/codec-examples.test.ts +572 -0
  1331. package/node_modules/zod/src/v4/classic/tests/codec.test.ts +704 -0
  1332. package/node_modules/zod/src/v4/classic/tests/coerce.test.ts +160 -0
  1333. package/node_modules/zod/src/v4/classic/tests/continuability.test.ts +374 -0
  1334. package/node_modules/zod/src/v4/classic/tests/credit-card.test.ts +76 -0
  1335. package/node_modules/zod/src/v4/classic/tests/custom.test.ts +40 -0
  1336. package/node_modules/zod/src/v4/classic/tests/cyclic-data.test.ts +985 -0
  1337. package/node_modules/zod/src/v4/classic/tests/date.test.ts +92 -0
  1338. package/node_modules/zod/src/v4/classic/tests/datetime.test.ts +316 -0
  1339. package/node_modules/zod/src/v4/classic/tests/deep-partial.test.ts +380 -0
  1340. package/node_modules/zod/src/v4/classic/tests/default-locale.test.ts +32 -0
  1341. package/node_modules/zod/src/v4/classic/tests/default.test.ts +455 -0
  1342. package/node_modules/zod/src/v4/classic/tests/describe-meta-checks.test.ts +27 -0
  1343. package/node_modules/zod/src/v4/classic/tests/description.test.ts +32 -0
  1344. package/node_modules/zod/src/v4/classic/tests/detached-methods.test.ts +221 -0
  1345. package/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +942 -0
  1346. package/node_modules/zod/src/v4/classic/tests/enum.test.ts +305 -0
  1347. package/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +917 -0
  1348. package/node_modules/zod/src/v4/classic/tests/error.test.ts +1108 -0
  1349. package/node_modules/zod/src/v4/classic/tests/file.test.ts +96 -0
  1350. package/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +179 -0
  1351. package/node_modules/zod/src/v4/classic/tests/fix-json-issue.test.ts +26 -0
  1352. package/node_modules/zod/src/v4/classic/tests/from-json-schema.test.ts +1467 -0
  1353. package/node_modules/zod/src/v4/classic/tests/function.test.ts +391 -0
  1354. package/node_modules/zod/src/v4/classic/tests/generics.test.ts +72 -0
  1355. package/node_modules/zod/src/v4/classic/tests/global-config.test.ts +32 -0
  1356. package/node_modules/zod/src/v4/classic/tests/hash.test.ts +67 -0
  1357. package/node_modules/zod/src/v4/classic/tests/iban.test.ts +81 -0
  1358. package/node_modules/zod/src/v4/classic/tests/in-out.test.ts +159 -0
  1359. package/node_modules/zod/src/v4/classic/tests/index.test.ts +958 -0
  1360. package/node_modules/zod/src/v4/classic/tests/instance-footprint.test.ts +319 -0
  1361. package/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +127 -0
  1362. package/node_modules/zod/src/v4/classic/tests/intersection.test.ts +334 -0
  1363. package/node_modules/zod/src/v4/classic/tests/issue-schema.test.ts +215 -0
  1364. package/node_modules/zod/src/v4/classic/tests/jitless-allows-eval.test.ts +39 -0
  1365. package/node_modules/zod/src/v4/classic/tests/json.test.ts +109 -0
  1366. package/node_modules/zod/src/v4/classic/tests/lazy.test.ts +262 -0
  1367. package/node_modules/zod/src/v4/classic/tests/literal.test.ts +128 -0
  1368. package/node_modules/zod/src/v4/classic/tests/locales_ka.test.ts +29 -0
  1369. package/node_modules/zod/src/v4/classic/tests/locales_ro.test.ts +24 -0
  1370. package/node_modules/zod/src/v4/classic/tests/map.test.ts +349 -0
  1371. package/node_modules/zod/src/v4/classic/tests/nan.test.ts +21 -0
  1372. package/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +168 -0
  1373. package/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +101 -0
  1374. package/node_modules/zod/src/v4/classic/tests/nullable.test.ts +22 -0
  1375. package/node_modules/zod/src/v4/classic/tests/number.test.ts +401 -0
  1376. package/node_modules/zod/src/v4/classic/tests/object.test.ts +1006 -0
  1377. package/node_modules/zod/src/v4/classic/tests/optin-ladder.test.ts +235 -0
  1378. package/node_modules/zod/src/v4/classic/tests/optional.test.ts +366 -0
  1379. package/node_modules/zod/src/v4/classic/tests/partial.test.ts +497 -0
  1380. package/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +211 -0
  1381. package/node_modules/zod/src/v4/classic/tests/pipe.test.ts +101 -0
  1382. package/node_modules/zod/src/v4/classic/tests/prefault.test.ts +144 -0
  1383. package/node_modules/zod/src/v4/classic/tests/preprocess-types.test.ts +44 -0
  1384. package/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +351 -0
  1385. package/node_modules/zod/src/v4/classic/tests/primitive.test.ts +175 -0
  1386. package/node_modules/zod/src/v4/classic/tests/promise.test.ts +81 -0
  1387. package/node_modules/zod/src/v4/classic/tests/properties.test.ts +141 -0
  1388. package/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +23 -0
  1389. package/node_modules/zod/src/v4/classic/tests/readonly.test.ts +184 -0
  1390. package/node_modules/zod/src/v4/classic/tests/record.test.ts +885 -0
  1391. package/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +707 -0
  1392. package/node_modules/zod/src/v4/classic/tests/redos.test.ts +68 -0
  1393. package/node_modules/zod/src/v4/classic/tests/refine.test.ts +693 -0
  1394. package/node_modules/zod/src/v4/classic/tests/registries.test.ts +243 -0
  1395. package/node_modules/zod/src/v4/classic/tests/set.test.ts +196 -0
  1396. package/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +153 -0
  1397. package/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +125 -0
  1398. package/node_modules/zod/src/v4/classic/tests/string.test.ts +1440 -0
  1399. package/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +124 -0
  1400. package/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +812 -0
  1401. package/node_modules/zod/src/v4/classic/tests/to-json-schema-methods.test.ts +438 -0
  1402. package/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +4733 -0
  1403. package/node_modules/zod/src/v4/classic/tests/transform.test.ts +378 -0
  1404. package/node_modules/zod/src/v4/classic/tests/tuple.test.ts +511 -0
  1405. package/node_modules/zod/src/v4/classic/tests/union.test.ts +310 -0
  1406. package/node_modules/zod/src/v4/classic/tests/url.test.ts +13 -0
  1407. package/node_modules/zod/src/v4/classic/tests/validate.test.ts +645 -0
  1408. package/node_modules/zod/src/v4/classic/tests/validations.test.ts +283 -0
  1409. package/node_modules/zod/src/v4/classic/tests/void.test.ts +12 -0
  1410. package/node_modules/zod/src/v4/core/api.ts +1875 -0
  1411. package/node_modules/zod/src/v4/core/checks.ts +1266 -0
  1412. package/node_modules/zod/src/v4/core/compile.ts +2322 -0
  1413. package/node_modules/zod/src/v4/core/core.ts +230 -0
  1414. package/node_modules/zod/src/v4/core/doc.ts +52 -0
  1415. package/node_modules/zod/src/v4/core/errors.ts +543 -0
  1416. package/node_modules/zod/src/v4/core/index.ts +19 -0
  1417. package/node_modules/zod/src/v4/core/json-schema-generator.ts +131 -0
  1418. package/node_modules/zod/src/v4/core/json-schema-processors.ts +934 -0
  1419. package/node_modules/zod/src/v4/core/json-schema.ts +148 -0
  1420. package/node_modules/zod/src/v4/core/memoizer.ts +331 -0
  1421. package/node_modules/zod/src/v4/core/parse.ts +309 -0
  1422. package/node_modules/zod/src/v4/core/regexes.ts +217 -0
  1423. package/node_modules/zod/src/v4/core/registries.ts +105 -0
  1424. package/node_modules/zod/src/v4/core/schemas.ts +5226 -0
  1425. package/node_modules/zod/src/v4/core/standard-schema.ts +159 -0
  1426. package/node_modules/zod/src/v4/core/tests/cached.test.ts +54 -0
  1427. package/node_modules/zod/src/v4/core/tests/compile-differential.test.ts +1004 -0
  1428. package/node_modules/zod/src/v4/core/tests/compile-generative.test.ts +445 -0
  1429. package/node_modules/zod/src/v4/core/tests/compile-global.test.ts +89 -0
  1430. package/node_modules/zod/src/v4/core/tests/compile-off-by-default.test.ts +26 -0
  1431. package/node_modules/zod/src/v4/core/tests/compile-stats.test.ts +34 -0
  1432. package/node_modules/zod/src/v4/core/tests/compile.test.ts +2036 -0
  1433. package/node_modules/zod/src/v4/core/tests/email-regex.test.ts +140 -0
  1434. package/node_modules/zod/src/v4/core/tests/extend.test.ts +59 -0
  1435. package/node_modules/zod/src/v4/core/tests/index.test.ts +46 -0
  1436. package/node_modules/zod/src/v4/core/tests/locales/be.test.ts +124 -0
  1437. package/node_modules/zod/src/v4/core/tests/locales/el.test.ts +214 -0
  1438. package/node_modules/zod/src/v4/core/tests/locales/en.test.ts +22 -0
  1439. package/node_modules/zod/src/v4/core/tests/locales/es.test.ts +180 -0
  1440. package/node_modules/zod/src/v4/core/tests/locales/fr.test.ts +72 -0
  1441. package/node_modules/zod/src/v4/core/tests/locales/he.test.ts +379 -0
  1442. package/node_modules/zod/src/v4/core/tests/locales/hr.test.ts +163 -0
  1443. package/node_modules/zod/src/v4/core/tests/locales/nl.test.ts +46 -0
  1444. package/node_modules/zod/src/v4/core/tests/locales/parity.test.ts +42 -0
  1445. package/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +128 -0
  1446. package/node_modules/zod/src/v4/core/tests/locales/tg.test.ts +85 -0
  1447. package/node_modules/zod/src/v4/core/tests/locales/tk.test.ts +69 -0
  1448. package/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +69 -0
  1449. package/node_modules/zod/src/v4/core/tests/locales/uz.test.ts +105 -0
  1450. package/node_modules/zod/src/v4/core/tests/polyfill-collision.test.ts +46 -0
  1451. package/node_modules/zod/src/v4/core/tests/record-constructor.test.ts +125 -0
  1452. package/node_modules/zod/src/v4/core/tests/recursive-tuples.test.ts +45 -0
  1453. package/node_modules/zod/src/v4/core/tests/treeshake.test.ts +51 -0
  1454. package/node_modules/zod/src/v4/core/tests/url-no-canparse.test.ts +133 -0
  1455. package/node_modules/zod/src/v4/core/to-json-schema.ts +857 -0
  1456. package/node_modules/zod/src/v4/core/util.ts +1293 -0
  1457. package/node_modules/zod/src/v4/core/versions.ts +5 -0
  1458. package/node_modules/zod/src/v4/core/visit.ts +193 -0
  1459. package/node_modules/zod/src/v4/core/zsf.ts +323 -0
  1460. package/node_modules/zod/src/v4/index.ts +4 -0
  1461. package/node_modules/zod/src/v4/locales/ar.ts +120 -0
  1462. package/node_modules/zod/src/v4/locales/az.ts +116 -0
  1463. package/node_modules/zod/src/v4/locales/be.ts +188 -0
  1464. package/node_modules/zod/src/v4/locales/bg.ts +133 -0
  1465. package/node_modules/zod/src/v4/locales/bn.ts +123 -0
  1466. package/node_modules/zod/src/v4/locales/ca.ts +121 -0
  1467. package/node_modules/zod/src/v4/locales/ckb.ts +140 -0
  1468. package/node_modules/zod/src/v4/locales/cs.ts +123 -0
  1469. package/node_modules/zod/src/v4/locales/da.ts +128 -0
  1470. package/node_modules/zod/src/v4/locales/de.ts +121 -0
  1471. package/node_modules/zod/src/v4/locales/el.ts +124 -0
  1472. package/node_modules/zod/src/v4/locales/en.ts +136 -0
  1473. package/node_modules/zod/src/v4/locales/eo.ts +123 -0
  1474. package/node_modules/zod/src/v4/locales/es.ts +145 -0
  1475. package/node_modules/zod/src/v4/locales/fa.ts +131 -0
  1476. package/node_modules/zod/src/v4/locales/fi.ts +126 -0
  1477. package/node_modules/zod/src/v4/locales/fr-CA.ts +121 -0
  1478. package/node_modules/zod/src/v4/locales/fr.ts +139 -0
  1479. package/node_modules/zod/src/v4/locales/gu.ts +123 -0
  1480. package/node_modules/zod/src/v4/locales/he.ts +253 -0
  1481. package/node_modules/zod/src/v4/locales/hi.ts +126 -0
  1482. package/node_modules/zod/src/v4/locales/hr.ts +135 -0
  1483. package/node_modules/zod/src/v4/locales/hu.ts +122 -0
  1484. package/node_modules/zod/src/v4/locales/hy.ts +175 -0
  1485. package/node_modules/zod/src/v4/locales/id.ts +120 -0
  1486. package/node_modules/zod/src/v4/locales/index.ts +63 -0
  1487. package/node_modules/zod/src/v4/locales/is.ts +124 -0
  1488. package/node_modules/zod/src/v4/locales/it.ts +121 -0
  1489. package/node_modules/zod/src/v4/locales/ja.ts +119 -0
  1490. package/node_modules/zod/src/v4/locales/ka.ts +128 -0
  1491. package/node_modules/zod/src/v4/locales/kh.ts +7 -0
  1492. package/node_modules/zod/src/v4/locales/km.ts +124 -0
  1493. package/node_modules/zod/src/v4/locales/kn.ts +126 -0
  1494. package/node_modules/zod/src/v4/locales/ko.ts +126 -0
  1495. package/node_modules/zod/src/v4/locales/lt.ts +243 -0
  1496. package/node_modules/zod/src/v4/locales/mk.ts +123 -0
  1497. package/node_modules/zod/src/v4/locales/ms.ts +120 -0
  1498. package/node_modules/zod/src/v4/locales/ne.ts +128 -0
  1499. package/node_modules/zod/src/v4/locales/nl.ts +126 -0
  1500. package/node_modules/zod/src/v4/locales/nn.ts +121 -0
  1501. package/node_modules/zod/src/v4/locales/no.ts +121 -0
  1502. package/node_modules/zod/src/v4/locales/ota.ts +122 -0
  1503. package/node_modules/zod/src/v4/locales/pl.ts +123 -0
  1504. package/node_modules/zod/src/v4/locales/ps.ts +131 -0
  1505. package/node_modules/zod/src/v4/locales/pt-BR.ts +161 -0
  1506. package/node_modules/zod/src/v4/locales/pt.ts +159 -0
  1507. package/node_modules/zod/src/v4/locales/ro.ts +132 -0
  1508. package/node_modules/zod/src/v4/locales/ru.ts +188 -0
  1509. package/node_modules/zod/src/v4/locales/sk.ts +123 -0
  1510. package/node_modules/zod/src/v4/locales/sl.ts +123 -0
  1511. package/node_modules/zod/src/v4/locales/sv.ts +124 -0
  1512. package/node_modules/zod/src/v4/locales/ta.ts +123 -0
  1513. package/node_modules/zod/src/v4/locales/tg.ts +135 -0
  1514. package/node_modules/zod/src/v4/locales/th.ts +124 -0
  1515. package/node_modules/zod/src/v4/locales/tk.ts +113 -0
  1516. package/node_modules/zod/src/v4/locales/tr.ts +116 -0
  1517. package/node_modules/zod/src/v4/locales/ua.ts +7 -0
  1518. package/node_modules/zod/src/v4/locales/uk.ts +122 -0
  1519. package/node_modules/zod/src/v4/locales/ur.ts +124 -0
  1520. package/node_modules/zod/src/v4/locales/uz.ts +120 -0
  1521. package/node_modules/zod/src/v4/locales/vi.ts +122 -0
  1522. package/node_modules/zod/src/v4/locales/yo.ts +129 -0
  1523. package/node_modules/zod/src/v4/locales/zh-CN.ts +121 -0
  1524. package/node_modules/zod/src/v4/locales/zh-TW.ts +120 -0
  1525. package/node_modules/zod/src/v4/mini/checks.ts +33 -0
  1526. package/node_modules/zod/src/v4/mini/coerce.ts +27 -0
  1527. package/node_modules/zod/src/v4/mini/deep-partial.ts +73 -0
  1528. package/node_modules/zod/src/v4/mini/external.ts +52 -0
  1529. package/node_modules/zod/src/v4/mini/in-out.ts +45 -0
  1530. package/node_modules/zod/src/v4/mini/index.ts +3 -0
  1531. package/node_modules/zod/src/v4/mini/iso.ts +66 -0
  1532. package/node_modules/zod/src/v4/mini/parse.ts +16 -0
  1533. package/node_modules/zod/src/v4/mini/schemas.ts +2051 -0
  1534. package/node_modules/zod/src/v4/mini/tests/apply.test.ts +57 -0
  1535. package/node_modules/zod/src/v4/mini/tests/assignability.test.ts +190 -0
  1536. package/node_modules/zod/src/v4/mini/tests/brand.test.ts +94 -0
  1537. package/node_modules/zod/src/v4/mini/tests/checks.test.ts +158 -0
  1538. package/node_modules/zod/src/v4/mini/tests/codec.test.ts +582 -0
  1539. package/node_modules/zod/src/v4/mini/tests/computed.test.ts +30 -0
  1540. package/node_modules/zod/src/v4/mini/tests/cyclic-data.test.ts +84 -0
  1541. package/node_modules/zod/src/v4/mini/tests/deep-partial.test.ts +54 -0
  1542. package/node_modules/zod/src/v4/mini/tests/error.test.ts +41 -0
  1543. package/node_modules/zod/src/v4/mini/tests/functions.test.ts +14 -0
  1544. package/node_modules/zod/src/v4/mini/tests/index.test.ts +1146 -0
  1545. package/node_modules/zod/src/v4/mini/tests/number.test.ts +109 -0
  1546. package/node_modules/zod/src/v4/mini/tests/object.test.ts +292 -0
  1547. package/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +43 -0
  1548. package/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +341 -0
  1549. package/node_modules/zod/src/v4/mini/tests/standard-schema.test.ts +50 -0
  1550. package/node_modules/zod/src/v4/mini/tests/string.test.ts +396 -0
  1551. package/node_modules/zod/src/v4-mini/index.ts +3 -0
  1552. package/node_modules/zod/v3/ZodError.cjs +167 -0
  1553. package/node_modules/zod/v3/ZodError.d.cts +164 -0
  1554. package/node_modules/zod/v3/ZodError.d.ts +164 -0
  1555. package/node_modules/zod/v3/ZodError.js +143 -0
  1556. package/node_modules/zod/v3/errors.cjs +36 -0
  1557. package/node_modules/zod/v3/errors.d.cts +5 -0
  1558. package/node_modules/zod/v3/errors.d.ts +5 -0
  1559. package/node_modules/zod/v3/errors.js +9 -0
  1560. package/node_modules/zod/v3/external.cjs +41 -0
  1561. package/node_modules/zod/v3/external.d.cts +6 -0
  1562. package/node_modules/zod/v3/external.d.ts +6 -0
  1563. package/node_modules/zod/v3/external.js +6 -0
  1564. package/node_modules/zod/v3/helpers/enumUtil.cjs +21 -0
  1565. package/node_modules/zod/v3/helpers/enumUtil.d.cts +8 -0
  1566. package/node_modules/zod/v3/helpers/enumUtil.d.ts +8 -0
  1567. package/node_modules/zod/v3/helpers/enumUtil.js +1 -0
  1568. package/node_modules/zod/v3/helpers/errorUtil.cjs +28 -0
  1569. package/node_modules/zod/v3/helpers/errorUtil.d.cts +9 -0
  1570. package/node_modules/zod/v3/helpers/errorUtil.d.ts +9 -0
  1571. package/node_modules/zod/v3/helpers/errorUtil.js +6 -0
  1572. package/node_modules/zod/v3/helpers/parseUtil.cjs +143 -0
  1573. package/node_modules/zod/v3/helpers/parseUtil.d.cts +78 -0
  1574. package/node_modules/zod/v3/helpers/parseUtil.d.ts +78 -0
  1575. package/node_modules/zod/v3/helpers/parseUtil.js +109 -0
  1576. package/node_modules/zod/v3/helpers/partialUtil.cjs +21 -0
  1577. package/node_modules/zod/v3/helpers/partialUtil.d.cts +8 -0
  1578. package/node_modules/zod/v3/helpers/partialUtil.d.ts +8 -0
  1579. package/node_modules/zod/v3/helpers/partialUtil.js +1 -0
  1580. package/node_modules/zod/v3/helpers/typeAliases.cjs +21 -0
  1581. package/node_modules/zod/v3/helpers/typeAliases.d.cts +2 -0
  1582. package/node_modules/zod/v3/helpers/typeAliases.d.ts +2 -0
  1583. package/node_modules/zod/v3/helpers/typeAliases.js +1 -0
  1584. package/node_modules/zod/v3/helpers/util.cjs +156 -0
  1585. package/node_modules/zod/v3/helpers/util.d.cts +85 -0
  1586. package/node_modules/zod/v3/helpers/util.d.ts +85 -0
  1587. package/node_modules/zod/v3/helpers/util.js +133 -0
  1588. package/node_modules/zod/v3/index.cjs +52 -0
  1589. package/node_modules/zod/v3/index.d.cts +4 -0
  1590. package/node_modules/zod/v3/index.d.ts +4 -0
  1591. package/node_modules/zod/v3/index.js +4 -0
  1592. package/node_modules/zod/v3/locales/en.cjs +112 -0
  1593. package/node_modules/zod/v3/locales/en.d.cts +3 -0
  1594. package/node_modules/zod/v3/locales/en.d.ts +3 -0
  1595. package/node_modules/zod/v3/locales/en.js +109 -0
  1596. package/node_modules/zod/v3/package.json +7 -0
  1597. package/node_modules/zod/v3/standard-schema.cjs +21 -0
  1598. package/node_modules/zod/v3/standard-schema.d.cts +102 -0
  1599. package/node_modules/zod/v3/standard-schema.d.ts +102 -0
  1600. package/node_modules/zod/v3/standard-schema.js +1 -0
  1601. package/node_modules/zod/v3/types.cjs +3798 -0
  1602. package/node_modules/zod/v3/types.d.cts +1034 -0
  1603. package/node_modules/zod/v3/types.d.ts +1034 -0
  1604. package/node_modules/zod/v3/types.js +3697 -0
  1605. package/node_modules/zod/v4/classic/checks.cjs +53 -0
  1606. package/node_modules/zod/v4/classic/checks.d.cts +1 -0
  1607. package/node_modules/zod/v4/classic/checks.d.ts +1 -0
  1608. package/node_modules/zod/v4/classic/checks.js +1 -0
  1609. package/node_modules/zod/v4/classic/coerce.cjs +66 -0
  1610. package/node_modules/zod/v4/classic/coerce.d.cts +17 -0
  1611. package/node_modules/zod/v4/classic/coerce.d.ts +17 -0
  1612. package/node_modules/zod/v4/classic/coerce.js +17 -0
  1613. package/node_modules/zod/v4/classic/compat.cjs +80 -0
  1614. package/node_modules/zod/v4/classic/compat.d.cts +48 -0
  1615. package/node_modules/zod/v4/classic/compat.d.ts +48 -0
  1616. package/node_modules/zod/v4/classic/compat.js +31 -0
  1617. package/node_modules/zod/v4/classic/deep-partial.cjs +58 -0
  1618. package/node_modules/zod/v4/classic/deep-partial.d.cts +14 -0
  1619. package/node_modules/zod/v4/classic/deep-partial.d.ts +14 -0
  1620. package/node_modules/zod/v4/classic/deep-partial.js +13 -0
  1621. package/node_modules/zod/v4/classic/errors.cjs +102 -0
  1622. package/node_modules/zod/v4/classic/errors.d.cts +29 -0
  1623. package/node_modules/zod/v4/classic/errors.d.ts +29 -0
  1624. package/node_modules/zod/v4/classic/errors.js +57 -0
  1625. package/node_modules/zod/v4/classic/external.cjs +97 -0
  1626. package/node_modules/zod/v4/classic/external.d.cts +19 -0
  1627. package/node_modules/zod/v4/classic/external.d.ts +19 -0
  1628. package/node_modules/zod/v4/classic/external.js +17 -0
  1629. package/node_modules/zod/v4/classic/from-json-schema.cjs +926 -0
  1630. package/node_modules/zod/v4/classic/from-json-schema.d.cts +12 -0
  1631. package/node_modules/zod/v4/classic/from-json-schema.d.ts +12 -0
  1632. package/node_modules/zod/v4/classic/from-json-schema.js +881 -0
  1633. package/node_modules/zod/v4/classic/in-out.cjs +82 -0
  1634. package/node_modules/zod/v4/classic/in-out.d.cts +8 -0
  1635. package/node_modules/zod/v4/classic/in-out.d.ts +8 -0
  1636. package/node_modules/zod/v4/classic/in-out.js +36 -0
  1637. package/node_modules/zod/v4/classic/index.cjs +52 -0
  1638. package/node_modules/zod/v4/classic/index.d.cts +3 -0
  1639. package/node_modules/zod/v4/classic/index.d.ts +3 -0
  1640. package/node_modules/zod/v4/classic/index.js +4 -0
  1641. package/node_modules/zod/v4/classic/iso.cjs +68 -0
  1642. package/node_modules/zod/v4/classic/iso.d.cts +7 -0
  1643. package/node_modules/zod/v4/classic/iso.d.ts +7 -0
  1644. package/node_modules/zod/v4/classic/iso.js +15 -0
  1645. package/node_modules/zod/v4/classic/package.json +7 -0
  1646. package/node_modules/zod/v4/classic/parse.cjs +63 -0
  1647. package/node_modules/zod/v4/classic/parse.d.cts +44 -0
  1648. package/node_modules/zod/v4/classic/parse.d.ts +44 -0
  1649. package/node_modules/zod/v4/classic/parse.js +16 -0
  1650. package/node_modules/zod/v4/classic/schemas.cjs +1676 -0
  1651. package/node_modules/zod/v4/classic/schemas.d.cts +816 -0
  1652. package/node_modules/zod/v4/classic/schemas.d.ts +816 -0
  1653. package/node_modules/zod/v4/classic/schemas.js +1535 -0
  1654. package/node_modules/zod/v4/core/api.cjs +1269 -0
  1655. package/node_modules/zod/v4/core/api.d.cts +335 -0
  1656. package/node_modules/zod/v4/core/api.d.ts +335 -0
  1657. package/node_modules/zod/v4/core/api.js +1107 -0
  1658. package/node_modules/zod/v4/core/checks.cjs +561 -0
  1659. package/node_modules/zod/v4/core/checks.d.cts +294 -0
  1660. package/node_modules/zod/v4/core/checks.d.ts +294 -0
  1661. package/node_modules/zod/v4/core/checks.js +516 -0
  1662. package/node_modules/zod/v4/core/compile.cjs +1916 -0
  1663. package/node_modules/zod/v4/core/compile.d.cts +65 -0
  1664. package/node_modules/zod/v4/core/compile.d.ts +65 -0
  1665. package/node_modules/zod/v4/core/compile.js +1866 -0
  1666. package/node_modules/zod/v4/core/core.cjs +167 -0
  1667. package/node_modules/zod/v4/core/core.d.cts +82 -0
  1668. package/node_modules/zod/v4/core/core.d.ts +82 -0
  1669. package/node_modules/zod/v4/core/core.js +141 -0
  1670. package/node_modules/zod/v4/core/doc.cjs +61 -0
  1671. package/node_modules/zod/v4/core/doc.d.cts +16 -0
  1672. package/node_modules/zod/v4/core/doc.d.ts +16 -0
  1673. package/node_modules/zod/v4/core/doc.js +38 -0
  1674. package/node_modules/zod/v4/core/errors.cjs +317 -0
  1675. package/node_modules/zod/v4/core/errors.d.cts +225 -0
  1676. package/node_modules/zod/v4/core/errors.d.ts +225 -0
  1677. package/node_modules/zod/v4/core/errors.js +267 -0
  1678. package/node_modules/zod/v4/core/index.cjs +70 -0
  1679. package/node_modules/zod/v4/core/index.d.cts +19 -0
  1680. package/node_modules/zod/v4/core/index.d.ts +19 -0
  1681. package/node_modules/zod/v4/core/index.js +19 -0
  1682. package/node_modules/zod/v4/core/json-schema-generator.cjs +122 -0
  1683. package/node_modules/zod/v4/core/json-schema-generator.d.cts +65 -0
  1684. package/node_modules/zod/v4/core/json-schema-generator.d.ts +65 -0
  1685. package/node_modules/zod/v4/core/json-schema-generator.js +99 -0
  1686. package/node_modules/zod/v4/core/json-schema-processors.cjs +929 -0
  1687. package/node_modules/zod/v4/core/json-schema-processors.d.cts +65 -0
  1688. package/node_modules/zod/v4/core/json-schema-processors.d.ts +65 -0
  1689. package/node_modules/zod/v4/core/json-schema-processors.js +843 -0
  1690. package/node_modules/zod/v4/core/json-schema.cjs +21 -0
  1691. package/node_modules/zod/v4/core/json-schema.d.cts +89 -0
  1692. package/node_modules/zod/v4/core/json-schema.d.ts +89 -0
  1693. package/node_modules/zod/v4/core/json-schema.js +1 -0
  1694. package/node_modules/zod/v4/core/memoizer.cjs +360 -0
  1695. package/node_modules/zod/v4/core/memoizer.d.cts +15 -0
  1696. package/node_modules/zod/v4/core/memoizer.d.ts +15 -0
  1697. package/node_modules/zod/v4/core/memoizer.js +311 -0
  1698. package/node_modules/zod/v4/core/package.json +7 -0
  1699. package/node_modules/zod/v4/core/parse.cjs +233 -0
  1700. package/node_modules/zod/v4/core/parse.d.cts +52 -0
  1701. package/node_modules/zod/v4/core/parse.d.ts +52 -0
  1702. package/node_modules/zod/v4/core/parse.js +175 -0
  1703. package/node_modules/zod/v4/core/regexes.cjs +209 -0
  1704. package/node_modules/zod/v4/core/regexes.d.cts +90 -0
  1705. package/node_modules/zod/v4/core/regexes.d.ts +90 -0
  1706. package/node_modules/zod/v4/core/regexes.js +156 -0
  1707. package/node_modules/zod/v4/core/registries.cjs +75 -0
  1708. package/node_modules/zod/v4/core/registries.d.cts +35 -0
  1709. package/node_modules/zod/v4/core/registries.d.ts +35 -0
  1710. package/node_modules/zod/v4/core/registries.js +51 -0
  1711. package/node_modules/zod/v4/core/schemas.cjs +2699 -0
  1712. package/node_modules/zod/v4/core/schemas.d.cts +1275 -0
  1713. package/node_modules/zod/v4/core/schemas.d.ts +1275 -0
  1714. package/node_modules/zod/v4/core/schemas.js +2636 -0
  1715. package/node_modules/zod/v4/core/standard-schema.cjs +21 -0
  1716. package/node_modules/zod/v4/core/standard-schema.d.cts +126 -0
  1717. package/node_modules/zod/v4/core/standard-schema.d.ts +126 -0
  1718. package/node_modules/zod/v4/core/standard-schema.js +1 -0
  1719. package/node_modules/zod/v4/core/to-json-schema.cjs +681 -0
  1720. package/node_modules/zod/v4/core/to-json-schema.d.cts +154 -0
  1721. package/node_modules/zod/v4/core/to-json-schema.d.ts +154 -0
  1722. package/node_modules/zod/v4/core/to-json-schema.js +651 -0
  1723. package/node_modules/zod/v4/core/util.cjs +964 -0
  1724. package/node_modules/zod/v4/core/util.d.cts +280 -0
  1725. package/node_modules/zod/v4/core/util.d.ts +280 -0
  1726. package/node_modules/zod/v4/core/util.js +873 -0
  1727. package/node_modules/zod/v4/core/versions.cjs +27 -0
  1728. package/node_modules/zod/v4/core/versions.d.cts +5 -0
  1729. package/node_modules/zod/v4/core/versions.d.ts +5 -0
  1730. package/node_modules/zod/v4/core/versions.js +5 -0
  1731. package/node_modules/zod/v4/core/visit.cjs +214 -0
  1732. package/node_modules/zod/v4/core/visit.d.cts +30 -0
  1733. package/node_modules/zod/v4/core/visit.d.ts +30 -0
  1734. package/node_modules/zod/v4/core/visit.js +169 -0
  1735. package/node_modules/zod/v4/index.cjs +51 -0
  1736. package/node_modules/zod/v4/index.d.cts +3 -0
  1737. package/node_modules/zod/v4/index.d.ts +3 -0
  1738. package/node_modules/zod/v4/index.js +4 -0
  1739. package/node_modules/zod/v4/locales/ar.cjs +138 -0
  1740. package/node_modules/zod/v4/locales/ar.d.cts +5 -0
  1741. package/node_modules/zod/v4/locales/ar.d.ts +4 -0
  1742. package/node_modules/zod/v4/locales/ar.js +111 -0
  1743. package/node_modules/zod/v4/locales/az.cjs +137 -0
  1744. package/node_modules/zod/v4/locales/az.d.cts +5 -0
  1745. package/node_modules/zod/v4/locales/az.d.ts +4 -0
  1746. package/node_modules/zod/v4/locales/az.js +110 -0
  1747. package/node_modules/zod/v4/locales/be.cjs +195 -0
  1748. package/node_modules/zod/v4/locales/be.d.cts +5 -0
  1749. package/node_modules/zod/v4/locales/be.d.ts +4 -0
  1750. package/node_modules/zod/v4/locales/be.js +168 -0
  1751. package/node_modules/zod/v4/locales/bg.cjs +152 -0
  1752. package/node_modules/zod/v4/locales/bg.d.cts +5 -0
  1753. package/node_modules/zod/v4/locales/bg.d.ts +4 -0
  1754. package/node_modules/zod/v4/locales/bg.js +125 -0
  1755. package/node_modules/zod/v4/locales/bn.cjs +140 -0
  1756. package/node_modules/zod/v4/locales/bn.d.cts +5 -0
  1757. package/node_modules/zod/v4/locales/bn.d.ts +4 -0
  1758. package/node_modules/zod/v4/locales/bn.js +113 -0
  1759. package/node_modules/zod/v4/locales/ca.cjs +139 -0
  1760. package/node_modules/zod/v4/locales/ca.d.cts +5 -0
  1761. package/node_modules/zod/v4/locales/ca.d.ts +4 -0
  1762. package/node_modules/zod/v4/locales/ca.js +112 -0
  1763. package/node_modules/zod/v4/locales/ckb.cjs +160 -0
  1764. package/node_modules/zod/v4/locales/ckb.d.cts +5 -0
  1765. package/node_modules/zod/v4/locales/ckb.d.ts +4 -0
  1766. package/node_modules/zod/v4/locales/ckb.js +133 -0
  1767. package/node_modules/zod/v4/locales/cs.cjs +143 -0
  1768. package/node_modules/zod/v4/locales/cs.d.cts +5 -0
  1769. package/node_modules/zod/v4/locales/cs.d.ts +4 -0
  1770. package/node_modules/zod/v4/locales/cs.js +116 -0
  1771. package/node_modules/zod/v4/locales/da.cjs +147 -0
  1772. package/node_modules/zod/v4/locales/da.d.cts +5 -0
  1773. package/node_modules/zod/v4/locales/da.d.ts +4 -0
  1774. package/node_modules/zod/v4/locales/da.js +120 -0
  1775. package/node_modules/zod/v4/locales/de.cjs +140 -0
  1776. package/node_modules/zod/v4/locales/de.d.cts +5 -0
  1777. package/node_modules/zod/v4/locales/de.d.ts +4 -0
  1778. package/node_modules/zod/v4/locales/de.js +113 -0
  1779. package/node_modules/zod/v4/locales/el.cjs +139 -0
  1780. package/node_modules/zod/v4/locales/el.d.cts +5 -0
  1781. package/node_modules/zod/v4/locales/el.d.ts +4 -0
  1782. package/node_modules/zod/v4/locales/el.js +112 -0
  1783. package/node_modules/zod/v4/locales/en.cjs +152 -0
  1784. package/node_modules/zod/v4/locales/en.d.cts +5 -0
  1785. package/node_modules/zod/v4/locales/en.d.ts +4 -0
  1786. package/node_modules/zod/v4/locales/en.js +125 -0
  1787. package/node_modules/zod/v4/locales/eo.cjs +141 -0
  1788. package/node_modules/zod/v4/locales/eo.d.cts +5 -0
  1789. package/node_modules/zod/v4/locales/eo.d.ts +4 -0
  1790. package/node_modules/zod/v4/locales/eo.js +114 -0
  1791. package/node_modules/zod/v4/locales/es.cjs +163 -0
  1792. package/node_modules/zod/v4/locales/es.d.cts +5 -0
  1793. package/node_modules/zod/v4/locales/es.d.ts +4 -0
  1794. package/node_modules/zod/v4/locales/es.js +136 -0
  1795. package/node_modules/zod/v4/locales/fa.cjs +146 -0
  1796. package/node_modules/zod/v4/locales/fa.d.cts +5 -0
  1797. package/node_modules/zod/v4/locales/fa.d.ts +4 -0
  1798. package/node_modules/zod/v4/locales/fa.js +119 -0
  1799. package/node_modules/zod/v4/locales/fi.cjs +144 -0
  1800. package/node_modules/zod/v4/locales/fi.d.cts +5 -0
  1801. package/node_modules/zod/v4/locales/fi.d.ts +4 -0
  1802. package/node_modules/zod/v4/locales/fi.js +117 -0
  1803. package/node_modules/zod/v4/locales/fr-CA.cjs +139 -0
  1804. package/node_modules/zod/v4/locales/fr-CA.d.cts +5 -0
  1805. package/node_modules/zod/v4/locales/fr-CA.d.ts +4 -0
  1806. package/node_modules/zod/v4/locales/fr-CA.js +112 -0
  1807. package/node_modules/zod/v4/locales/fr.cjs +156 -0
  1808. package/node_modules/zod/v4/locales/fr.d.cts +5 -0
  1809. package/node_modules/zod/v4/locales/fr.d.ts +4 -0
  1810. package/node_modules/zod/v4/locales/fr.js +129 -0
  1811. package/node_modules/zod/v4/locales/gu.cjs +140 -0
  1812. package/node_modules/zod/v4/locales/gu.d.cts +5 -0
  1813. package/node_modules/zod/v4/locales/gu.d.ts +4 -0
  1814. package/node_modules/zod/v4/locales/gu.js +113 -0
  1815. package/node_modules/zod/v4/locales/he.cjs +248 -0
  1816. package/node_modules/zod/v4/locales/he.d.cts +5 -0
  1817. package/node_modules/zod/v4/locales/he.d.ts +4 -0
  1818. package/node_modules/zod/v4/locales/he.js +221 -0
  1819. package/node_modules/zod/v4/locales/hi.cjs +138 -0
  1820. package/node_modules/zod/v4/locales/hi.d.cts +5 -0
  1821. package/node_modules/zod/v4/locales/hi.d.ts +4 -0
  1822. package/node_modules/zod/v4/locales/hi.js +111 -0
  1823. package/node_modules/zod/v4/locales/hr.cjs +153 -0
  1824. package/node_modules/zod/v4/locales/hr.d.cts +5 -0
  1825. package/node_modules/zod/v4/locales/hr.d.ts +4 -0
  1826. package/node_modules/zod/v4/locales/hr.js +126 -0
  1827. package/node_modules/zod/v4/locales/hu.cjs +140 -0
  1828. package/node_modules/zod/v4/locales/hu.d.cts +5 -0
  1829. package/node_modules/zod/v4/locales/hu.d.ts +4 -0
  1830. package/node_modules/zod/v4/locales/hu.js +113 -0
  1831. package/node_modules/zod/v4/locales/hy.cjs +185 -0
  1832. package/node_modules/zod/v4/locales/hy.d.cts +5 -0
  1833. package/node_modules/zod/v4/locales/hy.d.ts +4 -0
  1834. package/node_modules/zod/v4/locales/hy.js +158 -0
  1835. package/node_modules/zod/v4/locales/id.cjs +138 -0
  1836. package/node_modules/zod/v4/locales/id.d.cts +5 -0
  1837. package/node_modules/zod/v4/locales/id.d.ts +4 -0
  1838. package/node_modules/zod/v4/locales/id.js +111 -0
  1839. package/node_modules/zod/v4/locales/index.cjs +152 -0
  1840. package/node_modules/zod/v4/locales/index.d.cts +63 -0
  1841. package/node_modules/zod/v4/locales/index.d.ts +63 -0
  1842. package/node_modules/zod/v4/locales/index.js +63 -0
  1843. package/node_modules/zod/v4/locales/is.cjs +141 -0
  1844. package/node_modules/zod/v4/locales/is.d.cts +5 -0
  1845. package/node_modules/zod/v4/locales/is.d.ts +4 -0
  1846. package/node_modules/zod/v4/locales/is.js +114 -0
  1847. package/node_modules/zod/v4/locales/it.cjs +140 -0
  1848. package/node_modules/zod/v4/locales/it.d.cts +5 -0
  1849. package/node_modules/zod/v4/locales/it.d.ts +4 -0
  1850. package/node_modules/zod/v4/locales/it.js +113 -0
  1851. package/node_modules/zod/v4/locales/ja.cjs +139 -0
  1852. package/node_modules/zod/v4/locales/ja.d.cts +5 -0
  1853. package/node_modules/zod/v4/locales/ja.d.ts +4 -0
  1854. package/node_modules/zod/v4/locales/ja.js +112 -0
  1855. package/node_modules/zod/v4/locales/ka.cjs +144 -0
  1856. package/node_modules/zod/v4/locales/ka.d.cts +5 -0
  1857. package/node_modules/zod/v4/locales/ka.d.ts +4 -0
  1858. package/node_modules/zod/v4/locales/ka.js +117 -0
  1859. package/node_modules/zod/v4/locales/kh.cjs +12 -0
  1860. package/node_modules/zod/v4/locales/kh.d.cts +5 -0
  1861. package/node_modules/zod/v4/locales/kh.d.ts +5 -0
  1862. package/node_modules/zod/v4/locales/kh.js +5 -0
  1863. package/node_modules/zod/v4/locales/km.cjs +142 -0
  1864. package/node_modules/zod/v4/locales/km.d.cts +5 -0
  1865. package/node_modules/zod/v4/locales/km.d.ts +4 -0
  1866. package/node_modules/zod/v4/locales/km.js +115 -0
  1867. package/node_modules/zod/v4/locales/kn.cjs +143 -0
  1868. package/node_modules/zod/v4/locales/kn.d.cts +5 -0
  1869. package/node_modules/zod/v4/locales/kn.d.ts +4 -0
  1870. package/node_modules/zod/v4/locales/kn.js +116 -0
  1871. package/node_modules/zod/v4/locales/ko.cjs +143 -0
  1872. package/node_modules/zod/v4/locales/ko.d.cts +5 -0
  1873. package/node_modules/zod/v4/locales/ko.d.ts +4 -0
  1874. package/node_modules/zod/v4/locales/ko.js +116 -0
  1875. package/node_modules/zod/v4/locales/lt.cjs +234 -0
  1876. package/node_modules/zod/v4/locales/lt.d.cts +5 -0
  1877. package/node_modules/zod/v4/locales/lt.d.ts +4 -0
  1878. package/node_modules/zod/v4/locales/lt.js +207 -0
  1879. package/node_modules/zod/v4/locales/mk.cjs +141 -0
  1880. package/node_modules/zod/v4/locales/mk.d.cts +5 -0
  1881. package/node_modules/zod/v4/locales/mk.d.ts +4 -0
  1882. package/node_modules/zod/v4/locales/mk.js +114 -0
  1883. package/node_modules/zod/v4/locales/ms.cjs +139 -0
  1884. package/node_modules/zod/v4/locales/ms.d.cts +5 -0
  1885. package/node_modules/zod/v4/locales/ms.d.ts +4 -0
  1886. package/node_modules/zod/v4/locales/ms.js +112 -0
  1887. package/node_modules/zod/v4/locales/ne.cjs +138 -0
  1888. package/node_modules/zod/v4/locales/ne.d.cts +5 -0
  1889. package/node_modules/zod/v4/locales/ne.d.ts +4 -0
  1890. package/node_modules/zod/v4/locales/ne.js +111 -0
  1891. package/node_modules/zod/v4/locales/nl.cjs +142 -0
  1892. package/node_modules/zod/v4/locales/nl.d.cts +5 -0
  1893. package/node_modules/zod/v4/locales/nl.d.ts +4 -0
  1894. package/node_modules/zod/v4/locales/nl.js +115 -0
  1895. package/node_modules/zod/v4/locales/nn.cjs +140 -0
  1896. package/node_modules/zod/v4/locales/nn.d.cts +5 -0
  1897. package/node_modules/zod/v4/locales/nn.d.ts +4 -0
  1898. package/node_modules/zod/v4/locales/nn.js +113 -0
  1899. package/node_modules/zod/v4/locales/no.cjs +140 -0
  1900. package/node_modules/zod/v4/locales/no.d.cts +5 -0
  1901. package/node_modules/zod/v4/locales/no.d.ts +4 -0
  1902. package/node_modules/zod/v4/locales/no.js +113 -0
  1903. package/node_modules/zod/v4/locales/ota.cjs +141 -0
  1904. package/node_modules/zod/v4/locales/ota.d.cts +5 -0
  1905. package/node_modules/zod/v4/locales/ota.d.ts +4 -0
  1906. package/node_modules/zod/v4/locales/ota.js +114 -0
  1907. package/node_modules/zod/v4/locales/package.json +7 -0
  1908. package/node_modules/zod/v4/locales/pl.cjs +141 -0
  1909. package/node_modules/zod/v4/locales/pl.d.cts +5 -0
  1910. package/node_modules/zod/v4/locales/pl.d.ts +4 -0
  1911. package/node_modules/zod/v4/locales/pl.js +114 -0
  1912. package/node_modules/zod/v4/locales/ps.cjs +146 -0
  1913. package/node_modules/zod/v4/locales/ps.d.cts +5 -0
  1914. package/node_modules/zod/v4/locales/ps.d.ts +4 -0
  1915. package/node_modules/zod/v4/locales/ps.js +119 -0
  1916. package/node_modules/zod/v4/locales/pt-BR.cjs +170 -0
  1917. package/node_modules/zod/v4/locales/pt-BR.d.cts +5 -0
  1918. package/node_modules/zod/v4/locales/pt-BR.d.ts +4 -0
  1919. package/node_modules/zod/v4/locales/pt-BR.js +143 -0
  1920. package/node_modules/zod/v4/locales/pt.cjs +169 -0
  1921. package/node_modules/zod/v4/locales/pt.d.cts +5 -0
  1922. package/node_modules/zod/v4/locales/pt.d.ts +4 -0
  1923. package/node_modules/zod/v4/locales/pt.js +142 -0
  1924. package/node_modules/zod/v4/locales/ro.cjs +149 -0
  1925. package/node_modules/zod/v4/locales/ro.d.cts +5 -0
  1926. package/node_modules/zod/v4/locales/ro.d.ts +4 -0
  1927. package/node_modules/zod/v4/locales/ro.js +122 -0
  1928. package/node_modules/zod/v4/locales/ru.cjs +195 -0
  1929. package/node_modules/zod/v4/locales/ru.d.cts +5 -0
  1930. package/node_modules/zod/v4/locales/ru.d.ts +4 -0
  1931. package/node_modules/zod/v4/locales/ru.js +168 -0
  1932. package/node_modules/zod/v4/locales/sk.cjs +143 -0
  1933. package/node_modules/zod/v4/locales/sk.d.cts +5 -0
  1934. package/node_modules/zod/v4/locales/sk.d.ts +4 -0
  1935. package/node_modules/zod/v4/locales/sk.js +116 -0
  1936. package/node_modules/zod/v4/locales/sl.cjs +141 -0
  1937. package/node_modules/zod/v4/locales/sl.d.cts +5 -0
  1938. package/node_modules/zod/v4/locales/sl.d.ts +4 -0
  1939. package/node_modules/zod/v4/locales/sl.js +114 -0
  1940. package/node_modules/zod/v4/locales/sv.cjs +142 -0
  1941. package/node_modules/zod/v4/locales/sv.d.cts +5 -0
  1942. package/node_modules/zod/v4/locales/sv.d.ts +4 -0
  1943. package/node_modules/zod/v4/locales/sv.js +115 -0
  1944. package/node_modules/zod/v4/locales/ta.cjs +142 -0
  1945. package/node_modules/zod/v4/locales/ta.d.cts +5 -0
  1946. package/node_modules/zod/v4/locales/ta.d.ts +4 -0
  1947. package/node_modules/zod/v4/locales/ta.js +115 -0
  1948. package/node_modules/zod/v4/locales/tg.cjs +144 -0
  1949. package/node_modules/zod/v4/locales/tg.d.cts +5 -0
  1950. package/node_modules/zod/v4/locales/tg.d.ts +4 -0
  1951. package/node_modules/zod/v4/locales/tg.js +117 -0
  1952. package/node_modules/zod/v4/locales/th.cjs +142 -0
  1953. package/node_modules/zod/v4/locales/th.d.cts +5 -0
  1954. package/node_modules/zod/v4/locales/th.d.ts +4 -0
  1955. package/node_modules/zod/v4/locales/th.js +115 -0
  1956. package/node_modules/zod/v4/locales/tk.cjs +134 -0
  1957. package/node_modules/zod/v4/locales/tk.d.cts +5 -0
  1958. package/node_modules/zod/v4/locales/tk.d.ts +4 -0
  1959. package/node_modules/zod/v4/locales/tk.js +107 -0
  1960. package/node_modules/zod/v4/locales/tr.cjs +137 -0
  1961. package/node_modules/zod/v4/locales/tr.d.cts +5 -0
  1962. package/node_modules/zod/v4/locales/tr.d.ts +4 -0
  1963. package/node_modules/zod/v4/locales/tr.js +110 -0
  1964. package/node_modules/zod/v4/locales/ua.cjs +12 -0
  1965. package/node_modules/zod/v4/locales/ua.d.cts +5 -0
  1966. package/node_modules/zod/v4/locales/ua.d.ts +5 -0
  1967. package/node_modules/zod/v4/locales/ua.js +5 -0
  1968. package/node_modules/zod/v4/locales/uk.cjs +140 -0
  1969. package/node_modules/zod/v4/locales/uk.d.cts +5 -0
  1970. package/node_modules/zod/v4/locales/uk.d.ts +4 -0
  1971. package/node_modules/zod/v4/locales/uk.js +113 -0
  1972. package/node_modules/zod/v4/locales/ur.cjs +142 -0
  1973. package/node_modules/zod/v4/locales/ur.d.cts +5 -0
  1974. package/node_modules/zod/v4/locales/ur.d.ts +4 -0
  1975. package/node_modules/zod/v4/locales/ur.js +115 -0
  1976. package/node_modules/zod/v4/locales/uz.cjs +140 -0
  1977. package/node_modules/zod/v4/locales/uz.d.cts +5 -0
  1978. package/node_modules/zod/v4/locales/uz.d.ts +4 -0
  1979. package/node_modules/zod/v4/locales/uz.js +113 -0
  1980. package/node_modules/zod/v4/locales/vi.cjs +140 -0
  1981. package/node_modules/zod/v4/locales/vi.d.cts +5 -0
  1982. package/node_modules/zod/v4/locales/vi.d.ts +4 -0
  1983. package/node_modules/zod/v4/locales/vi.js +113 -0
  1984. package/node_modules/zod/v4/locales/yo.cjs +139 -0
  1985. package/node_modules/zod/v4/locales/yo.d.cts +5 -0
  1986. package/node_modules/zod/v4/locales/yo.d.ts +4 -0
  1987. package/node_modules/zod/v4/locales/yo.js +112 -0
  1988. package/node_modules/zod/v4/locales/zh-CN.cjs +141 -0
  1989. package/node_modules/zod/v4/locales/zh-CN.d.cts +5 -0
  1990. package/node_modules/zod/v4/locales/zh-CN.d.ts +4 -0
  1991. package/node_modules/zod/v4/locales/zh-CN.js +114 -0
  1992. package/node_modules/zod/v4/locales/zh-TW.cjs +139 -0
  1993. package/node_modules/zod/v4/locales/zh-TW.d.cts +5 -0
  1994. package/node_modules/zod/v4/locales/zh-TW.d.ts +4 -0
  1995. package/node_modules/zod/v4/locales/zh-TW.js +112 -0
  1996. package/node_modules/zod/v4/mini/checks.cjs +54 -0
  1997. package/node_modules/zod/v4/mini/checks.d.cts +1 -0
  1998. package/node_modules/zod/v4/mini/checks.d.ts +1 -0
  1999. package/node_modules/zod/v4/mini/checks.js +1 -0
  2000. package/node_modules/zod/v4/mini/coerce.cjs +71 -0
  2001. package/node_modules/zod/v4/mini/coerce.d.cts +7 -0
  2002. package/node_modules/zod/v4/mini/coerce.d.ts +7 -0
  2003. package/node_modules/zod/v4/mini/coerce.js +22 -0
  2004. package/node_modules/zod/v4/mini/deep-partial.cjs +58 -0
  2005. package/node_modules/zod/v4/mini/deep-partial.d.cts +14 -0
  2006. package/node_modules/zod/v4/mini/deep-partial.d.ts +14 -0
  2007. package/node_modules/zod/v4/mini/deep-partial.js +13 -0
  2008. package/node_modules/zod/v4/mini/external.cjs +95 -0
  2009. package/node_modules/zod/v4/mini/external.d.cts +16 -0
  2010. package/node_modules/zod/v4/mini/external.d.ts +16 -0
  2011. package/node_modules/zod/v4/mini/external.js +16 -0
  2012. package/node_modules/zod/v4/mini/in-out.cjs +82 -0
  2013. package/node_modules/zod/v4/mini/in-out.d.cts +8 -0
  2014. package/node_modules/zod/v4/mini/in-out.d.ts +8 -0
  2015. package/node_modules/zod/v4/mini/in-out.js +36 -0
  2016. package/node_modules/zod/v4/mini/index.cjs +51 -0
  2017. package/node_modules/zod/v4/mini/index.d.cts +3 -0
  2018. package/node_modules/zod/v4/mini/index.d.ts +3 -0
  2019. package/node_modules/zod/v4/mini/index.js +3 -0
  2020. package/node_modules/zod/v4/mini/iso.cjs +83 -0
  2021. package/node_modules/zod/v4/mini/iso.d.cts +22 -0
  2022. package/node_modules/zod/v4/mini/iso.d.ts +22 -0
  2023. package/node_modules/zod/v4/mini/iso.js +34 -0
  2024. package/node_modules/zod/v4/mini/package.json +7 -0
  2025. package/node_modules/zod/v4/mini/parse.cjs +37 -0
  2026. package/node_modules/zod/v4/mini/parse.d.cts +1 -0
  2027. package/node_modules/zod/v4/mini/parse.d.ts +1 -0
  2028. package/node_modules/zod/v4/mini/parse.js +1 -0
  2029. package/node_modules/zod/v4/mini/schemas.cjs +1147 -0
  2030. package/node_modules/zod/v4/mini/schemas.d.cts +480 -0
  2031. package/node_modules/zod/v4/mini/schemas.d.ts +480 -0
  2032. package/node_modules/zod/v4/mini/schemas.js +1002 -0
  2033. package/node_modules/zod/v4/package.json +7 -0
  2034. package/node_modules/zod/v4-mini/index.cjs +51 -0
  2035. package/node_modules/zod/v4-mini/index.d.cts +3 -0
  2036. package/node_modules/zod/v4-mini/index.d.ts +3 -0
  2037. package/node_modules/zod/v4-mini/index.js +3 -0
  2038. package/node_modules/zod/v4-mini/package.json +7 -0
  2039. package/package.json +70 -10
  2040. package/index.js +0 -1
@@ -0,0 +1,4671 @@
1
+ import { cancellableSandboxStartup } from "./startup-cancellation.js";
2
+ import { withAdapterExecutionPhase } from "../execution-phase.js";
3
+ import fs from "node:fs/promises";
4
+ import fsSync from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { execFile } from "node:child_process";
8
+ import { promisify } from "node:util";
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import { parseFrontmatterMarkdown } from "@tickernelz/wardmote-shared";
11
+ import { fileURLToPath } from "node:url";
12
+ import { adapterExecutionTargetSessionIdentity, describeAdapterExecutionTarget, adapterExecutionTargetDuplexObservabilityRecorder, adapterExecutionTargetEnablesSandboxDuplexBridge, formatAdapterExecutionTimeoutErrorMessage, formatAdapterExecutionTimeoutStartLogLine, prepareAdapterExecutionTargetRuntime, readAdapterExecutionTarget, resolveAdapterExecutionTargetTimeout, resolveReferencedSourceIgnore, runAdapterExecutionTargetShellCommand, startAdapterExecutionTargetPaperclipBridge, startAdapterExecutionTargetProcessSessionBridge, } from "@tickernelz/wardmote-adapter-utils/execution-target";
13
+ import { captureLocalProcess, capturedProcessExited, killCapturedLocalProcess } from "./local-process-control.js";
14
+ import { DUPLEX_CHANNEL_LOST_ERROR_CODE } from "../bridge-transport-contract.js";
15
+ import { classifyToolDefinitionFailure, formatTerminalSessionFailure, sanitizeTerminalSessionFailure, } from "./terminal-session-failure.js";
16
+ import { legacyEnvKey } from "@tickernelz/wardmote-shared/env-aliases";
17
+ import { resolveDefaultPaperclipHomeDir } from "@tickernelz/wardmote-shared/home-paths";
18
+ import { classifyWorkspaceRestoreFailure, describeWorkspaceRestoreFailure, } from "../workspace-restore-merge.js";
19
+ import { paperclipAgentPromptTemplate, DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE, applyPaperclipWorkspaceEnv, asNumber, asString, buildInvocationEnvForLogs, buildPaperclipEnv, ensureAbsoluteDirectory, ensurePathInEnv, ensurePaperclipSkillSymlink, isForbiddenConfigEnvKey, isPaperclipExternalChatTurn, isPaperclipRuntimeEnvKey, joinPromptSections, materializePaperclipSkillCopy, parseObject, isPaperclipSkillSourceMissing, readPaperclipRuntimeSkillEntries, readPaperclipIssueWorkModeFromContext, renderTemplate, resolvePaperclipInstanceRootForAdapter, hydrateFreshSessionHandoff, selectInitialCommunicationGuidance, selectPaperclipPromptSections, resolveLegacyPaperclipDesiredSkillNames, removeMaintainerOnlySkillSymlinks, rewriteWorkspaceCwdEnvVarsForExecution, shapePaperclipWorkspaceEnvForExecution, } from "@tickernelz/wardmote-adapter-utils/server-utils";
20
+ import { PAPERCLIP_MCP_SERVER_NAME, paperclipAccessGuidance, paperclipAccessMode, paperclipMcpToolsets, } from "@tickernelz/wardmote-adapter-utils/paperclip-mcp";
21
+ import { paperclipMcpHttpTarget } from "@tickernelz/wardmote-adapter-utils/paperclip-mcp-mount";
22
+ import { shellQuote } from "@tickernelz/wardmote-adapter-utils/ssh";
23
+ import { runToolProfile } from "@tickernelz/wardmote-adapter-utils/tool-profile";
24
+ import { createEphemeralSessionEnvironmentStore } from "./ephemeral-session-environment.js";
25
+ import { createAcpRuntime, createAgentRegistry, createRuntimeStore, isAcpRuntimeError, } from "acpx/runtime";
26
+ import { ACPX_DUPLEX_LOSS_CANCEL_DEADLINE_MS, ACPX_HANDSHAKE_TIMEOUT_MS, ACPX_HANDSHAKE_TRANSPORT_POLL_MS, DEFAULT_ACP_ENGINE_AGENT, DEFAULT_ACP_ENGINE_MODE, DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS, DEFAULT_ACP_ENGINE_PERMISSION_MODE, DEFAULT_ACP_ENGINE_TIMEOUT_SEC, DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS, } from "./constants.js";
27
+ import { createRunResourceLedger } from "./run-resource-ledger.js";
28
+ import { settleAcpRun } from "./settlement-sequence.js";
29
+ import { runAttempt, } from "./run-coordinator.js";
30
+ import { runTurn as runTurnSequence, } from "./turn-sequence.js";
31
+ import { createHostRunSite, } from "./run-site-host.js";
32
+ import { createSandboxRunSite } from "./run-site-sandbox.js";
33
+ import { createRuntimeSpanRunner, emitRunPhaseTiming, emitSkippedStartupStep, getActiveStepContext, measureStartupStep, NOOP_STARTUP_SPAN, NOOP_STARTUP_TRACE_CONTEXT, runWithRuntimeParent, setSandboxRootSpanAttributes, } from "./startup-timing.js";
34
+ const defaultModuleDir = path.dirname(fileURLToPath(import.meta.url));
35
+ const PAPERCLIP_MANAGED_CODEX_SKILLS_MANIFEST = ".paperclip-managed-skills.json";
36
+ const BENIGN_NES_CLOSE_STDERR = /method: ['"]nes\/close['"].*-32601/;
37
+ function routeChildStderr(state, chunk) {
38
+ if (state.logPath) {
39
+ fsSync.mkdirSync(path.dirname(state.logPath), { recursive: true });
40
+ fsSync.appendFileSync(state.logPath, chunk);
41
+ }
42
+ const combined = state.pendingLiveLine + chunk;
43
+ const lastNewline = combined.lastIndexOf("\n");
44
+ if (lastNewline < 0) {
45
+ state.pendingLiveLine = combined;
46
+ return;
47
+ }
48
+ const complete = combined.slice(0, lastNewline + 1);
49
+ state.pendingLiveLine = combined.slice(lastNewline + 1);
50
+ const filtered = complete
51
+ .split(/(?<=\n)/)
52
+ .filter((line) => !BENIGN_NES_CLOSE_STDERR.test(line))
53
+ .join("");
54
+ if (filtered)
55
+ process.stderr.write(filtered);
56
+ }
57
+ function flushChildStderr(state) {
58
+ if (state.pendingLiveLine && !BENIGN_NES_CLOSE_STDERR.test(state.pendingLiveLine)) {
59
+ process.stderr.write(state.pendingLiveLine);
60
+ }
61
+ state.pendingLiveLine = "";
62
+ }
63
+ const defaultWarmHandles = new Map();
64
+ const defaultStagedRuntimes = new Map();
65
+ const defaultStagingLocks = new Map();
66
+ function resolveEngineSettings(options) {
67
+ const moduleDir = path.resolve(options.moduleDir ?? defaultModuleDir);
68
+ return {
69
+ adapterType: options.adapterType?.trim() || "acp_engine",
70
+ moduleDir,
71
+ packageRootDir: path.resolve(options.packageRootDir ?? path.resolve(moduleDir, "../..")),
72
+ };
73
+ }
74
+ function stableJson(value) {
75
+ if (Array.isArray(value))
76
+ return `[${value.map(stableJson).join(",")}]`;
77
+ if (value && typeof value === "object") {
78
+ return `{${Object.entries(value)
79
+ .sort(([a], [b]) => a.localeCompare(b))
80
+ .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
81
+ .join(",")}}`;
82
+ }
83
+ return JSON.stringify(value);
84
+ }
85
+ function shortHash(value) {
86
+ return createHash("sha256").update(stableJson(value)).digest("hex").slice(0, 16);
87
+ }
88
+ /**
89
+ * Hash the session fingerprint. The builder accepts only a
90
+ * `SessionFingerprintIdentity`, so no company, agent, or task identifier can
91
+ * enter the hash. Those identifiers scope the outer session key only (see
92
+ * `SessionKeyIdentity`).
93
+ */
94
+ export function buildSessionFingerprint(identity) {
95
+ return shortHash(identity);
96
+ }
97
+ /**
98
+ * Build the session key from the fingerprint and the outer-key identity. The key
99
+ * form is `paperclip:companyId:agentId:taskKey:fingerprint`.
100
+ */
101
+ export function buildSessionKey(identity, fingerprint) {
102
+ return `paperclip:${identity.companyId}:${identity.agentId}:${identity.taskKey}:${fingerprint}`;
103
+ }
104
+ // ACPX runs inside the long-lived Paperclip server process. A local child needs
105
+ // a small amount of host context (PATH, locale, certificate/proxy settings, and
106
+ // provider authentication), but it must not inherit the server's complete
107
+ // environment. A runner-backed remote sandbox inherits no ambient host context
108
+ // at all. In particular, native-runner bootstrap and MCP credentials are host
109
+ // authority, not provider credentials.
110
+ const ACPX_INHERITED_HOST_ENV_KEYS = new Set([
111
+ "PATH",
112
+ "PATHEXT",
113
+ "SYSTEMROOT",
114
+ "WINDIR",
115
+ "COMSPEC",
116
+ "HOME",
117
+ "USERPROFILE",
118
+ "HOMEDRIVE",
119
+ "HOMEPATH",
120
+ "USER",
121
+ "USERNAME",
122
+ "LOGNAME",
123
+ "SHELL",
124
+ "LANG",
125
+ "LANGUAGE",
126
+ "TZ",
127
+ "TMPDIR",
128
+ "TEMP",
129
+ "TMP",
130
+ "XDG_CONFIG_HOME",
131
+ "XDG_CACHE_HOME",
132
+ "XDG_DATA_HOME",
133
+ "SSL_CERT_FILE",
134
+ "SSL_CERT_DIR",
135
+ "NODE_EXTRA_CA_CERTS",
136
+ "HTTP_PROXY",
137
+ "HTTPS_PROXY",
138
+ "NO_PROXY",
139
+ "ALL_PROXY",
140
+ ]);
141
+ const ACPX_INHERITED_PROVIDER_ENV_KEYS = {
142
+ codex: new Set([
143
+ "OPENAI_API_KEY",
144
+ "CODEX_API_KEY",
145
+ ]),
146
+ claude: new Set([
147
+ "ANTHROPIC_API_KEY",
148
+ "ANTHROPIC_AUTH_TOKEN",
149
+ "CLAUDE_CODE_OAUTH_TOKEN",
150
+ "ANTHROPIC_BASE_URL",
151
+ "ANTHROPIC_MODEL",
152
+ "ANTHROPIC_SMALL_FAST_MODEL",
153
+ "CLAUDE_CONFIG_DIR",
154
+ "CLAUDE_CODE_USE_BEDROCK",
155
+ "ANTHROPIC_BEDROCK_BASE_URL",
156
+ "AWS_BEARER_TOKEN_BEDROCK",
157
+ "AWS_ACCESS_KEY_ID",
158
+ "AWS_SECRET_ACCESS_KEY",
159
+ "AWS_SESSION_TOKEN",
160
+ "AWS_REGION",
161
+ "AWS_DEFAULT_REGION",
162
+ "AWS_PROFILE",
163
+ "AWS_CONFIG_FILE",
164
+ "AWS_SHARED_CREDENTIALS_FILE",
165
+ ]),
166
+ pi: new Set(["OPENROUTER_API_KEY"]),
167
+ gemini: new Set([
168
+ "GEMINI_API_KEY",
169
+ "GOOGLE_API_KEY",
170
+ "GOOGLE_APPLICATION_CREDENTIALS",
171
+ "GOOGLE_GENAI_USE_GCA",
172
+ ]),
173
+ kimi: new Set([
174
+ "KIMI_API_KEY",
175
+ "MOONSHOT_API_KEY",
176
+ "KIMI_MODEL_NAME",
177
+ "KIMI_MODEL_API_KEY",
178
+ "KIMI_MODEL_BASE_URL",
179
+ "KIMI_MODEL_PROVIDER_TYPE",
180
+ "KIMI_CODE_HOME",
181
+ ]),
182
+ grok: new Set(["XAI_API_KEY"]),
183
+ };
184
+ /**
185
+ * Project the server environment onto the closed set a host ACPX provider may
186
+ * inherit. A runner-backed remote sandbox passes `false` and projects nothing.
187
+ * Explicit adapter/runtime env is merged later and is intentionally not
188
+ * restricted by this host projection.
189
+ */
190
+ export function projectAcpxInheritedHostEnvironment(inheritedEnv, acpxAgent, inheritHostEnvironment) {
191
+ // A runner-backed remote sandbox crosses a serialization boundary. Ambient
192
+ // server state is never part of that contract: provider auth/config must be
193
+ // supplied through adapter config, resolved runtime env, or a contribution.
194
+ if (!inheritHostEnvironment)
195
+ return {};
196
+ const providerKeys = ACPX_INHERITED_PROVIDER_ENV_KEYS[acpxAgent];
197
+ const projected = {};
198
+ for (const [key, value] of Object.entries(inheritedEnv)) {
199
+ if (typeof value !== "string")
200
+ continue;
201
+ const normalizedKey = key.toUpperCase();
202
+ const allowed = ACPX_INHERITED_HOST_ENV_KEYS.has(normalizedKey) ||
203
+ /^LC_[A-Z0-9_]{1,32}$/.test(normalizedKey) ||
204
+ providerKeys?.has(normalizedKey) === true;
205
+ if (allowed)
206
+ projected[key] = value;
207
+ }
208
+ return projected;
209
+ }
210
+ /**
211
+ * Build the single branded launch environment for a run. This is the sole
212
+ * constructor of `LaunchEnvironment`. It applies each contribution into the base
213
+ * env in registration order, then resolves and freezes the launch env.
214
+ *
215
+ * A contribution carries its credential scope. A run-scoped contribution (the
216
+ * run API key, a bridge token) and a session-scoped contribution (the Codex auth
217
+ * copy-back material) both merge here. Neither scope can escape into a reuse
218
+ * payload, because the branded contribution type and the branded environment
219
+ * type forbid it.
220
+ */
221
+ export function finalizeLaunchEnvironment(baseEnv, contributions, options) {
222
+ for (const contribution of contributions) {
223
+ Object.assign(baseEnv, contribution.env);
224
+ }
225
+ const env = Object.freeze(resolveRuntimeEnv(baseEnv, options.acpxAgent, options));
226
+ return { env };
227
+ }
228
+ // Directory names the staging path never ships for a referenced project (heavy
229
+ // build/cache output and git history), applied regardless of the project's
230
+ // ignore resolution. The content signature skips them so it reflects only the
231
+ // staged tree and never reads their bytes. Keep this set equal to the fixed
232
+ // excludes the sandbox and SSH runtimes always apply. A project's OWN resolved
233
+ // Git-ignored paths (see `resolveReferencedSourceIgnore`) are matched
234
+ // separately, by relative path, inside `referencedSourceContentSignature` — that
235
+ // is the real invariant now: the signature and both staging lanes must consume
236
+ // the SAME one resolution per project, not just this fixed name list.
237
+ const REFERENCED_SOURCE_SIGNATURE_SKIP_DIRS = new Set([
238
+ "node_modules",
239
+ "vendor",
240
+ "dist",
241
+ "build",
242
+ "out",
243
+ "coverage",
244
+ ".next",
245
+ ".turbo",
246
+ ".cache",
247
+ ".git",
248
+ ]);
249
+ /**
250
+ * Content signature of a referenced-project host tree for the session fingerprint.
251
+ *
252
+ * The staged-runtime cache reuses an already-staged referenced-project tree on a
253
+ * compatible resume and does not re-sync it. Referenced-project metadata (id, host
254
+ * path, workspace id, repo url, pinned ref) can stay identical while the files at
255
+ * that host path change: a branch moved to a new commit, a re-checkout in place, or
256
+ * a dirty worktree. So the metadata identity alone lets a resume serve a stale tree.
257
+ * This signature folds the tree's own content state into the identity.
258
+ *
259
+ * The walk reads each file's relative path and bytes and folds them into the hash.
260
+ * It reads bytes, not only file stats. A stat-only signature (size and modification
261
+ * time) collides when an edit keeps the byte length and the modification time — a
262
+ * re-checkout that restores the same size and timestamp. The byte hash busts on any
263
+ * content change, so the fingerprint busts and the next launch stages the current
264
+ * tree. The walk skips the heavy build, cache, and git directories the staging path
265
+ * never ships, plus the project's own resolved Git-ignored paths, and records a
266
+ * symlink by its target text without following it. On a read error the function
267
+ * returns a stable marker, so the fingerprint does not churn while staging
268
+ * surfaces the real error. The walk runs only when the run carries referenced
269
+ * projects (the multi-project sync path).
270
+ *
271
+ * `ignoreResolution` is the ONE resolution `resolveReferencedSourceIgnore`
272
+ * computed for this project — the same one the sandbox lane and the SSH lane
273
+ * consume. A `failed` resolution skips the walk entirely and returns a stable
274
+ * marker instead, because a failed project is not staged and its bytes are not
275
+ * read anywhere.
276
+ */
277
+ export async function referencedSourceContentSignature(localPath, ignoreResolution) {
278
+ if (ignoreResolution.kind === "failed") {
279
+ return `unreadable:${ignoreResolution.reason}`;
280
+ }
281
+ const isIgnoredByGitResolution = (relativePath) => ignoreResolution.kind === "git" &&
282
+ ignoreResolution.ignoredPaths.some((entry) => relativePath === entry || relativePath.startsWith(`${entry}/`));
283
+ const hash = createHash("sha256");
284
+ const walk = async (relative) => {
285
+ const current = relative ? path.join(localPath, relative) : localPath;
286
+ const dirents = await fs.readdir(current, { withFileTypes: true });
287
+ dirents.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
288
+ for (const dirent of dirents) {
289
+ const next = relative ? path.posix.join(relative, dirent.name) : dirent.name;
290
+ if (isIgnoredByGitResolution(next)) {
291
+ continue;
292
+ }
293
+ if (dirent.isDirectory()) {
294
+ if (REFERENCED_SOURCE_SIGNATURE_SKIP_DIRS.has(dirent.name)) {
295
+ continue;
296
+ }
297
+ await walk(next);
298
+ continue;
299
+ }
300
+ const absolute = path.join(localPath, next);
301
+ const stats = await fs.lstat(absolute);
302
+ if (stats.isSymbolicLink()) {
303
+ const target = await fs.readlink(absolute);
304
+ hash.update(`symlink:${next}:${target}\n`);
305
+ continue;
306
+ }
307
+ if (!stats.isFile()) {
308
+ hash.update(`other:${next}:${stats.mode}\n`);
309
+ continue;
310
+ }
311
+ hash.update(`file:${next}:${stats.size}\n`);
312
+ hash.update(await fs.readFile(absolute));
313
+ hash.update("\n");
314
+ }
315
+ };
316
+ try {
317
+ await walk("");
318
+ }
319
+ catch (error) {
320
+ return `unreadable:${String(error)}`;
321
+ }
322
+ return hash.digest("hex").slice(0, 16);
323
+ }
324
+ function defaultPaperclipInstanceDir() {
325
+ const home = process.env.PAPERCLIP_HOME?.trim() || resolveDefaultPaperclipHomeDir();
326
+ const instanceId = process.env.PAPERCLIP_INSTANCE_ID?.trim() || "default";
327
+ return resolvePaperclipInstanceRootForAdapter({
328
+ homeDir: home,
329
+ instanceId,
330
+ });
331
+ }
332
+ function defaultStateDir(companyId, agentId) {
333
+ return path.join(defaultPaperclipInstanceDir(), "companies", companyId, "acp-engine", "agents", agentId);
334
+ }
335
+ function resolveManagedCodexHomeDir(companyId) {
336
+ return path.join(defaultPaperclipInstanceDir(), "companies", companyId, "codex-home");
337
+ }
338
+ function isCodexCredentialStoreHome(homePath) {
339
+ const companiesRoot = path.resolve(defaultPaperclipInstanceDir(), "companies");
340
+ const resolved = path.resolve(homePath);
341
+ if (!resolved.startsWith(companiesRoot + path.sep))
342
+ return false;
343
+ const segments = resolved.slice(companiesRoot.length + 1).split(path.sep);
344
+ return segments.length >= 2 && segments[1] === "codex-auth-cache";
345
+ }
346
+ function resolveManagedCodexApiKeyHomeDir(companyId, agentId) {
347
+ return path.join(defaultStateDir(companyId, agentId), "codex-home");
348
+ }
349
+ function resolveManagedGrokHomeDir(companyId) {
350
+ return path.join(defaultPaperclipInstanceDir(), "companies", companyId, "grok-home");
351
+ }
352
+ // Walk up from startDir looking for `node_modules/.bin/<binName>`. This matches
353
+ // npm/pnpm binary hoisting in packaged installs while preserving monorepo dev.
354
+ export async function findAncestorBin(startDir, binName) {
355
+ let current = path.resolve(startDir);
356
+ while (true) {
357
+ const binDir = path.join(current, "node_modules", ".bin");
358
+ const candidates = process.platform === "win32"
359
+ ? [path.join(binDir, `${binName}.cmd`), path.join(binDir, binName)]
360
+ : [path.join(binDir, binName)];
361
+ for (const candidate of candidates) {
362
+ if (await pathExists(candidate))
363
+ return candidate;
364
+ }
365
+ const parent = path.dirname(current);
366
+ if (parent === current)
367
+ return null;
368
+ current = parent;
369
+ }
370
+ }
371
+ async function resolveBuiltInAgentCommand(input) {
372
+ const { agent, packageRootDir, executionTargetIsRemote } = input;
373
+ if (agent === "gemini") {
374
+ return { command: "gemini --acp", shellCommand: "gemini --acp" };
375
+ }
376
+ if (agent === "kimi") {
377
+ // Kimi Code exposes its ACP server via the `kimi acp` subcommand (stdio),
378
+ // rather than a flag (gemini) or a dedicated bin (claude/codex).
379
+ return { command: "kimi acp", shellCommand: "kimi acp" };
380
+ }
381
+ const binName = agent === "claude" ? "claude-agent-acp" : agent === "codex" ? "codex-acp" : null;
382
+ if (!binName)
383
+ return null;
384
+ if (executionTargetIsRemote) {
385
+ return { command: binName, shellCommand: binName };
386
+ }
387
+ const resolved = (await findAncestorBin(packageRootDir, binName)) ?? binName;
388
+ return { command: resolved, shellCommand: shellQuote(resolved) };
389
+ }
390
+ const execFileAsync = promisify(execFile);
391
+ // Gemini CLI renamed --experimental-acp to --acp in 0.33.0. acpx normally
392
+ // rewrites the flag itself, but the agent wrapper script hides the gemini
393
+ // command from acpx's detection, so the engine must downgrade it here.
394
+ const GEMINI_NATIVE_ACP_FLAG_MIN_VERSION = [0, 33, 0];
395
+ const GEMINI_VERSION_PROBE_TIMEOUT_MS = 2000;
396
+ export function parseGeminiVersionParts(output) {
397
+ const match = output?.match(/(\d+)\.(\d+)\.(\d+)/);
398
+ if (!match)
399
+ return null;
400
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
401
+ }
402
+ export function geminiVersionSupportsNativeAcpFlag(parts) {
403
+ if (!parts)
404
+ return true;
405
+ for (let index = 0; index < GEMINI_NATIVE_ACP_FLAG_MIN_VERSION.length; index += 1) {
406
+ const diff = (parts[index] ?? 0) - GEMINI_NATIVE_ACP_FLAG_MIN_VERSION[index];
407
+ if (diff !== 0)
408
+ return diff > 0;
409
+ }
410
+ return true;
411
+ }
412
+ export function rewriteGeminiAcpFlagForVersion(commandShell, versionParts) {
413
+ if (geminiVersionSupportsNativeAcpFlag(versionParts))
414
+ return commandShell;
415
+ return commandShell
416
+ .trim()
417
+ .split(/\s+/)
418
+ .map((token) => (token === "--acp" ? "--experimental-acp" : token))
419
+ .join(" ");
420
+ }
421
+ function geminiAcpCommandTokens(commandShell) {
422
+ const tokens = commandShell.trim().split(/\s+/);
423
+ const bin = tokens[0];
424
+ if (!bin || bin.startsWith("'") || bin.startsWith('"'))
425
+ return null;
426
+ if (path.basename(bin) !== "gemini")
427
+ return null;
428
+ if (!tokens.includes("--acp"))
429
+ return null;
430
+ return tokens;
431
+ }
432
+ async function normalizeGeminiAcpCommandShell(commandShell, env) {
433
+ const tokens = geminiAcpCommandTokens(commandShell);
434
+ if (!tokens)
435
+ return commandShell;
436
+ let versionParts = null;
437
+ try {
438
+ const { stdout } = await execFileAsync(tokens[0], ["--version"], {
439
+ timeout: GEMINI_VERSION_PROBE_TIMEOUT_MS,
440
+ encoding: "utf8",
441
+ env,
442
+ });
443
+ versionParts = parseGeminiVersionParts(stdout);
444
+ }
445
+ catch {
446
+ return commandShell;
447
+ }
448
+ return rewriteGeminiAcpFlagForVersion(commandShell, versionParts);
449
+ }
450
+ function normalizeAgent(config) {
451
+ const agent = asString(config.agent, DEFAULT_ACP_ENGINE_AGENT).trim();
452
+ return agent || DEFAULT_ACP_ENGINE_AGENT;
453
+ }
454
+ async function pathExists(candidate) {
455
+ return fs.access(candidate).then(() => true).catch(() => false);
456
+ }
457
+ async function ensureParentDir(target) {
458
+ await fs.mkdir(path.dirname(target), { recursive: true });
459
+ }
460
+ async function writeFileAtomically(input) {
461
+ await ensureParentDir(input.target);
462
+ const tempPath = `${input.target}.tmp-${process.pid}-${randomUUID()}`;
463
+ const handle = await fs.open(tempPath, "wx", input.mode);
464
+ try {
465
+ await handle.writeFile(input.contents, "utf8");
466
+ await handle.close();
467
+ await fs.rename(tempPath, input.target);
468
+ await fs.chmod(input.target, input.mode).catch(() => { });
469
+ }
470
+ catch (err) {
471
+ await handle.close().catch(() => { });
472
+ await fs.rm(tempPath, { force: true }).catch(() => { });
473
+ throw err;
474
+ }
475
+ }
476
+ async function ensureSymlink(target, source) {
477
+ const resolvedSource = path.resolve(source);
478
+ const existing = await fs.lstat(target).catch(() => null);
479
+ if (!existing) {
480
+ await ensureParentDir(target);
481
+ await symlinkOrCopyFile(resolvedSource, target);
482
+ return;
483
+ }
484
+ if (!existing.isSymbolicLink()) {
485
+ await fs.rm(target, { recursive: true, force: true });
486
+ await symlinkOrCopyFile(resolvedSource, target);
487
+ return;
488
+ }
489
+ const linkedPath = await fs.readlink(target).catch(() => null);
490
+ if (!linkedPath)
491
+ return;
492
+ const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
493
+ if (resolvedLinkedPath === resolvedSource)
494
+ return;
495
+ await fs.unlink(target);
496
+ await symlinkOrCopyFile(resolvedSource, target);
497
+ }
498
+ async function symlinkOrCopyFile(source, target) {
499
+ try {
500
+ await fs.symlink(source, target);
501
+ }
502
+ catch (err) {
503
+ if (!isErrnoException(err, "EPERM"))
504
+ throw err;
505
+ await fs.copyFile(source, target);
506
+ }
507
+ }
508
+ function isErrnoException(err, code) {
509
+ return err instanceof Error && "code" in err && err.code === code;
510
+ }
511
+ async function ensureCopiedFile(target, source) {
512
+ if (await pathExists(target))
513
+ return;
514
+ await ensureParentDir(target);
515
+ await fs.copyFile(source, target);
516
+ }
517
+ async function prepareManagedCodexHome(input) {
518
+ const { sourceHome, targetHome, apiKey, onLog } = input;
519
+ if (path.resolve(sourceHome) === path.resolve(targetHome))
520
+ return targetHome;
521
+ await fs.mkdir(targetHome, { recursive: true });
522
+ const targetAuth = path.join(targetHome, "auth.json");
523
+ if (apiKey && isCodexCredentialStoreHome(targetHome)) {
524
+ await onLog("stdout", `[paperclip] Refusing to write an API-key auth.json into credential-store entry "${targetHome}"; the bound account's stored login stays authoritative.\n`);
525
+ }
526
+ else if (apiKey) {
527
+ await writeFileAtomically({
528
+ target: targetAuth,
529
+ contents: JSON.stringify({ OPENAI_API_KEY: apiKey }),
530
+ mode: 0o600,
531
+ });
532
+ }
533
+ else {
534
+ const sourceAuth = path.join(sourceHome, "auth.json");
535
+ if (await pathExists(sourceAuth))
536
+ await ensureSymlink(targetAuth, sourceAuth);
537
+ }
538
+ for (const name of ["config.json", "config.toml", "instructions.md"]) {
539
+ const source = path.join(sourceHome, name);
540
+ if (await pathExists(source))
541
+ await ensureCopiedFile(path.join(targetHome, name), source);
542
+ }
543
+ await onLog("stdout", `[paperclip] Using Paperclip-managed ACPX Codex home "${targetHome}" (seeded from "${sourceHome}").\n`);
544
+ return targetHome;
545
+ }
546
+ async function hashPathContents(candidate, hash, relativePath, seenDirectories) {
547
+ const stat = await fs.lstat(candidate);
548
+ if (stat.isSymbolicLink()) {
549
+ hash.update(`symlink-skipped:${relativePath}\n`);
550
+ return;
551
+ }
552
+ if (stat.isDirectory()) {
553
+ const realDir = await fs.realpath(candidate).catch(() => candidate);
554
+ hash.update(`dir:${relativePath}\n`);
555
+ if (seenDirectories.has(realDir)) {
556
+ hash.update("loop\n");
557
+ return;
558
+ }
559
+ seenDirectories.add(realDir);
560
+ const entries = await fs.readdir(candidate, { withFileTypes: true });
561
+ entries.sort((left, right) => left.name.localeCompare(right.name));
562
+ for (const entry of entries) {
563
+ const childRelativePath = relativePath.length > 0 ? `${relativePath}/${entry.name}` : entry.name;
564
+ await hashPathContents(path.join(candidate, entry.name), hash, childRelativePath, seenDirectories);
565
+ }
566
+ return;
567
+ }
568
+ if (stat.isFile()) {
569
+ hash.update(`file:${relativePath}\n`);
570
+ hash.update(await fs.readFile(candidate));
571
+ hash.update("\n");
572
+ return;
573
+ }
574
+ hash.update(`other:${relativePath}:${stat.mode}\n`);
575
+ }
576
+ async function buildSkillSetKey(input) {
577
+ const hash = createHash("sha256");
578
+ hash.update(`paperclip-acpx-${input.label}-skills:v1\n`);
579
+ const sorted = [...input.skills].sort((left, right) => left.runtimeName.localeCompare(right.runtimeName));
580
+ for (const entry of sorted) {
581
+ hash.update(`skill:${entry.key}:${entry.runtimeName}\n`);
582
+ await hashPathContents(entry.source, hash, entry.runtimeName, new Set());
583
+ }
584
+ return hash.digest("hex");
585
+ }
586
+ async function resolveSelectedRuntimeSkills(config, moduleDir) {
587
+ const allSkills = await readPaperclipRuntimeSkillEntries(config, moduleDir);
588
+ const desiredSkillNames = resolveLegacyPaperclipDesiredSkillNames(config, allSkills);
589
+ const desiredSet = new Set(desiredSkillNames);
590
+ return {
591
+ allSkills,
592
+ // Missing-source entries never mount: buildSkillSetKey hashes each
593
+ // selected entry's path contents, and a nonexistent source would abort
594
+ // runtime construction over one broken skill.
595
+ selectedSkills: allSkills.filter((entry) => desiredSet.has(entry.key) && !isPaperclipSkillSourceMissing(entry)),
596
+ desiredSkillNames,
597
+ };
598
+ }
599
+ async function prepareClaudeSkillRuntime(input) {
600
+ const { allSkills, selectedSkills, desiredSkillNames } = await resolveSelectedRuntimeSkills(input.config, input.moduleDir);
601
+ const skillSetKey = await buildSkillSetKey({ skills: selectedSkills, label: "claude" });
602
+ const bundleRoot = path.join(input.stateDir, "runtime-skills", "claude", skillSetKey);
603
+ const skillsHome = path.join(bundleRoot, ".claude", "skills");
604
+ await fs.mkdir(skillsHome, { recursive: true });
605
+ // A failed materialization, or a materialized copy with no usable
606
+ // `SKILL.md`, must drop the skill from every advertised list below.
607
+ // Otherwise the prompt and the session identity still name a skill whose
608
+ // `SKILL.md` is not in `skillsHome` — either the whole copy failed, or the
609
+ // copy skipped a symlinked `SKILL.md` — and the agent's read of that file
610
+ // fails with a missing-file error, the same symptom this bundle exists to
611
+ // fix.
612
+ const materializedNames = [];
613
+ for (const entry of selectedSkills) {
614
+ const target = path.join(skillsHome, entry.runtimeName);
615
+ try {
616
+ const result = await materializePaperclipSkillCopy(entry.source, target);
617
+ const skillMdStat = await fs.stat(path.join(target, "SKILL.md")).catch(() => null);
618
+ if (!skillMdStat?.isFile()) {
619
+ await fs.rm(target, { recursive: true, force: true });
620
+ await input.onLog("stderr", `[paperclip] Skipped ACPX Claude skill "${entry.key}": the staged copy at ${target} has no usable SKILL.md.\n`);
621
+ continue;
622
+ }
623
+ materializedNames.push(entry.runtimeName);
624
+ if (result.skippedSymlinks.length > 0) {
625
+ await input.onLog("stdout", `[paperclip] Materialized ACPX Claude skill "${entry.runtimeName}" into ${skillsHome} and skipped ${result.skippedSymlinks.length} symlink(s).\n`);
626
+ }
627
+ }
628
+ catch (err) {
629
+ await input.onLog("stderr", `[paperclip] Failed to materialize ACPX Claude skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`);
630
+ }
631
+ }
632
+ const selectedNames = materializedNames.sort();
633
+ const skillDescriptions = await Promise.all(selectedNames.map(async (name) => {
634
+ const file = path.join(skillsHome, name, "SKILL.md");
635
+ let description = "";
636
+ try {
637
+ const parsed = parseFrontmatterMarkdown(await fs.readFile(file, "utf8"));
638
+ description = asString(parsed.frontmatter.description, "").replace(/\s+/g, " ").trim().slice(0, 512);
639
+ }
640
+ catch {
641
+ // A readable skill without valid routing metadata remains available.
642
+ // Do not substitute its body for a missing description.
643
+ }
644
+ return `- ${name}${description ? `: ${description}` : ""} (file: ${file})`;
645
+ }));
646
+ const promptInstructions = selectedNames.length > 0
647
+ ? [
648
+ "Paperclip has materialized selected runtime skills for this ACPX Claude session.",
649
+ `Skill root: ${skillsHome}`,
650
+ `Selected skills: ${selectedNames.join(", ")}`,
651
+ ...skillDescriptions,
652
+ "When a task calls for one of these skills, read its SKILL.md from that root and follow it.",
653
+ ].join("\n")
654
+ : "";
655
+ return {
656
+ identity: {
657
+ mode: "claude",
658
+ skillSetKey,
659
+ desiredSkillNames,
660
+ selectedSkills: selectedNames,
661
+ skillRoot: selectedNames.length > 0 ? skillsHome : null,
662
+ },
663
+ promptInstructions,
664
+ commandNotes: selectedNames.length > 0
665
+ ? [`Materialized ${selectedNames.length} Paperclip skill(s) for ACPX Claude at ${skillsHome}.`]
666
+ : [],
667
+ bundleDir: selectedNames.length > 0 ? skillsHome : null,
668
+ };
669
+ }
670
+ async function readManagedCodexSkillsManifest(skillsHome) {
671
+ const manifestPath = path.join(skillsHome, PAPERCLIP_MANAGED_CODEX_SKILLS_MANIFEST);
672
+ try {
673
+ const raw = JSON.parse(await fs.readFile(manifestPath, "utf8"));
674
+ const parsed = parseObject(raw);
675
+ const skills = Array.isArray(parsed.managedSkillNames)
676
+ ? parsed.managedSkillNames.filter((value) => typeof value === "string" && value.trim().length > 0)
677
+ : [];
678
+ return new Set(skills);
679
+ }
680
+ catch {
681
+ return new Set();
682
+ }
683
+ }
684
+ async function writeManagedCodexSkillsManifest(skillsHome, skillNames) {
685
+ const managedSkillNames = Array.from(new Set(skillNames)).sort();
686
+ await fs.writeFile(path.join(skillsHome, PAPERCLIP_MANAGED_CODEX_SKILLS_MANIFEST), `${JSON.stringify({ version: 1, managedSkillNames }, null, 2)}\n`, "utf8");
687
+ }
688
+ async function removeSkillTarget(target) {
689
+ const existing = await fs.lstat(target).catch(() => null);
690
+ if (!existing)
691
+ return false;
692
+ await fs.rm(target, { recursive: true, force: true });
693
+ return true;
694
+ }
695
+ async function reconcileManagedCodexSkills(input) {
696
+ const desired = new Set(input.selectedSkills.map((entry) => entry.runtimeName));
697
+ const managed = await readManagedCodexSkillsManifest(input.skillsHome);
698
+ const availableByRuntimeName = new Map(input.allSkills.map((entry) => [entry.runtimeName, entry]));
699
+ for (const name of managed) {
700
+ if (desired.has(name))
701
+ continue;
702
+ if (await removeSkillTarget(path.join(input.skillsHome, name))) {
703
+ await input.onLog("stdout", `[paperclip] Revoked ACPX Codex skill "${name}" from ${input.skillsHome}\n`);
704
+ }
705
+ }
706
+ for (const entry of input.allSkills) {
707
+ if (desired.has(entry.runtimeName) || managed.has(entry.runtimeName))
708
+ continue;
709
+ const target = path.join(input.skillsHome, entry.runtimeName);
710
+ const existing = await fs.lstat(target).catch(() => null);
711
+ if (!existing?.isSymbolicLink())
712
+ continue;
713
+ const linkedPath = await fs.readlink(target).catch(() => null);
714
+ if (!linkedPath)
715
+ continue;
716
+ const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
717
+ if (resolvedLinkedPath !== path.resolve(entry.source))
718
+ continue;
719
+ if (await removeSkillTarget(target)) {
720
+ await input.onLog("stdout", `[paperclip] Revoked legacy ACPX Codex skill "${entry.runtimeName}" from ${input.skillsHome}\n`);
721
+ }
722
+ }
723
+ for (const name of managed) {
724
+ if (desired.has(name) || availableByRuntimeName.has(name))
725
+ continue;
726
+ if (await removeSkillTarget(path.join(input.skillsHome, name))) {
727
+ await input.onLog("stdout", `[paperclip] Revoked unavailable ACPX Codex skill "${name}" from ${input.skillsHome}\n`);
728
+ }
729
+ }
730
+ }
731
+ async function prepareCodexSkillRuntime(input) {
732
+ const now = input.now ?? (() => Date.now());
733
+ const envConfig = parseObject(input.config.env);
734
+ const configuredCodexHome = typeof envConfig.CODEX_HOME === "string" && envConfig.CODEX_HOME.trim().length > 0
735
+ ? path.resolve(envConfig.CODEX_HOME.trim())
736
+ : null;
737
+ const sourceCodexHome = typeof process.env.CODEX_HOME === "string" && process.env.CODEX_HOME.trim().length > 0
738
+ ? path.resolve(process.env.CODEX_HOME.trim())
739
+ : path.join(os.homedir(), ".codex");
740
+ const hostApiKey = input.executionTargetIsRemote
741
+ ? undefined
742
+ : process.env.OPENAI_API_KEY?.trim() || process.env.CODEX_API_KEY?.trim();
743
+ const apiKey = input.env.OPENAI_API_KEY?.trim() || input.env.CODEX_API_KEY?.trim()
744
+ || hostApiKey;
745
+ // Keep API-key auth separate from the company home used by subscription
746
+ // agents, so one agent cannot switch another agent's login on its next turn.
747
+ const managedCodexHome = apiKey
748
+ ? resolveManagedCodexApiKeyHomeDir(input.companyId, input.agentId)
749
+ : resolveManagedCodexHomeDir(input.companyId);
750
+ const effectiveCodexHome = configuredCodexHome ??
751
+ await prepareManagedCodexHome({
752
+ companyId: input.companyId,
753
+ sourceHome: sourceCodexHome,
754
+ targetHome: managedCodexHome,
755
+ apiKey,
756
+ onLog: input.onLog,
757
+ });
758
+ const { allSkills, selectedSkills, desiredSkillNames } = await resolveSelectedRuntimeSkills(input.config, input.moduleDir);
759
+ const skillSetKey = await buildSkillSetKey({ skills: selectedSkills, label: "codex" });
760
+ const skillsHome = path.join(effectiveCodexHome, "skills");
761
+ await fs.mkdir(skillsHome, { recursive: true });
762
+ // Step 3 — skills.reconcile: nested inside the codex-home seed (step 2), so it
763
+ // emits its own boundary event and span at this call-site. It must NOT add its
764
+ // wall time to the root work sum. The enclosing step 2 wall already covers this
765
+ // interval, so a second `onWallMs` call would count the same milliseconds
766
+ // twice. Drop `onWallMs` for the nested step; keep every other attribution
767
+ // field.
768
+ const nestedStepMetrics = {
769
+ ...(input.stepMetrics ?? {}),
770
+ onWallMs: undefined,
771
+ };
772
+ await measureStartupStep({ onEvent: input.onEvent }, now, "skills.reconcile", () => reconcileManagedCodexSkills({
773
+ skillsHome,
774
+ allSkills,
775
+ selectedSkills,
776
+ onLog: input.onLog,
777
+ }), nestedStepMetrics);
778
+ for (const entry of selectedSkills) {
779
+ const target = path.join(skillsHome, entry.runtimeName);
780
+ try {
781
+ const result = await materializePaperclipSkillCopy(entry.source, target);
782
+ if (result.skippedSymlinks.length > 0) {
783
+ await input.onLog("stdout", `[paperclip] Materialized ACPX Codex skill "${entry.runtimeName}" into ${skillsHome} and skipped ${result.skippedSymlinks.length} symlink(s).\n`);
784
+ }
785
+ }
786
+ catch (err) {
787
+ await input.onLog("stderr", `[paperclip] Failed to inject ACPX Codex skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`);
788
+ }
789
+ }
790
+ await writeManagedCodexSkillsManifest(skillsHome, selectedSkills.map((entry) => entry.runtimeName));
791
+ input.env.CODEX_HOME = effectiveCodexHome;
792
+ return {
793
+ identity: {
794
+ mode: "codex",
795
+ skillSetKey,
796
+ desiredSkillNames,
797
+ selectedSkills: selectedSkills.map((entry) => entry.runtimeName).sort(),
798
+ codexHome: effectiveCodexHome,
799
+ skillsHome,
800
+ },
801
+ commandNotes: [`Prepared ACPX Codex skill home at ${skillsHome}.`],
802
+ };
803
+ }
804
+ function resolveGeminiSkillsHome(config) {
805
+ const envConfig = parseObject(config.env);
806
+ const configuredHome = typeof envConfig.HOME === "string" && envConfig.HOME.trim().length > 0
807
+ ? path.resolve(envConfig.HOME.trim())
808
+ : os.homedir();
809
+ return path.join(configuredHome, ".gemini", "skills");
810
+ }
811
+ async function prepareGeminiSkillRuntime(input) {
812
+ const { selectedSkills, desiredSkillNames } = await resolveSelectedRuntimeSkills(input.config, input.moduleDir);
813
+ const skillSetKey = await buildSkillSetKey({ skills: selectedSkills, label: "gemini" });
814
+ const skillsHome = resolveGeminiSkillsHome(input.config);
815
+ await fs.mkdir(skillsHome, { recursive: true });
816
+ const allowedSkillNames = selectedSkills.map((entry) => entry.runtimeName);
817
+ const removedSkills = await removeMaintainerOnlySkillSymlinks(skillsHome, allowedSkillNames);
818
+ for (const skillName of removedSkills) {
819
+ await input.onLog("stdout", `[paperclip] Removed maintainer-only ACPX Gemini skill "${skillName}" from ${skillsHome}\n`);
820
+ }
821
+ for (const entry of selectedSkills) {
822
+ const target = path.join(skillsHome, entry.runtimeName);
823
+ try {
824
+ const result = await ensurePaperclipSkillSymlink(entry.source, target);
825
+ if (result === "created" || result === "repaired") {
826
+ await input.onLog("stdout", `[paperclip] ${result === "repaired" ? "Repaired" : "Linked"} ACPX Gemini skill "${entry.runtimeName}" into ${skillsHome}\n`);
827
+ }
828
+ }
829
+ catch (err) {
830
+ if (isErrnoException(err, "EPERM")) {
831
+ const result = await materializePaperclipSkillCopy(entry.source, target);
832
+ await input.onLog("stdout", `[paperclip] Copied ACPX Gemini skill "${entry.runtimeName}" into ${skillsHome} because symlinks are unavailable.${result.skippedSymlinks.length > 0 ? ` Skipped ${result.skippedSymlinks.length} nested symlink(s).` : ""}\n`);
833
+ continue;
834
+ }
835
+ await input.onLog("stderr", `[paperclip] Failed to link ACPX Gemini skill "${entry.key}" into ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`);
836
+ }
837
+ }
838
+ return {
839
+ identity: {
840
+ mode: "gemini",
841
+ skillSetKey,
842
+ desiredSkillNames,
843
+ selectedSkills: selectedSkills.map((entry) => entry.runtimeName).sort(),
844
+ skillsHome,
845
+ },
846
+ commandNotes: selectedSkills.length > 0
847
+ ? [`Prepared ${selectedSkills.length} ACPX Gemini skill(s) at ${skillsHome}.`]
848
+ : [],
849
+ };
850
+ }
851
+ function normalizeMode(config) {
852
+ return asString(config.mode, DEFAULT_ACP_ENGINE_MODE) === "oneshot" ? "oneshot" : "persistent";
853
+ }
854
+ function normalizePermissionMode(config) {
855
+ const value = asString(config.permissionMode, DEFAULT_ACP_ENGINE_PERMISSION_MODE).trim();
856
+ if (value === "approve-reads" || value === "deny-all")
857
+ return value;
858
+ if (value === "default")
859
+ return DEFAULT_ACP_ENGINE_PERMISSION_MODE;
860
+ return "approve-all";
861
+ }
862
+ const READ_ONLY_ACP_DENIED_KINDS = new Set(["edit", "delete", "move"]);
863
+ const READ_ONLY_CODEX_ALLOWED_KINDS = new Set(["read", "search", "fetch", "think"]);
864
+ const READ_ONLY_CLAUDE_DENIED_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
865
+ const READ_ONLY_ACP_SESSION_MODES = { claude: "default", codex: "read-only" };
866
+ export function readOnlyAcpPermissionDecision(acpxAgent, request) {
867
+ const toolCall = request.raw.toolCall;
868
+ const kind = request.inferredKind ?? toolCall.kind ?? undefined;
869
+ if (kind && READ_ONLY_ACP_DENIED_KINDS.has(kind))
870
+ return { outcome: "reject_once" };
871
+ if (typeof toolCall.name === "string" && READ_ONLY_CLAUDE_DENIED_TOOLS.has(toolCall.name)) {
872
+ return { outcome: "reject_once" };
873
+ }
874
+ if (acpxAgent !== "codex" || (kind && READ_ONLY_CODEX_ALLOWED_KINDS.has(kind)))
875
+ return undefined;
876
+ const meta = request.raw._meta;
877
+ return meta?.is_mcp_tool_approval === true ? undefined : { outcome: "reject_once" };
878
+ }
879
+ async function applyReadOnlySessionMode(input) {
880
+ if (input.prepared.toolProfile !== "read_only")
881
+ return;
882
+ const mode = READ_ONLY_ACP_SESSION_MODES[input.prepared.acpxAgent];
883
+ if (!mode)
884
+ return;
885
+ if (!input.runtime.setMode) {
886
+ const message = "ACPX runtime does not expose session mode controls, so the read_only tool profile cannot be applied.";
887
+ await input.onLog("stderr", `[paperclip] ${message}\n`);
888
+ throw new Error(message);
889
+ }
890
+ await input.runtime.setMode({ handle: input.handle, mode });
891
+ await input.onLog("stdout", `[paperclip] Applied read_only tool profile: ACPX ${input.prepared.acpxAgent} session mode ${mode}\n`);
892
+ }
893
+ function normalizeNonInteractivePermissions(config) {
894
+ return asString(config.nonInteractivePermissions, DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS) === "fail"
895
+ ? "fail"
896
+ : "deny";
897
+ }
898
+ function normalizeRequestedThinkingEffort(config) {
899
+ return (asString(config.modelReasoningEffort, "") ||
900
+ asString(config.reasoningEffort, "") ||
901
+ asString(config.thinkingEffort, "") ||
902
+ asString(config.effort, "")).trim();
903
+ }
904
+ function buildCodexStartupConfig(input) {
905
+ const hasRuntimeConfig = Boolean(input.requestedModel || input.requestedThinkingEffort || input.fastMode || input.identityEnvironmentKeys);
906
+ if (!hasRuntimeConfig)
907
+ return { value: null, invalidExistingConfig: false };
908
+ let existing = {};
909
+ let invalidExistingConfig = false;
910
+ if (input.existingConfig) {
911
+ try {
912
+ existing = parseObject(JSON.parse(input.existingConfig));
913
+ }
914
+ catch {
915
+ invalidExistingConfig = true;
916
+ existing = {};
917
+ }
918
+ }
919
+ return {
920
+ value: JSON.stringify({
921
+ ...existing,
922
+ ...(input.requestedModel ? { model: input.requestedModel } : {}),
923
+ ...(input.requestedThinkingEffort
924
+ ? { model_reasoning_effort: input.requestedThinkingEffort }
925
+ : {}),
926
+ ...(input.fastMode
927
+ ? {
928
+ service_tier: "fast",
929
+ features: {
930
+ ...parseObject(existing.features),
931
+ fast_mode: true,
932
+ },
933
+ }
934
+ : {}),
935
+ ...(input.identityEnvironmentKeys ? {
936
+ features: { ...parseObject(existing.features), ...(input.fastMode ? { fast_mode: true } : {}), shell_snapshot: false },
937
+ shell_environment_policy: { ...parseObject(existing.shell_environment_policy),
938
+ inherit: "all", ignore_default_excludes: true, include_only: input.identityEnvironmentKeys },
939
+ } : {}),
940
+ }),
941
+ invalidExistingConfig,
942
+ };
943
+ }
944
+ function isCompatibleSession(params, runtime) {
945
+ if (asString(params.configFingerprint, "") !== runtime.fingerprint)
946
+ return false;
947
+ if (asString(params.sessionKey, "") !== runtime.sessionKey)
948
+ return false;
949
+ if (asString(params.agent, "") !== runtime.acpxAgent)
950
+ return false;
951
+ if (asString(params.mode, "") !== runtime.mode)
952
+ return false;
953
+ const savedCwd = asString(params.cwd, "");
954
+ if (!savedCwd || path.resolve(savedCwd) !== path.resolve(runtime.cwd))
955
+ return false;
956
+ const savedRemote = parseObject(params.remoteExecution);
957
+ return stableJson(savedRemote) === stableJson(runtime.remoteExecutionIdentity ?? {});
958
+ }
959
+ function buildSessionParams(input) {
960
+ const { prepared, handle } = input;
961
+ return {
962
+ sessionKey: prepared.sessionKey,
963
+ runtimeSessionName: handle.runtimeSessionName,
964
+ acpxRecordId: handle.acpxRecordId,
965
+ acpSessionId: handle.backendSessionId,
966
+ agentSessionId: handle.agentSessionId,
967
+ agent: prepared.acpxAgent,
968
+ cwd: prepared.cwd,
969
+ mode: prepared.mode,
970
+ stateDir: prepared.stateDir,
971
+ configFingerprint: prepared.fingerprint,
972
+ mcpFingerprint: shortHash(prepared.mcpIdentity),
973
+ ...(prepared.requestedModel ? { model: prepared.requestedModel } : {}),
974
+ ...(prepared.requestedThinkingEffort ? { thinkingEffort: prepared.requestedThinkingEffort } : {}),
975
+ ...(prepared.fastMode ? { fastMode: true } : {}),
976
+ skills: prepared.skillsIdentity,
977
+ mcpServers: prepared.mcpIdentity,
978
+ ...(prepared.workspaceId ? { workspaceId: prepared.workspaceId } : {}),
979
+ ...(prepared.workspaceRepoUrl ? { repoUrl: prepared.workspaceRepoUrl } : {}),
980
+ ...(prepared.workspaceRepoRef ? { repoRef: prepared.workspaceRepoRef } : {}),
981
+ ...(prepared.remoteExecutionIdentity ? { remoteExecution: prepared.remoteExecutionIdentity } : {}),
982
+ };
983
+ }
984
+ function uniqueSorted(values) {
985
+ return [...new Set(values.filter((value) => typeof value === "string" && value.length > 0))].sort();
986
+ }
987
+ // The Claude Code SDK that `claude-agent-acp` runs uses
988
+ // `settingSources: ["user", "project", "local"]`. By writing a per-worktree
989
+ // `.claude/settings.local.json` we override the user's potentially-restrictive
990
+ // `~/.claude/settings.json` (e.g. `defaultMode: "dontAsk"`, which silently
991
+ // denies every non-allowlisted tool and never reaches `canUseTool`), and we
992
+ // widen the SDK's Read sandbox to include the Paperclip state dirs the agent
993
+ // needs to talk to its own control plane.
994
+ async function writePaperclipClaudeSettings(input) {
995
+ const filePath = path.join(input.cwd, ".claude", "settings.local.json");
996
+ const instanceRoot = defaultPaperclipInstanceDir();
997
+ const companyRoot = path.join(instanceRoot, "companies", input.companyId);
998
+ const paperclipAdditionalDirectories = uniqueSorted([
999
+ input.stateDir,
1000
+ input.agentHome,
1001
+ companyRoot,
1002
+ ]);
1003
+ const paperclipAllow = uniqueSorted([
1004
+ "Bash(curl:*)",
1005
+ "Bash(env:*)",
1006
+ "Bash(env)",
1007
+ `Bash(${input.cwd}/scripts/paperclip-issue-update.sh:*)`,
1008
+ `Bash(${input.cwd}/scripts/paperclip:*)`,
1009
+ ]);
1010
+ let existing = {};
1011
+ const existingRaw = await fs.readFile(filePath, "utf8").catch(() => null);
1012
+ if (existingRaw) {
1013
+ try {
1014
+ const parsed = JSON.parse(existingRaw);
1015
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
1016
+ existing = parsed;
1017
+ }
1018
+ catch {
1019
+ // Malformed settings file — leave it alone in `existing` and our merge will replace it with a valid one.
1020
+ }
1021
+ }
1022
+ const existingPerms = existing.permissions && typeof existing.permissions === "object" && !Array.isArray(existing.permissions)
1023
+ ? existing.permissions
1024
+ : {};
1025
+ const existingAllow = Array.isArray(existingPerms.allow)
1026
+ ? existingPerms.allow.filter((value) => typeof value === "string")
1027
+ : [];
1028
+ const existingAdditionalDirectories = Array.isArray(existingPerms.additionalDirectories)
1029
+ ? existingPerms.additionalDirectories.filter((value) => typeof value === "string")
1030
+ : [];
1031
+ const mergedAllow = uniqueSorted([...existingAllow, ...paperclipAllow]);
1032
+ const mergedAdditionalDirectories = uniqueSorted([
1033
+ ...existingAdditionalDirectories,
1034
+ ...paperclipAdditionalDirectories,
1035
+ ]);
1036
+ const existingDefaultMode = typeof existingPerms.defaultMode === "string" ? existingPerms.defaultMode : "";
1037
+ const defaultMode = existingDefaultMode && existingDefaultMode !== "dontAsk" ? existingDefaultMode : "default";
1038
+ const overrodeDontAsk = existingDefaultMode === "dontAsk";
1039
+ const nextPermissions = {
1040
+ ...existingPerms,
1041
+ allow: mergedAllow,
1042
+ additionalDirectories: mergedAdditionalDirectories,
1043
+ defaultMode,
1044
+ };
1045
+ const next = { ...existing, permissions: nextPermissions };
1046
+ await writeFileAtomically({
1047
+ target: filePath,
1048
+ contents: `${JSON.stringify(next, null, 2)}\n`,
1049
+ mode: 0o600,
1050
+ });
1051
+ return {
1052
+ filePath,
1053
+ allow: mergedAllow,
1054
+ additionalDirectories: mergedAdditionalDirectories,
1055
+ defaultMode,
1056
+ overrodeDontAsk,
1057
+ };
1058
+ }
1059
+ // Cross the CLI's staging seam for a runner-backed remote sandbox: ship the
1060
+ // workspace (and, in PR 2, the per-adapter managed-home `assets`) into the
1061
+ // sandbox and obtain the in-sandbox `workspaceRemoteDir` plus the non-null
1062
+ // `runtimeRootDir`/`assetDirs` the bridges and the home remap consume. This is
1063
+ // the shared-engine mirror of the CLI lanes (codex/claude/gemini
1064
+ // `*-local/execute.ts`). PR 1 shipped the workspace + cwd only; PR 2 threads
1065
+ // the home `assets` (built by the per-adapter `prepareRemoteManagedHome` seam,
1066
+ // carrying the codex `provision`/`restore` auth seams) through `assets` here so
1067
+ // `assetDirs.<key>` resolves to the seeded in-sandbox home. The returned
1068
+ // `restoreWorkspace` fires the per-asset `restore` (codex copy-back) at
1069
+ // teardown.
1070
+ async function stageAcpRemoteRuntime(input) {
1071
+ await input.onLog("stdout", `[paperclip] Syncing workspace to ${describeAdapterExecutionTarget(input.target)}.\n`);
1072
+ return await prepareAdapterExecutionTargetRuntime({
1073
+ runId: input.runId,
1074
+ target: input.target,
1075
+ adapterKey: input.adapterKey,
1076
+ timeoutSec: input.timeoutSec,
1077
+ workspaceLocalDir: input.workspaceLocalDir,
1078
+ ...(input.workspaceRemoteDir ? { workspaceRemoteDir: input.workspaceRemoteDir } : {}),
1079
+ ...(input.assets && input.assets.length > 0 ? { assets: input.assets } : {}),
1080
+ ...(input.additionalSources && input.additionalSources.length > 0
1081
+ ? { additionalSources: input.additionalSources }
1082
+ : {}),
1083
+ onProgress: (line) => input.onLog("stdout", line),
1084
+ onRuntimeProgress: input.onRuntimeProgress,
1085
+ runtimeSpan: input.runtimeSpan,
1086
+ });
1087
+ }
1088
+ // Dispose a freshly staged in-sandbox runtime after a managed-home seam threw. The
1089
+ // seam shipped the workspace/home into the sandbox through `stage()` but threw
1090
+ // before it could return its `disposeStaged`, so the engine removes the managed
1091
+ // runtime root here — otherwise the abandoned in-sandbox managed home (with its
1092
+ // staged credentials) leaks in a persistent sandbox. Fail-open: a cleanup miss on
1093
+ // an already-failing run is logged and never re-thrown, so it cannot mask the seam
1094
+ // error.
1095
+ async function disposeFreshStagedRuntime(input) {
1096
+ const runtimeRootDir = input.stagedRuntime.runtimeRootDir;
1097
+ if (!runtimeRootDir)
1098
+ return;
1099
+ try {
1100
+ await runAdapterExecutionTargetShellCommand(input.runId, input.target, `rm -rf ${shellQuote(runtimeRootDir)}`, {
1101
+ cwd: input.cwd,
1102
+ env: {},
1103
+ timeoutSec: Math.max(input.timeoutSec, 15),
1104
+ graceSec: 20,
1105
+ onLog: input.onLog,
1106
+ });
1107
+ }
1108
+ catch (err) {
1109
+ await input.onLog("stderr", `[paperclip] Failed to dispose the fresh staged runtime after a managed-home seam error: ${err instanceof Error ? err.message : String(err)}\n`);
1110
+ }
1111
+ }
1112
+ async function buildRuntime(input) {
1113
+ const { runId, agent, config, context, authToken } = input.ctx;
1114
+ // Injectable monotonic clock for per-step startup timing. Hoisted above the
1115
+ // first instrumented boundary (step 1 `workspace.resolve`, below) so every
1116
+ // `measureStartupStep` call in this function shares one deterministic clock.
1117
+ const nowMs = input.deps.now ?? (() => Date.now());
1118
+ const workspaceContext = parseObject(context.paperclipWorkspace);
1119
+ const secretsContext = parseObject(context.paperclipSecrets);
1120
+ const secretManifest = Array.isArray(secretsContext.manifest) ? secretsContext.manifest : [];
1121
+ const workspaceCwd = asString(workspaceContext.cwd, "");
1122
+ const workspaceSource = asString(workspaceContext.source, "");
1123
+ const workspaceStrategy = asString(workspaceContext.strategy, "");
1124
+ const workspaceId = asString(workspaceContext.workspaceId, "");
1125
+ const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
1126
+ const workspaceRepoRef = asString(workspaceContext.repoRef, "");
1127
+ const workspaceBranch = asString(workspaceContext.branchName, "");
1128
+ const workspaceWorktreePath = asString(workspaceContext.worktreePath, "");
1129
+ const agentHome = asString(workspaceContext.agentHome, "");
1130
+ const configuredCwd = asString(config.cwd, "");
1131
+ const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
1132
+ const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
1133
+ const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
1134
+ // Referenced (additional) projects to stage into the sandbox alongside the
1135
+ // anchor workspace, read from the workspace realization record. The list is
1136
+ // empty unless run prep resolved referenced projects — gated upstream by the
1137
+ // multi-project workspace-sync kill-switch — so the anchor-only path is
1138
+ // unchanged.
1139
+ const realizationContext = parseObject(workspaceContext.realization);
1140
+ const additionalSourceRecords = (Array.isArray(realizationContext.additional) ? realizationContext.additional : []).map((entry) => parseObject(entry));
1141
+ const additionalSourceCandidates = additionalSourceRecords
1142
+ .map((entry) => ({
1143
+ localPath: asString(entry.path, ""),
1144
+ projectId: asString(entry.projectId, ""),
1145
+ projectWorkspaceId: asString(entry.projectWorkspaceId, ""),
1146
+ repoUrl: asString(entry.repoUrl, ""),
1147
+ repoRef: asString(entry.repoRef, ""),
1148
+ }))
1149
+ .filter((entry) => entry.localPath.length > 0 && entry.projectId.length > 0);
1150
+ // Resolve each referenced project's Git-ignored paths ONCE, here, before any
1151
+ // staging site runs. The sandbox lane, the SSH lane, and the content signature
1152
+ // below all consume this SAME resolution per project, so they can never apply
1153
+ // a different exclusion set to the same project. See
1154
+ // `resolveReferencedSourceIgnore` for the fail-closed rules.
1155
+ const additionalSourcesWithIgnore = await Promise.all(additionalSourceCandidates.map(async (entry) => ({
1156
+ ...entry,
1157
+ ignoreResolution: await resolveReferencedSourceIgnore(entry.localPath),
1158
+ })));
1159
+ const additionalSources = additionalSourcesWithIgnore.map((entry) => ({
1160
+ localPath: entry.localPath,
1161
+ projectId: entry.projectId,
1162
+ ignoreResolution: entry.ignoreResolution,
1163
+ }));
1164
+ // Stable identity of the referenced-project set for the session fingerprint.
1165
+ // The staged-runtime cache reuses already-staged referenced-project trees on a
1166
+ // compatible resume, so the fingerprint must change when the set OR a project's
1167
+ // pinned checkout changes. Without this, a resume reuses a stale staged tree.
1168
+ // Fold in each project's id, host path, workspace id, and pinned ref; sort by
1169
+ // projectId so the identity depends on the set, not the record order.
1170
+ const additionalSourcesIdentityBase = additionalSourcesWithIgnore
1171
+ .map((entry) => ({
1172
+ projectId: entry.projectId,
1173
+ localPath: entry.localPath,
1174
+ projectWorkspaceId: entry.projectWorkspaceId,
1175
+ repoUrl: entry.repoUrl,
1176
+ repoRef: entry.repoRef,
1177
+ ignoreResolution: entry.ignoreResolution,
1178
+ }))
1179
+ .sort((a, b) => (a.projectId < b.projectId ? -1 : a.projectId > b.projectId ? 1 : 0));
1180
+ // Metadata alone does not change on a content-only checkout change (same host
1181
+ // path and pinned ref, new file bytes). Fold in each tree's content signature so
1182
+ // a file add, remove, or edit busts the fingerprint and the resume re-stages.
1183
+ // The signature reads the same `ignoreResolution` the staging sites above use,
1184
+ // so it never disagrees with what was actually shipped.
1185
+ const additionalSourcesIdentity = await Promise.all(additionalSourcesIdentityBase.map(async ({ ignoreResolution, ...entry }) => ({
1186
+ ...entry,
1187
+ contentSignature: await referencedSourceContentSignature(entry.localPath, ignoreResolution),
1188
+ })));
1189
+ // Referenced-project workspace hints exposed to the agent through PAPERCLIP_WORKSPACES_JSON. The
1190
+ // list joins the anchor project's alternative workspaces with the referenced (mentioned) projects.
1191
+ // On the confined sandbox lane the run repoints each referenced hint at its staged directory after
1192
+ // staging below. Empty unless run prep resolved referenced projects or alternative workspaces.
1193
+ const workspaceHints = Array.isArray(context.paperclipWorkspaces)
1194
+ ? context.paperclipWorkspaces.filter((value) => typeof value === "object" && value !== null)
1195
+ : [];
1196
+ const executionTarget = readAdapterExecutionTarget({
1197
+ executionTarget: input.ctx.executionTarget,
1198
+ legacyRemoteExecution: input.ctx.executionTransport?.remoteExecution,
1199
+ });
1200
+ const remoteExecutionIdentity = adapterExecutionTargetSessionIdentity(executionTarget);
1201
+ const effectiveExecutionCwd = remoteExecutionIdentity && typeof remoteExecutionIdentity.remoteCwd === "string"
1202
+ ? remoteExecutionIdentity.remoteCwd
1203
+ : cwd;
1204
+ const executionTargetIsRemote = remoteExecutionIdentity !== null;
1205
+ // Merge the injected tracer + root parent-context into every step option set,
1206
+ // so each boundary span parents to the root span. With no injected trace
1207
+ // context both fields are no-ops and the span path stays inert.
1208
+ const stepMetrics = {
1209
+ ...input.spanParent,
1210
+ };
1211
+ // The two bridge-start steps intentionally overlap. A shared `batch` tag marks
1212
+ // the two spans as one parallel batch, and `criticalPath: false` keeps their
1213
+ // inner exec spans off the critical path (their wall time overlaps).
1214
+ const concurrentBridgeStepMetrics = {
1215
+ ...input.spanParent,
1216
+ batch: STARTUP_BRIDGE_BATCH,
1217
+ criticalPath: false,
1218
+ };
1219
+ const shapedWorkspaceEnv = shapePaperclipWorkspaceEnvForExecution({
1220
+ workspaceCwd: effectiveWorkspaceCwd,
1221
+ workspaceWorktreePath,
1222
+ executionTargetIsRemote,
1223
+ executionCwd: effectiveExecutionCwd,
1224
+ });
1225
+ // Step 1 — workspace.resolve: the workspace resolution/fallback chain closes
1226
+ // here on the awaited directory materialization.
1227
+ await measureStartupStep(input.ctx, nowMs, "workspace.resolve", () => ensureAbsoluteDirectory(cwd, { createIfMissing: true }), stepMetrics);
1228
+ const acpxAgent = normalizeAgent(config);
1229
+ // Run summaries always fail closed to the final output segment so internal
1230
+ // thought text and intermediate narration cannot become issue comments.
1231
+ const coalescePlaceholderToolUpdates = config.coalescePlaceholderToolUpdates === true;
1232
+ const mode = normalizeMode(config);
1233
+ const permissionMode = normalizePermissionMode(config);
1234
+ const nonInteractivePermissions = normalizeNonInteractivePermissions(config);
1235
+ const toolProfile = runToolProfile(context);
1236
+ const requestedModel = asString(config.model, "").trim();
1237
+ const requestedThinkingEffort = normalizeRequestedThinkingEffort(config);
1238
+ const fastMode = acpxAgent === "codex" && config.fastMode === true;
1239
+ const runtimeMcpServers = input.ctx.runtimeMcp?.getServers() ?? [];
1240
+ const mcpIdentity = runtimeMcpServers.map(({ name, url, connectionId }) => ({
1241
+ name,
1242
+ url,
1243
+ connectionId,
1244
+ }));
1245
+ const mcpServers = runtimeMcpServers.map((server) => ({
1246
+ type: "http",
1247
+ name: server.name,
1248
+ url: server.url,
1249
+ headers: [{ name: "Authorization", value: `Bearer ${server.token}` }],
1250
+ }));
1251
+ const paperclipEnvForAccess = {
1252
+ ...buildPaperclipEnv(agent, { sameHost: !executionTargetIsRemote }),
1253
+ PAPERCLIP_RUN_ID: runId,
1254
+ ...(authToken ? { PAPERCLIP_API_KEY: authToken } : {}),
1255
+ };
1256
+ const paperclipAccess = paperclipAccessMode(config, paperclipEnvForAccess);
1257
+ const paperclipToolsets = paperclipMcpToolsets(config);
1258
+ if (paperclipAccess === "mcp") {
1259
+ const target = paperclipMcpHttpTarget({
1260
+ env: paperclipEnvForAccess,
1261
+ toolsets: paperclipToolsets,
1262
+ });
1263
+ mcpServers.unshift({
1264
+ type: "http",
1265
+ name: PAPERCLIP_MCP_SERVER_NAME,
1266
+ url: target.url,
1267
+ headers: Object.entries(target.headers).map(([name, value]) => ({ name, value })),
1268
+ });
1269
+ }
1270
+ // Resolve the wall-clock timeout through the shared execution-target
1271
+ // resolver so sandbox-backed runs pick up the 4h backstop default while
1272
+ // local/SSH runs keep the historical "0 = no adapter timeout" behavior.
1273
+ const timeoutResolution = resolveAdapterExecutionTargetTimeout(executionTarget, asNumber(config.timeoutSec, DEFAULT_ACP_ENGINE_TIMEOUT_SEC));
1274
+ const timeoutSec = timeoutResolution.timeoutSec;
1275
+ const stateDir = path.resolve(asString(config.stateDir, "") || defaultStateDir(agent.companyId, agent.id));
1276
+ await fs.mkdir(stateDir, { recursive: true });
1277
+ const envConfig = parseObject(config.env);
1278
+ const env = {
1279
+ ...buildPaperclipEnv(agent, { sameHost: !executionTargetIsRemote }, input.ctx.agentIdentity),
1280
+ PAPERCLIP_RUN_ID: runId,
1281
+ };
1282
+ const wakeTaskId = (typeof context.taskId === "string" && context.taskId.trim()) ||
1283
+ (typeof context.issueId === "string" && context.issueId.trim()) ||
1284
+ "";
1285
+ const wakeReason = typeof context.wakeReason === "string" ? context.wakeReason.trim() : "";
1286
+ const wakeCommentId = (typeof context.wakeCommentId === "string" && context.wakeCommentId.trim()) ||
1287
+ (typeof context.commentId === "string" && context.commentId.trim()) ||
1288
+ "";
1289
+ const approvalId = typeof context.approvalId === "string" ? context.approvalId.trim() : "";
1290
+ const approvalStatus = typeof context.approvalStatus === "string" ? context.approvalStatus.trim() : "";
1291
+ const linkedIssueIds = Array.isArray(context.issueIds)
1292
+ ? context.issueIds.filter((value) => typeof value === "string" && value.trim().length > 0)
1293
+ : [];
1294
+ const issueWorkMode = readPaperclipIssueWorkModeFromContext(context);
1295
+ if (wakeTaskId)
1296
+ env.PAPERCLIP_TASK_ID = wakeTaskId;
1297
+ if (issueWorkMode)
1298
+ env.PAPERCLIP_ISSUE_WORK_MODE = issueWorkMode;
1299
+ if (wakeReason)
1300
+ env.PAPERCLIP_WAKE_REASON = wakeReason;
1301
+ if (wakeCommentId)
1302
+ env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
1303
+ if (approvalId)
1304
+ env.PAPERCLIP_APPROVAL_ID = approvalId;
1305
+ if (approvalStatus)
1306
+ env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
1307
+ if (linkedIssueIds.length > 0)
1308
+ env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
1309
+ applyPaperclipWorkspaceEnv(env, {
1310
+ workspaceCwd: shapedWorkspaceEnv.workspaceCwd,
1311
+ workspaceSource,
1312
+ workspaceStrategy,
1313
+ workspaceId,
1314
+ workspaceRepoUrl,
1315
+ workspaceRepoRef,
1316
+ workspaceBranch,
1317
+ workspaceWorktreePath: shapedWorkspaceEnv.workspaceWorktreePath,
1318
+ agentHome,
1319
+ });
1320
+ const shapedEnvConfig = rewriteWorkspaceCwdEnvVarsForExecution({
1321
+ env: envConfig,
1322
+ workspaceCwd: effectiveWorkspaceCwd,
1323
+ executionCwd: shapedWorkspaceEnv.workspaceCwd,
1324
+ executionTargetIsRemote,
1325
+ });
1326
+ // Resolved adapter env (plain + server-resolved secret_ref values) that we
1327
+ // forward to the spawned agent process. Captured so a stable hash of it can be
1328
+ // folded into the session fingerprint below — a change here must invalidate a
1329
+ // warm/resumable session so the next launch picks up the latest env. Only
1330
+ // user/adapter-configured env flows through this loop; per-wake PAPERCLIP_*
1331
+ // runtime vars (PAPERCLIP_RUN_ID, wake/approval ids, ...) were assigned to
1332
+ // `env` above and are never present in shapedEnvConfig, so they inherently
1333
+ // stay out of the hash and don't reset the session every heartbeat.
1334
+ const resolvedAdapterEnv = {};
1335
+ const scratch = parseObject(context.paperclipScratch);
1336
+ const scratchKeys = scratch.type === "heartbeat_run" && typeof scratch.dir === "string"
1337
+ ? new Set(["PAPERCLIP_RUN_SCRATCH_DIR", "PAPERCLIP_TASK_SCRATCH_DIR", "PAPERCLIP_SCRATCH_DIR", "PAPERCLIP_TMPDIR",
1338
+ ...(Array.isArray(scratch.tempKeysApplied) ? scratch.tempKeysApplied.filter((key) => typeof key === "string" && ["TMPDIR", "TEMP", "TMP"].includes(key)) : [])])
1339
+ : new Set();
1340
+ const scratchPaths = new Set([scratch.dir, scratch.tempDir].filter((value) => typeof value === "string"));
1341
+ for (const [key, value] of Object.entries(shapedEnvConfig)) {
1342
+ if (typeof value !== "string")
1343
+ continue;
1344
+ // Runtime PAPERCLIP_* always wins over config: skip a PAPERCLIP_* key that
1345
+ // Paperclip has already assigned this run. PAPERCLIP_API_KEY is never
1346
+ // accepted from config — the harness-minted run token is the only source.
1347
+ // A PAPERCLIP_* key Paperclip did NOT set is stable per-run config, so it
1348
+ // applies and feeds the fingerprint hash below.
1349
+ if (isForbiddenConfigEnvKey(key))
1350
+ continue;
1351
+ if (isPaperclipRuntimeEnvKey(key) && legacyEnvKey(key) in env)
1352
+ continue;
1353
+ env[key] = value;
1354
+ // The server rotates run-owned scratch paths on every wake. Still forward
1355
+ // them, but only hash actual adapter settings. User-supplied temp overrides
1356
+ // are absent from tempKeysApplied and keep their compatibility protection.
1357
+ if (!scratchKeys.has(key) || !scratchPaths.has(value))
1358
+ resolvedAdapterEnv[key] = value;
1359
+ }
1360
+ if (authToken)
1361
+ env.PAPERCLIP_API_KEY = authToken;
1362
+ // For the claude agent, set model via ANTHROPIC_MODEL at startup rather than
1363
+ // via session/set_config_option — the ACP server's set_config_option handler
1364
+ // validates the value against its internal available-models list and rejects
1365
+ // bare model IDs (e.g. "claude-opus-4-7") that don't exactly match a model
1366
+ // entry in some versions. ANTHROPIC_MODEL is read during initialization, so
1367
+ // it reliably sets the model before any turns are run.
1368
+ if (requestedModel && acpxAgent === "claude" && !env.ANTHROPIC_MODEL) {
1369
+ env.ANTHROPIC_MODEL = requestedModel;
1370
+ }
1371
+ // Gemini CLI reads GEMINI_MODEL when creating each ACP session. Its ACP
1372
+ // implementation supports set_model, but not set_config_option; configure
1373
+ // the selected model before startup without changing the transport.
1374
+ if (requestedModel && acpxAgent === "gemini") {
1375
+ env.GEMINI_MODEL = requestedModel;
1376
+ }
1377
+ if (acpxAgent === "codex") {
1378
+ const codexStartupConfig = buildCodexStartupConfig({
1379
+ existingConfig: env.CODEX_CONFIG,
1380
+ ...(input.ctx.agentIdentity ? { identityEnvironmentKeys: [...new Set([
1381
+ "PATH", "HOME", "LANG", "TMPDIR", "CODEX_HOME",
1382
+ "PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY",
1383
+ // Preserve Codex's default secret-name exclusions. The short-lived
1384
+ // Paperclip API token is required by the agent skill's Bash/curl calls.
1385
+ ...Object.keys(env).filter(key => key === "PAPERCLIP_API_KEY" || !/key|secret|token/i.test(key)),
1386
+ ])] } : {}),
1387
+ requestedModel,
1388
+ requestedThinkingEffort,
1389
+ fastMode,
1390
+ });
1391
+ if (codexStartupConfig.invalidExistingConfig) {
1392
+ await input.ctx.onLog("stderr", "[paperclip] Ignoring invalid user CODEX_CONFIG while applying runtime Codex settings; expected a JSON object.\n");
1393
+ }
1394
+ if (codexStartupConfig.value)
1395
+ env.CODEX_CONFIG = codexStartupConfig.value;
1396
+ }
1397
+ let skillPromptInstructions = "";
1398
+ let skillsIdentity = { mode: "unsupported" };
1399
+ const skillCommandNotes = [];
1400
+ // The host directory a remote run stages as the `skills` asset. The engine
1401
+ // uses it to rewrite `skillPromptInstructions` and `skillsIdentity` onto
1402
+ // the in-sandbox copy, once `stagedRuntime` is known (see the rewrite
1403
+ // below, after `placeWorkspace` returns). This field is `null` for every
1404
+ // non-Claude agent, and for a Claude run with no skill selected.
1405
+ let claudeSkillsBundleDir = null;
1406
+ let paperclipClaudeSettings = null;
1407
+ if (acpxAgent === "claude") {
1408
+ const preparedSkills = await prepareClaudeSkillRuntime({
1409
+ stateDir,
1410
+ config,
1411
+ moduleDir: input.engine.moduleDir,
1412
+ onLog: input.ctx.onLog,
1413
+ });
1414
+ skillPromptInstructions = preparedSkills.promptInstructions;
1415
+ skillsIdentity = preparedSkills.identity;
1416
+ skillCommandNotes.push(...preparedSkills.commandNotes);
1417
+ claudeSkillsBundleDir = preparedSkills.bundleDir;
1418
+ paperclipClaudeSettings = await writePaperclipClaudeSettings({
1419
+ cwd,
1420
+ stateDir,
1421
+ // A run's writable AGENT_HOME moves, but the existing permission root
1422
+ // must not invalidate its resumable conversation. Run copies are covered
1423
+ // by the company root already granted in these settings; the process env
1424
+ // still receives this run's actual AGENT_HOME.
1425
+ agentHome: asString(workspaceContext.agentHomeForPermissions, agentHome),
1426
+ companyId: agent.companyId,
1427
+ });
1428
+ skillCommandNotes.push(`Wrote Paperclip-managed Claude settings to ${paperclipClaudeSettings.filePath} (defaultMode=${paperclipClaudeSettings.defaultMode}${paperclipClaudeSettings.overrodeDontAsk ? "; overrode user dontAsk" : ""}, +${paperclipClaudeSettings.additionalDirectories.length} read root(s), +${paperclipClaudeSettings.allow.length} allow rule(s)).`);
1429
+ }
1430
+ else if (acpxAgent === "codex") {
1431
+ // Step 2 — codex-home.seed: the codex managed-home + skills preparation.
1432
+ // The nested skills.reconcile boundary (step 3) is timed inside via the
1433
+ // threaded onEvent/now seam.
1434
+ const preparedSkills = await measureStartupStep(input.ctx, nowMs, "codex-home.seed", () => prepareCodexSkillRuntime({
1435
+ companyId: agent.companyId,
1436
+ agentId: agent.id,
1437
+ config,
1438
+ env,
1439
+ executionTargetIsRemote,
1440
+ moduleDir: input.engine.moduleDir,
1441
+ onLog: input.ctx.onLog,
1442
+ onEvent: input.ctx.onEvent,
1443
+ now: nowMs,
1444
+ stepMetrics,
1445
+ }), stepMetrics);
1446
+ skillsIdentity = preparedSkills.identity;
1447
+ skillCommandNotes.push(...preparedSkills.commandNotes);
1448
+ }
1449
+ else if (acpxAgent === "gemini") {
1450
+ const preparedSkills = await prepareGeminiSkillRuntime({
1451
+ config,
1452
+ moduleDir: input.engine.moduleDir,
1453
+ onLog: input.ctx.onLog,
1454
+ });
1455
+ skillsIdentity = preparedSkills.identity;
1456
+ skillCommandNotes.push(...preparedSkills.commandNotes);
1457
+ }
1458
+ else {
1459
+ // A minimal, separate Grok seam: only the company-scoped `GROK_HOME`
1460
+ // binding, so a Grok run authenticates from the credential a completed
1461
+ // device login wrote. This never touches `prepareCodexSkillRuntime` above
1462
+ // — that function stays Codex-only — and every other custom ACPX agent
1463
+ // (for example `kimi`) falls through this branch unaffected.
1464
+ if (acpxAgent === "grok" && !config.managedAiConnection) {
1465
+ env.GROK_HOME = resolveManagedGrokHomeDir(agent.companyId);
1466
+ }
1467
+ const desired = resolveLegacyPaperclipDesiredSkillNames(config, await readPaperclipRuntimeSkillEntries(config, input.engine.moduleDir));
1468
+ skillsIdentity = { mode: "custom_unsupported", desiredSkillNames: desired };
1469
+ if (desired.length > 0) {
1470
+ skillCommandNotes.push("Selected Paperclip skills are tracked only; ACPX custom commands do not expose a runtime skill contract yet.");
1471
+ }
1472
+ }
1473
+ const configuredCommand = asString(config.agentCommand, "").trim();
1474
+ const builtInCommand = await resolveBuiltInAgentCommand({
1475
+ agent: acpxAgent,
1476
+ packageRootDir: input.engine.packageRootDir,
1477
+ executionTargetIsRemote,
1478
+ });
1479
+ let agentCommand = configuredCommand || builtInCommand?.command || null;
1480
+ let agentCommandShell = configuredCommand || builtInCommand?.shellCommand || "";
1481
+ // A runner-backed remote sandbox is the only lane that crosses the staging
1482
+ // and serialized-launch-env seam. Runner-less ACP→CLI fallback, SSH, and
1483
+ // local runs keep their historical host-provider compatibility behavior.
1484
+ const useRemoteProcessSession = executionTarget?.kind === "remote" &&
1485
+ executionTarget.transport === "sandbox" &&
1486
+ Boolean(executionTarget.runner) &&
1487
+ Boolean(agentCommandShell);
1488
+ if (acpxAgent === "gemini" && agentCommandShell) {
1489
+ const normalized = await normalizeGeminiAcpCommandShell(agentCommandShell, resolveRuntimeEnv(env, acpxAgent, {
1490
+ inheritHostEnvironment: !useRemoteProcessSession,
1491
+ }));
1492
+ if (normalized !== agentCommandShell) {
1493
+ agentCommandShell = normalized;
1494
+ agentCommand = normalized;
1495
+ }
1496
+ }
1497
+ const childStderrDir = path.join(stateDir, "run-stderr");
1498
+ const childStderrLogPath = agentCommand ? path.join(childStderrDir, `${runId}.log`) : null;
1499
+ // Stream the agent output through the persistent session log stream instead of
1500
+ // the host output-file poll. The decision comes from the effective capability
1501
+ // snapshot alone: the provider must declare and verify incremental session
1502
+ // output. `incrementalSessionOutput` is an opt-in capability, so a generic
1503
+ // one-shot provider that keeps persistent process sessions and runs independent
1504
+ // control commands, yet never emits incremental session output, keeps the poll
1505
+ // path. The snapshot resolves this key false when it is absent, undeclared, or
1506
+ // capability resolution failed, so this fails closed to the poll path.
1507
+ const streamAgentSessionOutput = executionTarget?.kind === "remote" &&
1508
+ executionTarget.transport === "sandbox" &&
1509
+ executionTarget.effectiveCapabilities?.incrementalSessionOutput === true;
1510
+ // The ACP `session/new` cwd and every cwd-keyed session-state site
1511
+ // (fingerprint, compat, persist, ensureSession, error) bind to THIS single
1512
+ // value so a warm/resumable session created with the in-sandbox cwd is reused
1513
+ // — not invalidated — on the next run. Remote runner-backed → the in-sandbox
1514
+ // workspace dir; local and the runner-less fallback → the HOST cwd.
1515
+ // Local Gemini resolves tool paths through realpath. Give its ACP filesystem
1516
+ // client the same canonical root so workspace aliases stay within that root.
1517
+ //
1518
+ // PR 3: the staging transport derives the in-sandbox workspace dir
1519
+ // deterministically from the target's `remoteCwd` (it is exactly `remoteCwd`
1520
+ // for the sandbox transport), so we resolve `sessionCwd` — and therefore the
1521
+ // session fingerprint / cache key — BEFORE staging. That lets a compatible
1522
+ // resume decide to reuse an already-staged runtime instead of re-shipping the
1523
+ // workspace / re-seeding the managed home. The stage call below pins its
1524
+ // `workspaceRemoteDir` to this same value, so the staged cwd can never
1525
+ // diverge from the cwd that fed the fingerprint.
1526
+ const sessionCwd = useRemoteProcessSession && executionTarget?.kind === "remote"
1527
+ ? executionTarget.remoteCwd
1528
+ : acpxAgent === "gemini" && !executionTargetIsRemote
1529
+ ? await fs.realpath(cwd)
1530
+ : cwd;
1531
+ // The 17 fields the session fingerprint hashes. Company, agent, and task
1532
+ // identifiers are NOT here; they scope the outer session key only (see
1533
+ // `keyIdentity`). The fingerprint builder accepts only this identity.
1534
+ const fingerprintIdentity = {
1535
+ ...(input.ctx.agentIdentity ? { agentIdentityKeyId: input.ctx.agentIdentity.keyId } : {}),
1536
+ acpxAgent,
1537
+ agentCommand: agentCommand ?? acpxAgent,
1538
+ cwd: path.resolve(sessionCwd),
1539
+ mode,
1540
+ permissionMode,
1541
+ nonInteractivePermissions,
1542
+ requestedModel,
1543
+ requestedThinkingEffort,
1544
+ fastMode,
1545
+ remoteExecutionIdentity,
1546
+ // Referenced-project set + pinned-checkout identity. A change here (a project
1547
+ // added, removed, or re-pinned) invalidates a warm/resumable session so the
1548
+ // next launch stages the current referenced-project trees instead of reusing
1549
+ // a stale staged tree.
1550
+ additionalSourcesIdentity: additionalSourcesIdentity,
1551
+ skillsIdentity,
1552
+ skillPromptInstructions,
1553
+ paperclipClaudeSettings: paperclipClaudeSettings
1554
+ ? {
1555
+ allow: paperclipClaudeSettings.allow,
1556
+ additionalDirectories: paperclipClaudeSettings.additionalDirectories,
1557
+ defaultMode: paperclipClaudeSettings.defaultMode,
1558
+ }
1559
+ : null,
1560
+ // Qualified built-in ACP harnesses reconnect to the supplied MCP servers
1561
+ // on session/load. Keep their conversation identity independent of tools.
1562
+ mcpServers: ["claude", "codex", "grok", "gemini", "kimi"].includes(acpxAgent) ? [] : mcpIdentity,
1563
+ ...(toolProfile === "read_only" ? { toolProfile } : {}),
1564
+ secretManifestHash: shortHash(secretManifest),
1565
+ // Fold the resolved adapter env (all applied user-configured values —
1566
+ // plain, secret_ref, and stable PAPERCLIP_* config such as an explicit
1567
+ // PAPERCLIP_API_KEY) into the fingerprint so a change to any forwarded value
1568
+ // invalidates a warm handle / resumable session and forces a fresh launch
1569
+ // that sources the latest env. secretManifestHash alone misses plain-value
1570
+ // edits and same-version secret rotations. Per-wake runtime vars never enter
1571
+ // resolvedAdapterEnv, so they don't churn the fingerprint every heartbeat.
1572
+ adapterEnvHash: shortHash(resolvedAdapterEnv),
1573
+ };
1574
+ const fingerprint = buildSessionFingerprint(fingerprintIdentity);
1575
+ const taskKey = asString(input.ctx.runtime.taskKey, "") || wakeTaskId || workspaceId || "default";
1576
+ // Company, agent, and task identity for the outer session key. These parts
1577
+ // stay out of the fingerprint hash.
1578
+ const keyIdentity = {
1579
+ companyId: agent.companyId,
1580
+ agentId: agent.id,
1581
+ taskKey,
1582
+ };
1583
+ const sessionKey = buildSessionKey(keyIdentity, fingerprint);
1584
+ // Ship the workspace into the sandbox and capture `{ workspaceRemoteDir,
1585
+ // runtimeRootDir, assetDirs, restoreWorkspace }`. Done once here, before the
1586
+ // bridges, so both bridges receive the real (non-null) `runtimeRootDir`.
1587
+ //
1588
+ // PR 2: on the remote lane, delegate staging to the per-adapter
1589
+ // `prepareRemoteManagedHome` seam when the adapter supplies one. The seam
1590
+ // ships the adapter's managed home as an `assets` entry (through the `stage`
1591
+ // callback = `stageAcpRemoteRuntime`), repoints the home env var (`env`) onto
1592
+ // the in-sandbox `assetDirs.*` path, and returns a `teardown` (per-run codex
1593
+ // auth copy-back via `restoreWorkspace()`) plus a `disposeStaged` (one-time
1594
+ // staged-temp cleanup). Without a seam (custom agents / shared-engine tests)
1595
+ // the engine stages the workspace with no home asset — identical to PR-1.
1596
+ //
1597
+ // PR 3 (stage once per session): a COMPATIBLE resume whose fingerprint matches
1598
+ // this exact `sessionKey` reuses the already-staged in-sandbox runtime — no
1599
+ // workspace re-ship, no home re-seed — while an incompatible fingerprint (a
1600
+ // different key) misses the cache and stages fresh. The `sessionKey`
1601
+ // (`companyId:agentId:taskKey:fingerprint`) is the single scoping key, so one
1602
+ // session can never read another session's staged credentials. The cache is
1603
+ // populated by the executor only after a clean turn and dropped on
1604
+ // failure/cancel/timeout, so it always holds a known-good staged runtime.
1605
+ //
1606
+ // Two guards close the concurrency / cross-session windows Greptile flagged:
1607
+ // * Compatibility gate: reuse only when the supplied session params actually
1608
+ // resume THIS staged session (the same `isCompatibleSession` predicate the
1609
+ // warm-handle path uses). A fresh invocation with missing/cleared
1610
+ // `sessionParams` starts a new ACP session via `session/new`, so it must
1611
+ // NOT inherit the prior session's staged home/credentials — it stages
1612
+ // fresh even when company/agent/task/fingerprint (and hence sessionKey)
1613
+ // collide.
1614
+ // * Per-key staging lock: the stage-or-reuse decision runs under a
1615
+ // `sessionKey` mutex so two overlapping runs of the same session can never
1616
+ // ship into the same remote workspace at once (the loser waits, then
1617
+ // re-checks the cache before deciding).
1618
+ const stagedRuntimes = input.deps.stagedRuntimes ?? defaultStagedRuntimes;
1619
+ const stagingLocks = input.deps.stagingLocks ?? defaultStagingLocks;
1620
+ const previousParams = parseObject(input.ctx.runtime.sessionParams);
1621
+ const isCompatibleResume = isCompatibleSession(previousParams, {
1622
+ fingerprint,
1623
+ sessionKey,
1624
+ cwd: sessionCwd,
1625
+ mode,
1626
+ acpxAgent,
1627
+ remoteExecutionIdentity,
1628
+ });
1629
+ let stagedRuntime = null;
1630
+ let remoteManagedHomeTeardown = null;
1631
+ let remoteStagingDispose = null;
1632
+ let remoteStagingEnvDelta = null;
1633
+ let sessionStagingLeaseRelease = null;
1634
+ // The sandbox run site owns the sandbox lane's staging, the per-session
1635
+ // staging lease, both host-side bridges, the launch-environment contribution,
1636
+ // and sync-back. `buildRuntime` injects the leaf primitives (the workspace
1637
+ // stage call, the managed-home seam, the two bridge starts, the step timers,
1638
+ // and the launch-env finalizer) and reads the site's results back onto the
1639
+ // prepared-runtime fields, so the existing settlement path stays unchanged.
1640
+ let sandboxSite = null;
1641
+ if (useRemoteProcessSession && executionTarget?.kind === "remote") {
1642
+ const remoteTarget = executionTarget;
1643
+ sandboxSite = createSandboxRunSite({
1644
+ ledger: input.ledger,
1645
+ stagedRuntimes,
1646
+ stagingLocks,
1647
+ now: nowMs,
1648
+ idleMs: input.stagedIdleMs,
1649
+ sessionCwd,
1650
+ spawnCwd: cwd,
1651
+ target: remoteTarget,
1652
+ env,
1653
+ isCompatibleResume,
1654
+ stage: (assets) => stageAcpRemoteRuntime({
1655
+ runId,
1656
+ target: remoteTarget,
1657
+ adapterKey: input.engine.adapterType,
1658
+ workspaceLocalDir: cwd,
1659
+ workspaceRemoteDir: sessionCwd,
1660
+ timeoutSec,
1661
+ assets,
1662
+ additionalSources,
1663
+ onLog: input.ctx.onLog,
1664
+ onRuntimeProgress: input.ctx.onRuntimeProgress,
1665
+ runtimeSpan: input.stageRuntimeSpan,
1666
+ }),
1667
+ seedManagedHome: input.deps.prepareRemoteManagedHome
1668
+ ? async (stage) => {
1669
+ const seeded = await input.deps.prepareRemoteManagedHome({
1670
+ acpxAgent,
1671
+ companyId: agent.companyId,
1672
+ runId,
1673
+ config,
1674
+ executionTarget: remoteTarget,
1675
+ workspaceLocalDir: cwd,
1676
+ timeoutSec,
1677
+ env,
1678
+ onLog: input.ctx.onLog,
1679
+ onRuntimeProgress: input.ctx.onRuntimeProgress,
1680
+ skillsBundleDir: claudeSkillsBundleDir,
1681
+ stage,
1682
+ });
1683
+ return {
1684
+ stagedRuntime: seeded.stagedRuntime,
1685
+ teardown: seeded.teardown ?? null,
1686
+ dispose: seeded.disposeStaged ?? null,
1687
+ };
1688
+ }
1689
+ : undefined,
1690
+ disposeFreshStagedRuntime: (freshStagedRuntime) => disposeFreshStagedRuntime({
1691
+ runId,
1692
+ target: remoteTarget,
1693
+ stagedRuntime: freshStagedRuntime,
1694
+ cwd: sessionCwd,
1695
+ timeoutSec,
1696
+ onLog: input.ctx.onLog,
1697
+ }),
1698
+ measureStageStep: (run) => measureStartupStep(input.ctx, nowMs, "stage.sync", run, stepMetrics),
1699
+ publishStagedProjectHints: (stagedProjectDirs) => {
1700
+ const shapedHints = shapePaperclipWorkspaceEnvForExecution({
1701
+ workspaceCwd: effectiveWorkspaceCwd,
1702
+ workspaceWorktreePath,
1703
+ workspaceHints,
1704
+ executionTargetIsRemote,
1705
+ executionCwd: effectiveExecutionCwd,
1706
+ stagedProjectDirs,
1707
+ }).workspaceHints;
1708
+ if (shapedHints.length > 0) {
1709
+ env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(shapedHints);
1710
+ }
1711
+ },
1712
+ onReuseLog: () => input.ctx.onLog("stdout", "[paperclip] Reusing the staged in-sandbox runtime for this resumed session (no workspace re-ship / managed-home re-seed).\n"),
1713
+ startPaperclipBridge: (runtimeRootDir) => startAdapterExecutionTargetPaperclipBridge({
1714
+ runId,
1715
+ target: { ...remoteTarget, streamRunLogs: false },
1716
+ runtimeRootDir,
1717
+ adapterKey: input.engine.adapterType,
1718
+ timeoutSec,
1719
+ hostApiToken: env.PAPERCLIP_API_KEY,
1720
+ enableSandboxDuplexBridge: adapterExecutionTargetEnablesSandboxDuplexBridge(remoteTarget),
1721
+ duplexObservabilityRecorder: adapterExecutionTargetDuplexObservabilityRecorder(remoteTarget),
1722
+ onLog: input.ctx.onLog,
1723
+ getRuntimeParentContext: input.getRuntimeParentContext,
1724
+ runtimeSpan: input.runtimeSpan,
1725
+ }),
1726
+ startProcessSessionBridge: ({ runtimeRootDir, launchEnv }) => startAdapterExecutionTargetProcessSessionBridge({
1727
+ runId,
1728
+ target: remoteTarget,
1729
+ runtimeRootDir,
1730
+ adapterKey: input.engine.adapterType,
1731
+ command: "sh",
1732
+ args: ["-lc", `exec ${agentCommandShell}`],
1733
+ cwd: sessionCwd,
1734
+ env: launchEnv,
1735
+ timeoutSec,
1736
+ onLog: input.ctx.onLog,
1737
+ getRuntimeParentContext: input.getRuntimeParentContext,
1738
+ runtimeSpan: input.runtimeSpan,
1739
+ streamOutputViaSession: streamAgentSessionOutput,
1740
+ }),
1741
+ measureBridgeStep: (step, run) => measureStartupStep(input.ctx, nowMs, step, run, concurrentBridgeStepMetrics),
1742
+ finalizeLaunchEnv: (contributions) => finalizeLaunchEnvironment(env, contributions, {
1743
+ acpxAgent,
1744
+ inheritHostEnvironment: !useRemoteProcessSession,
1745
+ }).env,
1746
+ onPaperclipBridgeLog: () => input.ctx.onLog("stdout", "[paperclip] Sandbox ACP API callback bridge enabled for this run.\n"),
1747
+ stopBridges: async ({ controlBridge, agentBridge }) => {
1748
+ await Promise.allSettled([agentBridge?.stop(), controlBridge?.stop()]);
1749
+ if (remoteManagedHomeTeardown) {
1750
+ await remoteManagedHomeTeardown().catch(() => { });
1751
+ }
1752
+ },
1753
+ });
1754
+ // Place the workspace (stage fresh or reuse the already-staged runtime) under
1755
+ // the per-session staging lease, then read the staged result back onto the
1756
+ // prepared-runtime fields the settlement path consumes.
1757
+ const placeWorkspaceStart = nowMs();
1758
+ await sandboxSite.placeWorkspace({ sessionKey });
1759
+ await emitRunPhaseTiming(input.ctx, "place_workspace", nowMs() - placeWorkspaceStart, "ok");
1760
+ const placedStaged = sandboxSite.staged;
1761
+ stagedRuntime = placedStaged?.stagedRuntime ?? null;
1762
+ remoteManagedHomeTeardown = placedStaged?.teardown ?? null;
1763
+ remoteStagingDispose = placedStaged?.dispose ?? null;
1764
+ remoteStagingEnvDelta = placedStaged?.envDelta ?? null;
1765
+ sessionStagingLeaseRelease = sandboxSite.stagingLeaseRelease;
1766
+ }
1767
+ // Once the skill bundle is staged, rewrite the prompt and the identity onto
1768
+ // the in-sandbox copy. This code runs here, after `placeWorkspace` resolves
1769
+ // `stagedRuntime`. It runs on every invocation, both a fresh stage and a
1770
+ // compatible resume. It never runs inside the `prepareRemoteManagedHome`
1771
+ // seam, because a compatible resume never calls that seam again.
1772
+ // `skillPromptInstructions` and `skillsIdentity` already fed `fingerprint`
1773
+ // above, with the host-independent identity. So this rewrite never reaches
1774
+ // the fingerprint: it only replaces the host bundle path with the
1775
+ // in-sandbox path, in the local copies used for the returned prompt,
1776
+ // identity, and command notes.
1777
+ if (acpxAgent === "claude" && stagedRuntime && claudeSkillsBundleDir) {
1778
+ const inSandboxSkillsRoot = stagedRuntime.assetDirs.skills ??
1779
+ path.posix.join(stagedRuntime.runtimeRootDir ??
1780
+ path.posix.join(stagedRuntime.workspaceRemoteDir ?? cwd, ".paperclip-runtime", acpxAgent), "skills");
1781
+ const rebaseToSandbox = (value) => value.split(claudeSkillsBundleDir).join(inSandboxSkillsRoot);
1782
+ skillPromptInstructions = rebaseToSandbox(skillPromptInstructions);
1783
+ skillsIdentity = {
1784
+ ...skillsIdentity,
1785
+ skillRoot: typeof skillsIdentity.skillRoot === "string"
1786
+ ? rebaseToSandbox(skillsIdentity.skillRoot)
1787
+ : skillsIdentity.skillRoot,
1788
+ };
1789
+ for (let i = 0; i < skillCommandNotes.length; i += 1) {
1790
+ skillCommandNotes[i] = rebaseToSandbox(skillCommandNotes[i]);
1791
+ }
1792
+ }
1793
+ // Both bridge starts run under one try so a failure at EITHER — including the
1794
+ // paperclip callback bridge — fires the same abandon-path cleanup. The
1795
+ // paperclip bridge starts after the workspace + managed home were already
1796
+ // staged and the per-session staging lease is already held, so leaving it
1797
+ // outside the catch would strand the lease (and the staged temp) on a
1798
+ // start failure and deadlock the next run of this session.
1799
+ let paperclipBridge = null;
1800
+ let processSessionBridge = null;
1801
+ let runtimeEnv = {};
1802
+ const startTransportStart = nowMs();
1803
+ try {
1804
+ if (useRemoteProcessSession && sandboxSite) {
1805
+ // The sandbox run site brings up both host-side bridges concurrently, keeps
1806
+ // the one paperclip-env → process-session-launch dependency at a single
1807
+ // sequencing point, settles both starts, and returns the started handles
1808
+ // plus the finalized launch env. On a partial failure it stops nothing and
1809
+ // rethrows; the catch below stops whichever bridge the site started.
1810
+ const transport = await sandboxSite.startTransport({ sessionKey });
1811
+ paperclipBridge = transport.controlBridge;
1812
+ processSessionBridge = transport.agentBridge;
1813
+ runtimeEnv = transport.launchEnv;
1814
+ await emitRunPhaseTiming(input.ctx, "start_transport", nowMs() - startTransportStart, "ok");
1815
+ }
1816
+ else {
1817
+ // Local / runner-less lanes never start a bridge, so they add no
1818
+ // contribution. `finalizeLaunchEnvironment` still produces the one branded
1819
+ // launch env the prepared runtime and the log builder read.
1820
+ runtimeEnv = finalizeLaunchEnvironment(env, [], {
1821
+ acpxAgent,
1822
+ inheritHostEnvironment: !useRemoteProcessSession,
1823
+ }).env;
1824
+ }
1825
+ }
1826
+ catch (err) {
1827
+ // On a partial concurrent bring-up failure, ONE bridge may have started while
1828
+ // the other threw; `Promise.allSettled` stops whichever started so no live
1829
+ // bridge leaks (mirrors the settlement `stopTransport` step). The site sets its
1830
+ // started bridges before it rethrows, so read them from the site here (the
1831
+ // local handles stay null when `startTransport` throws before it returns).
1832
+ const startedControl = sandboxSite?.controlBridge ?? paperclipBridge;
1833
+ const startedAgent = sandboxSite?.agentBridge ?? processSessionBridge;
1834
+ await Promise.allSettled([startedControl?.stop(), startedAgent?.stop()]);
1835
+ // The staged home / copy-back teardown must run even if a bridge fails to
1836
+ // start after the workspace + managed home were already staged into the
1837
+ // sandbox, so a refreshed credential is copied back on this error path too.
1838
+ // This run never reaches the executor, so also fire the one-time staged-temp
1839
+ // dispose here (it no longer rides the per-run copy-back) — the run is being
1840
+ // abandoned, so its staged temp must be released — and release the per-session
1841
+ // staging lease so the abandoned run does not strand the next same-session run
1842
+ // (the run root `finally`, which normally releases it, is never reached here).
1843
+ //
1844
+ // Route the dispose through the same ownership-guarded removal
1845
+ // `discardStagedRuntime` uses. When this run BORROWED the cached staged runtime
1846
+ // (a compatible resume), the dispose releases the shared host staged-temp, so
1847
+ // the map entry must go too — otherwise a later resume reuses an entry whose
1848
+ // temp is already gone. The identity guard removes the entry only when the map
1849
+ // still holds this exact staged runtime, so a fresh stage (no cache entry) and
1850
+ // a concurrent run's entry are both left untouched.
1851
+ await remoteManagedHomeTeardown?.().catch(() => { });
1852
+ await releaseStagedRuntimeEntry({
1853
+ handles: stagedRuntimes,
1854
+ sessionKey,
1855
+ stagedRuntime,
1856
+ dispose: remoteStagingDispose,
1857
+ });
1858
+ sessionStagingLeaseRelease?.();
1859
+ await emitRunPhaseTiming(input.ctx, "start_transport", nowMs() - startTransportStart, "failed");
1860
+ throw err;
1861
+ }
1862
+ const currentSkillRoot = acpxAgent === "codex" && runtimeEnv.CODEX_HOME
1863
+ ? path.join(runtimeEnv.CODEX_HOME, "skills")
1864
+ : acpxAgent === "gemini" && !executionTargetIsRemote && typeof skillsIdentity.skillsHome === "string"
1865
+ ? skillsIdentity.skillsHome
1866
+ : null;
1867
+ if (currentSkillRoot && Array.isArray(skillsIdentity.selectedSkills) && skillsIdentity.selectedSkills.length > 0) {
1868
+ // Managed connection homes are disposable. A resumed conversation may
1869
+ // remember a previous home's skill paths; supply the current root on every
1870
+ // turn, after the remote launch environment has rebased CODEX_HOME.
1871
+ skillPromptInstructions = [
1872
+ `Paperclip has materialized selected runtime skills for this ACPX ${acpxAgent === "codex" ? "Codex" : "Gemini"} run.`,
1873
+ `Skill root for this run: ${currentSkillRoot}`,
1874
+ `Selected skills: ${skillsIdentity.selectedSkills.join(", ")}`,
1875
+ "When a task calls for one of these skills, read its SKILL.md from this root and follow it. Resolve referenced scripts and files relative to that skill. Use this run's root even when an earlier turn used a different path.",
1876
+ ...(acpxAgent === "gemini" && skillsIdentity.selectedSkills.includes("paperclip")
1877
+ ? [
1878
+ "Before calling Paperclip APIs or delivering task artifacts, read the selected paperclip skill's SKILL.md and its referenced artifact workflow. A completion comment does not upload an artifact or change task status.",
1879
+ "Gemini's shell tool rejects command substitution. Write JSON request bodies to a workspace file and use curl --data-binary @file, or use the selected skill's helpers, instead of constructing a body with command substitution.",
1880
+ ]
1881
+ : []),
1882
+ ].join("\n");
1883
+ }
1884
+ // The relay runs on the host with the sanitized remote launch environment.
1885
+ // Its /usr/bin/env node shebang cannot rely on that environment's PATH.
1886
+ const overrideCommand = processSessionBridge?.agentCommand
1887
+ ? [process.execPath, processSessionBridge.agentCommand]
1888
+ .map((part) => JSON.stringify(part.replaceAll("\\", "/"))).join(" ")
1889
+ : agentCommand;
1890
+ const overrides = overrideCommand ? { [acpxAgent]: overrideCommand } : undefined;
1891
+ const agentRegistry = createAgentRegistry({ overrides });
1892
+ const loggedEnv = buildInvocationEnvForLogs(env, {
1893
+ runtimeEnv,
1894
+ includeRuntimeKeys: ["HOME"],
1895
+ resolvedCommand: agentCommand ?? acpxAgent,
1896
+ });
1897
+ return {
1898
+ acpxAgent,
1899
+ coalescePlaceholderToolUpdates,
1900
+ mode,
1901
+ // Remote runner-backed → the in-sandbox workspace dir; local / runner-less
1902
+ // → the HOST cwd (`sessionCwd` resolves both). Every cwd-keyed session site
1903
+ // reads `prepared.cwd`, so binding it once here keeps them consistent.
1904
+ cwd: sessionCwd,
1905
+ // Only the remote process-session lane needs the host proxy's `spawn()`
1906
+ // `chdir` redirected off the in-sandbox `sessionCwd` and onto the host
1907
+ // `cwd` (which is where the workspace was staged FROM, so it is host-valid).
1908
+ // Every other lane leaves it `undefined` → acpx falls back to `cwd`.
1909
+ hostSpawnCwd: useRemoteProcessSession ? cwd : undefined,
1910
+ workspaceId,
1911
+ workspaceRepoUrl,
1912
+ workspaceRepoRef,
1913
+ env: runtimeEnv,
1914
+ loggedEnv,
1915
+ stateDir,
1916
+ permissionMode,
1917
+ nonInteractivePermissions,
1918
+ toolProfile,
1919
+ requestedModel,
1920
+ requestedThinkingEffort,
1921
+ fastMode,
1922
+ timeoutSec,
1923
+ timeoutResolution,
1924
+ sessionKey,
1925
+ fingerprint,
1926
+ agentCommand,
1927
+ agentRegistry,
1928
+ processSessionBridge,
1929
+ paperclipBridge,
1930
+ stagedRuntime,
1931
+ remoteManagedHomeTeardown,
1932
+ remoteStagingDispose,
1933
+ remoteStagingEnvDelta,
1934
+ sessionStagingLeaseRelease,
1935
+ remoteExecutionIdentity,
1936
+ skillPromptInstructions,
1937
+ paperclipAccess,
1938
+ paperclipToolsets,
1939
+ skillsIdentity: {
1940
+ ...skillsIdentity,
1941
+ commandNotes: skillCommandNotes,
1942
+ },
1943
+ childStderrLogPath,
1944
+ paperclipClaudeSettings,
1945
+ mcpServers,
1946
+ mcpIdentity,
1947
+ stepMetrics,
1948
+ };
1949
+ }
1950
+ function sessionConfigOptions(prepared) {
1951
+ const options = [];
1952
+ // Claude, Codex and Gemini runtime config is pre-set via startup env vars; skip
1953
+ // set_config_option to avoid ACP-server picker validation rejecting valid
1954
+ // backend model IDs that are not advertised by the local ACP server.
1955
+ if (prepared.requestedModel &&
1956
+ prepared.acpxAgent !== "claude" &&
1957
+ prepared.acpxAgent !== "codex" &&
1958
+ prepared.acpxAgent !== "gemini") {
1959
+ options.push({ key: "model", value: prepared.requestedModel });
1960
+ }
1961
+ if (prepared.requestedThinkingEffort && prepared.acpxAgent !== "codex") {
1962
+ options.push({
1963
+ key: "effort",
1964
+ value: prepared.requestedThinkingEffort,
1965
+ });
1966
+ }
1967
+ if (prepared.fastMode && prepared.acpxAgent !== "codex") {
1968
+ options.push({ key: "service_tier", value: "fast" }, { key: "features.fast_mode", value: "true" });
1969
+ }
1970
+ return options;
1971
+ }
1972
+ async function applySessionConfigOptions(input) {
1973
+ const options = sessionConfigOptions(input.prepared);
1974
+ if (options.length === 0)
1975
+ return;
1976
+ if (!input.runtime.setConfigOption) {
1977
+ const message = "ACPX runtime does not expose session config controls; upgrade ACPX or remove configured model, effort, and fast mode overrides.";
1978
+ await input.onLog("stderr", `[paperclip] ${message}\n`);
1979
+ throw new Error(message);
1980
+ }
1981
+ for (const option of options) {
1982
+ await input.runtime.setConfigOption({
1983
+ handle: input.handle,
1984
+ key: option.key,
1985
+ value: option.value,
1986
+ });
1987
+ await input.onLog("stdout", `[paperclip] Applied ACPX ${input.prepared.acpxAgent} config ${option.key}=${option.value}\n`);
1988
+ }
1989
+ }
1990
+ /**
1991
+ * Build the process-session launch env: the target-specific host projection
1992
+ * overlaid with the run's explicit `env` (so adapter config, runtime variables,
1993
+ * and bridge contributions win), narrowed to string values. Host-side launches
1994
+ * get the closed projection plus a default `PATH` when the host did not provide
1995
+ * one. Runner-backed remote sandbox launches get no ambient host state or
1996
+ * synthesized host `PATH`; omitting `PATH` preserves the sandbox-native value.
1997
+ */
1998
+ function resolveRuntimeEnv(env, acpxAgent, options) {
1999
+ const inheritedEnv = options.inheritedEnv ?? process.env;
2000
+ const projectedHostEnv = projectAcpxInheritedHostEnvironment(inheritedEnv, acpxAgent, options.inheritHostEnvironment);
2001
+ const inheritedLaunchEnv = options.inheritHostEnvironment
2002
+ ? ensurePathInEnv(projectedHostEnv)
2003
+ : projectedHostEnv;
2004
+ const mergedEnv = mergeRuntimeEnvironment(inheritedLaunchEnv, env, (options.platform ?? process.platform) === "win32");
2005
+ const finalEnv = Object.fromEntries(Object.entries(mergedEnv).filter((entry) => typeof entry[1] === "string"));
2006
+ // codex-acp supports both key names, but ACP clients must select its
2007
+ // api-key authentication method during session creation. Without this
2008
+ // request, the server advertises authentication and rejects session/new even
2009
+ // though the credential is present in the launched process environment. Check
2010
+ // the final merged environment, not just the explicit run config, so a host
2011
+ // key the local launch inherits still selects this default.
2012
+ if (acpxAgent === "codex" &&
2013
+ (finalEnv.OPENAI_API_KEY || finalEnv.CODEX_API_KEY) &&
2014
+ !finalEnv.DEFAULT_AUTH_REQUEST) {
2015
+ finalEnv.DEFAULT_AUTH_REQUEST = JSON.stringify({ methodId: "api-key" });
2016
+ }
2017
+ return finalEnv;
2018
+ }
2019
+ function mergeRuntimeEnvironment(inheritedEnv, explicitEnv, caseInsensitiveKeys) {
2020
+ if (!caseInsensitiveKeys) {
2021
+ return { ...inheritedEnv, ...explicitEnv };
2022
+ }
2023
+ const merged = {};
2024
+ const keyByCanonicalName = new Map();
2025
+ const apply = (source) => {
2026
+ for (const [key, value] of Object.entries(source)) {
2027
+ if (typeof value !== "string")
2028
+ continue;
2029
+ const canonicalName = key.toUpperCase();
2030
+ const previousKey = keyByCanonicalName.get(canonicalName);
2031
+ if (previousKey !== undefined && previousKey !== key) {
2032
+ delete merged[previousKey];
2033
+ }
2034
+ merged[key] = value;
2035
+ keyByCanonicalName.set(canonicalName, key);
2036
+ }
2037
+ };
2038
+ apply(inheritedEnv);
2039
+ apply(explicitEnv);
2040
+ return merged;
2041
+ }
2042
+ // Stop both host-side bridges in one `allSettled`. This is the settlement
2043
+ // `stopTransport` effect. The bridge tokens are run-scoped, so they die with the
2044
+ // bridges here (Amendment B).
2045
+ async function stopRunTransport(prepared) {
2046
+ await Promise.allSettled([
2047
+ prepared.processSessionBridge?.stop(),
2048
+ prepared.paperclipBridge?.stop(),
2049
+ ]);
2050
+ }
2051
+ // The site sync-back. This is the settlement `syncBack` effect. It runs AFTER the
2052
+ // bridges stop (mirrors the CLI finally: stop bridge → restore workspace). It
2053
+ // fires the codex auth copy-back via `restoreWorkspace()` and removes staged temp
2054
+ // dirs. The seam logs and swallows its own failures — an unclean-teardown
2055
+ // copy-back miss is the accepted, loud `refresh_token_reused` residual on the
2056
+ // next host Codex use, never silent HOST-credential corruption — so a teardown
2057
+ // fault never masks or fails the run result here. It still returns the restore
2058
+ // outcome, so the caller can record a failure on the run record; the run's exit
2059
+ // code and status stay exactly what the turn produced.
2060
+ // The per-session staging lease does NOT release here. The settlement releases
2061
+ // it last, in its own `finally`, so a same-session second run cannot re-stage
2062
+ // until this run fully settles and the caller observes the result.
2063
+ async function syncBackManagedHome(prepared) {
2064
+ if (!prepared.remoteManagedHomeTeardown) {
2065
+ return { ok: true };
2066
+ }
2067
+ // The teardown closure already catches and logs its own error (fail-soft);
2068
+ // this `.catch` is defense in depth for the case where it rejects anyway, so
2069
+ // a teardown fault can never propagate out of settlement.
2070
+ return await prepared
2071
+ .remoteManagedHomeTeardown()
2072
+ .catch(() => ({ ok: false, code: "restore_failed" }));
2073
+ }
2074
+ // ACP startup handshake guard and late-completion fence.
2075
+ //
2076
+ // `runtime.ensureSession()` comes from the external `acpx/runtime` package. It
2077
+ // takes no `AbortSignal`, so the engine cannot cancel it; it can only walk
2078
+ // away from the promise. `guardEnsureSession` races the call against a fixed
2079
+ // deadline and a poll of the duplex control-channel disposition, and rejects
2080
+ // with one of these two host-generated, typed errors the moment either
2081
+ // condition trips. The error type — not its message — is what
2082
+ // `classifyError` reads, so a startup timeout can never collapse into the
2083
+ // session-identity failure code.
2084
+ //
2085
+ // A guard rejection does not stop the external call. `HandshakeAbandonmentFence`
2086
+ // gives that abandoned promise one owner: a resolution that arrives after the
2087
+ // engine walked away can never become the live session handle, the promise
2088
+ // stays observed so it can never raise an unhandled rejection, and the real
2089
+ // handle is closed exactly once, whichever side — the settlement step or the
2090
+ // fence itself — ends up seeing it first.
2091
+ class AcpxHandshakeTimeoutError extends Error {
2092
+ acpxHandshakeGuardKind = "timeout";
2093
+ constructor() {
2094
+ super("The ACP startup handshake did not finish before the startup deadline.");
2095
+ this.name = "AcpxHandshakeTimeoutError";
2096
+ }
2097
+ }
2098
+ class AcpxHandshakeTransportLostError extends Error {
2099
+ acpxHandshakeGuardKind = "transport_lost";
2100
+ constructor() {
2101
+ super("The sandbox duplex control channel was lost during the ACP startup handshake.");
2102
+ this.name = "AcpxHandshakeTransportLostError";
2103
+ }
2104
+ }
2105
+ function isAcpxHandshakeTimeoutError(err) {
2106
+ return err instanceof AcpxHandshakeTimeoutError;
2107
+ }
2108
+ function isAcpxHandshakeTransportLostError(err) {
2109
+ return err instanceof AcpxHandshakeTransportLostError;
2110
+ }
2111
+ /**
2112
+ * Gives one abandoned `ensureSession` promise one owner. Construct one fence
2113
+ * per run and reuse it across both `ensureSession` call sites (the first
2114
+ * attempt and the fresh-session retry): only one of those two calls can ever
2115
+ * be the one a guard rejection abandons, because the retry only runs after
2116
+ * the first call already settled on its own.
2117
+ *
2118
+ * `seal()` is the idempotent boundary: only its first call can flip the
2119
+ * state and hand back a handle that arrived before it ran. A later call is a
2120
+ * no-op, so `endSession` can call it unconditionally as its first operation
2121
+ * on every settlement path, not only a handshake-guard one.
2122
+ */
2123
+ class HandshakeAbandonmentFence {
2124
+ sealedFlag = false;
2125
+ lateHandle = null;
2126
+ get isSealed() {
2127
+ return this.sealedFlag;
2128
+ }
2129
+ /** Record a late resolution that arrived before `seal()` ran. */
2130
+ storeLateHandle(handle) {
2131
+ if (this.sealedFlag)
2132
+ return;
2133
+ this.lateHandle = handle;
2134
+ }
2135
+ /** Idempotent. Only the first call can return a handle that beat it here. */
2136
+ seal() {
2137
+ if (this.sealedFlag)
2138
+ return null;
2139
+ this.sealedFlag = true;
2140
+ const handle = this.lateHandle;
2141
+ this.lateHandle = null;
2142
+ return handle;
2143
+ }
2144
+ }
2145
+ /**
2146
+ * Race one `ensureSession()` call against the startup guard. Whichever
2147
+ * settles first wins; `outcome` records which one, so the promise's own
2148
+ * `.then` (attached synchronously, right here, before this function returns)
2149
+ * can tell a genuinely late settlement apart from the one the race already
2150
+ * delivered through its normal return value.
2151
+ *
2152
+ * The deadline and the transport-loss poll both start now, at the call site,
2153
+ * not earlier. The bridge disposition this polls is a latch: once a loss
2154
+ * orders, every later read still reports it, so a loss that happened before
2155
+ * this call started polling is still caught on the first tick.
2156
+ */
2157
+ function guardEnsureSession(params) {
2158
+ const sessionPromise = params.call();
2159
+ let outcome = "pending";
2160
+ // Attached the moment the promise exists. A guard-won race still leaves
2161
+ // this promise observed for as long as it takes to settle, so it can never
2162
+ // raise an unhandled rejection.
2163
+ sessionPromise.then((handle) => {
2164
+ if (outcome !== "guard")
2165
+ return;
2166
+ if (params.fence.isSealed) {
2167
+ params.onLateHandleAfterSeal(handle);
2168
+ }
2169
+ else {
2170
+ params.fence.storeLateHandle(handle);
2171
+ }
2172
+ }, () => {
2173
+ if (outcome !== "guard")
2174
+ return;
2175
+ params.onLateRejection();
2176
+ });
2177
+ return new Promise((resolve, reject) => {
2178
+ let settled = false;
2179
+ const timer = setTimeout(() => {
2180
+ if (settled)
2181
+ return;
2182
+ settled = true;
2183
+ outcome = "guard";
2184
+ clearInterval(poll);
2185
+ reject(new AcpxHandshakeTimeoutError());
2186
+ }, ACPX_HANDSHAKE_TIMEOUT_MS);
2187
+ const poll = setInterval(() => {
2188
+ if (settled)
2189
+ return;
2190
+ if (!params.isTransportLost())
2191
+ return;
2192
+ settled = true;
2193
+ outcome = "guard";
2194
+ clearTimeout(timer);
2195
+ clearInterval(poll);
2196
+ reject(new AcpxHandshakeTransportLostError());
2197
+ }, ACPX_HANDSHAKE_TRANSPORT_POLL_MS);
2198
+ sessionPromise.then((handle) => {
2199
+ if (settled)
2200
+ return;
2201
+ settled = true;
2202
+ outcome = "session";
2203
+ clearTimeout(timer);
2204
+ clearInterval(poll);
2205
+ resolve(handle);
2206
+ }, (err) => {
2207
+ if (settled)
2208
+ return;
2209
+ settled = true;
2210
+ outcome = "session";
2211
+ clearTimeout(timer);
2212
+ clearInterval(poll);
2213
+ reject(err);
2214
+ });
2215
+ });
2216
+ }
2217
+ function renderPaperclipEnvNote(env) {
2218
+ const paperclipKeys = Object.keys(env)
2219
+ .filter((key) => key.startsWith("PAPERCLIP_"))
2220
+ .sort();
2221
+ if (paperclipKeys.length === 0)
2222
+ return "";
2223
+ return [
2224
+ "Paperclip runtime note:",
2225
+ `The following PAPERCLIP_* environment variables are available in this run: ${paperclipKeys.join(", ")}`,
2226
+ "Do not assume these variables are missing without checking your shell environment.",
2227
+ ].join("\n");
2228
+ }
2229
+ function renderApiAccessNote(env, access, toolsets) {
2230
+ if (!env.PAPERCLIP_API_URL || !env.PAPERCLIP_API_KEY)
2231
+ return "";
2232
+ const lines = ["Paperclip API access note:", paperclipAccessGuidance(access, { toolsets })];
2233
+ if (!env.PAPERCLIP_TASK_ID) {
2234
+ lines.push("Use a real issue id from the current context before making issue write requests.");
2235
+ }
2236
+ return lines.join("\n");
2237
+ }
2238
+ async function buildPrompt(ctx, resumedSession, env, paperclipAccess, paperclipToolsets) {
2239
+ const { agent, runId, config, context, onLog } = ctx;
2240
+ const configuredPromptTemplate = asString(config.promptTemplate, "");
2241
+ const hasCustomPromptTemplate = configuredPromptTemplate.trim().length > 0;
2242
+ const promptTemplate = hasCustomPromptTemplate
2243
+ ? configuredPromptTemplate
2244
+ : context.conversationMode === true
2245
+ ? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
2246
+ : paperclipAgentPromptTemplate(paperclipAccess);
2247
+ const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
2248
+ const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
2249
+ let instructionsPrefix = "";
2250
+ const commandNotes = [];
2251
+ if (instructionsFilePath) {
2252
+ try {
2253
+ const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
2254
+ instructionsPrefix =
2255
+ `${instructionsContents}\n\n` +
2256
+ `The above agent instructions were loaded from ${instructionsFilePath}. ` +
2257
+ `Resolve any relative file references from ${instructionsDir}.\n\n`;
2258
+ commandNotes.push(`Loaded agent instructions from ${instructionsFilePath}`, `Prepended instructions + path directive to the ACPX prompt (relative references from ${instructionsDir}).`);
2259
+ }
2260
+ catch (err) {
2261
+ const reason = err instanceof Error ? err.message : String(err);
2262
+ await onLog("stderr", `[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`);
2263
+ commandNotes.push(`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read.`);
2264
+ }
2265
+ }
2266
+ const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
2267
+ const templateData = {
2268
+ agentId: agent.id,
2269
+ companyId: agent.companyId,
2270
+ runId,
2271
+ company: { id: agent.companyId },
2272
+ agent,
2273
+ run: { id: runId, source: "on_demand" },
2274
+ context,
2275
+ };
2276
+ const renderedBootstrapPrompt = !resumedSession && bootstrapPromptTemplate.trim().length > 0
2277
+ ? renderTemplate(bootstrapPromptTemplate, templateData).trim()
2278
+ : "";
2279
+ await hydrateFreshSessionHandoff(ctx, { resumedSession });
2280
+ const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
2281
+ resumedSession,
2282
+ includeCommunicationGuidance: false,
2283
+ paperclipAccess,
2284
+ });
2285
+ const externalChatTurn = isPaperclipExternalChatTurn(context.paperclipWake);
2286
+ const shouldUseResumeDeltaPrompt = resumedSession && wakePrompt.length > 0;
2287
+ const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix;
2288
+ const renderedPrompt = shouldUseResumeDeltaPrompt || (externalChatTurn && !hasCustomPromptTemplate)
2289
+ ? ""
2290
+ : renderTemplate(promptTemplate, templateData);
2291
+ const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
2292
+ const paperclipEnvNote = externalChatTurn ? "" : renderPaperclipEnvNote(env);
2293
+ const apiAccessNote = externalChatTurn ? "" : renderApiAccessNote(env, paperclipAccess, paperclipToolsets);
2294
+ const prompt = joinPromptSections([
2295
+ promptInstructionsPrefix,
2296
+ renderedBootstrapPrompt,
2297
+ selectInitialCommunicationGuidance(context, { resumedSession }),
2298
+ wakePrompt,
2299
+ sessionHandoffNote,
2300
+ taskContextNote,
2301
+ paperclipEnvNote,
2302
+ apiAccessNote,
2303
+ renderedPrompt,
2304
+ ]);
2305
+ return {
2306
+ prompt,
2307
+ commandNotes,
2308
+ promptMetrics: {
2309
+ promptChars: prompt.length,
2310
+ instructionsChars: promptInstructionsPrefix.length,
2311
+ bootstrapPromptChars: renderedBootstrapPrompt.length,
2312
+ wakePromptChars: wakePrompt.length,
2313
+ sessionHandoffChars: sessionHandoffNote.length,
2314
+ taskContextChars: taskContextNote.length,
2315
+ runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
2316
+ heartbeatPromptChars: renderedPrompt.length,
2317
+ },
2318
+ };
2319
+ }
2320
+ async function emitAcpxLog(ctx, payload) {
2321
+ await ctx.onLog("stdout", `${JSON.stringify(payload)}\n`);
2322
+ }
2323
+ /**
2324
+ * Build the short run summary that Paperclip may auto-post as an issue comment
2325
+ * when the agent leaves no comment of its own.
2326
+ *
2327
+ * Prefer the last non-empty *output* segment after a tool call. Intermediate
2328
+ * "let me check…" narration between tools must not become a 50k-char dump.
2329
+ * Thought-stream text is never included (callers must not push it into segments).
2330
+ */
2331
+ export function buildAcpxRunSummary(input) {
2332
+ for (let i = input.outputSegments.length - 1; i >= 0; i -= 1) {
2333
+ const text = (input.outputSegments[i] ?? "").trim();
2334
+ if (text)
2335
+ return text;
2336
+ }
2337
+ const fallback = (input.fallback ?? "").trim();
2338
+ return fallback;
2339
+ }
2340
+ // acpx substitutes a literal "tool call" title when an ACP tool_call_update
2341
+ // omits one, which would persist a generic name over the real one ("Terminal",
2342
+ // "Read", …) in the stored run log. Remember each call's real title so update
2343
+ // lines keep the name durably. Some ACP backends also stream partial tool
2344
+ // arguments as one in-progress update per token under this placeholder;
2345
+ // adapters that opt into coalescePlaceholderToolUpdates in their acpx config
2346
+ // have those updates coalesced until a real title is available.
2347
+ const GENERIC_ACP_TOOL_TITLE = "tool call";
2348
+ async function emitRuntimeEvent(ctx, event, toolTitles, coalescePlaceholderToolUpdates) {
2349
+ if (event.type === "text_delta") {
2350
+ await emitAcpxLog(ctx, {
2351
+ type: "acpx.text_delta",
2352
+ text: event.text,
2353
+ channel: event.stream === "thought" ? "thought" : "output",
2354
+ tag: event.tag,
2355
+ });
2356
+ return;
2357
+ }
2358
+ if (event.type === "tool_call") {
2359
+ // Coalesce token-by-token argument streaming for adapters that opt in via
2360
+ // their acpx config: skip in-progress updates that still carry only the
2361
+ // unresolved placeholder title. Backends that stream tool arguments
2362
+ // otherwise emit tens of thousands of these per run, flooding the
2363
+ // transcript and pinning the live activity indicator to a generic
2364
+ // "tool call" instead of the real tool. The initial pending event, the
2365
+ // resolved-title in-progress update, and the terminal
2366
+ // completed/failed/cancelled update all still flow through. Adapters that
2367
+ // do not opt in never have an event dropped.
2368
+ if (coalescePlaceholderToolUpdates &&
2369
+ event.status === "in_progress" &&
2370
+ (event.title ?? "").trim() === GENERIC_ACP_TOOL_TITLE) {
2371
+ return;
2372
+ }
2373
+ const eventRecord = event;
2374
+ const toolInput = eventRecord.input;
2375
+ let name = event.title ?? "acp_tool";
2376
+ const toolCallId = typeof event.toolCallId === "string" ? event.toolCallId : "";
2377
+ if (toolTitles && toolCallId) {
2378
+ if (event.title && event.title !== GENERIC_ACP_TOOL_TITLE) {
2379
+ // First real title is the call's identity; later retitles (ACP swaps
2380
+ // in the invocation, e.g. "Terminal" → "ls -la") keep their own line
2381
+ // but don't become the remembered name.
2382
+ if (!toolTitles.has(toolCallId))
2383
+ toolTitles.set(toolCallId, event.title);
2384
+ }
2385
+ else {
2386
+ name = toolTitles.get(toolCallId) ?? name;
2387
+ }
2388
+ }
2389
+ await emitAcpxLog(ctx, {
2390
+ type: "acpx.tool_call",
2391
+ name,
2392
+ toolCallId: event.toolCallId,
2393
+ status: event.status,
2394
+ text: event.text,
2395
+ tag: event.tag,
2396
+ ...(toolInput !== undefined ? { input: toolInput } : {}),
2397
+ });
2398
+ return;
2399
+ }
2400
+ if (event.type === "status") {
2401
+ await emitAcpxLog(ctx, {
2402
+ type: "acpx.status",
2403
+ text: event.text,
2404
+ tag: event.tag,
2405
+ used: event.used,
2406
+ size: event.size,
2407
+ ...(event.cost ? { cost: event.cost } : {}),
2408
+ ...(event.breakdown ? { breakdown: event.breakdown } : {}),
2409
+ });
2410
+ return;
2411
+ }
2412
+ if (event.type === "done") {
2413
+ await emitAcpxLog(ctx, {
2414
+ type: "acpx.result",
2415
+ summary: event.stopReason ?? "completed",
2416
+ stopReason: event.stopReason,
2417
+ });
2418
+ return;
2419
+ }
2420
+ if (event.type === "error") {
2421
+ await emitAcpxLog(ctx, {
2422
+ type: "acpx.error",
2423
+ message: event.message,
2424
+ code: event.code,
2425
+ retryable: event.retryable,
2426
+ });
2427
+ }
2428
+ }
2429
+ function resultErrorMessage(result) {
2430
+ if (result.status !== "failed")
2431
+ return null;
2432
+ return result.error.message;
2433
+ }
2434
+ function usageBreakdownsEqual(left, right) {
2435
+ return (asNumber(left.inputTokens, 0) === asNumber(right.inputTokens, 0) &&
2436
+ asNumber(left.outputTokens, 0) === asNumber(right.outputTokens, 0) &&
2437
+ asNumber(left.cachedReadTokens, 0) === asNumber(right.cachedReadTokens, 0) &&
2438
+ asNumber(left.cachedWriteTokens, 0) === asNumber(right.cachedWriteTokens, 0) &&
2439
+ asNumber(left.thoughtTokens, 0) === asNumber(right.thoughtTokens, 0) &&
2440
+ asNumber(left.totalTokens, 0) === asNumber(right.totalTokens, 0));
2441
+ }
2442
+ function usdCostAmount(cost) {
2443
+ if (!cost || typeof cost.amount !== "number" || !Number.isFinite(cost.amount))
2444
+ return null;
2445
+ if (cost.currency && cost.currency.trim().toUpperCase() !== "USD")
2446
+ return null;
2447
+ return cost.amount;
2448
+ }
2449
+ async function readRuntimeStatus(runtime, handle) {
2450
+ if (!runtime.getStatus)
2451
+ return null;
2452
+ try {
2453
+ return (await runtime.getStatus({ handle })) ?? null;
2454
+ }
2455
+ catch {
2456
+ return null;
2457
+ }
2458
+ }
2459
+ /**
2460
+ * Fold the ACP runtime's post-turn usage into the adapter execution result
2461
+ * shape. The runtime persists the latest turn's token breakdown (adapters like
2462
+ * claude-agent-acp report per-turn accumulated usage in the prompt response),
2463
+ * so tokens are per-run. Cost is reported by agents as a cumulative session
2464
+ * amount, so the per-run cost is the delta against the pre-turn snapshot; a
2465
+ * decrease means the agent process restarted and its counter reset, in which
2466
+ * case the post-turn amount alone covers this run.
2467
+ */
2468
+ export function summarizeAcpxTurnUsage(input) {
2469
+ // The persisted breakdown is overwritten per turn, so an unchanged value
2470
+ // is stale for this turn. Prefer an in-turn event breakdown when available;
2471
+ // otherwise suppress the stale value so it cannot be double-counted.
2472
+ const preBreakdown = input.preStatus?.usage?.cumulative ?? null;
2473
+ const postBreakdown = input.postStatus?.usage?.cumulative ?? null;
2474
+ const postBreakdownIsStale = preBreakdown != null &&
2475
+ postBreakdown != null &&
2476
+ usageBreakdownsEqual(preBreakdown, postBreakdown);
2477
+ const breakdown = postBreakdownIsStale
2478
+ ? input.eventBreakdown
2479
+ : postBreakdown ?? input.eventBreakdown ?? null;
2480
+ const inputTokens = Math.max(0, Math.floor(asNumber(breakdown?.inputTokens, 0)));
2481
+ const outputTokens = Math.max(0, Math.floor(asNumber(breakdown?.outputTokens, 0)));
2482
+ const cachedReadTokens = Math.max(0, Math.floor(asNumber(breakdown?.cachedReadTokens, 0)));
2483
+ const cachedWriteTokens = Math.max(0, Math.floor(asNumber(breakdown?.cachedWriteTokens, 0)));
2484
+ const hasTokens = inputTokens > 0 || outputTokens > 0 || cachedReadTokens > 0 || cachedWriteTokens > 0;
2485
+ // Cache-write tokens are prompt tokens the provider billed to create cache
2486
+ // entries; UsageSummary has no dedicated field, so count them as input.
2487
+ const usage = hasTokens
2488
+ ? {
2489
+ inputTokens: inputTokens + cachedWriteTokens,
2490
+ outputTokens,
2491
+ cachedInputTokens: cachedReadTokens,
2492
+ }
2493
+ : null;
2494
+ const usageDetail = breakdown
2495
+ ? Object.fromEntries(Object.entries({
2496
+ inputTokens: breakdown.inputTokens,
2497
+ outputTokens: breakdown.outputTokens,
2498
+ cachedReadTokens: breakdown.cachedReadTokens,
2499
+ cachedWriteTokens: breakdown.cachedWriteTokens,
2500
+ thoughtTokens: breakdown.thoughtTokens,
2501
+ totalTokens: breakdown.totalTokens,
2502
+ }).filter((entry) => typeof entry[1] === "number"))
2503
+ : null;
2504
+ const previousCostUsd = usdCostAmount(input.preStatus?.usage?.cost);
2505
+ const postCostUsd = usdCostAmount(input.postStatus?.usage?.cost);
2506
+ const postCostIsStale = input.eventCostUsd != null &&
2507
+ previousCostUsd != null &&
2508
+ postCostUsd != null &&
2509
+ postCostUsd === previousCostUsd;
2510
+ const cumulativeCostUsd = postCostIsStale ? input.eventCostUsd : postCostUsd ?? input.eventCostUsd;
2511
+ let costUsd = null;
2512
+ if (cumulativeCostUsd != null) {
2513
+ costUsd =
2514
+ previousCostUsd != null && cumulativeCostUsd >= previousCostUsd
2515
+ ? cumulativeCostUsd - previousCostUsd
2516
+ : cumulativeCostUsd;
2517
+ }
2518
+ return { usage, usageDetail, costUsd, cumulativeCostUsd };
2519
+ }
2520
+ function describeErrorDiagnostics(err) {
2521
+ const errorName = err instanceof Error ? err.name || err.constructor.name : typeof err;
2522
+ const maybeCode = err && typeof err === "object" && typeof err.code === "string"
2523
+ ? err.code
2524
+ : null;
2525
+ const acpCode = isAcpRuntimeError(err) || (maybeCode?.startsWith("ACP_") ?? false) ? maybeCode : null;
2526
+ const cause = err && typeof err === "object" && err.cause !== undefined
2527
+ ? err.cause
2528
+ : undefined;
2529
+ const causeMessage = cause instanceof Error
2530
+ ? cause.message
2531
+ : typeof cause === "string"
2532
+ ? cause
2533
+ : null;
2534
+ const retryable = err && typeof err === "object" && typeof err.retryable === "boolean"
2535
+ ? err.retryable
2536
+ : null;
2537
+ const stack = err instanceof Error && typeof err.stack === "string" ? err.stack : "";
2538
+ const stackPreview = stack ? stack.split("\n").slice(0, 6).join("\n") : null;
2539
+ return { errorName, acpCode, causeMessage, retryable, stackPreview };
2540
+ }
2541
+ function classifyError(err, phase) {
2542
+ const message = err instanceof Error ? err.message : String(err);
2543
+ const diagnostics = describeErrorDiagnostics(err);
2544
+ const { acpCode, errorName, causeMessage, retryable, stackPreview } = diagnostics;
2545
+ const baseMeta = {
2546
+ errorName,
2547
+ ...(acpCode ? { acpCode } : {}),
2548
+ ...(causeMessage ? { causeMessage } : {}),
2549
+ ...(retryable !== null ? { retryable } : {}),
2550
+ ...(stackPreview ? { stackPreview } : {}),
2551
+ ...(phase ? { phase } : {}),
2552
+ };
2553
+ // A host-generated handshake-guard error is classified by its type, never
2554
+ // by message text, and runs before the message-driven heuristics below. A
2555
+ // startup timeout or a duplex control-channel loss must report its own
2556
+ // closed code, not the generic session-identity failure `phase ===
2557
+ // "ensure_session"` would otherwise produce a few lines down.
2558
+ if (isAcpxHandshakeTimeoutError(err)) {
2559
+ return {
2560
+ errorCode: "acpx_handshake_timeout",
2561
+ errorMeta: { category: "runtime", ...baseMeta },
2562
+ };
2563
+ }
2564
+ if (isAcpxHandshakeTransportLostError(err)) {
2565
+ return {
2566
+ errorCode: "acpx_handshake_transport_lost",
2567
+ errorMeta: { category: "runtime", ...baseMeta },
2568
+ };
2569
+ }
2570
+ const lower = message.toLowerCase();
2571
+ const authLike = lower.includes("auth") || lower.includes("login") || lower.includes("credential");
2572
+ if (authLike) {
2573
+ return {
2574
+ errorCode: "acpx_auth_required",
2575
+ errorMeta: { category: "auth", ...baseMeta },
2576
+ };
2577
+ }
2578
+ const phaseCode = (() => {
2579
+ if (acpCode === "ACP_SESSION_INIT_FAILED")
2580
+ return "acpx_session_init_failed";
2581
+ if (acpCode === "ACP_TURN_FAILED")
2582
+ return "acpx_turn_failed";
2583
+ if (acpCode === "ACP_BACKEND_MISSING")
2584
+ return "acpx_backend_missing";
2585
+ if (acpCode === "ACP_BACKEND_UNAVAILABLE")
2586
+ return "acpx_backend_unavailable";
2587
+ if (phase === "ensure_session")
2588
+ return "acpx_session_init_failed";
2589
+ if (phase === "configure_session")
2590
+ return "acpx_session_config_failed";
2591
+ if (phase === "turn")
2592
+ return "acpx_turn_failed";
2593
+ return null;
2594
+ })();
2595
+ if (phaseCode) {
2596
+ return {
2597
+ errorCode: phaseCode,
2598
+ errorMeta: { category: acpCode ? "protocol" : "runtime", ...baseMeta },
2599
+ };
2600
+ }
2601
+ if (acpCode) {
2602
+ return {
2603
+ errorCode: "acpx_protocol_error",
2604
+ errorMeta: { category: "protocol", ...baseMeta },
2605
+ };
2606
+ }
2607
+ return {
2608
+ errorCode: "acpx_runtime_error",
2609
+ errorMeta: { category: "runtime", ...baseMeta },
2610
+ };
2611
+ }
2612
+ async function readChildStderrTail(input) {
2613
+ if (!input.logPath)
2614
+ return null;
2615
+ const maxBytes = input.maxBytes ?? 4096;
2616
+ let handle = null;
2617
+ try {
2618
+ const stat = await fs.stat(input.logPath);
2619
+ if (stat.size === 0)
2620
+ return null;
2621
+ handle = await fs.open(input.logPath, "r");
2622
+ const readBytes = Math.min(stat.size, maxBytes);
2623
+ const buffer = Buffer.alloc(readBytes);
2624
+ await handle.read(buffer, 0, readBytes, Math.max(0, stat.size - readBytes));
2625
+ const tail = buffer.toString("utf8").trim();
2626
+ return tail.length > 0 ? tail : null;
2627
+ }
2628
+ catch {
2629
+ return null;
2630
+ }
2631
+ finally {
2632
+ if (handle)
2633
+ await handle.close().catch(() => { });
2634
+ }
2635
+ }
2636
+ async function emitAcpxFailure(input) {
2637
+ const { ctx, prepared, err, phase, messageOverride, suppressChildStderrTail } = input;
2638
+ const rawMessage = err instanceof Error ? err.message : String(err);
2639
+ const message = messageOverride ?? rawMessage;
2640
+ const classified = classifyError(err, phase);
2641
+ const childStderrTail = suppressChildStderrTail
2642
+ ? null
2643
+ : await readChildStderrTail({ logPath: prepared.childStderrLogPath });
2644
+ if (childStderrTail) {
2645
+ await ctx.onLog("stderr", `[paperclip] ACPX child stderr tail (${phase}):\n${childStderrTail}\n`);
2646
+ }
2647
+ await emitAcpxLog(ctx, {
2648
+ type: "acpx.error",
2649
+ message,
2650
+ phase,
2651
+ ...classified.errorMeta,
2652
+ ...(childStderrTail ? { childStderrTail } : {}),
2653
+ });
2654
+ return { classified, message, childStderrTail };
2655
+ }
2656
+ function isResumeFailure(err) {
2657
+ const message = err instanceof Error ? err.message : String(err);
2658
+ return /resume|load|not found|no session|unknown session|conversation/i.test(message);
2659
+ }
2660
+ // Drop staged-runtime entries the session has not touched within the warm-idle
2661
+ // window, so the cache does not accumulate abandoned sessions (e.g. every time
2662
+ // a config change shifts the fingerprint to a new key). The per-run copy-back
2663
+ // already ran on the entry's last run's settlement `syncBack`; eviction fires
2664
+ // the entry's one-time `dispose` (host staged-temp cleanup) — the only place
2665
+ // the staged temp is removed now that it no longer rides the per-run teardown.
2666
+ // A later run of the same session simply re-stages fresh (re-shipping into the
2667
+ // still-persistent sandbox, which the inbound monotonic auth-merge keeps safe).
2668
+ async function cleanupIdleStagedRuntimes(input) {
2669
+ if (input.idleMs <= 0)
2670
+ return;
2671
+ const stale = [];
2672
+ for (const entry of input.handles.entries()) {
2673
+ if (input.now() - entry[1].lastUsedAt >= input.idleMs)
2674
+ stale.push(entry);
2675
+ }
2676
+ for (const [key, entry] of stale) {
2677
+ const lease = await withSessionStagingLease(input.locks, key, async () => {
2678
+ const current = input.handles.get(key);
2679
+ if (current !== entry)
2680
+ return;
2681
+ if (input.now() - current.lastUsedAt < input.idleMs)
2682
+ return;
2683
+ input.handles.delete(key);
2684
+ if (entry.dispose)
2685
+ await entry.dispose().catch(() => { });
2686
+ });
2687
+ lease.release();
2688
+ }
2689
+ }
2690
+ // Persist a remote runner-backed session's staged runtime for reuse on the next
2691
+ // compatible resume. Called ONLY after a clean turn, so the cache never offers a
2692
+ // half-staged or failed session for reuse. Non-remote lanes carry a null
2693
+ // stagedRuntime / null envDelta and are skipped.
2694
+ function saveStagedRuntimeAfterCleanTurn(input) {
2695
+ const { prepared } = input;
2696
+ if (!prepared.stagedRuntime || prepared.remoteStagingEnvDelta === null)
2697
+ return;
2698
+ input.handles.set(prepared.sessionKey, {
2699
+ stagedRuntime: prepared.stagedRuntime,
2700
+ envDelta: prepared.remoteStagingEnvDelta,
2701
+ teardown: prepared.remoteManagedHomeTeardown,
2702
+ dispose: prepared.remoteStagingDispose,
2703
+ lastUsedAt: input.now,
2704
+ });
2705
+ }
2706
+ // Drop the staged-runtime entry a finished run owns and release its host-side
2707
+ // staged resources. Two guards make this safe under overlapping runs of the same
2708
+ // session key (PR 3 fix — "Concurrent Runs Corrupt Cache Ownership"):
2709
+ // 1. Ownership guard: only delete the map entry when it is still the exact
2710
+ // staged runtime THIS run installed/reused (object identity). A concurrent
2711
+ // run that installed a different clean entry keeps it — a failed run can no
2712
+ // longer evict another run's good cache entry.
2713
+ // 2. `dispose` is fired for THIS run's own staged resources regardless, so a
2714
+ // failed/cancelled run always frees its own staged temp. `dispose` is
2715
+ // idempotent, so a shared closure re-fired across a reuse chain is safe.
2716
+ async function discardStagedRuntime(input) {
2717
+ const { handles, prepared } = input;
2718
+ await releaseStagedRuntimeEntry({
2719
+ handles,
2720
+ sessionKey: prepared.sessionKey,
2721
+ stagedRuntime: prepared.stagedRuntime,
2722
+ dispose: prepared.remoteStagingDispose,
2723
+ });
2724
+ }
2725
+ // Ownership-guarded removal + dispose for a staged-runtime cache entry a run owns.
2726
+ // Shared by `discardStagedRuntime` (clean-run drop) and the partial-bring-up
2727
+ // rollback so both release a borrowed entry the same way:
2728
+ // 1. Delete the map entry ONLY when it still holds the exact staged runtime this
2729
+ // run installed or reused (object identity). A concurrent run that replaced
2730
+ // the entry with its own keeps it.
2731
+ // 2. Fire this run's own one-time host staged-temp dispose regardless. The
2732
+ // dispose closure is idempotent, so a shared closure re-fired across a reuse
2733
+ // chain is safe.
2734
+ async function releaseStagedRuntimeEntry(input) {
2735
+ const { handles, sessionKey, stagedRuntime, dispose } = input;
2736
+ const existing = handles.get(sessionKey);
2737
+ if (existing && stagedRuntime && existing.stagedRuntime === stagedRuntime) {
2738
+ handles.delete(sessionKey);
2739
+ }
2740
+ if (dispose)
2741
+ await dispose().catch(() => { });
2742
+ }
2743
+ // Per-`sessionKey` async lease: chains each caller after the previous one so
2744
+ // the stage-or-reuse decision for a session runs serially, then keeps the
2745
+ // lease held until the active turn finishes and bridge cleanup runs. That means
2746
+ // overlapping runs of the same session can never stage fresh into the same
2747
+ // remote workspace while a prior turn is still using it: the loser waits, then
2748
+ // re-checks the cache before deciding to reuse or re-stage.
2749
+ async function withSessionStagingLease(locks, key, fn) {
2750
+ const prev = locks.get(key) ?? Promise.resolve();
2751
+ let releaseGate;
2752
+ const gate = new Promise((resolve) => {
2753
+ releaseGate = resolve;
2754
+ });
2755
+ // The next waiter's `prev` is this promise; it settles only once we release
2756
+ // the gate below, so callers run one at a time.
2757
+ const mine = prev.then(() => gate);
2758
+ locks.set(key, mine);
2759
+ await prev.catch(() => { });
2760
+ let released = false;
2761
+ const release = () => {
2762
+ if (released)
2763
+ return;
2764
+ released = true;
2765
+ releaseGate();
2766
+ // GC the lock if no later caller has chained after us.
2767
+ if (locks.get(key) === mine)
2768
+ locks.delete(key);
2769
+ };
2770
+ try {
2771
+ return { value: await fn(), release };
2772
+ }
2773
+ catch (error) {
2774
+ if (!released)
2775
+ release();
2776
+ throw error;
2777
+ }
2778
+ }
2779
+ function clearWarmHandleTimer(entry) {
2780
+ if (!entry.cleanupTimer)
2781
+ return;
2782
+ clearTimeout(entry.cleanupTimer);
2783
+ entry.cleanupTimer = undefined;
2784
+ }
2785
+ async function closeWarmHandle(input) {
2786
+ if (input.handles.get(input.key) === input.entry) {
2787
+ input.handles.delete(input.key);
2788
+ }
2789
+ clearWarmHandleTimer(input.entry);
2790
+ const stopped = await input.entry.runtime.close({
2791
+ handle: input.entry.handle,
2792
+ reason: input.reason,
2793
+ discardPersistentState: input.discardPersistentState ?? false,
2794
+ }).then(() => true, () => false);
2795
+ flushChildStderr(input.entry.childStderrState);
2796
+ return stopped;
2797
+ }
2798
+ function warmHandleMatches(entry, runtime, handle) {
2799
+ return entry !== undefined && entry.runtime === runtime && entry.handle === handle;
2800
+ }
2801
+ /** The stable name of the one root span for a sandbox bring-up. It is a fixed
2802
+ * low-cardinality constant, never derived from run/user data. */
2803
+ const STARTUP_ROOT_SPAN_NAME = "sandbox.startup";
2804
+ /** The shared batch tag for the two parallel bridge steps. It is a fixed
2805
+ * low-cardinality literal, so it marks the two spans as one batch without
2806
+ * carrying run or user data. */
2807
+ const STARTUP_BRIDGE_BATCH = "bridge";
2808
+ /**
2809
+ * Open the one root span for a sandbox bring-up and return its parent-context
2810
+ * token plus a guarded `end`. The span parents to the run root span through
2811
+ * `runParentContext`, so `sandbox.startup` becomes a child of `task.run`. The
2812
+ * span then parents every startup boundary span in turn: the engine forwards
2813
+ * `parentContext` to each `measureStartupStep` call. The `end` closure runs at
2814
+ * most once (bring-up complete OR a bring-up failure) and swallows every tracer
2815
+ * error, so observability never changes startup control flow. With no injected
2816
+ * trace context, the tracer is a no-op and the span is a no-op.
2817
+ */
2818
+ function openStartupRootSpan(tracing, nowMs,
2819
+ // The run root span parent context. `sandbox.startup` opens as a child of it,
2820
+ // so the whole bring-up parents to `task.run`. It is an opaque token here.
2821
+ runParentContext,
2822
+ // Return the final root-span numbers and context at end time. The work sum
2823
+ // and the cold-start flag are known only after the bring-up runs, so the
2824
+ // caller reads them lazily here.
2825
+ finalize) {
2826
+ let span;
2827
+ try {
2828
+ span = tracing.tracer.startSpan(STARTUP_ROOT_SPAN_NAME, undefined, runParentContext);
2829
+ }
2830
+ catch {
2831
+ span = NOOP_STARTUP_SPAN;
2832
+ }
2833
+ let parentContext;
2834
+ try {
2835
+ parentContext = tracing.contextWithSpan(span);
2836
+ }
2837
+ catch {
2838
+ parentContext = undefined;
2839
+ }
2840
+ const startedAtMs = nowMs();
2841
+ let ended = false;
2842
+ return {
2843
+ parentContext,
2844
+ end: (failed) => {
2845
+ if (ended)
2846
+ return;
2847
+ ended = true;
2848
+ try {
2849
+ // The root span records its own wall time, the step-work sum, and the
2850
+ // bounded context. `setSandboxRootSpanAttributes` sets only the closed
2851
+ // allowlist, so no raw id or image reference rides the span.
2852
+ const { workMs, context } = finalize();
2853
+ setSandboxRootSpanAttributes(span, { wallMs: nowMs() - startedAtMs, workMs }, context);
2854
+ // `2` is `SpanStatusCode.ERROR`. `adapter-utils` stays OTel-free, so it
2855
+ // uses the numeric value that a real injected span reads as the error
2856
+ // status.
2857
+ if (failed)
2858
+ span.setStatus({ code: 2 });
2859
+ span.end();
2860
+ }
2861
+ catch {
2862
+ // Observability must not change startup control flow.
2863
+ }
2864
+ },
2865
+ };
2866
+ }
2867
+ /** The stable name of the one root span for a whole run. It is a fixed
2868
+ * low-cardinality constant, never derived from run or user data. */
2869
+ const RUN_ROOT_SPAN_NAME = "task.run";
2870
+ /** The stable name of the one span for the agent turn. It is a fixed
2871
+ * low-cardinality constant, never derived from run or user data. The turn span
2872
+ * is a child of the run root span. */
2873
+ const TURN_SPAN_NAME = "agent.turn";
2874
+ /** The attribute prefix for the run root span. It groups the run-level span
2875
+ * attributes under one namespace, the same shape as the sandbox startup
2876
+ * prefix. */
2877
+ const RUN_ROOT_SPAN_ATTR_PREFIX = "paperclip.task.run.";
2878
+ /** The attribute prefix for the agent turn span. It groups the turn-level span
2879
+ * attributes under one namespace, the same shape as the run root prefix. */
2880
+ const TURN_SPAN_ATTR_PREFIX = "paperclip.agent.turn.";
2881
+ /** Map a run id to a non-reversible 12-hex hash for a span attribute. The raw
2882
+ * run id never rides a span; only this hash does. This mirrors the id-hash rule
2883
+ * that `clampSpanLabel` uses for the startup ids. */
2884
+ function hashRunId(runId) {
2885
+ return createHash("sha256").update(runId).digest("hex").slice(0, 12);
2886
+ }
2887
+ /**
2888
+ * Open the one root span for a whole run and return its parent-context token
2889
+ * plus a guarded `end`. The run root span is the trace root: the sandbox
2890
+ * bring-up span (`sandbox.startup`) parents to it, so the engine forwards
2891
+ * `parentContext` into `openStartupRootSpan`. The `end` closure runs at most
2892
+ * once and swallows every tracer error, so observability never changes run
2893
+ * control flow. With no injected trace context the tracer is a no-op and the
2894
+ * span is a no-op.
2895
+ *
2896
+ * The span carries only a bounded, non-reversible run-id hash and its own wall
2897
+ * time. It never carries the prompt, the command, or any user text, so no raw
2898
+ * run text rides the span. This follows the same allowlist rule as
2899
+ * `openStartupRootSpan`.
2900
+ */
2901
+ function openRunRootSpan(tracing, nowMs, runId) {
2902
+ let span;
2903
+ try {
2904
+ span = tracing.tracer.startSpan(RUN_ROOT_SPAN_NAME);
2905
+ }
2906
+ catch {
2907
+ span = NOOP_STARTUP_SPAN;
2908
+ }
2909
+ let parentContext;
2910
+ try {
2911
+ parentContext = tracing.contextWithSpan(span);
2912
+ }
2913
+ catch {
2914
+ parentContext = undefined;
2915
+ }
2916
+ const startedAtMs = nowMs();
2917
+ let ended = false;
2918
+ return {
2919
+ parentContext,
2920
+ end: (failed) => {
2921
+ if (ended)
2922
+ return;
2923
+ ended = true;
2924
+ try {
2925
+ // The run id rides only as a non-reversible short hash, never as the raw
2926
+ // id. The wall time is a plain duration. No raw run text rides the span.
2927
+ span.setAttribute(`${RUN_ROOT_SPAN_ATTR_PREFIX}run_id`, hashRunId(runId));
2928
+ span.setAttribute(`${RUN_ROOT_SPAN_ATTR_PREFIX}wall_ms`, nowMs() - startedAtMs);
2929
+ // `2` is `SpanStatusCode.ERROR`. `adapter-utils` stays OTel-free, so it
2930
+ // uses the numeric value that a real injected span reads as the error
2931
+ // status.
2932
+ if (failed)
2933
+ span.setStatus({ code: 2 });
2934
+ span.end();
2935
+ }
2936
+ catch {
2937
+ // Observability must not change run control flow.
2938
+ }
2939
+ },
2940
+ };
2941
+ }
2942
+ /**
2943
+ * Open the one span for the agent turn and return its parent-context token plus
2944
+ * a guarded `end`. The span parents to the run root span through
2945
+ * `runParentContext`, so `agent.turn` becomes a child of `task.run`. The
2946
+ * executor holds the returned `parentContext` for later exec parenting. The
2947
+ * `end` closure runs at most once and swallows every tracer error, so
2948
+ * observability never changes turn control flow. With no injected trace context
2949
+ * the tracer is a no-op and the span is a no-op.
2950
+ *
2951
+ * The span carries only its own wall time. It never carries the prompt, the
2952
+ * command, or any user text, so no raw run text rides the span. This follows the
2953
+ * same allowlist rule as `openStartupRootSpan`.
2954
+ */
2955
+ function openTurnSpan(tracing, nowMs,
2956
+ // The run root span parent context. `agent.turn` opens as a child of it, so
2957
+ // the turn parents to `task.run`. It is an opaque token here.
2958
+ runParentContext) {
2959
+ let span;
2960
+ try {
2961
+ span = tracing.tracer.startSpan(TURN_SPAN_NAME, undefined, runParentContext);
2962
+ }
2963
+ catch {
2964
+ span = NOOP_STARTUP_SPAN;
2965
+ }
2966
+ let parentContext;
2967
+ try {
2968
+ parentContext = tracing.contextWithSpan(span);
2969
+ }
2970
+ catch {
2971
+ parentContext = undefined;
2972
+ }
2973
+ const startedAtMs = nowMs();
2974
+ let ended = false;
2975
+ return {
2976
+ parentContext,
2977
+ end: (failed) => {
2978
+ if (ended)
2979
+ return;
2980
+ ended = true;
2981
+ try {
2982
+ // The wall time is a plain duration. No raw run text rides the span.
2983
+ span.setAttribute(`${TURN_SPAN_ATTR_PREFIX}wall_ms`, nowMs() - startedAtMs);
2984
+ // `2` is `SpanStatusCode.ERROR`. `adapter-utils` stays OTel-free, so it
2985
+ // uses the numeric value that a real injected span reads as the error
2986
+ // status.
2987
+ if (failed)
2988
+ span.setStatus({ code: 2 });
2989
+ span.end();
2990
+ }
2991
+ catch {
2992
+ // Observability must not change turn control flow.
2993
+ }
2994
+ },
2995
+ };
2996
+ }
2997
+ export function createAcpxEngineExecutor(deps = {}) {
2998
+ const createRuntime = deps.createRuntime ?? createAcpRuntime;
2999
+ const now = deps.now ?? (() => Date.now());
3000
+ const duplexLossCancelDeadlineMs = deps.duplexLossCancelDeadlineMs ?? ACPX_DUPLEX_LOSS_CANCEL_DEADLINE_MS;
3001
+ const warmHandles = deps.warmHandles ?? defaultWarmHandles;
3002
+ const stagedRuntimes = deps.stagedRuntimes ?? defaultStagedRuntimes;
3003
+ const stagingLocks = deps.stagingLocks ?? defaultStagingLocks;
3004
+ const engine = resolveEngineSettings(deps);
3005
+ return async function executeAcpxEngine(ctx) {
3006
+ let billingIdentity = null;
3007
+ try {
3008
+ billingIdentity = (await deps.resolveBillingIdentity?.(ctx)) ?? null;
3009
+ }
3010
+ catch {
3011
+ billingIdentity = null;
3012
+ }
3013
+ const billingFields = {
3014
+ provider: billingIdentity?.provider ?? "acpx",
3015
+ ...(billingIdentity?.biller ? { biller: billingIdentity.biller } : {}),
3016
+ billingType: billingIdentity?.billingType ?? "unknown",
3017
+ pricingContext: undefined,
3018
+ };
3019
+ const warmIdleMs = asNumber(ctx.config.warmHandleIdleMs, DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS);
3020
+ // The host run site owns the warm-handle store on this run. It operates over
3021
+ // the engine's persistent `warmHandles` map, so a warm runtime stays live for
3022
+ // the next compatible resume. The store arms the per-entry idle timer on a
3023
+ // warm save, sweeps idle entries at run start, and closes a released entry
3024
+ // through `closeWarmEntry`. The run reads `warmHandleIdleMs` per run, so the
3025
+ // site takes this run's bound.
3026
+ const hostSite = createHostRunSite({
3027
+ warmHandles,
3028
+ now,
3029
+ idleMs: warmIdleMs,
3030
+ closeWarmEntry: async (entry) => {
3031
+ await entry.runtime
3032
+ .close({ handle: entry.handle, reason: "paperclip idle cleanup", discardPersistentState: false })
3033
+ .catch(() => { });
3034
+ flushChildStderr(entry.childStderrState);
3035
+ },
3036
+ });
3037
+ const hostStore = hostSite.reuse();
3038
+ // The `task.run` and `sandbox.startup` spans must not cover a local or SSH
3039
+ // run: those runs have no sandbox, so they stay out of sandbox telemetry.
3040
+ // Open a real root span only when the target is a remote sandbox and the
3041
+ // server injected a trace context; every other target forces the no-op
3042
+ // trace context, so the whole span path stays inert.
3043
+ const startupExecutionTarget = readAdapterExecutionTarget({
3044
+ executionTarget: ctx.executionTarget,
3045
+ legacyRemoteExecution: ctx.executionTransport?.remoteExecution,
3046
+ });
3047
+ const sandboxTarget = startupExecutionTarget?.kind === "remote" && startupExecutionTarget.transport === "sandbox"
3048
+ ? startupExecutionTarget
3049
+ : null;
3050
+ const targetsRemoteSandbox = sandboxTarget !== null;
3051
+ const tracing = targetsRemoteSandbox && ctx.startupTraceContext
3052
+ ? ctx.startupTraceContext
3053
+ : NOOP_STARTUP_TRACE_CONTEXT;
3054
+ // Open the one run root span at the engine first line, before any bring-up
3055
+ // work. It is the trace root for the whole run: the sandbox bring-up and the
3056
+ // agent turn parent to it. The engine forwards its parent context into the
3057
+ // startup span. `runRootSpan.end` runs exactly once, in the `finally` below,
3058
+ // on every return and on a throw.
3059
+ const runRootSpan = openRunRootSpan(tracing, now, ctx.runId);
3060
+ // Hold the current-run parent-context token for the whole run. It starts as
3061
+ // the `task.run` token, switches to the `agent.turn` token during the turn,
3062
+ // and switches back to the `task.run` token after the turn. It is never
3063
+ // `undefined` while the run is live. The holder is a run-scoped local, so two
3064
+ // concurrent runs in one host process keep separate tokens. A detached exec
3065
+ // reads it through `getRuntimeParentContext` to parent to the live span.
3066
+ let currentRunParentContext = runRootSpan.parentContext;
3067
+ const getRuntimeParentContext = () => currentRunParentContext;
3068
+ // Wrap each unit of bridge run-time work (one outbound ACP message, one poll
3069
+ // tick, one callback request) in its own named span, parented to the live run
3070
+ // span. The runner reads the run parent per call through
3071
+ // `getRuntimeParentContext`, so a wrapper span always parents to the current
3072
+ // run span. On a no-op trace context the runner opens no real span.
3073
+ const runRuntimeSpan = createRuntimeSpanRunner(tracing, getRuntimeParentContext);
3074
+ // Wrap the host workspace tarball build in one `pack` span. This runner
3075
+ // parents each span to the ACTIVE startup step (not the run span), so the
3076
+ // `pack` span nests under the `stage.sync` step that runs the staging seam.
3077
+ // The staging seam runs inside `stage.sync`'s measured step, so
3078
+ // `getActiveStepContext()` returns that step's child context at pack time.
3079
+ // On a no-op trace context the runner opens no real span.
3080
+ const runStageSpan = createRuntimeSpanRunner(tracing, () => getActiveStepContext()?.parentContext);
3081
+ // `runFailed` marks the run root span status at end time. It stays `true`
3082
+ // until the run reaches a clean completed turn, so every failure and every
3083
+ // early exit closes the span with error status.
3084
+ let runFailed = true;
3085
+ // The run's per-session staging lease release. `buildRuntime` returns it on
3086
+ // `prepared` after it acquires the lease; the startup step captures it here so
3087
+ // the run root `finally` can release it as the final settlement act. It stays
3088
+ // null on the host lane (no staging) and on a build failure (where
3089
+ // `buildRuntime` already released its own partial lease).
3090
+ let releaseStagingLease = null;
3091
+ let stopTimer;
3092
+ let removeStopListener;
3093
+ // Unregisters the sandbox duplex bridge's loss listener (below, in
3094
+ // `stepTurnStart`). Set only on a sandbox target whose bridge exposes
3095
+ // `onLoss`; stays undefined everywhere else, so the cleanup call is a
3096
+ // no-op there.
3097
+ let removeLossListener;
3098
+ // Bounds the wait after a latched terminal duplex loss so a silent agent
3099
+ // cannot hold the run open on the cooperative `turn.cancel()` request
3100
+ // alone. `stepTurnStart` arms `lossDeadlineTimer` the moment a loss
3101
+ // latches; it stays undefined everywhere else, so the cleanup call below
3102
+ // is a no-op there. `stepEventRelay` races the turn against
3103
+ // `lossDeadline` and, once it fires, ends the event drain and hands
3104
+ // `turnFinalize` a host-built terminal instead of the agent's.
3105
+ let lossDeadlineTimer;
3106
+ let lossDeadlineTripped = false;
3107
+ let resolveLossDeadline;
3108
+ const lossDeadline = new Promise((resolve) => {
3109
+ resolveLossDeadline = resolve;
3110
+ });
3111
+ let forcedStop = false;
3112
+ let runtimeStopConfirmed = false;
3113
+ let safeInterruptedSession = false;
3114
+ let preserveInterruptedSession = false;
3115
+ const interruptionTools = new Map();
3116
+ let incompleteToolInventory = false;
3117
+ try {
3118
+ await ctx.onCancellationReady?.();
3119
+ if (ctx.signal?.aborted)
3120
+ return {
3121
+ exitCode: null, signal: null, timedOut: false,
3122
+ errorCode: "cancelled", errorMessage: "Stopped before provider startup",
3123
+ executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
3124
+ resultJson: { executionCancellation: { state: "acknowledged", acknowledgedAt: new Date().toISOString(), forced: false } },
3125
+ };
3126
+ // Evict idle staged runtimes BEFORE building the runtime, since buildRuntime
3127
+ // consults the staged cache to decide whether a compatible resume may reuse
3128
+ // an already-staged runtime — an expired entry must not be reused.
3129
+ await cleanupIdleStagedRuntimes({
3130
+ handles: stagedRuntimes,
3131
+ locks: stagingLocks,
3132
+ now,
3133
+ idleMs: warmIdleMs,
3134
+ });
3135
+ // The sum of the step wall times. The root span records it as `root.work_ms`
3136
+ // and the difference from its own wall time as `root.diff_ms` (the overlap
3137
+ // the parallel steps saved). Every step reports its wall time through
3138
+ // `onWallMs`; a skipped step adds zero.
3139
+ let stepWallSumMs = 0;
3140
+ // Whether this bring-up is a cold start (no warm handle). Set once the warm-
3141
+ // handle lookup runs below; it stays undefined on an early build failure, so
3142
+ // the root span omits the attribute (fail open).
3143
+ let coldStart;
3144
+ const rootSpan = openStartupRootSpan(tracing, now, runRootSpan.parentContext, () => ({
3145
+ workMs: stepWallSumMs,
3146
+ context: {
3147
+ coldStart,
3148
+ // The provider key and the lease id are the only low-cardinality
3149
+ // context values this provider-agnostic layer holds. The region, the
3150
+ // image id, and the sandbox id are not threaded here, so the root span
3151
+ // omits them (fail open). The lease id rides only as a hash.
3152
+ provider: sandboxTarget?.providerKey ?? undefined,
3153
+ leaseId: sandboxTarget?.leaseId ?? undefined,
3154
+ },
3155
+ }));
3156
+ const spanParent = {
3157
+ tracer: tracing.tracer,
3158
+ parentContext: rootSpan.parentContext,
3159
+ // Each step uses this to publish its own child context, so an inner exec
3160
+ // span parents to the step span, not to the root.
3161
+ contextWithSpan: (span) => tracing.contextWithSpan(span),
3162
+ // Accumulate each step wall time into the root work sum.
3163
+ onWallMs: (wallMs) => {
3164
+ stepWallSumMs += wallMs;
3165
+ },
3166
+ };
3167
+ // `startupFailed` drives the sandbox.startup span end status. It stays true
3168
+ // until the bring-up establishes a session handle. The one `finally` below
3169
+ // ends the span exactly once, on every return and on every throw.
3170
+ let startupFailed = true;
3171
+ // `buildRuntimeSettled` marks that buildRuntime returned. A failure before it
3172
+ // settled has nothing to settle here; a failure after it settled routes
3173
+ // through the create_runtime handler below.
3174
+ let buildRuntimeSettled = false;
3175
+ // The bring-up assigns these. The turn and teardown paths read them after
3176
+ // the sandbox.startup span closes, so they are declared here.
3177
+ let prepared;
3178
+ let runtime;
3179
+ let sessionHandle;
3180
+ let childStderrState;
3181
+ let processIdentitySink;
3182
+ let resumedSession = false;
3183
+ let clearSession = false;
3184
+ let referencedProjectStagingFailuresField = {};
3185
+ // Set only when the settlement sync-back reports a failed workspace
3186
+ // restore. `reproduceResult` merges this into the returned result's
3187
+ // `resultJson`, so a clean run adds no new key. The run's exit code and
3188
+ // status stay exactly what the turn produced — this is a signal, not an
3189
+ // outcome change.
3190
+ let workspaceRestoreFailureField = {};
3191
+ // The one settlement step name whose error can be the same workspace-
3192
+ // restore failure the adapter teardown closure already classifies (a
3193
+ // caught error from `syncBackManagedHome`). The closure already
3194
+ // sanitizes its own `onLog` line; this is a second, independent layer,
3195
+ // so a defect in that closure (or a future call site that forgets to
3196
+ // sanitize) still cannot put a raw `Error.message` — and the host path
3197
+ // or process id it can carry — on the run log.
3198
+ const SYNC_BACK_SETTLEMENT_STEP = "settlement-sync_back";
3199
+ const recordTeardownError = async (step, teardownErr) => {
3200
+ const reason = step === SYNC_BACK_SETTLEMENT_STEP
3201
+ ? describeWorkspaceRestoreFailure(classifyWorkspaceRestoreFailure(teardownErr))
3202
+ : teardownErr instanceof Error
3203
+ ? teardownErr.message
3204
+ : String(teardownErr);
3205
+ await withAdapterExecutionPhase(ctx, "phase_reporting", () => ctx
3206
+ .onLog("stderr", `[paperclip] ACPX teardown step "${step}" failed: ${reason}\n`)
3207
+ .catch(() => { }));
3208
+ };
3209
+ // Emit one per-phase timing run-log event. It is not an OpenTelemetry
3210
+ // export and it is not a Telemetry event: it carries the phase name
3211
+ // (from the closed allowlist), the wall time, and the outcome, and
3212
+ // never a command, a path, an environment value, or an identifier. A
3213
+ // failure to emit this event never fails the run.
3214
+ const emitPhase = (phase, startMs, outcome) => emitRunPhaseTiming(ctx, phase, now() - startMs, outcome);
3215
+ // Time a settlement step and emit its phase timing on every path. A step
3216
+ // error still emits `failed` before it re-throws to the Phase 3 error policy.
3217
+ const timedPhase = async (phase, run) => {
3218
+ const start = now();
3219
+ try {
3220
+ await withAdapterExecutionPhase(ctx, phase, run);
3221
+ }
3222
+ catch (error) {
3223
+ await withAdapterExecutionPhase(ctx, "phase_reporting", () => emitPhase(phase, start, "failed"));
3224
+ throw error;
3225
+ }
3226
+ await withAdapterExecutionPhase(ctx, "phase_reporting", () => emitPhase(phase, start, "ok"));
3227
+ };
3228
+ // The turn the run started. It is hoisted to the run scope so the settlement
3229
+ // `endSession` step can cancel a running turn before it closes the runtime
3230
+ // (the cancel-before-close order). The turn wrapper assigns it in `turnStart`.
3231
+ let activeTurn = null;
3232
+ let terminalFailureClassification = null;
3233
+ let terminalSessionFailure = null;
3234
+ // How the settlement `endSession` step must release the runtime for the path
3235
+ // this run took. Each exit path that acquired the runtime records it before it
3236
+ // returns; a build or create-runtime failure never registers the runtime, so
3237
+ // the step no-ops on the empty slot and this stays null.
3238
+ let runtimeSettlement = null;
3239
+ // True only when a handshake-guard rejection (a startup timeout or a
3240
+ // duplex transport loss) abandoned an `ensureSession` call. It tells the
3241
+ // settlement `endSession` step to defer the close to `handshakeFence`
3242
+ // when no late handle has arrived yet, instead of closing the synthetic
3243
+ // placeholder itself — closing both would close the same session twice.
3244
+ let handshakeAbandoned = false;
3245
+ // The one owner of an abandoned `ensureSession` promise for this run. See
3246
+ // `HandshakeAbandonmentFence` above for the state machine.
3247
+ const handshakeFence = new HandshakeAbandonmentFence();
3248
+ // A synthetic close handle from the prepared identity, for a close that has no
3249
+ // established session handle (a cold `ensureSession` throw or a missing
3250
+ // handle). `runtime.close` reads the session key and the runtime session name.
3251
+ const syntheticCloseHandle = () => ({
3252
+ sessionKey: prepared.sessionKey,
3253
+ backend: prepared.acpxAgent,
3254
+ runtimeSessionName: prepared.sessionKey,
3255
+ });
3256
+ // The run coordinator owns the one ledger for the attempt. The engine
3257
+ // creates it here, passes it into `buildRuntime` (the sandbox site registers
3258
+ // what it acquires into it), and hands it to `runAttempt` as the plan
3259
+ // ledger. The turn and settlement code still runs inline in the step
3260
+ // wrappers below; Phases 21-22 move it into its own modules.
3261
+ const runResourceLedger = createRunResourceLedger();
3262
+ // The step wrappers build the external result inline (today's behavior) and
3263
+ // record it here; the coordinator reproduces it after settlement. An empty
3264
+ // consumed set satisfies the `settle` result shape without claiming the run
3265
+ // ledger, because the inline teardown reads `prepared.*`, not the ledger, in
3266
+ // this phase.
3267
+ let capturedResult = null;
3268
+ const emptyConsumed = createRunResourceLedger().takeForSettlement();
3269
+ // Build the `settle` startup result for a pre-turn failure. The step wrapper
3270
+ // already recorded the external result and ran the inline teardown; this
3271
+ // carries only the routing kind and the cause for the coordinator.
3272
+ const settleFor = (phase, error) => ({
3273
+ kind: "settle",
3274
+ cause: {
3275
+ kind: "pre_turn_failed",
3276
+ phase,
3277
+ error: error instanceof Error ? error : new Error(String(error)),
3278
+ },
3279
+ resources: emptyConsumed,
3280
+ });
3281
+ // The startup step: bring up the runtime, establish the session, and apply
3282
+ // the session config. It returns `ready` on success, `settle` on a pre-turn
3283
+ // failure after the ledger acquired resources, and throws on a build failure
3284
+ // or a partial-bridge failure (the coordinator owns that rollback).
3285
+ const startup = async () => {
3286
+ try {
3287
+ // Publish the `sandbox.startup` context to the runtime-parent store for
3288
+ // the whole bring-up. A startup-body exec that runs outside a measured
3289
+ // step reads this token and parents its span to `sandbox.startup`, not to
3290
+ // a detached root. A measured step nests its own `activeStepContextStorage`
3291
+ // run inside this wrap and overrides the store, so an in-step exec still
3292
+ // parents to its step span. On a local or SSH target
3293
+ // `spanParent.parentContext` is a no-op token, so the wrap is inert.
3294
+ const startupCancellation = cancellableSandboxStartup(ctx);
3295
+ try {
3296
+ prepared = await runWithRuntimeParent(spanParent.parentContext, () => buildRuntime({
3297
+ ctx: startupCancellation.context,
3298
+ engine,
3299
+ deps,
3300
+ ledger: runResourceLedger,
3301
+ stagedIdleMs: warmIdleMs,
3302
+ spanParent,
3303
+ getRuntimeParentContext,
3304
+ runtimeSpan: runRuntimeSpan,
3305
+ stageRuntimeSpan: runStageSpan,
3306
+ }));
3307
+ buildRuntimeSettled = true;
3308
+ billingFields.pricingContext = prepared.fastMode ? { serviceTier: "fast" } : undefined;
3309
+ // Capture acquired resources before the cancellation boundary so the
3310
+ // normal settlement path also releases a just-completed build.
3311
+ releaseStagingLease = prepared.sessionStagingLeaseRelease;
3312
+ }
3313
+ finally {
3314
+ await startupCancellation.finish();
3315
+ }
3316
+ // Per-project staging outcomes for the referenced (mentioned) projects, surfaced back to the
3317
+ // server on the run result. A referenced project that failed to stage into the sandbox is a
3318
+ // first-class, counted failure in the requested-vs-synced observability, not only a warning. The
3319
+ // list is empty on a local target, on a transport that does not stage referenced projects, or
3320
+ // when every staged referenced project succeeded, so the spread adds the field only when there
3321
+ // is a failure to report.
3322
+ const referencedProjectStagingFailures = (prepared.stagedRuntime?.additionalSourceFailures ?? []).map((failure) => ({ projectId: failure.projectId, error: failure.error }));
3323
+ referencedProjectStagingFailuresField =
3324
+ referencedProjectStagingFailures.length > 0 ? { referencedProjectStagingFailures } : {};
3325
+ // Write one run-log line per failure, so a reader of the run log alone sees
3326
+ // each dropped referenced project and its reason. The run continues without
3327
+ // the failed project (per-project failure isolation). Goes to stderr: the
3328
+ // acpx stdout log stream carries machine-parseable JSON event payloads.
3329
+ for (const failure of referencedProjectStagingFailures) {
3330
+ await ctx.onLog("stderr", `[paperclip] Referenced project ${failure.projectId} failed to stage; the run continues without it: ${failure.error}\n`);
3331
+ }
3332
+ // State the effective wall-clock timeout and its source up front so a
3333
+ // later timeout is diagnosable from the run log alone. Goes to stderr:
3334
+ // the acpx stdout log stream carries JSON acpx.* event payloads and must
3335
+ // stay machine-parseable line by line.
3336
+ await ctx.onLog("stderr", `[paperclip] ${formatAdapterExecutionTimeoutStartLogLine(prepared.timeoutResolution)}\n`);
3337
+ await hostStore.evictIdle(now());
3338
+ const previousParams = parseObject(ctx.runtime.sessionParams);
3339
+ const canResume = isCompatibleSession(previousParams, prepared);
3340
+ const resumeSessionId = canResume ? asString(previousParams.acpSessionId, "") || undefined : undefined;
3341
+ // Borrow the warm entry without removing it, so an overlapping run of the
3342
+ // same session still sees it. The borrow clears the entry's idle timer, so
3343
+ // the reused runtime cannot expire under its own timer while this run uses
3344
+ // it (today's `clearWarmHandleTimer(cached)` after the reuse decision).
3345
+ let cached = canResume ? hostStore.borrow(prepared.sessionKey) : undefined;
3346
+ if (cached && (ctx.context.refreshTools === true
3347
+ || asString(previousParams.mcpFingerprint, "") !== shortHash(prepared.mcpIdentity)
3348
+ // MCP bearer credentials are run-scoped, even for an unchanged catalog.
3349
+ || prepared.mcpServers.length > 0)) {
3350
+ await hostStore.discard(prepared.sessionKey);
3351
+ cached = undefined;
3352
+ }
3353
+ childStderrState = cached?.childStderrState ?? { logPath: null, pendingLiveLine: "" };
3354
+ processIdentitySink = cached?.processIdentitySink ?? {
3355
+ current: ctx.onSpawn,
3356
+ latest: null,
3357
+ };
3358
+ // ACPX runtimes can stay warm across heartbeat runs. Keep the callback
3359
+ // target mutable so a later agent respawn records identity on the current
3360
+ // heartbeat instead of the run that originally created the runtime.
3361
+ processIdentitySink.current = ctx.onSpawn;
3362
+ flushChildStderr(childStderrState);
3363
+ childStderrState.logPath = prepared.childStderrLogPath;
3364
+ const persistedRuntimeStore = createRuntimeStore({ stateDir: prepared.stateDir });
3365
+ // Resume with this run's launch environment; keep it out of the saved
3366
+ // conversation record without mutating the live runtime's options.
3367
+ const runtimeStore = createEphemeralSessionEnvironmentStore(persistedRuntimeStore, prepared.env);
3368
+ const runtimeOptions = {
3369
+ cwd: prepared.cwd,
3370
+ // Host-only spawn cwd for the relay proxy on the remote process-session
3371
+ // lane; `undefined` elsewhere so acpx falls back to `cwd` (byte-identical).
3372
+ // The advertised `session/new` cwd (`prepared.cwd` = `remoteCwd`) and the
3373
+ // fingerprint / compat key are unaffected — this redirects ONLY the host
3374
+ // `spawn()` `chdir`, not the in-sandbox data path.
3375
+ spawnCwd: prepared.hostSpawnCwd,
3376
+ sessionStore: runtimeStore,
3377
+ agentRegistry: prepared.agentRegistry,
3378
+ permissionMode: prepared.permissionMode,
3379
+ nonInteractivePermissions: prepared.nonInteractivePermissions,
3380
+ ...(prepared.toolProfile === "read_only"
3381
+ ? {
3382
+ onPermissionRequest: async (request) => readOnlyAcpPermissionDecision(prepared.acpxAgent, request),
3383
+ }
3384
+ : {}),
3385
+ mcpServers: prepared.mcpServers,
3386
+ timeoutMs: prepared.timeoutSec > 0 ? prepared.timeoutSec * 1000 : undefined,
3387
+ // Scope ACPX runtime verbose logs to the claude agent only. Codex
3388
+ // and custom agents already emit their own per-tool output and don't
3389
+ // benefit from doubling the log volume.
3390
+ verbose: prepared.acpxAgent === "claude",
3391
+ // The engine passes a complete, sanitized launch environment. ACPX
3392
+ // must not merge the Paperclip server's ambient environment back in
3393
+ // when it spawns the provider child.
3394
+ inheritProcessEnv: false,
3395
+ onAgentStderr: prepared.childStderrLogPath
3396
+ ? (chunk) => routeChildStderr(childStderrState, chunk)
3397
+ : undefined,
3398
+ onAgentSpawn: async (meta) => {
3399
+ processIdentitySink.latest = meta;
3400
+ processIdentitySink.localProcess = prepared.processSessionBridge ? undefined : captureLocalProcess(meta.pid);
3401
+ await processIdentitySink.current?.({
3402
+ pid: meta.pid,
3403
+ processGroupId: null,
3404
+ startedAt: meta.startedAt,
3405
+ });
3406
+ },
3407
+ getRuntimeParentContext,
3408
+ };
3409
+ // Open Q2: split the ~7s `acp.handshake` into the two in-repo-observable
3410
+ // sub-phases — the ACP runtime construction (`createRuntime`) vs the session
3411
+ // establishment envelope (`ensureSession`). The patched spawn lifecycle
3412
+ // hook records process identity, but the finer spawn/`initialize`/
3413
+ // `session/new` timing split still lives inside external `acpx`.
3414
+ // `createRuntime` runs once and only on a cold start; a warm-handle hit
3415
+ // reuses `cached.runtime`, so `createRuntimeMs` stays undefined and the
3416
+ // split reports nothing for it.
3417
+ let createRuntimeMs;
3418
+ // A warm handle reuses the running ACP runtime; a miss constructs one. The
3419
+ // root span records this as `cold_start`.
3420
+ coldStart = !cached?.runtime;
3421
+ if (cached?.runtime) {
3422
+ runtime = cached.runtime;
3423
+ }
3424
+ else {
3425
+ const createRuntimeStart = now();
3426
+ runtime = createRuntime(runtimeOptions);
3427
+ createRuntimeMs = now() - createRuntimeStart;
3428
+ // The create_runtime phase runs only on a cold start.
3429
+ await emitRunPhaseTiming(ctx, "create_runtime", createRuntimeMs, "ok");
3430
+ }
3431
+ // Register the runtime composite in the ledger now that it exists. The
3432
+ // settlement `endSession` step closes it on every path the reuse decision
3433
+ // does not transfer. Registration here (before `ensureSession`) closes the
3434
+ // cold-handshake leak: a cold `ensureSession` throw before a handle exists
3435
+ // still leaves the runtime in the ledger for `endSession` to close. A
3436
+ // create-runtime failure throws before this line, so the runtime never
3437
+ // enters the ledger and the settlement no-ops on the empty slot. The
3438
+ // session handle fills in below; the payload carries the best-known handle
3439
+ // for the composite (`runtime.close` is the one release boundary).
3440
+ runResourceLedger.register({
3441
+ id: "acp_runtime",
3442
+ payload: {
3443
+ runtime,
3444
+ sessionHandle: cached?.handle ?? syntheticCloseHandle(),
3445
+ childProcessPid: processIdentitySink.latest?.pid ?? null,
3446
+ },
3447
+ scope: "per_run",
3448
+ });
3449
+ if (!canResume && asString(previousParams.runtimeSessionName, "")) {
3450
+ await ctx.onLog("stdout", `[paperclip] ACPX session "${asString(previousParams.runtimeSessionName, "")}" does not match the current agent/cwd/mode/runtime identity; starting fresh in "${prepared.cwd}".\n`);
3451
+ }
3452
+ let handle = cached?.handle ?? null;
3453
+ // The ensure_session phase covers the handshake (session establishment or
3454
+ // resume) up to the established handle.
3455
+ const ensureSessionPhaseStart = now();
3456
+ resumedSession = Boolean(handle ?? resumeSessionId);
3457
+ const isHandshakeTransportLost = () => prepared.paperclipBridge?.readRunDisposition?.().failed ?? false;
3458
+ // The fence's own close, for a real handle that resolves after
3459
+ // `endSession` already sealed. `endSession` closed the synthetic
3460
+ // placeholder by then (or skipped closing because the channel was
3461
+ // already known lost), so this is the one close for this real handle,
3462
+ // not a second one.
3463
+ // A rejected close comes from inside the sandbox (a forged late handle
3464
+ // can make `runtime.close` reject with chosen bytes). It crosses the
3465
+ // sandbox-to-host trust boundary, so it must never reach the run log,
3466
+ // the result, or a classification: log the fixed closed code only.
3467
+ // The catch stays attached so the promise stays observed and no
3468
+ // unhandled rejection can occur.
3469
+ const closeLateHandshakeHandle = (lateHandle) => {
3470
+ if (isHandshakeTransportLost())
3471
+ return;
3472
+ void runtime
3473
+ .close({
3474
+ handle: lateHandle,
3475
+ reason: "paperclip late handshake cleanup",
3476
+ discardPersistentState: false,
3477
+ })
3478
+ .catch(() => ctx
3479
+ .onLog("stderr", "[paperclip] ACPX handshake late close failed: acpx_handshake_late_close_failed\n")
3480
+ .catch(() => { }));
3481
+ };
3482
+ // The late rejection comes from inside the sandbox. It crosses the
3483
+ // sandbox-to-host trust boundary, so it must never reach the run log,
3484
+ // the result, or a classification: log the fixed closed code only.
3485
+ const recordLateHandshakeRejection = () => {
3486
+ void ctx
3487
+ .onLog("stderr", "[paperclip] ACPX handshake late rejection: acpx_handshake_late_rejection\n")
3488
+ .catch(() => { });
3489
+ };
3490
+ try {
3491
+ if (!handle) {
3492
+ try {
3493
+ // Step 7 — acp.handshake: ACP session establishment (session/new or
3494
+ // resume). A throwing handshake still reports its duration before the
3495
+ // resume-retry path below runs. The createRuntime/ensureSession
3496
+ // sub-split rides the step span as fixed, closed keys (Open Q2).
3497
+ let ensureSessionMs;
3498
+ handle = await measureStartupStep(ctx, now, "acp.handshake", async () => {
3499
+ const ensureSessionStart = now();
3500
+ const established = await guardEnsureSession({
3501
+ call: () => runtime.ensureSession({
3502
+ sessionKey: prepared.sessionKey,
3503
+ agent: prepared.acpxAgent,
3504
+ mode: prepared.mode,
3505
+ cwd: prepared.cwd,
3506
+ resumeSessionId,
3507
+ sessionOptions: { env: prepared.env },
3508
+ }),
3509
+ fence: handshakeFence,
3510
+ isTransportLost: isHandshakeTransportLost,
3511
+ onLateHandleAfterSeal: closeLateHandshakeHandle,
3512
+ onLateRejection: recordLateHandshakeRejection,
3513
+ });
3514
+ ensureSessionMs = now() - ensureSessionStart;
3515
+ return established;
3516
+ }, {
3517
+ ...prepared.stepMetrics,
3518
+ // The two sub-times ride the span as fixed, closed keys.
3519
+ spanWallTimes: () => ({
3520
+ createRuntime: createRuntimeMs,
3521
+ ensureSession: ensureSessionMs,
3522
+ }),
3523
+ });
3524
+ }
3525
+ catch (err) {
3526
+ if (!resumeSessionId || !isResumeFailure(err))
3527
+ throw err;
3528
+ clearSession = true;
3529
+ resumedSession = false;
3530
+ await ctx.onLog("stdout", `[paperclip] ACPX resume session "${resumeSessionId}" is unavailable; retrying with a fresh session.\n`);
3531
+ // Fresh-session retry: the runtime was already constructed on the
3532
+ // first attempt (never re-created), so this event reports only its
3533
+ // own `ensureSessionMs` — no `createRuntimeMs`.
3534
+ let retryEnsureSessionMs;
3535
+ handle = await measureStartupStep(ctx, now, "acp.handshake", async () => {
3536
+ const ensureSessionStart = now();
3537
+ const established = await guardEnsureSession({
3538
+ call: () => runtime.ensureSession({
3539
+ sessionKey: prepared.sessionKey,
3540
+ agent: prepared.acpxAgent,
3541
+ mode: prepared.mode,
3542
+ cwd: prepared.cwd,
3543
+ sessionOptions: { env: prepared.env },
3544
+ }),
3545
+ fence: handshakeFence,
3546
+ isTransportLost: isHandshakeTransportLost,
3547
+ onLateHandleAfterSeal: closeLateHandshakeHandle,
3548
+ onLateRejection: recordLateHandshakeRejection,
3549
+ });
3550
+ retryEnsureSessionMs = now() - ensureSessionStart;
3551
+ return established;
3552
+ }, {
3553
+ ...prepared.stepMetrics,
3554
+ // The retry reuses the runtime from the first attempt, so it reports
3555
+ // only its own ensure-session sub-time on the span.
3556
+ spanWallTimes: () => ({ ensureSession: retryEnsureSessionMs }),
3557
+ });
3558
+ }
3559
+ }
3560
+ else {
3561
+ // Warm-handle hit: a compatible cached handle reuses the running ACP
3562
+ // agent, so the `acp.handshake` step does no work. Emit a step span and
3563
+ // event with `outcome = skipped` and a zero wall time, so the trace and
3564
+ // the run log show the skip as a distinct outcome, never a misleading
3565
+ // zero-work `ok` step.
3566
+ await emitSkippedStartupStep(ctx, "acp.handshake", {
3567
+ tracer: prepared.stepMetrics.tracer,
3568
+ parentContext: prepared.stepMetrics.parentContext,
3569
+ });
3570
+ }
3571
+ if (resumeSessionId && handle?.backendSessionId !== resumeSessionId) {
3572
+ resumedSession = false;
3573
+ clearSession = true;
3574
+ }
3575
+ // A compatible warm handle reuses the already-running ACP agent and does
3576
+ // not emit another spawn event. Persist its known identity on this run
3577
+ // before the next prompt starts so every running heartbeat is adoptable.
3578
+ if (handle && cached && processIdentitySink.latest && ctx.onSpawn) {
3579
+ await ctx.onSpawn({
3580
+ pid: processIdentitySink.latest.pid,
3581
+ processGroupId: null,
3582
+ startedAt: processIdentitySink.latest.startedAt,
3583
+ });
3584
+ }
3585
+ }
3586
+ catch (err) {
3587
+ // Record how the settlement closes the runtime on a pre-turn handshake
3588
+ // failure: a direct close that drops a matching warm entry, the same as
3589
+ // the configuration-failure path. A warm-hit reuse already cleared the
3590
+ // idle timer before the handshake ran, so the failure must close and
3591
+ // remove the entry, never re-arm it. A cold `ensureSession` throw has no
3592
+ // established handle, so the settlement closes the synthetic handle — the
3593
+ // ledger now holds the runtime, so `endSession` closes it and the former
3594
+ // cold-handshake leak is gone. The settlement stops the bridges, releases
3595
+ // the staging lease, and flushes the child stderr on every exit path.
3596
+ //
3597
+ // A handshake-guard rejection is the one exception: `handle` stays
3598
+ // null, but the abandoned `ensureSession` call can still resolve
3599
+ // into a real handle later. `handshakeAbandoned` tells `endSession`
3600
+ // to defer that placeholder close to `handshakeFence` when no late
3601
+ // handle has arrived yet, instead of closing it here and possibly
3602
+ // again later.
3603
+ const guardTripped = isAcpxHandshakeTimeoutError(err) || isAcpxHandshakeTransportLostError(err);
3604
+ handshakeAbandoned = guardTripped;
3605
+ runtimeSettlement = {
3606
+ mode: "direct",
3607
+ handle: handle ?? syntheticCloseHandle(),
3608
+ reason: "paperclip handshake cleanup",
3609
+ discardPersistentState: false,
3610
+ dropWarmEntry: true,
3611
+ recordCloseError: true,
3612
+ cancelTurnReason: null,
3613
+ skipRemoteClose: false,
3614
+ };
3615
+ await emitPhase("ensure_session", ensureSessionPhaseStart, "failed");
3616
+ const { classified, message } = await emitAcpxFailure({
3617
+ ctx,
3618
+ prepared,
3619
+ err,
3620
+ phase: "ensure_session",
3621
+ // The guard's own message is already generic and host-authored, so
3622
+ // this replaces the underlying error text with the same closed
3623
+ // message `classifyError` classified — the ensure_session phase
3624
+ // never gets a chance to summarize it differently.
3625
+ ...(guardTripped && err instanceof Error ? { messageOverride: err.message } : {}),
3626
+ // A compromised child can hold ensureSession open until the guard
3627
+ // fires, then write chosen bytes to its own stderr. Suppress the
3628
+ // child stderr tail on this route only, so those sandbox-provided
3629
+ // bytes never reach the run log or the acpx.error payload.
3630
+ ...(guardTripped ? { suppressChildStderrTail: true } : {}),
3631
+ });
3632
+ capturedResult = {
3633
+ exitCode: 1,
3634
+ signal: null,
3635
+ timedOut: false,
3636
+ errorMessage: message,
3637
+ ...classified,
3638
+ ...billingFields,
3639
+ ...referencedProjectStagingFailuresField,
3640
+ model: prepared.requestedModel || null,
3641
+ clearSession,
3642
+ resultJson: { phase: "ensure_session" },
3643
+ summary: message,
3644
+ };
3645
+ return settleFor("handshake", err);
3646
+ }
3647
+ if (!handle) {
3648
+ // ensureSession returned no session handle. The ledger holds the runtime
3649
+ // the run constructed, so record a direct close of the synthetic handle
3650
+ // for the settlement `endSession` step (the child process cannot leak).
3651
+ runtimeSettlement = {
3652
+ mode: "direct",
3653
+ handle: syntheticCloseHandle(),
3654
+ reason: "paperclip missing-handle cleanup",
3655
+ discardPersistentState: false,
3656
+ dropWarmEntry: false,
3657
+ recordCloseError: true,
3658
+ cancelTurnReason: null,
3659
+ skipRemoteClose: false,
3660
+ };
3661
+ await emitPhase("ensure_session", ensureSessionPhaseStart, "failed");
3662
+ capturedResult = {
3663
+ exitCode: 1,
3664
+ signal: null,
3665
+ timedOut: false,
3666
+ errorMessage: "ACPX did not return a runtime session handle.",
3667
+ errorCode: "acpx_runtime_error",
3668
+ ...billingFields,
3669
+ ...referencedProjectStagingFailuresField,
3670
+ model: prepared.requestedModel || null,
3671
+ resultJson: { phase: "ensure_session" },
3672
+ summary: "ACPX did not return a runtime session handle.",
3673
+ };
3674
+ return settleFor("session_handle_missing", new Error("ACPX did not return a runtime session handle."));
3675
+ }
3676
+ sessionHandle = handle;
3677
+ startupFailed = false;
3678
+ await emitPhase("ensure_session", ensureSessionPhaseStart, "ok");
3679
+ }
3680
+ catch (err) {
3681
+ if (!buildRuntimeSettled) {
3682
+ // buildRuntime failed before it staged or bridged anything, so there is
3683
+ // nothing to settle here. The finally below ends the sandbox.startup
3684
+ // span; let the failure propagate.
3685
+ throw err;
3686
+ }
3687
+ // The post-build runtime-creation window failed after buildRuntime returned
3688
+ // live bridges and a held staging lease. `createRuntime` throws before the
3689
+ // ledger registers the runtime, so the settlement `endSession` step no-ops
3690
+ // on the empty slot (create_runtime never closes a runtime). The settlement
3691
+ // still stops the bridges, discards the staged runtime, releases the staging
3692
+ // lease, and flushes the child stderr.
3693
+ const { classified, message } = await emitAcpxFailure({
3694
+ ctx,
3695
+ prepared,
3696
+ err,
3697
+ phase: "create_runtime",
3698
+ });
3699
+ capturedResult = {
3700
+ exitCode: 1,
3701
+ signal: null,
3702
+ timedOut: false,
3703
+ errorMessage: message,
3704
+ ...classified,
3705
+ ...billingFields,
3706
+ ...referencedProjectStagingFailuresField,
3707
+ model: prepared.requestedModel || null,
3708
+ clearSession,
3709
+ resultJson: { phase: "create_runtime" },
3710
+ summary: message,
3711
+ };
3712
+ return settleFor("runtime_create", err);
3713
+ }
3714
+ finally {
3715
+ // End the sandbox.startup span exactly once, on every return and on every
3716
+ // throw. It covers buildRuntime through acp.handshake and no further; the
3717
+ // agent turn runs after and is out of the span's scope.
3718
+ rootSpan.end(startupFailed);
3719
+ }
3720
+ const configureSessionStart = now();
3721
+ try {
3722
+ await applySessionConfigOptions({
3723
+ runtime,
3724
+ handle: sessionHandle,
3725
+ prepared,
3726
+ onLog: ctx.onLog,
3727
+ });
3728
+ await applyReadOnlySessionMode({
3729
+ runtime,
3730
+ handle: sessionHandle,
3731
+ prepared,
3732
+ onLog: ctx.onLog,
3733
+ });
3734
+ await emitPhase("configure_session", configureSessionStart, "ok");
3735
+ }
3736
+ catch (err) {
3737
+ // Record a direct close that drops the matching warm entry for the
3738
+ // settlement `endSession` step. The settlement stops the bridges, discards
3739
+ // the staged runtime, releases the staging lease, and flushes the child
3740
+ // stderr on this exit path too.
3741
+ runtimeSettlement = {
3742
+ mode: "direct",
3743
+ handle: sessionHandle,
3744
+ reason: "paperclip config cleanup",
3745
+ discardPersistentState: false,
3746
+ dropWarmEntry: true,
3747
+ recordCloseError: true,
3748
+ cancelTurnReason: null,
3749
+ skipRemoteClose: false,
3750
+ };
3751
+ await emitPhase("configure_session", configureSessionStart, "failed");
3752
+ const { classified, message } = await emitAcpxFailure({
3753
+ ctx,
3754
+ prepared,
3755
+ err,
3756
+ phase: "configure_session",
3757
+ });
3758
+ capturedResult = {
3759
+ exitCode: 1,
3760
+ signal: null,
3761
+ timedOut: false,
3762
+ errorMessage: message,
3763
+ ...classified,
3764
+ ...billingFields,
3765
+ ...referencedProjectStagingFailuresField,
3766
+ model: prepared.requestedModel || null,
3767
+ clearSession,
3768
+ resultJson: {
3769
+ phase: "configure_session",
3770
+ agent: prepared.acpxAgent,
3771
+ requestedModel: prepared.requestedModel || null,
3772
+ requestedThinkingEffort: prepared.requestedThinkingEffort || null,
3773
+ fastMode: prepared.fastMode,
3774
+ },
3775
+ summary: message,
3776
+ };
3777
+ return settleFor("session_configuration", err);
3778
+ }
3779
+ // Startup succeeded: seal the ledger (promotes the startup_rollback entries
3780
+ // that survived to `per_run`) and hand the ready resources to the turn. The
3781
+ // turn wrapper reads the run state through the shared closure locals in this
3782
+ // phase, so the sealed view and the context are the contract carriers only.
3783
+ return {
3784
+ kind: "ready",
3785
+ resources: runResourceLedger.seal([]),
3786
+ context: { sessionKey: prepared.sessionKey },
3787
+ };
3788
+ };
3789
+ // The turn step: run the turn sequence and settle the runtime inline
3790
+ // (today's behavior). The sequence owns the wall-clock timer and the abort
3791
+ // controller and never rejects; it returns a `TurnCompletion`. The step
3792
+ // bodies below record the external result for the coordinator to reproduce.
3793
+ const runTurn = async (_ready) => {
3794
+ // Summary accumulation collects output text only (never thought stream),
3795
+ // segmented on tool starts so multi-step narration is not glued into one
3796
+ // automatic comment dump.
3797
+ const outputSegments = [];
3798
+ let currentOutputChunk = [];
3799
+ const flushOutputSegment = () => {
3800
+ if (currentOutputChunk.length === 0)
3801
+ return;
3802
+ outputSegments.push(currentOutputChunk.join(""));
3803
+ currentOutputChunk = [];
3804
+ };
3805
+ let eventBreakdown = null;
3806
+ let eventCostUsd = null;
3807
+ // Receipt persistence is fallible; retain the provider evidence before
3808
+ // calling the sink so the failure result can still return it to the host.
3809
+ let observedUsage = { usageComplete: false };
3810
+ let lastRuntimeEventAt = null;
3811
+ let observedRuntimeEvents = 0;
3812
+ let turnDispatchAttempted = false;
3813
+ // The turn-local state the sequence steps share. `promptBuild` sets the
3814
+ // prompt, `preTurnUsage` sets the pre-turn status, `turnStart` sets the
3815
+ // active turn, and `turnFinalize` reads all three. `activeTurn` is the run-
3816
+ // scoped hoisted local, so the settlement `endSession` step can cancel it.
3817
+ let runPrompt = "";
3818
+ let preTurnStatus = null;
3819
+ // Phase-timing markers for the prepare_turn and turn phases. The prepare
3820
+ // phase covers the prompt build and the pre-turn usage snapshot; the turn
3821
+ // phase covers the started turn and the event relay.
3822
+ let preparePhaseStart = now();
3823
+ let turnPhaseStart = now();
3824
+ // Open the agent turn span as a child of the run root span. It wraps the
3825
+ // whole turn: the executor holds `turnSpan.parentContext` for later exec
3826
+ // parenting, and the `finally` below ends the span once on every path. The
3827
+ // span is declared before the `try` so the `finally` can reach it.
3828
+ const turnSpan = openTurnSpan(tracing, now, runRootSpan.parentContext);
3829
+ // Switch the current-run holder to the `agent.turn` token for the turn, so
3830
+ // a detached exec during the turn parents to `agent.turn`. The turn
3831
+ // `finally` resets the holder to the `task.run` token.
3832
+ currentRunParentContext = turnSpan.parentContext;
3833
+ const stepPromptBuild = async (_signal) => {
3834
+ // Build the prompt and emit the run metadata inside the turn failure
3835
+ // boundary. A failure here returns an error result with phase
3836
+ // `prepare_turn`.
3837
+ preparePhaseStart = now();
3838
+ const { prompt, promptMetrics, commandNotes } = await buildPrompt(ctx, resumedSession, prepared.env, prepared.paperclipAccess, prepared.paperclipToolsets);
3839
+ runPrompt = joinPromptSections([prepared.skillPromptInstructions, prompt]);
3840
+ await emitAcpxLog(ctx, {
3841
+ type: "acpx.session",
3842
+ agent: prepared.acpxAgent,
3843
+ sessionId: sessionHandle.backendSessionId,
3844
+ acpSessionId: sessionHandle.backendSessionId,
3845
+ agentSessionId: sessionHandle.agentSessionId,
3846
+ runtimeSessionName: sessionHandle.runtimeSessionName,
3847
+ mode: prepared.mode,
3848
+ permissionMode: prepared.permissionMode,
3849
+ model: prepared.requestedModel || null,
3850
+ thinkingEffort: prepared.requestedThinkingEffort || null,
3851
+ fastMode: prepared.fastMode,
3852
+ });
3853
+ if (ctx.onMeta) {
3854
+ await ctx.onMeta({
3855
+ adapterType: engine.adapterType,
3856
+ command: prepared.agentCommand ?? prepared.acpxAgent,
3857
+ cwd: prepared.cwd,
3858
+ commandNotes: [
3859
+ `ACPX runtime embedded in Paperclip with ${prepared.mode} session mode.`,
3860
+ `Effective ACPX permission mode: ${prepared.permissionMode}.`,
3861
+ ...(prepared.requestedModel
3862
+ ? [
3863
+ prepared.acpxAgent === "claude"
3864
+ ? `Requested ACPX model: ${prepared.requestedModel} (set via ANTHROPIC_MODEL env at startup).`
3865
+ : prepared.acpxAgent === "codex"
3866
+ ? `Requested ACPX model: ${prepared.requestedModel} (set via CODEX_CONFIG at startup).`
3867
+ : prepared.acpxAgent === "gemini"
3868
+ ? `Requested ACPX model: ${prepared.requestedModel} (set via GEMINI_MODEL at startup).`
3869
+ : `Requested ACPX model: ${prepared.requestedModel}.`,
3870
+ ]
3871
+ : []),
3872
+ ...(prepared.requestedThinkingEffort ? [`Requested ACPX thinking effort: ${prepared.requestedThinkingEffort}.`] : []),
3873
+ ...(prepared.fastMode ? ["Requested ACPX Codex fast mode."] : []),
3874
+ ...(Array.isArray(prepared.skillsIdentity.commandNotes)
3875
+ ? prepared.skillsIdentity.commandNotes.filter((note) => typeof note === "string")
3876
+ : []),
3877
+ ...commandNotes,
3878
+ ],
3879
+ env: prepared.loggedEnv,
3880
+ prompt: runPrompt,
3881
+ promptMetrics,
3882
+ context: ctx.context,
3883
+ });
3884
+ }
3885
+ };
3886
+ const stepPreTurnUsage = async () => {
3887
+ // Snapshot pre-turn usage so cumulative agent-reported cost can be
3888
+ // attributed to this run alone.
3889
+ preTurnStatus = await readRuntimeStatus(runtime, sessionHandle);
3890
+ // The prepare phase (prompt build + usage snapshot) finished; the turn
3891
+ // phase starts next.
3892
+ await emitPhase("prepare_turn", preparePhaseStart, "ok");
3893
+ turnPhaseStart = now();
3894
+ };
3895
+ const stepTurnStart = (signal, startTimeoutMs) => {
3896
+ ctx.signal?.throwIfAborted();
3897
+ // After entering startTurn, a thrown error cannot prove the provider
3898
+ // received no work. Only failures before this boundary are free to settle.
3899
+ turnDispatchAttempted = true;
3900
+ const turn = runtime.startTurn({
3901
+ handle: sessionHandle,
3902
+ text: runPrompt,
3903
+ mode: "prompt",
3904
+ requestId: ctx.runId,
3905
+ timeoutMs: startTimeoutMs,
3906
+ signal,
3907
+ // The callback belongs to this turn, including when a runtime is reused.
3908
+ // Diagnostics are retained even when an adapter has no recovery
3909
+ // classifier. Redact before bounding so partial secrets cannot leak.
3910
+ onTerminalSessionFailure: (failure) => {
3911
+ terminalFailureClassification = classifyToolDefinitionFailure(failure)
3912
+ ?? deps.classifyTerminalSessionFailure?.(failure, new Date(now())) ?? null;
3913
+ terminalSessionFailure = sanitizeTerminalSessionFailure(failure, prepared.env, ctx.authToken, parseObject(ctx.config.env));
3914
+ },
3915
+ });
3916
+ activeTurn = turn;
3917
+ // A latched sandbox duplex-channel loss otherwise has no way to reach
3918
+ // this turn: the bridge only exposes a pull read, and the engine
3919
+ // pulls it at the terminal-finalization boundary, which runs only
3920
+ // after the turn already returned a terminal result. A channel that
3921
+ // dies mid-turn then leaves the turn with no terminal result to
3922
+ // return, so it waits for the wall-clock adapter execution timeout
3923
+ // instead of failing fast. Cancel the turn the moment a terminal loss
3924
+ // latches — whether it latches from here on, or already latched
3925
+ // before this turn started — so the turn returns a terminal result
3926
+ // right away. `turnFinalize` reads the same latch and builds the
3927
+ // failure from the typed loss reason alone.
3928
+ const bridge = prepared.paperclipBridge;
3929
+ if (bridge?.onLoss) {
3930
+ const cancelForLoss = (reason) => {
3931
+ void turn.cancel({ reason: `paperclip sandbox duplex channel lost (${reason})` }).catch(() => { });
3932
+ // `cancel()` only asks the agent to end the turn; it does not end
3933
+ // the turn by itself. Start the fail-fast deadline the moment the
3934
+ // loss latches, so the run does not wait past this bound for an
3935
+ // agent that stopped answering.
3936
+ if (!lossDeadlineTimer && !lossDeadlineTripped) {
3937
+ lossDeadlineTimer = setTimeout(() => {
3938
+ lossDeadlineTripped = true;
3939
+ resolveLossDeadline?.();
3940
+ }, duplexLossCancelDeadlineMs);
3941
+ }
3942
+ };
3943
+ removeLossListener = bridge.onLoss(cancelForLoss);
3944
+ const alreadyLatched = bridge.readRunDisposition?.();
3945
+ if (alreadyLatched?.failed)
3946
+ cancelForLoss(alreadyLatched.lossReason ?? "other");
3947
+ }
3948
+ // ACP can resolve the turn before its provider exits. Keep the Stop
3949
+ // deadline armed through settlement, including provider cleanup.
3950
+ const armStopDeadline = () => {
3951
+ stopTimer = setTimeout(() => {
3952
+ forcedStop = true;
3953
+ const providerPid = processIdentitySink.latest?.pid;
3954
+ if (providerPid && !prepared.processSessionBridge) {
3955
+ // Escalate the owned local process directly. A second ACP close
3956
+ // can wait behind the same hung cleanup (or open a new client).
3957
+ killCapturedLocalProcess(processIdentitySink.localProcess);
3958
+ }
3959
+ else {
3960
+ void runtime.close({ handle: sessionHandle, reason: "operator stop deadline", discardPersistentState: true })
3961
+ .catch(() => { });
3962
+ }
3963
+ }, Math.max(1, asNumber(ctx.config.graceSec, 15)) * 1000);
3964
+ };
3965
+ ctx.signal?.addEventListener("abort", armStopDeadline, { once: true });
3966
+ removeStopListener = () => ctx.signal?.removeEventListener("abort", armStopDeadline);
3967
+ if (ctx.signal?.aborted)
3968
+ armStopDeadline();
3969
+ return {
3970
+ cancel: async (reason) => {
3971
+ await withAdapterExecutionPhase(ctx, "cancel_turn", () => turn.cancel({ reason }));
3972
+ },
3973
+ };
3974
+ };
3975
+ // The host-built terminal `stepEventRelay` hands to `turnFinalize` once
3976
+ // the fail-fast deadline fires with no agent-supplied terminal. Its
3977
+ // `status` mirrors the shape a real cooperative cancel already
3978
+ // produces, so `turnFinalize` needs no change: it reads the latched
3979
+ // loss disposition, not this `stopReason`, to build the reported
3980
+ // failure and its message.
3981
+ const LOSS_DEADLINE_TERMINAL = {
3982
+ status: "cancelled",
3983
+ stopReason: "paperclip_duplex_loss_deadline",
3984
+ };
3985
+ const stepEventRelay = async () => {
3986
+ const turn = activeTurn;
3987
+ const toolTitles = new Map();
3988
+ const drainEvents = (async () => {
3989
+ for await (const event of turn.events) {
3990
+ lastRuntimeEventAt = now();
3991
+ observedRuntimeEvents += 1;
3992
+ // ACPX currently flattens client-side filesystem/terminal receipts
3993
+ // into status text. They cannot establish complete action outcomes.
3994
+ if (event.type === "status" && /^(fs|terminal)\//.test(event.text))
3995
+ incompleteToolInventory = true;
3996
+ if (event.type === "tool_call") {
3997
+ if (!event.toolCallId)
3998
+ incompleteToolInventory = true;
3999
+ else {
4000
+ const previous = interruptionTools.get(event.toolCallId);
4001
+ interruptionTools.set(event.toolCallId, {
4002
+ kind: event.kind ?? previous?.kind,
4003
+ status: event.status ?? previous?.status,
4004
+ });
4005
+ }
4006
+ }
4007
+ if (event.type === "text_delta" && event.stream !== "thought") {
4008
+ currentOutputChunk.push(event.text);
4009
+ }
4010
+ else if (event.type === "tool_call" && event.tag !== "tool_call_update") {
4011
+ // ACP makes tool-call status optional. The normalized event tag is
4012
+ // the reliable boundary between an initial call and its updates,
4013
+ // so a statusless initial call must still end the preceding output
4014
+ // segment while updates must not create extra boundaries.
4015
+ flushOutputSegment();
4016
+ }
4017
+ if (event.type === "status" && event.tag === "usage_update") {
4018
+ eventBreakdown = event.breakdown ?? eventBreakdown;
4019
+ eventCostUsd = usdCostAmount(event.cost) ?? eventCostUsd;
4020
+ const checkpoint = summarizeAcpxTurnUsage({ preStatus: preTurnStatus, postStatus: null, eventBreakdown, eventCostUsd });
4021
+ observedUsage = { usage: checkpoint.usage ?? undefined, costUsd: checkpoint.costUsd, usageBasis: "per_run", usageComplete: false };
4022
+ await ctx.onUsage?.({ ...billingFields, usage: checkpoint.usage ?? undefined, costUsd: checkpoint.costUsd,
4023
+ model: prepared.requestedModel, usageBasis: "per_run", complete: false });
4024
+ }
4025
+ await emitRuntimeEvent(ctx, event, toolTitles, prepared.coalescePlaceholderToolUpdates);
4026
+ }
4027
+ })();
4028
+ // A latched loss already asked the agent to cancel (above, in
4029
+ // `cancelForLoss`); that request settles neither `turn.events` nor
4030
+ // `turn.result` by itself. Race the event drain against the fail-fast
4031
+ // deadline so a silent agent cannot hold this wait open.
4032
+ const eventsEnded = await Promise.race([
4033
+ drainEvents.then(() => true),
4034
+ lossDeadline.then(() => false),
4035
+ ]);
4036
+ if (!eventsEnded) {
4037
+ // The deadline won: stop waiting on the agent. `closeStream` ends
4038
+ // the event drain locally, with no agent cooperation required. Await
4039
+ // both the close call and the drain it unblocks before this step
4040
+ // returns, so no late runtime event can still mutate shared state
4041
+ // (output segments, tool inventory) after finalization reads it.
4042
+ await turn.closeStream({ reason: "paperclip duplex loss cancel deadline" }).catch(() => { });
4043
+ await drainEvents.catch(() => { });
4044
+ flushOutputSegment();
4045
+ return LOSS_DEADLINE_TERMINAL;
4046
+ }
4047
+ flushOutputSegment();
4048
+ // `turn.result` settles only when the agent's provider process
4049
+ // returns or rejects; a latched loss that armed the deadline after
4050
+ // the event drain already ended must still bound this wait.
4051
+ return await Promise.race([turn.result, lossDeadline.then(() => LOSS_DEADLINE_TERMINAL)]);
4052
+ };
4053
+ const stepTurnFinalize = async (input) => {
4054
+ // Capture runtime activity before usage reads, error logs, or cleanup
4055
+ // make an otherwise silent turn look active at its execution deadline.
4056
+ const lastEventAgeMs = lastRuntimeEventAt === null ? undefined : now() - lastRuntimeEventAt;
4057
+ const activityDiagnostics = {
4058
+ acpObservedEventCount: observedRuntimeEvents,
4059
+ ...(lastEventAgeMs !== undefined && Number.isSafeInteger(lastEventAgeMs) && lastEventAgeMs >= 0
4060
+ ? { acpLastEventAgeMs: lastEventAgeMs } : {}),
4061
+ acpPendingToolCount: [...interruptionTools.values()].filter((tool) => tool.status !== "completed" && tool.status !== "failed" && tool.status !== "cancelled").length,
4062
+ acpToolInventoryComplete: !incompleteToolInventory,
4063
+ };
4064
+ if (input.kind === "terminal") {
4065
+ const terminal = input.terminal;
4066
+ const timedOut = input.timedOut;
4067
+ // Read the sandbox duplex control-channel disposition at the ACP
4068
+ // terminal-finalization boundary, before the bridge teardown, on every
4069
+ // terminal outcome. A control channel that died before this point
4070
+ // latches a failure with a typed loss reason; a healthy channel or a
4071
+ // normal-teardown loss reports a success. The read and the mark of the
4072
+ // host-observed orderly completion happen atomically in one broker
4073
+ // step, with no `await` between them, so a teardown loss cannot slip
4074
+ // in between. This stops a later teardown `channel_exit` from latching
4075
+ // a false loss. The mark no-ops once a loss already latched, so a real
4076
+ // mid-turn loss still fails the run — including a loss that arrived
4077
+ // through the in-flight-turn cancel this seam issues, which surfaces
4078
+ // here as a `cancelled` (not `completed`) terminal, not just through a
4079
+ // nominally completed terminal. The file bridge path never sets this
4080
+ // method, so the optional call no-ops there.
4081
+ let duplexLossReason = null;
4082
+ const disposition = prepared.paperclipBridge?.settleRunDisposition?.() ?? null;
4083
+ if (disposition?.failed) {
4084
+ duplexLossReason = disposition.lossReason ?? "other";
4085
+ }
4086
+ // A terminal that reports "completed" but whose duplex control channel
4087
+ // died before the completion is not a success. The seam fails it closed.
4088
+ const channelLost = duplexLossReason !== null;
4089
+ // Build the boundary failure message only from the closed loss-reason
4090
+ // enum, so no raw provider text rides the message.
4091
+ const channelLostMessage = duplexLossReason
4092
+ ? `The sandbox duplex control channel was lost (${duplexLossReason}) before the run completed.`
4093
+ : null;
4094
+ // A completed, non-timed-out turn whose channel stayed live is the one
4095
+ // success path. Every other outcome — a failed, cancelled, or timed-out
4096
+ // terminal, or a completed terminal with a lost channel — is a failure.
4097
+ const turnSucceeded = terminal.status === "completed" && !timedOut && !channelLost;
4098
+ // Read usage before the settlement can discard runtime state.
4099
+ const postTurnStatus = await readRuntimeStatus(runtime, sessionHandle);
4100
+ const turnUsage = summarizeAcpxTurnUsage({
4101
+ preStatus: preTurnStatus,
4102
+ postStatus: postTurnStatus,
4103
+ eventBreakdown,
4104
+ eventCostUsd,
4105
+ });
4106
+ // An interrupted stream is provisional unless the runtime supplies its
4107
+ // post-terminal receipt. An in-stream usage_update alone cannot close it.
4108
+ const usageComplete = !channelLost && (turnSucceeded || postTurnStatus?.usage != null);
4109
+ observedUsage = { usage: turnUsage.usage ?? undefined, costUsd: turnUsage.costUsd, usageBasis: "per_run", usageComplete };
4110
+ await ctx.onUsage?.({ ...billingFields, usage: turnUsage.usage ?? undefined, costUsd: turnUsage.costUsd,
4111
+ model: prepared.requestedModel, usageBasis: "per_run", complete: usageComplete });
4112
+ const failedTurn = terminal.status === "failed" || terminal.status === "cancelled" || timedOut;
4113
+ // ACPX can defer session/load until runTurn. Forget an unavailable
4114
+ // session so the next bounded turn receives the full task conversation.
4115
+ const sessionUnavailable = terminal.status === "failed" &&
4116
+ terminal.error.detailCode === "SESSION_RESUME_REQUIRED";
4117
+ if (sessionUnavailable)
4118
+ clearSession = true;
4119
+ // Saving a conversation is independent from certifying tool outcomes.
4120
+ // Its next turn receives history, not a replay of pending tool calls.
4121
+ preserveInterruptedSession = ctx.signal?.aborted === true && !forcedStop && !timedOut && !channelLost
4122
+ && (terminal.status === "cancelled" || terminal.status === "completed")
4123
+ && prepared.mode === "persistent" && !prepared.processSessionBridge
4124
+ && Boolean(sessionHandle.backendSessionId);
4125
+ safeInterruptedSession = preserveInterruptedSession
4126
+ && !incompleteToolInventory
4127
+ && [...interruptionTools.values()].every((tool) => tool.kind === "read" && tool.status === "completed");
4128
+ // Record how the settlement `endSession` step closes the runtime for this
4129
+ // outcome. A clean persistent host turn is save-eligible, but the
4130
+ // Amendment B credential gate fails on the host lane (the run API key is
4131
+ // never revoked), so the reuse decision discards and `endSession` closes it
4132
+ // (close-and-relaunch). The sandbox lane always closes the runtime; its
4133
+ // staged files are the reuse. A matching warm entry closes through the warm
4134
+ // store (which also flushes its stderr); otherwise the runtime closes
4135
+ // directly. The settlement then stops the bridges, saves or discards the
4136
+ // staged runtime, releases the staging lease, and flushes the child stderr.
4137
+ runtimeSettlement = {
4138
+ mode: "warm_or_close",
4139
+ handle: sessionHandle,
4140
+ reason: timedOut
4141
+ ? "paperclip timeout cleanup"
4142
+ : channelLost
4143
+ ? "paperclip duplex channel lost cleanup"
4144
+ : failedTurn
4145
+ ? `paperclip turn ${terminal.status}`
4146
+ : "paperclip completed turn cleanup",
4147
+ discardPersistentState: sessionUnavailable || (terminal.status === "cancelled" && !preserveInterruptedSession) || timedOut || channelLost,
4148
+ dropWarmEntry: false,
4149
+ recordCloseError: false,
4150
+ cancelTurnReason: null,
4151
+ skipRemoteClose: channelLost,
4152
+ };
4153
+ const failureDiagnostic = !timedOut && !channelLost && terminal.status === "failed"
4154
+ ? terminalSessionFailure
4155
+ : null;
4156
+ const errorMessage = timedOut
4157
+ ? formatAdapterExecutionTimeoutErrorMessage(prepared.timeoutResolution)
4158
+ : channelLost
4159
+ ? channelLostMessage
4160
+ : formatTerminalSessionFailure(resultErrorMessage(terminal), failureDiagnostic);
4161
+ const terminalStopReason = terminal.status === "failed" ? terminal.error.message : terminal.stopReason;
4162
+ const classifiedFailure = !timedOut && !channelLost && terminal.status === "failed"
4163
+ ? terminalFailureClassification
4164
+ : null;
4165
+ await emitAcpxLog(ctx, {
4166
+ type: turnSucceeded ? "acpx.result" : "acpx.error",
4167
+ summary: channelLost ? "duplex_channel_lost" : terminal.status,
4168
+ stopReason: terminalStopReason,
4169
+ message: errorMessage,
4170
+ });
4171
+ // The one clean-completion path clears the run failure flag; every other
4172
+ // path keeps it set, so the run root span closes with error status. A
4173
+ // completed terminal with a lost duplex channel keeps the flag set.
4174
+ runFailed = turnSucceeded ? false : true;
4175
+ capturedResult = {
4176
+ exitCode: turnSucceeded ? 0 : 1,
4177
+ signal: timedOut ? "SIGTERM" : null,
4178
+ timedOut,
4179
+ errorMessage,
4180
+ errorCode: timedOut
4181
+ ? "acpx_timeout"
4182
+ : channelLost
4183
+ ? DUPLEX_CHANNEL_LOST_ERROR_CODE
4184
+ : terminal.status === "failed"
4185
+ ? classifiedFailure?.errorCode ?? "acpx_turn_failed"
4186
+ : null,
4187
+ ...(classifiedFailure?.errorFamily ? { errorFamily: classifiedFailure.errorFamily } : {}),
4188
+ ...(classifiedFailure?.retryNotBefore ? { retryNotBefore: classifiedFailure.retryNotBefore } : {}),
4189
+ sessionId: sessionHandle.backendSessionId ?? sessionHandle.runtimeSessionName,
4190
+ sessionParams: buildSessionParams({ prepared, handle: sessionHandle }),
4191
+ sessionDisplayId: sessionHandle.agentSessionId ?? sessionHandle.backendSessionId ?? sessionHandle.runtimeSessionName,
4192
+ ...billingFields,
4193
+ ...referencedProjectStagingFailuresField,
4194
+ model: prepared.requestedModel || null,
4195
+ ...(turnUsage.usage ? { usage: turnUsage.usage, usageBasis: "per_run" } : {}),
4196
+ costUsd: turnUsage.costUsd,
4197
+ usageComplete,
4198
+ resultJson: {
4199
+ status: channelLost ? "failed" : terminal.status,
4200
+ ...activityDiagnostics,
4201
+ ...(failureDiagnostic ? { terminalSessionFailure: failureDiagnostic } : {}),
4202
+ ...(classifiedFailure?.errorFamily ? { errorFamily: classifiedFailure.errorFamily } : {}),
4203
+ ...(classifiedFailure?.retryNotBefore
4204
+ ? {
4205
+ retryNotBefore: classifiedFailure.retryNotBefore,
4206
+ ...(classifiedFailure.errorFamily === "provider_quota"
4207
+ ? { providerQuotaRetryNotBefore: classifiedFailure.retryNotBefore }
4208
+ : {}),
4209
+ }
4210
+ : {}),
4211
+ stopReason: terminalStopReason,
4212
+ permissionMode: prepared.permissionMode,
4213
+ mode: prepared.mode,
4214
+ requestedModel: prepared.requestedModel || null,
4215
+ requestedThinkingEffort: prepared.requestedThinkingEffort || null,
4216
+ fastMode: prepared.fastMode,
4217
+ ...(turnUsage.usageDetail ? { usage: turnUsage.usageDetail } : {}),
4218
+ ...(turnUsage.cumulativeCostUsd != null
4219
+ ? { cumulativeCostUsd: turnUsage.cumulativeCostUsd }
4220
+ : {}),
4221
+ },
4222
+ summary: buildAcpxRunSummary({
4223
+ outputSegments,
4224
+ fallback: terminalStopReason || terminal.status,
4225
+ }),
4226
+ clearSession,
4227
+ };
4228
+ // The turn phase finished. A completed, non-timed-out turn with a live
4229
+ // duplex channel is `ok`; every other terminal outcome is `failed`.
4230
+ await emitPhase("turn", turnPhaseStart, turnSucceeded ? "ok" : "failed");
4231
+ // Return the typed turn completion so the coordinator settles for the right
4232
+ // cause. The completion carries no live resources; the settlement claims the
4233
+ // ledger and owns the release. A clean completed turn carries no cause, so
4234
+ // the reuse decision can permit a save; a timed-out, failed, or cancelled
4235
+ // turn carries its cause, which forbids the save.
4236
+ if (timedOut) {
4237
+ return {
4238
+ kind: "timed_out",
4239
+ cause: { kind: "turn_timed_out", timeoutSec: prepared.timeoutSec },
4240
+ resources: emptyConsumed,
4241
+ };
4242
+ }
4243
+ if (terminal.status === "cancelled") {
4244
+ return {
4245
+ kind: "cancelled",
4246
+ cause: { kind: "turn_cancelled", reason: terminal.stopReason ?? "cancelled" },
4247
+ resources: emptyConsumed,
4248
+ };
4249
+ }
4250
+ // A duplex control-channel loss outranks a provider-reported failure or
4251
+ // completion: the loss reason explains why the provider terminal reads
4252
+ // the way it does, not the other way round. This also covers a
4253
+ // "completed" terminal whose channel died mid-turn. The message carries
4254
+ // only the typed loss reason, so no raw provider text rides the cause,
4255
+ // even when the provider terminal itself reports `failed`.
4256
+ if (channelLost) {
4257
+ return {
4258
+ kind: "failed",
4259
+ cause: {
4260
+ kind: "turn_failed",
4261
+ error: new Error(channelLostMessage ?? "The sandbox duplex control channel was lost."),
4262
+ },
4263
+ resources: emptyConsumed,
4264
+ };
4265
+ }
4266
+ if (terminal.status === "failed") {
4267
+ return {
4268
+ kind: "failed",
4269
+ cause: {
4270
+ kind: "turn_failed",
4271
+ error: terminal.error instanceof Error ? terminal.error : new Error(String(terminal.error)),
4272
+ },
4273
+ resources: emptyConsumed,
4274
+ };
4275
+ }
4276
+ return { kind: "finalized" };
4277
+ }
4278
+ const err = input.error;
4279
+ const timedOut = input.timedOut;
4280
+ // The failure phase comes from the sequence: a failure before the turn
4281
+ // started is `prepare_turn`; a failure after it is `turn`. The teardown is
4282
+ // the same; only the reported phase differs.
4283
+ const phase = input.phase;
4284
+ // Emit the failed phase timing for the phase the sequence reported.
4285
+ if (phase === "prepare_turn") {
4286
+ await emitPhase("prepare_turn", preparePhaseStart, "failed");
4287
+ }
4288
+ else {
4289
+ await emitPhase("turn", turnPhaseStart, "failed");
4290
+ }
4291
+ const messageOverride = timedOut
4292
+ ? formatAdapterExecutionTimeoutErrorMessage(prepared.timeoutResolution)
4293
+ : undefined;
4294
+ const preEmitMessage = messageOverride ?? (err instanceof Error ? err.message : String(err));
4295
+ // Record a direct close for the settlement `endSession` step: cancel the
4296
+ // running turn first (cancel-before-close), then close the runtime and drop
4297
+ // a matching warm entry. The settlement discards the staged runtime, stops
4298
+ // the bridges, releases the staging lease, and flushes the child stderr.
4299
+ runtimeSettlement = {
4300
+ mode: "direct",
4301
+ handle: sessionHandle,
4302
+ reason: timedOut ? "paperclip timeout cleanup" : "paperclip error cleanup",
4303
+ discardPersistentState: timedOut,
4304
+ dropWarmEntry: true,
4305
+ recordCloseError: true,
4306
+ cancelTurnReason: preEmitMessage,
4307
+ skipRemoteClose: false,
4308
+ };
4309
+ // Emit the failure best-effort. `turnFinalize` must not reject, so a
4310
+ // failing emission never propagates: the settlement owns the teardown, and
4311
+ // it runs only after this returns a completion. On an emission failure the
4312
+ // run records a degraded result from the pre-emit message.
4313
+ let emitted = null;
4314
+ try {
4315
+ emitted = await emitAcpxFailure({ ctx, prepared, err, phase, messageOverride });
4316
+ }
4317
+ catch {
4318
+ emitted = null;
4319
+ }
4320
+ const message = emitted?.message ?? preEmitMessage;
4321
+ capturedResult = {
4322
+ exitCode: 1,
4323
+ signal: timedOut ? "SIGTERM" : null,
4324
+ timedOut,
4325
+ errorMessage: message,
4326
+ errorCode: timedOut ? "acpx_timeout" : (emitted?.classified.errorCode ?? null),
4327
+ errorMeta: emitted?.classified.errorMeta,
4328
+ ...observedUsage,
4329
+ ...(!turnDispatchAttempted ? { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } : {}),
4330
+ ...billingFields,
4331
+ ...referencedProjectStagingFailuresField,
4332
+ model: prepared.requestedModel || null,
4333
+ clearSession: clearSession || timedOut,
4334
+ resultJson: { phase, ...activityDiagnostics },
4335
+ summary: message,
4336
+ };
4337
+ // Return a typed failed completion so the coordinator settles for a cause
4338
+ // that forbids the save. The reported phase lives on the recorded result.
4339
+ return {
4340
+ kind: "failed",
4341
+ cause: { kind: "turn_failed", error: err instanceof Error ? err : new Error(String(err)) },
4342
+ resources: emptyConsumed,
4343
+ };
4344
+ };
4345
+ try {
4346
+ return await runTurnSequence({
4347
+ signal: ctx.signal,
4348
+ timeoutMs: prepared.timeoutSec > 0 ? prepared.timeoutSec * 1000 : undefined,
4349
+ timeoutMessage: formatAdapterExecutionTimeoutErrorMessage(prepared.timeoutResolution),
4350
+ promptBuild: stepPromptBuild,
4351
+ preTurnUsage: stepPreTurnUsage,
4352
+ turnStart: stepTurnStart,
4353
+ eventRelay: stepEventRelay,
4354
+ turnFinalize: stepTurnFinalize,
4355
+ });
4356
+ }
4357
+ finally {
4358
+ // End the agent turn span exactly once, on every return and on a throw.
4359
+ // `runFailed` is `false` only on a completed, non-timed-out turn, so the
4360
+ // span status is correct for success, error, and timeout.
4361
+ turnSpan.end(runFailed);
4362
+ // Reset the current-run holder to the `task.run` token after the turn.
4363
+ // The run stays live here, so the holder is never `undefined`. A detached
4364
+ // exec after the turn parents to `task.run`.
4365
+ currentRunParentContext = runRootSpan.parentContext;
4366
+ }
4367
+ };
4368
+ // A live run-scoped credential marker. The host-lane reuse candidate carries
4369
+ // it, so the Amendment B credential gate blocks the host warm save: the
4370
+ // run-minted API key is never revoked, so it stays valid and forces a
4371
+ // close-and-relaunch. It is a non-secret marker; the settlement reads only its
4372
+ // presence, and no report or reuse payload carries it.
4373
+ const LIVE_RUN_SCOPED_API_KEY = "paperclip-run-scoped-api-key";
4374
+ // Record the final per-resource disposition report where a test can observe
4375
+ // it. The engine never reads it back.
4376
+ const recordDispositionReport = (report) => {
4377
+ deps.onSettlementDisposition?.(report);
4378
+ };
4379
+ // The settlement sequence is the one live cleanup owner for every settled path
4380
+ // (Phase 22). It claims the ledger once, makes the pure reuse decision, then
4381
+ // runs the ordered steps: `endSession`, `settleReuse`, `stopTransport`,
4382
+ // `syncBack`, and `releaseStagingLease` (in a finally). Each step reads the run
4383
+ // state through the shared closure locals and no-ops on an empty ledger slot.
4384
+ // The Phase 3 error policy governs every step. The coordinator alone owns the
4385
+ // startup rollback.
4386
+ const settlementSteps = {
4387
+ // Derive the reuse candidate. Only a clean turn (no cause) can save. The
4388
+ // host lane would save the live runtime, but the Amendment B credential gate
4389
+ // fails there: the run-minted API key is never revoked, so a live run-scoped
4390
+ // credential stays valid and the decision discards (close-and-relaunch). The
4391
+ // sandbox lane saves its staged files, which carry no credential.
4392
+ reuseCandidate: (slots, cause) => {
4393
+ const clean = cause === null;
4394
+ if (prepared.processSessionBridge) {
4395
+ // Sandbox lane: the staged files are the reuse. Save only after a clean
4396
+ // turn and only when the run holds a staged runtime.
4397
+ if (!clean || !slots.has("staged_runtime"))
4398
+ return null;
4399
+ return { kind: "sandbox", causePermitsSave: true, liveRunScopedCredentials: [] };
4400
+ }
4401
+ // Host lane: save a clean persistent warm-eligible turn, but carry the
4402
+ // live run-scoped credential so the gate blocks the transfer.
4403
+ if (!slots.has("acp_runtime"))
4404
+ return null;
4405
+ const permits = clean && prepared.mode === "persistent" && warmIdleMs > 0;
4406
+ if (!permits)
4407
+ return null;
4408
+ return { kind: "host", causePermitsSave: true, liveRunScopedCredentials: [LIVE_RUN_SCOPED_API_KEY] };
4409
+ },
4410
+ // Close every runtime the decision did not transfer, and drop the warm entry
4411
+ // on close.
4412
+ endSession: (slots, decision) => timedPhase("end_session", async () => {
4413
+ // The fence is the one idempotent owner of the abandoned promise's
4414
+ // eventual handle. Seal it first, before every other decision
4415
+ // below, including the empty-slot and save early returns: a late
4416
+ // handle that already arrived must never race this step.
4417
+ const lateHandle = handshakeFence.seal();
4418
+ if (!slots.has("acp_runtime"))
4419
+ return;
4420
+ if (decision.kind === "save" && decision.savedId === "acp_runtime")
4421
+ return;
4422
+ const baseSettlement = runtimeSettlement ?? {
4423
+ mode: "direct",
4424
+ handle: syntheticCloseHandle(),
4425
+ reason: "paperclip cleanup",
4426
+ discardPersistentState: false,
4427
+ dropWarmEntry: false,
4428
+ recordCloseError: true,
4429
+ cancelTurnReason: null,
4430
+ skipRemoteClose: false,
4431
+ };
4432
+ // A late handle that arrived before this seal replaces the synthetic
4433
+ // placeholder, so the one close call below uses the real identity
4434
+ // `ensureSession` eventually returned.
4435
+ const settlement = lateHandle
4436
+ ? { ...baseSettlement, handle: lateHandle }
4437
+ : baseSettlement;
4438
+ // Cancel a running turn before the close (the turn-error path).
4439
+ if (settlement.cancelTurnReason && activeTurn) {
4440
+ await withAdapterExecutionPhase(ctx, "cancel_turn", () => activeTurn.cancel({ reason: settlement.cancelTurnReason }).catch(() => { }));
4441
+ }
4442
+ const existing = warmHandles.get(prepared.sessionKey);
4443
+ // Re-read the duplex control-channel disposition here, at the
4444
+ // boundary that places the remote call. The settlement snapshot
4445
+ // above can predate a channel loss the bridge latches during the
4446
+ // awaited finalization work between the snapshot and this point, so
4447
+ // a stale `false` on the snapshot must not force a call onto a
4448
+ // channel that is dead by now. The read is non-mutating and only
4449
+ // adds a later-observed loss; it never clears the snapshot's `true`.
4450
+ const remoteChannelLost = settlement.skipRemoteClose || (prepared.paperclipBridge?.readRunDisposition?.().failed ?? false);
4451
+ // The control channel is already known lost, so no remote call can
4452
+ // reach the backend. Release the local bookkeeping only and place no
4453
+ // `runtime.close(...)` call — that call has no deadline of its own
4454
+ // and would block on the dead channel.
4455
+ if (remoteChannelLost) {
4456
+ if (warmHandleMatches(existing, runtime, settlement.handle) && existing) {
4457
+ clearWarmHandleTimer(existing);
4458
+ warmHandles.delete(prepared.sessionKey);
4459
+ flushChildStderr(existing.childStderrState);
4460
+ }
4461
+ return;
4462
+ }
4463
+ // The handshake guard abandoned this `ensureSession` call and no late
4464
+ // handle has arrived yet. Do not close the synthetic placeholder now:
4465
+ // the real handle can still resolve later, and closing it too would
4466
+ // close the same session twice. `handshakeFence`'s own late-arrival
4467
+ // hook (armed at the `ensureSession` call site) closes it once,
4468
+ // whenever it shows up. A guarded call only ever runs on a cold
4469
+ // start, so there is no matching warm entry here to drop.
4470
+ if (handshakeAbandoned && !lateHandle)
4471
+ return;
4472
+ if (settlement.mode === "warm_or_close" &&
4473
+ warmHandleMatches(existing, runtime, settlement.handle) &&
4474
+ existing) {
4475
+ // A matching warm entry closes through the warm store, which also
4476
+ // clears its idle timer and flushes its child stderr.
4477
+ runtimeStopConfirmed = await withAdapterExecutionPhase(ctx, "close_session", () => closeWarmHandle({
4478
+ handles: warmHandles,
4479
+ key: prepared.sessionKey,
4480
+ entry: existing,
4481
+ reason: settlement.reason,
4482
+ discardPersistentState: settlement.discardPersistentState,
4483
+ }));
4484
+ return;
4485
+ }
4486
+ const onCloseError = settlement.recordCloseError || ctx.signal?.aborted
4487
+ ? (closeErr) => recordTeardownError("runtime-close", closeErr)
4488
+ : () => { };
4489
+ await withAdapterExecutionPhase(ctx, "close_session", () => runtime
4490
+ .close({
4491
+ handle: settlement.handle,
4492
+ reason: settlement.reason,
4493
+ discardPersistentState: settlement.discardPersistentState,
4494
+ })
4495
+ .then(() => { runtimeStopConfirmed = true; })
4496
+ .catch(onCloseError));
4497
+ if (settlement.dropWarmEntry && warmHandleMatches(existing, runtime, settlement.handle) && existing) {
4498
+ clearWarmHandleTimer(existing);
4499
+ warmHandles.delete(prepared.sessionKey);
4500
+ }
4501
+ }),
4502
+ // Perform the reuse decision. A save transfers the staged files to the site
4503
+ // store (which arms the idle policy); every other case discards the staged
4504
+ // runtime. The host warm save is closed in `endSession`.
4505
+ settleReuse: (slots, decision) => timedPhase("settle_reuse", async () => {
4506
+ if (!slots.has("staged_runtime"))
4507
+ return;
4508
+ if (decision.kind === "save" && decision.savedId === "staged_runtime") {
4509
+ saveStagedRuntimeAfterCleanTurn({ handles: stagedRuntimes, prepared, now: now() });
4510
+ return;
4511
+ }
4512
+ await discardStagedRuntime({ handles: stagedRuntimes, prepared });
4513
+ }),
4514
+ // Stop both bridges in one allSettled.
4515
+ stopTransport: () => timedPhase("stop_transport", async () => {
4516
+ await stopRunTransport(prepared);
4517
+ }),
4518
+ // The site sync-back (the managed-home copy-back). The run-parented span
4519
+ // runner wraps the restore in a `sandbox.syncBack` span. The runner also
4520
+ // publishes the run parent into the runtime-parent store while the restore
4521
+ // runs, so the host mints a `traceparent` for the provider spans, and the
4522
+ // per-task restore spans parent to `sandbox.syncBack`.
4523
+ syncBack: () => timedPhase("sync_back", async () => {
4524
+ // A transport error or terminal narrative cannot authorize collecting
4525
+ // mutable provider files. Require the owned close or local OS handle.
4526
+ const stopped = runtimeStopConfirmed || (!prepared.processSessionBridge && capturedProcessExited(processIdentitySink?.localProcess));
4527
+ try {
4528
+ if (stopped)
4529
+ await withAdapterExecutionPhase(ctx, "instruction_collection", () => ctx.onProviderStopped?.());
4530
+ }
4531
+ catch {
4532
+ // Match ACP's fail-soft teardown policy without describing this as
4533
+ // a workspace restore failure or exposing paths from a raw error.
4534
+ await recordTeardownError("instruction-collection", new Error("Instruction collection failed after provider stop. No instruction save is claimed."));
4535
+ }
4536
+ finally {
4537
+ await withAdapterExecutionPhase(ctx, "workspace_restore", () => runRuntimeSpan("sandbox.syncBack", async () => {
4538
+ const restoreOutcome = await syncBackManagedHome(prepared);
4539
+ if (!restoreOutcome.ok) {
4540
+ workspaceRestoreFailureField = {
4541
+ workspaceRestoreFailure: restoreOutcome.code,
4542
+ ...(restoreOutcome.diagnostic ? { workspaceRestoreDiagnostic: restoreOutcome.diagnostic } : {}),
4543
+ };
4544
+ }
4545
+ }));
4546
+ }
4547
+ }),
4548
+ // The staging lease releases as the run's final act, AFTER the coordinator
4549
+ // reproduces the result, in the run root `finally` below. This step stays a
4550
+ // no-op in the live engine: a same-session second run must stay blocked on
4551
+ // the lease until this run fully returns, not merely until the settlement
4552
+ // sync-back finishes, so the release cannot move earlier into settlement.
4553
+ releaseStagingLease: () => { },
4554
+ recordError: async (step, error) => {
4555
+ await recordTeardownError(`settlement-${step}`, error);
4556
+ },
4557
+ };
4558
+ // Drive the attempt through the coordinator routing table. The startup step
4559
+ // returns `ready` or `settle` (or throws on a build or partial-bridge
4560
+ // failure); the coordinator runs the turn on the ready path, settles, then
4561
+ // reproduces the recorded result.
4562
+ const plan = {
4563
+ ledger: runResourceLedger,
4564
+ startup,
4565
+ runTurn,
4566
+ // The coordinator owns the startup rollback: `buildRuntime` runs its own
4567
+ // partial-bring-up rollback and throws, so no ledger resource is left to
4568
+ // release here.
4569
+ rollbackStartup: () => { },
4570
+ recordDisposition: recordDispositionReport,
4571
+ // The settlement sequence is the one live cleanup owner. It claims the
4572
+ // ledger, releases every settled resource, and returns the final
4573
+ // disposition report. The child stderr flushes after the sync-back on every
4574
+ // settled exit path (it stays null before the run reads the warm entry).
4575
+ settle: async (reason) => {
4576
+ const cause = reason.kind === "pre_turn"
4577
+ ? reason.cause
4578
+ : reason.completion.kind === "finalized"
4579
+ ? null
4580
+ : reason.completion.cause;
4581
+ const report = await settleAcpRun(runResourceLedger, cause, settlementSteps);
4582
+ recordDispositionReport(report);
4583
+ if (childStderrState)
4584
+ flushChildStderr(childStderrState);
4585
+ },
4586
+ reproduceResult: async () => {
4587
+ if (!capturedResult) {
4588
+ throw new Error("run coordinator reproduced a result before the run recorded one");
4589
+ }
4590
+ clearTimeout(stopTimer);
4591
+ let providerExited = false;
4592
+ const providerPid = processIdentitySink?.latest?.pid;
4593
+ if (ctx.signal?.aborted && providerPid && !prepared.processSessionBridge) {
4594
+ for (let attempt = 0; attempt < 40; attempt += 1) {
4595
+ providerExited = capturedProcessExited(processIdentitySink.localProcess);
4596
+ if (providerExited || !forcedStop)
4597
+ break;
4598
+ await new Promise((resolve) => setTimeout(resolve, 25));
4599
+ }
4600
+ }
4601
+ // A forced process exit can reject ACP close after the OS has already
4602
+ // confirmed termination. Acknowledge Stop, but never grant replay.
4603
+ if (ctx.signal?.aborted && providerExited && (runtimeStopConfirmed || forcedStop)) {
4604
+ capturedResult = {
4605
+ ...capturedResult,
4606
+ ...(safeInterruptedSession && !forcedStop && !("workspaceRestoreFailure" in workspaceRestoreFailureField)
4607
+ ? { executionRecovery: { kind: "interrupted", providerStopped: true, sessionPreserved: true, actionOutcomes: "settled" },
4608
+ sessionParams: { ...capturedResult.sessionParams, interruptedCheckpoint: true } }
4609
+ : {}),
4610
+ resultJson: { ...capturedResult.resultJson, executionCancellation: {
4611
+ state: "acknowledged", acknowledgedAt: new Date().toISOString(), forced: forcedStop,
4612
+ } },
4613
+ };
4614
+ }
4615
+ // Preserve the policy resolved for this execution target. The server
4616
+ // cannot reconstruct sandbox defaults from the stored agent config.
4617
+ capturedResult = {
4618
+ ...capturedResult,
4619
+ resultJson: {
4620
+ ...capturedResult.resultJson,
4621
+ adapterExecutionTimeout: { ...prepared.timeoutResolution },
4622
+ },
4623
+ };
4624
+ // The sync-back settlement step runs before this reproduces the result
4625
+ // (settlement precedes reproduction), so a failed workspace restore is
4626
+ // already recorded by the time we get here. Merge it into `resultJson`
4627
+ // only on a failure — a clean restore adds no new key.
4628
+ if (!("workspaceRestoreFailure" in workspaceRestoreFailureField)) {
4629
+ return capturedResult;
4630
+ }
4631
+ return {
4632
+ ...capturedResult,
4633
+ resultJson: {
4634
+ ...(capturedResult.resultJson ?? {}),
4635
+ ...workspaceRestoreFailureField,
4636
+ },
4637
+ };
4638
+ },
4639
+ };
4640
+ return await runAttempt(plan);
4641
+ }
4642
+ finally {
4643
+ clearTimeout(stopTimer);
4644
+ removeStopListener?.();
4645
+ removeLossListener?.();
4646
+ clearTimeout(lossDeadlineTimer);
4647
+ // End the run root span exactly once, on every return and on a throw.
4648
+ runRootSpan.end(runFailed);
4649
+ // Release the per-session staging lease as the run's final act, AFTER the
4650
+ // coordinator settled every other resource and reproduced the result. It runs
4651
+ // last, in this `finally`, so a same-session second run stays blocked on the
4652
+ // lease until this run fully returns (not merely until the settlement
4653
+ // sync-back finishes) and an earlier teardown fault never strands the lease.
4654
+ // It stays null on a build failure (where `buildRuntime` released its own
4655
+ // partial lease) and on the host lane (no staging). The settlement stopped the
4656
+ // bridges and ran the sync-back before this point, so the ordering is
4657
+ // bridge-stop → sync-back → lease release.
4658
+ const leaseRelease = releaseStagingLease;
4659
+ if (leaseRelease) {
4660
+ const leaseStart = now();
4661
+ leaseRelease();
4662
+ // Fire-and-forget the phase timing: the release is the run's final act, so
4663
+ // the run must not await telemetry here. `emitRunPhaseTiming` swallows a
4664
+ // sink failure, so this never rejects.
4665
+ void emitRunPhaseTiming(ctx, "release_staging_lease", now() - leaseStart, "ok");
4666
+ }
4667
+ }
4668
+ };
4669
+ }
4670
+ export const execute = createAcpxEngineExecutor();
4671
+ //# sourceMappingURL=execute.js.map