stitchkit 0.132.3 → 0.133.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 (338) hide show
  1. package/CHANGELOG.md +178 -1
  2. package/README.md +4 -0
  3. package/dist/agent-executor/acp/v1-connect.d.ts +12 -1
  4. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  5. package/dist/agent-executor/acp/v1-driver.d.ts +3 -1
  6. package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
  7. package/dist/agent-executor/acp/v1-handlers.d.ts +9 -1
  8. package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -1
  9. package/dist/agent-executor/acp/v1-permission.d.ts +3 -2
  10. package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -1
  11. package/dist/agent-executor/acp/v1-probe.d.ts +10 -1
  12. package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -1
  13. package/dist/agent-executor/acp/v1-session.d.ts +11 -2
  14. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  15. package/dist/agent-executor/acp/v1-turn.d.ts +13 -10
  16. package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
  17. package/dist/agent-executor/claude/cli-driver.d.ts +6 -0
  18. package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
  19. package/dist/agent-executor/claude/record-router.d.ts +44 -0
  20. package/dist/agent-executor/claude/record-router.d.ts.map +1 -0
  21. package/dist/agent-executor/claude/session.d.ts +2 -0
  22. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  23. package/dist/agent-executor/claude-sdk/driver.d.ts +20 -2
  24. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  25. package/dist/agent-executor/claude-sdk/engine-spawn.d.ts +18 -0
  26. package/dist/agent-executor/claude-sdk/engine-spawn.d.ts.map +1 -0
  27. package/dist/agent-executor/claude-sdk/query-loop.d.ts +8 -11
  28. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
  29. package/dist/agent-executor/claude-sdk/query-manager.d.ts +4 -2
  30. package/dist/agent-executor/claude-sdk/query-manager.d.ts.map +1 -1
  31. package/dist/agent-executor/claude-sdk/query-options.d.ts +1 -0
  32. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -1
  33. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  34. package/dist/agent-executor/codex/capabilities.d.ts +8 -0
  35. package/dist/agent-executor/codex/capabilities.d.ts.map +1 -0
  36. package/dist/agent-executor/codex/connect.d.ts +6 -1
  37. package/dist/agent-executor/codex/connect.d.ts.map +1 -1
  38. package/dist/agent-executor/codex/driver.d.ts +10 -0
  39. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  40. package/dist/agent-executor/codex/event-routing.d.ts +23 -1
  41. package/dist/agent-executor/codex/event-routing.d.ts.map +1 -1
  42. package/dist/agent-executor/codex/handlers.d.ts +23 -3
  43. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  44. package/dist/agent-executor/codex/limits.d.ts +17 -0
  45. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  46. package/dist/agent-executor/codex/request-answers.d.ts +23 -3
  47. package/dist/agent-executor/codex/request-answers.d.ts.map +1 -1
  48. package/dist/agent-executor/codex/session-bind.d.ts +6 -1
  49. package/dist/agent-executor/codex/session-bind.d.ts.map +1 -1
  50. package/dist/agent-executor/codex/session-types.d.ts +5 -1
  51. package/dist/agent-executor/codex/session-types.d.ts.map +1 -1
  52. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  53. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  54. package/dist/agent-executor/codex/shared-thread.d.ts +6 -8
  55. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  56. package/dist/agent-executor/codex/thread-open.d.ts +12 -3
  57. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
  58. package/dist/agent-executor/engine-requests.d.ts +42 -0
  59. package/dist/agent-executor/engine-requests.d.ts.map +1 -1
  60. package/dist/agent-executor/handoff-schemas.d.ts.map +1 -1
  61. package/dist/agent-executor/handoff.d.ts.map +1 -1
  62. package/dist/agent-executor/image-input.d.ts +6 -5
  63. package/dist/agent-executor/image-input.d.ts.map +1 -1
  64. package/dist/agent-executor/profile.d.ts +3 -5
  65. package/dist/agent-executor/profile.d.ts.map +1 -1
  66. package/dist/agent-executor/session-primitives.d.ts +64 -3
  67. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  68. package/dist/agent-executor/testing/claude-sdk-stubs.d.ts +5 -0
  69. package/dist/agent-executor/testing/claude-sdk-stubs.d.ts.map +1 -0
  70. package/dist/agent-executor/testing/conformance-lifecycle.d.ts +11 -0
  71. package/dist/agent-executor/testing/conformance-lifecycle.d.ts.map +1 -0
  72. package/dist/agent-executor/testing/conformance-support.d.ts +23 -0
  73. package/dist/agent-executor/testing/conformance-support.d.ts.map +1 -0
  74. package/dist/agent-executor/testing/conformance.d.ts +7 -2
  75. package/dist/agent-executor/testing/conformance.d.ts.map +1 -1
  76. package/dist/agent-executor/testing/consumer-stubs.d.ts +5 -3
  77. package/dist/agent-executor/testing/consumer-stubs.d.ts.map +1 -1
  78. package/dist/agent-executor/testing/fake-codex-app-server.d.ts +5 -1
  79. package/dist/agent-executor/testing/fake-codex-app-server.d.ts.map +1 -1
  80. package/dist/agent-executor/testing/replay-driver.d.ts +6 -0
  81. package/dist/agent-executor/testing/replay-driver.d.ts.map +1 -1
  82. package/dist/agent-executor/testing/replay-gate.d.ts +4 -1
  83. package/dist/agent-executor/testing/replay-gate.d.ts.map +1 -1
  84. package/dist/agent-runtime/deferred-tool-types.d.ts +2 -0
  85. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  86. package/dist/agent-runtime/deferred-tools.d.ts.map +1 -1
  87. package/dist/browser/client.d.ts.map +1 -1
  88. package/dist/browser/operation-refusal.d.ts +10 -0
  89. package/dist/browser/operation-refusal.d.ts.map +1 -0
  90. package/dist/contract/client-types.d.ts +13 -4
  91. package/dist/contract/client-types.d.ts.map +1 -1
  92. package/dist/contract/define-validation.d.ts +6 -0
  93. package/dist/contract/define-validation.d.ts.map +1 -1
  94. package/dist/contract/define.d.ts +3 -0
  95. package/dist/contract/define.d.ts.map +1 -1
  96. package/dist/contract/errors-factory.d.ts +8 -2
  97. package/dist/contract/errors-factory.d.ts.map +1 -1
  98. package/dist/contract/errors.d.ts +9 -0
  99. package/dist/contract/errors.d.ts.map +1 -1
  100. package/dist/contract/fingerprint.d.ts +4 -1
  101. package/dist/contract/fingerprint.d.ts.map +1 -1
  102. package/dist/contract/operation-refusals.d.ts +51 -0
  103. package/dist/contract/operation-refusals.d.ts.map +1 -0
  104. package/dist/contract/tool-options.d.ts +4 -0
  105. package/dist/contract/tool-options.d.ts.map +1 -1
  106. package/dist/entrypoints/agent-executor/acp.js +253 -210
  107. package/dist/entrypoints/agent-executor/claude-sdk.js +248 -173
  108. package/dist/entrypoints/agent-executor/claude.js +57 -109
  109. package/dist/entrypoints/agent-executor/codex.js +412 -335
  110. package/dist/entrypoints/agent-executor/testing/claude-sdk.d.ts +3 -0
  111. package/dist/entrypoints/agent-executor/testing/claude-sdk.d.ts.map +1 -0
  112. package/dist/entrypoints/agent-executor/testing/claude-sdk.js +329 -0
  113. package/dist/entrypoints/agent-executor/testing.d.ts +1 -2
  114. package/dist/entrypoints/agent-executor/testing.d.ts.map +1 -1
  115. package/dist/entrypoints/agent-executor/testing.js +413 -667
  116. package/dist/entrypoints/agent-executor.d.ts +1 -1
  117. package/dist/entrypoints/agent-executor.d.ts.map +1 -1
  118. package/dist/entrypoints/agent-executor.js +12 -12
  119. package/dist/entrypoints/agent-runtime/browser.js +2 -2
  120. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  121. package/dist/entrypoints/agent-runtime/harness.js +8 -8
  122. package/dist/entrypoints/agent-runtime/postgres.js +5 -5
  123. package/dist/entrypoints/agent-runtime/realtime.js +2 -2
  124. package/dist/entrypoints/agent-runtime/sandbox.js +3 -3
  125. package/dist/entrypoints/agent-runtime/sqlite/bun.js +6 -6
  126. package/dist/entrypoints/agent-runtime/sqlite/node.js +6 -6
  127. package/dist/entrypoints/agent-runtime/testing.js +5 -5
  128. package/dist/entrypoints/agent-runtime.js +26 -18
  129. package/dist/entrypoints/application/grammy.js +1 -1
  130. package/dist/entrypoints/application.js +2 -2
  131. package/dist/entrypoints/cli.js +8 -8
  132. package/dist/entrypoints/contract.d.ts +3 -2
  133. package/dist/entrypoints/contract.d.ts.map +1 -1
  134. package/dist/entrypoints/contract.js +6 -4
  135. package/dist/entrypoints/files/packaging.d.ts +4 -1
  136. package/dist/entrypoints/files/packaging.d.ts.map +1 -1
  137. package/dist/entrypoints/files/packaging.js +1008 -168
  138. package/dist/entrypoints/files.js +1 -1
  139. package/dist/entrypoints/handler.js +7 -7
  140. package/dist/entrypoints/http.js +2 -2
  141. package/dist/entrypoints/index.js +10 -8
  142. package/dist/entrypoints/node.js +11 -11
  143. package/dist/entrypoints/observability.js +1 -1
  144. package/dist/entrypoints/process/bootstrap.d.ts +3 -0
  145. package/dist/entrypoints/process/bootstrap.d.ts.map +1 -0
  146. package/dist/entrypoints/process/bootstrap.js +16 -0
  147. package/dist/entrypoints/process.js +7 -7
  148. package/dist/entrypoints/realtime.js +3 -3
  149. package/dist/entrypoints/remote.js +8 -7
  150. package/dist/entrypoints/server.js +30 -14
  151. package/dist/entrypoints/service-host/macos.js +72 -206
  152. package/dist/entrypoints/service-host/work.d.ts +15 -0
  153. package/dist/entrypoints/service-host/work.d.ts.map +1 -0
  154. package/dist/entrypoints/service-host/work.js +676 -0
  155. package/dist/entrypoints/service-host.js +146 -536
  156. package/dist/entrypoints/telegram/screens.js +4 -4
  157. package/dist/entrypoints/telegram.js +4 -4
  158. package/dist/entrypoints/testing.d.ts +2 -1
  159. package/dist/entrypoints/testing.d.ts.map +1 -1
  160. package/dist/entrypoints/testing.js +27 -8
  161. package/dist/entrypoints/tools/agent.js +6 -6
  162. package/dist/entrypoints/tools/connections.js +2 -2
  163. package/dist/entrypoints/tools/invoker.js +5 -5
  164. package/dist/entrypoints/tools/mcp.js +8 -6
  165. package/dist/entrypoints/tools/toolkit.js +11 -9
  166. package/dist/entrypoints/tools.js +19 -17
  167. package/dist/entrypoints/tracking/contract.js +1 -1
  168. package/dist/entrypoints/tracking/performance.js +3 -3
  169. package/dist/files/client-artifact.d.ts +14 -42
  170. package/dist/files/client-artifact.d.ts.map +1 -1
  171. package/dist/files/client-build.d.ts +57 -0
  172. package/dist/files/client-build.d.ts.map +1 -0
  173. package/dist/files/client-declarations.d.ts +35 -0
  174. package/dist/files/client-declarations.d.ts.map +1 -0
  175. package/dist/files/client-package-bundle.d.ts +25 -0
  176. package/dist/files/client-package-bundle.d.ts.map +1 -0
  177. package/dist/files/client-package-contract.d.ts +183 -0
  178. package/dist/files/client-package-contract.d.ts.map +1 -0
  179. package/dist/files/client-package-proof.d.ts +40 -0
  180. package/dist/files/client-package-proof.d.ts.map +1 -0
  181. package/dist/files/client-package.d.ts +17 -0
  182. package/dist/files/client-package.d.ts.map +1 -0
  183. package/dist/files/declaration-specifiers.d.ts +30 -0
  184. package/dist/files/declaration-specifiers.d.ts.map +1 -0
  185. package/dist/{index-v759mzed.js → index-02r5sq9p.js} +36 -23
  186. package/dist/{index-0r15pkjq.js → index-0k1ba0ss.js} +1 -1
  187. package/dist/{index-znd1b57f.js → index-1dn2wjq6.js} +5 -4
  188. package/dist/{index-p06z7g7w.js → index-1p8q0yrt.js} +6 -5
  189. package/dist/{index-wa6h4tz6.js → index-1qwd54n3.js} +6 -5
  190. package/dist/index-2dzc7mv9.js +174 -0
  191. package/dist/index-2mz8hj58.js +155 -0
  192. package/dist/{index-17qgm6xe.js → index-34k82crg.js} +2 -2
  193. package/dist/index-3mcbr8sx.js +349 -0
  194. package/dist/{index-ybdq8kk2.js → index-3y2tzhr8.js} +3 -3
  195. package/dist/{index-fgahdc7s.js → index-5n3a8hd8.js} +5 -3
  196. package/dist/{index-jb4m241t.js → index-6918kxbf.js} +45 -1
  197. package/dist/{index-n3bm7zqq.js → index-6kmjcm81.js} +4 -4
  198. package/dist/{index-akf0xkrm.js → index-78da4g74.js} +1 -1
  199. package/dist/{index-9pv126eh.js → index-7fjbdga8.js} +7 -1
  200. package/dist/{index-zhshhxew.js → index-8jf4bt7v.js} +1 -1
  201. package/dist/{index-p16q492v.js → index-8t9dr41h.js} +18 -5
  202. package/dist/{index-xq4s9mka.js → index-8yt3rwe7.js} +1 -1
  203. package/dist/{index-39c2hj6h.js → index-9c76vfxf.js} +7 -3
  204. package/dist/index-9ft4n9j1.js +432 -0
  205. package/dist/{index-sd4e5x5j.js → index-9wdrwx3b.js} +8 -7
  206. package/dist/{index-z114ax5e.js → index-an7vcmwf.js} +49 -2
  207. package/dist/{index-pzhqydxb.js → index-d04w81fz.js} +1 -1
  208. package/dist/index-d2drhb9c.js +219 -0
  209. package/dist/{index-8gmmdz7k.js → index-dacxr7nf.js} +1 -1
  210. package/dist/{index-dnzxxf8a.js → index-dm6nxkn1.js} +1 -1
  211. package/dist/index-dxft2mnm.js +42 -0
  212. package/dist/{index-rxh3qy4x.js → index-fzd477xk.js} +1 -1
  213. package/dist/{index-xgae0bn7.js → index-g4gstmp1.js} +2 -2
  214. package/dist/{index-athc412x.js → index-g5fgeb6v.js} +1 -1
  215. package/dist/{index-z9d74jmb.js → index-gbhj370g.js} +3 -3
  216. package/dist/{index-3fym4j8n.js → index-gtaaxe9d.js} +1 -1
  217. package/dist/{index-v59pxmf1.js → index-jpecjm30.js} +2 -2
  218. package/dist/index-k9g061ma.js +164 -0
  219. package/dist/{index-669374qc.js → index-ma26mfnt.js} +84 -315
  220. package/dist/{index-ryxb427v.js → index-msxf2r8x.js} +16 -3
  221. package/dist/{index-rbd2rq3z.js → index-nr4fhfn4.js} +1 -1
  222. package/dist/{index-qa2jjb65.js → index-pbekeqzm.js} +1 -1
  223. package/dist/{index-mkfhpk11.js → index-pq6g1k9t.js} +2 -2
  224. package/dist/{index-gya4hwh3.js → index-pws5c3x6.js} +21 -1
  225. package/dist/{index-x2fb37t0.js → index-q427q23r.js} +3 -2
  226. package/dist/{index-jcrj0b8z.js → index-qggqqja2.js} +39 -2
  227. package/dist/{index-jxtg307y.js → index-rkjfzs0a.js} +1 -1
  228. package/dist/{index-5tdc0q43.js → index-rw8ze745.js} +5 -3
  229. package/dist/index-s43tr4my.js +129 -0
  230. package/dist/{index-f9p62ean.js → index-stpy56r3.js} +175 -249
  231. package/dist/index-t5g5rm9n.js +213 -0
  232. package/dist/{index-z20pdxeb.js → index-tmv3ez1h.js} +3 -3
  233. package/dist/{index-dcsxj68j.js → index-tqjamnax.js} +1 -1
  234. package/dist/{index-j15dhkda.js → index-wddcfbng.js} +1 -325
  235. package/dist/{index-9sfhje6y.js → index-wh70tmpd.js} +24 -234
  236. package/dist/index-wxjv4sqx.js +82 -0
  237. package/dist/{index-qhjmmsm2.js → index-x46y9z26.js} +2 -2
  238. package/dist/{index-nk0cy9g1.js → index-y53cqwke.js} +1 -1
  239. package/dist/{index-sv5svtq7.js → index-y68gavb5.js} +1 -1
  240. package/dist/{index-5y7j383h.js → index-yrhw10ef.js} +1 -1
  241. package/dist/process/bootstrap.d.ts +12 -0
  242. package/dist/process/bootstrap.d.ts.map +1 -0
  243. package/dist/process/owner-loss-guard.d.ts +2 -9
  244. package/dist/process/owner-loss-guard.d.ts.map +1 -1
  245. package/dist/process/work-root.d.ts +20 -0
  246. package/dist/process/work-root.d.ts.map +1 -0
  247. package/dist/server/contract-identity.d.ts.map +1 -1
  248. package/dist/server/contract-method.d.ts +12 -0
  249. package/dist/server/contract-method.d.ts.map +1 -1
  250. package/dist/server/implement.d.ts.map +1 -1
  251. package/dist/server/openapi.d.ts.map +1 -1
  252. package/dist/server/types.d.ts +10 -9
  253. package/dist/server/types.d.ts.map +1 -1
  254. package/dist/service-host/host-adapter.d.ts +2 -0
  255. package/dist/service-host/host-adapter.d.ts.map +1 -1
  256. package/dist/service-host/work/command.d.ts +72 -0
  257. package/dist/service-host/work/command.d.ts.map +1 -0
  258. package/dist/service-host/work/errors.d.ts +29 -0
  259. package/dist/service-host/work/errors.d.ts.map +1 -0
  260. package/dist/service-host/work/host.d.ts +38 -0
  261. package/dist/service-host/work/host.d.ts.map +1 -0
  262. package/dist/service-host/work/launch.d.ts +51 -0
  263. package/dist/service-host/work/launch.d.ts.map +1 -0
  264. package/dist/service-host/work/membership.d.ts +51 -0
  265. package/dist/service-host/work/membership.d.ts.map +1 -0
  266. package/dist/service-host/work/origin.d.ts +79 -0
  267. package/dist/service-host/work/origin.d.ts.map +1 -0
  268. package/dist/service-host/work/owner.d.ts +45 -0
  269. package/dist/service-host/work/owner.d.ts.map +1 -0
  270. package/dist/service-host/work/placement.d.ts +55 -0
  271. package/dist/service-host/work/placement.d.ts.map +1 -0
  272. package/dist/service-host/work/probe.d.ts +24 -0
  273. package/dist/service-host/work/probe.d.ts.map +1 -0
  274. package/dist/service-host/work/scope-command.d.ts +68 -0
  275. package/dist/service-host/work/scope-command.d.ts.map +1 -0
  276. package/dist/sync/session.d.ts +4 -1
  277. package/dist/sync/session.d.ts.map +1 -1
  278. package/dist/testing/surface-manifest-digest.d.ts +2 -0
  279. package/dist/testing/surface-manifest-digest.d.ts.map +1 -1
  280. package/dist/testing/surface-manifest.d.ts +32 -3
  281. package/dist/testing/surface-manifest.d.ts.map +1 -1
  282. package/dist/tools/agent.d.ts +2 -0
  283. package/dist/tools/agent.d.ts.map +1 -1
  284. package/dist/tools/cli/stream-surface.d.ts.map +1 -1
  285. package/dist/tools/internal/mcp-projection.d.ts +58 -0
  286. package/dist/tools/internal/mcp-projection.d.ts.map +1 -0
  287. package/dist/tools/internal/surface-projector.d.ts +3 -47
  288. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  289. package/dist/tools/invoker.d.ts +2 -0
  290. package/dist/tools/invoker.d.ts.map +1 -1
  291. package/dist/tools/manifest.d.ts +2 -0
  292. package/dist/tools/manifest.d.ts.map +1 -1
  293. package/dist/tools/mcp/handler.d.ts.map +1 -1
  294. package/dist/tools/mcp/lazy-discovery.d.ts.map +1 -1
  295. package/dist/tools/mcp/mount.d.ts +4 -0
  296. package/dist/tools/mcp/mount.d.ts.map +1 -1
  297. package/dist/tools/mcp/prepare.d.ts +5 -2
  298. package/dist/tools/mcp/prepare.d.ts.map +1 -1
  299. package/dist/tools/mount.d.ts +2 -0
  300. package/dist/tools/mount.d.ts.map +1 -1
  301. package/dist/tools/remote.d.ts.map +1 -1
  302. package/dist/tools/schema/nesting-limit.d.ts +8 -0
  303. package/dist/tools/schema/nesting-limit.d.ts.map +1 -0
  304. package/dist/tools/schema/presentation.d.ts +7 -0
  305. package/dist/tools/schema/presentation.d.ts.map +1 -1
  306. package/dist/tools/surface.d.ts.map +1 -1
  307. package/llms/agent-executor-acp.txt +3 -3
  308. package/llms/agent-executor-claude-sdk.txt +1 -1
  309. package/llms/agent-executor-claude.txt +1 -1
  310. package/llms/agent-executor-codex.txt +1 -1
  311. package/llms/agent-executor-testing-claude-sdk.txt +28 -0
  312. package/llms/agent-executor-testing.txt +7 -8
  313. package/llms/agent-executor.txt +27 -4
  314. package/llms/agent-runtime.txt +1 -1
  315. package/llms/contract.txt +8 -2
  316. package/llms/files-packaging.txt +11 -6
  317. package/llms/process-bootstrap.txt +18 -0
  318. package/llms/process.2.txt +248 -18
  319. package/llms/process.txt +130 -92
  320. package/llms/server.4.txt +49 -1
  321. package/llms/service-host-work.txt +34 -0
  322. package/llms/stitchkit.2.txt +31 -0
  323. package/llms/stitchkit.txt +78 -75
  324. package/llms/sync.txt +5 -2
  325. package/llms/testing.txt +1 -0
  326. package/llms/tools.2.txt +747 -775
  327. package/llms/tools.3.txt +846 -210
  328. package/llms/tools.4.txt +226 -0
  329. package/llms/tools.txt +3 -790
  330. package/llms/{upgrading-0.128.0-0.132.0.txt → upgrading-0.128.0-0.133.0.txt} +194 -6
  331. package/llms/upgrading.txt +1 -1
  332. package/llms-full.txt +779 -135
  333. package/llms.txt +18 -16
  334. package/package.json +12 -4
  335. package/dist/entrypoints/process/owner-loss.d.ts +0 -3
  336. package/dist/entrypoints/process/owner-loss.d.ts.map +0 -1
  337. package/dist/entrypoints/process/owner-loss.js +0 -7
  338. package/llms/process-owner-loss.txt +0 -18
