@asterxsk/kiln 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (491) hide show
  1. package/README.md +155 -170
  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 +4 -0
  6. package/agent/extensions/ask-user/install.sh +3 -0
  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 +4 -0
  14. package/agent/extensions/background-terminals/install.sh +3 -0
  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/install.ps1 +4 -0
  32. package/agent/extensions/destructive/install.sh +3 -0
  33. package/agent/extensions/file-search/index.spec.ts +443 -443
  34. package/agent/extensions/file-search/index.ts +459 -459
  35. package/agent/extensions/file-search/install.ps1 +4 -0
  36. package/agent/extensions/file-search/install.sh +3 -0
  37. package/agent/extensions/file-search/package-lock.json +2253 -2253
  38. package/agent/extensions/file-search/package.json +23 -23
  39. package/agent/extensions/file-search/src/args.ts +122 -122
  40. package/agent/extensions/file-search/src/binaries.ts +422 -422
  41. package/agent/extensions/file-search/src/output.ts +126 -126
  42. package/agent/extensions/file-search/src/process.ts +146 -146
  43. package/agent/extensions/file-search/src/prompt.ts +52 -52
  44. package/agent/extensions/file-search/tsconfig.json +7 -7
  45. package/agent/extensions/goal/install.ps1 +4 -0
  46. package/agent/extensions/goal/install.sh +3 -0
  47. package/agent/extensions/herdr-agent-state.ts +257 -0
  48. package/agent/extensions/kiln-update/README.md +25 -0
  49. package/agent/extensions/kiln-update/index.ts +99 -0
  50. package/agent/extensions/kiln-update/install.ps1 +27 -0
  51. package/agent/extensions/kiln-update/install.sh +24 -0
  52. package/agent/extensions/modelconf/PLAN.md +915 -915
  53. package/agent/extensions/modelconf/index.ts +296 -296
  54. package/agent/extensions/modelconf/install.ps1 +4 -0
  55. package/agent/extensions/modelconf/install.sh +3 -0
  56. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  57. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  58. package/agent/extensions/pi-web-access/LICENSE +21 -21
  59. package/agent/extensions/pi-web-access/README.md +470 -470
  60. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  61. package/agent/extensions/pi-web-access/activity.ts +101 -101
  62. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  63. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  64. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  65. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  66. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  67. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  68. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  69. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  70. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  71. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  72. package/agent/extensions/pi-web-access/exa.ts +526 -526
  73. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  74. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  75. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  76. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  77. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  78. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  79. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  80. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  81. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  82. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  83. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  84. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  85. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  86. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  87. package/agent/extensions/pi-web-access/package.json +64 -64
  88. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  89. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  90. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  91. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  92. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  93. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  94. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  95. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  96. package/agent/extensions/pi-web-access/storage.ts +521 -521
  97. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  98. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  99. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  100. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  101. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  102. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  103. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  104. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  105. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  106. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  107. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  108. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  109. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  110. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  111. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  112. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  113. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  114. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  115. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  116. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  117. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  118. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  119. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  120. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  121. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  122. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  123. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  124. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  125. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  126. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  127. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  128. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  129. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  130. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  131. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  132. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  133. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  134. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  135. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  136. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  137. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  138. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  139. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  140. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  141. package/agent/extensions/pi-web-access/utils.ts +451 -451
  142. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  143. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  144. package/agent/extensions/shared/activity-status.ts +31 -31
  145. package/agent/extensions/shared/child-session.test.ts +270 -270
  146. package/agent/extensions/shared/child-session.ts +148 -148
  147. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  148. package/agent/extensions/shared/context-utilization.ts +47 -47
  149. package/agent/extensions/shared/dashboard-state.ts +99 -99
  150. package/agent/extensions/shared/install.ps1 +4 -0
  151. package/agent/extensions/shared/install.sh +3 -0
  152. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  153. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  154. package/agent/extensions/skillsconf/install.ps1 +4 -0
  155. package/agent/extensions/skillsconf/install.sh +3 -0
  156. package/agent/extensions/statusline/index.ts +282 -0
  157. package/agent/extensions/statusline/install.ps1 +27 -0
  158. package/agent/extensions/statusline/install.sh +24 -0
  159. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  160. package/agent/extensions/subagents/claude.test.ts +119 -119
  161. package/agent/extensions/subagents/codex.test.ts +102 -102
  162. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  163. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  164. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  165. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  166. package/agent/extensions/subagents/index.ts +779 -779
  167. package/agent/extensions/subagents/install.ps1 +4 -0
  168. package/agent/extensions/subagents/install.sh +3 -0
  169. package/agent/extensions/subagents/manager.test.ts +276 -276
  170. package/agent/extensions/subagents/package-lock.json +2244 -2244
  171. package/agent/extensions/subagents/package.json +19 -19
  172. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  173. package/agent/extensions/subagents/src/backend.ts +73 -73
  174. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  175. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  176. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  177. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  178. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  179. package/agent/extensions/subagents/src/domain.ts +253 -253
  180. package/agent/extensions/subagents/src/format.ts +74 -74
  181. package/agent/extensions/subagents/src/manager.ts +736 -736
  182. package/agent/extensions/subagents/src/prompt.ts +92 -92
  183. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  184. package/agent/extensions/subagents/src/runtime.ts +53 -53
  185. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  186. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  187. package/agent/extensions/subagents/takeover.test.ts +29 -29
  188. package/agent/extensions/subagents/tsconfig.json +7 -7
  189. package/agent/extensions/taste/install.ps1 +4 -0
  190. package/agent/extensions/taste/install.sh +3 -0
  191. package/agent/extensions/todo/AGENTS.md +38 -38
  192. package/agent/extensions/todo/LICENSE +21 -21
  193. package/agent/extensions/todo/config.ts +55 -55
  194. package/agent/extensions/todo/index.ts +151 -151
  195. package/agent/extensions/todo/install.ps1 +4 -0
  196. package/agent/extensions/todo/install.sh +3 -0
  197. package/agent/extensions/todo/locales/de.json +17 -17
  198. package/agent/extensions/todo/locales/en.json +15 -15
  199. package/agent/extensions/todo/locales/es.json +17 -17
  200. package/agent/extensions/todo/locales/fr.json +17 -17
  201. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  202. package/agent/extensions/todo/locales/pt.json +17 -17
  203. package/agent/extensions/todo/locales/ru.json +17 -17
  204. package/agent/extensions/todo/locales/uk.json +17 -17
  205. package/agent/extensions/todo/locales/zh.json +17 -17
  206. package/agent/extensions/todo/package-lock.json +3358 -3358
  207. package/agent/extensions/todo/package.json +67 -67
  208. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  209. package/agent/extensions/todo/state/invariants.ts +20 -20
  210. package/agent/extensions/todo/state/replay.ts +38 -38
  211. package/agent/extensions/todo/state/selectors.ts +107 -107
  212. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  213. package/agent/extensions/todo/state/state.ts +18 -18
  214. package/agent/extensions/todo/state/store.ts +82 -82
  215. package/agent/extensions/todo/state/task-graph.ts +57 -57
  216. package/agent/extensions/todo/todo-overlay.ts +200 -200
  217. package/agent/extensions/todo/todo.ts +155 -155
  218. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  219. package/agent/extensions/todo/tool/types.ts +206 -206
  220. package/agent/extensions/todo/view/format.ts +177 -177
  221. package/agent/extensions/trim-context/install.ps1 +4 -0
  222. package/agent/extensions/trim-context/install.sh +3 -0
  223. package/agent/keybindings.json +7 -7
  224. package/agent/version.txt +1 -0
  225. package/agent.bak.20260905-190020/AGENTS.md +67 -0
  226. package/agent.bak.20260905-190020/README.md +5 -0
  227. package/agent.bak.20260905-190020/extensions/ask-user/index.ts +418 -0
  228. package/agent.bak.20260905-190020/extensions/ask-user/package-lock.json +769 -0
  229. package/agent.bak.20260905-190020/extensions/ask-user/package.json +19 -0
  230. package/agent.bak.20260905-190020/extensions/ask-user/prompt.ts +45 -0
  231. package/agent.bak.20260905-190020/extensions/ask-user/tsconfig.json +7 -0
  232. package/agent.bak.20260905-190020/extensions/background-terminals/docs/implementation-guide.md +942 -0
  233. package/agent.bak.20260905-190020/extensions/background-terminals/index.ts +629 -0
  234. package/agent.bak.20260905-190020/extensions/background-terminals/install.ps1 +23 -0
  235. package/agent.bak.20260905-190020/extensions/background-terminals/install.sh +21 -0
  236. package/agent.bak.20260905-190020/extensions/background-terminals/package-lock.json +769 -0
  237. package/agent.bak.20260905-190020/extensions/background-terminals/package.json +17 -0
  238. package/agent.bak.20260905-190020/extensions/background-terminals/src/domain.ts +87 -0
  239. package/agent.bak.20260905-190020/extensions/background-terminals/src/manager.ts +907 -0
  240. package/agent.bak.20260905-190020/extensions/background-terminals/src/output.ts +84 -0
  241. package/agent.bak.20260905-190020/extensions/background-terminals/src/prompt.ts +142 -0
  242. package/agent.bak.20260905-190020/extensions/background-terminals/src/result-delivery.ts +27 -0
  243. package/agent.bak.20260905-190020/extensions/background-terminals/src/runtime.ts +36 -0
  244. package/agent.bak.20260905-190020/extensions/background-terminals/src/ui/output-view.ts +79 -0
  245. package/agent.bak.20260905-190020/extensions/background-terminals/src/ui/ps.ts +621 -0
  246. package/agent.bak.20260905-190020/extensions/background-terminals/src/widget-order.ts +121 -0
  247. package/agent.bak.20260905-190020/extensions/background-terminals/test/manager.test.ts +735 -0
  248. package/agent.bak.20260905-190020/extensions/background-terminals/test/output.test.ts +109 -0
  249. package/agent.bak.20260905-190020/extensions/background-terminals/test/prompt.test.ts +125 -0
  250. package/agent.bak.20260905-190020/extensions/background-terminals/test/ps.test.ts +82 -0
  251. package/agent.bak.20260905-190020/extensions/background-terminals/test/result-delivery.test.ts +44 -0
  252. package/agent.bak.20260905-190020/extensions/background-terminals/tsconfig.json +7 -0
  253. package/agent.bak.20260905-190020/extensions/destructive/README.md +34 -0
  254. package/agent.bak.20260905-190020/extensions/destructive/index.ts +124 -0
  255. package/agent.bak.20260905-190020/extensions/destructive/install.ps1 +23 -0
  256. package/agent.bak.20260905-190020/extensions/destructive/install.sh +21 -0
  257. package/agent.bak.20260905-190020/extensions/file-search/index.ts +459 -0
  258. package/agent.bak.20260905-190020/extensions/file-search/install.ps1 +23 -0
  259. package/agent.bak.20260905-190020/extensions/file-search/install.sh +21 -0
  260. package/agent.bak.20260905-190020/extensions/file-search/package-lock.json +2253 -0
  261. package/agent.bak.20260905-190020/extensions/file-search/package.json +23 -0
  262. package/agent.bak.20260905-190020/extensions/file-search/src/args.ts +122 -0
  263. package/agent.bak.20260905-190020/extensions/file-search/src/binaries.ts +422 -0
  264. package/agent.bak.20260905-190020/extensions/file-search/src/output.ts +126 -0
  265. package/agent.bak.20260905-190020/extensions/file-search/src/process.ts +146 -0
  266. package/agent.bak.20260905-190020/extensions/file-search/src/prompt.ts +52 -0
  267. package/agent.bak.20260905-190020/extensions/file-search/test/index.spec.ts +443 -0
  268. package/agent.bak.20260905-190020/extensions/file-search/tsconfig.json +7 -0
  269. package/agent.bak.20260905-190020/extensions/goal/README.md +50 -0
  270. package/agent.bak.20260905-190020/extensions/goal/index.ts +155 -0
  271. package/agent.bak.20260905-190020/extensions/goal/install.ps1 +23 -0
  272. package/agent.bak.20260905-190020/extensions/goal/install.sh +21 -0
  273. package/agent.bak.20260905-190020/extensions/kiln-update/README.md +25 -0
  274. package/agent.bak.20260905-190020/extensions/kiln-update/index.ts +99 -0
  275. package/agent.bak.20260905-190020/extensions/kiln-update/install.ps1 +23 -0
  276. package/agent.bak.20260905-190020/extensions/kiln-update/install.sh +21 -0
  277. package/agent.bak.20260905-190020/extensions/modelconf/PLAN.md +915 -0
  278. package/agent.bak.20260905-190020/extensions/modelconf/README.md +66 -0
  279. package/agent.bak.20260905-190020/extensions/modelconf/index.ts +296 -0
  280. package/agent.bak.20260905-190020/extensions/modelconf/install.ps1 +23 -0
  281. package/agent.bak.20260905-190020/extensions/modelconf/install.sh +21 -0
  282. package/agent.bak.20260905-190020/extensions/modelconf/package-lock.json +1809 -0
  283. package/agent.bak.20260905-190020/extensions/modelconf/package.json +13 -0
  284. package/agent.bak.20260905-190020/extensions/modelconf/src/fuzzy.ts +26 -0
  285. package/agent.bak.20260905-190020/extensions/modelconf/src/glob.ts +13 -0
  286. package/agent.bak.20260905-190020/extensions/modelconf/src/persistence.test.ts +46 -0
  287. package/agent.bak.20260905-190020/extensions/modelconf/src/persistence.ts +164 -0
  288. package/agent.bak.20260905-190020/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -0
  289. package/agent.bak.20260905-190020/extensions/modelconf/src/ui/ModelConfView.ts +1101 -0
  290. package/agent.bak.20260905-190020/extensions/modelconf/tsconfig.json +15 -0
  291. package/agent.bak.20260905-190020/extensions/pi-web-access/CHANGELOG.md +690 -0
  292. package/agent.bak.20260905-190020/extensions/pi-web-access/LICENSE +21 -0
  293. package/agent.bak.20260905-190020/extensions/pi-web-access/README.md +470 -0
  294. package/agent.bak.20260905-190020/extensions/pi-web-access/SECURITY.md +5 -0
  295. package/agent.bak.20260905-190020/extensions/pi-web-access/activity.ts +101 -0
  296. package/agent.bak.20260905-190020/extensions/pi-web-access/auth-fetch.ts +148 -0
  297. package/agent.bak.20260905-190020/extensions/pi-web-access/banner.png +0 -0
  298. package/agent.bak.20260905-190020/extensions/pi-web-access/brightdata-unlocker.ts +272 -0
  299. package/agent.bak.20260905-190020/extensions/pi-web-access/chrome-cookies.ts +669 -0
  300. package/agent.bak.20260905-190020/extensions/pi-web-access/content-find.ts +139 -0
  301. package/agent.bak.20260905-190020/extensions/pi-web-access/credential-source.ts +191 -0
  302. package/agent.bak.20260905-190020/extensions/pi-web-access/data-uri-sanitize.ts +406 -0
  303. package/agent.bak.20260905-190020/extensions/pi-web-access/datalab-pdf-extract.ts +568 -0
  304. package/agent.bak.20260905-190020/extensions/pi-web-access/declared-web-links.ts +173 -0
  305. package/agent.bak.20260905-190020/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -0
  306. package/agent.bak.20260905-190020/extensions/pi-web-access/evidence/contract-probe.mjs +140 -0
  307. package/agent.bak.20260905-190020/extensions/pi-web-access/exa.ts +526 -0
  308. package/agent.bak.20260905-190020/extensions/pi-web-access/extract.ts +1196 -0
  309. package/agent.bak.20260905-190020/extensions/pi-web-access/feature-config.ts +29 -0
  310. package/agent.bak.20260905-190020/extensions/pi-web-access/fetch-params.ts +111 -0
  311. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-adc.ts +298 -0
  312. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-api.ts +353 -0
  313. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-pdf-extract.ts +108 -0
  314. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-search.ts +21 -0
  315. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-url-context.ts +128 -0
  316. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-web-config.ts +101 -0
  317. package/agent.bak.20260905-190020/extensions/pi-web-access/gemini-web.ts +487 -0
  318. package/agent.bak.20260905-190020/extensions/pi-web-access/github-api.ts +197 -0
  319. package/agent.bak.20260905-190020/extensions/pi-web-access/github-extract.ts +746 -0
  320. package/agent.bak.20260905-190020/extensions/pi-web-access/github-issue-pr.ts +700 -0
  321. package/agent.bak.20260905-190020/extensions/pi-web-access/index.ts +1737 -0
  322. package/agent.bak.20260905-190020/extensions/pi-web-access/package-lock.json +5808 -0
  323. package/agent.bak.20260905-190020/extensions/pi-web-access/package.json +64 -0
  324. package/agent.bak.20260905-190020/extensions/pi-web-access/page-query.ts +96 -0
  325. package/agent.bak.20260905-190020/extensions/pi-web-access/pdf-extract.ts +409 -0
  326. package/agent.bak.20260905-190020/extensions/pi-web-access/pi-web-fetch-demo.mp4 +0 -0
  327. package/agent.bak.20260905-190020/extensions/pi-web-access/promise-try.d.ts +7 -0
  328. package/agent.bak.20260905-190020/extensions/pi-web-access/query-rewrite.ts +51 -0
  329. package/agent.bak.20260905-190020/extensions/pi-web-access/render-search-error.ts +170 -0
  330. package/agent.bak.20260905-190020/extensions/pi-web-access/rsc-extract.ts +338 -0
  331. package/agent.bak.20260905-190020/extensions/pi-web-access/search-types.ts +20 -0
  332. package/agent.bak.20260905-190020/extensions/pi-web-access/source-check.ts +282 -0
  333. package/agent.bak.20260905-190020/extensions/pi-web-access/ssrf-protection.ts +526 -0
  334. package/agent.bak.20260905-190020/extensions/pi-web-access/storage.ts +521 -0
  335. package/agent.bak.20260905-190020/extensions/pi-web-access/summary-model-scope.ts +125 -0
  336. package/agent.bak.20260905-190020/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -0
  337. package/agent.bak.20260905-190020/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -0
  338. package/agent.bak.20260905-190020/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -0
  339. package/agent.bak.20260905-190020/extensions/pi-web-access/test/config-path.test.mjs +283 -0
  340. package/agent.bak.20260905-190020/extensions/pi-web-access/test/content-find.test.mjs +25 -0
  341. package/agent.bak.20260905-190020/extensions/pi-web-access/test/credential-source.test.mjs +118 -0
  342. package/agent.bak.20260905-190020/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -0
  343. package/agent.bak.20260905-190020/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -0
  344. package/agent.bak.20260905-190020/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -0
  345. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -0
  346. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -0
  347. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -0
  348. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -0
  349. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -0
  350. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-params.test.mjs +86 -0
  351. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -0
  352. package/agent.bak.20260905-190020/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -0
  353. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -0
  354. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -0
  355. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -0
  356. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -0
  357. package/agent.bak.20260905-190020/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -0
  358. package/agent.bak.20260905-190020/extensions/pi-web-access/test/get-search-content.test.mjs +223 -0
  359. package/agent.bak.20260905-190020/extensions/pi-web-access/test/github-extract.test.mjs +378 -0
  360. package/agent.bak.20260905-190020/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -0
  361. package/agent.bak.20260905-190020/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -0
  362. package/agent.bak.20260905-190020/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -0
  363. package/agent.bak.20260905-190020/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -0
  364. package/agent.bak.20260905-190020/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -0
  365. package/agent.bak.20260905-190020/extensions/pi-web-access/test/page-query.test.mjs +51 -0
  366. package/agent.bak.20260905-190020/extensions/pi-web-access/test/pdf-config.test.mjs +140 -0
  367. package/agent.bak.20260905-190020/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -0
  368. package/agent.bak.20260905-190020/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -0
  369. package/agent.bak.20260905-190020/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -0
  370. package/agent.bak.20260905-190020/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -0
  371. package/agent.bak.20260905-190020/extensions/pi-web-access/test/search-error-render.test.mjs +152 -0
  372. package/agent.bak.20260905-190020/extensions/pi-web-access/test/search-providers.test.mjs +274 -0
  373. package/agent.bak.20260905-190020/extensions/pi-web-access/test/source-check.test.mjs +179 -0
  374. package/agent.bak.20260905-190020/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -0
  375. package/agent.bak.20260905-190020/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -0
  376. package/agent.bak.20260905-190020/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -0
  377. package/agent.bak.20260905-190020/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -0
  378. package/agent.bak.20260905-190020/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -0
  379. package/agent.bak.20260905-190020/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -0
  380. package/agent.bak.20260905-190020/extensions/pi-web-access/tsconfig.json +11 -0
  381. package/agent.bak.20260905-190020/extensions/pi-web-access/utils.ts +451 -0
  382. package/agent.bak.20260905-190020/extensions/pi-web-access/video-extract.ts +392 -0
  383. package/agent.bak.20260905-190020/extensions/pi-web-access/youtube-extract.ts +328 -0
  384. package/agent.bak.20260905-190020/extensions/shared/activity-status.ts +31 -0
  385. package/agent.bak.20260905-190020/extensions/shared/child-session.ts +148 -0
  386. package/agent.bak.20260905-190020/extensions/shared/context-utilization.ts +47 -0
  387. package/agent.bak.20260905-190020/extensions/shared/dashboard-state.ts +99 -0
  388. package/agent.bak.20260905-190020/extensions/shared/install.ps1 +23 -0
  389. package/agent.bak.20260905-190020/extensions/shared/install.sh +21 -0
  390. package/agent.bak.20260905-190020/extensions/shared/test/child-session.test.ts +270 -0
  391. package/agent.bak.20260905-190020/extensions/shared/test/context-utilization.test.ts +48 -0
  392. package/agent.bak.20260905-190020/extensions/shared/test/tool-call-timeout.test.ts +117 -0
  393. package/agent.bak.20260905-190020/extensions/shared/test/widget-order.test.ts +167 -0
  394. package/agent.bak.20260905-190020/extensions/shared/tool-call-timeout.ts +104 -0
  395. package/agent.bak.20260905-190020/extensions/skillsconf/README.md +74 -0
  396. package/agent.bak.20260905-190020/extensions/skillsconf/index.ts +92 -0
  397. package/agent.bak.20260905-190020/extensions/skillsconf/install.ps1 +23 -0
  398. package/agent.bak.20260905-190020/extensions/skillsconf/install.sh +21 -0
  399. package/agent.bak.20260905-190020/extensions/skillsconf/package-lock.json +1809 -0
  400. package/agent.bak.20260905-190020/extensions/skillsconf/package.json +18 -0
  401. package/agent.bak.20260905-190020/extensions/skillsconf/src/delete-skill.test.ts +64 -0
  402. package/agent.bak.20260905-190020/extensions/skillsconf/src/delete-skill.ts +45 -0
  403. package/agent.bak.20260905-190020/extensions/skillsconf/src/filter.test.ts +80 -0
  404. package/agent.bak.20260905-190020/extensions/skillsconf/src/filter.ts +74 -0
  405. package/agent.bak.20260905-190020/extensions/skillsconf/src/fuzzy.ts +26 -0
  406. package/agent.bak.20260905-190020/extensions/skillsconf/src/persistence.test.ts +72 -0
  407. package/agent.bak.20260905-190020/extensions/skillsconf/src/persistence.ts +169 -0
  408. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -0
  409. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/SkillConfView.ts +758 -0
  410. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/text-input.ts +91 -0
  411. package/agent.bak.20260905-190020/extensions/skillsconf/src/ui/tui-helpers.ts +144 -0
  412. package/agent.bak.20260905-190020/extensions/skillsconf/tsconfig.json +15 -0
  413. package/agent.bak.20260905-190020/extensions/statusline/install.ps1 +23 -0
  414. package/agent.bak.20260905-190020/extensions/statusline/install.sh +21 -0
  415. package/agent.bak.20260905-190020/extensions/subagents/docs/design-plan.md +568 -0
  416. package/agent.bak.20260905-190020/extensions/subagents/docs/effect-v4-extension-guide.md +354 -0
  417. package/agent.bak.20260905-190020/extensions/subagents/docs/effect-v4-notes.md +571 -0
  418. package/agent.bak.20260905-190020/extensions/subagents/index.ts +826 -0
  419. package/agent.bak.20260905-190020/extensions/subagents/install.ps1 +23 -0
  420. package/agent.bak.20260905-190020/extensions/subagents/install.sh +21 -0
  421. package/agent.bak.20260905-190020/extensions/subagents/package-lock.json +2244 -0
  422. package/agent.bak.20260905-190020/extensions/subagents/package.json +19 -0
  423. package/agent.bak.20260905-190020/extensions/subagents/src/backend.ts +73 -0
  424. package/agent.bak.20260905-190020/extensions/subagents/src/backends/claude.ts +701 -0
  425. package/agent.bak.20260905-190020/extensions/subagents/src/backends/codex.ts +1060 -0
  426. package/agent.bak.20260905-190020/extensions/subagents/src/backends/pi.ts +575 -0
  427. package/agent.bak.20260905-190020/extensions/subagents/src/backends/stub.ts +300 -0
  428. package/agent.bak.20260905-190020/extensions/subagents/src/by-the-way.ts +21 -0
  429. package/agent.bak.20260905-190020/extensions/subagents/src/domain.ts +253 -0
  430. package/agent.bak.20260905-190020/extensions/subagents/src/format.ts +74 -0
  431. package/agent.bak.20260905-190020/extensions/subagents/src/manager.ts +736 -0
  432. package/agent.bak.20260905-190020/extensions/subagents/src/prompt.ts +92 -0
  433. package/agent.bak.20260905-190020/extensions/subagents/src/result-delivery.ts +20 -0
  434. package/agent.bak.20260905-190020/extensions/subagents/src/runtime.ts +53 -0
  435. package/agent.bak.20260905-190020/extensions/subagents/src/ui/takeover.ts +583 -0
  436. package/agent.bak.20260905-190020/extensions/subagents/src/ui/transcript.ts +201 -0
  437. package/agent.bak.20260905-190020/extensions/subagents/src/widget-order.ts +121 -0
  438. package/agent.bak.20260905-190020/extensions/subagents/test/by-the-way.test.ts +29 -0
  439. package/agent.bak.20260905-190020/extensions/subagents/test/claude.test.ts +119 -0
  440. package/agent.bak.20260905-190020/extensions/subagents/test/codex.test.ts +102 -0
  441. package/agent.bak.20260905-190020/extensions/subagents/test/context-usage.test.ts +107 -0
  442. package/agent.bak.20260905-190020/extensions/subagents/test/manager.test.ts +276 -0
  443. package/agent.bak.20260905-190020/extensions/subagents/test/result-delivery.test.ts +27 -0
  444. package/agent.bak.20260905-190020/extensions/subagents/test/takeover.test.ts +29 -0
  445. package/agent.bak.20260905-190020/extensions/subagents/tsconfig.json +7 -0
  446. package/agent.bak.20260905-190020/extensions/taste/index.ts +443 -0
  447. package/agent.bak.20260905-190020/extensions/taste/install.ps1 +23 -0
  448. package/agent.bak.20260905-190020/extensions/taste/install.sh +21 -0
  449. package/agent.bak.20260905-190020/extensions/todo/AGENTS.md +38 -0
  450. package/agent.bak.20260905-190020/extensions/todo/LICENSE +21 -0
  451. package/agent.bak.20260905-190020/extensions/todo/config.ts +55 -0
  452. package/agent.bak.20260905-190020/extensions/todo/index.ts +151 -0
  453. package/agent.bak.20260905-190020/extensions/todo/install.ps1 +23 -0
  454. package/agent.bak.20260905-190020/extensions/todo/install.sh +21 -0
  455. package/agent.bak.20260905-190020/extensions/todo/locales/de.json +17 -0
  456. package/agent.bak.20260905-190020/extensions/todo/locales/en.json +15 -0
  457. package/agent.bak.20260905-190020/extensions/todo/locales/es.json +17 -0
  458. package/agent.bak.20260905-190020/extensions/todo/locales/fr.json +17 -0
  459. package/agent.bak.20260905-190020/extensions/todo/locales/pt-BR.json +17 -0
  460. package/agent.bak.20260905-190020/extensions/todo/locales/pt.json +17 -0
  461. package/agent.bak.20260905-190020/extensions/todo/locales/ru.json +17 -0
  462. package/agent.bak.20260905-190020/extensions/todo/locales/uk.json +17 -0
  463. package/agent.bak.20260905-190020/extensions/todo/locales/zh.json +17 -0
  464. package/agent.bak.20260905-190020/extensions/todo/package-lock.json +3358 -0
  465. package/agent.bak.20260905-190020/extensions/todo/package.json +67 -0
  466. package/agent.bak.20260905-190020/extensions/todo/state/i18n-bridge.ts +64 -0
  467. package/agent.bak.20260905-190020/extensions/todo/state/invariants.ts +20 -0
  468. package/agent.bak.20260905-190020/extensions/todo/state/replay.ts +38 -0
  469. package/agent.bak.20260905-190020/extensions/todo/state/selectors.ts +107 -0
  470. package/agent.bak.20260905-190020/extensions/todo/state/state-reducer.ts +326 -0
  471. package/agent.bak.20260905-190020/extensions/todo/state/state.ts +18 -0
  472. package/agent.bak.20260905-190020/extensions/todo/state/store.ts +82 -0
  473. package/agent.bak.20260905-190020/extensions/todo/state/task-graph.ts +57 -0
  474. package/agent.bak.20260905-190020/extensions/todo/todo-overlay.ts +204 -0
  475. package/agent.bak.20260905-190020/extensions/todo/todo.ts +155 -0
  476. package/agent.bak.20260905-190020/extensions/todo/tool/response-envelope.ts +109 -0
  477. package/agent.bak.20260905-190020/extensions/todo/tool/types.ts +206 -0
  478. package/agent.bak.20260905-190020/extensions/todo/view/format.ts +177 -0
  479. package/agent.bak.20260905-190020/extensions/todo/widget-order.ts +121 -0
  480. package/agent.bak.20260905-190020/extensions/trim-context/README.md +54 -0
  481. package/agent.bak.20260905-190020/extensions/trim-context/index.ts +487 -0
  482. package/agent.bak.20260905-190020/extensions/trim-context/install.ps1 +23 -0
  483. package/agent.bak.20260905-190020/extensions/trim-context/install.sh +21 -0
  484. package/agent.bak.20260905-190020/keybindings.json +7 -0
  485. package/bin/kiln.js +588 -358
  486. package/package.json +27 -21
  487. package/agent/install.ps1 +0 -527
  488. package/agent/install.sh +0 -511
  489. /package/{agent/extensions/status line → agent.bak.20260905-190020/extensions/ask-user}/install.ps1 +0 -0
  490. /package/{agent/extensions/status line → agent.bak.20260905-190020/extensions/ask-user}/install.sh +0 -0
  491. /package/{agent/extensions/status line → agent.bak.20260905-190020/extensions/statusline}/index.ts +0 -0
@@ -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
+ };