stitchkit 0.127.0 → 0.129.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 (313) hide show
  1. package/CHANGELOG.md +194 -6
  2. package/dist/agent-executor/acp/v1-connect.d.ts +9 -1
  3. package/dist/agent-executor/acp/v1-connect.d.ts.map +1 -1
  4. package/dist/agent-executor/acp/v1-driver.d.ts +8 -2
  5. package/dist/agent-executor/acp/v1-driver.d.ts.map +1 -1
  6. package/dist/agent-executor/acp/v1-map.d.ts.map +1 -1
  7. package/dist/agent-executor/acp/v1-session.d.ts +8 -0
  8. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  9. package/dist/agent-executor/claude/cli-driver.d.ts +4 -0
  10. package/dist/agent-executor/claude/cli-driver.d.ts.map +1 -1
  11. package/dist/agent-executor/claude/protocol.d.ts +20 -2
  12. package/dist/agent-executor/claude/protocol.d.ts.map +1 -1
  13. package/dist/agent-executor/claude/session.d.ts +2 -1
  14. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  15. package/dist/agent-executor/claude/transcript.d.ts +9 -6
  16. package/dist/agent-executor/claude/transcript.d.ts.map +1 -1
  17. package/dist/agent-executor/claude-sdk/controls.d.ts +19 -0
  18. package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -0
  19. package/dist/agent-executor/claude-sdk/driver.d.ts +118 -4
  20. package/dist/agent-executor/claude-sdk/driver.d.ts.map +1 -1
  21. package/dist/agent-executor/claude-sdk/query-loop.d.ts +46 -0
  22. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -0
  23. package/dist/agent-executor/claude-sdk/query-options.d.ts +27 -0
  24. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -0
  25. package/dist/agent-executor/claude-sdk/session.d.ts +6 -5
  26. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  27. package/dist/agent-executor/codex/classify.d.ts.map +1 -1
  28. package/dist/agent-executor/codex/connect.d.ts +45 -0
  29. package/dist/agent-executor/codex/connect.d.ts.map +1 -0
  30. package/dist/agent-executor/codex/driver.d.ts +55 -10
  31. package/dist/agent-executor/codex/driver.d.ts.map +1 -1
  32. package/dist/agent-executor/codex/limits.d.ts +11 -2
  33. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  34. package/dist/agent-executor/codex/protocol.d.ts +75 -6
  35. package/dist/agent-executor/codex/protocol.d.ts.map +1 -1
  36. package/dist/agent-executor/codex/session-controls.d.ts +155 -0
  37. package/dist/agent-executor/codex/session-controls.d.ts.map +1 -0
  38. package/dist/agent-executor/codex/session.d.ts +28 -30
  39. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  40. package/dist/agent-executor/codex/unix-socket-target.d.ts +26 -0
  41. package/dist/agent-executor/codex/unix-socket-target.d.ts.map +1 -0
  42. package/dist/agent-executor/codex/unix-socket.d.ts +26 -0
  43. package/dist/agent-executor/codex/unix-socket.d.ts.map +1 -0
  44. package/dist/agent-executor/codex/ws-frame.d.ts +15 -0
  45. package/dist/agent-executor/codex/ws-frame.d.ts.map +1 -0
  46. package/dist/agent-executor/contract.d.ts +2 -0
  47. package/dist/agent-executor/contract.d.ts.map +1 -1
  48. package/dist/agent-executor/engine-process.d.ts +9 -0
  49. package/dist/agent-executor/engine-process.d.ts.map +1 -1
  50. package/dist/agent-executor/hello.d.ts +8 -0
  51. package/dist/agent-executor/hello.d.ts.map +1 -1
  52. package/dist/agent-executor/image-input.d.ts +71 -0
  53. package/dist/agent-executor/image-input.d.ts.map +1 -0
  54. package/dist/agent-executor/session-primitives.d.ts +0 -3
  55. package/dist/agent-executor/session-primitives.d.ts.map +1 -1
  56. package/dist/agent-runtime/agent-tool.d.ts +21 -7
  57. package/dist/agent-runtime/agent-tool.d.ts.map +1 -1
  58. package/dist/agent-runtime/branch-contract.d.ts +1 -0
  59. package/dist/agent-runtime/branch-contract.d.ts.map +1 -1
  60. package/dist/agent-runtime/branch-identities.d.ts +5 -2
  61. package/dist/agent-runtime/branch-identities.d.ts.map +1 -1
  62. package/dist/agent-runtime/branch-messages.d.ts +9 -9
  63. package/dist/agent-runtime/branch-messages.d.ts.map +1 -1
  64. package/dist/agent-runtime/branch-observations.d.ts +49 -36
  65. package/dist/agent-runtime/branch-observations.d.ts.map +1 -1
  66. package/dist/agent-runtime/branch-provider.d.ts +14 -8
  67. package/dist/agent-runtime/branch-provider.d.ts.map +1 -1
  68. package/dist/agent-runtime/branch-source.d.ts +13 -1
  69. package/dist/agent-runtime/branch-source.d.ts.map +1 -1
  70. package/dist/agent-runtime/child-tools.d.ts +64 -0
  71. package/dist/agent-runtime/child-tools.d.ts.map +1 -1
  72. package/dist/agent-runtime/event-search-tools.d.ts +82 -5
  73. package/dist/agent-runtime/event-search-tools.d.ts.map +1 -1
  74. package/dist/agent-runtime/invocation-attempt.d.ts +1 -1
  75. package/dist/agent-runtime/invocation-attempt.d.ts.map +1 -1
  76. package/dist/agent-runtime/invocation-payload.d.ts +12 -0
  77. package/dist/agent-runtime/invocation-payload.d.ts.map +1 -1
  78. package/dist/agent-runtime/invocation-read.d.ts +6 -3
  79. package/dist/agent-runtime/invocation-read.d.ts.map +1 -1
  80. package/dist/agent-runtime/invocation-schema.d.ts +50 -8
  81. package/dist/agent-runtime/invocation-schema.d.ts.map +1 -1
  82. package/dist/agent-runtime/invocations.d.ts +20 -9
  83. package/dist/agent-runtime/invocations.d.ts.map +1 -1
  84. package/dist/agent-runtime/postgres.d.ts.map +1 -1
  85. package/dist/agent-runtime/schedule-tools.d.ts +30 -0
  86. package/dist/agent-runtime/schedule-tools.d.ts.map +1 -1
  87. package/dist/agent-runtime/schemas-invocation-payload.d.ts +48 -0
  88. package/dist/agent-runtime/schemas-invocation-payload.d.ts.map +1 -0
  89. package/dist/agent-runtime/sql-events.d.ts.map +1 -1
  90. package/dist/agent-runtime/sql-rows.d.ts +10 -10
  91. package/dist/agent-runtime/sql-session.d.ts +11 -0
  92. package/dist/agent-runtime/sql-session.d.ts.map +1 -1
  93. package/dist/agent-runtime/sqlite-transactions.d.ts.map +1 -1
  94. package/dist/agent-runtime/state-tools.d.ts +55 -0
  95. package/dist/agent-runtime/state-tools.d.ts.map +1 -1
  96. package/dist/agent-runtime/store-branch.d.ts.map +1 -1
  97. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
  98. package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
  99. package/dist/agent-runtime/store-create.d.ts.map +1 -1
  100. package/dist/agent-runtime/store-driver-contract.d.ts +12 -0
  101. package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -1
  102. package/dist/agent-runtime/store-memory-events.d.ts.map +1 -1
  103. package/dist/agent-runtime/store.d.ts +7 -0
  104. package/dist/agent-runtime/store.d.ts.map +1 -1
  105. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  106. package/dist/declaration/declaration.d.ts +6 -3
  107. package/dist/declaration/declaration.d.ts.map +1 -1
  108. package/dist/entrypoints/agent-executor/acp.d.ts +1 -1
  109. package/dist/entrypoints/agent-executor/acp.d.ts.map +1 -1
  110. package/dist/entrypoints/agent-executor/acp.js +28 -17
  111. package/dist/entrypoints/agent-executor/claude-sdk.d.ts +1 -1
  112. package/dist/entrypoints/agent-executor/claude-sdk.d.ts.map +1 -1
  113. package/dist/entrypoints/agent-executor/claude-sdk.js +543 -96
  114. package/dist/entrypoints/agent-executor/claude.js +40 -21
  115. package/dist/entrypoints/agent-executor/codex.d.ts +4 -0
  116. package/dist/entrypoints/agent-executor/codex.d.ts.map +1 -1
  117. package/dist/entrypoints/agent-executor/codex.js +1530 -207
  118. package/dist/entrypoints/agent-executor.js +7 -7
  119. package/dist/entrypoints/agent-runtime/browser.js +1 -1
  120. package/dist/entrypoints/agent-runtime/coding-tools.js +3 -3
  121. package/dist/entrypoints/agent-runtime/harness.js +10 -11
  122. package/dist/entrypoints/agent-runtime/openrouter.js +4 -4
  123. package/dist/entrypoints/agent-runtime/postgres.js +12 -7
  124. package/dist/entrypoints/agent-runtime/realtime.js +4 -4
  125. package/dist/entrypoints/agent-runtime/sandbox.js +7 -7
  126. package/dist/entrypoints/agent-runtime/sqlite/bun.js +7 -7
  127. package/dist/entrypoints/agent-runtime/sqlite/node.js +7 -7
  128. package/dist/entrypoints/agent-runtime/testing.js +9 -9
  129. package/dist/entrypoints/agent-runtime.d.ts +9 -7
  130. package/dist/entrypoints/agent-runtime.d.ts.map +1 -1
  131. package/dist/entrypoints/agent-runtime.js +254 -207
  132. package/dist/entrypoints/application/diagnostic-journal.js +4 -4
  133. package/dist/entrypoints/application/directory-inbox.js +8 -8
  134. package/dist/entrypoints/application/opentelemetry.js +2 -2
  135. package/dist/entrypoints/application.js +2 -2
  136. package/dist/entrypoints/cli/publish.js +8 -8
  137. package/dist/entrypoints/cli.js +12 -11
  138. package/dist/entrypoints/contract.js +2 -2
  139. package/dist/entrypoints/declaration.js +0 -1
  140. package/dist/entrypoints/files/packaging.js +2 -2
  141. package/dist/entrypoints/files.js +42 -19
  142. package/dist/entrypoints/handler.js +4 -4
  143. package/dist/entrypoints/http.js +5 -5
  144. package/dist/entrypoints/index.js +7 -7
  145. package/dist/entrypoints/node.js +7 -7
  146. package/dist/entrypoints/observability.js +4 -4
  147. package/dist/entrypoints/primitives.js +2 -2
  148. package/dist/entrypoints/process.js +6 -6
  149. package/dist/entrypoints/react.js +1 -1
  150. package/dist/entrypoints/remote.js +2 -2
  151. package/dist/entrypoints/server.js +10 -10
  152. package/dist/entrypoints/service-host/macos.js +6 -6
  153. package/dist/entrypoints/service-host.d.ts +4 -1
  154. package/dist/entrypoints/service-host.d.ts.map +1 -1
  155. package/dist/entrypoints/service-host.js +835 -224
  156. package/dist/entrypoints/spend.js +1 -1
  157. package/dist/entrypoints/sync/postgres.js +1 -1
  158. package/dist/entrypoints/sync.js +2 -2
  159. package/dist/entrypoints/telegram.js +5 -5
  160. package/dist/entrypoints/testing.js +5 -5
  161. package/dist/entrypoints/tools/agent.js +5 -4
  162. package/dist/entrypoints/tools/connections.js +2 -2
  163. package/dist/entrypoints/tools/invoker.js +4 -3
  164. package/dist/entrypoints/tools/mcp.js +5 -4
  165. package/dist/entrypoints/tools/toolkit.js +8 -7
  166. package/dist/entrypoints/tools.d.ts +1 -1
  167. package/dist/entrypoints/tools.d.ts.map +1 -1
  168. package/dist/entrypoints/tools.js +15 -13
  169. package/dist/entrypoints/tracking/contract.js +1 -1
  170. package/dist/entrypoints/xlsx.js +1 -1
  171. package/dist/files/directory-appearance.d.ts +20 -9
  172. package/dist/files/directory-appearance.d.ts.map +1 -1
  173. package/dist/files/polled-json.d.ts.map +1 -1
  174. package/dist/files/regular-file.d.ts +15 -5
  175. package/dist/files/regular-file.d.ts.map +1 -1
  176. package/dist/{index-prf6ayhf.js → index-13wmzpa6.js} +1 -1
  177. package/dist/{index-qnzhmk2s.js → index-17qgm6xe.js} +91 -48
  178. package/dist/{index-wv8dqy7q.js → index-205456mf.js} +1 -1
  179. package/dist/{index-3gwp8ez6.js → index-21cfxc4z.js} +13 -18
  180. package/dist/{index-xtkw9866.js → index-2c5w2d1d.js} +1 -1
  181. package/dist/{index-g1q7fwn9.js → index-2nwvn7m2.js} +1 -1
  182. package/dist/{index-d4svrknj.js → index-39c2hj6h.js} +2 -2
  183. package/dist/{index-sfzfd2m2.js → index-39rmc00v.js} +1 -1
  184. package/dist/{index-ky3ardqn.js → index-3fym4j8n.js} +1 -1
  185. package/dist/{index-d96c1n1q.js → index-5tdc0q43.js} +20 -19
  186. package/dist/{index-3ypvpkwr.js → index-669374qc.js} +1 -1
  187. package/dist/{index-x90w78yz.js → index-673drwkn.js} +23 -8
  188. package/dist/{index-83n766x4.js → index-7jqn3b3g.js} +16 -10
  189. package/dist/{index-5jyjb4s0.js → index-80acsm27.js} +1 -1
  190. package/dist/{index-xmr47znh.js → index-827bgv33.js} +1 -1
  191. package/dist/{index-xypxnzhp.js → index-93n6jwy0.js} +4 -4
  192. package/dist/{index-wbnpa8z6.js → index-9kpxz49v.js} +5 -5
  193. package/dist/{index-fcw255hd.js → index-9sfhje6y.js} +3 -3
  194. package/dist/{index-bh4pmtr9.js → index-afb6z77w.js} +3 -1
  195. package/dist/{index-9y0afd5f.js → index-apf5g7y9.js} +1 -1
  196. package/dist/{index-4qvyhn23.js → index-bjmj2q1z.js} +1 -1
  197. package/dist/{index-bbzvrq66.js → index-dcsxj68j.js} +457 -204
  198. package/dist/{index-j516jaaz.js → index-dnzxxf8a.js} +49 -2
  199. package/dist/{index-kmbpej2y.js → index-emgrmavr.js} +102 -61
  200. package/dist/index-fgahdc7s.js +100 -0
  201. package/dist/{index-kzavdze2.js → index-gr0kxymw.js} +5 -1
  202. package/dist/{index-e06z0tkb.js → index-gya4hwh3.js} +2 -2
  203. package/dist/{index-3djgv3ch.js → index-hab790s6.js} +26 -11
  204. package/dist/{index-j13gzgdv.js → index-j0ef04jw.js} +9 -5
  205. package/dist/{index-rhb33thr.js → index-jcge9tx3.js} +1 -1
  206. package/dist/{index-dvd1qdwa.js → index-ke02kxsr.js} +3 -3
  207. package/dist/{index-3agqmmrg.js → index-mkfhpk11.js} +7 -9
  208. package/dist/{index-a725ayvz.js → index-mttkdm5a.js} +1 -1
  209. package/dist/{index-9wh98cpa.js → index-n3bm7zqq.js} +131 -91
  210. package/dist/{index-7xp05h20.js → index-p06z7g7w.js} +7 -7
  211. package/dist/{index-kt6dh1n6.js → index-p16q492v.js} +1 -1
  212. package/dist/{index-5zwac8ft.js → index-pp97q86a.js} +3 -3
  213. package/dist/{index-39n02e0q.js → index-psye60qn.js} +1 -1
  214. package/dist/{index-5ptwb6ka.js → index-pzhqydxb.js} +1 -1
  215. package/dist/{index-7kfcb576.js → index-qa2jjb65.js} +1 -1
  216. package/dist/{index-0djnptn8.js → index-qhjmmsm2.js} +10 -3
  217. package/dist/{index-7grgs8cx.js → index-qpzyahe3.js} +2 -2
  218. package/dist/{index-8xr2eq99.js → index-r97ppg0g.js} +4 -4
  219. package/dist/{index-bmaz3jzy.js → index-rjs94dny.js} +1 -1
  220. package/dist/{index-p1m9djt6.js → index-rxh3qy4x.js} +33 -6
  221. package/dist/{index-en8e5zsj.js → index-ryxb427v.js} +1 -1
  222. package/dist/{index-nbv44x0x.js → index-s2e3h616.js} +137 -36
  223. package/dist/{index-dwa6pskj.js → index-sd4e5x5j.js} +86 -47
  224. package/dist/{index-g56ht6qf.js → index-t3qcac2a.js} +1 -1
  225. package/dist/index-vgzhw2zk.js +304 -0
  226. package/dist/{index-jrka9029.js → index-vmbxj75t.js} +2 -2
  227. package/dist/{index-caywx1c0.js → index-wv2amqm4.js} +109 -12
  228. package/dist/{index-5e0zsbf7.js → index-x2fb37t0.js} +2 -2
  229. package/dist/{index-z4k0hqp9.js → index-y71zn1gw.js} +137 -27
  230. package/dist/{index-wavv538x.js → index-ybdq8kk2.js} +3 -3
  231. package/dist/{index-4gk6k3zc.js → index-ycr4pk0z.js} +1 -1
  232. package/dist/{index-0tyt97nk.js → index-yrr3n391.js} +1 -1
  233. package/dist/{index-v37b2cd6.js → index-z20pdxeb.js} +2 -2
  234. package/dist/{index-0hdm5sx6.js → index-z9d74jmb.js} +8 -4
  235. package/dist/{index-4s2w4g37.js → index-zhshhxew.js} +80 -2
  236. package/dist/{index-3b31z0pc.js → index-znd1b57f.js} +12 -6
  237. package/dist/internal/bounded-file-confirm.d.ts +32 -0
  238. package/dist/internal/bounded-file-confirm.d.ts.map +1 -0
  239. package/dist/internal/bounded-file-read.d.ts +10 -7
  240. package/dist/internal/bounded-file-read.d.ts.map +1 -1
  241. package/dist/internal/file-observation.d.ts +5 -1
  242. package/dist/internal/file-observation.d.ts.map +1 -1
  243. package/dist/internal/positive-integer.d.ts +2 -0
  244. package/dist/internal/positive-integer.d.ts.map +1 -1
  245. package/dist/internal/process-instance.d.ts +8 -0
  246. package/dist/internal/process-instance.d.ts.map +1 -1
  247. package/dist/internal/unix-socket.d.ts +10 -1
  248. package/dist/internal/unix-socket.d.ts.map +1 -1
  249. package/dist/server/unix-client.d.ts +7 -0
  250. package/dist/server/unix-client.d.ts.map +1 -1
  251. package/dist/service-host/systemd-inspect.d.ts +3 -1
  252. package/dist/service-host/systemd-inspect.d.ts.map +1 -1
  253. package/dist/service-host/systemd-render-shared.d.ts +64 -0
  254. package/dist/service-host/systemd-render-shared.d.ts.map +1 -0
  255. package/dist/service-host/systemd-render.d.ts +31 -26
  256. package/dist/service-host/systemd-render.d.ts.map +1 -1
  257. package/dist/service-host/systemd-timer-render.d.ts +31 -0
  258. package/dist/service-host/systemd-timer-render.d.ts.map +1 -0
  259. package/dist/service-host/systemd-timer-rollback.d.ts +26 -0
  260. package/dist/service-host/systemd-timer-rollback.d.ts.map +1 -0
  261. package/dist/service-host/systemd-timer.d.ts +82 -0
  262. package/dist/service-host/systemd-timer.d.ts.map +1 -0
  263. package/dist/service-host/systemd-unit-ops.d.ts +26 -0
  264. package/dist/service-host/systemd-unit-ops.d.ts.map +1 -0
  265. package/dist/service-host/systemd.d.ts +1 -1
  266. package/dist/service-host/systemd.d.ts.map +1 -1
  267. package/dist/tools/access.d.ts +30 -1
  268. package/dist/tools/access.d.ts.map +1 -1
  269. package/dist/tools/agent.d.ts +2 -2
  270. package/dist/tools/agent.d.ts.map +1 -1
  271. package/dist/tools/cli/args-scan.d.ts +5 -0
  272. package/dist/tools/cli/args-scan.d.ts.map +1 -1
  273. package/dist/tools/cli/args.d.ts +11 -5
  274. package/dist/tools/cli/args.d.ts.map +1 -1
  275. package/dist/tools/cli/invoke.d.ts +2 -1
  276. package/dist/tools/cli/invoke.d.ts.map +1 -1
  277. package/dist/tools/cli/notices.d.ts.map +1 -1
  278. package/dist/tools/cli/run-managed.d.ts.map +1 -1
  279. package/dist/tools/cli/session.d.ts.map +1 -1
  280. package/dist/tools/execute.d.ts.map +1 -1
  281. package/dist/tools/invoker.d.ts +2 -1
  282. package/dist/tools/invoker.d.ts.map +1 -1
  283. package/dist/tools/list-names.d.ts +2 -3
  284. package/dist/tools/list-names.d.ts.map +1 -1
  285. package/dist/tools/manifest.d.ts +2 -3
  286. package/dist/tools/manifest.d.ts.map +1 -1
  287. package/dist/tools/mcp/mount.d.ts +5 -5
  288. package/dist/tools/mcp/mount.d.ts.map +1 -1
  289. package/dist/tools/mcp/register.d.ts +2 -1
  290. package/dist/tools/mcp/register.d.ts.map +1 -1
  291. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -1
  292. package/llms/agent-executor-acp.txt +10 -6
  293. package/llms/agent-executor-claude-sdk.txt +13 -10
  294. package/llms/agent-executor-claude.txt +2 -2
  295. package/llms/agent-executor-codex.txt +9 -3
  296. package/llms/agent-executor.txt +2 -2
  297. package/llms/agent-runtime.4.txt +21 -9
  298. package/llms/cli.3.txt +4 -4
  299. package/llms/cli.txt +1 -0
  300. package/llms/declaration.txt +2 -2
  301. package/llms/files.txt +1 -1
  302. package/llms/node.txt +2 -2
  303. package/llms/server.5.txt +2 -2
  304. package/llms/service-host.txt +5 -5
  305. package/llms/stitchkit.txt +81 -77
  306. package/llms/tools.3.txt +3 -2
  307. package/llms/upgrading-0.128.0-0.129.0.txt +175 -0
  308. package/llms/upgrading.txt +1 -0
  309. package/llms-full.txt +323 -127
  310. package/llms.txt +15 -14
  311. package/package.json +1 -1
  312. package/dist/index-ajmtxsky.js +0 -193
  313. package/dist/index-ax3wns1a.js +0 -93