@@ -1,8 +1,9 @@
1
1
  import"../../index-09f7w2qq.js";
2
- import"../../index-v59pxmf1.js";
3
- import"../../index-qa2jjb65.js";
2
+ import"../../index-jpecjm30.js";
3
+ import"../../index-pbekeqzm.js";
4
4
  import"../../index-6kec3b14.js";
5
5
  import"../../index-2rf33y2h.js";
6
+ import"../../index-s43tr4my.js";
6
7
  import {
7
8
  InteractionReplySchema2,
8
9
  PlanWindowSchema2,
@@ -17,14 +18,16 @@ import {
17
18
  createTurnDeltaChannel,
18
19
  offerTurnDelta,
19
20
  sessionAbort,
21
+ sessionLiveness,
20
22
  runEngineCli,
21
23
  stopConnection,
22
24
  withEphemeralConnection,
23
25
  safeJsonValue,
24
- invokeSafely,
26
+ reportObserverError,
27
+ invokeObserver,
25
28
  emitStartupPhase,
26
29
  clampUniqueWindowName
27
- } from "../../index-f9p62ean.js";
30
+ } from "../../index-stpy56r3.js";
28
31
  import {
29
32
  JsonRpcValueSchema2,
30
33
  JsonRpcError2,
@@ -67,14 +70,9 @@ import {
67
70
  CODEX_INPUT_REQUEST,
68
71
  CODEX_ELICITATION_REQUEST,
69
72
  CODEX_APPROVAL_DECISION,
70
- CodexUnixSocketError2,
71
- validateCodexUnixSocketPath,
72
- assertCodexUnixListenTargetAvailable,
73
- assertCodexUnixSocketClientTarget,
74
- maskedWsFrameByteLength,
75
- encodeMaskedWsFrame,
76
- createWsFrameDecoder
77
- } from "../../index-j15dhkda.js";
73
+ codexDriverCapabilities,
74
+ codexSharedServerCapabilities
75
+ } from "../../index-3mcbr8sx.js";
78
76
  import"../../index-673drwkn.js";
