@asterxsk/kiln 0.3.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (522) hide show
  1. package/README.md +155 -155
  2. package/agent/AGENTS.md +67 -67
  3. package/agent/README.md +5 -5
  4. package/agent/extensions/ask-user/index.ts +418 -418
  5. package/agent/extensions/ask-user/install.ps1 +27 -27
  6. package/agent/extensions/ask-user/install.sh +24 -24
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/install.ps1 +27 -27
  14. package/agent/extensions/background-terminals/install.sh +24 -24
  15. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  16. package/agent/extensions/background-terminals/output.test.ts +109 -109
  17. package/agent/extensions/background-terminals/package-lock.json +769 -769
  18. package/agent/extensions/background-terminals/package.json +17 -17
  19. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  20. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  21. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  22. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  23. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  24. package/agent/extensions/background-terminals/src/output.ts +84 -84
  25. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  26. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  27. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  28. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  29. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  30. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  31. package/agent/extensions/destructive/README.md +31 -31
  32. package/agent/extensions/destructive/index.ts +88 -88
  33. package/agent/extensions/destructive/install.ps1 +27 -27
  34. package/agent/extensions/destructive/install.sh +24 -24
  35. package/agent/extensions/file-search/index.spec.ts +443 -443
  36. package/agent/extensions/file-search/index.ts +459 -459
  37. package/agent/extensions/file-search/install.ps1 +27 -27
  38. package/agent/extensions/file-search/install.sh +24 -24
  39. package/agent/extensions/file-search/package-lock.json +2253 -2253
  40. package/agent/extensions/file-search/package.json +23 -23
  41. package/agent/extensions/file-search/src/args.ts +122 -122
  42. package/agent/extensions/file-search/src/binaries.ts +422 -422
  43. package/agent/extensions/file-search/src/output.ts +126 -126
  44. package/agent/extensions/file-search/src/process.ts +146 -146
  45. package/agent/extensions/file-search/src/prompt.ts +52 -52
  46. package/agent/extensions/file-search/tsconfig.json +7 -7
  47. package/agent/extensions/goal/README.md +50 -50
  48. package/agent/extensions/goal/index.ts +155 -155
  49. package/agent/extensions/goal/install.ps1 +27 -27
  50. package/agent/extensions/goal/install.sh +24 -24
  51. package/agent/extensions/kiln-update/README.md +38 -25
  52. package/agent/extensions/kiln-update/index.ts +177 -99
  53. package/agent/extensions/modelconf/PLAN.md +915 -915
  54. package/agent/extensions/modelconf/README.md +66 -66
  55. package/agent/extensions/modelconf/index.ts +296 -296
  56. package/agent/extensions/modelconf/install.ps1 +27 -27
  57. package/agent/extensions/modelconf/install.sh +24 -24
  58. package/agent/extensions/modelconf/package-lock.json +1809 -1809
  59. package/agent/extensions/modelconf/package.json +13 -13
  60. package/agent/extensions/modelconf/src/fuzzy.ts +26 -26
  61. package/agent/extensions/modelconf/src/glob.ts +13 -13
  62. package/agent/extensions/modelconf/src/persistence.test.ts +46 -46
  63. package/agent/extensions/modelconf/src/persistence.ts +164 -164
  64. package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -75
  65. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  66. package/agent/extensions/modelconf/tsconfig.json +15 -15
  67. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  68. package/agent/extensions/pi-web-access/LICENSE +21 -21
  69. package/agent/extensions/pi-web-access/README.md +470 -470
  70. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  71. package/agent/extensions/pi-web-access/activity.ts +101 -101
  72. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  73. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  74. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  75. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  76. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  77. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  78. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  79. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  80. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  81. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  82. package/agent/extensions/pi-web-access/exa.ts +526 -526
  83. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  84. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  85. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  86. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  87. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  88. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  89. package/agent/extensions/pi-web-access/gemini-search.ts +21 -21
  90. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  91. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  92. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  93. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  94. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  95. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  96. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  97. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  98. package/agent/extensions/pi-web-access/package.json +64 -64
  99. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  100. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  101. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  102. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  103. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  104. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  105. package/agent/extensions/pi-web-access/search-types.ts +20 -20
  106. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  107. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  108. package/agent/extensions/pi-web-access/storage.ts +521 -521
  109. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  110. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  111. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  112. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  113. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  114. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  115. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  116. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  117. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  118. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  119. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  120. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  121. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  122. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  123. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  124. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  125. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  126. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  127. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  128. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  129. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  130. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  131. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  132. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  133. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  134. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  135. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  136. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  137. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  138. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  139. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  140. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  141. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  142. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  143. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  144. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  145. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  146. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  147. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  148. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  149. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  150. package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -106
  151. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  152. package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -66
  153. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  154. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  155. package/agent/extensions/pi-web-access/utils.ts +451 -451
  156. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  157. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  158. package/agent/extensions/shared/activity-status.ts +31 -31
  159. package/agent/extensions/shared/child-session.test.ts +270 -270
  160. package/agent/extensions/shared/child-session.ts +148 -148
  161. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  162. package/agent/extensions/shared/context-utilization.ts +47 -47
  163. package/agent/extensions/shared/dashboard-state.ts +99 -99
  164. package/agent/extensions/shared/install.ps1 +27 -27
  165. package/agent/extensions/shared/install.sh +24 -24
  166. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  167. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  168. package/agent/extensions/skillsconf/README.md +74 -74
  169. package/agent/extensions/skillsconf/index.ts +92 -92
  170. package/agent/extensions/skillsconf/install.ps1 +27 -27
  171. package/agent/extensions/skillsconf/install.sh +24 -24
  172. package/agent/extensions/skillsconf/package-lock.json +1809 -1809
  173. package/agent/extensions/skillsconf/package.json +18 -18
  174. package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -64
  175. package/agent/extensions/skillsconf/src/delete-skill.ts +45 -45
  176. package/agent/extensions/skillsconf/src/filter.test.ts +80 -80
  177. package/agent/extensions/skillsconf/src/filter.ts +74 -74
  178. package/agent/extensions/skillsconf/src/fuzzy.ts +26 -26
  179. package/agent/extensions/skillsconf/src/persistence.test.ts +72 -72
  180. package/agent/extensions/skillsconf/src/persistence.ts +169 -169
  181. package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -337
  182. package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -758
  183. package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -91
  184. package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -144
  185. package/agent/extensions/skillsconf/tsconfig.json +15 -15
  186. package/agent/extensions/statusline/index.ts +273 -282
  187. package/agent/extensions/statusline/install.ps1 +27 -27
  188. package/agent/extensions/statusline/install.sh +24 -24
  189. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  190. package/agent/extensions/subagents/claude.test.ts +119 -119
  191. package/agent/extensions/subagents/codex.test.ts +102 -102
  192. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  193. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  194. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  195. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  196. package/agent/extensions/subagents/index.ts +779 -779
  197. package/agent/extensions/subagents/install.ps1 +27 -27
  198. package/agent/extensions/subagents/install.sh +24 -24
  199. package/agent/extensions/subagents/manager.test.ts +276 -276
  200. package/agent/extensions/subagents/package-lock.json +2244 -2244
  201. package/agent/extensions/subagents/package.json +19 -19
  202. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  203. package/agent/extensions/subagents/src/backend.ts +73 -73
  204. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  205. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  206. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  207. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  208. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  209. package/agent/extensions/subagents/src/domain.ts +253 -253
  210. package/agent/extensions/subagents/src/format.ts +74 -74
  211. package/agent/extensions/subagents/src/manager.ts +736 -736
  212. package/agent/extensions/subagents/src/prompt.ts +92 -92
  213. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  214. package/agent/extensions/subagents/src/runtime.ts +53 -53
  215. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  216. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  217. package/agent/extensions/subagents/takeover.test.ts +29 -29
  218. package/agent/extensions/subagents/tsconfig.json +7 -7
  219. package/agent/extensions/todo/AGENTS.md +38 -38
  220. package/agent/extensions/todo/LICENSE +21 -21
  221. package/agent/extensions/todo/config.ts +55 -55
  222. package/agent/extensions/todo/index.ts +151 -151
  223. package/agent/extensions/todo/install.ps1 +27 -27
  224. package/agent/extensions/todo/install.sh +24 -24
  225. package/agent/extensions/todo/locales/de.json +17 -17
  226. package/agent/extensions/todo/locales/en.json +15 -15
  227. package/agent/extensions/todo/locales/es.json +17 -17
  228. package/agent/extensions/todo/locales/fr.json +17 -17
  229. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  230. package/agent/extensions/todo/locales/pt.json +17 -17
  231. package/agent/extensions/todo/locales/ru.json +17 -17
  232. package/agent/extensions/todo/locales/uk.json +17 -17
  233. package/agent/extensions/todo/locales/zh.json +17 -17
  234. package/agent/extensions/todo/package-lock.json +3358 -3358
  235. package/agent/extensions/todo/package.json +67 -67
  236. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  237. package/agent/extensions/todo/state/invariants.ts +20 -20
  238. package/agent/extensions/todo/state/replay.ts +38 -38
  239. package/agent/extensions/todo/state/selectors.ts +107 -107
  240. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  241. package/agent/extensions/todo/state/state.ts +18 -18
  242. package/agent/extensions/todo/state/store.ts +82 -82
  243. package/agent/extensions/todo/state/task-graph.ts +57 -57
  244. package/agent/extensions/todo/todo-overlay.ts +200 -200
  245. package/agent/extensions/todo/todo.ts +155 -155
  246. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  247. package/agent/extensions/todo/tool/types.ts +206 -206
  248. package/agent/extensions/todo/view/format.ts +177 -177
  249. package/agent/extensions/trim-context/README.md +54 -54
  250. package/agent/extensions/trim-context/index.ts +487 -487
  251. package/agent/extensions/trim-context/install.ps1 +27 -27
  252. package/agent/extensions/trim-context/install.sh +24 -24
  253. package/agent/keybindings.json +7 -7
  254. package/agent/version.txt +1 -1
  255. package/bin/kiln.js +30 -21
  256. package/package.json +1 -1
  257. package/agent/extensions/taste/index.ts +0 -443
  258. package/agent/extensions/taste/install.ps1 +0 -27
  259. package/agent/extensions/taste/install.sh +0 -24
  260. package/agent.bak.20260905-190020/AGENTS.md +0 -67
  261. package/agent.bak.20260905-190020/README.md +0 -5
  262. package/agent.bak.20260905-190020/extensions/ask-user/index.ts +0 -418
  263. package/agent.bak.20260905-190020/extensions/ask-user/install.ps1 +0 -23
  264. package/agent.bak.20260905-190020/extensions/ask-user/install.sh +0 -21
  265. package/agent.bak.20260905-190020/extensions/ask-user/package-lock.json +0 -769
  266. package/agent.bak.20260905-190020/extensions/ask-user/package.json +0 -19
  267. package/agent.bak.20260905-190020/extensions/ask-user/prompt.ts +0 -45
  268. package/agent.bak.20260905-190020/extensions/ask-user/tsconfig.json +0 -7
  269. package/agent.bak.20260905-190020/extensions/background-terminals/docs/implementation-guide.md +0 -942
  270. package/agent.bak.20260905-190020/extensions/background-terminals/index.ts +0 -629
  271. package/agent.bak.20260905-190020/extensions/background-terminals/install.ps1 +0 -23
  272. package/agent.bak.20260905-190020/extensions/background-terminals/install.sh +0 -21
  273. package/agent.bak.20260905-190020/extensions/background-terminals/package-lock.json +0 -769
  274. package/agent.bak.20260905-190020/extensions/background-terminals/package.json +0 -17
  275. package/agent.bak.20260905-190020/extensions/background-terminals/src/domain.ts +0 -87
  276. package/agent.bak.20260905-190020/extensions/background-terminals/src/manager.ts +0 -907
  277. package/agent.bak.20260905-190020/extensions/background-terminals/src/output.ts +0 -84
  278. package/agent.bak.20260905-190020/extensions/background-terminals/src/prompt.ts +0 -142
  279. package/agent.bak.20260905-190020/extensions/background-terminals/src/result-delivery.ts +0 -27
  280. package/agent.bak.20260905-190020/extensions/background-terminals/src/runtime.ts +0 -36
  281. package/agent.bak.20260905-190020/extensions/background-terminals/src/ui/output-view.ts +0 -79
  282. package/agent.bak.20260905-190020/extensions/background-terminals/src/ui/ps.ts +0 -621
  283. package/agent.bak.20260905-190020/extensions/background-terminals/src/widget-order.ts +0 -121
  284. package/agent.bak.20260905-190020/extensions/background-terminals/test/manager.test.ts +0 -735
  285. package/agent.bak.20260905-190020/extensions/background-terminals/test/output.test.ts +0 -109
  286. package/agent.bak.20260905-190020/extensions/background-terminals/test/prompt.test.ts +0 -125
  287. package/agent.bak.20260905-190020/extensions/background-terminals/test/ps.test.ts +0 -82
  288. package/agent.bak.20260905-190020/extensions/background-terminals/test/result-delivery.test.ts +0 -44
  289. package/agent.bak.20260905-190020/extensions/background-terminals/tsconfig.json +0 -7
  290. package/agent.bak.20260905-190020/extensions/destructive/README.md +0 -34
  291. package/agent.bak.20260905-190020/extensions/destructive/index.ts +0 -124
  292. package/agent.bak.20260905-190020/extensions/destructive/install.ps1 +0 -23
  293. package/agent.bak.20260905-190020/extensions/destructive/install.sh +0 -21
  294. package/agent.bak.20260905-190020/extensions/file-search/index.ts +0 -459
  295. package/agent.bak.20260905-190020/extensions/file-search/install.ps1 +0 -23
  296. package/agent.bak.20260905-190020/extensions/file-search/install.sh +0 -21
  297. package/agent.bak.20260905-190020/extensions/file-search/package-lock.json +0 -2253
  298. package/agent.bak.20260905-190020/extensions/file-search/package.json +0 -23
  299. package/agent.bak.20260905-190020/extensions/file-search/src/args.ts +0 -122
  300. package/agent.bak.20260905-190020/extensions/file-search/src/binaries.ts +0 -422
  301. package/agent.bak.20260905-190020/extensions/file-search/src/output.ts +0 -126
  302. package/agent.bak.20260905-190020/extensions/file-search/src/process.ts +0 -146
  303. package/agent.bak.20260905-190020/extensions/file-search/src/prompt.ts +0 -52
  304. package/agent.bak.20260905-190020/extensions/file-search/test/index.spec.ts +0 -443
  305. package/agent.bak.20260905-190020/extensions/file-search/tsconfig.json +0 -7
  306. package/agent.bak.20260905-190020/extensions/goal/README.md +0 -50
  307. package/agent.bak.20260905-190020/extensions/goal/index.ts +0 -155
  308. package/agent.bak.20260905-190020/extensions/goal/install.ps1 +0 -23
  309. package/agent.bak.20260905-190020/extensions/goal/install.sh +0 -21
  310. package/agent.bak.20260905-190020/extensions/kiln-update/README.md +0 -25
  311. package/agent.bak.20260905-190020/extensions/kiln-update/index.ts +0 -99
  312. package/agent.bak.20260905-190020/extensions/kiln-update/install.ps1 +0 -23
  313. package/agent.bak.20260905-190020/extensions/kiln-update/install.sh +0 -21
  314. package/agent.bak.20260905-190020/extensions/modelconf/PLAN.md +0 -915
  315. package/agent.bak.20260905-190020/extensions/modelconf/README.md +0 -66
  316. package/agent.bak.20260905-190020/extensions/modelconf/index.ts +0 -296
  317. package/agent.bak.20260905-190020/extensions/modelconf/install.ps1 +0 -23
  318. package/agent.bak.20260905-190020/extensions/modelconf/install.sh +0 -21
  319. package/agent.bak.20260905-190020/extensions/modelconf/package-lock.json +0 -1809
  320. package/agent.bak.20260905-190020/extensions/modelconf/package.json +0 -13
  321. package/agent.bak.20260905-190020/extensions/modelconf/src/fuzzy.ts +0 -26
  322. package/agent.bak.20260905-190020/extensions/modelconf/src/glob.ts +0 -13
  323. package/agent.bak.20260905-190020/extensions/modelconf/src/persistence.test.ts +0 -46
  324. package/agent.bak.20260905-190020/extensions/modelconf/src/persistence.ts +0 -164
  325. package/agent.bak.20260905-190020/extensions/modelconf/src/ui/ModelConfView.test.ts +0 -75
  326. package/agent.bak.20260905-190020/extensions/modelconf/src/ui/ModelConfView.ts +0 -1101
  327. package/agent.bak.20260905-190020/extensions/modelconf/tsconfig.json +0 -15
  328. package/agent.bak.20260905-190020/extensions/pi-web-access/CHANGELOG.md +0 -690
  329. package/agent.bak.20260905-190020/extensions/pi-web-access/LICENSE +0 -21
  330. package/agent.bak.20260905-190020/extensions/pi-web-access/README.md +0 -470
  331. package/agent.bak.20260905-190020/extensions/pi-web-access/SECURITY.md +0 -5
  332. package/agent.bak.20260905-190020/extensions/pi-web-access/activity.ts +0 -101
  333. package/agent.bak.20260905-190020/extensions/pi-web-access/auth-fetch.ts +0 -148
  334. package/agent.bak.20260905-190020/extensions/pi-web-access/banner.png +0 -0
  335. package/agent.bak.20260905-190020/extensions/pi-web-access/brightdata-unlocker.ts +0 -272
  336. package/agent.bak.20260905-190020/extensions/pi-web-access/chrome-cookies.ts +0 -669
  337. package/agent.bak.20260905-190020/extensions/pi-web-access/content-find.ts +0 -139
  338. package/agent.bak.20260905-190020/extensions/pi-web-access/credential-source.ts +0 -191
  339. package/agent.bak.20260905-190020/extensions/pi-web-access/data-uri-sanitize.ts +0 -406
  340. package/agent.bak.20260905-190020/extensions/pi-web-access/datalab-pdf-extract.ts +0 -568
  341. package/agent.bak.20260905-190020/extensions/pi-web-access/declared-web-links.ts +0 -173
  342. package/agent.bak.20260905-190020/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +0 -496
  343. package/agent.bak.20260905-190020/extensions/pi-web-access/evidence/contract-probe.mjs +0 -140
  344. package/agent.bak.20260905-190020/extensions/pi-web-access/exa.ts +0 -526
  345. package/agent.bak.20260905-190020/extensions/pi-web-access/extract.ts +0 -1196
  346. package/agent.bak.20260905-190020/extensions/pi-web-access/feature-config.ts +0 -29
  347. package/agent.bak.20260905-190020/extensions/pi-web-access/fetch-params.ts +0 -111
  348. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-adc.ts +0 -298
  349. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-api.ts +0 -353
  350. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-pdf-extract.ts +0 -108
  351. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-search.ts +0 -21
  352. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-url-context.ts +0 -128
  353. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-web-config.ts +0 -101
  354. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-web.ts +0 -487
  355. package/agent.bak.20260905-190020/extensions/pi-web-access/github-api.ts +0 -197
  356. package/agent.bak.20260905-190020/extensions/pi-web-access/github-extract.ts +0 -746
  357. package/agent.bak.20260905-190020/extensions/pi-web-access/github-issue-pr.ts +0 -700
  358. package/agent.bak.20260905-190020/extensions/pi-web-access/index.ts +0 -1737
  359. package/agent.bak.20260905-190020/extensions/pi-web-access/package-lock.json +0 -5808
  360. package/agent.bak.20260905-190020/extensions/pi-web-access/package.json +0 -64
  361. package/agent.bak.20260905-190020/extensions/pi-web-access/page-query.ts +0 -96
  362. package/agent.bak.20260905-190020/extensions/pi-web-access/pdf-extract.ts +0 -409
  363. package/agent.bak.20260905-190020/extensions/pi-web-access/pi-web-fetch-demo.mp4 +0 -0
  364. package/agent.bak.20260905-190020/extensions/pi-web-access/promise-try.d.ts +0 -7
  365. package/agent.bak.20260905-190020/extensions/pi-web-access/query-rewrite.ts +0 -51
  366. package/agent.bak.20260905-190020/extensions/pi-web-access/render-search-error.ts +0 -170
  367. package/agent.bak.20260905-190020/extensions/pi-web-access/rsc-extract.ts +0 -338
  368. package/agent.bak.20260905-190020/extensions/pi-web-access/search-types.ts +0 -20
  369. package/agent.bak.20260905-190020/extensions/pi-web-access/source-check.ts +0 -282
  370. package/agent.bak.20260905-190020/extensions/pi-web-access/ssrf-protection.ts +0 -526
  371. package/agent.bak.20260905-190020/extensions/pi-web-access/storage.ts +0 -521
  372. package/agent.bak.20260905-190020/extensions/pi-web-access/summary-model-scope.ts +0 -125
  373. package/agent.bak.20260905-190020/extensions/pi-web-access/test/auth-fetch.test.mjs +0 -208
  374. package/agent.bak.20260905-190020/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +0 -840
  375. package/agent.bak.20260905-190020/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +0 -441
  376. package/agent.bak.20260905-190020/extensions/pi-web-access/test/config-path.test.mjs +0 -283
  377. package/agent.bak.20260905-190020/extensions/pi-web-access/test/content-find.test.mjs +0 -25
  378. package/agent.bak.20260905-190020/extensions/pi-web-access/test/credential-source.test.mjs +0 -118
  379. package/agent.bak.20260905-190020/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +0 -210
  380. package/agent.bak.20260905-190020/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +0 -552
  381. package/agent.bak.20260905-190020/extensions/pi-web-access/test/declared-web-links.test.mjs +0 -212
  382. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +0 -40
  383. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +0 -334
  384. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +0 -95
  385. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-modes.test.mjs +0 -53
  386. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +0 -92
  387. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-params.test.mjs +0 -86
  388. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-render-call.test.mjs +0 -34
  389. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-routing.test.mjs +0 -173
  390. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +0 -257
  391. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-api-transport.test.mjs +0 -170
  392. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +0 -133
  393. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +0 -178
  394. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +0 -148
  395. package/agent.bak.20260905-190020/extensions/pi-web-access/test/get-search-content.test.mjs +0 -223
  396. package/agent.bak.20260905-190020/extensions/pi-web-access/test/github-extract.test.mjs +0 -378
  397. package/agent.bak.20260905-190020/extensions/pi-web-access/test/github-issue-pr.test.mjs +0 -565
  398. package/agent.bak.20260905-190020/extensions/pi-web-access/test/inline-content-config.test.mjs +0 -99
  399. package/agent.bak.20260905-190020/extensions/pi-web-access/test/lazy-extract-load.test.mjs +0 -118
  400. package/agent.bak.20260905-190020/extensions/pi-web-access/test/local-video-oversize.test.mjs +0 -52
  401. package/agent.bak.20260905-190020/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +0 -50
  402. package/agent.bak.20260905-190020/extensions/pi-web-access/test/page-query.test.mjs +0 -51
  403. package/agent.bak.20260905-190020/extensions/pi-web-access/test/pdf-config.test.mjs +0 -140
  404. package/agent.bak.20260905-190020/extensions/pi-web-access/test/pdf-extract.test.mjs +0 -500
  405. package/agent.bak.20260905-190020/extensions/pi-web-access/test/proxy-transport.test.mjs +0 -286
  406. package/agent.bak.20260905-190020/extensions/pi-web-access/test/query-rewrite.test.mjs +0 -52
  407. package/agent.bak.20260905-190020/extensions/pi-web-access/test/rsc-fallback.test.mjs +0 -102
  408. package/agent.bak.20260905-190020/extensions/pi-web-access/test/search-error-render.test.mjs +0 -152
  409. package/agent.bak.20260905-190020/extensions/pi-web-access/test/search-providers.test.mjs +0 -274
  410. package/agent.bak.20260905-190020/extensions/pi-web-access/test/source-check.test.mjs +0 -179
  411. package/agent.bak.20260905-190020/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +0 -205
  412. package/agent.bak.20260905-190020/extensions/pi-web-access/test/ssrf-protection.test.mjs +0 -456
  413. package/agent.bak.20260905-190020/extensions/pi-web-access/test/summary-model-scope.test.mjs +0 -106
  414. package/agent.bak.20260905-190020/extensions/pi-web-access/test/tool-registration-config.test.mjs +0 -182
  415. package/agent.bak.20260905-190020/extensions/pi-web-access/test/web-search-answer-render.test.mjs +0 -66
  416. package/agent.bak.20260905-190020/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +0 -64
  417. package/agent.bak.20260905-190020/extensions/pi-web-access/tsconfig.json +0 -11
  418. package/agent.bak.20260905-190020/extensions/pi-web-access/utils.ts +0 -451
  419. package/agent.bak.20260905-190020/extensions/pi-web-access/video-extract.ts +0 -392
  420. package/agent.bak.20260905-190020/extensions/pi-web-access/youtube-extract.ts +0 -328
  421. package/agent.bak.20260905-190020/extensions/shared/activity-status.ts +0 -31
  422. package/agent.bak.20260905-190020/extensions/shared/child-session.ts +0 -148
  423. package/agent.bak.20260905-190020/extensions/shared/context-utilization.ts +0 -47
  424. package/agent.bak.20260905-190020/extensions/shared/dashboard-state.ts +0 -99
  425. package/agent.bak.20260905-190020/extensions/shared/install.ps1 +0 -23
  426. package/agent.bak.20260905-190020/extensions/shared/install.sh +0 -21
  427. package/agent.bak.20260905-190020/extensions/shared/test/child-session.test.ts +0 -270
  428. package/agent.bak.20260905-190020/extensions/shared/test/context-utilization.test.ts +0 -48
  429. package/agent.bak.20260905-190020/extensions/shared/test/tool-call-timeout.test.ts +0 -117
  430. package/agent.bak.20260905-190020/extensions/shared/test/widget-order.test.ts +0 -167
  431. package/agent.bak.20260905-190020/extensions/shared/tool-call-timeout.ts +0 -104
  432. package/agent.bak.20260905-190020/extensions/skillsconf/README.md +0 -74
  433. package/agent.bak.20260905-190020/extensions/skillsconf/index.ts +0 -92
  434. package/agent.bak.20260905-190020/extensions/skillsconf/install.ps1 +0 -23
  435. package/agent.bak.20260905-190020/extensions/skillsconf/install.sh +0 -21
  436. package/agent.bak.20260905-190020/extensions/skillsconf/package-lock.json +0 -1809
  437. package/agent.bak.20260905-190020/extensions/skillsconf/package.json +0 -18
  438. package/agent.bak.20260905-190020/extensions/skillsconf/src/delete-skill.test.ts +0 -64
  439. package/agent.bak.20260905-190020/extensions/skillsconf/src/delete-skill.ts +0 -45
  440. package/agent.bak.20260905-190020/extensions/skillsconf/src/filter.test.ts +0 -80
  441. package/agent.bak.20260905-190020/extensions/skillsconf/src/filter.ts +0 -74
  442. package/agent.bak.20260905-190020/extensions/skillsconf/src/fuzzy.ts +0 -26
  443. package/agent.bak.20260905-190020/extensions/skillsconf/src/persistence.test.ts +0 -72
  444. package/agent.bak.20260905-190020/extensions/skillsconf/src/persistence.ts +0 -169
  445. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/SkillConfView.test.ts +0 -337
  446. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/SkillConfView.ts +0 -758
  447. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/text-input.ts +0 -91
  448. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/tui-helpers.ts +0 -144
  449. package/agent.bak.20260905-190020/extensions/skillsconf/tsconfig.json +0 -15
  450. package/agent.bak.20260905-190020/extensions/statusline/index.ts +0 -282
  451. package/agent.bak.20260905-190020/extensions/statusline/install.ps1 +0 -23
  452. package/agent.bak.20260905-190020/extensions/statusline/install.sh +0 -21
  453. package/agent.bak.20260905-190020/extensions/subagents/docs/design-plan.md +0 -568
  454. package/agent.bak.20260905-190020/extensions/subagents/docs/effect-v4-extension-guide.md +0 -354
  455. package/agent.bak.20260905-190020/extensions/subagents/docs/effect-v4-notes.md +0 -571
  456. package/agent.bak.20260905-190020/extensions/subagents/index.ts +0 -826
  457. package/agent.bak.20260905-190020/extensions/subagents/install.ps1 +0 -23
  458. package/agent.bak.20260905-190020/extensions/subagents/install.sh +0 -21
  459. package/agent.bak.20260905-190020/extensions/subagents/package-lock.json +0 -2244
  460. package/agent.bak.20260905-190020/extensions/subagents/package.json +0 -19
  461. package/agent.bak.20260905-190020/extensions/subagents/src/backend.ts +0 -73
  462. package/agent.bak.20260905-190020/extensions/subagents/src/backends/claude.ts +0 -701
  463. package/agent.bak.20260905-190020/extensions/subagents/src/backends/codex.ts +0 -1060
  464. package/agent.bak.20260905-190020/extensions/subagents/src/backends/pi.ts +0 -575
  465. package/agent.bak.20260905-190020/extensions/subagents/src/backends/stub.ts +0 -300
  466. package/agent.bak.20260905-190020/extensions/subagents/src/by-the-way.ts +0 -21
  467. package/agent.bak.20260905-190020/extensions/subagents/src/domain.ts +0 -253
  468. package/agent.bak.20260905-190020/extensions/subagents/src/format.ts +0 -74
  469. package/agent.bak.20260905-190020/extensions/subagents/src/manager.ts +0 -736
  470. package/agent.bak.20260905-190020/extensions/subagents/src/prompt.ts +0 -92
  471. package/agent.bak.20260905-190020/extensions/subagents/src/result-delivery.ts +0 -20
  472. package/agent.bak.20260905-190020/extensions/subagents/src/runtime.ts +0 -53
  473. package/agent.bak.20260905-190020/extensions/subagents/src/ui/takeover.ts +0 -583
  474. package/agent.bak.20260905-190020/extensions/subagents/src/ui/transcript.ts +0 -201
  475. package/agent.bak.20260905-190020/extensions/subagents/src/widget-order.ts +0 -121
  476. package/agent.bak.20260905-190020/extensions/subagents/test/by-the-way.test.ts +0 -29
  477. package/agent.bak.20260905-190020/extensions/subagents/test/claude.test.ts +0 -119
  478. package/agent.bak.20260905-190020/extensions/subagents/test/codex.test.ts +0 -102
  479. package/agent.bak.20260905-190020/extensions/subagents/test/context-usage.test.ts +0 -107
  480. package/agent.bak.20260905-190020/extensions/subagents/test/manager.test.ts +0 -276
  481. package/agent.bak.20260905-190020/extensions/subagents/test/result-delivery.test.ts +0 -27
  482. package/agent.bak.20260905-190020/extensions/subagents/test/takeover.test.ts +0 -29
  483. package/agent.bak.20260905-190020/extensions/subagents/tsconfig.json +0 -7
  484. package/agent.bak.20260905-190020/extensions/taste/index.ts +0 -443
  485. package/agent.bak.20260905-190020/extensions/taste/install.ps1 +0 -23
  486. package/agent.bak.20260905-190020/extensions/taste/install.sh +0 -21
  487. package/agent.bak.20260905-190020/extensions/todo/AGENTS.md +0 -38
  488. package/agent.bak.20260905-190020/extensions/todo/LICENSE +0 -21
  489. package/agent.bak.20260905-190020/extensions/todo/config.ts +0 -55
  490. package/agent.bak.20260905-190020/extensions/todo/index.ts +0 -151
  491. package/agent.bak.20260905-190020/extensions/todo/install.ps1 +0 -23
  492. package/agent.bak.20260905-190020/extensions/todo/install.sh +0 -21
  493. package/agent.bak.20260905-190020/extensions/todo/locales/de.json +0 -17
  494. package/agent.bak.20260905-190020/extensions/todo/locales/en.json +0 -15
  495. package/agent.bak.20260905-190020/extensions/todo/locales/es.json +0 -17
  496. package/agent.bak.20260905-190020/extensions/todo/locales/fr.json +0 -17
  497. package/agent.bak.20260905-190020/extensions/todo/locales/pt-BR.json +0 -17
  498. package/agent.bak.20260905-190020/extensions/todo/locales/pt.json +0 -17
  499. package/agent.bak.20260905-190020/extensions/todo/locales/ru.json +0 -17
  500. package/agent.bak.20260905-190020/extensions/todo/locales/uk.json +0 -17
  501. package/agent.bak.20260905-190020/extensions/todo/locales/zh.json +0 -17
  502. package/agent.bak.20260905-190020/extensions/todo/package-lock.json +0 -3358
  503. package/agent.bak.20260905-190020/extensions/todo/package.json +0 -67
  504. package/agent.bak.20260905-190020/extensions/todo/state/i18n-bridge.ts +0 -64
  505. package/agent.bak.20260905-190020/extensions/todo/state/invariants.ts +0 -20
  506. package/agent.bak.20260905-190020/extensions/todo/state/replay.ts +0 -38
  507. package/agent.bak.20260905-190020/extensions/todo/state/selectors.ts +0 -107
  508. package/agent.bak.20260905-190020/extensions/todo/state/state-reducer.ts +0 -326
  509. package/agent.bak.20260905-190020/extensions/todo/state/state.ts +0 -18
  510. package/agent.bak.20260905-190020/extensions/todo/state/store.ts +0 -82
  511. package/agent.bak.20260905-190020/extensions/todo/state/task-graph.ts +0 -57
  512. package/agent.bak.20260905-190020/extensions/todo/todo-overlay.ts +0 -204
  513. package/agent.bak.20260905-190020/extensions/todo/todo.ts +0 -155
  514. package/agent.bak.20260905-190020/extensions/todo/tool/response-envelope.ts +0 -109
  515. package/agent.bak.20260905-190020/extensions/todo/tool/types.ts +0 -206
  516. package/agent.bak.20260905-190020/extensions/todo/view/format.ts +0 -177
  517. package/agent.bak.20260905-190020/extensions/todo/widget-order.ts +0 -121
  518. package/agent.bak.20260905-190020/extensions/trim-context/README.md +0 -54
  519. package/agent.bak.20260905-190020/extensions/trim-context/index.ts +0 -487
  520. package/agent.bak.20260905-190020/extensions/trim-context/install.ps1 +0 -23
  521. package/agent.bak.20260905-190020/extensions/trim-context/install.sh +0 -21
  522. package/agent.bak.20260905-190020/keybindings.json +0 -7