@@ -4,121 +4,162 @@ import {
4
4
  PlanWindowSchema2,
5
5
  engineProfile,
6
6
  engineEnvironment2
7
- } from "../../index-bh4pmtr9.js";
7
+ } from "../../index-afb6z77w.js";
8
8
  import"../../index-09f7w2qq.js";
9
9
  import"../../index-v59pxmf1.js";
10
- import"../../index-7kfcb576.js";
10
+ import"../../index-qa2jjb65.js";
11
11
  import"../../index-6kec3b14.js";
12
12
  import {
13
13
  nonEmptyString,
14
14
  epochSecondsToIso,
15
15
  createTurnDeltaChannel,
16
16
  offerTurnDelta,
17
- extractTextOnlyInput,
18
17
  sessionAbort,
19
18
  runEngineCli,
20
19
  stopConnection,
21
20
  withEphemeralConnection,
22
21
  safeJsonValue,
22
+ validateImageOptions,
23
+ inlineParts,
24
+ imageTurnStarter,
23
25
  holdEngineRequest,
24
26
  answerEngineRequest,
25
27
  drainEngineRequests,
26
28
  endEngineTurn,
27
29
  loseEngineTurn
28
- } from "../../index-caywx1c0.js";
30
+ } from "../../index-wv2amqm4.js";
31
+ import"../../index-673drwkn.js";
32
+ import"../../index-vmbxj75t.js";
29
33
  import {
30
34
  JsonRpcError2,
31
35
  JSON_RPC_METHOD_NOT_FOUND2,
32
36
  createJsonRpcPeer2
33
37
  } from "../../index-1q0n6zek.js";
34
- import"../../index-5ptwb6ka.js";
38
+ import"../../index-pzhqydxb.js";
35
39
  import {
36
40
  spawnEngineProcess2
37
- } from "../../index-p1m9djt6.js";
38
- import"../../index-ky3ardqn.js";
41
+ } from "../../index-rxh3qy4x.js";
42
+ import"../../index-3fym4j8n.js";
39
43
  import {
40
44
  planLimitsReadFailed2,
41
45
  mergeRateLimitEvent2
42
- } from "../../index-4qvyhn23.js";
46
+ } from "../../index-bjmj2q1z.js";
47
+ import {
48
+ assertUnixSocketPathLength,
49
+ assertExpectedOwnerUid,
50
+ unixSocketDirectoryViolation
51
+ } from "../../index-hab790s6.js";
52
+ import {
53
+ errnoOf
54
+ } from "../../index-jj9228tt.js";
55
+ import {
56
+ isPositiveSafeInteger,
57
+ assertPositiveSafeInteger
58
+ } from "../../index-gr0kxymw.js";
59
+ import {
60
+ assertTimerMs,
61
+ withSignalDeadline
62
+ } from "../../index-agy5fqgf.js";
63
+ import {
64
+ abortReason,
65
+ raceAbort
66
+ } from "../../index-rptj3qnc.js";
43
67
 
44
- // src/agent-executor/codex/limits.ts
68
+ // src/agent-executor/codex/protocol.ts
45
69
  import { z } from "zod";
