@skillcdn/console 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (415) hide show
  1. package/README.md +7 -7
  2. package/dist/agent-page.d.ts.map +1 -1
  3. package/dist/agent-page.js +58 -35
  4. package/dist/agent-page.js.map +1 -1
  5. package/dist/agent-usage.d.ts +51 -0
  6. package/dist/agent-usage.d.ts.map +1 -0
  7. package/dist/agent-usage.js +77 -0
  8. package/dist/agent-usage.js.map +1 -0
  9. package/dist/api.d.ts +4 -2
  10. package/dist/api.d.ts.map +1 -1
  11. package/dist/api.js +4 -2
  12. package/dist/api.js.map +1 -1
  13. package/dist/cli/cli.d.ts +9 -2
  14. package/dist/cli/cli.d.ts.map +1 -1
  15. package/dist/cli/cli.js +491 -125
  16. package/dist/cli/cli.js.map +1 -1
  17. package/dist/cli/format.d.ts +46 -4
  18. package/dist/cli/format.d.ts.map +1 -1
  19. package/dist/cli/format.js +163 -45
  20. package/dist/cli/format.js.map +1 -1
  21. package/dist/cli/help.d.ts.map +1 -1
  22. package/dist/cli/help.js +62 -13
  23. package/dist/cli/help.js.map +1 -1
  24. package/dist/cli/machine-check.d.ts +24 -5
  25. package/dist/cli/machine-check.d.ts.map +1 -1
  26. package/dist/cli/machine-check.js +128 -16
  27. package/dist/cli/machine-check.js.map +1 -1
  28. package/dist/cli/pack.d.ts +11 -8
  29. package/dist/cli/pack.d.ts.map +1 -1
  30. package/dist/cli/pack.js +63 -28
  31. package/dist/cli/pack.js.map +1 -1
  32. package/dist/cli/runner-host.d.ts +2 -0
  33. package/dist/cli/runner-host.d.ts.map +1 -1
  34. package/dist/cli/runner-host.js +1 -0
  35. package/dist/cli/runner-host.js.map +1 -1
  36. package/dist/cli/secret-notes.d.ts.map +1 -1
  37. package/dist/cli/secret-notes.js +9 -1
  38. package/dist/cli/secret-notes.js.map +1 -1
  39. package/dist/cli/terminal.d.ts +10 -2
  40. package/dist/cli/terminal.d.ts.map +1 -1
  41. package/dist/cli/terminal.js +16 -4
  42. package/dist/cli/terminal.js.map +1 -1
  43. package/dist/client.d.ts +30 -7
  44. package/dist/client.d.ts.map +1 -1
  45. package/dist/client.js +13 -1
  46. package/dist/client.js.map +1 -1
  47. package/dist/components/agent-page.d.ts +76 -18
  48. package/dist/components/agent-page.d.ts.map +1 -1
  49. package/dist/components/agent-page.js +183 -53
  50. package/dist/components/agent-page.js.map +1 -1
  51. package/dist/components/agents.d.ts +2 -0
  52. package/dist/components/agents.d.ts.map +1 -1
  53. package/dist/components/agents.js +6 -5
  54. package/dist/components/agents.js.map +1 -1
  55. package/dist/components/calendar.d.ts +24 -4
  56. package/dist/components/calendar.d.ts.map +1 -1
  57. package/dist/components/calendar.js +79 -36
  58. package/dist/components/calendar.js.map +1 -1
  59. package/dist/components/categories.js +2 -2
  60. package/dist/components/categories.js.map +1 -1
  61. package/dist/components/comments.js +2 -2
  62. package/dist/components/comments.js.map +1 -1
  63. package/dist/components/decision-list.d.ts.map +1 -1
  64. package/dist/components/decision-list.js +5 -5
  65. package/dist/components/decision-list.js.map +1 -1
  66. package/dist/components/documents.d.ts.map +1 -1
  67. package/dist/components/documents.js +4 -4
  68. package/dist/components/documents.js.map +1 -1
  69. package/dist/components/event-feed.d.ts +2 -3
  70. package/dist/components/event-feed.d.ts.map +1 -1
  71. package/dist/components/event-feed.js +4 -184
  72. package/dist/components/event-feed.js.map +1 -1
  73. package/dist/components/goals.d.ts.map +1 -1
  74. package/dist/components/goals.js +3 -3
  75. package/dist/components/goals.js.map +1 -1
  76. package/dist/components/home.js +9 -9
  77. package/dist/components/home.js.map +1 -1
  78. package/dist/components/icon.d.ts.map +1 -1
  79. package/dist/components/icon.js +11 -2
  80. package/dist/components/icon.js.map +1 -1
  81. package/dist/components/notifications.d.ts +65 -0
  82. package/dist/components/notifications.d.ts.map +1 -0
  83. package/dist/components/notifications.js +162 -0
  84. package/dist/components/notifications.js.map +1 -0
  85. package/dist/components/pack-connect.js +1 -1
  86. package/dist/components/pack-connect.js.map +1 -1
  87. package/dist/components/pack-token.js +1 -1
  88. package/dist/components/pack-token.js.map +1 -1
  89. package/dist/components/people.js +2 -2
  90. package/dist/components/people.js.map +1 -1
  91. package/dist/components/pictures.js +1 -1
  92. package/dist/components/pictures.js.map +1 -1
  93. package/dist/components/plugin-settings.d.ts +22 -1
  94. package/dist/components/plugin-settings.d.ts.map +1 -1
  95. package/dist/components/plugin-settings.js +63 -11
  96. package/dist/components/plugin-settings.js.map +1 -1
  97. package/dist/components/projects.js +1 -1
  98. package/dist/components/projects.js.map +1 -1
  99. package/dist/components/roadmap.js +2 -2
  100. package/dist/components/roadmap.js.map +1 -1
  101. package/dist/components/rules.js +2 -2
  102. package/dist/components/rules.js.map +1 -1
  103. package/dist/components/runs.d.ts.map +1 -1
  104. package/dist/components/runs.js +1 -1
  105. package/dist/components/runs.js.map +1 -1
  106. package/dist/components/sessions.js +1 -1
  107. package/dist/components/sessions.js.map +1 -1
  108. package/dist/components/shell.d.ts +2 -0
  109. package/dist/components/shell.d.ts.map +1 -1
  110. package/dist/components/shell.js +1 -1
  111. package/dist/components/shell.js.map +1 -1
  112. package/dist/components/sign-in.js +2 -2
  113. package/dist/components/sign-in.js.map +1 -1
  114. package/dist/components/skills.d.ts.map +1 -1
  115. package/dist/components/skills.js +1 -1
  116. package/dist/components/skills.js.map +1 -1
  117. package/dist/components/task-view.d.ts +6 -0
  118. package/dist/components/task-view.d.ts.map +1 -1
  119. package/dist/components/task-view.js +3 -2
  120. package/dist/components/task-view.js.map +1 -1
  121. package/dist/components/tokens.js +1 -1
  122. package/dist/components/tokens.js.map +1 -1
  123. package/dist/components/ui.d.ts +21 -2
  124. package/dist/components/ui.d.ts.map +1 -1
  125. package/dist/components/ui.js +24 -3
  126. package/dist/components/ui.js.map +1 -1
  127. package/dist/components/work.js +1 -1
  128. package/dist/components/work.js.map +1 -1
  129. package/dist/console.css +506 -289
  130. package/dist/console.d.ts.map +1 -1
  131. package/dist/console.js +193 -16
  132. package/dist/console.js.map +1 -1
  133. package/dist/data.d.ts +17 -1
  134. package/dist/data.d.ts.map +1 -1
  135. package/dist/data.js +31 -0
  136. package/dist/data.js.map +1 -1
  137. package/dist/desk-page.js +5 -5
  138. package/dist/desk-page.js.map +1 -1
  139. package/dist/feed-words.d.ts +5 -0
  140. package/dist/feed-words.d.ts.map +1 -0
  141. package/dist/feed-words.js +193 -0
  142. package/dist/feed-words.js.map +1 -0
  143. package/dist/i18n/en.d.ts +93 -1
  144. package/dist/i18n/en.d.ts.map +1 -1
  145. package/dist/i18n/en.js +103 -15
  146. package/dist/i18n/en.js.map +1 -1
  147. package/dist/i18n/ko.d.ts.map +1 -1
  148. package/dist/i18n/ko.js +105 -22
  149. package/dist/i18n/ko.js.map +1 -1
  150. package/dist/icons/glyphs.d.ts +370 -104
  151. package/dist/icons/glyphs.d.ts.map +1 -1
  152. package/dist/icons/glyphs.js +72 -66
  153. package/dist/icons/glyphs.js.map +1 -1
  154. package/dist/icons/index.d.ts.map +1 -1
  155. package/dist/icons/index.js +9 -1
  156. package/dist/icons/index.js.map +1 -1
  157. package/dist/index.d.ts +3 -2
  158. package/dist/index.d.ts.map +1 -1
  159. package/dist/index.js +3 -2
  160. package/dist/index.js.map +1 -1
  161. package/dist/limits.d.ts +7 -0
  162. package/dist/limits.d.ts.map +1 -1
  163. package/dist/limits.js +7 -0
  164. package/dist/limits.js.map +1 -1
  165. package/dist/notifications.d.ts +124 -0
  166. package/dist/notifications.d.ts.map +1 -0
  167. package/dist/notifications.js +147 -0
  168. package/dist/notifications.js.map +1 -0
  169. package/dist/onboarding.d.ts.map +1 -1
  170. package/dist/onboarding.js +7 -12
  171. package/dist/onboarding.js.map +1 -1
  172. package/dist/plugin/capabilities.d.ts +1 -1
  173. package/dist/plugin/capabilities.d.ts.map +1 -1
  174. package/dist/plugin/capabilities.js +10 -0
  175. package/dist/plugin/capabilities.js.map +1 -1
  176. package/dist/plugin/context.d.ts +85 -1
  177. package/dist/plugin/context.d.ts.map +1 -1
  178. package/dist/plugin/limits.d.ts +7 -0
  179. package/dist/plugin/limits.d.ts.map +1 -1
  180. package/dist/plugin/limits.js +7 -0
  181. package/dist/plugin/limits.js.map +1 -1
  182. package/dist/plugin/manifest.d.ts +8 -0
  183. package/dist/plugin/manifest.d.ts.map +1 -1
  184. package/dist/plugin/manifest.js +13 -0
  185. package/dist/plugin/manifest.js.map +1 -1
  186. package/dist/plugin/rest-schemas.d.ts +22 -0
  187. package/dist/plugin/rest-schemas.d.ts.map +1 -1
  188. package/dist/plugin/rest-schemas.js +19 -3
  189. package/dist/plugin/rest-schemas.js.map +1 -1
  190. package/dist/plugin/testing.d.ts +2 -0
  191. package/dist/plugin/testing.d.ts.map +1 -1
  192. package/dist/plugin/testing.js +2 -0
  193. package/dist/plugin/testing.js.map +1 -1
  194. package/dist/plugin.d.ts +1 -1
  195. package/dist/plugin.d.ts.map +1 -1
  196. package/dist/plugin.js +1 -1
  197. package/dist/plugin.js.map +1 -1
  198. package/dist/router.d.ts +6 -0
  199. package/dist/router.d.ts.map +1 -1
  200. package/dist/router.js +5 -0
  201. package/dist/router.js.map +1 -1
  202. package/dist/routes.d.ts +2 -0
  203. package/dist/routes.d.ts.map +1 -1
  204. package/dist/routes.js +2 -0
  205. package/dist/routes.js.map +1 -1
  206. package/dist/rules.js +1 -1
  207. package/dist/rules.js.map +1 -1
  208. package/dist/runner/acp.d.ts.map +1 -1
  209. package/dist/runner/acp.js +12 -97
  210. package/dist/runner/acp.js.map +1 -1
  211. package/dist/runner/browser.d.ts +50 -0
  212. package/dist/runner/browser.d.ts.map +1 -0
  213. package/dist/runner/browser.js +104 -0
  214. package/dist/runner/browser.js.map +1 -0
  215. package/dist/runner/claude.d.ts +1 -2
  216. package/dist/runner/claude.d.ts.map +1 -1
  217. package/dist/runner/claude.js +352 -13
  218. package/dist/runner/claude.js.map +1 -1
  219. package/dist/runner/codex.d.ts +9 -10
  220. package/dist/runner/codex.d.ts.map +1 -1
  221. package/dist/runner/codex.js +809 -346
  222. package/dist/runner/codex.js.map +1 -1
  223. package/dist/runner/config.d.ts +14 -3
  224. package/dist/runner/config.d.ts.map +1 -1
  225. package/dist/runner/config.js +27 -7
  226. package/dist/runner/config.js.map +1 -1
  227. package/dist/runner/desk.d.ts +3 -1
  228. package/dist/runner/desk.d.ts.map +1 -1
  229. package/dist/runner/desk.js +17 -5
  230. package/dist/runner/desk.js.map +1 -1
  231. package/dist/runner/message.d.ts +53 -3
  232. package/dist/runner/message.d.ts.map +1 -1
  233. package/dist/runner/message.js +201 -20
  234. package/dist/runner/message.js.map +1 -1
  235. package/dist/runner/registry.d.ts +6 -0
  236. package/dist/runner/registry.d.ts.map +1 -1
  237. package/dist/runner/registry.js.map +1 -1
  238. package/dist/runner/rpc.d.ts +31 -0
  239. package/dist/runner/rpc.d.ts.map +1 -0
  240. package/dist/runner/rpc.js +102 -0
  241. package/dist/runner/rpc.js.map +1 -0
  242. package/dist/runner/runner.d.ts +41 -1
  243. package/dist/runner/runner.d.ts.map +1 -1
  244. package/dist/runner/runner.js +695 -52
  245. package/dist/runner/runner.js.map +1 -1
  246. package/dist/runner/slack.d.ts +17 -8
  247. package/dist/runner/slack.d.ts.map +1 -1
  248. package/dist/runner/slack.js +1250 -78
  249. package/dist/runner/slack.js.map +1 -1
  250. package/dist/runner/types.d.ts +160 -8
  251. package/dist/runner/types.d.ts.map +1 -1
  252. package/dist/runner/types.js.map +1 -1
  253. package/dist/runner/usage.d.ts +105 -0
  254. package/dist/runner/usage.d.ts.map +1 -0
  255. package/dist/runner/usage.js +218 -0
  256. package/dist/runner/usage.js.map +1 -0
  257. package/dist/runner.d.ts +4 -4
  258. package/dist/runner.d.ts.map +1 -1
  259. package/dist/runner.js +3 -3
  260. package/dist/runner.js.map +1 -1
  261. package/dist/schemas.d.ts +673 -0
  262. package/dist/schemas.d.ts.map +1 -1
  263. package/dist/schemas.js +205 -1
  264. package/dist/schemas.js.map +1 -1
  265. package/dist/services.js +3 -3
  266. package/dist/services.js.map +1 -1
  267. package/dist/setup-guide.d.ts +4 -3
  268. package/dist/setup-guide.d.ts.map +1 -1
  269. package/dist/setup-guide.js +11 -13
  270. package/dist/setup-guide.js.map +1 -1
  271. package/dist/text.d.ts +7 -0
  272. package/dist/text.d.ts.map +1 -1
  273. package/dist/text.js +18 -0
  274. package/dist/text.js.map +1 -1
  275. package/dist/vocabulary.d.ts +4 -2
  276. package/dist/vocabulary.d.ts.map +1 -1
  277. package/dist/vocabulary.js +4 -1
  278. package/dist/vocabulary.js.map +1 -1
  279. package/docs/specs/cli.md +26 -19
  280. package/docs/specs/plugins.md +16 -10
  281. package/docs/specs/rest.md +28 -10
  282. package/docs/specs/runner.md +132 -44
  283. package/package.json +4 -4
  284. package/skills/building-a-console/SKILL.md +2 -2
  285. package/skills/building-a-console/references/configuring.md +1 -1
  286. package/skills/building-a-plugin/SKILL.md +4 -4
  287. package/skills/planning-the-board/SKILL.md +1 -1
  288. package/skills/planning-the-board/references/setting-up.md +2 -2
  289. package/skills/running-an-agent/SKILL.md +15 -64
  290. package/skills/running-an-agent/references/preparing-the-machine.md +17 -0
  291. package/skills/running-an-agent/references/several-tasks.md +37 -0
  292. package/skills/running-an-agent/references/slack-app.md +70 -13
  293. package/skills/running-an-agent/references/the-account-and-the-invitation.md +5 -0
  294. package/skills/running-an-agent/references/what-was-not-seen-run-yet.md +3 -0
  295. package/skills/running-an-agent/references/when-the-agent-could-not-go-on.md +16 -0
  296. package/skills/running-an-agent/references/your-first-task.md +14 -0
  297. package/skills/working-the-board/SKILL.md +9 -12
  298. package/skills/working-the-board/references/a-pack-skills-questions.md +3 -0
  299. package/skills/working-the-board/references/a-plugins-commands.md +3 -0
  300. package/skills/working-the-board/references/a-review.md +3 -0
  301. package/skills/working-the-board/references/an-open-run.md +3 -0
  302. package/skills/working-the-board/references/requirements.md +7 -0
  303. package/skills/working-the-board/references/the-pack.md +2 -2
  304. package/skills/working-the-board/references/what-they-were-told.md +3 -0
  305. package/skills/working-the-board/references/work-given-in-chat.md +5 -0
  306. package/src/agent-page.tsx +76 -47
  307. package/src/agent-usage.ts +113 -0
  308. package/src/api.ts +62 -0
  309. package/src/cli/cli.ts +634 -162
  310. package/src/cli/format.ts +190 -47
  311. package/src/cli/help.ts +77 -12
  312. package/src/cli/machine-check.ts +182 -29
  313. package/src/cli/pack.ts +81 -40
  314. package/src/cli/runner-host.ts +3 -0
  315. package/src/cli/secret-notes.ts +9 -1
  316. package/src/cli/terminal.ts +20 -4
  317. package/src/client.ts +94 -6
  318. package/src/components/agent-page.tsx +280 -63
  319. package/src/components/agents.tsx +23 -3
  320. package/src/components/calendar.tsx +93 -37
  321. package/src/components/categories.tsx +2 -2
  322. package/src/components/comments.tsx +5 -5
  323. package/src/components/decision-list.tsx +13 -10
  324. package/src/components/documents.tsx +13 -8
  325. package/src/components/event-feed.tsx +4 -203
  326. package/src/components/goals.tsx +6 -4
  327. package/src/components/home.tsx +12 -12
  328. package/src/components/icon.tsx +16 -3
  329. package/src/components/notifications.tsx +419 -0
  330. package/src/components/pack-connect.tsx +1 -1
  331. package/src/components/pack-token.tsx +5 -5
  332. package/src/components/people.tsx +3 -3
  333. package/src/components/pictures.tsx +1 -1
  334. package/src/components/plugin-settings.tsx +128 -23
  335. package/src/components/projects.tsx +1 -1
  336. package/src/components/roadmap.tsx +2 -2
  337. package/src/components/rules.tsx +2 -2
  338. package/src/components/runs.tsx +6 -3
  339. package/src/components/sessions.tsx +2 -2
  340. package/src/components/shell.tsx +3 -0
  341. package/src/components/sign-in.tsx +3 -3
  342. package/src/components/skills.tsx +5 -3
  343. package/src/components/task-view.tsx +18 -7
  344. package/src/components/tokens.tsx +2 -2
  345. package/src/components/ui.tsx +70 -5
  346. package/src/components/work.tsx +2 -2
  347. package/src/console.tsx +269 -12
  348. package/src/data.ts +54 -0
  349. package/src/desk-page.tsx +5 -5
  350. package/src/feed-words.ts +214 -0
  351. package/src/i18n/en.ts +114 -15
  352. package/src/i18n/ko.ts +115 -22
  353. package/src/icons/glyphs.ts +74 -68
  354. package/src/icons/index.ts +9 -1
  355. package/src/index.ts +11 -0
  356. package/src/limits.ts +7 -0
  357. package/src/notifications.ts +205 -0
  358. package/src/onboarding.ts +10 -14
  359. package/src/plugin/capabilities.ts +13 -0
  360. package/src/plugin/context.ts +87 -0
  361. package/src/plugin/limits.ts +7 -0
  362. package/src/plugin/manifest.ts +14 -0
  363. package/src/plugin/rest-schemas.ts +27 -3
  364. package/src/plugin/testing.ts +4 -0
  365. package/src/plugin.ts +2 -0
  366. package/src/router.ts +7 -0
  367. package/src/routes.ts +2 -0
  368. package/src/rules.ts +1 -1
  369. package/src/runner/acp.ts +12 -118
  370. package/src/runner/browser.ts +128 -0
  371. package/src/runner/claude.ts +399 -12
  372. package/src/runner/codex.ts +904 -400
  373. package/src/runner/config.ts +30 -7
  374. package/src/runner/desk.ts +22 -6
  375. package/src/runner/message.ts +251 -21
  376. package/src/runner/registry.ts +6 -0
  377. package/src/runner/rpc.ts +140 -0
  378. package/src/runner/runner.ts +863 -53
  379. package/src/runner/slack.ts +1535 -85
  380. package/src/runner/types.ts +150 -5
  381. package/src/runner/usage.ts +299 -0
  382. package/src/runner.ts +16 -1
  383. package/src/schemas.ts +249 -0
  384. package/src/services.ts +3 -3
  385. package/src/setup-guide.ts +12 -14
  386. package/src/styles/README.md +11 -7
  387. package/src/styles/console.css +2 -0
  388. package/src/styles/drawn-by-pages.json +7 -82
  389. package/src/styles/pages/agents.css +46 -35
  390. package/src/styles/pages/calendar.css +0 -1
  391. package/src/styles/pages/connect.css +0 -14
  392. package/src/styles/pages/decisions.css +2 -43
  393. package/src/styles/pages/documents.css +0 -29
  394. package/src/styles/pages/home.css +4 -16
  395. package/src/styles/pages/people.css +2 -17
  396. package/src/styles/pages/plugins.css +9 -12
  397. package/src/styles/pages/roadmap.css +0 -16
  398. package/src/styles/pages/settings.css +0 -28
  399. package/src/styles/pages/sign-in.css +2 -17
  400. package/src/styles/pages/thread.css +4 -50
  401. package/src/styles/pages/work.css +0 -5
  402. package/src/styles/parts/button.css +31 -0
  403. package/src/styles/parts/count.css +10 -0
  404. package/src/styles/parts/divider.css +17 -0
  405. package/src/styles/parts/frame.css +12 -0
  406. package/src/styles/parts/icon.css +39 -0
  407. package/src/styles/parts/menu.css +184 -0
  408. package/src/styles/parts/panel.css +7 -0
  409. package/src/styles/parts/progress.css +63 -0
  410. package/src/styles/parts/settings.css +2 -0
  411. package/src/styles/parts/sheet.css +28 -0
  412. package/src/styles/parts/text.css +34 -0
  413. package/src/text.ts +19 -0
  414. package/src/vocabulary.ts +4 -1
  415. package/template/plugin/package.json +1 -1
