stitchkit 0.132.2 → 0.133.0

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