79
77
  import"../../index-vmbxj75t.js";
80
78
  import {
@@ -82,28 +80,41 @@ import {
82
80
  inlineOrderedParts,
83
81
  guardedTurnStarter
84
82
  } from "../../index-y0a4gt1s.js";
83
+ import {
84
+ CodexUnixSocketError2,
85
+ validateCodexUnixSocketPath,
86
+ assertCodexUnixListenTargetAvailable,
87
+ assertCodexUnixSocketClientTarget,
88
+ maskedWsFrameByteLength,
89
+ encodeMaskedWsFrame,
90
+ createWsFrameDecoder
91
+ } from "../../index-wddcfbng.js";
85
92
  import {
86
93
  holdEngineRequest,
87
- answerEngineRequest,
88
- drainEngineRequests,
89
94
  endEngineTurn,
90
- loseEngineTurn
91
- } from "../../index-jcrj0b8z.js";
95
+ loseEngineTurn,
96
+ leaveEngineRequestUnanswered,
97
+ refuseEngineTurnRequests,
98
+ interruptEngineTurn,
99
+ respondToEngineRequest
100
+ } from "../../index-qggqqja2.js";
92
101
  import {
93
102
  spawnEngineProcess2
94
- } from "../../index-rxh3qy4x.js";
95
- import"../../index-3fym4j8n.js";
103
+ } from "../../index-fzd477xk.js";
104
+ import"../../index-gtaaxe9d.js";
96
105
  import {
97
- planLimitsReadFailed2,
98
- mergeRateLimitEvent2
99
- } from "../../index-athc412x.js";
100
- import"../../index-pzhqydxb.js";
106
+ planLimitsReadFailed2
107
+ } from "../../index-g5fgeb6v.js";
108
+ import"../../index-d04w81fz.js";
101
109
  import {
102
110
  assertExpectedOwnerUid
103
111
  } from "../../index-hab790s6.js";
104
112
  import {
105
113
  errnoOf
106
114
  } from "../../index-jj9228tt.js";