@@ -1,4 +1,6 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { DriverHost } from "./registry.js";
3
+ import { connectionOf, METHOD_NOT_FOUND, RpcError } from "./rpc.js";
2
4
  import {
3
5
  type Child,
4
6
  type Cut,
@@ -12,21 +14,39 @@ import {
12
14
  plainCut,
13
15
  plainCutEnd,
14
16
  type StartOptions,
17
+ type UsageWindow,
15
18
  } from "./types.js";
19
+ import { saysUsageLimit } from "./usage.js";
16
20
 
17
- // The `codex` driver (docs/specs/runner.md): the Codex binary, unmodified, run with nobody at
18
- // its terminal, `codex exec --json`. A process a turn: the message on its standard input, an
19
- // event a line on its standard output, and the conversation gone on with by the id its first
20
- // turn named. The product takes no message while a turn runs, so one that arrives then waits
21
- // for the turn to end, and one that is to be read now ends the turn's process first.
21
+ // The `codex` driver (docs/specs/runner.md, ADR-0153): the Codex binary, unmodified, run as its
22
+ // app server, `codex app-server`: one process a session, spoken to over its standard input and
23
+ // output, a JSON-RPC message a line. A conversation is a thread of the product's, begun or gone
24
+ // on with when the session opens. A message starts a turn, and one that arrives while a turn
25
+ // runs is put into that turn (`turn/steer`), where the product reads it after the step under
26
+ // way; one that is to be read now stops the turn first.
22
27
  //
23
- // Written from what the binary printed when it was run (0.164.0), with its own help for the
24
- // words it is started with; what was not seen there is marked where it is read. Everything the
25
- // product prints is data: read by shape, never run, and bounded by the runner before it is
26
- // sent on.
28
+ // Written from the protocol as the binary itself writes it out (`codex app-server
29
+ // generate-ts`, 0.172.0), from the product's own source at that build, and from what the binary
30
+ // answered when it was spoken to signed out, 0.139.0, 0.167.0 and 0.172.0: a thread begun and
31
+ // gone on with, a turn started, a message put into it and said back, a turn stopped, a turn
32
+ // that failed for the sign-in, and what it refuses. A turn of a signed-in product, with its
33
+ // tools, is in the shapes of that protocol and was not seen run. Everything the product writes
34
+ // is data: read by shape, never run, and bounded by the runner before it is sent on.
27
35
 
28
- /** How long a process asked to end is given before it is killed. */
29
- const KILL_GRACE_MS = 5000;
36
+ /** The words the product is started with: its app server, on its standard input and output. */
37
+ const ARGUMENTS = ["app-server"] as const;
38
+ /**
39
+ * The oldest build the driver speaks to: the first whose app server says a message back under
40
+ * the id it was handed over with, which is how the driver knows a message put into a turn was
41
+ * read. An older one has the app server and no such id: a message put into a turn there would
42
+ * be read and, never said back, handed over once more with the next turn.
43
+ */
44
+ const OLDEST = [0, 139, 0] as const;
45
+ /** How long a session that is stopped is given to end by itself, then after it was asked to. */
46
+ const STOP_GRACE_MS = 5000;
47
+ const KILL_GRACE_MS = 2000;
48
+ /** How long the product is given to open a conversation. */
49
+ const START_TIMEOUT_MS = 120_000;
30
50
  /** How much of a tool's input a tool call shows. */
31
51
  const MAX_INPUT_LENGTH = 4000;
32
52
  /** How many models, and how many levels of effort, are read from the product's own list. */
@@ -35,21 +55,132 @@ const MAX_OFFERED = 50;
35
55
  const MAX_CATALOG_LENGTH = 8 * 1024 * 1024;
36
56
 
37
57
  /**
38
- * A word that goes on the product's command line: a model, a level of effort, a conversation's
39
- * id. Anything else is no such word, and is left out: it never becomes an option of the
40
- * product's, or a setting beside the one it was meant for.
58
+ * A word the product is handed as one: a model, a level of effort, a conversation's id.
59
+ * Anything else is no such word, and is left out.
41
60
  */
42
61
  const WORD = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
43
62
  const word = (value: string | null | undefined): string | undefined =>
44
63
  typeof value === "string" && WORD.test(value) ? value : undefined;
45
64
 
46
65
  /**
47
- * What an error says when the product is not signed in or its login ran out. Its words for it
48
- * were not seen, since that takes signing it out: read by pattern, and no contract.
66
+ * What an error says when the product is not signed in or its login ran out, beside the status
67
+ * the service answered with. Seen signed out (0.172.0): `unexpected status 401 Unauthorized:
68
+ * Missing bearer or basic authentication in header`. The rest is read by pattern, and no contract.
49
69
  */
50
70
  const SIGN_IN =
51
71
  /not (?:logged|signed) in|codex login|log ?in again|sign in again|\b401\b|unauthorized|token (?:has )?(?:expired|been revoked)|invalid (?:api )?key/i;
52
72
 
73
+ /**
74
+ * The build that answered, from what it calls itself when it is greeted: the client's name, a
75
+ * stroke, and its own version (`skillcdn-console-runner/0.171.0-alpha.13.2 (Windows ...)`, seen
76
+ * with that build). Nothing where it says none that reads as one.
77
+ */
78
+ export function codexBuild(
79
+ userAgent: unknown,
80
+ ): { readonly text: string; readonly numbers: readonly [number, number, number] } | undefined {
81
+ const found =
82
+ typeof userAgent === "string"
83
+ ? /^[^/\s]{1,80}\/((\d{1,4})\.(\d{1,5})\.(\d{1,6})[0-9A-Za-z.+-]{0,40})(?:\s|$)/.exec(
84
+ userAgent,
85
+ )
86
+ : null;
87
+ return found === null
88
+ ? undefined
89
+ : { text: found[1] ?? "", numbers: [Number(found[2]), Number(found[3]), Number(found[4])] };
90
+ }
91
+
92
+ /** Whether a build is older than the oldest the driver speaks to. */
93
+ const tooOld = (numbers: readonly [number, number, number]): boolean => {
94
+ for (const [at, least] of OLDEST.entries()) {
95
+ const has = numbers[at] ?? 0;
96
+ if (has !== least) {
97
+ return has < least;
98
+ }
99
+ }
100
+ return false;
101
+ };
102
+
103
+ /** The product's sandboxes, from the one that allows the least to the one that allows the most, by its word for each in an answer. */
104
+ const SANDBOXES = [
105
+ ["readOnly", "read-only"],
106
+ ["workspaceWrite", "workspace-write"],
107
+ ["dangerFullAccess", "danger-full-access"],
108
+ ] as const;
109
+
110
+ /** The sandbox a mode asks for, in the product's word for it. */
111
+ const sandboxOf = (mode: string): string => {
112
+ const asked = modeSettings(mode).sandbox;
113
+ return typeof asked === "string" ? asked : LEAST_MODE;
114
+ };
115
+
116
+ /** The bucket of the plan's own allowance, by the product's id for it (seen with 0.171.0). */
117
+ const PLAN_BUCKET = "codex";
118
+ /** How much of a bucket's name is said after a window's own. */
119
+ const MAX_BUCKET_NAME = 24;
120
+
121
+ /**
122
+ * The windows of the product's allowance, as it says them (`account/rateLimits/updated`): each
123
+ * with the share used and when it resets, named by how long it lasts. Seen with 0.171.0, asked
124
+ * of a signed-in product with no turn: a share in hundredths, a length in minutes and a moment
125
+ * in seconds (`{ usedPercent: 4, windowDurationMins: 10080, resetsAt: 1795927747 }`). An
126
+ * update is sparse: a window it says nothing of is not one that reset. An update is of one
127
+ * bucket, which it names (`limitId`): the plan's own is `codex`, and any other is a quota kept
128
+ * apart, one model's say, whose windows are said with the bucket's name after their own, so
129
+ * that an update of one is never read as the plan's.
130
+ */
131
+ function allowanceOf(limits: unknown): UsageWindow[] {
132
+ const said = isObject(limits) ? limits : {};
133
+ const bucket = textOf(said.limitId);
134
+ const apart = bucket !== undefined && bucket !== PLAN_BUCKET;
135
+ // By the name the product shows for the bucket, or its id where it gives none: one line,
136
+ // and short, since the window's own name stands before it.
137
+ const called = (textOf(said.limitName) ?? "").replaceAll(/\s+/g, " ").trim();
138
+ const of = apart ? (called === "" ? bucket : called).slice(0, MAX_BUCKET_NAME) : "";
139
+ const windows: UsageWindow[] = [];
140
+ for (const [place, one] of [
141
+ ["primary", said.primary],
142
+ ["secondary", said.secondary],
143
+ ] as const) {
144
+ if (!isObject(one) || typeof one.usedPercent !== "number" || !(one.usedPercent >= 0)) {
145
+ continue;
146
+ }
147
+ const minutes =
148
+ typeof one.windowDurationMins === "number" && one.windowDurationMins > 0
149
+ ? Math.round(one.windowDurationMins)
150
+ : undefined;
151
+ const name =
152
+ minutes === undefined
153
+ ? place
154
+ : minutes === 10_080
155
+ ? "weekly"
156
+ : minutes % 1440 === 0
157
+ ? `${minutes / 1440}-day`
158
+ : minutes % 60 === 0
159
+ ? `${minutes / 60}-hour`
160
+ : `${minutes}-minute`;
161
+ const resets =
162
+ typeof one.resetsAt === "number" && one.resetsAt > 0 && one.resetsAt < 1e11
163
+ ? Math.floor(one.resetsAt * 1000)
164
+ : undefined;
165
+ windows.push({
166
+ name: of === "" ? name : `${name} ${of}`,
167
+ used: Math.min(1, one.usedPercent / 100),
168
+ resetsAt: resets,
169
+ ...(apart ? { apart } : {}),
170
+ });
171
+ }
172
+ return windows;
173
+ }
174
+
175
+ /**
176
+ * Whether a turn's error says that what the subscription allows is used up: the product's own
177
+ * word for it (`usageLimitExceeded`, as its protocol has it, not seen said), or its words.
178
+ */
179
+ function usageLimited(error: unknown): boolean {
180
+ const info = isObject(error) ? error.codexErrorInfo : undefined;
181
+ return info === "usageLimitExceeded" || saysUsageLimit(errorOf(error));
182
+ }
183
+
53
184
  /** The product's words for what runs without asking: its three sandboxes, and the flag by which its own reviewer answers what a sandbox would ask. */
54
185
  const MODES = ["read-only", "workspace-write", "approve-for-me", "danger-full-access"] as const;
55
186
  /**
@@ -74,62 +205,63 @@ export function codexMode(named: string | undefined): string {
74
205
  : (MODES.find((mode) => mode === named) ?? LEAST_MODE);
75
206
  }
76
207
 
208
+ type Json = Record<string, unknown>;
209
+ const isObject = (value: unknown): value is Json =>
210
+ typeof value === "object" && value !== null && !Array.isArray(value);
211
+ const textOf = (value: unknown): string | undefined =>
212
+ typeof value === "string" ? value : undefined;
213
+
77
214
  /**
78
- * A mode as the settings the product takes at any turn, a conversation begun or one gone on
79
- * with: a turn keeps nothing of the mode the turn before ran in. Whatever a mode does not allow
80
- * is asked of nobody: refused, or answered by the product's reviewer.
215
+ * A mode as the settings a conversation is begun or gone on with, each said whole: a thread
216
+ * keeps what it last ran with, and one gone on with ran in whatever the desk named then.
217
+ * Whatever a mode does not allow is asked of nobody: refused, or answered by the product's
218
+ * reviewer.
81
219
  */
82
- function modeArguments(mode: string): readonly string[] {
83
- const set = (key: string, value: string): string[] => ["-c", `${key}="${value}"`];
220
+ function modeSettings(mode: string): Json {
84
221
  switch (mode) {
85
222
  case "approve-for-me":
86
- return [
87
- ...set("sandbox_mode", "workspace-write"),
88
- ...set("approval_policy", "on-request"),
89
- ...set("approvals_reviewer", "auto_review"),
90
- ];
223
+ return {
224
+ sandbox: "workspace-write",
225
+ approvalPolicy: "on-request",
226
+ approvalsReviewer: "auto_review",
227
+ };
91
228
  case "workspace-write":
92
229
  case "danger-full-access":
93
- return [...set("sandbox_mode", mode), ...set("approval_policy", "never")];
230
+ return { sandbox: mode, approvalPolicy: "never", approvalsReviewer: "user" };
94
231
  default:
95
- return [...set("sandbox_mode", "read-only"), ...set("approval_policy", "never")];
232
+ return { sandbox: "read-only", approvalPolicy: "never", approvalsReviewer: "user" };
96
233
  }
97
234
  }
98
235
 
99
- /** The arguments one turn of the product is started with. */
100
- export function codexArguments(turn: {
101
- readonly model: string | null;
102
- readonly effort: string | null;
103
- readonly permissions: string | undefined;
104
- /** The conversation to go on with, or nothing for a new one. */
105
- readonly conversation: string | undefined;
106
- /** The pictures that go with the turn's message, each a file by its path from the desk. */
107
- readonly images?: readonly string[] | undefined;
108
- }): readonly string[] {
109
- const model = word(turn.model);
110
- const effort = word(turn.effort);
111
- const conversation = word(turn.conversation);
112
- return [
113
- "exec",
114
- ...(conversation === undefined ? [] : ["resume"]),
115
- // A picture each under its own option, and before an option that takes nothing: the
116
- // product's option takes several values, and would take what follows it for one.
117
- ...(turn.images ?? []).filter(isPicturePath).flatMap((path) => ["-i", path]),
118
- "--json",
119
- // The desk is the agent's own, a repository or not one yet.
120
- "--skip-git-repo-check",
121
- ...modeArguments(codexMode(turn.permissions)),
122
- ...(model === undefined ? [] : ["-m", model]),
123
- ...(effort === undefined ? [] : ["-c", `model_reasoning_effort="${effort}"`]),
124
- ...(conversation === undefined ? [] : [conversation]),
125
- // The message is read from the standard input.
126
- "-",
127
- ];
128
- }
236
+ /**
237
+ * What the product is asked to keep to itself: a block as it grows, a piece at a time, where
238
+ * the driver reads whole blocks, and counts nobody asked for.
239
+ */
240
+ const UNREAD = [
241
+ "thread/started",
242
+ "item/agentMessage/delta",
243
+ "item/reasoning/summaryTextDelta",
244
+ "item/reasoning/summaryPartAdded",
245
+ "item/reasoning/textDelta",
246
+ "item/commandExecution/outputDelta",
247
+ "item/fileChange/outputDelta",
248
+ "item/plan/delta",
249
+ "thread/tokenUsage/updated",
250
+ ] as const;
251
+
252
+ /** What the runner says of itself when it begins: nothing of the product's that is still an experiment is asked for. */
253
+ const hello = (version: string | undefined): Json => ({
254
+ clientInfo: {
255
+ name: "skillcdn-console-runner",
256
+ title: "SkillCDN Console runner",
257
+ version: version ?? "0.0.0",
258
+ },
259
+ capabilities: { experimentalApi: false, optOutNotificationMethods: UNREAD },
260
+ });
129
261
 
130
262
  /**
131
- * A path that goes on the product's command line as a picture: one the runner wrote under the
132
- * desk's `work/inbox/`, and nothing that begins as an option.
263
+ * A path the product is handed as a picture: one the runner wrote under the desk's
264
+ * `work/inbox/`, and no other file of the machine.
133
265
  */
134
266
  const PICTURE_PATH = /^work\/inbox\/[1-9]\d{0,15}\/([^/\\]{1,200})$/;
135
267
  const isPicturePath = (path: string): boolean => {
@@ -137,23 +269,22 @@ const isPicturePath = (path: string): boolean => {
137
269
  return name !== undefined && !/^\.+$/.test(name);
138
270
  };
139
271
 
140
- type Json = Record<string, unknown>;
141
- const isObject = (value: unknown): value is Json =>
142
- typeof value === "object" && value !== null && !Array.isArray(value);
143
- const textOf = (value: unknown): string | undefined =>
144
- typeof value === "string" ? value : undefined;
145
-
146
- /** One line of the product's output as an object with a type, or nothing for anything else. */
147
- function lineOf(line: string): Json | undefined {
148
- if (line.trim().length === 0) {
149
- return undefined;
150
- }
151
- try {
152
- const parsed: unknown = JSON.parse(line);
153
- return isObject(parsed) && typeof parsed.type === "string" ? parsed : undefined;
154
- } catch {
155
- return undefined;
156
- }
272
+ /**
273
+ * Messages as the input of a turn: what arrived together is read together, each under its own
274
+ * header, and every picture of it goes with it, as a file by its path in the desk.
275
+ */
276
+ function inputOf(messages: readonly DriverMessage[], desk: string): Json[] {
277
+ const root = desk.replace(/[\\/]+$/, "");
278
+ return [
279
+ { type: "text", text: messages.map((message) => message.text).join("\n\n"), text_elements: [] },
280
+ ...messages.flatMap((message) =>
281
+ message.images.flatMap((picture) =>
282
+ picture.path !== undefined && isPicturePath(picture.path)
283
+ ? [{ type: "localImage", path: `${root}/${picture.path}` }]
284
+ : [],
285
+ ),
286
+ ),
287
+ ];
157
288
  }
158
289
 
159
290
  /** Anything as a line of text a person reads, bounded. */
@@ -169,49 +300,38 @@ function shown(value: unknown, cut: Cut): string {
169
300
  }
170
301
 
171
302
  /**
172
- * What an error of the product says. It writes one as the answer of the service it asked, a
173
- * line of JSON inside its line, where the service answered; the words are read out of it.
303
+ * What an error of the product says: its message, with what it carries beside it. It may write
304
+ * the message as the answer of the service it asked, a line of JSON, where the service
305
+ * answered; the words are read out of it.
174
306
  */
175
- function errorOf(message: unknown): string {
176
- const text = textOf(message) ?? "";
307
+ function errorOf(error: unknown): string {
308
+ const said = isObject(error) ? error : {};
309
+ let message = textOf(said.message)?.trim() ?? "";
177
310
  try {
178
- const parsed: unknown = JSON.parse(text);
311
+ const parsed: unknown = JSON.parse(message);
179
312
  if (isObject(parsed) && isObject(parsed.error) && typeof parsed.error.message === "string") {
180
- return parsed.error.message;
313
+ message = parsed.error.message;
181
314
  }
182
315
  } catch {
183
316
  // Words, and not an answer of the service: said as they are.
184
317
  }
185
- return text;
186
- }
187
-
188
- /** What the lines of one session left so far, for the next line to be read by. */
189
- interface Read {
190
- /** Whether the product said that a conversation began. */
191
- began: boolean;
192
- /** What was last said of how it runs, and the conversation it last named. */
193
- runs: string | undefined;
194
- conversation: string | undefined;
195
- /** The tool calls said already, by the product's id for each. */
196
- readonly called: Set<string>;
197
- /** The last error said, which the product writes twice where a turn fails of it. */
198
- error: string | undefined;
199
- /** Whether the turn under way said that it completed, and what it said where it failed. */
200
- completed: boolean;
201
- failed: string | undefined;
202
- /** Whether the process of the turn under way got as far as a turn: it said that one started. */
203
- turned: boolean;
204
- /** How many messages the turn under way was started with. */
205
- messages: number;
206
- /** What cuts a text to what is shown of it. */
207
- readonly cut: Cut;
318
+ const more = textOf(said.additionalDetails)?.trim() ?? "";
319
+ if (more.length === 0 || message.includes(more)) {
320
+ return message;
321
+ }
322
+ return message.length === 0 ? more : `${message}\n${more}`;
208
323
  }
209
324
 
210
- /** What a turn runs with, as the session's first event and the heartbeat say it. */
211
- interface Runs {
212
- readonly model: string | null;
213
- readonly effort: string | null;
214
- readonly mode: string;
325
+ /**
326
+ * Whether an error says that the product is not signed in: in the product's own word for it,
327
+ * by the status the service refused it with, or in its words.
328
+ */
329
+ function signedOut(error: unknown): boolean {
330
+ const info = isObject(error) ? error.codexErrorInfo : undefined;
331
+ const refused =
332
+ isObject(info) &&
333
+ Object.values(info).some((one) => isObject(one) && one.httpStatusCode === 401);
334
+ return info === "unauthorized" || refused || SIGN_IN.test(errorOf(error));
215
335
  }
216
336
 
217
337
  /** A tool call of the product, by the kind of item it writes for one: its name and its input as a line. */
@@ -220,28 +340,30 @@ function callOf(
220
340
  cut: Cut,
221
341
  ): { readonly tool: string; readonly text: string } | undefined {
222
342
  switch (item.type) {
223
- case "command_execution":
343
+ case "commandExecution":
224
344
  return { tool: "command_execution", text: shown(item.command ?? "", cut) };
225
- case "file_change": {
345
+ case "fileChange": {
226
346
  const changes = Array.isArray(item.changes) ? item.changes : [];
227
347
  return {
228
348
  tool: "file_change",
229
349
  text: cut(
230
350
  changes
231
351
  .filter(isObject)
232
- .map((change) => `${textOf(change.kind) ?? "change"} ${textOf(change.path) ?? ""}`)
352
+ .map((change) => {
353
+ const kind = isObject(change.kind) ? textOf(change.kind.type) : textOf(change.kind);
354
+ return `${kind ?? "change"} ${textOf(change.path) ?? ""}`;
355
+ })
233
356
  .join("\n"),
234
357
  MAX_INPUT_LENGTH,
235
358
  ),
236
359
  };
237
360
  }
238
- // The two below are in the shape the product's documentation gives them: not seen run.
239
- case "mcp_tool_call":
361
+ case "mcpToolCall":
240
362
  return {
241
363
  tool: `${textOf(item.server) ?? "mcp"}.${textOf(item.tool) ?? "tool"}`,
242
364
  text: item.arguments === undefined ? "" : shown(item.arguments, cut),
243
365
  };
244
- case "web_search":
366
+ case "webSearch":
245
367
  return { tool: "web_search", text: shown(item.query ?? "", cut) };
246
368
  default:
247
369
  return undefined;
@@ -250,10 +372,10 @@ function callOf(
250
372
 
251
373
  /** What came back from a tool call, where the product says: a command's output, or what a tool answered. */
252
374
  function resultOf(item: Json, cut: Cut): string {
253
- if (item.type === "command_execution") {
254
- return textOf(item.aggregated_output) ?? "";
375
+ if (item.type === "commandExecution") {
376
+ return textOf(item.aggregatedOutput) ?? "";
255
377
  }
256
- if (item.type === "mcp_tool_call") {
378
+ if (item.type === "mcpToolCall") {
257
379
  if (isObject(item.error) && typeof item.error.message === "string") {
258
380
  return item.error.message;
259
381
  }
@@ -262,150 +384,47 @@ function resultOf(item: Json, cut: Cut): string {
262
384
  return "";
263
385
  }
264
386
 
265
- /** The events of one line of the product's output. `read` is what the lines before it left. */
266
- function eventsOf(line: Json, read: Read, runs: Runs): DriverEvent[] {
267
- const events: DriverEvent[] = [];
268
- const item = isObject(line.item) ? line.item : undefined;
269
- switch (line.type) {
270
- case "thread.started": {
271
- // Written at the start of every turn: said on once, and again where it is something else.
272
- const said = JSON.stringify([runs.model, runs.effort]);
273
- const conversation = textOf(line.thread_id);
274
- if (said !== read.runs) {
275
- // The product names neither its model nor its version here: what it was asked for.
276
- events.push({ type: "running", model: runs.model, effort: runs.effort, version: null });
277
- }
278
- if (conversation !== undefined && conversation !== read.conversation) {
279
- events.push({ type: "conversation", id: conversation });
280
- }
281
- if (!read.began) {
282
- events.push({
283
- type: "event",
284
- kind: "status",
285
- text: "The product started.",
286
- data: { model: runs.model, effort: runs.effort, version: null, mode: runs.mode },
287
- });
288
- }
289
- read.began = true;
290
- read.runs = said;
291
- read.conversation = conversation ?? read.conversation;
292
- return events;
293
- }
294
- case "item.started": {
295
- const call = item === undefined ? undefined : callOf(item, read.cut);
296
- const id = textOf(item?.id);
297
- if (call !== undefined) {
298
- events.push({
299
- type: "event",
300
- kind: "tool_call",
301
- text: call.text,
302
- data: { tool: call.tool, id: id ?? null },
303
- });
304
- if (id !== undefined) {
305
- read.called.add(id);
306
- }
307
- }
308
- return events;
309
- }
310
- case "item.completed": {
311
- if (item === undefined) {
312
- return events;
313
- }
314
- const id = textOf(item.id);
315
- if (item.type === "agent_message" && typeof item.text === "string") {
316
- events.push({ type: "event", kind: "assistant", text: item.text });
317
- } else if (item.type === "reasoning" && typeof item.text === "string") {
318
- // As the product's documentation has it: none was written in the runs it was tried in.
319
- events.push({ type: "event", kind: "thinking", text: item.text });
320
- } else if (item.type === "error") {
321
- // A word of warning inside a turn: the turn goes on.
322
- events.push({ type: "event", kind: "error", text: errorOf(item.message) });
323
- } else {
324
- const call = callOf(item, read.cut);
325
- if (call === undefined) {
326
- return events;
327
- }
328
- // A call the product wrote no beginning of is said with its end.
329
- if (id === undefined || !read.called.delete(id)) {
330
- events.push({
331
- type: "event",
332
- kind: "tool_call",
333
- text: call.text,
334
- data: { tool: call.tool, id: id ?? null },
335
- });
336
- }
337
- if (item.type === "web_search") {
338
- return events;
339
- }
340
- const exit = typeof item.exit_code === "number" ? item.exit_code : null;
341
- const data: Record<string, Fact> = {
342
- id: id ?? null,
343
- error: item.status === "failed" || (exit !== null && exit !== 0),
344
- };
345
- if (exit !== null) {
346
- data.exit = exit;
347
- }
348
- events.push({
349
- type: "event",
350
- kind: "tool_result",
351
- text: resultOf(item, read.cut),
352
- data,
353
- pictures: [],
354
- });
355
- }
356
- return events;
357
- }
358
- case "turn.started":
359
- // The turn's messages are the product's from here on: said once for each.
360
- if (!read.turned) {
361
- for (let taken = 0; taken < read.messages; taken += 1) {
362
- events.push({ type: "taken" });
363
- }
364
- }
365
- read.turned = true;
366
- return events;
367
- case "turn.completed":
368
- read.completed = true;
369
- return events;
370
- case "turn.failed":
371
- case "error": {
372
- const said = errorOf(
373
- line.type === "error" ? line.message : isObject(line.error) ? line.error.message : "",
374
- );
375
- if (line.type === "turn.failed") {
376
- read.failed = said;
377
- }
378
- // The product writes what failed a turn twice: as an error, and as the turn's failing.
379
- if (said !== read.error) {
380
- events.push({
381
- type: "event",
382
- kind: "error",
383
- text: said.length === 0 ? "The turn ended with an error." : said,
384
- });
385
- }
386
- read.error = said;
387
- return events;
388
- }
389
- default:
390
- return events;
391
- }
392
- }
393
-
394
387
  const wait = (ms: number): Promise<"timeout"> =>
395
388
  new Promise((resolve) => {
396
389
  setTimeout(() => resolve("timeout"), ms).unref?.();
397
390
  });
398
391
 
399
- /** Ends a process: asked first, then killed. */
392
+ /** Ends a process: its input closed first, then asked, then made to. */
400
393
  async function endOf(child: Child): Promise<void> {
401
- child.kill("SIGTERM");
402
- if ((await Promise.race([child.exited, wait(KILL_GRACE_MS)])) === "timeout") {
403
- child.kill("SIGKILL");
394
+ child.end();
395
+ if ((await Promise.race([child.exited, wait(STOP_GRACE_MS)])) === "timeout") {
396
+ child.kill("SIGTERM");
397
+ if ((await Promise.race([child.exited, wait(KILL_GRACE_MS)])) === "timeout") {
398
+ child.kill("SIGKILL");
399
+ }
404
400
  }
405
401
  }
406
402
 
403
+ /** The turn under way. */
404
+ interface Turn {
405
+ /** The product's id for it, once the product said it. */
406
+ id: string | undefined;
407
+ /** Why it was stopped, where it was. */
408
+ cut: "message" | "stopped" | undefined;
409
+ /** Whether a message is put into it: not once the product refused one, a turn that is over or one of a kind it puts none into. */
410
+ steers: boolean;
411
+ }
412
+
413
+ /** What the product was handed and has not said it took: under the id it says it back by. */
414
+ interface Handed {
415
+ readonly id: string;
416
+ readonly messages: readonly DriverMessage[];
417
+ /** Whether it was put into a turn under way, where the others began one. */
418
+ readonly steered: boolean;
419
+ }
420
+
407
421
  function sessionOf(
408
- host: { readonly spawn: DriverHost["spawn"]; readonly command: string },
422
+ child: Child,
423
+ host: {
424
+ readonly command: string;
425
+ readonly version: string | undefined;
426
+ readonly uuid: () => string;
427
+ },
409
428
  options: StartOptions,
410
429
  ): DriverSession {
411
430
  // What the session says, in order, for whoever reads it: until it ends.
@@ -432,167 +451,647 @@ function sessionOf(
432
451
  }
433
452
  }
434
453
 
435
- const read: Read = {
436
- began: false,
437
- runs: undefined,
438
- conversation: undefined,
439
- called: new Set(),
440
- error: undefined,
441
- completed: false,
442
- failed: undefined,
443
- turned: false,
444
- messages: 0,
445
- cut: options.cut ?? plainCut,
446
- };
454
+ const cut = options.cut ?? plainCut;
455
+ const connection = connectionOf(child, { cut, header: false });
447
456
  const mode = codexMode(options.permissions);
448
- let conversation = word(options.resume);
449
457
  let choice = { model: options.model, effort: options.effort };
450
- /** The turn under way: its process, why it was ended where it was, and when it is read to its end. */
451
- let turn:
452
- | {
453
- readonly child: Child;
454
- cut: "message" | "stopped" | "ended" | undefined;
455
- done: Promise<void>;
456
- }
457
- | undefined;
458
- /** The messages that arrived while a turn ran: the next turn's. */
459
- let waiting: DriverMessage[] = [];
458
+ /** What the conversation runs with, as the product said it or as it was last asked. */
459
+ let runs: { model: string | null; effort: string | null } = { model: null, effort: null };
460
+ let version: string | null = null;
461
+ /** The conversation, once it is open. */
462
+ let thread: string | undefined;
463
+ /** Whether the product answered at all, whether the conversation is open, and whether the session gave up or is being stopped. */
464
+ let began = false;
465
+ let ready = false;
466
+ let gaveUp = false;
467
+ let stopping = false;
468
+ /** Whether the product's output closed: nothing more reaches a process that is gone. */
460
469
  let over = false;
470
+ let turn: Turn | undefined;
471
+ /** The messages the product was not handed yet: the next turn's, or the next put into the one under way. */
472
+ let waiting: DriverMessage[] = [];
473
+ let handed: Handed[] = [];
474
+ /** Whether a request that hands messages over is on its way: they are handed over one request at a time, in order. */
475
+ let busy = false;
476
+ /** The tool calls said already, by the product's id for each. */
477
+ const called = new Set<string>();
478
+ /** The last error said, which the product writes twice where a turn fails of it. */
479
+ let lastError: string | undefined;
480
+ /**
481
+ * Whether the product says a message back under the id it was handed over with: a build
482
+ * known to, or one that did. Until then none is put into a turn, since one that is read and
483
+ * never said back would be handed over again with the next turn.
484
+ */
485
+ let saysBack = false;
486
+ /** The windows of the allowance as the product last said them, by name: an update says some of them. */
487
+ const allowance = new Map<string, UsageWindow>();
461
488
 
462
- const run = (messages: readonly DriverMessage[]): void => {
463
- const child = host.spawn(
464
- host.command,
465
- codexArguments({
466
- ...choice,
467
- permissions: options.permissions,
468
- conversation,
469
- // What arrived together is one turn's: every picture of it goes with the turn.
470
- images: messages.flatMap((message) =>
471
- message.images.flatMap((picture) => (picture.path === undefined ? [] : [picture.path])),
472
- ),
473
- }),
474
- { cwd: options.cwd, env: options.env },
475
- );
476
- const mine: NonNullable<typeof turn> = { child, cut: undefined, done: Promise.resolve() };
477
- const runs: Runs = {
478
- model: word(choice.model) ?? null,
479
- effort: word(choice.effort) ?? null,
480
- mode,
481
- };
482
- read.completed = false;
483
- read.failed = undefined;
484
- read.turned = false;
485
- read.messages = messages.length;
486
- read.error = undefined;
487
- read.called.clear();
489
+ const taken = (count: number): DriverEvent[] =>
490
+ Array.from({ length: count }, (): DriverEvent => ({ type: "taken" }));
491
+
492
+ const sayError = (words: string): void => {
493
+ if (words !== lastError) {
494
+ emit({
495
+ type: "event",
496
+ kind: "error",
497
+ text: words.length === 0 ? "The turn ended with an error." : words,
498
+ });
499
+ }
500
+ lastError = words;
501
+ };
502
+
503
+ /** Asks the product to stop a turn: once it said which turn it is. */
504
+ const interruptOf = (one: Turn): void => {
505
+ if (one.id === undefined || thread === undefined) {
506
+ return;
507
+ }
508
+ // Answered when the turn is over, which the product says by itself too.
509
+ void connection
510
+ .request("turn/interrupt", { threadId: thread, turnId: one.id })
511
+ .catch(() => undefined);
512
+ };
513
+
514
+ const stopTurn = (why: "message" | "stopped"): void => {
515
+ if (turn === undefined || turn.cut !== undefined) {
516
+ return;
517
+ }
518
+ turn.cut = why;
519
+ interruptOf(turn);
520
+ };
521
+
522
+ /** Starts a turn with what waited: one message, each part under its own header. */
523
+ const start = async (messages: readonly DriverMessage[]): Promise<void> => {
524
+ const mine: Turn = { id: undefined, cut: undefined, steers: true };
525
+ const entry: Handed = { id: host.uuid(), messages, steered: false };
488
526
  turn = mine;
489
- mine.done = (async () => {
490
- try {
491
- // One message: what arrived together is read together, each under its own header.
492
- await child.write(messages.map((message) => message.text).join("\n\n"));
493
- } catch {
494
- // A process that is gone takes nothing: how it ended says the rest.
495
- }
496
- child.end();
497
- try {
498
- for await (const text of child.lines) {
499
- const line = lineOf(text);
500
- if (line !== undefined) {
501
- emit(...eventsOf(line, read, runs));
502
- }
527
+ handed.push(entry);
528
+ lastError = undefined;
529
+ // Said with the turn, and kept by the conversation from then on. A choice left at the
530
+ // product's own is not said: the conversation goes on with what it ran with.
531
+ const model = word(choice.model);
532
+ const effort = word(choice.effort);
533
+ if (
534
+ (model !== undefined && model !== runs.model) ||
535
+ (effort !== undefined && effort !== runs.effort)
536
+ ) {
537
+ runs = { model: model ?? runs.model, effort: effort ?? runs.effort };
538
+ emit({ type: "running", model: runs.model, effort: runs.effort, version });
539
+ }
540
+ try {
541
+ const result = await connection.request("turn/start", {
542
+ threadId: thread ?? "",
543
+ clientUserMessageId: entry.id,
544
+ input: inputOf(messages, options.cwd),
545
+ ...(model === undefined ? {} : { model }),
546
+ ...(effort === undefined ? {} : { effort }),
547
+ });
548
+ if (turn === mine) {
549
+ mine.id ??= isObject(result) && isObject(result.turn) ? textOf(result.turn.id) : undefined;
550
+ // A stop that was asked before the product named the turn is said now.
551
+ if (mine.cut !== undefined) {
552
+ interruptOf(mine);
503
553
  }
504
- } catch {
505
- // The output closed in the middle of a line: how the process ended says the rest.
506
554
  }
507
- const exit = await child.exited;
508
- conversation = word(read.conversation) ?? conversation;
509
- turn = undefined;
510
- if (mine.cut === "ended") {
555
+ } catch (error) {
556
+ if (turn === mine) {
557
+ turn = undefined;
558
+ }
559
+ handed = handed.filter((one) => one !== entry);
560
+ if (!(error instanceof RpcError)) {
561
+ // The process is gone: how it ended is said where its output ends.
511
562
  return;
512
563
  }
513
- if (mine.cut !== undefined) {
564
+ emit({
565
+ type: "event",
566
+ kind: "error",
567
+ text: `The product refused the turn: ${error.message}`,
568
+ });
569
+ if (SIGN_IN.test(error.message)) {
570
+ // Nothing was taken: the runner sends again what it sent.
571
+ waiting = [];
572
+ handed = [];
573
+ emit({ type: "cannot_go_on", state: "failed", reason: "sign_in" });
574
+ return;
575
+ }
576
+ // A turn the product itself refused is a turn that ended: it takes the next message.
577
+ emit(...taken(messages.length));
578
+ done();
579
+ }
580
+ };
581
+
582
+ /**
583
+ * Puts a message into the turn under way. The product answers that it was put in, and says
584
+ * the message back when it reads it, after the step under way: that is when it is taken.
585
+ */
586
+ const steer = async (message: DriverMessage, into: Turn): Promise<void> => {
587
+ const entry: Handed = { id: host.uuid(), messages: [message], steered: true };
588
+ handed.push(entry);
589
+ try {
590
+ await connection.request("turn/steer", {
591
+ threadId: thread ?? "",
592
+ expectedTurnId: into.id ?? "",
593
+ clientUserMessageId: entry.id,
594
+ input: inputOf([message], options.cwd),
595
+ });
596
+ } catch {
597
+ // Not put in: the turn is over, or is one a message is put into none of. It waits for
598
+ // the turn's end, first of what waits, unless that end came first and has it wait already.
599
+ into.steers = false;
600
+ if (handed.includes(entry)) {
601
+ handed = handed.filter((one) => one !== entry);
602
+ waiting.unshift(message);
603
+ }
604
+ }
605
+ };
606
+
607
+ /** Hands over what waits, one request at a time: a turn started, or a message put into the one under way. */
608
+ const pump = (): void => {
609
+ if (busy || !ready || gaveUp || stopping || over) {
610
+ return;
611
+ }
612
+ const head = waiting[0];
613
+ if (head === undefined) {
614
+ return;
615
+ }
616
+ const after = (): void => {
617
+ busy = false;
618
+ pump();
619
+ };
620
+ if (turn === undefined) {
621
+ busy = true;
622
+ void start(waiting.splice(0)).finally(after);
623
+ return;
624
+ }
625
+ // A turn that is being stopped, or takes no message, is waited for: its end hands over.
626
+ // So is a turn of a product that has not yet said a message back.
627
+ if (turn.cut !== undefined || !turn.steers || turn.id === undefined || !saysBack) {
628
+ return;
629
+ }
630
+ busy = true;
631
+ waiting.shift();
632
+ void steer(head, turn).finally(after);
633
+ };
634
+
635
+ /** A turn ended: the agent is done when nothing it was sent still waits. */
636
+ const done = (): void => {
637
+ // A session that is being stopped says nothing more of a turn: what it was handed and
638
+ // did not take is the runner's to settle, and a turn said completed here would have the
639
+ // runner count as read what the product never got.
640
+ if (stopping) {
641
+ return;
642
+ }
643
+ if (waiting.length > 0) {
644
+ pump();
645
+ } else {
646
+ emit({ type: "turn_completed" });
647
+ }
648
+ };
649
+
650
+ /** The product said a message back: it read it, and the message is taken. */
651
+ const took = (id: string | undefined): void => {
652
+ const entry = handed.find((one) => one.id === id);
653
+ if (entry !== undefined) {
654
+ saysBack = true;
655
+ handed = handed.filter((one) => one !== entry);
656
+ emit(...taken(entry.messages.length));
657
+ }
658
+ // The message a turn began with, said back: the turn is under way, and what waited for
659
+ // the product to say one back is put into it now.
660
+ pump();
661
+ };
662
+
663
+ const onItem = (params: Json, completed: boolean): void => {
664
+ const item = isObject(params.item) ? params.item : undefined;
665
+ if (item === undefined) {
666
+ return;
667
+ }
668
+ const id = textOf(item.id);
669
+ if (item.type === "userMessage") {
670
+ took(textOf(item.clientId));
671
+ return;
672
+ }
673
+ if (!completed) {
674
+ const call = callOf(item, cut);
675
+ if (call !== undefined) {
514
676
  emit({
515
677
  type: "event",
516
- kind: "status",
517
- text:
518
- mine.cut === "message"
519
- ? "The turn was stopped for a message."
520
- : "The turn was stopped.",
678
+ kind: "tool_call",
679
+ text: call.text,
680
+ data: { tool: call.tool, id: id ?? null },
521
681
  });
522
- } else if (exit.error !== undefined) {
523
- emit(
524
- { type: "event", kind: "error", text: notStarted(exit.error, host.command) },
525
- { type: "cannot_go_on", state: "failed", reason: "start" },
526
- );
527
- // Nothing was taken: the runner sends again what it sent.
682
+ if (id !== undefined) {
683
+ called.add(id);
684
+ }
685
+ }
686
+ return;
687
+ }
688
+ if (item.type === "agentMessage") {
689
+ if (typeof item.text === "string" && item.text.length > 0) {
690
+ emit({ type: "event", kind: "assistant", text: item.text });
691
+ }
692
+ return;
693
+ }
694
+ if (item.type === "reasoning") {
695
+ const parts = [item.summary, item.content].flatMap((one) =>
696
+ Array.isArray(one) ? one.filter((part) => typeof part === "string") : [],
697
+ );
698
+ if (parts.length > 0) {
699
+ emit({ type: "event", kind: "thinking", text: parts.join("\n\n") });
700
+ }
701
+ return;
702
+ }
703
+ const call = callOf(item, cut);
704
+ if (call === undefined) {
705
+ return;
706
+ }
707
+ // A call the product wrote no beginning of is said with its end.
708
+ if (id === undefined || !called.delete(id)) {
709
+ emit({
710
+ type: "event",
711
+ kind: "tool_call",
712
+ text: call.text,
713
+ data: { tool: call.tool, id: id ?? null },
714
+ });
715
+ }
716
+ if (item.type === "webSearch") {
717
+ return;
718
+ }
719
+ const exit = typeof item.exitCode === "number" ? item.exitCode : null;
720
+ const data: Record<string, Fact> = {
721
+ id: id ?? null,
722
+ // Declined is the product's word for a call its sandbox or its reviewer did not let run.
723
+ error:
724
+ item.status === "failed" || item.status === "declined" || (exit !== null && exit !== 0),
725
+ };
726
+ if (exit !== null) {
727
+ data.exit = exit;
728
+ }
729
+ emit({ type: "event", kind: "tool_result", text: resultOf(item, cut), data, pictures: [] });
730
+ };
731
+
732
+ const onTurnCompleted = (params: Json): void => {
733
+ const ended = isObject(params.turn) ? params.turn : {};
734
+ const id = textOf(ended.id);
735
+ if (turn === undefined || (turn.id !== undefined && id !== undefined && turn.id !== id)) {
736
+ return;
737
+ }
738
+ const mine = turn;
739
+ turn = undefined;
740
+ called.clear();
741
+ if (stopping) {
742
+ return;
743
+ }
744
+ // What the product did not say it took. A turn began with its first message, which is the
745
+ // product's from then on. One put into the turn and never said back was not read: the
746
+ // product lets go of it where the turn is stopped first (seen with 0.139.0), so it is the
747
+ // next turn's, before whatever else waits.
748
+ const again: DriverMessage[] = [];
749
+ for (const one of handed) {
750
+ if (one.steered) {
751
+ again.push(...one.messages);
752
+ } else {
753
+ emit(...taken(one.messages.length));
754
+ }
755
+ }
756
+ handed = [];
757
+ waiting = [...again, ...waiting];
758
+ if (ended.status === "failed") {
759
+ sayError(errorOf(ended.error));
760
+ if (signedOut(ended.error)) {
761
+ // The runner sends again what it sent, once the product is signed in.
528
762
  waiting = [];
763
+ emit({ type: "cannot_go_on", state: "failed", reason: "sign_in" });
529
764
  return;
530
- } else if (!read.completed) {
531
- const errors = child.errors().trim();
532
- if (read.failed === undefined) {
533
- // Its end, cut after the secrets are out, so that none stands at the cut.
534
- const shown = errorsShown(errors, options.cutEnd ?? plainCutEnd);
535
- emit({
536
- type: "event",
537
- kind: "error",
538
- text: `The product's process ended${exit.signal === null ? ` with code ${exit.code}` : ` on ${exit.signal}`} before the turn did.${shown.length === 0 ? "" : `\n${shown}`}`,
539
- });
540
- }
541
- if (SIGN_IN.test(`${read.failed ?? ""}\n${errors}`)) {
542
- emit({ type: "cannot_go_on", state: "failed", reason: "sign_in" });
543
- waiting = [];
544
- return;
765
+ }
766
+ if (usageLimited(ended.error)) {
767
+ // Nothing goes better before a window resets: the runner waits, brings the agent back
768
+ // by itself, and hands over again what was not answered. Until when is the reset of
769
+ // the window the product last said is used up, where it said one.
770
+ const resets = [...allowance.values()]
771
+ .filter((window) => window.used !== undefined && window.used >= 1)
772
+ .flatMap((window) => (window.resetsAt === undefined ? [] : [window.resetsAt]));
773
+ waiting = [];
774
+ emit({
775
+ type: "cannot_go_on",
776
+ state: "failed",
777
+ reason: "usage_limit",
778
+ ...(resets.length === 0 ? {} : { until: Math.max(...resets) }),
779
+ });
780
+ return;
781
+ }
782
+ // A turn the product itself said failed is a turn that ended: the agent takes the next message.
783
+ } else if (ended.status === "interrupted") {
784
+ emit({
785
+ type: "event",
786
+ kind: "status",
787
+ text:
788
+ mine.cut === "message" ? "The turn was stopped for a message." : "The turn was stopped.",
789
+ });
790
+ }
791
+ done();
792
+ };
793
+
794
+ const onNotification = (method: string, params: Json): void => {
795
+ // The allowance is the account's, and of no thread: said on as the product says it, for
796
+ // the runner to tell its agent by.
797
+ if (method === "account/rateLimits/updated") {
798
+ // Said on where it says something new: the product writes it several times a turn
799
+ // (seen with 0.171.0, six times in a turn of one command, the same each time).
800
+ const windows = allowanceOf(params.rateLimits).filter((window) => {
801
+ const before = allowance.get(window.name);
802
+ return before?.used !== window.used || before?.resetsAt !== window.resetsAt;
803
+ });
804
+ for (const window of windows) {
805
+ allowance.set(window.name, window);
806
+ }
807
+ if (windows.length > 0 && !stopping) {
808
+ emit({ type: "usage", windows });
809
+ }
810
+ return;
811
+ }
812
+ // A thread of the product's other than the conversation's is none of the session's: what
813
+ // an agent it started does there is that agent's, and its turns are not this one's.
814
+ if (thread === undefined || params.threadId !== thread) {
815
+ return;
816
+ }
817
+ switch (method) {
818
+ case "turn/started": {
819
+ const id = isObject(params.turn) ? textOf(params.turn.id) : undefined;
820
+ if (turn === undefined) {
821
+ // A turn the product began by itself: a message that arrives now is put into it.
822
+ turn = { id, cut: undefined, steers: true };
823
+ pump();
824
+ } else {
825
+ turn.id ??= id;
545
826
  }
546
- if (read.failed === undefined) {
547
- // The product fell over without a word of the turn: nothing says that the next one
548
- // goes better, a conversation it cannot find again say (seen with 0.164.0), so the
549
- // agent cannot go on by itself. Before a turn started nothing was taken, and the
550
- // runner sends again what it sent; after, what the turn was at is not known.
551
- emit({
552
- type: "cannot_go_on",
553
- state: "failed",
554
- reason: read.turned ? "crashed" : "start",
827
+ return;
828
+ }
829
+ case "turn/completed":
830
+ onTurnCompleted(params);
831
+ return;
832
+ case "item/started":
833
+ onItem(params, false);
834
+ return;
835
+ case "item/completed":
836
+ onItem(params, true);
837
+ return;
838
+ case "error":
839
+ // A word of warning inside a turn, a try that is made again say: the turn goes on, and
840
+ // says by itself where it ends of one.
841
+ sayError(errorOf(params.error));
842
+ return;
843
+ default:
844
+ // Whatever else it writes, how the thread stands, what it plans, what its reviewer
845
+ // found, is left where it is.
846
+ return;
847
+ }
848
+ };
849
+
850
+ /** What the product asks of whoever is at its terminal: nobody is, so it is refused and recorded. */
851
+ const onRequest = (id: unknown, method: string, params: Json): void => {
852
+ const denied = (tool: string, what: string, answer: Json): void => {
853
+ const data: Record<string, Fact> = { tool, answer: "denied" };
854
+ const item = textOf(params.itemId);
855
+ if (item !== undefined) {
856
+ data.id = item;
857
+ }
858
+ emit({
859
+ type: "event",
860
+ kind: "permission",
861
+ text: `Denied, with nobody at the terminal to ask: ${cut(what, MAX_INPUT_LENGTH)}`,
862
+ data,
863
+ });
864
+ void connection.answer(id, answer).catch(() => undefined);
865
+ };
866
+ const reason = textOf(params.reason)?.trim();
867
+ switch (method) {
868
+ case "item/commandExecution/requestApproval":
869
+ denied("command_execution", textOf(params.command) ?? reason ?? "a command", {
870
+ decision: "decline",
871
+ });
872
+ return;
873
+ case "item/fileChange/requestApproval":
874
+ denied("file_change", reason ?? "a change to files", { decision: "decline" });
875
+ return;
876
+ case "item/permissions/requestApproval":
877
+ // Leave to do more than the mode allows: none is given.
878
+ denied("permissions", reason ?? "more than the mode allows", {
879
+ permissions: {},
880
+ scope: "turn",
881
+ });
882
+ return;
883
+ case "item/tool/requestUserInput":
884
+ denied("request_user_input", "a question for a person", { answers: {} });
885
+ return;
886
+ case "mcpServer/elicitation/request":
887
+ denied(
888
+ `${textOf(params.serverName) ?? "mcp"}.elicitation`,
889
+ textOf(params.message) ?? "a question for a person",
890
+ { action: "decline", content: null, _meta: null },
891
+ );
892
+ return;
893
+ default:
894
+ // No tool and no sign-in of the runner's own was offered: a product that asks for one
895
+ // all the same is told.
896
+ void connection
897
+ .refuse(id, METHOD_NOT_FOUND, `${method} is not offered`)
898
+ .catch(() => undefined);
899
+ }
900
+ };
901
+
902
+ /** Why the conversation could not open, said once; the process is ended, and nothing more is said of it. */
903
+ const cannotStart = (text: string, reason: "start" | "sign_in"): void => {
904
+ gaveUp = true;
905
+ waiting = [];
906
+ emit({ type: "event", kind: "error", text }, { type: "cannot_go_on", state: "failed", reason });
907
+ void endOf(child);
908
+ };
909
+
910
+ const open = async (): Promise<void> => {
911
+ const greeted = await connection.request("initialize", hello(host.version));
912
+ began = true;
913
+ // The build that runs, from what it calls itself: a conversation says the build that began
914
+ // it, which is another once the product was updated.
915
+ const build = codexBuild(isObject(greeted) ? greeted.userAgent : undefined);
916
+ version = build?.text ?? null;
917
+ if (build !== undefined && tooOld(build.numbers)) {
918
+ cannotStart(
919
+ `This Codex is ${build.text}, and the driver speaks to ${OLDEST.join(".")} or later, whose app server says a message back when it reads it. Update it, as it was installed.`,
920
+ "start",
921
+ );
922
+ return;
923
+ }
924
+ // A build that says which it is, and is none of the old ones, says a message back; one
925
+ // that says nothing of itself is believed once it did.
926
+ saysBack = build !== undefined;
927
+ await connection.notify("initialized");
928
+ const model = word(choice.model);
929
+ const settings: Json = {
930
+ cwd: options.cwd,
931
+ ...modeSettings(mode),
932
+ ...(model === undefined ? {} : { model }),
933
+ };
934
+ let opened: unknown;
935
+ const resume = word(options.resume);
936
+ if (resume !== undefined) {
937
+ try {
938
+ // Gone on with, without its history said again: nobody reads it here.
939
+ opened = await connection
940
+ .request("thread/resume", { threadId: resume, ...settings, excludeTurns: true })
941
+ .catch((error: unknown) => {
942
+ // A build that takes that word only as an experiment (0.139.0) is asked without it.
943
+ if (error instanceof RpcError && error.message.includes("excludeTurns")) {
944
+ return connection.request("thread/resume", { threadId: resume, ...settings });
945
+ }
946
+ throw error;
555
947
  });
556
- waiting = [];
557
- return;
948
+ } catch (error) {
949
+ // Not signed in is said as that, and a process that is gone where its output ends.
950
+ if (!(error instanceof RpcError) || SIGN_IN.test(error.message)) {
951
+ throw error;
558
952
  }
559
- // A turn the product itself said failed is a turn that ended: the agent takes the next message.
560
- }
561
- // The agent is done when nothing it was sent still waits: what arrived meanwhile is its next turn.
562
- if (waiting.length > 0) {
563
- const next = waiting;
564
- waiting = [];
565
- run(next);
566
- } else {
567
- emit({ type: "turn_completed" });
953
+ // A conversation the product has no more: said, and a new one begun, as the runner
954
+ // begins one where the conversation kept was another product's.
955
+ emit({
956
+ type: "event",
957
+ kind: "status",
958
+ text: `The product could not go on with the conversation it had (${error.message}): a new one begins.`,
959
+ });
568
960
  }
569
- })();
961
+ }
962
+ opened ??= await connection.request("thread/start", settings);
963
+ const said = isObject(opened) ? opened : {};
964
+ const named = isObject(said.thread) ? said.thread : {};
965
+ thread = word(textOf(named.id));
966
+ if (thread === undefined) {
967
+ cannotStart("The product opened a conversation and did not say which.", "start");
968
+ return;
969
+ }
970
+ // The sandbox the product says the conversation runs in. More than was asked is never
971
+ // gone on with; less is said, since it is what the agent does without asking: a product
972
+ // whose own sandbox is not set up on the machine answers its read-only one (seen on
973
+ // Windows with 0.171.0, with a home it had set nothing up in).
974
+ const asked = sandboxOf(mode);
975
+ const answered = isObject(said.sandbox) ? textOf(said.sandbox.type) : undefined;
976
+ const width = (name: string | undefined, at: 0 | 1): number =>
977
+ SANDBOXES.findIndex((one) => one[at] === name);
978
+ const sandbox = SANDBOXES[width(answered, 0)]?.[1];
979
+ // One the driver does not know by its word is said as it came: how much it allows is not
980
+ // known here, and saying nothing would read as the sandbox that was asked for.
981
+ const unknown = sandbox === undefined ? word(answered) : undefined;
982
+ if (sandbox !== undefined && width(sandbox, 1) > width(asked, 1)) {
983
+ cannotStart(
984
+ `The product opened the conversation in its sandbox ${sandbox}, which allows more than ${asked}, the one it was asked for.`,
985
+ "start",
986
+ );
987
+ return;
988
+ }
989
+ runs = {
990
+ model: word(textOf(said.model)) ?? model ?? null,
991
+ effort: word(textOf(said.reasoningEffort)) ?? null,
992
+ };
993
+ emit(
994
+ { type: "conversation", id: thread },
995
+ { type: "running", model: runs.model, effort: runs.effort, version },
996
+ {
997
+ type: "event",
998
+ kind: "status",
999
+ text:
1000
+ unknown !== undefined
1001
+ ? `The product started, in a sandbox the driver does not know, ${unknown}, and not in ${asked}, which it was asked for.`
1002
+ : sandbox === undefined || sandbox === asked
1003
+ ? "The product started."
1004
+ : `The product started, in its sandbox ${sandbox} and not in ${asked}, which it was asked for.`,
1005
+ data: {
1006
+ model: runs.model,
1007
+ effort: runs.effort,
1008
+ version,
1009
+ mode,
1010
+ ...(unknown !== undefined
1011
+ ? { sandbox: unknown }
1012
+ : sandbox === undefined || sandbox === asked
1013
+ ? {}
1014
+ : { sandbox }),
1015
+ },
1016
+ },
1017
+ );
1018
+ ready = true;
1019
+ pump();
570
1020
  };
571
1021
 
1022
+ void (async () => {
1023
+ const reading = connection.read({ notification: onNotification, request: onRequest });
1024
+ const opening = open().catch((error: unknown) => {
1025
+ if (gaveUp || stopping) {
1026
+ return;
1027
+ }
1028
+ if (error instanceof RpcError) {
1029
+ const signIn = SIGN_IN.test(error.message);
1030
+ cannotStart(
1031
+ signIn
1032
+ ? `The product is not signed in: ${error.message}`
1033
+ : `The product did not open a conversation: ${error.message}`,
1034
+ signIn ? "sign_in" : "start",
1035
+ );
1036
+ }
1037
+ // Anything else is a process that is gone: how it ended is said where its output ends.
1038
+ });
1039
+ void wait(START_TIMEOUT_MS).then(() => {
1040
+ if (!ready && !gaveUp && !stopping) {
1041
+ cannotStart("The product did not open a conversation in time.", "start");
1042
+ }
1043
+ });
1044
+ await reading;
1045
+ over = true;
1046
+ await opening;
1047
+ const exit = await child.exited;
1048
+ const clean = stopping || (exit.code === 0 && exit.signal === null && exit.error === undefined);
1049
+ if (!clean && !gaveUp) {
1050
+ const errors = child.errors().trim();
1051
+ // Its end, cut after the secrets are out, so that none stands at the cut.
1052
+ const shown = errorsShown(errors, options.cutEnd ?? plainCutEnd);
1053
+ const how = exit.signal === null ? ` with code ${exit.code}` : ` on ${exit.signal}`;
1054
+ emit(
1055
+ {
1056
+ type: "event",
1057
+ kind: "error",
1058
+ text:
1059
+ exit.error !== undefined
1060
+ ? notStarted(exit.error, host.command)
1061
+ : `The product's process ended${how}${began ? "" : " before it answered as its app server, which this driver speaks to (codex app-server)"}.${shown.length === 0 ? "" : `\n${shown}`}`,
1062
+ },
1063
+ {
1064
+ type: "cannot_go_on",
1065
+ state: "failed",
1066
+ // Before the conversation was open nothing was taken, and the runner sends again
1067
+ // what it sent; after, what a turn was at is not known.
1068
+ // What it wrote of a sign-in counts before the conversation opened alone: after, a
1069
+ // turn says so itself, and a line written long before is no reason for this end.
1070
+ reason: ready ? "crashed" : SIGN_IN.test(errors) ? "sign_in" : "start",
1071
+ },
1072
+ );
1073
+ }
1074
+ emit({ type: "ended", how: clean ? "exited" : "crashed" });
1075
+ })();
1076
+
572
1077
  return {
573
1078
  events: events(),
574
1079
  async send(message) {
575
- if (over) {
1080
+ // Kept by the runner, where it is not handed over: a product that is gone takes nothing.
1081
+ if (stopping || gaveUp || over) {
576
1082
  throw new Error("the session takes no more input");
577
1083
  }
578
- if (turn === undefined) {
579
- run([message]);
580
- return;
581
- }
582
1084
  waiting.push(message);
583
- // The product takes no message in a turn: one to be read now ends the turn's process.
584
- if (message.priority === "now" && turn.cut === undefined) {
585
- turn.cut = "message";
586
- void endOf(turn.child);
1085
+ // One that is to be read now stops the turn under way, and is the turn after.
1086
+ if (message.priority === "now") {
1087
+ stopTurn("message");
587
1088
  }
1089
+ pump();
588
1090
  },
589
1091
  async interrupt() {
590
- if (turn !== undefined && turn.cut === undefined) {
591
- turn.cut = "stopped";
592
- void endOf(turn.child);
593
- }
1092
+ stopTurn("stopped");
594
1093
  },
595
- // Each turn is started with them: taken from the next turn on.
1094
+ // Said with the next turn that is started, and the conversation's from then on.
596
1095
  async set(next) {
597
1096
  choice = {
598
1097
  model: next.model === undefined ? choice.model : next.model,
@@ -601,18 +1100,12 @@ function sessionOf(
601
1100
  return true;
602
1101
  },
603
1102
  async stop() {
604
- if (over) {
1103
+ if (stopping) {
605
1104
  return;
606
1105
  }
607
- over = true;
1106
+ stopping = true;
608
1107
  waiting = [];
609
- const open = turn;
610
- if (open !== undefined) {
611
- open.cut = "ended";
612
- await endOf(open.child);
613
- await open.done;
614
- }
615
- emit({ type: "ended", how: "exited" });
1108
+ await endOf(child);
616
1109
  },
617
1110
  };
618
1111
  }
@@ -649,11 +1142,18 @@ function offeredOf(text: string): { models: string[]; efforts: string[] } {
649
1142
  return { models, efforts };
650
1143
  }
651
1144
 
652
- /** The builds of the binary the driver was run against: what the fixtures of the tests were written down from. */
653
- const TRIED = ["0.164.0-alpha.11.1"] as const;
1145
+ /**
1146
+ * The builds of the binary the driver ran a turn of a signed-in product against, on Windows
1147
+ * (2026-11-24): a turn with a command and a file written in the desk, a message put into a turn
1148
+ * while a command ran, a turn stopped for a message, and the allowance as the product says it.
1149
+ * The app server was spoken to signed out with 0.139.0, 0.167.0 and 0.172.0, which is where the
1150
+ * shapes of the tests that say so were written down from.
1151
+ */
1152
+ const TRIED: readonly string[] = ["0.171.0-alpha.13.2"];
654
1153
 
655
1154
  export function createCodexDriver(host: DriverHost): Driver {
656
1155
  const command = host.command ?? "codex";
1156
+ const uuid = host.uuid ?? randomUUID;
657
1157
  /** What the product prints for a command that asks it something, or nothing where it could not be asked. */
658
1158
  const asked = async (args: readonly string[]): Promise<string | undefined> => {
659
1159
  try {
@@ -674,9 +1174,9 @@ export function createCodexDriver(host: DriverHost): Driver {
674
1174
  return {
675
1175
  name: "codex",
676
1176
  product: { name: "Codex", tried: TRIED },
677
- // No message is taken in a turn, and a picture is taken as a file, which the driver has
678
- // nowhere to write: neither is offered. The model and the effort are each turn's.
679
- can: { steer: false, images: true, imageFiles: true, resume: true, set: true },
1177
+ // A message is put into the turn under way. A picture is taken as a file, by its path in
1178
+ // the desk. The model and the effort are said with a turn, and taken from the next one on.
1179
+ can: { steer: true, images: true, imageFiles: true, resume: true, set: true },
680
1180
  permissions: { modes: MODES, unattended: UNATTENDED_MODE, least: LEAST_MODE },
681
1181
  async probe() {
682
1182
  // One line: what the command is called, then its version.
@@ -686,7 +1186,11 @@ export function createCodexDriver(host: DriverHost): Driver {
686
1186
  return { version, models: offered.models, efforts: offered.efforts };
687
1187
  },
688
1188
  start(options) {
689
- return sessionOf({ spawn: host.spawn, command }, options);
1189
+ return sessionOf(
1190
+ host.spawn(command, ARGUMENTS, { cwd: options.cwd, env: options.env }),
1191
+ { command, version: host.version, uuid },
1192
+ options,
1193
+ );
690
1194
  },
691
1195
  };
692
1196
  }