46
- var WindowSchema = z.looseObject({
47
- usedPercent: z.number().min(0),
48
- windowDurationMins: z.number().positive().nullable().optional(),
49
- resetsAt: z.number().positive().nullable().optional()
70
+ var CodexCollaborationModeSchema = z.strictObject({
71
+ mode: z.enum(["plan", "default"]),
72
+ settings: z.strictObject({
73
+ model: z.string().min(1),
74
+ reasoning_effort: z.string().min(1).nullable().optional(),
75
+ developer_instructions: z.string().nullable().optional()
76
+ })
50
77
  });
51
- var RateLimitsSchema = z.looseObject({
52
- primary: WindowSchema.nullable().optional(),
53
- secondary: WindowSchema.nullable().optional()
78
+ var CodexThreadItemSchema = z.looseObject({
79
+ type: z.string(),
80
+ id: z.string().min(1)
54
81
  });
55
- function codexPlanWindows(rateLimits) {
56
- const parsed = RateLimitsSchema.safeParse(rateLimits);
57
- if (!parsed.success)
58
- return [];
59
- const windows = [];
60
- for (const name of ["primary", "secondary"]) {
61
- const window = parsed.data[name];
62
- if (window === null || window === undefined)
63
- continue;
64
- const resetsAt = epochSecondsToIso(window.resetsAt);
65
- windows.push(PlanWindowSchema2.parse({
66
- name,
67
- usedPercent: Math.min(100, window.usedPercent),
68
- ...resetsAt !== undefined && { resetsAt }
69
- }));
70
- }
71
- return windows;
72
- }
73
-
74
- // src/agent-executor/codex/protocol.ts
75
- import { z as z2 } from "zod";
76
- var CodexThreadItemSchema = z2.looseObject({
77
- type: z2.string(),
78
- id: z2.string().min(1)
79
- });
80
- var CodexTurnSchema = z2.looseObject({
81
- id: z2.string().min(1),
82
- status: z2.enum(["completed", "interrupted", "failed", "inProgress"]),
83
- error: z2.looseObject({ message: z2.string(), codexErrorInfo: z2.json().nullable().optional() }).nullable().optional(),
84
- items: z2.array(z2.looseObject({ type: z2.string(), clientId: z2.string().nullable().optional() })).optional()
82
+ var CodexTurnSchema = z.looseObject({
83
+ id: z.string().min(1),
84
+ status: z.enum(["completed", "interrupted", "failed", "inProgress"]),
85
+ error: z.looseObject({ message: z.string(), codexErrorInfo: z.json().nullable().optional() }).nullable().optional(),
86
+ items: z.array(z.looseObject({ type: z.string(), clientId: z.string().nullable().optional() })).optional()
85
87
  });
86
88
  var CodexNotificationParams = {
87
- "item/agentMessage/delta": z2.looseObject({ itemId: z2.string(), delta: z2.string() }),
88
- "item/reasoning/textDelta": z2.looseObject({ itemId: z2.string(), delta: z2.string() }),
89
- "item/reasoning/summaryTextDelta": z2.looseObject({ itemId: z2.string(), delta: z2.string() }),
90
- "item/started": z2.looseObject({ item: CodexThreadItemSchema }),
91
- "item/completed": z2.looseObject({ item: CodexThreadItemSchema }),
92
- "turn/completed": z2.looseObject({ turn: CodexTurnSchema }),
93
- "thread/tokenUsage/updated": z2.looseObject({
94
- tokenUsage: z2.looseObject({
95
- last: z2.looseObject({
96
- inputTokens: z2.int().nonnegative(),
97
- outputTokens: z2.int().nonnegative(),
98
- cachedInputTokens: z2.int().nonnegative().optional()
89
+ "item/agentMessage/delta": z.looseObject({ itemId: z.string(), delta: z.string() }),
90
+ "item/reasoning/textDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
91
+ "item/reasoning/summaryTextDelta": z.looseObject({ itemId: z.string(), delta: z.string() }),
92
+ "item/started": z.looseObject({ item: CodexThreadItemSchema }),
93
+ "item/completed": z.looseObject({ item: CodexThreadItemSchema }),
94
+ "turn/completed": z.looseObject({ turn: CodexTurnSchema }),
95
+ "thread/tokenUsage/updated": z.looseObject({
96
+ tokenUsage: z.looseObject({
97
+ last: z.looseObject({
98
+ inputTokens: z.int().nonnegative(),
99
+ outputTokens: z.int().nonnegative(),
100
+ cachedInputTokens: z.int().nonnegative().optional()
99
101
  })
100
102
  })
101
103
  }),
102
- "serverRequest/resolved": z2.looseObject({ requestId: z2.union([z2.string(), z2.int()]) }),
103
- "account/rateLimits/updated": z2.looseObject({ rateLimits: z2.json() })
104
+ "serverRequest/resolved": z.looseObject({ requestId: z.union([z.string(), z.int()]) }),
105
+ "account/rateLimits/updated": z.looseObject({
106
+ rateLimits: z.json(),
107
+ rateLimitsByLimitId: z.json().optional()
108
+ })
104
109
  };
105
- var CodexApprovalParamsSchema = z2.looseObject({
106
- itemId: z2.string(),
107
- command: z2.string().nullable().optional(),
108
- reason: z2.string().nullable().optional()
110
+ var CodexApprovalParamsSchema = z.looseObject({
111
+ itemId: z.string(),
112
+ command: z.string().nullable().optional(),
113
+ reason: z.string().nullable().optional()
114
+ });
115
+ var CodexUserInputParamsSchema = z.looseObject({
116
+ itemId: z.string(),
117
+ questions: z.array(z.looseObject({ id: z.string(), question: z.string(), header: z.string() }))
118
+ });
119
+ var CodexUserInputAnswersSchema = z.record(z.string(), z.strictObject({ answers: z.array(z.string()) }));
120
+ var CodexThreadContextSchema = z.object({
121
+ model: z.string().optional(),
122
+ modelProvider: z.string().optional(),
123
+ reasoningEffort: z.string().nullable().optional(),
124
+ approvalPolicy: z.json().optional(),
125
+ sandbox: z.json().optional(),
126
+ cwd: z.string().optional(),
127
+ runtimeWorkspaceRoots: z.array(z.string()).readonly().optional()
128
+ });
129
+ var CodexStartedThreadSchema = CodexThreadContextSchema.extend({
130
+ thread: z.looseObject({ id: z.string().min(1) })
131
+ }).loose();
132
+ function extractCodexThreadContext(parsed) {
133
+ return {
134
+ ...parsed.model !== undefined && { model: parsed.model },
135
+ ...parsed.modelProvider !== undefined && { modelProvider: parsed.modelProvider },
136
+ ...parsed.reasoningEffort !== undefined && { reasoningEffort: parsed.reasoningEffort },
137
+ ...parsed.approvalPolicy !== undefined && { approvalPolicy: parsed.approvalPolicy },
138
+ ...parsed.sandbox !== undefined && { sandbox: parsed.sandbox },
139
+ ...parsed.cwd !== undefined && { cwd: parsed.cwd },
140
+ ...parsed.runtimeWorkspaceRoots !== undefined && {
141
+ runtimeWorkspaceRoots: parsed.runtimeWorkspaceRoots
142
+ }
143
+ };
144
+ }
145
+ var CodexStartedTurnSchema = z.looseObject({
146
+ turn: z.looseObject({ id: z.string().min(1) })
109
147
  });
110
- var CodexUserInputParamsSchema = z2.looseObject({
111
- itemId: z2.string(),
112
- questions: z2.array(z2.looseObject({ id: z2.string(), question: z2.string(), header: z2.string() }))
148
+ var CodexTurnSteerResponseSchema = z.looseObject({
149
+ turnId: z.string().min(1)
113
150
  });
114
- var CodexUserInputAnswersSchema = z2.record(z2.string(), z2.strictObject({ answers: z2.array(z2.string()) }));
115
- var CodexStartedThreadSchema = z2.looseObject({
116
- thread: z2.looseObject({ id: z2.string().min(1) })
151
+ var CodexListedTurnItemSchema = z.looseObject({
152
+ type: z.string(),
153
+ clientId: z.string().nullable().optional()
117
154
  });
118
- var CodexStartedTurnSchema = z2.looseObject({
119
- turn: z2.looseObject({ id: z2.string().min(1) })
155
+ var CodexListedTurnSchema = CodexTurnSchema.extend({
156
+ items: z.array(CodexListedTurnItemSchema),
157
+ itemsView: z.literal("full").optional()
158
+ });
159
+ var CodexTurnsPageSchema = z.looseObject({
160
+ data: z.array(CodexListedTurnSchema),
161
+ nextCursor: z.string().nullable().optional()
120
162
  });
121
- var CodexTurnsPageSchema = z2.looseObject({ data: z2.array(CodexTurnSchema) });
122
163
  var CODEX_OPTED_OUT_NOTIFICATIONS = [
123
164
  "item/commandExecution/outputDelta",
124
165
  "item/fileChange/outputDelta",
@@ -157,6 +198,990 @@ var CODEX_APPROVAL_DECISION = {
157
198
  interrupted: "cancel"
158
199
  };
159
200
 
201
+ // src/agent-executor/codex/unix-socket.ts
202
+ import { createHash, randomBytes as randomBytes2 } from "node:crypto";
203
+ import { createConnection } from "node:net";
204
+
205
+ // src/agent-executor/codex/unix-socket-target.ts
206
+ import { lstatSync, realpathSync } from "node:fs";
207
+ import { dirname } from "node:path";
208
+ class CodexUnixSocketError extends Error {
209
+ kind;
210
+ socketPath;
211
+ constructor(kind, socketPath, message, options) {
212
+ super(message, options);
213
+ this.kind = kind;
214
+ this.socketPath = socketPath;
215
+ this.name = "CodexUnixSocketError";
216
+ }
217
+ }
218
+ function validateCodexUnixSocketPath(socketPath, caller) {
219
+ if (typeof socketPath !== "string" || socketPath.length === 0) {
220
+ throw new TypeError(`[stitchkit] ${caller}: unix socketPath must be a non-empty string`);
221
+ }
222
+ if (!socketPath.startsWith("/")) {
223
+ throw new TypeError(`[stitchkit] ${caller}: unix socketPath must be an absolute path starting with "/", received ${JSON.stringify(socketPath)}`);
224
+ }
225
+ if (/[\0\r\n\s?#]/.test(socketPath)) {
226
+ throw new TypeError(`[stitchkit] ${caller}: unix socketPath contains forbidden characters (whitespace, NUL, ?, or #)`);
227
+ }
228
+ assertUnixSocketPathLength(socketPath, caller);
229
+ }
230
+ function lstatTarget(targetPath, label, socketPath, caller) {
231
+ try {
232
+ return lstatSync(targetPath, { throwIfNoEntry: false });
233
+ } catch (error) {
234
+ if (errnoOf(error) === "ENOENT")
235
+ return;
236
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to inspect unix socket ${label} "${targetPath}"`, { cause: error });
237
+ }
238
+ }
239
+ function assertPrivateDirStats(dir, requiredUid, socketPath, caller) {
240
+ const stats = lstatTarget(dir, "directory", socketPath, caller);
241
+ if (stats === undefined)
242
+ return "absent";
243
+ const violation = unixSocketDirectoryViolation(dir, stats, caller, requiredUid);
244
+ if (violation !== undefined) {
245
+ throw new CodexUnixSocketError("target-refused", socketPath, violation);
246
+ }
247
+ return "present";
248
+ }
249
+ function assertCodexUnixListenTargetAvailable(socketPath, caller) {
250
+ const dir = dirname(socketPath);
251
+ const requiredUid = typeof process.getuid === "function" ? process.getuid() : undefined;
252
+ if (assertPrivateDirStats(dir, requiredUid, socketPath, caller) === "absent") {
253
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket directory "${dir}" does not exist`);
254
+ }
255
+ const existing = lstatTarget(socketPath, "path", socketPath, caller);
256
+ if (existing !== undefined) {
257
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket path "${socketPath}" already exists — choose a fresh socket path or remove the stale socket first`);
258
+ }
259
+ }
260
+ function assertCodexUnixSocketClientTarget(socketPath, caller, expectedOwnerUid) {
261
+ assertExpectedOwnerUid(expectedOwnerUid, caller);
262
+ const requiredUid = expectedOwnerUid !== undefined ? expectedOwnerUid : typeof process.getuid === "function" ? process.getuid() : undefined;
263
+ if (assertPrivateDirStats(dirname(socketPath), requiredUid, socketPath, caller) === "absent") {
264
+ return "absent";
265
+ }
266
+ const stats = lstatTarget(socketPath, "path", socketPath, caller);
267
+ if (stats === undefined)
268
+ return "absent";
269
+ if (requiredUid !== undefined && stats.uid !== requiredUid) {
270
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: unix socket "${socketPath}" is owned by uid ${stats.uid}, expected ${requiredUid}`);
271
+ }
272
+ if (stats.isSymbolicLink()) {
273
+ let resolved;
274
+ try {
275
+ resolved = realpathSync(socketPath);
276
+ } catch (error) {
277
+ if (errnoOf(error) === "ENOENT")
278
+ return "absent";
279
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: failed to resolve unix socket symlink "${socketPath}"`, { cause: error });
280
+ }
281
+ if (assertPrivateDirStats(dirname(resolved), requiredUid, socketPath, caller) === "absent") {
282
+ return "absent";
283
+ }
284
+ const targetStats = lstatTarget(resolved, "resolved target", socketPath, caller);
285
+ if (targetStats === undefined)
286
+ return "absent";
287
+ if (!targetStats.isSocket()) {
288
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is not a socket`);
289
+ }
290
+ if (requiredUid !== undefined && targetStats.uid !== requiredUid) {
291
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: resolved unix socket target "${resolved}" is owned by uid ${targetStats.uid}, expected ${requiredUid}`);
292
+ }
293
+ return "present";
294
+ }
295
+ if (!stats.isSocket()) {
296
+ throw new CodexUnixSocketError("target-refused", socketPath, `[stitchkit] ${caller}: "${socketPath}" is not a unix socket`);
297
+ }
298
+ return "present";
299
+ }
300
+
301
+ // src/agent-executor/codex/ws-frame.ts
302
+ import { randomBytes } from "node:crypto";
303
+ var MAX_WS_FRAGMENTS = 1024;
304
+ var MAX_CONTROL_PAYLOAD_BYTES = 125;
305
+ function maskedWsFrameByteLength(payloadBytes) {
306
+ const headerLen = payloadBytes < 126 ? 2 : payloadBytes <= 65535 ? 4 : 10;
307
+ return headerLen + 4 + payloadBytes;
308
+ }
309
+ function encodeMaskedWsFrame(opcode, payload) {
310
+ const len = payload.byteLength;
311
+ const headerLen = len < 126 ? 2 : len <= 65535 ? 4 : 10;
312
+ const frame = Buffer.allocUnsafe(headerLen + 4 + len);
313
+ frame[0] = 128 | opcode & 15;
314
+ if (len < 126) {
315
+ frame[1] = 128 | len;
316
+ } else if (len <= 65535) {
317
+ frame[1] = 128 | 126;
318
+ frame.writeUInt16BE(len, 2);
319
+ } else {
320
+ frame[1] = 128 | 127;
321
+ const hi = Math.floor(len / 4294967296);
322
+ const lo = len >>> 0;
323
+ frame.writeUInt32BE(hi, 2);
324
+ frame.writeUInt32BE(lo, 6);
325
+ }
326
+ const mask = randomBytes(4);
327
+ frame[headerLen] = mask[0] ?? 0;
328
+ frame[headerLen + 1] = mask[1] ?? 0;
329
+ frame[headerLen + 2] = mask[2] ?? 0;
330
+ frame[headerLen + 3] = mask[3] ?? 0;
331
+ const bodyOffset = headerLen + 4;
332
+ for (let i = 0;i < len; i += 1) {
333
+ frame[bodyOffset + i] = (payload[i] ?? 0) ^ (mask[i & 3] ?? 0);
334
+ }
335
+ return frame;
336
+ }
337
+ function createByteQueue() {
338
+ const chunks = [];
339
+ let headOffset = 0;
340
+ let total = 0;
341
+ return {
342
+ get length() {
343
+ return total;
344
+ },
345
+ push(chunk) {
346
+ if (chunk.byteLength === 0)
347
+ return;
348
+ chunks.push(chunk);
349
+ total += chunk.byteLength;
350
+ },
351
+ peekBytes(count) {
352
+ const first = chunks[0];
353
+ if (first !== undefined && first.byteLength - headOffset >= count) {
354
+ return first.subarray(headOffset, headOffset + count);
355
+ }
356
+ const out = Buffer.allocUnsafe(count);
357
+ let written = 0;
358
+ let idx = 0;
359
+ let off = headOffset;
360
+ while (written < count && idx < chunks.length) {
361
+ const cur = chunks[idx];
362
+ if (cur === undefined)
363
+ break;
364
+ const take = Math.min(cur.byteLength - off, count - written);
365
+ cur.copy(out, written, off, off + take);
366
+ written += take;
367
+ idx += 1;
368
+ off = 0;
369
+ }
370
+ return out;
371
+ },
372
+ consume(count) {
373
+ const out = Buffer.allocUnsafe(count);
374
+ let written = 0;
375
+ while (written < count && chunks.length > 0) {
376
+ const cur = chunks[0];
377
+ if (cur === undefined)
378
+ break;
379
+ const avail = cur.byteLength - headOffset;
380
+ const take = Math.min(avail, count - written);
381
+ cur.copy(out, written, headOffset, headOffset + take);
382
+ written += take;
383
+ total -= take;
384
+ if (take === avail) {
385
+ chunks.shift();
386
+ headOffset = 0;
387
+ } else {
388
+ headOffset += take;
389
+ }
390
+ }
391
+ return out;
392
+ },
393
+ skip(count) {
394
+ let left = count;
395
+ while (left > 0 && chunks.length > 0) {
396
+ const cur = chunks[0];
397
+ if (cur === undefined)
398
+ break;
399
+ const avail = cur.byteLength - headOffset;
400
+ if (left >= avail) {
401
+ chunks.shift();
402
+ headOffset = 0;
403
+ total -= avail;
404
+ left -= avail;
405
+ } else {
406
+ headOffset += left;
407
+ total -= left;
408
+ left = 0;
409
+ }
410
+ }
411
+ },
412
+ clear() {
413
+ chunks.length = 0;
414
+ headOffset = 0;
415
+ total = 0;
416
+ }
417
+ };
418
+ }
419
+ function createWsFrameDecoder(handlers) {
420
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
421
+ const queue = createByteQueue();
422
+ let fragments;
423
+ let fragmentBytes = 0;
424
+ let stopped = false;
425
+ const fail = (message) => {
426
+ stopped = true;
427
+ queue.clear();
428
+ fragments = undefined;
429
+ fragmentBytes = 0;
430
+ handlers.onProtocolError(message);
431
+ };
432
+ return {
433
+ push(chunk) {
434
+ if (stopped || chunk.byteLength === 0)
435
+ return;
436
+ queue.push(chunk);
437
+ while (!stopped && queue.length >= 2) {
438
+ const head2 = queue.peekBytes(2);
439
+ const b0 = head2[0] ?? 0;
440
+ const b1 = head2[1] ?? 0;
441
+ if ((b0 & 112) !== 0)
442
+ return fail("Server WebSocket frame set reserved RSV bits");
443
+ if ((b1 & 128) !== 0)
444
+ return fail("Server WebSocket frame must not be masked");
445
+ const fin = (b0 & 128) !== 0;
446
+ const opcode = b0 & 15;
447
+ const len7 = b1 & 127;
448
+ let headerLen = 2;
449
+ let payloadLen = len7;
450
+ if (len7 === 126) {
451
+ if (queue.length < 4)
452
+ break;
453
+ headerLen = 4;
454
+ payloadLen = queue.peekBytes(4).readUInt16BE(2);
455
+ } else if (len7 === 127) {
456
+ if (queue.length < 10)
457
+ break;
458
+ headerLen = 10;
459
+ const head10 = queue.peekBytes(10);
460
+ const hi = head10.readUInt32BE(2);
461
+ const lo = head10.readUInt32BE(6);
462
+ if ((hi & 2147483648) !== 0)
463
+ return fail("WebSocket 64-bit frame length has MSB set");
464
+ payloadLen = hi * 4294967296 + lo;
465
+ }
466
+ if (opcode >= 8) {
467
+ if (!fin)
468
+ return fail("Control WebSocket frame must not be fragmented");
469
+ if (payloadLen > MAX_CONTROL_PAYLOAD_BYTES) {
470
+ return fail(`Control WebSocket frame payload (${payloadLen} bytes) exceeds 125 bytes`);
471
+ }
472
+ if (opcode !== 8 && opcode !== 9 && opcode !== 10) {
473
+ return fail(`Unsupported WebSocket control opcode 0x${opcode.toString(16)}`);
474
+ }
475
+ } else {
476
+ if (opcode !== 0 && opcode !== 1) {
477
+ return fail(`Unsupported WebSocket data opcode 0x${opcode.toString(16)}`);
478
+ }
479
+ if (!Number.isSafeInteger(payloadLen) || payloadLen > handlers.maxFrameBytes) {
480
+ return fail(`WebSocket frame payload (${payloadLen} bytes) exceeds maxFrameBytes (${handlers.maxFrameBytes})`);
481
+ }
482
+ if (opcode === 1 && fragments !== undefined) {
483
+ return fail("Interleaved WebSocket text frame during fragmented message");
484
+ }
485
+ if (opcode === 0 && fragments === undefined) {
486
+ return fail("Unexpected WebSocket continuation frame without an active message");
487
+ }
488
+ if (fragments !== undefined) {
489
+ if (fragments.length + 1 > MAX_WS_FRAGMENTS) {
490
+ return fail(`Fragmented WebSocket message exceeded ${MAX_WS_FRAGMENTS} frames`);
491
+ }
492
+ if (fragmentBytes + payloadLen > handlers.maxFrameBytes) {
493
+ return fail(`Fragmented WebSocket message exceeded maxFrameBytes (${handlers.maxFrameBytes})`);
494
+ }
495
+ }
496
+ }
497
+ if (queue.length < headerLen + payloadLen)
498
+ break;
499
+ queue.skip(headerLen);
500
+ const payload = queue.consume(payloadLen);
501
+ if (opcode === 9) {
502
+ handlers.onPing(payload);
503
+ } else if (opcode === 10) {} else if (opcode === 8) {
504
+ if (payload.byteLength === 1)
505
+ return fail("WebSocket close frame payload cannot be 1 byte");
506
+ const code = payload.byteLength >= 2 ? payload.readUInt16BE(0) : undefined;
507
+ let reason = "";
508
+ if (payload.byteLength > 2) {
509
+ try {
510
+ reason = utf8.decode(payload.subarray(2));
511
+ } catch {
512
+ return fail("WebSocket close frame reason is not valid UTF-8");
513
+ }
514
+ }
515
+ stopped = true;
516
+ queue.clear();
517
+ fragments = undefined;
518
+ fragmentBytes = 0;
519
+ handlers.onClose(code, reason);
520
+ return;
521
+ } else if (opcode === 1) {
522
+ if (fin) {
523
+ let text;
524
+ try {
525
+ text = utf8.decode(payload);
526
+ } catch {
527
+ return fail("WebSocket text frame is not valid UTF-8");
528
+ }
529
+ handlers.onMessage(text);
530
+ } else {
531
+ fragments = [payload];
532
+ fragmentBytes = payload.byteLength;
533
+ }
534
+ } else if (opcode === 0 && fragments !== undefined) {
535
+ fragments.push(payload);
536
+ fragmentBytes += payload.byteLength;
537
+ if (fin) {
538
+ const combined = Buffer.concat(fragments, fragmentBytes);
539
+ fragments = undefined;
540
+ fragmentBytes = 0;
541
+ let text;
542
+ try {
543
+ text = utf8.decode(combined);
544
+ } catch {
545
+ return fail("Reassembled WebSocket text message is not valid UTF-8");
546
+ }
547
+ handlers.onMessage(text);
548
+ }
549
+ }
550
+ }
551
+ }
552
+ };
553
+ }
554
+
555
+ // src/agent-executor/codex/unix-socket.ts
556
+ var WS_MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
557
+ var MAX_HANDSHAKE_HEADER_BYTES = 64 * 1024;
558
+ var DEFAULT_HANDSHAKE_TIMEOUT_MS = 15000;
559
+ var DEFAULT_MAX_FRAME_BYTES = 16 * 1024 * 1024;
560
+ var DEFAULT_MAX_PENDING_WRITE_BYTES = 16 * 1024 * 1024;
561
+ var CLOSE_GRACE_MS = 250;
562
+ function validateHandshakeResponse(headerText, expectedAccept, socketPath) {
563
+ const lines = headerText.split(`\r
564
+ `);
565
+ const statusLine = lines[0] ?? "";
566
+ if (!/^HTTP\/1\.1 101(?:\s|$)/.test(statusLine)) {
567
+ throw new CodexUnixSocketError("upgrade-refused", socketPath, `Codex Unix socket WebSocket upgrade failed: ${statusLine || "empty response"}`);
568
+ }
569
+ const headers = new Map;
570
+ for (let i = 1;i < lines.length; i += 1) {
571
+ const line = lines[i] ?? "";
572
+ if (line.length === 0)
573
+ continue;
574
+ const colon = line.indexOf(":");
575
+ if (colon <= 0) {
576
+ throw new CodexUnixSocketError("upgrade-refused", socketPath, "Codex Unix socket upgrade response contained a malformed HTTP header line");
577
+ }
578
+ const key = line.slice(0, colon).trim().toLowerCase();
579
+ const value = line.slice(colon + 1).trim();
580
+ const existing = headers.get(key);
581
+ headers.set(key, existing === undefined ? value : `${existing}, ${value}`);
582
+ }
583
+ if ((headers.get("upgrade") ?? "").toLowerCase() !== "websocket") {
584
+ throw new CodexUnixSocketError("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Upgrade: websocket" header');
585
+ }
586
+ const connectionTokens = (headers.get("connection") ?? "").toLowerCase().split(",").map((token) => token.trim());
587
+ if (!connectionTokens.includes("upgrade")) {
588
+ throw new CodexUnixSocketError("upgrade-refused", socketPath, 'Codex Unix socket upgrade response missing "Connection: upgrade" header');
589
+ }
590
+ if (headers.get("sec-websocket-accept") !== expectedAccept) {
591
+ throw new CodexUnixSocketError("upgrade-refused", socketPath, "Codex Unix socket upgrade response returned an invalid Sec-WebSocket-Accept header");
592
+ }
593
+ }
594
+ function classifyConnectError(error, socketPath) {
595
+ const code = errnoOf(error);
596
+ if (code === "ENOENT") {
597
+ return new CodexUnixSocketError("endpoint-absent", socketPath, `Codex Unix socket "${socketPath}" does not exist`, { cause: error });
598
+ }
599
+ if (code === "ECONNREFUSED") {
600
+ return new CodexUnixSocketError("endpoint-not-listening", socketPath, `Codex Unix socket "${socketPath}" refused connection`, { cause: error });
601
+ }
602
+ return new CodexUnixSocketError("connection-lost", socketPath, `Failed to connect to Codex Unix socket "${socketPath}": ${error instanceof Error ? error.message : String(error)}`, { cause: error });
603
+ }
604
+ function performWsUpgrade(input) {
605
+ const wsKey = randomBytes2(16).toString("base64");
606
+ const expectedAccept = createHash("sha1").update(`${wsKey}${WS_MAGIC_GUID}`).digest("base64");
607
+ return withSignalDeadline(input.handshakeTimeoutMs, input.signal, () => new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket WebSocket handshake timed out after ${input.handshakeTimeoutMs} ms`), (handshakeSignal) => new Promise((resolve, reject) => {
608
+ let settled = false;
609
+ let handshakeBuf = Buffer.alloc(0);
610
+ const sock = createConnection({ path: input.socketPath });
611
+ const cleanup = () => {
612
+ handshakeSignal.removeEventListener("abort", onAbort);
613
+ sock.off("connect", onConnect);
614
+ sock.off("data", onData);
615
+ sock.off("error", onError);
616
+ sock.off("close", onClose);
617
+ };
618
+ const fail = (error) => {
619
+ if (settled)
620
+ return;
621
+ settled = true;
622
+ cleanup();
623
+ sock.destroy();
624
+ reject(error);
625
+ };
626
+ const onAbort = () => fail(abortReason(handshakeSignal));
627
+ const onConnect = () => {
628
+ sock.write(`GET /rpc HTTP/1.1\r
629
+ Host: localhost\r
630
+ Upgrade: websocket\r
631
+ Connection: Upgrade\r
632
+ Sec-WebSocket-Key: ${wsKey}\r
633
+ Sec-WebSocket-Version: 13\r
634
+ \r
635
+ `);
636
+ };
637
+ const onData = (chunk) => {
638
+ const combinedLen = handshakeBuf.byteLength + chunk.byteLength;
639
+ if (handshakeBuf.byteLength > MAX_HANDSHAKE_HEADER_BYTES) {
640
+ fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
641
+ return;
642
+ }
643
+ const nextBuf = handshakeBuf.byteLength === 0 ? chunk : Buffer.concat([handshakeBuf, chunk]);
644
+ const boundary = nextBuf.indexOf(`\r
645
+ \r
646
+ `);
647
+ if (boundary === -1) {
648
+ if (combinedLen > MAX_HANDSHAKE_HEADER_BYTES) {
649
+ fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
650
+ return;
651
+ }
652
+ handshakeBuf = nextBuf;
653
+ return;
654
+ }
655
+ if (boundary > MAX_HANDSHAKE_HEADER_BYTES) {
656
+ fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, `Codex Unix socket upgrade headers exceeded ${MAX_HANDSHAKE_HEADER_BYTES} bytes`));
657
+ return;
658
+ }
659
+ const headerText = nextBuf.subarray(0, boundary).toString("latin1");
660
+ const rest = Buffer.from(nextBuf.subarray(boundary + 4));
661
+ try {
662
+ validateHandshakeResponse(headerText, expectedAccept, input.socketPath);
663
+ } catch (error) {
664
+ fail(error);
665
+ return;
666
+ }
667
+ settled = true;
668
+ sock.pause();
669
+ cleanup();
670
+ resolve({ socket: sock, trailing: rest });
671
+ };
672
+ const onError = (error) => fail(classifyConnectError(error, input.socketPath));
673
+ const onClose = () => fail(new CodexUnixSocketError("upgrade-refused", input.socketPath, "Codex Unix socket closed before completing WebSocket upgrade"));
674
+ handshakeSignal.addEventListener("abort", onAbort, { once: true });
675
+ sock.once("connect", onConnect);
676
+ sock.on("data", onData);
677
+ sock.once("error", onError);
678
+ sock.once("close", onClose);
679
+ }));
680
+ }
681
+ async function connectCodexUnixSocket(input) {
682
+ validateCodexUnixSocketPath(input.socketPath, "connectCodexUnixSocket");
683
+ assertTimerMs("handshakeTimeoutMs", input.handshakeTimeoutMs);
684
+ assertPositiveSafeInteger("maxFrameBytes", input.maxFrameBytes);
685
+ assertPositiveSafeInteger("maxPendingWriteBytes", input.maxPendingWriteBytes);
686
+ input.signal.throwIfAborted();
687
+ input.connectSignal?.throwIfAborted();
688
+ const targetState = assertCodexUnixSocketClientTarget(input.socketPath, "connectCodexUnixSocket", input.expectedOwnerUid);
689
+ if (targetState === "absent") {
690
+ throw new CodexUnixSocketError("endpoint-absent", input.socketPath, `Codex Unix socket "${input.socketPath}" does not exist`);
691
+ }
692
+ const maxFrameBytes = input.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
693
+ const maxPendingWriteBytes = input.maxPendingWriteBytes ?? DEFAULT_MAX_PENDING_WRITE_BYTES;
694
+ const { socket, trailing } = await performWsUpgrade({
695
+ socketPath: input.socketPath,
696
+ signal: input.connectSignal ?? input.signal,
697
+ handshakeTimeoutMs: input.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS
698
+ });
699
+ if (input.signal.aborted) {
700
+ socket.destroy();
701
+ throw abortReason(input.signal);
702
+ }
703
+ if (socket.destroyed) {
704
+ throw new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed during WebSocket upgrade`);
705
+ }
706
+ let closed = false;
707
+ let closeSent = false;
708
+ const closedDeferred = Promise.withResolvers();
709
+ const finishClosed = (error) => {
710
+ if (closed)
711
+ return;
712
+ closed = true;
713
+ input.signal.removeEventListener("abort", onSignalAbort);
714
+ closedDeferred.resolve();
715
+ input.onClose(error);
716
+ };
717
+ const sendControlFrame = (opcode, payload) => {
718
+ if (closed || socket.destroyed || !socket.writable)
719
+ return;
720
+ const frameBytes = maskedWsFrameByteLength(payload.byteLength);
721
+ if (socket.writableLength + frameBytes > maxPendingWriteBytes)
722
+ return;
723
+ socket.write(encodeMaskedWsFrame(opcode, payload));
724
+ };
725
+ const closeGracefully = async () => {
726
+ if (closed)
727
+ return closedDeferred.promise;
728
+ if (!closeSent && socket.writable && !socket.destroyed) {
729
+ closeSent = true;
730
+ const closeBody = Buffer.allocUnsafe(2);
731
+ closeBody.writeUInt16BE(1000, 0);
732
+ try {
733
+ sendControlFrame(8, closeBody);
734
+ } catch {}
735
+ socket.end();
736
+ }
737
+ const grace = setTimeout(() => {
738
+ if (!socket.destroyed)
739
+ socket.destroy();
740
+ }, CLOSE_GRACE_MS);
741
+ grace.unref?.();
742
+ try {
743
+ await closedDeferred.promise;
744
+ } finally {
745
+ clearTimeout(grace);
746
+ }
747
+ };
748
+ const onSignalAbort = () => {
749
+ const err = new CodexUnixSocketError("connection-lost", input.socketPath, "Codex Unix socket connection aborted", { cause: abortReason(input.signal) });
750
+ socket.destroy();
751
+ finishClosed(err);
752
+ };
753
+ input.signal.addEventListener("abort", onSignalAbort, { once: true });
754
+ const decoder = createWsFrameDecoder({
755
+ maxFrameBytes,
756
+ onMessage: input.onMessage,
757
+ onPing: (payload) => sendControlFrame(10, payload),
758
+ onClose: (code, reason) => {
759
+ if (!closeSent) {
760
+ closeSent = true;
761
+ sendControlFrame(8, Buffer.alloc(0));
762
+ }
763
+ socket.end();
764
+ const suffix = reason.length > 0 ? `: ${reason}` : "";
765
+ finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket closed by peer (${code ?? "no-code"})${suffix}`));
766
+ },
767
+ onProtocolError: (message) => {
768
+ const err = new CodexUnixSocketError("connection-lost", input.socketPath, message);
769
+ socket.destroy();
770
+ finishClosed(err);
771
+ }
772
+ });
773
+ socket.on("data", (chunk) => decoder.push(chunk));
774
+ socket.on("error", (error) => {
775
+ finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket error: ${error.message}`, { cause: error }));
776
+ });
777
+ socket.on("close", () => {
778
+ finishClosed(new CodexUnixSocketError("connection-lost", input.socketPath, `Codex Unix socket "${input.socketPath}" closed`));
779
+ });
780
+ if (trailing.byteLength > 0)
781
+ decoder.push(trailing);
782
+ if (!closed && !socket.destroyed)
783
+ socket.resume();
784
+ return {
785
+ send(text) {
786
+ if (closed || socket.destroyed || !socket.writable) {
787
+ throw new CodexUnixSocketError("connection-lost", input.socketPath, "Codex Unix socket connection is closed");
788
+ }
789
+ const payloadBytes = Buffer.byteLength(text, "utf8");
790
+ const frameBytes = maskedWsFrameByteLength(payloadBytes);
791
+ if (socket.writableLength + frameBytes > maxPendingWriteBytes) {
792
+ throw new RangeError(`Codex Unix socket outbound queue exceeded ${maxPendingWriteBytes} bytes (${frameBytes} bytes needed)`);
793
+ }
794
+ socket.write(encodeMaskedWsFrame(1, Buffer.from(text, "utf8")));
795
+ },
796
+ close: () => closeGracefully(),
797
+ closed: closedDeferred.promise
798
+ };
799
+ }
800
+
801
+ // src/agent-executor/codex/connect.ts
802
+ var BOOTSTRAP_MS = 45000;
803
+ var REQUEST_MS = 60000;
804
+ var DEFAULT_LISTEN_TIMEOUT_MS = 15000;
805
+ var POLL_INITIAL_MS = 15;
806
+ var POLL_MAX_MS = 50;
807
+ function validateCodexTransportAndArgs(config) {
808
+ if (config.serverArgs !== undefined) {
809
+ if (!Array.isArray(config.serverArgs)) {
810
+ throw new TypeError("[stitchkit] createCodexDriver: serverArgs must be an array of strings");
811
+ }
812
+ for (const arg of config.serverArgs) {
813
+ if (typeof arg !== "string") {
814
+ throw new TypeError("[stitchkit] createCodexDriver: every serverArgs entry must be a string");
815
+ }
816
+ if (arg === "--listen" || arg === "--stdio" || arg.startsWith("--listen=") || arg.startsWith("--stdio=")) {
817
+ throw new TypeError(`[stitchkit] createCodexDriver: serverArgs must not include "${arg}"; configure transport via config.transport instead`);
818
+ }
819
+ }
820
+ }
821
+ const transport = config.transport;
822
+ if (transport === undefined || transport.kind === "stdio")
823
+ return;
824
+ if (transport.kind === "unix-listen") {
825
+ validateCodexUnixSocketPath(transport.socketPath, "createCodexDriver");
826
+ assertTimerMs("listenTimeoutMs", transport.listenTimeoutMs);
827
+ return;
828
+ }
829
+ if (transport.kind === "unix-connect") {
830
+ validateCodexUnixSocketPath(transport.socketPath, "createCodexDriver");
831
+ assertExpectedOwnerUid(transport.expectedOwnerUid, "createCodexDriver");
832
+ if ((config.serverArgs?.length ?? 0) > 0) {
833
+ throw new TypeError('[stitchkit] createCodexDriver: serverArgs cannot be used with transport kind "unix-connect"');
834
+ }
835
+ return;
836
+ }
837
+ throw new TypeError(`[stitchkit] createCodexDriver: unsupported transport kind ${JSON.stringify(Reflect.get(Object(transport), "kind"))}`);
838
+ }
839
+ async function initializeCodexPeer(peer, version) {
840
+ await peer.request("initialize", {
841
+ clientInfo: { name: "stitchkit-agent-executor", version },
842
+ capabilities: {
843
+ experimentalApi: true,
844
+ optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
845
+ }
846
+ }, { timeoutMs: BOOTSTRAP_MS });
847
+ peer.notify("initialized");
848
+ }
849
+ function sleepAbortable(ms, signal) {
850
+ if (signal.aborted)
851
+ return Promise.reject(abortReason(signal));
852
+ return new Promise((resolve, reject) => {
853
+ const timer = setTimeout(() => {
854
+ signal.removeEventListener("abort", onAbort);
855
+ resolve();
856
+ }, ms);
857
+ const onAbort = () => {
858
+ clearTimeout(timer);
859
+ reject(abortReason(signal));
860
+ };
861
+ signal.addEventListener("abort", onAbort, { once: true });
862
+ });
863
+ }
864
+ async function dialWithEngineRace(input) {
865
+ const exitAbort = new AbortController;
866
+ let exitedEarly;
867
+ input.engine.result.then((res) => {
868
+ const detail = input.engine.stderrTail().slice(-2000).trim();
869
+ exitedEarly = new Error(`Codex app-server exited before listening on "${input.socketPath}" (code ${res.exitCode ?? "signal"})${detail.length > 0 ? `: ${detail}` : ""}`);
870
+ exitAbort.abort(exitedEarly);
871
+ }, (error) => {
872
+ const detail = input.engine.stderrTail().slice(-2000).trim();
873
+ exitedEarly = new Error(`Codex app-server failed before listening on "${input.socketPath}": ${error instanceof Error ? error.message : String(error)}${detail.length > 0 ? ` (${detail})` : ""}`, { cause: error });
874
+ exitAbort.abort(exitedEarly);
875
+ });
876
+ return withSignalDeadline(input.listenTimeoutMs, input.signal, () => new CodexUnixSocketError("endpoint-absent", input.socketPath, `Codex app-server did not listen on "${input.socketPath}" within ${input.listenTimeoutMs} ms`), async (deadlineSignal) => {
877
+ let delayMs = POLL_INITIAL_MS;
878
+ for (;; ) {
879
+ if (exitedEarly !== undefined)
880
+ throw exitedEarly;
881
+ deadlineSignal.throwIfAborted();
882
+ try {
883
+ return await raceAbort(connectCodexUnixSocket({
884
+ socketPath: input.socketPath,
885
+ signal: input.signal,
886
+ connectSignal: deadlineSignal,
887
+ ...input.maxFrameBytes !== undefined && { maxFrameBytes: input.maxFrameBytes },
888
+ onMessage: input.onMessage,
889
+ onClose: input.onClose
890
+ }), exitAbort.signal, (lateClient) => {
891
+ lateClient.close().catch(() => {
892
+ return;
893
+ });
894
+ });
895
+ } catch (error) {
896
+ if (exitedEarly !== undefined)
897
+ throw exitedEarly;
898
+ const retryable = error instanceof CodexUnixSocketError && (error.kind === "endpoint-absent" || error.kind === "endpoint-not-listening");
899
+ if (!retryable)
900
+ throw error;
901
+ await raceAbort(sleepAbortable(delayMs, deadlineSignal), exitAbort.signal);
902
+ delayMs = Math.min(POLL_MAX_MS, Math.round(delayMs * 1.5));
903
+ }
904
+ }
905
+ });
906
+ }
907
+ async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd = () => {
908
+ return;
909
+ }) {
910
+ const transport = config.transport ?? { kind: "stdio" };
911
+ const extraArgs = config.serverArgs ?? [];
912
+ if (transport.kind === "stdio") {
913
+ const env = engineEnvironment2(profile, config.ambient);
914
+ const peer = createJsonRpcPeer2({
915
+ header: "omitted",
916
+ requestTimeoutMs: REQUEST_MS,
917
+ send: (line) => engine.send(line),
918
+ ...handlers
919
+ });
920
+ const engine = spawnEngineProcess2({
921
+ executable: config.executable,
922
+ args: [...config.prefix, "app-server", ...extraArgs],
923
+ cwd,
924
+ env,
925
+ signal,
926
+ ...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
927
+ });
928
+ const reading = (async () => {
929
+ try {
930
+ for await (const line of engine.lines)
931
+ peer.receive(line);
932
+ const ended = new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`);
933
+ peer.close(ended);
934
+ onEnd(ended);
935
+ } catch (error) {
936
+ const failed = error instanceof Error ? error : new Error(String(error));
937
+ peer.close(failed);
938
+ onEnd(failed);
939
+ await engine.stop().catch(() => {
940
+ return;
941
+ });
942
+ }
943
+ })();
944
+ try {
945
+ await initializeCodexPeer(peer, config.version);
946
+ const providerPid = await engine.pidReady ?? engine.pid;
947
+ return { engine, peer, reading, providerPid };
948
+ } catch (error) {
949
+ await stopConnection({ engine, reading }, { error });
950
+ throw error;
951
+ }
952
+ }
953
+ let wsClient;
954
+ let spawnedEngine;
955
+ let endedError;
956
+ let ready = false;
957
+ const peer = createJsonRpcPeer2({
958
+ header: "omitted",
959
+ requestTimeoutMs: REQUEST_MS,
960
+ send: (line) => {
961
+ if (wsClient === undefined) {
962
+ throw new Error("Codex Unix socket transport is not connected");
963
+ }
964
+ wsClient.send(line);
965
+ },
966
+ ...handlers
967
+ });
968
+ const finishEnd = (error) => {
969
+ if (endedError !== undefined)
970
+ return;
971
+ endedError = error;
972
+ peer.close(error);
973
+ if (ready)
974
+ onEnd(error);
975
+ };
976
+ const onMessage = (line) => {
977
+ try {
978
+ peer.receive(line);
979
+ } catch (error) {
980
+ const failed = error instanceof Error ? error : new Error(String(error));
981
+ finishEnd(failed);
982
+ wsClient?.close().catch(() => {
983
+ return;
984
+ });
985
+ spawnedEngine?.stop().catch(() => {
986
+ return;
987
+ });
988
+ }
989
+ };
990
+ const onClose = (error) => {
991
+ finishEnd(error);
992
+ };
993
+ if (transport.kind === "unix-listen") {
994
+ assertCodexUnixListenTargetAvailable(transport.socketPath, "createCodexDriver");
995
+ const env = engineEnvironment2(profile, config.ambient);
996
+ spawnedEngine = spawnEngineProcess2({
997
+ executable: config.executable,
998
+ args: [
999
+ ...config.prefix,
1000
+ "app-server",
1001
+ "--listen",
1002
+ `unix://${transport.socketPath}`,
1003
+ ...extraArgs
1004
+ ],
1005
+ cwd,
1006
+ env,
1007
+ signal,
1008
+ stdoutMode: "drain",
1009
+ ...config.maxLineBytes !== undefined && { maxLineBytes: config.maxLineBytes }
1010
+ });
1011
+ try {
1012
+ wsClient = await dialWithEngineRace({
1013
+ socketPath: transport.socketPath,
1014
+ listenTimeoutMs: transport.listenTimeoutMs ?? DEFAULT_LISTEN_TIMEOUT_MS,
1015
+ ...config.maxLineBytes !== undefined && { maxFrameBytes: config.maxLineBytes },
1016
+ signal,
1017
+ engine: spawnedEngine,
1018
+ onMessage,
1019
+ onClose
1020
+ });
1021
+ } catch (error) {
1022
+ peer.close(error);
1023
+ await spawnedEngine.stop().catch(() => {
1024
+ return;
1025
+ });
1026
+ throw error;
1027
+ }
1028
+ } else {
1029
+ try {
1030
+ wsClient = await connectCodexUnixSocket({
1031
+ socketPath: transport.socketPath,
1032
+ ...transport.expectedOwnerUid !== undefined && {
1033
+ expectedOwnerUid: transport.expectedOwnerUid
1034
+ },
1035
+ signal,
1036
+ ...config.maxLineBytes !== undefined && { maxFrameBytes: config.maxLineBytes },
1037
+ onMessage,
1038
+ onClose
1039
+ });
1040
+ } catch (error) {
1041
+ peer.close(error);
1042
+ throw error;
1043
+ }
1044
+ }
1045
+ const activeWs = wsClient;
1046
+ const compositeEngine = {
1047
+ async stop() {
1048
+ try {
1049
+ await activeWs.close();
1050
+ } finally {
1051
+ if (spawnedEngine !== undefined)
1052
+ await spawnedEngine.stop();
1053
+ }
1054
+ }
1055
+ };
1056
+ const reading = activeWs.closed;
1057
+ try {
1058
+ if (endedError !== undefined)
1059
+ throw endedError;
1060
+ await initializeCodexPeer(peer, config.version);
1061
+ if (endedError !== undefined)
1062
+ throw endedError;
1063
+ const providerPid = spawnedEngine !== undefined ? await spawnedEngine.pidReady ?? spawnedEngine.pid : undefined;
1064
+ ready = true;
1065
+ return { engine: compositeEngine, peer, reading, providerPid };
1066
+ } catch (error) {
1067
+ await stopConnection({ engine: compositeEngine, reading }, { error });
1068
+ throw error;
1069
+ }
1070
+ }
1071
+
1072
+ // src/agent-executor/codex/limits.ts
1073
+ import { createHash as createHash2 } from "node:crypto";
1074
+ import { z as z2 } from "zod";
1075
+ var MAX_WINDOW_NAME_CHARS = 256;
1076
+ var MAX_PLAN_WINDOWS = 32;
1077
+ var WindowSchema = z2.looseObject({
1078
+ usedPercent: z2.number().min(0),
1079
+ windowDurationMins: z2.number().positive().nullable().optional(),
1080
+ resetsAt: z2.number().nonnegative().nullable().optional()
1081
+ });
1082
+ var SnapshotSchema = z2.looseObject({
1083
+ limitId: z2.string().nullable().optional(),
1084
+ limitName: z2.string().nullable().optional(),
1085
+ primary: WindowSchema.nullable().optional(),
1086
+ secondary: WindowSchema.nullable().optional()
1087
+ });
1088
+ function positiveSafeInt(value) {
1089
+ return isPositiveSafeInteger(value) ? value : undefined;
1090
+ }
1091
+ function clampWindowName(prefix, suffix, seenNames, disambiguatorSeed) {
1092
+ const maxPrefix = Math.max(1, MAX_WINDOW_NAME_CHARS - suffix.length);
1093
+ let candidate = prefix.length > maxPrefix ? `${prefix.slice(0, maxPrefix)}${suffix}`.slice(0, MAX_WINDOW_NAME_CHARS) : `${prefix}${suffix}`;
1094
+ if (!seenNames.has(candidate)) {
1095
+ seenNames.add(candidate);
1096
+ return candidate;
1097
+ }
1098
+ const digest = createHash2("sha256").update(disambiguatorSeed).digest("hex").slice(0, 8);
1099
+ const tag = `#${digest}${suffix}`;
1100
+ const room = Math.max(1, MAX_WINDOW_NAME_CHARS - tag.length);
1101
+ candidate = `${prefix.slice(0, room)}${tag}`.slice(0, MAX_WINDOW_NAME_CHARS);
1102
+ let n = 2;
1103
+ while (seenNames.has(candidate)) {
1104
+ const indexedTag = `#${digest}_${n}${suffix}`;
1105
+ const indexedRoom = Math.max(1, MAX_WINDOW_NAME_CHARS - indexedTag.length);
1106
+ candidate = `${prefix.slice(0, indexedRoom)}${indexedTag}`.slice(0, MAX_WINDOW_NAME_CHARS);
1107
+ n += 1;
1108
+ }
1109
+ seenNames.add(candidate);
1110
+ return candidate;
1111
+ }
1112
+ function clampLabel(value) {
1113
+ const trimmed = nonEmptyString(value)?.trim();
1114
+ if (trimmed === undefined)
1115
+ return;
1116
+ return trimmed.slice(0, MAX_WINDOW_NAME_CHARS);
1117
+ }
1118
+ function appendBucketWindows(out, seenNames, bucketId, seedKey, snapshot) {
1119
+ const label = clampLabel(snapshot.limitName);
1120
+ const primary = snapshot.primary ?? undefined;
1121
+ const secondary = snapshot.secondary ?? undefined;
1122
+ const primaryMins = positiveSafeInt(primary?.windowDurationMins);
1123
+ const secondaryMins = positiveSafeInt(secondary?.windowDurationMins);
1124
+ const duplicateDuration = primary !== undefined && secondary !== undefined && primaryMins !== undefined && primaryMins === secondaryMins;
1125
+ const slots = [
1126
+ ["primary", primary, primaryMins],
1127
+ ["secondary", secondary, secondaryMins]
1128
+ ];
1129
+ for (const [slot, window, mins] of slots) {
1130
+ if (window === undefined || out.length >= MAX_PLAN_WINDOWS)
1131
+ continue;
1132
+ const suffix = mins === undefined ? `:${slot}` : duplicateDuration ? `:${mins}m:${slot}` : `:${mins}m`;
1133
+ const name = clampWindowName(bucketId, suffix, seenNames, `${seedKey}:${bucketId}:${slot}`);
1134
+ const resetsAt = window.resetsAt !== undefined && window.resetsAt !== null && window.resetsAt > 0 ? epochSecondsToIso(window.resetsAt) : undefined;
1135
+ out.push(PlanWindowSchema2.parse({
1136
+ name,
1137
+ usedPercent: Math.min(100, window.usedPercent),
1138
+ ...resetsAt !== undefined && { resetsAt },
1139
+ ...mins !== undefined && { windowDurationMins: mins },
1140
+ ...label !== undefined && { label }
1141
+ }));
1142
+ }
1143
+ }
1144
+ function isPlainRecord(value) {
1145
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1146
+ }
1147
+ function codexPlanWindows(reported) {
1148
+ const windows = [];
1149
+ const seenNames = new Set;
1150
+ if (isPlainRecord(reported) && (("rateLimits" in reported) || ("rateLimitsByLimitId" in reported))) {
1151
+ const seenLimitIds = new Set;
1152
+ const rawById = reported.rateLimitsByLimitId;
1153
+ if (isPlainRecord(rawById)) {
1154
+ for (const mapKey of Object.keys(rawById).sort((a, b) => a.localeCompare(b))) {
1155
+ const parsed = SnapshotSchema.safeParse(rawById[mapKey]);
1156
+ if (!parsed.success)
1157
+ continue;
1158
+ const limitId = nonEmptyString(parsed.data.limitId)?.trim() ?? nonEmptyString(mapKey)?.trim() ?? "limit";
1159
+ seenLimitIds.add(limitId);
1160
+ appendBucketWindows(windows, seenNames, limitId, mapKey, parsed.data);
1161
+ if (windows.length >= MAX_PLAN_WINDOWS)
1162
+ return windows;
1163
+ }
1164
+ }
1165
+ if (windows.length < MAX_PLAN_WINDOWS && reported.rateLimits !== undefined) {
1166
+ const parsedSingle = SnapshotSchema.safeParse(reported.rateLimits);
1167
+ if (parsedSingle.success) {
1168
+ const explicitId = nonEmptyString(parsedSingle.data.limitId)?.trim();
1169
+ const shouldIncludeSingle = seenLimitIds.size === 0 || explicitId !== undefined && !seenLimitIds.has(explicitId);
1170
+ if (shouldIncludeSingle) {
1171
+ appendBucketWindows(windows, seenNames, explicitId ?? "limit", explicitId ?? "rateLimits", parsedSingle.data);
1172
+ }
1173
+ }
1174
+ }
1175
+ return windows;
1176
+ }
1177
+ const single = SnapshotSchema.safeParse(reported);
1178
+ if (!single.success)
1179
+ return [];
1180
+ const limitId = nonEmptyString(single.data.limitId)?.trim() ?? "limit";
1181
+ appendBucketWindows(windows, seenNames, limitId, limitId, single.data);
1182
+ return windows;
1183
+ }
1184
+
160
1185
  // src/agent-executor/codex/classify.ts
161
1186
  var raw = (type) => ({ source: "codex", type });
162
1187
  var TOOL_ITEMS = new Set([
@@ -323,11 +1348,16 @@ function classifyCodexNotification(method, params, state) {
323
1348
  kind: "resolved",
324
1349
  requestId: String(CodexNotificationParams[method].parse(params).requestId)
325
1350
  };
326
- case "account/rateLimits/updated":
1351
+ case "account/rateLimits/updated": {
1352
+ const parsed = CodexNotificationParams[method].parse(params);
327
1353
  return {
328
1354
  kind: "limits",
329
- rateLimits: CodexNotificationParams[method].parse(params).rateLimits
1355
+ rateLimits: parsed.rateLimitsByLimitId !== undefined ? {
1356
+ rateLimits: parsed.rateLimits,
1357
+ rateLimitsByLimitId: parsed.rateLimitsByLimitId
1358
+ } : parsed.rateLimits
330
1359
  };
1360
+ }
331
1361
  default:
332
1362
  if (CODEX_QUIET_NOTIFICATIONS.has(method))
333
1363
  return { kind: "ignore", reason: method };
@@ -345,57 +1375,212 @@ function classifyCodexNotification(method, params, state) {
345
1375
  }
346
1376
  }
347
1377
 
348
- // src/agent-executor/codex/session.ts
349
- var BOOTSTRAP_MS = 45000;
350
- var REQUEST_MS = 60000;
351
- async function connectCodex(config, profile, cwd, signal, handlers = {}, onEnd = () => {
352
- return;
353
- }) {
354
- const env = engineEnvironment2(profile, config.ambient);
355
- const peer = createJsonRpcPeer2({
356
- header: "omitted",
357
- requestTimeoutMs: REQUEST_MS,
358
- send: (line) => engine.send(line),
359
- ...handlers
360
- });
361
- const engine = spawnEngineProcess2({
362
- executable: config.executable,
363
- args: [...config.prefix, "app-server"],
364
- cwd,
365
- env,
366
- signal
367
- });
368
- const reading = (async () => {
369
- try {
370
- for await (const line of engine.lines)
371
- peer.receive(line);
372
- const ended = new Error(`Codex app-server exited: ${engine.stderrTail().slice(-2000)}`);
373
- peer.close(ended);
374
- onEnd(ended);
375
- } catch (error) {
376
- const failed = error instanceof Error ? error : new Error(String(error));
377
- peer.close(failed);
378
- onEnd(failed);
379
- await engine.stop().catch(() => {
380
- return;
381
- });
1378
+ // src/agent-executor/codex/session-controls.ts
1379
+ function codexTurnInput(parts) {
1380
+ if (parts.every((part) => part.type === "text")) {
1381
+ return [
1382
+ { type: "text", text: parts.map((part) => part.text).join(`
1383
+ `), text_elements: [] }
1384
+ ];
1385
+ }
1386
+ const out = [];
1387
+ for (const part of parts) {
1388
+ if (part.type === "text") {
1389
+ out.push({ type: "text", text: part.text, text_elements: [] });
1390
+ } else {
1391
+ out.push({ type: "image", url: `data:${part.mediaType};base64,${part.base64}` });
382
1392
  }
383
- })();
384
- try {
385
- await peer.request("initialize", {
386
- clientInfo: { name: "stitchkit-agent-executor", version: config.version },
387
- capabilities: {
388
- experimentalApi: true,
389
- optOutNotificationMethods: CODEX_OPTED_OUT_NOTIFICATIONS
390
- }
391
- }, { timeoutMs: BOOTSTRAP_MS });
392
- peer.notify("initialized");
393
- return { engine, peer, reading };
394
- } catch (error) {
395
- await stopConnection({ engine, reading }, { error });
396
- throw error;
397
1393
  }
1394
+ return out;
398
1395
  }
1396
+ function validateCodexPolicyOverrides(overrides, caller) {
1397
+ if (overrides.runtimeWorkspaceRoots !== undefined) {
1398
+ if (!Array.isArray(overrides.runtimeWorkspaceRoots)) {
1399
+ throw new TypeError(`[stitchkit] ${caller}: runtimeWorkspaceRoots must be an array of strings`);
1400
+ }
1401
+ for (const root of overrides.runtimeWorkspaceRoots) {
1402
+ if (typeof root !== "string" || root.trim().length === 0) {
1403
+ throw new TypeError(`[stitchkit] ${caller}: every runtimeWorkspaceRoots entry must be a non-empty string`);
1404
+ }
1405
+ }
1406
+ }
1407
+ if (overrides.config !== undefined) {
1408
+ if (typeof overrides.config !== "object" || overrides.config === null || Array.isArray(overrides.config)) {
1409
+ throw new TypeError(`[stitchkit] ${caller}: config must be a plain JSON object`);
1410
+ }
1411
+ safeJsonValue(overrides.config);
1412
+ }
1413
+ }
1414
+ function buildCodexThreadPolicyParams(base, overrides) {
1415
+ const mergedConfig = base.config !== undefined || overrides?.config !== undefined ? { ...base.config ?? {}, ...overrides?.config ?? {} } : undefined;
1416
+ const merged = {
1417
+ ...base,
1418
+ ...overrides,
1419
+ ...mergedConfig !== undefined && { config: mergedConfig }
1420
+ };
1421
+ validateCodexPolicyOverrides(merged, "CodexSession");
1422
+ const params = {};
1423
+ if (merged.model !== undefined)
1424
+ params.model = merged.model;
1425
+ if (merged.modelProvider !== undefined)
1426
+ params.modelProvider = merged.modelProvider;
1427
+ if (merged.approvalPolicy !== undefined)
1428
+ params.approvalPolicy = safeJsonValue(merged.approvalPolicy);
1429
+ if (merged.sandbox !== undefined)
1430
+ params.sandbox = merged.sandbox;
1431
+ if (merged.developerInstructions !== undefined)
1432
+ params.developerInstructions = merged.developerInstructions;
1433
+ if (merged.runtimeWorkspaceRoots !== undefined)
1434
+ params.runtimeWorkspaceRoots = [...merged.runtimeWorkspaceRoots];
1435
+ if (merged.config !== undefined)
1436
+ params.config = safeJsonValue(merged.config);
1437
+ return params;
1438
+ }
1439
+ function validateCodexTurnStartOverrides(turnInput, activeModelProvider) {
1440
+ if (turnInput.modelProvider !== undefined) {
1441
+ if (activeModelProvider === undefined || turnInput.modelProvider !== activeModelProvider) {
1442
+ throw new TypeError(`Codex turn/start cannot switch modelProvider to ${JSON.stringify(turnInput.modelProvider)} (thread active provider is ${JSON.stringify(activeModelProvider ?? "unknown")})`);
1443
+ }
1444
+ }
1445
+ if (turnInput.collaborationMode !== undefined) {
1446
+ CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
1447
+ }
1448
+ if (turnInput.approvalPolicy !== undefined) {
1449
+ safeJsonValue(turnInput.approvalPolicy);
1450
+ }
1451
+ if (turnInput.sandboxPolicy !== undefined) {
1452
+ safeJsonValue(turnInput.sandboxPolicy);
1453
+ }
1454
+ if (turnInput.runtimeWorkspaceRoots !== undefined) {
1455
+ validateCodexPolicyOverrides({ runtimeWorkspaceRoots: turnInput.runtimeWorkspaceRoots }, "CodexSession.startTurn");
1456
+ }
1457
+ }
1458
+ function buildCodexTurnStartParams(threadId, turnInput, parts, activeModelProvider) {
1459
+ validateCodexTurnStartOverrides(turnInput, activeModelProvider);
1460
+ const params = {
1461
+ threadId,
1462
+ input: codexTurnInput(parts),
1463
+ clientUserMessageId: turnInput.clientId
1464
+ };
1465
+ if (turnInput.model !== undefined)
1466
+ params.model = turnInput.model;
1467
+ if (turnInput.reasoningEffort !== undefined)
1468
+ params.effort = turnInput.reasoningEffort;
1469
+ if (turnInput.collaborationMode !== undefined) {
1470
+ params.collaborationMode = CodexCollaborationModeSchema.parse(turnInput.collaborationMode);
1471
+ }
1472
+ if (turnInput.approvalPolicy !== undefined) {
1473
+ params.approvalPolicy = safeJsonValue(turnInput.approvalPolicy);
1474
+ }
1475
+ if (turnInput.sandboxPolicy !== undefined) {
1476
+ params.sandboxPolicy = safeJsonValue(turnInput.sandboxPolicy);
1477
+ }
1478
+ if (turnInput.runtimeWorkspaceRoots !== undefined) {
1479
+ params.runtimeWorkspaceRoots = [...turnInput.runtimeWorkspaceRoots];
1480
+ }
1481
+ return params;
1482
+ }
1483
+ function createCodexControlClient(input) {
1484
+ const call = async (method, params) => {
1485
+ input.ensureAlive();
1486
+ return input.peer.request(method, params);
1487
+ };
1488
+ return {
1489
+ readConfig(params) {
1490
+ return call("config/read", {
1491
+ ...params?.cwd !== undefined && { cwd: params.cwd },
1492
+ ...params?.includeLayers !== undefined && { includeLayers: params.includeLayers }
1493
+ });
1494
+ },
1495
+ listMcpServerStatus(params) {
1496
+ return call("mcpServerStatus/list", {
1497
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1498
+ ...params?.limit !== undefined && { limit: params.limit },
1499
+ ...params?.threadId !== undefined && { threadId: params.threadId },
1500
+ ...params?.serverName !== undefined && { serverName: params.serverName },
1501
+ ...params?.detail !== undefined && { detail: params.detail }
1502
+ });
1503
+ },
1504
+ listSkills(params) {
1505
+ return call("skills/list", {
1506
+ ...params?.cwds !== undefined && { cwds: [...params.cwds] },
1507
+ ...params?.forceReload !== undefined && { forceReload: params.forceReload }
1508
+ });
1509
+ },
1510
+ listModels(params) {
1511
+ return call("model/list", {
1512
+ ...params?.cursor !== undefined && { cursor: params.cursor },
1513
+ ...params?.limit !== undefined && { limit: params.limit },
1514
+ ...params?.includeHidden !== undefined && { includeHidden: params.includeHidden },
1515
+ ...params?.modelProvider !== undefined && { modelProvider: params.modelProvider }
1516
+ });
1517
+ },
1518
+ readAccount(params) {
1519
+ return call("account/read", {
1520
+ ...params?.refreshToken !== undefined && { refreshToken: params.refreshToken }
1521
+ });
1522
+ },
1523
+ readRateLimits() {
1524
+ return call("account/rateLimits/read");
1525
+ }
1526
+ };
1527
+ }
1528
+ function createCodexSessionMutators(input) {
1529
+ return {
1530
+ async steerTurn(steerInput) {
1531
+ input.ensureAlive();
1532
+ const active = input.getActiveTurn();
1533
+ const expectedTurnId = active?.codexTurnId;
1534
+ if (active === undefined || expectedTurnId === undefined) {
1535
+ throw new Error("Cannot steer turn: no Codex turn is currently running");
1536
+ }
1537
+ if (steerInput.expectedTurnId !== undefined && steerInput.expectedTurnId !== expectedTurnId) {
1538
+ throw new TypeError(`Expected active Codex turn ${steerInput.expectedTurnId}, but current turn is ${expectedTurnId}`);
1539
+ }
1540
+ const parts = await inlineParts(steerInput.input, {
1541
+ ...input.imageOptions,
1542
+ driverLabel: "The Codex driver",
1543
+ signal: input.signal
1544
+ });
1545
+ input.ensureAlive();
1546
+ const afterAwait = input.getActiveTurn();
1547
+ if (afterAwait !== active || afterAwait.codexTurnId !== expectedTurnId) {
1548
+ throw new Error("Cannot steer turn: the active Codex turn ended before steering was sent");
1549
+ }
1550
+ const steered = CodexTurnSteerResponseSchema.parse(await input.peer.request("turn/steer", {
1551
+ threadId: input.threadId,
1552
+ expectedTurnId,
1553
+ input: codexTurnInput(parts),
1554
+ ...steerInput.clientId !== undefined && {
1555
+ clientUserMessageId: steerInput.clientId
1556
+ }
1557
+ }));
1558
+ return { turnId: steered.turnId };
1559
+ },
1560
+ async forkThread(options = {}) {
1561
+ input.ensureAlive();
1562
+ const policyParams = buildCodexThreadPolicyParams({}, options);
1563
+ const forked = CodexStartedThreadSchema.parse(await input.peer.request("thread/fork", {
1564
+ threadId: input.threadId,
1565
+ ...policyParams,
1566
+ ...options.cwd !== undefined && { cwd: options.cwd },
1567
+ ...options.beforeTurnId !== undefined && { beforeTurnId: options.beforeTurnId },
1568
+ ...options.lastTurnId !== undefined && { lastTurnId: options.lastTurnId },
1569
+ ...options.excludeTurns !== undefined && { excludeTurns: options.excludeTurns }
1570
+ }));
1571
+ return {
1572
+ nativeThreadId: forked.thread.id,
1573
+ threadContext: extractCodexThreadContext(forked)
1574
+ };
1575
+ },
1576
+ async compactThread() {
1577
+ input.ensureAlive();
1578
+ await input.peer.request("thread/compact/start", { threadId: input.threadId });
1579
+ }
1580
+ };
1581
+ }
1582
+
1583
+ // src/agent-executor/codex/session.ts
399
1584
  function approvalDetail(params) {
400
1585
  const asked = CodexApprovalParamsSchema.parse(params);
401
1586
  const callId = nonEmptyString(asked.itemId);
@@ -441,11 +1626,24 @@ function createCodexHandlers(state) {
441
1626
  }
442
1627
  switch (verdict.kind) {
443
1628
  case "limits":
444
- state.limits.set(state.profileId, mergeRateLimitEvent2({
445
- previous: state.limits.get(state.profileId),
446
- windows: codexPlanWindows(verdict.rateLimits),
447
- now: new Date
448
- }));
1629
+ try {
1630
+ state.limits.set(state.profileId, mergeRateLimitEvent2({
1631
+ previous: state.limits.get(state.profileId),
1632
+ windows: codexPlanWindows(verdict.rateLimits),
1633
+ now: new Date
1634
+ }));
1635
+ } catch (error) {
1636
+ if (turn !== undefined) {
1637
+ offerTurnDelta(turn.channel, {
1638
+ type: "error",
1639
+ turnId: turn.state.turnId,
1640
+ itemId: `unhandled:${method}`,
1641
+ raw: { source: "codex", type: method },
1642
+ kind: "unhandled",
1643
+ message: `Codex rate-limit update could not be merged: ${error instanceof Error ? error.message : String(error)}`
1644
+ });
1645
+ }
1646
+ }
449
1647
  return;
450
1648
  case "resolved":
451
1649
  if (turn?.pending.delete(verdict.requestId)) {
@@ -511,11 +1709,75 @@ function createCodexHandlers(state) {
511
1709
  }
512
1710
  };
513
1711
  }
1712
+ function createCodexStartTurn(input) {
1713
+ return imageTurnStarter({
1714
+ driverLabel: "The Codex driver",
1715
+ busyMessage: "A turn is already running in this Codex thread",
1716
+ imageOptions: input.config,
1717
+ signal: input.signal,
1718
+ check(turnInput) {
1719
+ input.ensureAlive();
1720
+ if (input.getTurn() !== undefined)
1721
+ throw new Error("A turn is already running in this Codex thread");
1722
+ validateCodexTurnStartOverrides(turnInput, input.activeModelProvider);
1723
+ },
1724
+ async dispatch(turnInput, parts) {
1725
+ const turnParams = buildCodexTurnStartParams(input.threadId, turnInput, parts, input.activeModelProvider);
1726
+ const turn = {
1727
+ state: { turnId: turnInput.turnId, interruptRequested: false },
1728
+ channel: createTurnDeltaChannel(),
1729
+ pending: new Map
1730
+ };
1731
+ input.setTurn(turn);
1732
+ try {
1733
+ const started = await input.peer.request("turn/start", turnParams);
1734
+ turn.codexTurnId = CodexStartedTurnSchema.parse(started).turn.id;
1735
+ } catch (error) {
1736
+ if (input.getTurn() === turn)
1737
+ input.setTurn(undefined);
1738
+ throw error;
1739
+ }
1740
+ return {
1741
+ deltas: turn.channel,
1742
+ async interrupt() {
1743
+ turn.state.interruptRequested = true;
1744
+ drainEngineRequests(turn, codexStopped);
1745
+ if (turn.codexTurnId !== undefined) {
1746
+ await input.peer.request("turn/interrupt", {
1747
+ threadId: input.threadId,
1748
+ turnId: turn.codexTurnId
1749
+ });
1750
+ }
1751
+ },
1752
+ async respond(interactionId, rawReply) {
1753
+ const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
1754
+ const waiting = turn.pending.get(interactionId);
1755
+ if (waiting === undefined)
1756
+ throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
1757
+ if (CODEX_APPROVAL_REQUESTS.has(waiting.detail.method)) {
1758
+ if (reply.kind === "input")
1759
+ throw new TypeError("A Codex approval is approved or denied, not answered with input");
1760
+ answerEngineRequest(turn, interactionId, {
1761
+ decision: reply.kind === "approve" ? CODEX_APPROVAL_DECISION.approve : CODEX_APPROVAL_DECISION.deny
1762
+ });
1763
+ } else {
1764
+ if (reply.kind !== "input")
1765
+ throw new TypeError("A Codex input request is answered with input");
1766
+ answerEngineRequest(turn, interactionId, {
1767
+ answers: CodexUserInputAnswersSchema.parse(reply.value)
1768
+ });
1769
+ }
1770
+ }
1771
+ };
1772
+ }
1773
+ });
1774
+ }
514
1775
  async function openCodexSession(config, input) {
515
1776
  const profile = engineProfile("codex", input.profile);
516
1777
  const linked = sessionAbort(input.signal);
517
1778
  let current;
518
1779
  let dead;
1780
+ let closing = false;
519
1781
  let connected;
520
1782
  try {
521
1783
  connected = await connectCodex(config, profile, input.cwd, linked.signal, createCodexHandlers({
@@ -536,84 +1798,102 @@ async function openCodexSession(config, input) {
536
1798
  linked.release();
537
1799
  throw error;
538
1800
  }
539
- const { peer } = connected;
1801
+ const { peer, providerPid } = connected;
1802
+ const ensureAlive = () => {
1803
+ if (closing)
1804
+ throw new Error("The Codex session is closed");
1805
+ if (dead !== undefined)
1806
+ throw dead;
1807
+ };
540
1808
  const stop = async (primary) => {
541
- linked.abort();
542
- await stopConnection(connected, primary);
1809
+ closing = true;
1810
+ try {
1811
+ await stopConnection(connected, primary);
1812
+ } finally {
1813
+ linked.abort();
1814
+ linked.release();
1815
+ }
543
1816
  };
1817
+ const controlClient = createCodexControlClient({ peer, ensureAlive });
544
1818
  let threadId;
1819
+ let threadContext;
1820
+ let dynamicOverrides;
545
1821
  try {
1822
+ if (config.prepareThread !== undefined) {
1823
+ dynamicOverrides = await raceAbort(Promise.resolve(config.prepareThread({
1824
+ controls: controlClient,
1825
+ cwd: input.cwd,
1826
+ ...input.nativeThreadId !== undefined && {
1827
+ nativeThreadId: input.nativeThreadId
1828
+ }
1829
+ })), linked.signal);
1830
+ linked.signal.throwIfAborted();
1831
+ }
1832
+ const basePolicy = {
1833
+ ...config.model !== undefined && { model: config.model },
1834
+ ...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
1835
+ ...config.approvalPolicy !== undefined && { approvalPolicy: config.approvalPolicy },
1836
+ ...config.sandbox !== undefined && { sandbox: config.sandbox },
1837
+ ...config.developerInstructions !== undefined && {
1838
+ developerInstructions: config.developerInstructions
1839
+ },
1840
+ ...config.runtimeWorkspaceRoots !== undefined && {
1841
+ runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
1842
+ },
1843
+ ...config.config !== undefined && { config: config.config }
1844
+ };
546
1845
  const threadParams = {
547
1846
  cwd: input.cwd,
548
- approvalPolicy: config.approvalPolicy,
549
- sandbox: config.sandbox,
550
- ...config.model !== undefined && { model: config.model }
1847
+ ...buildCodexThreadPolicyParams(basePolicy, dynamicOverrides)
551
1848
  };
552
1849
  const opened = input.nativeThreadId ? await peer.request("thread/resume", {
553
1850
  threadId: input.nativeThreadId,
554
1851
  excludeTurns: true,
555
1852
  ...threadParams
556
1853
  }) : await peer.request("thread/start", threadParams);
557
- threadId = CodexStartedThreadSchema.parse(opened).thread.id;
1854
+ const parsed = CodexStartedThreadSchema.parse(opened);
1855
+ threadId = parsed.thread.id;
1856
+ threadContext = extractCodexThreadContext(parsed);
1857
+ if (config.verifyThread !== undefined) {
1858
+ await raceAbort(Promise.resolve(config.verifyThread({
1859
+ nativeThreadId: threadId,
1860
+ threadContext,
1861
+ controls: controlClient
1862
+ })), linked.signal);
1863
+ linked.signal.throwIfAborted();
1864
+ }
558
1865
  } catch (error) {
559
1866
  await stop({ error });
560
1867
  throw error;
561
1868
  }
1869
+ const activeModelProvider = threadContext.modelProvider ?? dynamicOverrides?.modelProvider ?? config.modelProvider;
1870
+ const startTurn = createCodexStartTurn({
1871
+ config,
1872
+ peer,
1873
+ threadId,
1874
+ activeModelProvider,
1875
+ signal: linked.signal,
1876
+ ensureAlive,
1877
+ getTurn: () => current,
1878
+ setTurn: (turn) => {
1879
+ current = turn;
1880
+ }
1881
+ });
1882
+ const mutators = createCodexSessionMutators({
1883
+ peer,
1884
+ threadId,
1885
+ imageOptions: config,
1886
+ signal: linked.signal,
1887
+ ensureAlive,
1888
+ getActiveTurn: () => current
1889
+ });
562
1890
  return {
563
1891
  nativeThreadId: threadId,
564
- async startTurn(turnInput) {
565
- if (dead !== undefined)
566
- throw dead;
567
- if (current !== undefined)
568
- throw new Error("A turn is already running in this Codex thread");
569
- const text = extractTextOnlyInput(turnInput.input, "The Codex driver");
570
- const turn = {
571
- state: { turnId: turnInput.turnId, interruptRequested: false },
572
- channel: createTurnDeltaChannel(),
573
- pending: new Map
574
- };
575
- current = turn;
576
- try {
577
- const started = await peer.request("turn/start", {
578
- threadId,
579
- input: [{ type: "text", text, text_elements: [] }],
580
- clientUserMessageId: turnInput.clientId
581
- });
582
- turn.codexTurnId = CodexStartedTurnSchema.parse(started).turn.id;
583
- } catch (error) {
584
- if (current === turn)
585
- current = undefined;
586
- throw error;
587
- }
588
- return {
589
- deltas: turn.channel,
590
- async interrupt() {
591
- turn.state.interruptRequested = true;
592
- drainEngineRequests(turn, codexStopped);
593
- if (turn.codexTurnId !== undefined)
594
- await peer.request("turn/interrupt", { threadId, turnId: turn.codexTurnId });
595
- },
596
- async respond(interactionId, rawReply) {
597
- const reply = InteractionReplySchema2.shape.reply.parse(rawReply);
598
- const waiting = turn.pending.get(interactionId);
599
- if (waiting === undefined)
600
- throw new TypeError(`Unknown interaction ${interactionId} for this turn`);
601
- if (CODEX_APPROVAL_REQUESTS.has(waiting.detail.method)) {
602
- if (reply.kind === "input")
603
- throw new TypeError("A Codex approval is approved or denied, not answered with input");
604
- answerEngineRequest(turn, interactionId, {
605
- decision: reply.kind === "approve" ? CODEX_APPROVAL_DECISION.approve : CODEX_APPROVAL_DECISION.deny
606
- });
607
- } else {
608
- if (reply.kind !== "input")
609
- throw new TypeError("A Codex input request is answered with input");
610
- answerEngineRequest(turn, interactionId, {
611
- answers: CodexUserInputAnswersSchema.parse(reply.value)
612
- });
613
- }
614
- }
615
- };
616
- },
1892
+ providerPid,
1893
+ threadContext,
1894
+ startTurn,
1895
+ ...controlClient,
1896
+ ...mutators,
617
1897
  async close() {
618
1898
  await stop();
619
1899
  }
@@ -621,24 +1901,50 @@ async function openCodexSession(config, input) {
621
1901
  }
622
1902
 
623
1903
  // src/agent-executor/codex/driver.ts
1904
+ var MAX_HISTORY_PAGES = 256;
1905
+ var FIND_INPUT_MAX_LINE_BYTES = 64 * 1024 * 1024;
624
1906
  function createCodexDriver(config = {}) {
1907
+ validateImageOptions(config);
1908
+ validateCodexTransportAndArgs(config);
1909
+ validateCodexPolicyOverrides(config, "createCodexDriver");
625
1910
  const executable = config.executable ?? "codex";
626
1911
  const prefix = config.prefixArgs ?? [];
627
1912
  const ambient = config.ambient ?? process.env;
628
1913
  const limits = new Map;
629
1914
  let version = "unknown";
630
- const session = () => ({
631
- executable,
632
- prefix,
633
- ...config.model !== undefined && { model: config.model },
634
- approvalPolicy: config.approvalPolicy ?? "on-request",
635
- sandbox: config.sandbox ?? "workspace-write",
636
- ambient,
637
- limits,
638
- version
639
- });
1915
+ const session = (options) => {
1916
+ const transport = options?.forceStdioForListen && config.transport?.kind === "unix-listen" ? { kind: "stdio" } : config.transport;
1917
+ return {
1918
+ executable,
1919
+ prefix,
1920
+ ...transport !== undefined && { transport },
1921
+ ...config.serverArgs !== undefined && { serverArgs: config.serverArgs },
1922
+ ...config.model !== undefined && { model: config.model },
1923
+ ...config.modelProvider !== undefined && { modelProvider: config.modelProvider },
1924
+ approvalPolicy: config.approvalPolicy ?? "on-request",
1925
+ sandbox: config.sandbox ?? "workspace-write",
1926
+ ...config.developerInstructions !== undefined && {
1927
+ developerInstructions: config.developerInstructions
1928
+ },
1929
+ ...config.runtimeWorkspaceRoots !== undefined && {
1930
+ runtimeWorkspaceRoots: config.runtimeWorkspaceRoots
1931
+ },
1932
+ ...config.config !== undefined && { config: config.config },
1933
+ ...config.prepareThread !== undefined && { prepareThread: config.prepareThread },
1934
+ ...config.verifyThread !== undefined && { verifyThread: config.verifyThread },
1935
+ ambient,
1936
+ limits,
1937
+ version,
1938
+ ...config.resolveFile !== undefined && { resolveFile: config.resolveFile },
1939
+ ...config.maxImageBytes !== undefined && { maxImageBytes: config.maxImageBytes },
1940
+ ...options?.maxLineBytes !== undefined && { maxLineBytes: options.maxLineBytes }
1941
+ };
1942
+ };
640
1943
  const cli = (profile, args) => runEngineCli({ executable, prefix, args, profile, ambient });
641
- const ask = (profile, cwd, question) => withEphemeralConnection((signal) => connectCodex(session(), engineProfile("codex", profile), cwd, signal), (connection) => question(connection.peer));
1944
+ const ask = (profile, cwd, question, maxLineBytes) => withEphemeralConnection((signal) => connectCodex(session({
1945
+ ...maxLineBytes !== undefined && { maxLineBytes },
1946
+ forceStdioForListen: true
1947
+ }), engineProfile("codex", profile), cwd, signal), (connection) => question(connection.peer));
642
1948
  return {
643
1949
  engine: "codex",
644
1950
  reconcile: "client-id",
@@ -670,7 +1976,7 @@ ${decoder.decode(loginResult.stderr)}`.trim();
670
1976
  if (credential === "subscription") {
671
1977
  try {
672
1978
  const answer = await ask(parsed, process.cwd(), (peer) => peer.request("account/rateLimits/read"));
673
- const windows = codexPlanWindows(Reflect.get(Object(answer), "rateLimits"));
1979
+ const windows = codexPlanWindows(answer);
674
1980
  planLimits = mergeRateLimitEvent2({ previous: planLimits, windows, now: new Date });
675
1981
  limits.set(parsed.profileId, planLimits);
676
1982
  } catch (error) {
@@ -695,13 +2001,29 @@ ${decoder.decode(loginResult.stderr)}`.trim();
695
2001
  },
696
2002
  async findInput(input) {
697
2003
  return ask(input.profile, input.cwd, async (peer) => {
698
- const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
699
- threadId: input.nativeThreadId,
700
- limit: 50,
701
- itemsView: "full"
702
- }));
703
- return page.data.some((turn) => (turn.items ?? []).some((item) => item.clientId === input.clientId));
704
- });
2004
+ const seen = new Set;
2005
+ let cursor;
2006
+ for (let pageNumber = 0;pageNumber < MAX_HISTORY_PAGES; pageNumber += 1) {
2007
+ const page = CodexTurnsPageSchema.parse(await peer.request("thread/turns/list", {
2008
+ threadId: input.nativeThreadId,
2009
+ limit: 50,
2010
+ itemsView: "full",
2011
+ ...cursor !== undefined && { cursor }
2012
+ }));
2013
+ if (page.data.some((turn) => turn.items.some((item) => item.type === "userMessage" && item.clientId === input.clientId))) {
2014
+ return true;
2015
+ }
2016
+ const next = page.nextCursor;
2017
+ if (next === null || next === undefined)
2018
+ return false;
2019
+ if (seen.has(next)) {
2020
+ throw new Error(`Codex thread/turns/list repeated cursor ${JSON.stringify(next)} before history ended`);
2021
+ }
2022
+ seen.add(next);
2023
+ cursor = next;
2024
+ }
2025
+ throw new Error(`Codex thread/turns/list exceeded ${MAX_HISTORY_PAGES} pages without reaching the end of history`);
2026
+ }, FIND_INPUT_MAX_LINE_BYTES);
705
2027
  },
706
2028
  open: (input) => openCodexSession(session(), input)
707
2029
  };
@@ -792,6 +2114,7 @@ var codexFakeScenarios = {
792
2114
  crash: () => steps(text("dying "), { do: "crash" })
793
2115
  };
794
2116
  export {
2117
+ CodexUnixSocketError,
795
2118
  codexFakeScenarios,
796
2119
  codexPlanWindows,
797
2120
  createCodexDriver