@@ -1,1060 +1,1060 @@
1
- /**
2
- * Codex backend — real implementation over `codex app-server`.
3
- *
4
- * One scoped app-server process owns one persistent Codex thread. The server
5
- * speaks LF-delimited JSON-RPC over stdio: initialize, thread/start, and
6
- * turn/start drive runs; v2 item notifications are translated into normalized
7
- * SubagentEvents. send() queues a follow-up turn while busy, and interrupt uses
8
- * turn/interrupt with a local deadline so a missing server acknowledgement can
9
- * never leave the manager stuck in "running".
10
- */
11
-
12
- import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
13
- import * as fs from "node:fs";
14
- import * as path from "node:path";
15
- import type { Cause, Scope } from "effect";
16
- import { Effect, Queue, Stream } from "effect";
17
- import type { SubagentBackend, SubagentSession } from "../backend.ts";
18
- import type {
19
- ReasoningEffort,
20
- RunOutcome,
21
- SpawnTask,
22
- SubagentEvent,
23
- SubagentMeta,
24
- TranscriptPart,
25
- } from "../domain.ts";
26
- import { SendError, SpawnError } from "../domain.ts";
27
-
28
- const REQUEST_TIMEOUT_MS = 30_000;
29
- const MODEL_LIST_TIMEOUT_MS = 5_000;
30
- const INTERRUPT_FALLBACK_MS = 1_500;
31
- const FORCE_KILL_AFTER_MS = 2_000;
32
- const PREVIEW_MAX_LENGTH = 1_024;
33
- /** A protocol line larger than this without a newline means a broken peer. */
34
- const STDOUT_BUFFER_MAX_BYTES = 4 * 1024 * 1024;
35
-
36
- type JsonRecord = Record<string, unknown>;
37
-
38
- interface PendingRequest {
39
- readonly resolve: (result: JsonRecord) => void;
40
- readonly reject: (error: Error) => void;
41
- readonly timer: ReturnType<typeof setTimeout>;
42
- }
43
-
44
- interface ToolState {
45
- readonly name: string;
46
- output: string;
47
- }
48
-
49
- // --- Binary + protocol helpers -----------------------------------------------
50
-
51
- let cachedCodexBinary: string | null | undefined;
52
-
53
- function executable(file: string) {
54
- try {
55
- fs.accessSync(file, fs.constants.X_OK);
56
- return true;
57
- } catch {
58
- return false;
59
- }
60
- }
61
-
62
- /** Resolve once on first use; availability checks after that are allocation-only. */
63
- function resolveCodexBinary() {
64
- if (cachedCodexBinary !== undefined) return cachedCodexBinary ?? undefined;
65
- const names =
66
- process.platform === "win32" ? ["codex.exe", "codex.cmd"] : ["codex"];
67
- for (const directory of (process.env.PATH ?? "").split(path.delimiter)) {
68
- if (!directory) continue;
69
- for (const name of names) {
70
- const candidate = path.join(directory, name);
71
- if (executable(candidate)) {
72
- cachedCodexBinary = candidate;
73
- return candidate;
74
- }
75
- }
76
- }
77
- cachedCodexBinary = null;
78
- return undefined;
79
- }
80
-
81
- function record(value: unknown): JsonRecord | undefined {
82
- return value !== null && typeof value === "object" && !Array.isArray(value)
83
- ? (value as JsonRecord)
84
- : undefined;
85
- }
86
-
87
- function stringValue(value: unknown) {
88
- return typeof value === "string" ? value : undefined;
89
- }
90
-
91
- function numberValue(value: unknown) {
92
- return typeof value === "number" && Number.isFinite(value)
93
- ? value
94
- : undefined;
95
- }
96
-
97
- function booleanValue(value: unknown) {
98
- return typeof value === "boolean" ? value : undefined;
99
- }
100
-
101
- function records(value: unknown) {
102
- return Array.isArray(value)
103
- ? value.map(record).filter((item): item is JsonRecord => item !== undefined)
104
- : [];
105
- }
106
-
107
- function strings(value: unknown) {
108
- return Array.isArray(value)
109
- ? value.filter((item): item is string => typeof item === "string")
110
- : [];
111
- }
112
-
113
- function safeJson(value: unknown) {
114
- try {
115
- const text = JSON.stringify(value);
116
- return text === undefined ? undefined : text.slice(0, PREVIEW_MAX_LENGTH);
117
- } catch {
118
- return undefined;
119
- }
120
- }
121
-
122
- function firstLine(value: unknown) {
123
- if (typeof value !== "string") return undefined;
124
- const line = value.split("\n").find((candidate) => candidate.trim());
125
- return line?.trim().slice(0, PREVIEW_MAX_LENGTH);
126
- }
127
-
128
- function boundedError(error: unknown) {
129
- return (error instanceof Error ? error.message : String(error)).slice(
130
- 0,
131
- 4096,
132
- );
133
- }
134
-
135
- function protocolError(value: unknown) {
136
- const error = record(value);
137
- const message = stringValue(error?.message);
138
- return boundedError(
139
- message ?? safeJson(value) ?? "Codex app-server request failed",
140
- );
141
- }
142
-
143
- /** 0.144.3 accepts these effort slugs; individual models expose a subset. */
144
- function preferredCodexEffort(effort: ReasoningEffort | undefined) {
145
- switch (effort) {
146
- case "off":
147
- case "minimal":
148
- return "minimal";
149
- case "low":
150
- case "medium":
151
- case "high":
152
- return effort;
153
- case "xhigh":
154
- case "max":
155
- return "xhigh";
156
- case undefined:
157
- return undefined;
158
- }
159
- }
160
-
161
- /** Clamp against model/list because, for example, some models use none instead of minimal. */
162
- function supportedCodexEffort(
163
- effort: ReasoningEffort | undefined,
164
- modelLabel: string | undefined,
165
- modelList: JsonRecord | undefined,
166
- ) {
167
- const preferred = preferredCodexEffort(effort);
168
- if (!preferred) return undefined;
169
- const models = records(modelList?.data);
170
- const model =
171
- models.find(
172
- (candidate) =>
173
- stringValue(candidate.id) === modelLabel ||
174
- stringValue(candidate.model) === modelLabel,
175
- ) ?? models.find((candidate) => candidate.isDefault === true);
176
- if (!model) return preferred;
177
- const supported = records(model.supportedReasoningEfforts)
178
- .map((option) => stringValue(option.reasoningEffort))
179
- .filter((value): value is string => value !== undefined);
180
- if (supported.includes(preferred)) return preferred;
181
-
182
- const scale = ["none", "minimal", "low", "medium", "high", "xhigh"] as const;
183
- const target = scale.indexOf(preferred);
184
- const candidates = supported
185
- .map((value) => ({
186
- value,
187
- index: scale.indexOf(value as (typeof scale)[number]),
188
- }))
189
- .filter((candidate) => candidate.index >= 0)
190
- .sort((a, b) => {
191
- const distance = Math.abs(a.index - target) - Math.abs(b.index - target);
192
- if (distance !== 0) return distance;
193
- // "off" biases down to none; all other values bias toward more reasoning.
194
- return effort === "off" ? a.index - b.index : b.index - a.index;
195
- });
196
- return candidates[0]?.value ?? preferred;
197
- }
198
-
199
- function textInput(text: string) {
200
- return { type: "text", text, text_elements: [] };
201
- }
202
-
203
- /**
204
- * Parse a `thread/tokenUsage/updated` payload into context occupancy.
205
- * `tokenUsage.total` accumulates every request in the thread (cached prompt
206
- * tokens re-counted per request), so it is a cumulative spend counter — not
207
- * occupancy — and treating it as occupancy pinned the gauge at 100%.
208
- * `tokenUsage.last` is the most recent request, whose totalTokens is what
209
- * codex-rs itself uses as `tokens_in_context_window()`.
210
- */
211
- export function parseThreadTokenUsage(params: unknown) {
212
- const usage = record(record(params)?.tokenUsage);
213
- const last = record(usage?.last);
214
- return {
215
- tokens: numberValue(last?.totalTokens),
216
- contextWindow: numberValue(usage?.modelContextWindow),
217
- };
218
- }
219
-
220
- // --- Item translation --------------------------------------------------------
221
-
222
- function fileChangePreview(item: JsonRecord) {
223
- const paths = records(item.changes)
224
- .map((change) => stringValue(change.path))
225
- .filter((value): value is string => value !== undefined);
226
- return paths.length > 0
227
- ? paths.join(", ").slice(0, PREVIEW_MAX_LENGTH)
228
- : undefined;
229
- }
230
-
231
- function toolDescription(
232
- item: JsonRecord,
233
- ): { id: string; name: string; args?: string } | undefined {
234
- const id = stringValue(item.id);
235
- const type = stringValue(item.type);
236
- if (!id || !type) return undefined;
237
- switch (type) {
238
- case "commandExecution":
239
- return { id, name: "shell", args: firstLine(item.command) };
240
- case "fileChange":
241
- return { id, name: "apply_patch", args: fileChangePreview(item) };
242
- case "webSearch":
243
- return { id, name: "web_search", args: firstLine(item.query) };
244
- case "mcpToolCall": {
245
- const server = stringValue(item.server);
246
- const tool = stringValue(item.tool) ?? "tool";
247
- return {
248
- id,
249
- name: server ? `${server}/${tool}` : tool,
250
- args: safeJson(item.arguments),
251
- };
252
- }
253
- case "dynamicToolCall": {
254
- const namespace = stringValue(item.namespace);
255
- const tool = stringValue(item.tool) ?? "tool";
256
- return {
257
- id,
258
- name: namespace ? `${namespace}/${tool}` : tool,
259
- args: safeJson(item.arguments),
260
- };
261
- }
262
- default:
263
- return undefined;
264
- }
265
- }
266
-
267
- function toolOutput(item: JsonRecord, buffered: string) {
268
- switch (stringValue(item.type)) {
269
- case "commandExecution":
270
- return stringValue(item.aggregatedOutput) ?? buffered;
271
- case "fileChange":
272
- return fileChangePreview(item);
273
- case "webSearch":
274
- return stringValue(item.query);
275
- case "mcpToolCall":
276
- return safeJson(item.result ?? item.error);
277
- case "dynamicToolCall": {
278
- const text = records(item.contentItems)
279
- .map((content) => stringValue(content.text))
280
- .filter((value): value is string => value !== undefined)
281
- .join("\n");
282
- return text || safeJson(item.contentItems);
283
- }
284
- default:
285
- return buffered;
286
- }
287
- }
288
-
289
- function toolFailed(item: JsonRecord) {
290
- const status = stringValue(item.status);
291
- const exitCode = numberValue(item.exitCode);
292
- const success = booleanValue(item.success);
293
- return (
294
- (exitCode !== undefined && exitCode !== 0) ||
295
- success === false ||
296
- status === "failed" ||
297
- status === "declined" ||
298
- status === "cancelled"
299
- );
300
- }
301
-
302
- // --- The session -------------------------------------------------------------
303
-
304
- const makeCodexSession = (
305
- task: SpawnTask,
306
- ): Effect.Effect<SubagentSession, SpawnError, Scope.Scope> =>
307
- Effect.gen(function* () {
308
- const binary = resolveCodexBinary();
309
- if (!binary) {
310
- return yield* new SpawnError({
311
- message: "codex executable was not found on PATH.",
312
- });
313
- }
314
-
315
- const events = yield* Queue.make<SubagentEvent, Cause.Done>();
316
- const emit = (event: SubagentEvent) => {
317
- Queue.offerUnsafe(events, event);
318
- };
319
-
320
- const child = yield* Effect.try({
321
- try: () =>
322
- spawn(binary, ["app-server", "--stdio"], {
323
- cwd: task.cwd,
324
- env: process.env,
325
- stdio: ["pipe", "pipe", "pipe"],
326
- windowsHide: true,
327
- // Own process group on POSIX so teardown can signal the whole
328
- // tree: a wedged app-server must not orphan a still-running
329
- // shell command it spawned.
330
- detached: process.platform !== "win32",
331
- }),
332
- catch: (error) => new SpawnError({ message: boundedError(error) }),
333
- });
334
-
335
- const state = {
336
- closed: false,
337
- closing: false,
338
- exited: false,
339
- activeRun: false,
340
- dispatching: false,
341
- interruptRequested: false,
342
- effort: preferredCodexEffort(task.reasoningEffort),
343
- runSerial: 0,
344
- activeTurnId: undefined as string | undefined,
345
- runError: undefined as string | undefined,
346
- finalText: "",
347
- lastAssistantText: "",
348
- pendingPrompts: [] as string[],
349
- nextRequestId: 0,
350
- stderr: "",
351
- meta: {
352
- backend: "codex",
353
- modelLabel: task.model,
354
- } satisfies SubagentMeta as SubagentMeta,
355
- interruptTimer: undefined as ReturnType<typeof setTimeout> | undefined,
356
- };
357
- const pendingRequests = new Map<number, PendingRequest>();
358
- const tools = new Map<string, ToolState>();
359
- /** Turns locally settled by the interrupt fallback may still emit late events. */
360
- const ignoredTurnIds = new Set<string>();
361
-
362
- const writeMessage = (message: JsonRecord) => {
363
- if (state.closed || !child.stdin.writable) return false;
364
- child.stdin.write(`${JSON.stringify(message)}\n`);
365
- return true;
366
- };
367
-
368
- const request = (
369
- method: string,
370
- params: JsonRecord,
371
- timeoutMs = REQUEST_TIMEOUT_MS,
372
- ) =>
373
- new Promise<JsonRecord>((resolve, reject) => {
374
- if (state.closed) {
375
- reject(new Error("Codex app-server is closed."));
376
- return;
377
- }
378
- const id = ++state.nextRequestId;
379
- const timer = setTimeout(() => {
380
- pendingRequests.delete(id);
381
- reject(new Error(`Codex app-server request ${method} timed out.`));
382
- }, timeoutMs);
383
- pendingRequests.set(id, { resolve, reject, timer });
384
- if (!writeMessage({ id, method, params })) {
385
- clearTimeout(timer);
386
- pendingRequests.delete(id);
387
- reject(new Error("Codex app-server stdin is closed."));
388
- }
389
- });
390
-
391
- const rejectPending = (message: string) => {
392
- for (const pending of pendingRequests.values()) {
393
- clearTimeout(pending.timer);
394
- pending.reject(new Error(message));
395
- }
396
- pendingRequests.clear();
397
- };
398
-
399
- const queuedView = () =>
400
- state.pendingPrompts.map((text) => ({
401
- text,
402
- kind: "follow-up" as const,
403
- }));
404
-
405
- const startNextQueued = () => {
406
- if (state.closed || state.activeRun) return;
407
- const next = state.pendingPrompts.shift();
408
- if (next === undefined) return;
409
- emit({ _tag: "QueueChanged", queued: queuedView() });
410
- startRun(next);
411
- };
412
-
413
- const settleRun = (outcome: RunOutcome, serial = state.runSerial) => {
414
- if (!state.activeRun || serial !== state.runSerial) return;
415
- if (state.interruptTimer) clearTimeout(state.interruptTimer);
416
- state.interruptTimer = undefined;
417
- state.activeRun = false;
418
- state.dispatching = false;
419
- // A late turn/completed for this turn must not be misattributed to the
420
- // next queued run (which starts with no activeTurnId to filter on).
421
- if (state.activeTurnId) ignoredTurnIds.add(state.activeTurnId);
422
- state.activeTurnId = undefined;
423
- state.interruptRequested = false;
424
- tools.clear();
425
- emit({ _tag: "RunSettled", outcome });
426
- queueMicrotask(startNextQueued);
427
- };
428
-
429
- const sendInterrupt = (serial: number) => {
430
- const turnId = state.activeTurnId;
431
- const threadId = state.meta.nativeSessionId;
432
- if (
433
- !turnId ||
434
- !threadId ||
435
- !state.activeRun ||
436
- serial !== state.runSerial
437
- )
438
- return;
439
- void request(
440
- "turn/interrupt",
441
- { threadId, turnId },
442
- INTERRUPT_FALLBACK_MS,
443
- ).catch((error) => {
444
- if (state.activeRun && serial === state.runSerial) {
445
- emit({ _tag: "BackendError", message: boundedError(error) });
446
- }
447
- });
448
- };
449
-
450
- function startRun(text: string) {
451
- if (state.closed || state.activeRun) return;
452
- const threadId = state.meta.nativeSessionId;
453
- if (!threadId) return;
454
- const serial = ++state.runSerial;
455
- state.activeRun = true;
456
- state.dispatching = true;
457
- state.interruptRequested = false;
458
- state.activeTurnId = undefined;
459
- state.runError = undefined;
460
- state.finalText = "";
461
- state.lastAssistantText = "";
462
- emit({ _tag: "UserMessage", text });
463
- emit({ _tag: "RunStarted" });
464
-
465
- const params: JsonRecord = {
466
- threadId,
467
- input: [textInput(text)],
468
- ...(state.effort ? { effort: state.effort } : {}),
469
- };
470
- void request("turn/start", params).then(
471
- (result) => {
472
- const turn = record(result.turn);
473
- const turnId = stringValue(turn?.id);
474
- if (!state.activeRun || serial !== state.runSerial) {
475
- if (turnId) {
476
- // The run was already settled locally (interrupt fallback or
477
- // failure), so whatever native turn this response describes is
478
- // invisible work — stop it unconditionally.
479
- ignoredTurnIds.add(turnId);
480
- void request(
481
- "turn/interrupt",
482
- { threadId, turnId },
483
- INTERRUPT_FALLBACK_MS,
484
- ).catch(() => undefined);
485
- }
486
- return;
487
- }
488
- state.dispatching = false;
489
- state.activeTurnId = turnId ?? state.activeTurnId;
490
- if (state.interruptRequested) sendInterrupt(serial);
491
- },
492
- (error) => {
493
- if (!state.activeRun || serial !== state.runSerial) return;
494
- const errorText = boundedError(error);
495
- settleRun(
496
- state.interruptRequested
497
- ? {
498
- _tag: "Interrupted",
499
- partialText: state.finalText || undefined,
500
- }
501
- : {
502
- _tag: "Failed",
503
- errorText,
504
- partialText: state.finalText || undefined,
505
- },
506
- serial,
507
- );
508
- // A timed-out turn/start means a turn may be running that we can
509
- // never see or interrupt (no turn id). That session cannot be
510
- // trusted with further work — kill it; the exit handler reports
511
- // the death. Explicit protocol rejections keep the session alive.
512
- if (errorText.includes("timed out")) {
513
- void terminateChild(child, () => state.exited);
514
- }
515
- },
516
- );
517
- }
518
-
519
- const emitToolStart = (item: JsonRecord) => {
520
- const tool = toolDescription(item);
521
- if (!tool || tools.has(tool.id)) return;
522
- tools.set(tool.id, { name: tool.name, output: "" });
523
- const toolPart: TranscriptPart = {
524
- type: "toolCall",
525
- toolId: tool.id,
526
- name: tool.name,
527
- argsPreview: tool.args,
528
- };
529
- emit({ _tag: "AssistantMessage", parts: [toolPart] });
530
- emit({
531
- _tag: "ToolStart",
532
- toolId: tool.id,
533
- name: tool.name,
534
- argsPreview: tool.args,
535
- });
536
- };
537
-
538
- const emitToolEnd = (item: JsonRecord) => {
539
- const description = toolDescription(item);
540
- if (!description) return;
541
- if (!tools.has(description.id)) emitToolStart(item);
542
- const live = tools.get(description.id);
543
- const output = toolOutput(item, live?.output ?? "");
544
- tools.delete(description.id);
545
- emit({
546
- _tag: "ToolEnd",
547
- toolId: description.id,
548
- name: live?.name ?? description.name,
549
- isError: toolFailed(item),
550
- outputPreview: firstLine(output),
551
- });
552
- };
553
-
554
- const handleItemCompleted = (item: JsonRecord) => {
555
- const type = stringValue(item.type);
556
- if (type === "agentMessage") {
557
- const text = stringValue(item.text) ?? "";
558
- if (text) {
559
- emit({ _tag: "AssistantMessage", parts: [{ type: "text", text }] });
560
- state.lastAssistantText = text;
561
- if (stringValue(item.phase) === "final_answer")
562
- state.finalText = text;
563
- }
564
- return;
565
- }
566
- if (type === "reasoning") {
567
- const thinking = [
568
- ...strings(item.summary),
569
- ...strings(item.content),
570
- ].join("\n");
571
- if (thinking) {
572
- emit({
573
- _tag: "AssistantMessage",
574
- parts: [{ type: "thinking", text: thinking }],
575
- });
576
- }
577
- return;
578
- }
579
- emitToolEnd(item);
580
- };
581
-
582
- const handleNotification = (message: JsonRecord) => {
583
- if (state.closed) return;
584
- const method = stringValue(message.method);
585
- const params = record(message.params) ?? {};
586
- const notificationTurn = record(params.turn);
587
- const turnId =
588
- stringValue(params.turnId) ?? stringValue(notificationTurn?.id);
589
- if (turnId && ignoredTurnIds.has(turnId)) return;
590
- const belongsToRun =
591
- method === "error" ||
592
- method?.startsWith("turn/") === true ||
593
- method?.startsWith("item/") === true ||
594
- method === "thread/tokenUsage/updated";
595
- if (belongsToRun && !state.activeRun) {
596
- if (turnId) ignoredTurnIds.add(turnId);
597
- return;
598
- }
599
- if (
600
- belongsToRun &&
601
- turnId &&
602
- state.activeTurnId &&
603
- turnId !== state.activeTurnId
604
- ) {
605
- return;
606
- }
607
- switch (method) {
608
- case "thread/started": {
609
- const thread = record(params.thread);
610
- const id = stringValue(thread?.id);
611
- const sessionFilePath = stringValue(thread?.path);
612
- if (id) state.meta = { ...state.meta, nativeSessionId: id };
613
- if (sessionFilePath) state.meta = { ...state.meta, sessionFilePath };
614
- emit({ _tag: "MetaChanged", meta: state.meta });
615
- break;
616
- }
617
- case "thread/settings/updated": {
618
- const settings = record(params.threadSettings);
619
- const modelLabel = stringValue(settings?.model);
620
- if (modelLabel) {
621
- state.meta = { ...state.meta, modelLabel };
622
- emit({ _tag: "MetaChanged", meta: { modelLabel } });
623
- }
624
- break;
625
- }
626
- case "model/rerouted": {
627
- const modelLabel = stringValue(params.toModel);
628
- if (modelLabel) {
629
- state.meta = { ...state.meta, modelLabel };
630
- emit({ _tag: "MetaChanged", meta: { modelLabel } });
631
- }
632
- break;
633
- }
634
- case "turn/started": {
635
- const turn = record(params.turn);
636
- const startedId = stringValue(turn?.id);
637
- // Only adopt a turn we are actually waiting on. A stale start from
638
- // a run the interrupt fallback settled before its turn/start
639
- // response arrived would otherwise capture activeTurnId and filter
640
- // out every event of the real next turn.
641
- if (!state.dispatching && startedId !== state.activeTurnId) {
642
- if (startedId) ignoredTurnIds.add(startedId);
643
- break;
644
- }
645
- state.activeTurnId = startedId ?? state.activeTurnId;
646
- state.dispatching = false;
647
- emit({ _tag: "RunStarted" });
648
- if (state.interruptRequested) sendInterrupt(state.runSerial);
649
- break;
650
- }
651
- case "item/agentMessage/delta": {
652
- const delta = stringValue(params.delta);
653
- if (delta) emit({ _tag: "AssistantDelta", kind: "text", delta });
654
- break;
655
- }
656
- case "item/reasoning/summaryTextDelta":
657
- case "item/reasoning/textDelta": {
658
- const delta = stringValue(params.delta);
659
- if (delta) emit({ _tag: "AssistantDelta", kind: "thinking", delta });
660
- break;
661
- }
662
- case "item/started": {
663
- const item = record(params.item);
664
- if (item) emitToolStart(item);
665
- break;
666
- }
667
- case "item/completed": {
668
- const item = record(params.item);
669
- if (item) handleItemCompleted(item);
670
- break;
671
- }
672
- case "item/commandExecution/outputDelta":
673
- case "item/fileChange/outputDelta": {
674
- const id = stringValue(params.itemId);
675
- const delta = stringValue(params.delta);
676
- const tool = id ? tools.get(id) : undefined;
677
- if (id && tool && delta) {
678
- tool.output = `${tool.output}${delta}`.slice(-16_384);
679
- emit({
680
- _tag: "ToolUpdate",
681
- toolId: id,
682
- outputPreview: firstLine(tool.output),
683
- });
684
- }
685
- break;
686
- }
687
- case "item/fileChange/patchUpdated": {
688
- const id = stringValue(params.itemId);
689
- if (id) {
690
- emit({
691
- _tag: "ToolUpdate",
692
- toolId: id,
693
- outputPreview: fileChangePreview({ changes: params.changes }),
694
- });
695
- }
696
- break;
697
- }
698
- case "item/mcpToolCall/progress": {
699
- const id = stringValue(params.itemId);
700
- if (id) {
701
- emit({
702
- _tag: "ToolUpdate",
703
- toolId: id,
704
- outputPreview: firstLine(params.message),
705
- });
706
- }
707
- break;
708
- }
709
- case "thread/tokenUsage/updated": {
710
- const { tokens, contextWindow } = parseThreadTokenUsage(params);
711
- if (contextWindow !== undefined) {
712
- state.meta = { ...state.meta, contextWindow };
713
- emit({ _tag: "MetaChanged", meta: { contextWindow } });
714
- }
715
- emit({ _tag: "UsageChanged", tokens, contextWindow });
716
- break;
717
- }
718
- case "error": {
719
- const error = record(params.error);
720
- const messageText = boundedError(
721
- stringValue(error?.message) ?? "Codex run failed",
722
- );
723
- if (params.willRetry !== true) state.runError = messageText;
724
- emit({ _tag: "BackendError", message: messageText });
725
- break;
726
- }
727
- case "turn/completed": {
728
- const turn = record(params.turn);
729
- const status = stringValue(turn?.status);
730
- const error = record(turn?.error);
731
- const partialText =
732
- state.finalText || state.lastAssistantText || undefined;
733
- if (state.interruptRequested || status === "interrupted") {
734
- settleRun({ _tag: "Interrupted", partialText });
735
- } else if (status === "failed") {
736
- settleRun({
737
- _tag: "Failed",
738
- errorText: boundedError(
739
- state.runError ??
740
- stringValue(error?.message) ??
741
- "Codex run failed",
742
- ),
743
- partialText,
744
- });
745
- } else {
746
- settleRun({
747
- _tag: "Completed",
748
- finalText: state.finalText || state.lastAssistantText,
749
- });
750
- }
751
- break;
752
- }
753
- }
754
- };
755
-
756
- const handleServerRequest = (message: JsonRecord) => {
757
- const id = message.id;
758
- if (typeof id !== "number" && typeof id !== "string") return;
759
- const method = stringValue(message.method);
760
- if (
761
- method === "item/commandExecution/requestApproval" ||
762
- method === "item/fileChange/requestApproval"
763
- ) {
764
- writeMessage({ id, result: { decision: "decline" } });
765
- return;
766
- }
767
- writeMessage({
768
- id,
769
- error: {
770
- code: -32601,
771
- message: `Unsupported headless server request: ${method ?? "unknown"}`,
772
- },
773
- });
774
- };
775
-
776
- const handleLine = (line: string) => {
777
- if (!line.trim()) return;
778
- let parsed: unknown;
779
- try {
780
- parsed = JSON.parse(line);
781
- } catch {
782
- emit({
783
- _tag: "BackendError",
784
- message: `Invalid Codex protocol line: ${line.slice(0, 512)}`,
785
- });
786
- return;
787
- }
788
- const message = record(parsed);
789
- if (!message) return;
790
- const id = numberValue(message.id);
791
- if (id !== undefined && pendingRequests.has(id)) {
792
- const pending = pendingRequests.get(id);
793
- if (!pending) return;
794
- pendingRequests.delete(id);
795
- clearTimeout(pending.timer);
796
- if (message.error !== undefined)
797
- pending.reject(new Error(protocolError(message.error)));
798
- else pending.resolve(record(message.result) ?? {});
799
- return;
800
- }
801
- if (message.id !== undefined && message.method !== undefined)
802
- handleServerRequest(message);
803
- else if (message.method !== undefined) handleNotification(message);
804
- };
805
-
806
- const failForProcessExit = (detail: string) => {
807
- if (state.exited) return;
808
- state.exited = true;
809
- rejectPending(detail);
810
- if (state.closing) return;
811
- state.closed = true;
812
- state.pendingPrompts = [];
813
- emit({ _tag: "QueueChanged", queued: [] });
814
- if (state.activeRun) {
815
- settleRun({
816
- _tag: "Failed",
817
- errorText: boundedError(detail),
818
- partialText: state.finalText || state.lastAssistantText || undefined,
819
- });
820
- }
821
- Queue.endUnsafe(events);
822
- };
823
-
824
- let stdoutBuffer = "";
825
- child.stdout.setEncoding("utf8");
826
- child.stdout.on("data", (chunk: string) => {
827
- stdoutBuffer += chunk;
828
- while (true) {
829
- const newline = stdoutBuffer.indexOf("\n");
830
- if (newline < 0) break;
831
- const line = stdoutBuffer.slice(0, newline).replace(/\r$/, "");
832
- stdoutBuffer = stdoutBuffer.slice(newline + 1);
833
- handleLine(line);
834
- }
835
- if (stdoutBuffer.length > STDOUT_BUFFER_MAX_BYTES) {
836
- // A frame this large with no newline is protocol corruption, and an
837
- // unbounded buffer is a memory leak. Session-fatal: the exit handler
838
- // settles any active run.
839
- stdoutBuffer = "";
840
- void terminateChild(child, () => state.exited);
841
- }
842
- });
843
- child.stderr.setEncoding("utf8");
844
- child.stderr.on("data", (chunk: string) => {
845
- state.stderr = `${state.stderr}${chunk}`.slice(-4096);
846
- });
847
- child.once("error", (error) =>
848
- failForProcessExit(`Codex app-server failed: ${boundedError(error)}`),
849
- );
850
- child.once("exit", (code, signal) => {
851
- const suffix = firstLine(state.stderr);
852
- failForProcessExit(
853
- `Codex app-server exited (${signal ?? `code ${code ?? "unknown"}`})${suffix ? `: ${suffix}` : ""}`,
854
- );
855
- });
856
-
857
- yield* Effect.addFinalizer(() =>
858
- Effect.promise(async () => {
859
- if (state.closing) return;
860
- state.closing = true;
861
- if (state.interruptTimer) clearTimeout(state.interruptTimer);
862
- // Settle before marking closed so the run gets the correct
863
- // "Interrupted" outcome instead of the pump's generic fallback.
864
- if (state.activeRun) {
865
- settleRun({
866
- _tag: "Interrupted",
867
- partialText:
868
- state.finalText || state.lastAssistantText || undefined,
869
- });
870
- }
871
- state.closed = true;
872
- rejectPending("Codex session closed.");
873
- await terminateChild(child, () => state.exited);
874
- Queue.endUnsafe(events);
875
- }),
876
- );
877
-
878
- const threadResult = yield* Effect.tryPromise({
879
- try: async () => {
880
- await request("initialize", {
881
- clientInfo: {
882
- name: "pi-subagents",
883
- title: "pi subagent",
884
- version: "2.0.0",
885
- },
886
- capabilities: { experimentalApi: true },
887
- });
888
- writeMessage({ method: "initialized" });
889
- // Headless children cannot answer approval prompts. The caller
890
- // already chose to launch an autonomous subagent, so give the thread
891
- // full workspace access without interactive approval requests.
892
- return request("thread/start", {
893
- cwd: task.cwd,
894
- approvalPolicy: "never",
895
- sandbox: "danger-full-access",
896
- ephemeral: false,
897
- ...(task.model ? { model: task.model } : {}),
898
- });
899
- },
900
- catch: (error) => new SpawnError({ message: boundedError(error) }),
901
- });
902
-
903
- const thread = record(threadResult.thread);
904
- const nativeSessionId = stringValue(thread?.id);
905
- if (!nativeSessionId) {
906
- return yield* new SpawnError({
907
- message: "Codex thread/start returned no thread id.",
908
- });
909
- }
910
- state.meta = {
911
- backend: "codex",
912
- modelLabel: stringValue(threadResult.model) ?? task.model,
913
- sessionFilePath: stringValue(thread?.path),
914
- nativeSessionId,
915
- };
916
- if (task.reasoningEffort) {
917
- // Optional capability probe: never let a slow/unsupported model/list
918
- // hold up the spawn (and its concurrency reservation) for the full
919
- // request timeout; the unclamped preferred effort is a fine fallback.
920
- const modelList = yield* Effect.tryPromise(() =>
921
- request("model/list", { includeHidden: true }, MODEL_LIST_TIMEOUT_MS),
922
- ).pipe(Effect.orElseSucceed(() => undefined));
923
- state.effort = supportedCodexEffort(
924
- task.reasoningEffort,
925
- state.meta.modelLabel,
926
- modelList,
927
- );
928
- }
929
- emit({ _tag: "MetaChanged", meta: state.meta });
930
- startRun(task.prompt);
931
-
932
- return {
933
- meta: Effect.sync(() => state.meta),
934
- events: Stream.fromQueue(events),
935
- send: (text) =>
936
- Effect.suspend((): Effect.Effect<void, SendError> => {
937
- if (state.closed) {
938
- return new SendError({ message: "Subagent session is closed." });
939
- }
940
- if (state.activeRun) {
941
- state.pendingPrompts.push(text);
942
- emit({ _tag: "QueueChanged", queued: queuedView() });
943
- return Effect.void;
944
- }
945
- return Effect.sync(() => startRun(text));
946
- }),
947
- interrupt: Effect.promise(async () => {
948
- if (state.closed || !state.activeRun) return;
949
- const serial = state.runSerial;
950
- state.pendingPrompts = [];
951
- emit({ _tag: "QueueChanged", queued: [] });
952
- state.interruptRequested = true;
953
- sendInterrupt(serial);
954
- if (state.interruptTimer) clearTimeout(state.interruptTimer);
955
- state.interruptTimer = setTimeout(() => {
956
- if (state.activeRun && serial === state.runSerial) {
957
- if (state.activeTurnId) ignoredTurnIds.add(state.activeTurnId);
958
- settleRun({
959
- _tag: "Interrupted",
960
- partialText:
961
- state.finalText || state.lastAssistantText || undefined,
962
- });
963
- // The server never acknowledged the interrupt, so the native
964
- // turn may still be executing tools. A session that ignores
965
- // interrupts cannot be trusted — kill it rather than let
966
- // invisible work continue behind a "settled" run.
967
- void terminateChild(child, () => state.exited);
968
- }
969
- }, INTERRUPT_FALLBACK_MS);
970
- }),
971
- } satisfies SubagentSession;
972
- });
973
-
974
- /** Signal the whole process group on POSIX so tool descendants (shell
975
- * commands the app-server spawned) die with it; a wedged or force-killed
976
- * server must not orphan a still-running command in the workspace. */
977
- function killTree(
978
- child: ChildProcessWithoutNullStreams,
979
- signal: NodeJS.Signals,
980
- ) {
981
- if (process.platform === "win32" && child.pid) {
982
- try {
983
- const killer = spawn(
984
- "taskkill",
985
- [
986
- "/pid",
987
- String(child.pid),
988
- "/T",
989
- ...(signal === "SIGKILL" ? ["/F"] : []),
990
- ],
991
- { stdio: "ignore", windowsHide: true },
992
- );
993
- const killDirect = () => {
994
- try {
995
- child.kill(signal);
996
- } catch {
997
- // Process may already be gone.
998
- }
999
- };
1000
- killer.once("error", killDirect);
1001
- killer.once("exit", (code) => {
1002
- if (code !== 0) killDirect();
1003
- });
1004
- killer.unref();
1005
- return;
1006
- } catch {
1007
- // Fall through to a direct signal when taskkill cannot be launched.
1008
- }
1009
- }
1010
- if (process.platform !== "win32" && child.pid) {
1011
- try {
1012
- process.kill(-child.pid, signal);
1013
- return;
1014
- } catch {
1015
- // Group may already be gone; fall through to the direct signal.
1016
- }
1017
- }
1018
- try {
1019
- child.kill(signal);
1020
- } catch {
1021
- // Process may already be gone.
1022
- }
1023
- }
1024
-
1025
- /** SIGTERM is normally enough; the second deadline covers a wedged Rust process. */
1026
- function terminateChild(
1027
- child: ChildProcessWithoutNullStreams,
1028
- exited: () => boolean,
1029
- ) {
1030
- if (exited()) return Promise.resolve();
1031
- return new Promise<void>((resolve) => {
1032
- let done = false;
1033
- let forceTimer: ReturnType<typeof setTimeout> | undefined;
1034
- let lastTimer: ReturnType<typeof setTimeout> | undefined;
1035
- const finish = () => {
1036
- if (done) return;
1037
- done = true;
1038
- if (forceTimer) clearTimeout(forceTimer);
1039
- if (lastTimer) clearTimeout(lastTimer);
1040
- resolve();
1041
- };
1042
- child.once("exit", finish);
1043
- killTree(child, "SIGTERM");
1044
- forceTimer = setTimeout(() => {
1045
- if (!exited()) killTree(child, "SIGKILL");
1046
- }, FORCE_KILL_AFTER_MS);
1047
- lastTimer = setTimeout(finish, FORCE_KILL_AFTER_MS + 500);
1048
- });
1049
- }
1050
-
1051
- export const codexBackend: SubagentBackend = {
1052
- name: "codex",
1053
- capabilities: {
1054
- steering: false,
1055
- modelSelection: true,
1056
- reasoningEffort: true,
1057
- },
1058
- available: Effect.sync(() => resolveCodexBinary() !== undefined),
1059
- spawn: makeCodexSession,
1060
- };
1
+ /**
2
+ * Codex backend — real implementation over `codex app-server`.
3
+ *
4
+ * One scoped app-server process owns one persistent Codex thread. The server
5
+ * speaks LF-delimited JSON-RPC over stdio: initialize, thread/start, and
6
+ * turn/start drive runs; v2 item notifications are translated into normalized
7
+ * SubagentEvents. send() queues a follow-up turn while busy, and interrupt uses
8
+ * turn/interrupt with a local deadline so a missing server acknowledgement can
9
+ * never leave the manager stuck in "running".
10
+ */
11
+
12
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
13
+ import * as fs from "node:fs";
14
+ import * as path from "node:path";
15
+ import type { Cause, Scope } from "effect";
16
+ import { Effect, Queue, Stream } from "effect";
17
+ import type { SubagentBackend, SubagentSession } from "../backend.ts";
18
+ import type {
19
+ ReasoningEffort,
20
+ RunOutcome,
21
+ SpawnTask,
22
+ SubagentEvent,
23
+ SubagentMeta,
24
+ TranscriptPart,
25
+ } from "../domain.ts";
26
+ import { SendError, SpawnError } from "../domain.ts";
27
+
28
+ const REQUEST_TIMEOUT_MS = 30_000;
29
+ const MODEL_LIST_TIMEOUT_MS = 5_000;
30
+ const INTERRUPT_FALLBACK_MS = 1_500;
31
+ const FORCE_KILL_AFTER_MS = 2_000;
32
+ const PREVIEW_MAX_LENGTH = 1_024;
33
+ /** A protocol line larger than this without a newline means a broken peer. */
34
+ const STDOUT_BUFFER_MAX_BYTES = 4 * 1024 * 1024;
35
+
36
+ type JsonRecord = Record<string, unknown>;
37
+
38
+ interface PendingRequest {
39
+ readonly resolve: (result: JsonRecord) => void;
40
+ readonly reject: (error: Error) => void;
41
+ readonly timer: ReturnType<typeof setTimeout>;
42
+ }
43
+
44
+ interface ToolState {
45
+ readonly name: string;
46
+ output: string;
47
+ }
48
+
49
+ // --- Binary + protocol helpers -----------------------------------------------
50
+
51
+ let cachedCodexBinary: string | null | undefined;
52
+
53
+ function executable(file: string) {
54
+ try {
55
+ fs.accessSync(file, fs.constants.X_OK);
56
+ return true;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ /** Resolve once on first use; availability checks after that are allocation-only. */
63
+ function resolveCodexBinary() {
64
+ if (cachedCodexBinary !== undefined) return cachedCodexBinary ?? undefined;
65
+ const names =
66
+ process.platform === "win32" ? ["codex.exe", "codex.cmd"] : ["codex"];
67
+ for (const directory of (process.env.PATH ?? "").split(path.delimiter)) {
68
+ if (!directory) continue;
69
+ for (const name of names) {
70
+ const candidate = path.join(directory, name);
71
+ if (executable(candidate)) {
72
+ cachedCodexBinary = candidate;
73
+ return candidate;
74
+ }
75
+ }
76
+ }
77
+ cachedCodexBinary = null;
78
+ return undefined;
79
+ }
80
+
81
+ function record(value: unknown): JsonRecord | undefined {
82
+ return value !== null && typeof value === "object" && !Array.isArray(value)
83
+ ? (value as JsonRecord)
84
+ : undefined;
85
+ }
86
+
87
+ function stringValue(value: unknown) {
88
+ return typeof value === "string" ? value : undefined;
89
+ }
90
+
91
+ function numberValue(value: unknown) {
92
+ return typeof value === "number" && Number.isFinite(value)
93
+ ? value
94
+ : undefined;
95
+ }
96
+
97
+ function booleanValue(value: unknown) {
98
+ return typeof value === "boolean" ? value : undefined;
99
+ }
100
+
101
+ function records(value: unknown) {
102
+ return Array.isArray(value)
103
+ ? value.map(record).filter((item): item is JsonRecord => item !== undefined)
104
+ : [];
105
+ }
106
+
107
+ function strings(value: unknown) {
108
+ return Array.isArray(value)
109
+ ? value.filter((item): item is string => typeof item === "string")
110
+ : [];
111
+ }
112
+
113
+ function safeJson(value: unknown) {
114
+ try {
115
+ const text = JSON.stringify(value);
116
+ return text === undefined ? undefined : text.slice(0, PREVIEW_MAX_LENGTH);
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ }
121
+
122
+ function firstLine(value: unknown) {
123
+ if (typeof value !== "string") return undefined;
124
+ const line = value.split("\n").find((candidate) => candidate.trim());
125
+ return line?.trim().slice(0, PREVIEW_MAX_LENGTH);
126
+ }
127
+
128
+ function boundedError(error: unknown) {
129
+ return (error instanceof Error ? error.message : String(error)).slice(
130
+ 0,
131
+ 4096,
132
+ );
133
+ }
134
+
135
+ function protocolError(value: unknown) {
136
+ const error = record(value);
137
+ const message = stringValue(error?.message);
138
+ return boundedError(
139
+ message ?? safeJson(value) ?? "Codex app-server request failed",
140
+ );
141
+ }
142
+
143
+ /** 0.144.3 accepts these effort slugs; individual models expose a subset. */
144
+ function preferredCodexEffort(effort: ReasoningEffort | undefined) {
145
+ switch (effort) {
146
+ case "off":
147
+ case "minimal":
148
+ return "minimal";
149
+ case "low":
150
+ case "medium":
151
+ case "high":
152
+ return effort;
153
+ case "xhigh":
154
+ case "max":
155
+ return "xhigh";
156
+ case undefined:
157
+ return undefined;
158
+ }
159
+ }
160
+
161
+ /** Clamp against model/list because, for example, some models use none instead of minimal. */
162
+ function supportedCodexEffort(
163
+ effort: ReasoningEffort | undefined,
164
+ modelLabel: string | undefined,
165
+ modelList: JsonRecord | undefined,
166
+ ) {
167
+ const preferred = preferredCodexEffort(effort);
168
+ if (!preferred) return undefined;
169
+ const models = records(modelList?.data);
170
+ const model =
171
+ models.find(
172
+ (candidate) =>
173
+ stringValue(candidate.id) === modelLabel ||
174
+ stringValue(candidate.model) === modelLabel,
175
+ ) ?? models.find((candidate) => candidate.isDefault === true);
176
+ if (!model) return preferred;
177
+ const supported = records(model.supportedReasoningEfforts)
178
+ .map((option) => stringValue(option.reasoningEffort))
179
+ .filter((value): value is string => value !== undefined);
180
+ if (supported.includes(preferred)) return preferred;
181
+
182
+ const scale = ["none", "minimal", "low", "medium", "high", "xhigh"] as const;
183
+ const target = scale.indexOf(preferred);
184
+ const candidates = supported
185
+ .map((value) => ({
186
+ value,
187
+ index: scale.indexOf(value as (typeof scale)[number]),
188
+ }))
189
+ .filter((candidate) => candidate.index >= 0)
190
+ .sort((a, b) => {
191
+ const distance = Math.abs(a.index - target) - Math.abs(b.index - target);
192
+ if (distance !== 0) return distance;
193
+ // "off" biases down to none; all other values bias toward more reasoning.
194
+ return effort === "off" ? a.index - b.index : b.index - a.index;
195
+ });
196
+ return candidates[0]?.value ?? preferred;
197
+ }
198
+
199
+ function textInput(text: string) {
200
+ return { type: "text", text, text_elements: [] };
201
+ }
202
+
203
+ /**
204
+ * Parse a `thread/tokenUsage/updated` payload into context occupancy.
205
+ * `tokenUsage.total` accumulates every request in the thread (cached prompt
206
+ * tokens re-counted per request), so it is a cumulative spend counter — not
207
+ * occupancy — and treating it as occupancy pinned the gauge at 100%.
208
+ * `tokenUsage.last` is the most recent request, whose totalTokens is what
209
+ * codex-rs itself uses as `tokens_in_context_window()`.
210
+ */
211
+ export function parseThreadTokenUsage(params: unknown) {
212
+ const usage = record(record(params)?.tokenUsage);
213
+ const last = record(usage?.last);
214
+ return {
215
+ tokens: numberValue(last?.totalTokens),
216
+ contextWindow: numberValue(usage?.modelContextWindow),
217
+ };
218
+ }
219
+
220
+ // --- Item translation --------------------------------------------------------
221
+
222
+ function fileChangePreview(item: JsonRecord) {
223
+ const paths = records(item.changes)
224
+ .map((change) => stringValue(change.path))
225
+ .filter((value): value is string => value !== undefined);
226
+ return paths.length > 0
227
+ ? paths.join(", ").slice(0, PREVIEW_MAX_LENGTH)
228
+ : undefined;
229
+ }
230
+
231
+ function toolDescription(
232
+ item: JsonRecord,
233
+ ): { id: string; name: string; args?: string } | undefined {
234
+ const id = stringValue(item.id);
235
+ const type = stringValue(item.type);
236
+ if (!id || !type) return undefined;
237
+ switch (type) {
238
+ case "commandExecution":
239
+ return { id, name: "shell", args: firstLine(item.command) };
240
+ case "fileChange":
241
+ return { id, name: "apply_patch", args: fileChangePreview(item) };
242
+ case "webSearch":
243
+ return { id, name: "web_search", args: firstLine(item.query) };
244
+ case "mcpToolCall": {
245
+ const server = stringValue(item.server);
246
+ const tool = stringValue(item.tool) ?? "tool";
247
+ return {
248
+ id,
249
+ name: server ? `${server}/${tool}` : tool,
250
+ args: safeJson(item.arguments),
251
+ };
252
+ }
253
+ case "dynamicToolCall": {
254
+ const namespace = stringValue(item.namespace);
255
+ const tool = stringValue(item.tool) ?? "tool";
256
+ return {
257
+ id,
258
+ name: namespace ? `${namespace}/${tool}` : tool,
259
+ args: safeJson(item.arguments),
260
+ };
261
+ }
262
+ default:
263
+ return undefined;
264
+ }
265
+ }
266
+
267
+ function toolOutput(item: JsonRecord, buffered: string) {
268
+ switch (stringValue(item.type)) {
269
+ case "commandExecution":
270
+ return stringValue(item.aggregatedOutput) ?? buffered;
271
+ case "fileChange":
272
+ return fileChangePreview(item);
273
+ case "webSearch":
274
+ return stringValue(item.query);
275
+ case "mcpToolCall":
276
+ return safeJson(item.result ?? item.error);
277
+ case "dynamicToolCall": {
278
+ const text = records(item.contentItems)
279
+ .map((content) => stringValue(content.text))
280
+ .filter((value): value is string => value !== undefined)
281
+ .join("\n");
282
+ return text || safeJson(item.contentItems);
283
+ }
284
+ default:
285
+ return buffered;
286
+ }
287
+ }
288
+
289
+ function toolFailed(item: JsonRecord) {
290
+ const status = stringValue(item.status);
291
+ const exitCode = numberValue(item.exitCode);
292
+ const success = booleanValue(item.success);
293
+ return (
294
+ (exitCode !== undefined && exitCode !== 0) ||
295
+ success === false ||
296
+ status === "failed" ||
297
+ status === "declined" ||
298
+ status === "cancelled"
299
+ );
300
+ }
301
+
302
+ // --- The session -------------------------------------------------------------
303
+
304
+ const makeCodexSession = (
305
+ task: SpawnTask,
306
+ ): Effect.Effect<SubagentSession, SpawnError, Scope.Scope> =>
307
+ Effect.gen(function* () {
308
+ const binary = resolveCodexBinary();
309
+ if (!binary) {
310
+ return yield* new SpawnError({
311
+ message: "codex executable was not found on PATH.",
312
+ });
313
+ }
314
+
315
+ const events = yield* Queue.make<SubagentEvent, Cause.Done>();
316
+ const emit = (event: SubagentEvent) => {
317
+ Queue.offerUnsafe(events, event);
318
+ };
319
+
320
+ const child = yield* Effect.try({
321
+ try: () =>
322
+ spawn(binary, ["app-server", "--stdio"], {
323
+ cwd: task.cwd,
324
+ env: process.env,
325
+ stdio: ["pipe", "pipe", "pipe"],
326
+ windowsHide: true,
327
+ // Own process group on POSIX so teardown can signal the whole
328
+ // tree: a wedged app-server must not orphan a still-running
329
+ // shell command it spawned.
330
+ detached: process.platform !== "win32",
331
+ }),
332
+ catch: (error) => new SpawnError({ message: boundedError(error) }),
333
+ });
334
+
335
+ const state = {
336
+ closed: false,
337
+ closing: false,
338
+ exited: false,
339
+ activeRun: false,
340
+ dispatching: false,
341
+ interruptRequested: false,
342
+ effort: preferredCodexEffort(task.reasoningEffort),
343
+ runSerial: 0,
344
+ activeTurnId: undefined as string | undefined,
345
+ runError: undefined as string | undefined,
346
+ finalText: "",
347
+ lastAssistantText: "",
348
+ pendingPrompts: [] as string[],
349
+ nextRequestId: 0,
350
+ stderr: "",
351
+ meta: {
352
+ backend: "codex",
353
+ modelLabel: task.model,
354
+ } satisfies SubagentMeta as SubagentMeta,
355
+ interruptTimer: undefined as ReturnType<typeof setTimeout> | undefined,
356
+ };
357
+ const pendingRequests = new Map<number, PendingRequest>();
358
+ const tools = new Map<string, ToolState>();
359
+ /** Turns locally settled by the interrupt fallback may still emit late events. */
360
+ const ignoredTurnIds = new Set<string>();
361
+
362
+ const writeMessage = (message: JsonRecord) => {
363
+ if (state.closed || !child.stdin.writable) return false;
364
+ child.stdin.write(`${JSON.stringify(message)}\n`);
365
+ return true;
366
+ };
367
+
368
+ const request = (
369
+ method: string,
370
+ params: JsonRecord,
371
+ timeoutMs = REQUEST_TIMEOUT_MS,
372
+ ) =>
373
+ new Promise<JsonRecord>((resolve, reject) => {
374
+ if (state.closed) {
375
+ reject(new Error("Codex app-server is closed."));
376
+ return;
377
+ }
378
+ const id = ++state.nextRequestId;
379
+ const timer = setTimeout(() => {
380
+ pendingRequests.delete(id);
381
+ reject(new Error(`Codex app-server request ${method} timed out.`));
382
+ }, timeoutMs);
383
+ pendingRequests.set(id, { resolve, reject, timer });
384
+ if (!writeMessage({ id, method, params })) {
385
+ clearTimeout(timer);
386
+ pendingRequests.delete(id);
387
+ reject(new Error("Codex app-server stdin is closed."));
388
+ }
389
+ });
390
+
391
+ const rejectPending = (message: string) => {
392
+ for (const pending of pendingRequests.values()) {
393
+ clearTimeout(pending.timer);
394
+ pending.reject(new Error(message));
395
+ }
396
+ pendingRequests.clear();
397
+ };
398
+
399
+ const queuedView = () =>
400
+ state.pendingPrompts.map((text) => ({
401
+ text,
402
+ kind: "follow-up" as const,
403
+ }));
404
+
405
+ const startNextQueued = () => {
406
+ if (state.closed || state.activeRun) return;
407
+ const next = state.pendingPrompts.shift();
408
+ if (next === undefined) return;
409
+ emit({ _tag: "QueueChanged", queued: queuedView() });
410
+ startRun(next);
411
+ };
412
+
413
+ const settleRun = (outcome: RunOutcome, serial = state.runSerial) => {
414
+ if (!state.activeRun || serial !== state.runSerial) return;
415
+ if (state.interruptTimer) clearTimeout(state.interruptTimer);
416
+ state.interruptTimer = undefined;
417
+ state.activeRun = false;
418
+ state.dispatching = false;
419
+ // A late turn/completed for this turn must not be misattributed to the
420
+ // next queued run (which starts with no activeTurnId to filter on).
421
+ if (state.activeTurnId) ignoredTurnIds.add(state.activeTurnId);
422
+ state.activeTurnId = undefined;
423
+ state.interruptRequested = false;
424
+ tools.clear();
425
+ emit({ _tag: "RunSettled", outcome });
426
+ queueMicrotask(startNextQueued);
427
+ };
428
+
429
+ const sendInterrupt = (serial: number) => {
430
+ const turnId = state.activeTurnId;
431
+ const threadId = state.meta.nativeSessionId;
432
+ if (
433
+ !turnId ||
434
+ !threadId ||
435
+ !state.activeRun ||
436
+ serial !== state.runSerial
437
+ )
438
+ return;
439
+ void request(
440
+ "turn/interrupt",
441
+ { threadId, turnId },
442
+ INTERRUPT_FALLBACK_MS,
443
+ ).catch((error) => {
444
+ if (state.activeRun && serial === state.runSerial) {
445
+ emit({ _tag: "BackendError", message: boundedError(error) });
446
+ }
447
+ });
448
+ };
449
+
450
+ function startRun(text: string) {
451
+ if (state.closed || state.activeRun) return;
452
+ const threadId = state.meta.nativeSessionId;
453
+ if (!threadId) return;
454
+ const serial = ++state.runSerial;
455
+ state.activeRun = true;
456
+ state.dispatching = true;
457
+ state.interruptRequested = false;
458
+ state.activeTurnId = undefined;
459
+ state.runError = undefined;
460
+ state.finalText = "";
461
+ state.lastAssistantText = "";
462
+ emit({ _tag: "UserMessage", text });
463
+ emit({ _tag: "RunStarted" });
464
+
465
+ const params: JsonRecord = {
466
+ threadId,
467
+ input: [textInput(text)],
468
+ ...(state.effort ? { effort: state.effort } : {}),
469
+ };
470
+ void request("turn/start", params).then(
471
+ (result) => {
472
+ const turn = record(result.turn);
473
+ const turnId = stringValue(turn?.id);
474
+ if (!state.activeRun || serial !== state.runSerial) {
475
+ if (turnId) {
476
+ // The run was already settled locally (interrupt fallback or
477
+ // failure), so whatever native turn this response describes is
478
+ // invisible work — stop it unconditionally.
479
+ ignoredTurnIds.add(turnId);
480
+ void request(
481
+ "turn/interrupt",
482
+ { threadId, turnId },
483
+ INTERRUPT_FALLBACK_MS,
484
+ ).catch(() => undefined);
485
+ }
486
+ return;
487
+ }
488
+ state.dispatching = false;
489
+ state.activeTurnId = turnId ?? state.activeTurnId;
490
+ if (state.interruptRequested) sendInterrupt(serial);
491
+ },
492
+ (error) => {
493
+ if (!state.activeRun || serial !== state.runSerial) return;
494
+ const errorText = boundedError(error);
495
+ settleRun(
496
+ state.interruptRequested
497
+ ? {
498
+ _tag: "Interrupted",
499
+ partialText: state.finalText || undefined,
500
+ }
501
+ : {
502
+ _tag: "Failed",
503
+ errorText,
504
+ partialText: state.finalText || undefined,
505
+ },
506
+ serial,
507
+ );
508
+ // A timed-out turn/start means a turn may be running that we can
509
+ // never see or interrupt (no turn id). That session cannot be
510
+ // trusted with further work — kill it; the exit handler reports
511
+ // the death. Explicit protocol rejections keep the session alive.
512
+ if (errorText.includes("timed out")) {
513
+ void terminateChild(child, () => state.exited);
514
+ }
515
+ },
516
+ );
517
+ }
518
+
519
+ const emitToolStart = (item: JsonRecord) => {
520
+ const tool = toolDescription(item);
521
+ if (!tool || tools.has(tool.id)) return;
522
+ tools.set(tool.id, { name: tool.name, output: "" });
523
+ const toolPart: TranscriptPart = {
524
+ type: "toolCall",
525
+ toolId: tool.id,
526
+ name: tool.name,
527
+ argsPreview: tool.args,
528
+ };
529
+ emit({ _tag: "AssistantMessage", parts: [toolPart] });
530
+ emit({
531
+ _tag: "ToolStart",
532
+ toolId: tool.id,
533
+ name: tool.name,
534
+ argsPreview: tool.args,
535
+ });
536
+ };
537
+
538
+ const emitToolEnd = (item: JsonRecord) => {
539
+ const description = toolDescription(item);
540
+ if (!description) return;
541
+ if (!tools.has(description.id)) emitToolStart(item);
542
+ const live = tools.get(description.id);
543
+ const output = toolOutput(item, live?.output ?? "");
544
+ tools.delete(description.id);
545
+ emit({
546
+ _tag: "ToolEnd",
547
+ toolId: description.id,
548
+ name: live?.name ?? description.name,
549
+ isError: toolFailed(item),
550
+ outputPreview: firstLine(output),
551
+ });
552
+ };
553
+
554
+ const handleItemCompleted = (item: JsonRecord) => {
555
+ const type = stringValue(item.type);
556
+ if (type === "agentMessage") {
557
+ const text = stringValue(item.text) ?? "";
558
+ if (text) {
559
+ emit({ _tag: "AssistantMessage", parts: [{ type: "text", text }] });
560
+ state.lastAssistantText = text;
561
+ if (stringValue(item.phase) === "final_answer")
562
+ state.finalText = text;
563
+ }
564
+ return;
565
+ }
566
+ if (type === "reasoning") {
567
+ const thinking = [
568
+ ...strings(item.summary),
569
+ ...strings(item.content),
570
+ ].join("\n");
571
+ if (thinking) {
572
+ emit({
573
+ _tag: "AssistantMessage",
574
+ parts: [{ type: "thinking", text: thinking }],
575
+ });
576
+ }
577
+ return;
578
+ }
579
+ emitToolEnd(item);
580
+ };
581
+
582
+ const handleNotification = (message: JsonRecord) => {
583
+ if (state.closed) return;
584
+ const method = stringValue(message.method);
585
+ const params = record(message.params) ?? {};
586
+ const notificationTurn = record(params.turn);
587
+ const turnId =
588
+ stringValue(params.turnId) ?? stringValue(notificationTurn?.id);
589
+ if (turnId && ignoredTurnIds.has(turnId)) return;
590
+ const belongsToRun =
591
+ method === "error" ||
592
+ method?.startsWith("turn/") === true ||
593
+ method?.startsWith("item/") === true ||
594
+ method === "thread/tokenUsage/updated";
595
+ if (belongsToRun && !state.activeRun) {
596
+ if (turnId) ignoredTurnIds.add(turnId);
597
+ return;
598
+ }
599
+ if (
600
+ belongsToRun &&
601
+ turnId &&
602
+ state.activeTurnId &&
603
+ turnId !== state.activeTurnId
604
+ ) {
605
+ return;
606
+ }
607
+ switch (method) {
608
+ case "thread/started": {
609
+ const thread = record(params.thread);
610
+ const id = stringValue(thread?.id);
611
+ const sessionFilePath = stringValue(thread?.path);
612
+ if (id) state.meta = { ...state.meta, nativeSessionId: id };
613
+ if (sessionFilePath) state.meta = { ...state.meta, sessionFilePath };
614
+ emit({ _tag: "MetaChanged", meta: state.meta });
615
+ break;
616
+ }
617
+ case "thread/settings/updated": {
618
+ const settings = record(params.threadSettings);
619
+ const modelLabel = stringValue(settings?.model);
620
+ if (modelLabel) {
621
+ state.meta = { ...state.meta, modelLabel };
622
+ emit({ _tag: "MetaChanged", meta: { modelLabel } });
623
+ }
624
+ break;
625
+ }
626
+ case "model/rerouted": {
627
+ const modelLabel = stringValue(params.toModel);
628
+ if (modelLabel) {
629
+ state.meta = { ...state.meta, modelLabel };
630
+ emit({ _tag: "MetaChanged", meta: { modelLabel } });
631
+ }
632
+ break;
633
+ }
634
+ case "turn/started": {
635
+ const turn = record(params.turn);
636
+ const startedId = stringValue(turn?.id);
637
+ // Only adopt a turn we are actually waiting on. A stale start from
638
+ // a run the interrupt fallback settled before its turn/start
639
+ // response arrived would otherwise capture activeTurnId and filter
640
+ // out every event of the real next turn.
641
+ if (!state.dispatching && startedId !== state.activeTurnId) {
642
+ if (startedId) ignoredTurnIds.add(startedId);
643
+ break;
644
+ }
645
+ state.activeTurnId = startedId ?? state.activeTurnId;
646
+ state.dispatching = false;
647
+ emit({ _tag: "RunStarted" });
648
+ if (state.interruptRequested) sendInterrupt(state.runSerial);
649
+ break;
650
+ }
651
+ case "item/agentMessage/delta": {
652
+ const delta = stringValue(params.delta);
653
+ if (delta) emit({ _tag: "AssistantDelta", kind: "text", delta });
654
+ break;
655
+ }
656
+ case "item/reasoning/summaryTextDelta":
657
+ case "item/reasoning/textDelta": {
658
+ const delta = stringValue(params.delta);
659
+ if (delta) emit({ _tag: "AssistantDelta", kind: "thinking", delta });
660
+ break;
661
+ }
662
+ case "item/started": {
663
+ const item = record(params.item);
664
+ if (item) emitToolStart(item);
665
+ break;
666
+ }
667
+ case "item/completed": {
668
+ const item = record(params.item);
669
+ if (item) handleItemCompleted(item);
670
+ break;
671
+ }
672
+ case "item/commandExecution/outputDelta":
673
+ case "item/fileChange/outputDelta": {
674
+ const id = stringValue(params.itemId);
675
+ const delta = stringValue(params.delta);
676
+ const tool = id ? tools.get(id) : undefined;
677
+ if (id && tool && delta) {
678
+ tool.output = `${tool.output}${delta}`.slice(-16_384);
679
+ emit({
680
+ _tag: "ToolUpdate",
681
+ toolId: id,
682
+ outputPreview: firstLine(tool.output),
683
+ });
684
+ }
685
+ break;
686
+ }
687
+ case "item/fileChange/patchUpdated": {
688
+ const id = stringValue(params.itemId);
689
+ if (id) {
690
+ emit({
691
+ _tag: "ToolUpdate",
692
+ toolId: id,
693
+ outputPreview: fileChangePreview({ changes: params.changes }),
694
+ });
695
+ }
696
+ break;
697
+ }
698
+ case "item/mcpToolCall/progress": {
699
+ const id = stringValue(params.itemId);
700
+ if (id) {
701
+ emit({
702
+ _tag: "ToolUpdate",
703
+ toolId: id,
704
+ outputPreview: firstLine(params.message),
705
+ });
706
+ }
707
+ break;
708
+ }
709
+ case "thread/tokenUsage/updated": {
710
+ const { tokens, contextWindow } = parseThreadTokenUsage(params);
711
+ if (contextWindow !== undefined) {
712
+ state.meta = { ...state.meta, contextWindow };
713
+ emit({ _tag: "MetaChanged", meta: { contextWindow } });
714
+ }
715
+ emit({ _tag: "UsageChanged", tokens, contextWindow });
716
+ break;
717
+ }
718
+ case "error": {
719
+ const error = record(params.error);
720
+ const messageText = boundedError(
721
+ stringValue(error?.message) ?? "Codex run failed",
722
+ );
723
+ if (params.willRetry !== true) state.runError = messageText;
724
+ emit({ _tag: "BackendError", message: messageText });
725
+ break;
726
+ }
727
+ case "turn/completed": {
728
+ const turn = record(params.turn);
729
+ const status = stringValue(turn?.status);
730
+ const error = record(turn?.error);
731
+ const partialText =
732
+ state.finalText || state.lastAssistantText || undefined;
733
+ if (state.interruptRequested || status === "interrupted") {
734
+ settleRun({ _tag: "Interrupted", partialText });
735
+ } else if (status === "failed") {
736
+ settleRun({
737
+ _tag: "Failed",
738
+ errorText: boundedError(
739
+ state.runError ??
740
+ stringValue(error?.message) ??
741
+ "Codex run failed",
742
+ ),
743
+ partialText,
744
+ });
745
+ } else {
746
+ settleRun({
747
+ _tag: "Completed",
748
+ finalText: state.finalText || state.lastAssistantText,
749
+ });
750
+ }
751
+ break;
752
+ }
753
+ }
754
+ };
755
+
756
+ const handleServerRequest = (message: JsonRecord) => {
757
+ const id = message.id;
758
+ if (typeof id !== "number" && typeof id !== "string") return;
759
+ const method = stringValue(message.method);
760
+ if (
761
+ method === "item/commandExecution/requestApproval" ||
762
+ method === "item/fileChange/requestApproval"
763
+ ) {
764
+ writeMessage({ id, result: { decision: "decline" } });
765
+ return;
766
+ }
767
+ writeMessage({
768
+ id,
769
+ error: {
770
+ code: -32601,
771
+ message: `Unsupported headless server request: ${method ?? "unknown"}`,
772
+ },
773
+ });
774
+ };
775
+
776
+ const handleLine = (line: string) => {
777
+ if (!line.trim()) return;
778
+ let parsed: unknown;
779
+ try {
780
+ parsed = JSON.parse(line);
781
+ } catch {
782
+ emit({
783
+ _tag: "BackendError",
784
+ message: `Invalid Codex protocol line: ${line.slice(0, 512)}`,
785
+ });
786
+ return;
787
+ }
788
+ const message = record(parsed);
789
+ if (!message) return;
790
+ const id = numberValue(message.id);
791
+ if (id !== undefined && pendingRequests.has(id)) {
792
+ const pending = pendingRequests.get(id);
793
+ if (!pending) return;
794
+ pendingRequests.delete(id);
795
+ clearTimeout(pending.timer);
796
+ if (message.error !== undefined)
797
+ pending.reject(new Error(protocolError(message.error)));
798
+ else pending.resolve(record(message.result) ?? {});
799
+ return;
800
+ }
801
+ if (message.id !== undefined && message.method !== undefined)
802
+ handleServerRequest(message);
803
+ else if (message.method !== undefined) handleNotification(message);
804
+ };
805
+
806
+ const failForProcessExit = (detail: string) => {
807
+ if (state.exited) return;
808
+ state.exited = true;
809
+ rejectPending(detail);
810
+ if (state.closing) return;
811
+ state.closed = true;
812
+ state.pendingPrompts = [];
813
+ emit({ _tag: "QueueChanged", queued: [] });
814
+ if (state.activeRun) {
815
+ settleRun({
816
+ _tag: "Failed",
817
+ errorText: boundedError(detail),
818
+ partialText: state.finalText || state.lastAssistantText || undefined,
819
+ });
820
+ }
821
+ Queue.endUnsafe(events);
822
+ };
823
+
824
+ let stdoutBuffer = "";
825
+ child.stdout.setEncoding("utf8");
826
+ child.stdout.on("data", (chunk: string) => {
827
+ stdoutBuffer += chunk;
828
+ while (true) {
829
+ const newline = stdoutBuffer.indexOf("\n");
830
+ if (newline < 0) break;
831
+ const line = stdoutBuffer.slice(0, newline).replace(/\r$/, "");
832
+ stdoutBuffer = stdoutBuffer.slice(newline + 1);
833
+ handleLine(line);
834
+ }
835
+ if (stdoutBuffer.length > STDOUT_BUFFER_MAX_BYTES) {
836
+ // A frame this large with no newline is protocol corruption, and an
837
+ // unbounded buffer is a memory leak. Session-fatal: the exit handler
838
+ // settles any active run.
839
+ stdoutBuffer = "";
840
+ void terminateChild(child, () => state.exited);
841
+ }
842
+ });
843
+ child.stderr.setEncoding("utf8");
844
+ child.stderr.on("data", (chunk: string) => {
845
+ state.stderr = `${state.stderr}${chunk}`.slice(-4096);
846
+ });
847
+ child.once("error", (error) =>
848
+ failForProcessExit(`Codex app-server failed: ${boundedError(error)}`),
849
+ );
850
+ child.once("exit", (code, signal) => {
851
+ const suffix = firstLine(state.stderr);
852
+ failForProcessExit(
853
+ `Codex app-server exited (${signal ?? `code ${code ?? "unknown"}`})${suffix ? `: ${suffix}` : ""}`,
854
+ );
855
+ });
856
+
857
+ yield* Effect.addFinalizer(() =>
858
+ Effect.promise(async () => {
859
+ if (state.closing) return;
860
+ state.closing = true;
861
+ if (state.interruptTimer) clearTimeout(state.interruptTimer);
862
+ // Settle before marking closed so the run gets the correct
863
+ // "Interrupted" outcome instead of the pump's generic fallback.
864
+ if (state.activeRun) {
865
+ settleRun({
866
+ _tag: "Interrupted",
867
+ partialText:
868
+ state.finalText || state.lastAssistantText || undefined,
869
+ });
870
+ }
871
+ state.closed = true;
872
+ rejectPending("Codex session closed.");
873
+ await terminateChild(child, () => state.exited);
874
+ Queue.endUnsafe(events);
875
+ }),
876
+ );
877
+
878
+ const threadResult = yield* Effect.tryPromise({
879
+ try: async () => {
880
+ await request("initialize", {
881
+ clientInfo: {
882
+ name: "pi-subagents",
883
+ title: "pi subagent",
884
+ version: "2.0.0",
885
+ },
886
+ capabilities: { experimentalApi: true },
887
+ });
888
+ writeMessage({ method: "initialized" });
889
+ // Headless children cannot answer approval prompts. The caller
890
+ // already chose to launch an autonomous subagent, so give the thread
891
+ // full workspace access without interactive approval requests.
892
+ return request("thread/start", {
893
+ cwd: task.cwd,
894
+ approvalPolicy: "never",
895
+ sandbox: "danger-full-access",
896
+ ephemeral: false,
897
+ ...(task.model ? { model: task.model } : {}),
898
+ });
899
+ },
900
+ catch: (error) => new SpawnError({ message: boundedError(error) }),
901
+ });
902
+
903
+ const thread = record(threadResult.thread);
904
+ const nativeSessionId = stringValue(thread?.id);
905
+ if (!nativeSessionId) {
906
+ return yield* new SpawnError({
907
+ message: "Codex thread/start returned no thread id.",
908
+ });
909
+ }
910
+ state.meta = {
911
+ backend: "codex",
912
+ modelLabel: stringValue(threadResult.model) ?? task.model,
913
+ sessionFilePath: stringValue(thread?.path),
914
+ nativeSessionId,
915
+ };
916
+ if (task.reasoningEffort) {
917
+ // Optional capability probe: never let a slow/unsupported model/list
918
+ // hold up the spawn (and its concurrency reservation) for the full
919
+ // request timeout; the unclamped preferred effort is a fine fallback.
920
+ const modelList = yield* Effect.tryPromise(() =>
921
+ request("model/list", { includeHidden: true }, MODEL_LIST_TIMEOUT_MS),
922
+ ).pipe(Effect.orElseSucceed(() => undefined));
923
+ state.effort = supportedCodexEffort(
924
+ task.reasoningEffort,
925
+ state.meta.modelLabel,
926
+ modelList,
927
+ );
928
+ }
929
+ emit({ _tag: "MetaChanged", meta: state.meta });
930
+ startRun(task.prompt);
931
+
932
+ return {
933
+ meta: Effect.sync(() => state.meta),
934
+ events: Stream.fromQueue(events),
935
+ send: (text) =>
936
+ Effect.suspend((): Effect.Effect<void, SendError> => {
937
+ if (state.closed) {
938
+ return new SendError({ message: "Subagent session is closed." });
939
+ }
940
+ if (state.activeRun) {
941
+ state.pendingPrompts.push(text);
942
+ emit({ _tag: "QueueChanged", queued: queuedView() });
943
+ return Effect.void;
944
+ }
945
+ return Effect.sync(() => startRun(text));
946
+ }),
947
+ interrupt: Effect.promise(async () => {
948
+ if (state.closed || !state.activeRun) return;
949
+ const serial = state.runSerial;
950
+ state.pendingPrompts = [];
951
+ emit({ _tag: "QueueChanged", queued: [] });
952
+ state.interruptRequested = true;
953
+ sendInterrupt(serial);
954
+ if (state.interruptTimer) clearTimeout(state.interruptTimer);
955
+ state.interruptTimer = setTimeout(() => {
956
+ if (state.activeRun && serial === state.runSerial) {
957
+ if (state.activeTurnId) ignoredTurnIds.add(state.activeTurnId);
958
+ settleRun({
959
+ _tag: "Interrupted",
960
+ partialText:
961
+ state.finalText || state.lastAssistantText || undefined,
962
+ });
963
+ // The server never acknowledged the interrupt, so the native
964
+ // turn may still be executing tools. A session that ignores
965
+ // interrupts cannot be trusted — kill it rather than let
966
+ // invisible work continue behind a "settled" run.
967
+ void terminateChild(child, () => state.exited);
968
+ }
969
+ }, INTERRUPT_FALLBACK_MS);
970
+ }),
971
+ } satisfies SubagentSession;
972
+ });
973
+
974
+ /** Signal the whole process group on POSIX so tool descendants (shell
975
+ * commands the app-server spawned) die with it; a wedged or force-killed
976
+ * server must not orphan a still-running command in the workspace. */
977
+ function killTree(
978
+ child: ChildProcessWithoutNullStreams,
979
+ signal: NodeJS.Signals,
980
+ ) {
981
+ if (process.platform === "win32" && child.pid) {
982
+ try {
983
+ const killer = spawn(
984
+ "taskkill",
985
+ [
986
+ "/pid",
987
+ String(child.pid),
988
+ "/T",
989
+ ...(signal === "SIGKILL" ? ["/F"] : []),
990
+ ],
991
+ { stdio: "ignore", windowsHide: true },
992
+ );
993
+ const killDirect = () => {
994
+ try {
995
+ child.kill(signal);
996
+ } catch {
997
+ // Process may already be gone.
998
+ }
999
+ };
1000
+ killer.once("error", killDirect);
1001
+ killer.once("exit", (code) => {
1002
+ if (code !== 0) killDirect();
1003
+ });
1004
+ killer.unref();
1005
+ return;
1006
+ } catch {
1007
+ // Fall through to a direct signal when taskkill cannot be launched.
1008
+ }
1009
+ }
1010
+ if (process.platform !== "win32" && child.pid) {
1011
+ try {
1012
+ process.kill(-child.pid, signal);
1013
+ return;
1014
+ } catch {
1015
+ // Group may already be gone; fall through to the direct signal.
1016
+ }
1017
+ }
1018
+ try {
1019
+ child.kill(signal);
1020
+ } catch {
1021
+ // Process may already be gone.
1022
+ }
1023
+ }
1024
+
1025
+ /** SIGTERM is normally enough; the second deadline covers a wedged Rust process. */
1026
+ function terminateChild(
1027
+ child: ChildProcessWithoutNullStreams,
1028
+ exited: () => boolean,
1029
+ ) {
1030
+ if (exited()) return Promise.resolve();
1031
+ return new Promise<void>((resolve) => {
1032
+ let done = false;
1033
+ let forceTimer: ReturnType<typeof setTimeout> | undefined;
1034
+ let lastTimer: ReturnType<typeof setTimeout> | undefined;
1035
+ const finish = () => {
1036
+ if (done) return;
1037
+ done = true;
1038
+ if (forceTimer) clearTimeout(forceTimer);
1039
+ if (lastTimer) clearTimeout(lastTimer);
1040
+ resolve();
1041
+ };
1042
+ child.once("exit", finish);
1043
+ killTree(child, "SIGTERM");
1044
+ forceTimer = setTimeout(() => {
1045
+ if (!exited()) killTree(child, "SIGKILL");
1046
+ }, FORCE_KILL_AFTER_MS);
1047
+ lastTimer = setTimeout(finish, FORCE_KILL_AFTER_MS + 500);
1048
+ });
1049
+ }
1050
+
1051
+ export const codexBackend: SubagentBackend = {
1052
+ name: "codex",
1053
+ capabilities: {
1054
+ steering: false,
1055
+ modelSelection: true,
1056
+ reasoningEffort: true,
1057
+ },
1058
+ available: Effect.sync(() => resolveCodexBinary() !== undefined),
1059
+ spawn: makeCodexSession,
1060
+ };