115
+ import {
116
+ utf8ByteLength
117
+ } from "../../index-827bgv33.js";
107
118
  import {
108
119
  isPositiveSafeInteger,
109
120
  assertPositiveSafeInteger,
@@ -920,6 +931,9 @@ var REQUEST_MS = 60000;
920
931
  var DEFAULT_LISTEN_TIMEOUT_MS = 15000;
921
932
  var POLL_INITIAL_MS = 15;
922
933
  var POLL_MAX_MS = 50;
934
+ function codexTransportShared(config) {
935
+ return config.transport !== undefined && config.transport.kind !== "stdio";
936
+ }
923
937
  function validateCodexTransportAndArgs(config) {
924
938
  if (config.serverArgs !== undefined) {
925
939
  if (!Array.isArray(config.serverArgs)) {
@@ -1040,7 +1054,7 @@ async function connectCodexStdio(config, profile, cwd, extraArgs, signal, handle
1040
1054
  if (ready)
1041
1055
  onEnd(error);
1042
1056
  };
1043
- emitStartupPhase(onStartupPhase, "spawning");
1057
+ emitStartupPhase(onStartupPhase, "spawning", config.onObserverError);
1044
1058
  const engine = spawnEngineProcess2({
1045
1059
  executable: config.executable,
1046
1060
  args: [...config.prefix, "app-server", ...extraArgs],
@@ -1063,7 +1077,7 @@ async function connectCodexStdio(config, profile, cwd, extraArgs, signal, handle
1063
1077
  }
1064
1078
  })();
1065
1079
  try {
1066
- emitStartupPhase(onStartupPhase, "initializing");
1080
+ emitStartupPhase(onStartupPhase, "initializing", config.onObserverError);
1067
1081
  const userAgent = await initializeCodexPeer(peer, config.version);
1068
1082
  const providerPid = await engine.pidReady ?? engine.pid;
1069
1083
  if (endedError !== undefined)
@@ -1126,7 +1140,7 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1126
1140
  if (transport.kind === "unix-listen") {
1127
1141
  assertCodexUnixListenTargetAvailable(transport.socketPath, "createCodexDriver");
1128
1142
  const env = engineEnvironment2(profile, config.ambient);
1129
- emitStartupPhase(onStartupPhase, "spawning");
1143
+ emitStartupPhase(onStartupPhase, "spawning", config.onObserverError);
1130
1144
  spawnedEngine = spawnEngineProcess2({
1131
1145
  executable: config.executable,
1132
1146
  args: [
@@ -1191,7 +1205,7 @@ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd =
1191
1205
  try {
1192
1206
  if (endedError !== undefined)
1193
1207
  throw endedError;
1194
- emitStartupPhase(onStartupPhase, "initializing");
1208
+ emitStartupPhase(onStartupPhase, "initializing", config.onObserverError);
1195
1209
  const userAgent = await initializeCodexPeer(peer, config.version);
1196
1210
  if (endedError !== undefined)
1197
1211
  throw endedError;
@@ -1982,41 +1996,53 @@ function codexTurnIdOf(params) {
1982
1996
  }
1983
1997
 
1984
1998
  class CodexStartingTurn {
1999
+ limits;
1985
2000
  waiting = [];
1986
2001
  bytes = 0;
1987
2002
  failure;
1988
2003
  discarded = false;
1989
2004
  flushing = false;
2005
+ observed;
2006
+ constructor(limits = TURN_QUEUE) {
2007
+ this.limits = limits;
2008
+ }
1990
2009
  get isBuffering() {
1991
2010
  return !this.discarded && !this.flushing;
1992
2011
  }
1993
- defer(params, deliver) {
2012
+ get observedTurnId() {
2013
+ return this.observed;
2014
+ }
2015
+ defer(params, deliver, refuse) {
1994
2016
  if (!this.isBuffering)
1995
2017
  return;
1996
2018
  if (this.failure !== undefined)
1997
- throw this.failure;
1998
- this.bytes += JSON.stringify(params ?? null).length;
1999
- if (this.waiting.length >= TURN_QUEUE.maxItems || this.bytes > TURN_QUEUE.maxBytes) {
2019
+ return this.failure;
2020
+ this.bytes += utf8ByteLength(JSON.stringify(params ?? null));
2021
+ if (this.waiting.length >= this.limits.maxItems || this.bytes > this.limits.maxBytes) {
2000
2022
  this.failure = new Error("Codex events before turn/start exceeded the turn queue limit");
2001
- throw this.failure;
2023
+ return this.failure;
2002
2024
  }
2003
- this.waiting.push(deliver);
2025
+ this.observed ??= codexTurnIdOf(params);
2026
+ this.waiting.push({ deliver, refuse });
2027
+ return;
2004
2028
  }
2005
2029
  discard() {
2006
- this.discarded = true;
2007
- this.waiting.length = 0;
2008
- this.bytes = 0;
2009
- this.failure = undefined;
2030
+ this.drop();
2031
+ }
2032
+ refuse() {
2033
+ for (const event of this.drop())
2034
+ event.refuse?.();
2010
2035
  }
2011
2036
  flush(shouldContinue) {
2012
2037
  this.flushing = true;
2013
2038
  try {
2014
- for (const deliver of this.waiting.splice(0)) {
2039
+ const waiting = this.waiting.splice(0);
2040
+ for (const event of waiting) {
2015
2041
  if (this.discarded || shouldContinue?.() === false) {
2016
2042
  this.discard();
2017
2043
  return;
2018
2044
  }
2019
- deliver();
2045
+ event.deliver();
2020
2046
  }
2021
2047
  if (!this.discarded && shouldContinue?.() !== false && this.failure !== undefined) {
2022
2048
  throw this.failure;
@@ -2025,6 +2051,13 @@ class CodexStartingTurn {
2025
2051
  this.flushing = false;
2026
2052
  }
2027
2053
  }
2054
+ drop() {
2055
+ this.discarded = true;
2056
+ const dropped = this.waiting.splice(0);
2057
+ this.bytes = 0;
2058
+ this.failure = undefined;
2059
+ return dropped;
2060
+ }
2028
2061
  }
2029
2062
  function discardStartingTurn(turn) {
2030
2063
  if (turn?.starting === undefined)
@@ -2033,6 +2066,13 @@ function discardStartingTurn(turn) {
2033
2066
  delete turn.starting;
2034
2067
  starting.discard();
2035
2068
  }
2069
+ function refuseStartingTurn(turn) {
2070
+ if (turn?.starting === undefined)
2071
+ return;
2072
+ const starting = turn.starting;
2073
+ delete turn.starting;
2074
+ starting.refuse();
2075
+ }
2036
2076
  function codexEventTurn(current, params) {
2037
2077
  if (current === undefined)
2038
2078
  return;
@@ -2200,6 +2240,22 @@ function codexStoppedAnswer(method) {
2200
2240
  return { answers: {} };
2201
2241
  }
2202
2242
  var codexStopped = (waiting) => codexStoppedAnswer(waiting.detail.method);
2243
+ function releaseExternalCodexRequests(pending, answer) {
2244
+ if (answer)
2245
+ for (const waiting of pending.values())
2246
+ waiting.resolve(codexStopped(waiting));
2247
+ pending.clear();
2248
+ }
2249
+ async function releaseExternalCodexRequestsBeforeStop(held, answer) {
2250
+ const answered = answer && held.some((pending) => pending.size > 0);
2251
+ for (const pending of held)
2252
+ releaseExternalCodexRequests(pending, answer);
2253
+ if (answered)
2254
+ await new Promise((resolve) => setImmediate(resolve));
2255
+ }
2256
+ function codexStoppedReply(method) {
2257
+ return isKnownCodexRequestMethod(method) ? Promise.resolve(codexStoppedAnswer(method)) : Promise.reject(new JsonRpcError2(JSON_RPC_METHOD_NOT_FOUND2, `${method} is not handled by this executor`));
2258
+ }
2203
2259
  function buildCodexRequestAnswer(detail, rawReply) {
2204
2260
  const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
2205
2261
  if (CODEX_APPROVAL_REQUESTS.has(detail.method)) {
@@ -2260,17 +2316,13 @@ function buildCodexRequestAnswer(detail, rawReply) {
2260
2316
  }
2261
2317
  return { answers: CodexUserInputAnswersSchema.parse(reply.value) };
2262
2318
  }
2263
- function answerActiveCodexTurnRequest(turn, interactionId, rawReply) {
2264
- const waiting = turn.pending.get(interactionId);
2265
- if (waiting === undefined) {
2266
- throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
2267
- }
2268
- const answer = buildCodexRequestAnswer(waiting.detail, rawReply);
2269
- answerEngineRequest(turn, interactionId, answer);
2319
+ function answerActiveCodexTurnRequest(turn, liveness, interactionId, rawReply) {
2320
+ respondToEngineRequest(turn, liveness, interactionId, (detail) => buildCodexRequestAnswer(detail, rawReply));
2270
2321
  }
2271
2322
  function answerCodexSessionRequest(input) {
2323
+ input.liveness.ensureAlive();
2272
2324
  if (input.turn?.pending.has(input.interactionId)) {
2273
- answerActiveCodexTurnRequest(input.turn, input.interactionId, input.reply);
2325
+ answerActiveCodexTurnRequest(input.turn, input.liveness, input.interactionId, input.reply);
2274
2326
  return;
2275
2327
  }
2276
2328
  const external = input.externalPending.get(input.interactionId);
@@ -2286,8 +2338,25 @@ function answerCodexSessionRequest(input) {
2286
2338
  function interruptLocalCodexTurn(turn, turnId) {
2287
2339
  if (turn === undefined || turn.codexTurnId !== turnId)
2288
2340
  return;
2289
- turn.state.interruptRequested = true;
2290
- drainEngineRequests(turn, codexStopped);
2341
+ refuseEngineTurnRequests(turn, codexStopped);
2342
+ }
2343
+ var ABANDONED_TURN_MS = 5000;
2344
+ function interruptAbandonedCodexTurn(peer, threadId, turn) {
2345
+ if (turn === undefined || turn.abandoned === true)
2346
+ return Promise.resolve();
2347
+ turn.abandoned = true;
2348
+ const known = turn.codexTurnId ?? turn.starting?.observedTurnId;
2349
+ const reply = turn.startReply;
2350
+ const named = known !== undefined || reply === undefined ? Promise.resolve(known) : raceAbort(reply, AbortSignal.timeout(ABANDONED_TURN_MS)).then(codexTurnIdOf, () => {
2351
+ return;
2352
+ });
2353
+ return named.then(async (turnId) => {
2354
+ if (turnId === undefined)
2355
+ return;
2356
+ await peer.request("turn/interrupt", { threadId, turnId }, { timeoutMs: ABANDONED_TURN_MS });
2357
+ }).catch(() => {
2358
+ return;
2359
+ });
2291
2360
  }
2292
2361
  function buildCodexResumeThreadParams(params) {
2293
2362
  const caller = "CodexControlClient.resumeThread";
@@ -2308,7 +2377,7 @@ function createCodexStartTurn(input) {
2308
2377
  return guardedTurnStarter({
2309
2378
  busyMessage: "A turn is already running in this Codex thread",
2310
2379
  check: (turnInput) => {
2311
- input.ensureAlive();
2380
+ input.liveness.ensureAlive();
2312
2381
  if (input.getTurn() !== undefined) {
2313
2382
  throw new Error("A turn is already running in this Codex thread");
2314
2383
  }
@@ -2327,29 +2396,24 @@ function createCodexStartTurn(input) {
2327
2396
  starting,
2328
2397
  state: { turnId: turnInput.turnId, interruptRequested: false },
2329
2398
  channel: createTurnDeltaChannel(),
2330
- pending: new Map
2331
- };
2332
- const isAlive = () => {
2333
- if (input.signal.aborted)
2334
- return false;
2335
- try {
2336
- input.ensureAlive();
2337
- return true;
2338
- } catch {
2339
- return false;
2340
- }
2399
+ pending: new Map,
2400
+ settled: false
2341
2401
  };
2402
+ const isAlive = () => input.liveness.isAlive();
2342
2403
  input.setTurn(turn);
2404
+ const reply = input.peer.request("turn/start", turnParams);
2405
+ turn.startReply = reply;
2406
+ reply.catch(() => {
2407
+ return;
2408
+ });
2343
2409
  let nativeTurnId;
2344
2410
  try {
2345
- const started = await input.peer.request("turn/start", turnParams, {
2346
- signal: input.signal
2347
- });
2411
+ const started = await raceAbort(reply, input.signal);
2348
2412
  if (!isAlive() || input.getTurn() !== turn) {
2349
2413
  if (input.getTurn() === turn)
2350
2414
  input.setTurn(undefined);
2351
2415
  discardStartingTurn(turn);
2352
- input.ensureAlive();
2416
+ input.liveness.ensureAlive();
2353
2417
  throw new Error("The Codex session is closed");
2354
2418
  }
2355
2419
  nativeTurnId = parseCodexResponse("turn/start", CodexStartedTurnSchema, started).turn.id;
@@ -2363,6 +2427,8 @@ function createCodexStartTurn(input) {
2363
2427
  } catch (error) {
2364
2428
  if (input.getTurn() === turn)
2365
2429
  input.setTurn(undefined);
2430
+ if (isAlive())
2431
+ interruptAbandonedCodexTurn(input.peer, input.threadId, turn);
2366
2432
  if (turn.starting !== undefined) {
2367
2433
  const pending = turn.starting;
2368
2434
  try {
@@ -2380,23 +2446,15 @@ function createCodexStartTurn(input) {
2380
2446
  return {
2381
2447
  nativeTurnId,
2382
2448
  deltas: turn.channel,
2383
- async interrupt() {
2384
- if (input.getTurn() !== turn)
2385
- return;
2386
- try {
2387
- input.ensureAlive();
2388
- } catch {
2389
- return;
2390
- }
2391
- interruptLocalCodexTurn(turn, nativeTurnId);
2392
- await input.peer.request("turn/interrupt", {
2449
+ interrupt: () => interruptEngineTurn(turn, input.liveness, {
2450
+ refusal: codexStopped,
2451
+ tell: () => input.peer.request("turn/interrupt", {
2393
2452
  threadId: input.threadId,
2394
2453
  turnId: nativeTurnId
2395
- });
2396
- },
2454
+ })
2455
+ }),
2397
2456
  async respond(interactionId, rawReply) {
2398
- input.ensureAlive();
2399
- answerActiveCodexTurnRequest(turn, interactionId, rawReply);
2457
+ answerActiveCodexTurnRequest(turn, input.liveness, interactionId, rawReply);
2400
2458
  }
2401
2459
  };
2402
2460
  }
@@ -2658,12 +2716,16 @@ function nameBucketWindows(windows, bucketLabels) {
2658
2716
  });
2659
2717
  });
2660
2718
  }
2661
- function parseCodexRateLimitsInternal(reported) {
2662
- if (!isRecord(reported))
2663
- return { windows: [], plan: undefined };
2664
- const windows = [];
2665
- const bucketLabels = new Map;
2719
+ function parseCodexRateLimitsInternal(reported, base) {
2720
+ const windows = [...base?.windows ?? []];
2721
+ const bucketLabels = new Map(base?.labels ?? []);
2666
2722
  let plan;
2723
+ const finish = () => {
2724
+ const sources = { windows, labels: bucketLabels, plan: plan ?? base?.plan };
2725
+ return { windows: nameBucketWindows(windows, bucketLabels), plan: sources.plan, sources };
2726
+ };
2727
+ if (!isRecord(reported))
2728
+ return finish();
2667
2729
  function readBucket(raw, fallbackId) {
2668
2730
  const parsed = SnapshotSchema.safeParse(raw);
2669
2731
  if (!parsed.success)
@@ -2690,7 +2752,38 @@ function parseCodexRateLimitsInternal(reported) {
2690
2752
  readBucket(byId[key], nonEmptyString(key)?.trim() ?? "limit");
2691
2753
  }
2692
2754
  }
2693
- return { windows: nameBucketWindows(windows, bucketLabels), plan };
2755
+ return finish();
2756
+ }
2757
+ function limitsOf(parsed, now, previous) {
2758
+ return PlanLimitsSchema2.parse({
2759
+ answer: parsed.windows.length > 0 ? "known" : previous?.answer ?? "unpublished",
2760
+ windows: parsed.windows.toSorted((a, b) => a.name.localeCompare(b.name)),
2761
+ observedAt: now.toISOString(),
2762
+ ...parsed.plan !== undefined && { plan: parsed.plan }
2763
+ });
2764
+ }
2765
+
2766
+ class CodexLimitBook {
2767
+ #entries = new Map;
2768
+ get(profileId) {
2769
+ return this.#entries.get(profileId)?.limits;
2770
+ }
2771
+ delete(profileId) {
2772
+ this.#entries.delete(profileId);
2773
+ }
2774
+ replace(profileId, reported, now) {
2775
+ const parsed = parseCodexRateLimitsInternal(reported);
2776
+ const limits = limitsOf(parsed, now);
2777
+ this.#entries.set(profileId, { limits, sources: parsed.sources });
2778
+ return limits;
2779
+ }
2780
+ update(profileId, reported, now) {
2781
+ const previous = this.#entries.get(profileId);
2782
+ const parsed = parseCodexRateLimitsInternal(reported, previous?.sources);
2783
+ const limits = limitsOf(parsed, now, previous?.limits);
2784
+ this.#entries.set(profileId, { limits, sources: parsed.sources });
2785
+ return limits;
2786
+ }
2694
2787
  }
2695
2788
  function codexPlanWindows(reported) {
2696
2789
  return parseCodexRateLimitsInternal(reported).windows;
@@ -2804,18 +2897,20 @@ async function findCodexTurnByClientId(controls, params) {
2804
2897
  // src/agent-executor/codex/handlers.ts
2805
2898
  var JSON_RPC_INTERNAL_ERROR = -32603;
2806
2899
  var MAX_EXTERNAL_PENDING_REQUESTS = 256;
2807
- function isHandlersAlive(state) {
2808
- try {
2809
- state.ensureAlive();
2810
- return true;
2811
- } catch {
2812
- return false;
2813
- }
2900
+ function codexObserverOptions(config) {
2901
+ return {
2902
+ ...config.onNotification !== undefined && { onNotification: config.onNotification },
2903
+ ...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
2904
+ ...config.serverRequestDelivery !== undefined && {
2905
+ serverRequestDelivery: config.serverRequestDelivery
2906
+ },
2907
+ ...config.onObserverError !== undefined && { onObserverError: config.onObserverError }
2908
+ };
2814
2909
  }
2815
2910
  function emitCodexNotification(state, method, params, duringActiveTurn, deltas) {
2816
2911
  if (state.onNotification === undefined)
2817
2912
  return;
2818
- invokeSafely(() => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
2913
+ invokeObserver(state.onObserverError, "onNotification", () => state.onNotification?.({ method, params, duringActiveTurn, deltas }));
2819
2914
  }
2820
2915
  function handleCodexNotification(state, method, params) {
2821
2916
  const turn = codexEventTurn(state.getTurn(), params);
@@ -2841,13 +2936,7 @@ function handleCodexNotification(state, method, params) {
2841
2936
  switch (verdict.kind) {
2842
2937
  case "limits":
2843
2938
  try {
2844
- const parsedLimits = codexPlanLimits(verdict.rateLimits, new Date);
2845
- state.limits.set(state.profileId, mergeRateLimitEvent2({
2846
- previous: state.limits.get(state.profileId),
2847
- windows: parsedLimits.windows,
2848
- ...parsedLimits.plan !== undefined && { plan: parsedLimits.plan },
2849
- now: new Date
2850
- }));
2939
+ state.limits.update(state.profileId, verdict.rateLimits, new Date);
2851
2940
  emitCodexNotification(state, method, params, duringActiveTurn, []);
2852
2941
  } catch (error) {
2853
2942
  const errorDelta = {
@@ -2941,9 +3030,9 @@ function handleCodexRequest(state, method, params, id) {
2941
3030
  resolve
2942
3031
  });
2943
3032
  });
2944
- if (state.serverRequestDelivery === "all" && state.onServerRequest !== undefined && turn.pending.has(interactionId) && isHandlersAlive(state)) {
3033
+ if (state.serverRequestDelivery === "all" && state.onServerRequest !== undefined && turn.pending.has(interactionId) && state.liveness.isAlive()) {
2945
3034
  const observer = state.onServerRequest;
2946
- invokeSafely(() => observer({
3035
+ invokeObserver(state.onObserverError, "onServerRequest", () => observer({
2947
3036
  interactionId,
2948
3037
  requestId: id,
2949
3038
  method,
@@ -2951,8 +3040,7 @@ function handleCodexRequest(state, method, params, id) {
2951
3040
  duringActiveTurn: true,
2952
3041
  delta,
2953
3042
  async respond(reply) {
2954
- state.ensureAlive();
2955
- answerActiveCodexTurnRequest(turn, interactionId, reply);
3043
+ answerActiveCodexTurnRequest(turn, state.liveness, interactionId, reply);
2956
3044
  }
2957
3045
  }));
2958
3046
  }
@@ -2988,14 +3076,21 @@ function handleCodexRequest(state, method, params, id) {
2988
3076
  resolve
2989
3077
  };
2990
3078
  state.externalPending.set(interactionId, entry);
2991
- const onObserverError = (error) => {
3079
+ const report = (error) => {
3080
+ if (!(error instanceof JsonRpcError2))
3081
+ reportObserverError(state.onObserverError, "onServerRequest", error);
3082
+ };
3083
+ const onObserverFailure = (error) => {
3084
+ report(error);
2992
3085
  if (state.externalPending.get(interactionId) !== entry)
2993
3086
  return;
2994
3087
  state.externalPending.delete(interactionId);
2995
- if (!isHandlersAlive(state))
3088
+ if (!state.liveness.isAlive())
2996
3089
  return;
2997
3090
  if (error instanceof JsonRpcError2)
2998
3091
  reject(error);
3092
+ else if (!state.sharedWithOtherClients)
3093
+ reject(new JsonRpcError2(JSON_RPC_INTERNAL_ERROR, "The executor could not handle this request"));
2999
3094
  };
3000
3095
  try {
3001
3096
  const outcome = observer({
@@ -3006,8 +3101,8 @@ function handleCodexRequest(state, method, params, id) {
3006
3101
  duringActiveTurn: false,
3007
3102
  delta,
3008
3103
  async respond(reply) {
3009
- state.ensureAlive();
3010
3104
  answerCodexSessionRequest({
3105
+ liveness: state.liveness,
3011
3106
  turn: undefined,
3012
3107
  externalPending: state.externalPending,
3013
3108
  expectedEntry: entry,
@@ -3017,39 +3112,35 @@ function handleCodexRequest(state, method, params, id) {
3017
3112
  }
3018
3113
  });
3019
3114
  const thenable = typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function";
3020
- if (!isHandlersAlive(state)) {
3115
+ if (!state.liveness.isAlive()) {
3021
3116
  if (state.externalPending.get(interactionId) === entry) {
3022
3117
  state.externalPending.delete(interactionId);
3023
3118
  }
3024
3119
  if (thenable)
3025
- Promise.resolve(outcome).catch(() => {
3026
- return;
3027
- });
3120
+ Promise.resolve(outcome).catch(report);
3028
3121
  return;
3029
3122
  }
3030
3123
  if (thenable) {
3031
3124
  Promise.resolve(outcome).then(() => {
3032
- if (!isHandlersAlive(state) && state.externalPending.get(interactionId) === entry) {
3125
+ if (!state.liveness.isAlive() && state.externalPending.get(interactionId) === entry) {
3033
3126
  state.externalPending.delete(interactionId);
3034
3127
  }
3035
- }, onObserverError);
3128
+ }, onObserverFailure);
3036
3129
  }
3037
3130
  } catch (error) {
3038
- onObserverError(error);
3131
+ onObserverFailure(error);
3039
3132
  }
3040
3133
  });
3041
3134
  }
3042
3135
  function createCodexHandlers(state) {
3043
- const dropClosedRequest = () => new Promise(() => {
3044
- return;
3045
- });
3136
+ const answerClosedRequest = (method) => state.closingGracefully?.() === true && !state.sharedWithOtherClients ? codexStoppedReply(method) : leaveEngineRequestUnanswered();
3046
3137
  return {
3047
3138
  onNotification(method, params) {
3048
- if (!isHandlersAlive(state))
3139
+ if (!state.liveness.isAlive())
3049
3140
  return;
3050
3141
  const starting = codexEventTurn(state.getTurn(), params)?.starting;
3051
3142
  const deliver = () => {
3052
- if (!isHandlersAlive(state))
3143
+ if (!state.liveness.isAlive())
3053
3144
  return;
3054
3145
  handleCodexNotification(state, method, params);
3055
3146
  };
@@ -3059,29 +3150,34 @@ function createCodexHandlers(state) {
3059
3150
  starting.defer(params, deliver);
3060
3151
  },
3061
3152
  onRequest(method, params, id) {
3062
- if (!isHandlersAlive(state))
3063
- return dropClosedRequest();
3153
+ if (!state.liveness.isAlive())
3154
+ return answerClosedRequest(method);
3064
3155
  const starting = codexEventTurn(state.getTurn(), params)?.starting;
3065
- const deliver = () => isHandlersAlive(state) ? handleCodexRequest(state, method, params, id) : dropClosedRequest();
3156
+ const deliver = () => state.liveness.isAlive() ? handleCodexRequest(state, method, params, id) : answerClosedRequest(method);
3066
3157
  if (starting === undefined || !starting.isBuffering)
3067
3158
  return deliver();
3068
3159
  return new Promise((resolve, reject) => {
3069
- starting.defer(params, () => {
3070
- if (!isHandlersAlive(state))
3160
+ const overflow = starting.defer(params, () => {
3161
+ if (!state.liveness.isAlive())
3071
3162
  return;
3072
3163
  try {
3073
3164
  resolve(deliver());
3074
3165
  } catch (error) {
3075
3166
  reject(error);
3076
3167
  }
3077
- });
3168
+ }, () => codexStoppedReply(method).then(resolve, reject));
3169
+ if (overflow !== undefined)
3170
+ reject(overflow);
3078
3171
  });
3079
3172
  }
3080
3173
  };
3081
3174
  }
3082
3175
 
3083
3176
  // src/agent-executor/codex/session-bind.ts
3084
- function bindCodexSessionThreadControls(controlClient, threadId) {
3177
+ function refuseOwnedUnsubscribe(threadId) {
3178
+ return Promise.reject(new TypeError(`[stitchkit] Codex thread ${threadId} is open in this driver; close its session instead of unsubscribing it`));
3179
+ }
3180
+ function bindCodexSessionThreadControls(controlClient, threadId, ownsThread = (id) => id === threadId) {
3085
3181
  return {
3086
3182
  readThread(params, options) {
3087
3183
  return controlClient.readThread({
@@ -3120,9 +3216,10 @@ function bindCodexSessionThreadControls(controlClient, threadId) {
3120
3216
  }, options);
3121
3217
  },
3122
3218
  unsubscribeThread(params, options) {
3123
- return controlClient.unsubscribeThread({
3124
- threadId: params?.threadId ?? threadId
3125
- }, options);
3219
+ const target = params?.threadId ?? threadId;
3220
+ if (ownsThread(target))
3221
+ return refuseOwnedUnsubscribe(target);
3222
+ return controlClient.unsubscribeThread({ threadId: target }, options);
3126
3223
  },
3127
3224
  archiveThread(params, options) {
3128
3225
  return controlClient.archiveThread({
@@ -3161,6 +3258,17 @@ function bindCodexSessionThreadControls(controlClient, threadId) {
3161
3258
  }
3162
3259
 
3163
3260
  // src/agent-executor/codex/session.ts
3261
+ function threadClosedAware(handlers, ownThreadId, onOwnThreadClosed) {
3262
+ return {
3263
+ onNotification(method, params) {
3264
+ handlers.onNotification(method, params);
3265
+ const own = ownThreadId();
3266
+ if (method === "thread/closed" && own !== undefined && codexThreadIdOf(params) === own)
3267
+ onOwnThreadClosed(new Error(`Codex closed thread ${own}`));
3268
+ },
3269
+ onRequest: handlers.onRequest
3270
+ };
3271
+ }
3164
3272
  async function openCodexSession(config, input) {
3165
3273
  validateCodexOpenInput(input);
3166
3274
  const profile = engineProfile("codex", input.profile);
@@ -3168,42 +3276,40 @@ async function openCodexSession(config, input) {
3168
3276
  const externalPending = new Map;
3169
3277
  let current;
3170
3278
  let activeThreadId;
3171
- let dead;
3172
3279
  let opened = false;
3173
- let closing = false;
3174
- const ensureAlive = () => {
3175
- if (closing)
3176
- throw new Error("The Codex session is closed");
3177
- if (dead !== undefined)
3178
- throw dead;
3179
- if (input.signal?.aborted)
3180
- throw abortReason(input.signal);
3181
- if (linked.signal.aborted)
3182
- throw abortReason(linked.signal);
3183
- };
3280
+ const liveness = sessionLiveness({
3281
+ closedMessage: "The Codex session is closed",
3282
+ caller: input.signal,
3283
+ linked: linked.signal
3284
+ });
3285
+ const ensureAlive = () => liveness.ensureAlive();
3184
3286
  let connected;
3185
3287
  try {
3186
- connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
3288
+ connected = await connectCodex(config, profile, input.cwd, linked.signal, threadClosedAware(createCodexHandlers({
3289
+ sharedWithOtherClients: codexTransportShared(config),
3187
3290
  profileId: profile.profileId,
3188
3291
  limits: config.limits,
3189
3292
  externalPending,
3190
- ensureAlive,
3293
+ liveness,
3294
+ closingGracefully: () => liveness.closingGracefully,
3191
3295
  getTurn: () => current,
3192
3296
  clearTurn: () => {
3193
3297
  current = undefined;
3194
3298
  },
3195
- ...config.onNotification !== undefined && { onNotification: config.onNotification },
3196
- ...config.onServerRequest !== undefined && {
3197
- onServerRequest: config.onServerRequest
3198
- },
3199
- ...config.serverRequestDelivery !== undefined && {
3200
- serverRequestDelivery: config.serverRequestDelivery
3201
- }
3299
+ ...codexObserverOptions(config)
3300
+ }), () => activeThreadId, (closed) => {
3301
+ if (liveness.closing || liveness.lost !== undefined)
3302
+ return;
3303
+ liveness.markLost(closed);
3304
+ const turn = current;
3305
+ current = undefined;
3306
+ discardStartingTurn(turn);
3307
+ loseEngineTurn(turn, codexStopped, closed);
3202
3308
  }), (error) => {
3203
- const abortedByCaller = input.signal?.aborted === true;
3204
- const shouldNotify = opened && !closing && !abortedByCaller;
3205
- if (!closing && !abortedByCaller)
3206
- dead = error;
3309
+ const { abortedByCaller } = liveness;
3310
+ const shouldNotify = opened && !liveness.closing && !abortedByCaller;
3311
+ if (!liveness.closing && !abortedByCaller)
3312
+ liveness.markLost(error);
3207
3313
  const turn = current;
3208
3314
  current = undefined;
3209
3315
  discardStartingTurn(turn);
@@ -3211,17 +3317,18 @@ async function openCodexSession(config, input) {
3211
3317
  loseEngineTurn(turn, codexStopped, abortedByCaller && input.signal !== undefined ? abortReason(input.signal) : error);
3212
3318
  linked.abort();
3213
3319
  if (shouldNotify)
3214
- invokeSafely(() => config.onDisconnect?.(error));
3320
+ invokeObserver(config.onObserverError, "onDisconnect", () => config.onDisconnect?.(error));
3215
3321
  }, input.onStartupPhase);
3216
3322
  } catch (error) {
3217
3323
  linked.release();
3218
3324
  throw error;
3219
3325
  }
3220
3326
  const { peer, providerPid, userAgent } = connected;
3327
+ const answersWhileClosing = () => liveness.closingGracefully && !codexTransportShared(config);
3221
3328
  const stop = async (primary) => {
3222
- closing = true;
3329
+ liveness.markClosing();
3223
3330
  discardStartingTurn(current);
3224
- externalPending.clear();
3331
+ await releaseExternalCodexRequestsBeforeStop([externalPending], answersWhileClosing());
3225
3332
  try {
3226
3333
  await stopConnection(connected, primary);
3227
3334
  } finally {
@@ -3261,7 +3368,7 @@ async function openCodexSession(config, input) {
3261
3368
  activeThreadId = threadId;
3262
3369
  threadContext = extractCodexThreadContext(parsed);
3263
3370
  if (config.verifyThread !== undefined) {
3264
- emitStartupPhase(input.onStartupPhase, "verifying");
3371
+ emitStartupPhase(input.onStartupPhase, "verifying", config.onObserverError);
3265
3372
  await raceAbort(Promise.resolve(config.verifyThread({
3266
3373
  nativeThreadId: threadId,
3267
3374
  threadContext,
@@ -3269,8 +3376,8 @@ async function openCodexSession(config, input) {
3269
3376
  })), linked.signal);
3270
3377
  linked.signal.throwIfAborted();
3271
3378
  }
3272
- if (dead !== undefined)
3273
- throw dead;
3379
+ if (liveness.lost !== undefined)
3380
+ throw liveness.lost.reason;
3274
3381
  linked.signal.throwIfAborted();
3275
3382
  } catch (error) {
3276
3383
  await stop({ error });
@@ -3283,7 +3390,7 @@ async function openCodexSession(config, input) {
3283
3390
  threadId,
3284
3391
  activeModelProvider,
3285
3392
  signal: linked.signal,
3286
- ensureAlive,
3393
+ liveness,
3287
3394
  getTurn: () => current,
3288
3395
  setTurn: (turn) => {
3289
3396
  current = turn;
@@ -3305,8 +3412,13 @@ async function openCodexSession(config, input) {
3305
3412
  threadContext,
3306
3413
  startTurn,
3307
3414
  async respond(interactionId, reply) {
3308
- ensureAlive();
3309
- answerCodexSessionRequest({ turn: current, externalPending, interactionId, reply });
3415
+ answerCodexSessionRequest({
3416
+ liveness,
3417
+ turn: current,
3418
+ externalPending,
3419
+ interactionId,
3420
+ reply
3421
+ });
3310
3422
  },
3311
3423
  ...controlClient,
3312
3424
  ...bindCodexSessionThreadControls(controlClient, threadId),
@@ -3320,56 +3432,47 @@ async function openCodexControlConnection(config, input) {
3320
3432
  const profile = engineProfile("codex", input.profile);
3321
3433
  const linked = sessionAbort(input.signal);
3322
3434
  const externalPending = new Map;
3323
- let dead;
3324
3435
  let opened = false;
3325
- let closing = false;
3326
- const ensureAlive = () => {
3327
- if (closing)
3328
- throw new Error("The Codex control connection is closed");
3329
- if (dead !== undefined)
3330
- throw dead;
3331
- if (input.signal?.aborted)
3332
- throw abortReason(input.signal);
3333
- if (linked.signal.aborted)
3334
- throw abortReason(linked.signal);
3335
- };
3436
+ const liveness = sessionLiveness({
3437
+ closedMessage: "The Codex control connection is closed",
3438
+ caller: input.signal,
3439
+ linked: linked.signal
3440
+ });
3441
+ const ensureAlive = () => liveness.ensureAlive();
3336
3442
  let connected;
3337
3443
  try {
3338
3444
  connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
3445
+ sharedWithOtherClients: codexTransportShared(config),
3339
3446
  profileId: profile.profileId,
3340
3447
  limits: config.limits,
3341
3448
  externalPending,
3342
- ensureAlive,
3449
+ liveness,
3450
+ closingGracefully: () => liveness.closingGracefully,
3343
3451
  getTurn: () => {
3344
3452
  return;
3345
3453
  },
3346
3454
  clearTurn: () => {
3347
3455
  return;
3348
3456
  },
3349
- ...config.onNotification !== undefined && { onNotification: config.onNotification },
3350
- ...config.onServerRequest !== undefined && {
3351
- onServerRequest: config.onServerRequest
3352
- },
3353
- ...config.serverRequestDelivery !== undefined && {
3354
- serverRequestDelivery: config.serverRequestDelivery
3355
- }
3457
+ ...codexObserverOptions(config)
3356
3458
  }), (error) => {
3357
- const abortedByCaller = input.signal?.aborted === true;
3358
- const shouldNotify = opened && !closing && !abortedByCaller;
3359
- if (!closing && !abortedByCaller)
3360
- dead = error;
3459
+ const { abortedByCaller } = liveness;
3460
+ const shouldNotify = opened && !liveness.closing && !abortedByCaller;
3461
+ if (!liveness.closing && !abortedByCaller)
3462
+ liveness.markLost(error);
3361
3463
  externalPending.clear();
3362
3464
  linked.abort();
3363
3465
  if (shouldNotify)
3364
- invokeSafely(() => config.onDisconnect?.(error));
3466
+ invokeObserver(config.onObserverError, "onDisconnect", () => config.onDisconnect?.(error));
3365
3467
  }, input.onStartupPhase);
3366
3468
  } catch (error) {
3367
3469
  linked.release();
3368
3470
  throw error;
3369
3471
  }
3370
- if (dead !== undefined || linked.signal.aborted) {
3371
- const reason = dead ?? abortReason(linked.signal);
3372
- closing = true;
3472
+ const failedOpening = liveness.terminated();
3473
+ if (failedOpening !== undefined) {
3474
+ const { reason } = failedOpening;
3475
+ liveness.markClosing();
3373
3476
  externalPending.clear();
3374
3477
  try {
3375
3478
  await stopConnection(connected, { error: reason });
@@ -3391,12 +3494,17 @@ async function openCodexControlConnection(config, input) {
3391
3494
  userAgent: connected.userAgent,
3392
3495
  ...controlClient,
3393
3496
  async respond(interactionId, reply) {
3394
- ensureAlive();
3395
- answerCodexSessionRequest({ turn: undefined, externalPending, interactionId, reply });
3497
+ answerCodexSessionRequest({
3498
+ liveness,
3499
+ turn: undefined,
3500
+ externalPending,
3501
+ interactionId,
3502
+ reply
3503
+ });
3396
3504
  },
3397
3505
  async close() {
3398
- closing = true;
3399
- externalPending.clear();
3506
+ liveness.markClosing();
3507
+ await releaseExternalCodexRequestsBeforeStop([externalPending], liveness.closingGracefully && !codexTransportShared(config));
3400
3508
  try {
3401
3509
  await stopConnection(connected);
3402
3510
  } finally {
@@ -3410,7 +3518,7 @@ async function openCodexControlConnection(config, input) {
3410
3518
  // src/agent-executor/codex/shared-thread.ts
3411
3519
  var CLOSE_UNSUBSCRIBE_TIMEOUT_MS = 5000;
3412
3520
  function bestEffortUnsubscribe(state, threadId) {
3413
- if (state.isServerClosing() || state.getServerDead() !== undefined) {
3521
+ if (state.liveness.closing || state.liveness.lost !== undefined) {
3414
3522
  return Promise.resolve();
3415
3523
  }
3416
3524
  return state.peer.request("thread/unsubscribe", { threadId }, { timeoutMs: CLOSE_UNSUBSCRIBE_TIMEOUT_MS }).then(() => {
@@ -3421,7 +3529,8 @@ function bestEffortUnsubscribe(state, threadId) {
3421
3529
  }
3422
3530
  function buildSharedThreadSession(params) {
3423
3531
  const { state, slot, threadContext, activeModelProvider, threadAbort } = params;
3424
- const { threadId, ensureAlive: ensureThreadAlive } = slot;
3532
+ const { threadId, liveness } = slot;
3533
+ const ensureThreadAlive = () => liveness.ensureAlive();
3425
3534
  const threadControlClient = createCodexControlClient({
3426
3535
  peer: state.peer,
3427
3536
  imageOptions: state.config,
@@ -3435,7 +3544,7 @@ function buildSharedThreadSession(params) {
3435
3544
  threadId,
3436
3545
  activeModelProvider,
3437
3546
  signal: threadAbort.signal,
3438
- ensureAlive: ensureThreadAlive,
3547
+ liveness,
3439
3548
  getTurn: () => slot.current,
3440
3549
  setTurn: (turn) => {
3441
3550
  slot.current = turn;
@@ -3449,40 +3558,40 @@ function buildSharedThreadSession(params) {
3449
3558
  ensureAlive: ensureThreadAlive,
3450
3559
  getActiveTurn: () => slot.current
3451
3560
  });
3561
+ const retire = (reason) => {
3562
+ const turn = slot.current;
3563
+ slot.current = undefined;
3564
+ const interrupted = interruptAbandonedCodexTurn(state.peer, threadId, turn);
3565
+ refuseStartingTurn(turn);
3566
+ releaseExternalCodexRequests(slot.externalPending, true);
3567
+ loseEngineTurn(turn, codexStopped, reason);
3568
+ state.threads.delete(threadId);
3569
+ state.closingThreadIds.add(threadId);
3570
+ return interrupted.then(() => bestEffortUnsubscribe(state, threadId)).finally(() => state.closingThreadIds.delete(threadId));
3571
+ };
3452
3572
  const closeThread = async () => {
3453
- if (slot.closed)
3573
+ if (liveness.closing)
3454
3574
  return;
3455
- slot.closed = true;
3456
- if (slot.dead !== undefined) {
3575
+ liveness.markClosing();
3576
+ if (liveness.lost !== undefined) {
3457
3577
  slot.releaseThreadSignal();
3458
3578
  return;
3459
3579
  }
3460
- const turn = slot.current;
3461
- slot.current = undefined;
3462
- discardStartingTurn(turn);
3463
- slot.externalPending.clear();
3464
- loseEngineTurn(turn, codexStopped, new Error("The Codex session closed"));
3465
- state.threads.delete(threadId);
3580
+ const retired = retire(new Error("The Codex session closed"));
3466
3581
  threadAbort.abort();
3467
3582
  try {
3468
- await bestEffortUnsubscribe(state, threadId);
3583
+ await retired;
3469
3584
  } finally {
3470
3585
  slot.releaseThreadSignal();
3471
3586
  }
3472
3587
  };
3473
3588
  threadAbort.signal.addEventListener("abort", () => {
3474
- if (slot.closed || slot.dead !== undefined)
3589
+ if (liveness.closing || liveness.lost !== undefined)
3475
3590
  return;
3476
3591
  const reason = abortReason(threadAbort.signal);
3477
- slot.dead = { reason };
3478
- const turn = slot.current;
3479
- slot.current = undefined;
3480
- discardStartingTurn(turn);
3481
- slot.externalPending.clear();
3482
- loseEngineTurn(turn, codexStopped, reason);
3483
- state.threads.delete(threadId);
3592
+ liveness.markLost(reason);
3484
3593
  slot.releaseThreadSignal();
3485
- bestEffortUnsubscribe(state, threadId);
3594
+ retire(reason);
3486
3595
  }, { once: true });
3487
3596
  return {
3488
3597
  nativeThreadId: threadId,
@@ -3491,8 +3600,8 @@ function buildSharedThreadSession(params) {
3491
3600
  threadContext,
3492
3601
  startTurn,
3493
3602
  async respond(interactionId, reply) {
3494
- ensureThreadAlive();
3495
3603
  answerCodexSessionRequest({
3604
+ liveness,
3496
3605
  turn: slot.current,
3497
3606
  externalPending: slot.externalPending,
3498
3607
  interactionId,
@@ -3500,13 +3609,13 @@ function buildSharedThreadSession(params) {
3500
3609
  });
3501
3610
  },
3502
3611
  ...threadControlClient,
3503
- ...bindCodexSessionThreadControls(threadControlClient, threadId),
3612
+ ...bindCodexSessionThreadControls(threadControlClient, threadId, (id) => state.threads.has(id) || state.closingThreadIds.has(id)),
3504
3613
  ...mutators,
3505
3614
  close: closeThread
3506
3615
  };
3507
3616
  }
3508
3617
  async function openSharedCodexThread(state, threadInput) {
3509
- state.ensureServerAlive();
3618
+ state.liveness.ensureAlive();
3510
3619
  validateCodexOpenInput({ ...threadInput, profile: state.profile });
3511
3620
  if (threadInput.nativeThreadId !== undefined && (state.threads.has(threadInput.nativeThreadId) || state.openingNativeThreadIds.has(threadInput.nativeThreadId))) {
3512
3621
  throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadInput.nativeThreadId} is already open on this shared server`);
@@ -3514,10 +3623,6 @@ async function openSharedCodexThread(state, threadInput) {
3514
3623
  if (state.threads.size + state.openingThreads >= state.maxThreads) {
3515
3624
  throw new RangeError(`[stitchkit] CodexSharedServer.openThread: active thread limit (${state.maxThreads}) reached`);
3516
3625
  }
3517
- if (threadInput.signal?.aborted)
3518
- throw abortReason(threadInput.signal);
3519
- if (state.serverSignal.aborted)
3520
- throw abortReason(state.serverSignal);
3521
3626
  const ownThreadAbort = new AbortController;
3522
3627
  const threadLink = linkAbortSignals(threadInput.signal, state.serverSignal, ownThreadAbort.signal);
3523
3628
  let signalReleased = false;
@@ -3532,6 +3637,18 @@ async function openSharedCodexThread(state, threadInput) {
3532
3637
  abort: (reason) => ownThreadAbort.abort(reason),
3533
3638
  release: releaseThreadSignal
3534
3639
  };
3640
+ const liveness = sessionLiveness({
3641
+ closedMessage: "The Codex session is closed",
3642
+ caller: threadInput.signal,
3643
+ linked: threadAbort.signal,
3644
+ within: state.liveness
3645
+ });
3646
+ try {
3647
+ liveness.ensureAlive();
3648
+ } catch (error) {
3649
+ releaseThreadSignal();
3650
+ throw error;
3651
+ }
3535
3652
  state.openingThreads += 1;
3536
3653
  if (threadInput.nativeThreadId !== undefined) {
3537
3654
  state.openingNativeThreadIds.add(threadInput.nativeThreadId);
@@ -3541,16 +3658,10 @@ async function openSharedCodexThread(state, threadInput) {
3541
3658
  peer: state.peer,
3542
3659
  imageOptions: state.config,
3543
3660
  signal: threadAbort.signal,
3544
- ensureAlive: () => {
3545
- if (threadInput.signal?.aborted)
3546
- throw abortReason(threadInput.signal);
3547
- threadAbort.signal.throwIfAborted();
3548
- state.ensureServerAlive();
3549
- },
3661
+ ensureAlive: () => liveness.ensureAlive(),
3550
3662
  onBeforeInterruptTurn: state.onBeforeInterruptTurn
3551
3663
  });
3552
3664
  try {
3553
- threadAbort.signal.throwIfAborted();
3554
3665
  let dynamicOverrides;
3555
3666
  if (state.config.prepareThread !== undefined) {
3556
3667
  dynamicOverrides = await raceAbort(Promise.resolve(state.config.prepareThread({
@@ -3561,8 +3672,7 @@ async function openSharedCodexThread(state, threadInput) {
3561
3672
  },
3562
3673
  ...threadInput.forkFrom !== undefined && { forkFrom: threadInput.forkFrom }
3563
3674
  })), threadAbort.signal);
3564
- threadAbort.signal.throwIfAborted();
3565
- state.ensureServerAlive();
3675
+ liveness.ensureAlive();
3566
3676
  }
3567
3677
  const disposeLateOpen = (reply) => {
3568
3678
  const parsedLate = CodexStartedThreadSchema.safeParse(reply);
@@ -3571,8 +3681,7 @@ async function openSharedCodexThread(state, threadInput) {
3571
3681
  }
3572
3682
  };
3573
3683
  const openedReply = await raceAbort(openCodexThreadRpc(state.peer, state.config, threadInput, dynamicOverrides), threadAbort.signal, disposeLateOpen);
3574
- threadAbort.signal.throwIfAborted();
3575
- state.ensureServerAlive();
3684
+ liveness.ensureAlive();
3576
3685
  const openMethod = threadInput.forkFrom !== undefined ? "thread/fork" : threadInput.nativeThreadId !== undefined ? "thread/resume" : "thread/start";
3577
3686
  const parsed = parseCodexResponse(openMethod, CodexStartedThreadSchema, openedReply);
3578
3687
  const threadId = parsed.thread.id;
@@ -3581,61 +3690,37 @@ async function openSharedCodexThread(state, threadInput) {
3581
3690
  throw new Error(`[stitchkit] CodexSharedServer.openThread: thread ${threadId} is already open on this shared server`);
3582
3691
  }
3583
3692
  const externalPending = new Map;
3584
- const ensureAlive = () => {
3585
- if (slot.closed)
3586
- throw new Error("The Codex session is closed");
3587
- if (slot.dead !== undefined)
3588
- throw slot.dead.reason;
3589
- state.ensureServerAlive();
3590
- if (threadInput.signal?.aborted)
3591
- throw abortReason(threadInput.signal);
3592
- if (threadAbort.signal.aborted)
3593
- throw abortReason(threadAbort.signal);
3594
- };
3595
3693
  const slot = {
3596
3694
  threadId,
3597
3695
  current: undefined,
3598
3696
  externalPending,
3599
- ensureAlive,
3600
- closed: false,
3601
- dead: undefined,
3697
+ liveness,
3602
3698
  abortThread: (reason) => threadAbort.abort(reason),
3603
3699
  releaseThreadSignal,
3604
3700
  handlers: createCodexHandlers({
3701
+ sharedWithOtherClients: false,
3605
3702
  profileId: state.profile.profileId,
3606
3703
  limits: state.config.limits,
3607
3704
  externalPending,
3608
- ensureAlive,
3705
+ liveness,
3609
3706
  getTurn: () => slot.current,
3610
3707
  clearTurn: () => {
3611
3708
  slot.current = undefined;
3612
3709
  },
3613
- ...state.config.onNotification !== undefined && {
3614
- onNotification: state.config.onNotification
3615
- },
3616
- ...state.config.onServerRequest !== undefined && {
3617
- onServerRequest: state.config.onServerRequest
3618
- },
3619
- ...state.config.serverRequestDelivery !== undefined && {
3620
- serverRequestDelivery: state.config.serverRequestDelivery
3621
- }
3710
+ ...codexObserverOptions(state.config)
3622
3711
  })
3623
3712
  };
3624
3713
  state.threads.set(threadId, slot);
3625
3714
  registeredThreadId = threadId;
3626
3715
  if (state.config.verifyThread !== undefined) {
3627
- emitStartupPhase(threadInput.onStartupPhase, "verifying");
3716
+ emitStartupPhase(threadInput.onStartupPhase, "verifying", state.config.onObserverError);
3628
3717
  await raceAbort(Promise.resolve(state.config.verifyThread({
3629
3718
  nativeThreadId: threadId,
3630
3719
  threadContext,
3631
3720
  controls: openControls
3632
3721
  })), threadAbort.signal);
3633
- threadAbort.signal.throwIfAborted();
3634
3722
  }
3635
- state.ensureServerAlive();
3636
- threadAbort.signal.throwIfAborted();
3637
- if (slot.dead !== undefined)
3638
- throw slot.dead.reason;
3723
+ liveness.ensureAlive();
3639
3724
  const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? threadInput.forkFrom?.modelProvider ?? state.config.modelProvider;
3640
3725
  return buildSharedThreadSession({
3641
3726
  state,
@@ -3648,7 +3733,7 @@ async function openSharedCodexThread(state, threadInput) {
3648
3733
  if (registeredThreadId !== undefined) {
3649
3734
  const failedSlot = state.threads.get(registeredThreadId);
3650
3735
  if (failedSlot !== undefined) {
3651
- failedSlot.closed = true;
3736
+ failedSlot.liveness.markClosing();
3652
3737
  failedSlot.externalPending.clear();
3653
3738
  }
3654
3739
  state.threads.delete(registeredThreadId);
@@ -3684,40 +3769,36 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3684
3769
  const profile = engineProfile("codex", input.profile);
3685
3770
  const linked = sessionAbort(input.signal);
3686
3771
  const threads = new Map;
3772
+ const closingThreadIds = new Set;
3687
3773
  const globalExternalPending = new Map;
3688
- let serverDead;
3689
- let serverClosing = false;
3690
3774
  let opened = false;
3691
- const ensureServerAlive = () => {
3692
- if (serverClosing)
3693
- throw new Error("The Codex shared server is closed");
3694
- if (serverDead !== undefined)
3695
- throw serverDead;
3696
- if (input.signal?.aborted)
3697
- throw abortReason(input.signal);
3698
- if (linked.signal.aborted)
3699
- throw abortReason(linked.signal);
3700
- };
3775
+ const liveness = sessionLiveness({
3776
+ closedMessage: "The Codex shared server is closed",
3777
+ caller: input.signal,
3778
+ linked: linked.signal
3779
+ });
3701
3780
  const globalHandlers = createCodexHandlers({
3781
+ sharedWithOtherClients: false,
3702
3782
  profileId: profile.profileId,
3703
3783
  limits: config.limits,
3704
3784
  externalPending: globalExternalPending,
3705
- ensureAlive: ensureServerAlive,
3785
+ liveness,
3786
+ closingGracefully: () => liveness.closingGracefully,
3706
3787
  getTurn: () => {
3707
3788
  return;
3708
3789
  },
3709
3790
  clearTurn: () => {
3710
3791
  return;
3711
3792
  },
3712
- ...config.onNotification !== undefined && { onNotification: config.onNotification },
3713
- ...config.onServerRequest !== undefined && { onServerRequest: config.onServerRequest },
3714
- ...config.serverRequestDelivery !== undefined && {
3715
- serverRequestDelivery: config.serverRequestDelivery
3716
- }
3793
+ ...codexObserverOptions(config)
3717
3794
  });
3795
+ const heldGlobally = (params) => {
3796
+ const requestId = isRecord(params) ? params.requestId : undefined;
3797
+ return (typeof requestId === "string" || typeof requestId === "number") && globalExternalPending.has(String(requestId));
3798
+ };
3718
3799
  const failAllThreads = (reason) => {
3719
3800
  for (const slot of [...threads.values()]) {
3720
- slot.dead = slot.dead ?? { reason };
3801
+ slot.liveness.markLost(reason);
3721
3802
  const turn = slot.current;
3722
3803
  slot.current = undefined;
3723
3804
  discardStartingTurn(turn);
@@ -3728,39 +3809,50 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3728
3809
  }
3729
3810
  threads.clear();
3730
3811
  };
3812
+ const contained = (handle) => invokeObserver(config.onObserverError, "driver:notification", handle);
3731
3813
  let connected;
3732
3814
  try {
3733
3815
  connected = await connectCodex(config, profile, input.cwd, linked.signal, {
3734
3816
  onNotification(method, params) {
3735
3817
  if (method === "account/rateLimits/updated") {
3736
- invokeSafely(() => globalHandlers.onNotification(method, params));
3818
+ contained(() => globalHandlers.onNotification(method, params));
3737
3819
  return;
3738
3820
  }
3739
3821
  const targetId = codexThreadIdOf(params);
3822
+ if (targetId !== undefined && closingThreadIds.has(targetId))
3823
+ return;
3824
+ if (method === "serverRequest/resolved" && heldGlobally(params)) {
3825
+ contained(() => globalHandlers.onNotification(method, params));
3826
+ return;
3827
+ }
3740
3828
  const slot = targetId !== undefined ? threads.get(targetId) : undefined;
3741
3829
  if (slot !== undefined) {
3742
- invokeSafely(() => slot.handlers.onNotification(method, params));
3830
+ contained(() => slot.handlers.onNotification(method, params));
3831
+ if (method === "thread/closed")
3832
+ slot.abortThread(new Error(`Codex closed thread ${slot.threadId}`));
3743
3833
  return;
3744
3834
  }
3745
- invokeSafely(() => globalHandlers.onNotification(method, params));
3835
+ contained(() => globalHandlers.onNotification(method, params));
3746
3836
  },
3747
3837
  onRequest(method, params, id) {
3748
3838
  const targetId = codexThreadIdOf(params);
3839
+ if (targetId !== undefined && closingThreadIds.has(targetId))
3840
+ return codexStoppedReply(method);
3749
3841
  const slot = targetId !== undefined ? threads.get(targetId) : undefined;
3750
3842
  if (slot !== undefined)
3751
3843
  return slot.handlers.onRequest(method, params, id);
3752
3844
  return globalHandlers.onRequest(method, params, id);
3753
3845
  }
3754
3846
  }, (error) => {
3755
- const abortedByCaller = input.signal?.aborted === true;
3756
- const shouldNotify = opened && !serverClosing && !abortedByCaller;
3757
- if (!serverClosing && !abortedByCaller)
3758
- serverDead = error;
3847
+ const { abortedByCaller } = liveness;
3848
+ const shouldNotify = opened && !liveness.closing && !abortedByCaller;
3849
+ if (!liveness.closing && !abortedByCaller)
3850
+ liveness.markLost(error);
3759
3851
  globalExternalPending.clear();
3760
3852
  failAllThreads(abortedByCaller && input.signal !== undefined ? abortReason(input.signal) : error);
3761
3853
  linked.abort();
3762
3854
  if (shouldNotify)
3763
- invokeSafely(() => config.onDisconnect?.(error));
3855
+ invokeObserver(config.onObserverError, "onDisconnect", () => config.onDisconnect?.(error));
3764
3856
  }, input.onStartupPhase);
3765
3857
  } catch (error) {
3766
3858
  linked.release();
@@ -3774,13 +3866,10 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3774
3866
  peer,
3775
3867
  imageOptions: config,
3776
3868
  signal: linked.signal,
3777
- ensureAlive: ensureServerAlive,
3869
+ ensureAlive: () => liveness.ensureAlive(),
3778
3870
  onBeforeInterruptTurn
3779
3871
  });
3780
- const sharedCapabilities = {
3781
- ...baseCapabilities,
3782
- multiThreadPerProcess: true
3783
- };
3872
+ const sharedCapabilities = codexSharedServerCapabilities(baseCapabilities);
3784
3873
  const state = {
3785
3874
  config,
3786
3875
  profile,
@@ -3791,24 +3880,26 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3791
3880
  onBeforeInterruptTurn,
3792
3881
  serverSignal: linked.signal,
3793
3882
  threads,
3883
+ closingThreadIds,
3794
3884
  openingNativeThreadIds: new Set,
3795
3885
  openingThreads: 0,
3796
- isServerClosing: () => serverClosing,
3797
- getServerDead: () => serverDead,
3798
- ensureServerAlive
3886
+ liveness
3799
3887
  };
3800
- const closeServer = async () => {
3801
- if (serverClosing)
3802
- return;
3803
- serverClosing = true;
3804
- globalExternalPending.clear();
3805
- failAllThreads(new Error("The Codex shared server closed"));
3806
- try {
3807
- await stopConnection(connected);
3808
- } finally {
3809
- linked.abort();
3810
- linked.release();
3811
- }
3888
+ let closing;
3889
+ const closeServer = () => {
3890
+ closing ??= (async () => {
3891
+ liveness.markClosing();
3892
+ const answer = liveness.closingGracefully;
3893
+ await releaseExternalCodexRequestsBeforeStop([globalExternalPending, ...[...threads.values()].map((slot) => slot.externalPending)], answer);
3894
+ failAllThreads(new Error("The Codex shared server closed"));
3895
+ try {
3896
+ await stopConnection(connected);
3897
+ } finally {
3898
+ linked.abort();
3899
+ linked.release();
3900
+ }
3901
+ })();
3902
+ return closing;
3812
3903
  };
3813
3904
  opened = true;
3814
3905
  return {
@@ -3820,6 +3911,11 @@ async function openCodexSharedServer(config, baseCapabilities, input) {
3820
3911
  },
3821
3912
  capabilities: sharedCapabilities,
3822
3913
  ...controlClient,
3914
+ unsubscribeThread(params, options) {
3915
+ if (threads.has(params.threadId) || closingThreadIds.has(params.threadId))
3916
+ return refuseOwnedUnsubscribe(params.threadId);
3917
+ return controlClient.unsubscribeThread(params, options);
3918
+ },
3823
3919
  openThread: (threadInput) => openSharedCodexThread(state, threadInput),
3824
3920
  close: closeServer
3825
3921
  };
@@ -3867,6 +3963,7 @@ function buildCodexSessionConfig(input) {
3867
3963
  serverRequestDelivery: config.serverRequestDelivery
3868
3964
  },
3869
3965
  ...!input.ephemeralProbe && config.onDisconnect !== undefined && { onDisconnect: config.onDisconnect },
3966
+ ...config.onObserverError !== undefined && { onObserverError: config.onObserverError },
3870
3967
  ambient: input.ambient,
3871
3968
  limits: input.limits,
3872
3969
  version: input.version,
@@ -3880,24 +3977,9 @@ function createCodexDriver(config = {}) {
3880
3977
  const executable = config.executable ?? "codex";
3881
3978
  const prefix = config.prefixArgs ?? [];
3882
3979
  const ambient = config.ambient ?? process.env;
3883
- const limits = new Map;
3980
+ const limits = new CodexLimitBook;
3884
3981
  let version = "unknown";
3885
- const capabilities = {
3886
- runtimePolicyEnforcement: "native",
3887
- sessionApproval: true,
3888
- interruptOnDeny: true,
3889
- updatedToolInput: false,
3890
- structuredInput: true,
3891
- steer: true,
3892
- fork: true,
3893
- revert: true,
3894
- compact: true,
3895
- injectItems: true,
3896
- backgroundWorkOutlivesTurn: false,
3897
- multiThreadPerProcess: false,
3898
- images: config.resolveFile !== undefined,
3899
- planLimits: "pull"
3900
- };
3982
+ const capabilities = codexDriverCapabilities({ images: config.resolveFile !== undefined });
3901
3983
  const session = (options) => buildCodexSessionConfig({
3902
3984
  config,
3903
3985
  executable,
@@ -3948,12 +4030,7 @@ ${decoder.decode(loginResult.stderr)}`.trim();
3948
4030
  if (credential === "subscription") {
3949
4031
  try {
3950
4032
  const answer = await ask(parsed, process.cwd(), (peer) => peer.request("account/rateLimits/read"));
3951
- const snapshot = codexPlanLimits(answer);
3952
- planLimits = {
3953
- ...snapshot,
3954
- windows: snapshot.windows.toSorted((a, b) => a.name.localeCompare(b.name))
3955
- };
3956
- limits.set(parsed.profileId, planLimits);
4033
+ planLimits = limits.replace(parsed.profileId, answer, new Date);
3957
4034
  } catch (error) {
3958
4035
  planLimits = planLimitsReadFailed2({
3959
4036
  previous: limits.get(parsed.profileId),