@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
@@ -21,6 +21,9 @@ import {
21
21
  GROUP_WINDOW_MS,
22
22
  introOf,
23
23
  makeMark,
24
+ type Slept,
25
+ sleptOf,
26
+ wakeTextOf,
24
27
  } from "./message.js";
25
28
  import { cutShown, cutShownEnd, type Redactor, redactorOf } from "./redact.js";
26
29
  import type {
@@ -33,11 +36,25 @@ import type {
33
36
  WakeHost,
34
37
  WakeSource,
35
38
  } from "./types.js";
39
+ import {
40
+ type Limited,
41
+ limitWords,
42
+ noteUsage,
43
+ RESET_MARGIN_MS,
44
+ runnerSays,
45
+ type ToldOfUsage,
46
+ type UsageSeen,
47
+ usageSaid,
48
+ usageToTell,
49
+ usageWords,
50
+ } from "./usage.js";
36
51
 
37
52
  // The runner (ADR-0085, docs/specs/runner.md): one process per agent account on its machine. It
38
53
  // keeps one session of the agent's product at a time, feeds it what the console sends, reports
39
54
  // what the product does, and says every thirty seconds that it is there. It restarts nothing by
40
- // itself: an agent that cannot go on waits, and a supervisor's signal is what is tried next.
55
+ // itself: an agent that cannot go on waits, and a supervisor's signal is what is tried next,
56
+ // but for an agent its product's usage limit stopped, which the runner brings back by itself
57
+ // when the limit resets (ADR-0150).
41
58
  // The one thing it ends for by itself is an update of the command it runs from (ADR-0101): when
42
59
  // no turn is under way, for the service that keeps it to start it again with the new one.
43
60
  //
@@ -53,6 +70,18 @@ export const BATCH_MS = 1000;
53
70
  /** How long what arrives by itself waits after the agent could not go on: at first, and at most, twice as long after each try that ends the same way. */
54
71
  export const COOL_DOWN_MS = 15 * 60_000;
55
72
  export const MAX_COOL_DOWN_MS = 4 * 60 * 60_000;
73
+ /**
74
+ * How long the runner holds an ending that waits for the agent's turn, a model chosen, the
75
+ * account's own reset, an update or a `runner.json` that changed, for the sub-agents at work
76
+ * in the background of the session (ADR-0162): counted from when it first held one for them.
77
+ */
78
+ export const SUBAGENTS_MS = 60 * 60_000;
79
+ /**
80
+ * How long a session that had sub-agents in the background is not taken for idle after one
81
+ * ended or a turn did: the product hands the agent a sub-agent's report in a turn it starts
82
+ * itself, a moment after.
83
+ */
84
+ export const REPORT_MS = 10_000;
56
85
  /** How long the runner waits before it asks for its stream of signals again. */
57
86
  export const RECONNECT_MS = 5000;
58
87
  /** What an autosave's commit says: the runner's, and never the agent's own words. */
@@ -68,6 +97,26 @@ export const MAX_HOLD_MS = 15 * 60_000;
68
97
  export const MAX_SOURCE_PAUSE_MS = 5 * 60_000;
69
98
  /** How long a wake source holds before the runner takes it to have worked. */
70
99
  const SOURCE_HELD_MS = 60_000;
100
+ /**
101
+ * How far past a heartbeat's interval the clock is, when the runner looks at it, before the
102
+ * runner takes itself not to have run in between: a process that runs is never a minute late
103
+ * for a timer of its own.
104
+ */
105
+ const SLEPT_MS = 60_000;
106
+ /** The kinds of event that are the agent's own answer: what it said, thought or called. */
107
+ const ANSWERS: ReadonlySet<TranscriptKind> = new Set(["assistant", "thinking", "tool_call"]);
108
+ /** How many signals the runner writes down as kept for the agent beside what the record sends again. */
109
+ const MAX_KEPT = 50;
110
+ /** How long before its moment a timer may ring: a delivery asked for at a moment is taken within it. */
111
+ const TIMER_EARLY_MS = 20;
112
+ /**
113
+ * The furthest off a product's usage limit is waited for at the moment it names: longer than
114
+ * any window a subscription counts in, a month. A moment past it is taken for none, and the
115
+ * runner tries after the cool-down instead.
116
+ */
117
+ const MAX_LIMIT_MS = 32 * 24 * 3_600_000;
118
+ /** How many messages a turn took are remembered, for a turn that ends on the usage limit: the oldest is let go past it. */
119
+ const MAX_TAKEN = 200;
71
120
  /** The kinds of file a console keeps as a picture: what a product is handed as one. */
72
121
  const PICTURE_TYPES: ReadonlySet<string> = new Set([
73
122
  "image/png",
@@ -106,7 +155,9 @@ export type RunnerClient = Pick<
106
155
  | "secret"
107
156
  | "readSignalFile"
108
157
  | "raiseWake"
109
- >;
158
+ > &
159
+ // Who wrote at a messenger (ADR-0164): asked where the client has it, by a wake source.
160
+ Partial<Pick<ConsoleClient, "writers">>;
110
161
 
111
162
  /** What the runner keeps between its own restarts. No secret is in it. */
112
163
  export interface RunnerState {
@@ -125,6 +176,18 @@ export interface RunnerState {
125
176
  * say, it is taken as this driver's.
126
177
  */
127
178
  readonly driver?: string | undefined;
179
+ /**
180
+ * The usage limit that stopped the agent and that it is not back from (ADR-0150): since
181
+ * when, and until when where the product said. Kept, so that a runner started meanwhile
182
+ * brings the agent back all the same.
183
+ */
184
+ readonly limited?: Limited | undefined;
185
+ /**
186
+ * The numbers of the signals the record has as delivered and the agent never read, since a
187
+ * usage limit stopped it (ADR-0150): the console sends none of them again by itself, so a
188
+ * runner started meanwhile takes them from the stream once more.
189
+ */
190
+ readonly kept?: readonly number[] | undefined;
128
191
  }
129
192
 
130
193
  export interface RunnerOptions {
@@ -133,6 +196,11 @@ export interface RunnerOptions {
133
196
  readonly config: RunnerConfig;
134
197
  /** The desk: the directory the runner was started in. */
135
198
  readonly cwd: string;
199
+ /**
200
+ * The id of the account the runner is: a `reset` that account sent is its own (ADR-0154),
201
+ * taken when the turn under way is over. Left out, every reset is a supervisor's.
202
+ */
203
+ readonly account?: string | undefined;
136
204
  readonly machine: { readonly name: string; readonly os: string; readonly user: string };
137
205
  /** The version of the package the runner runs from. */
138
206
  readonly version: string;
@@ -151,6 +219,13 @@ export interface RunnerOptions {
151
219
  readonly random: () => number;
152
220
  /** A moment as a header says it: the hour and the minute in the workspace's zone. */
153
221
  readonly time: (iso: string) => string;
222
+ /**
223
+ * A moment with its day, as the command prints one, for what the runner says of a moment that
224
+ * may be on another day: a stretch the runner did not run in, when a window of the product's
225
+ * allowance resets, and from when a usage limit stopped the agent. Left out, as ISO 8601
226
+ * says it, in UTC.
227
+ */
228
+ readonly moment?: ((iso: string) => string) | undefined;
154
229
  /**
155
230
  * Files under the desk's ignored `work/`, written for their owner alone: what a session is
156
231
  * handed of the account's store, removed at its end, and what came with a signal, under
@@ -204,6 +279,9 @@ export interface RunnerOptions {
204
279
  reconnectMs: number;
205
280
  holdMs: number;
206
281
  maxHoldMs: number;
282
+ resetMarginMs: number;
283
+ subagentsMs: number;
284
+ reportMs: number;
207
285
  }>;
208
286
  /** The bounds, for a test to lower. */
209
287
  readonly bounds?: Partial<{ outboxBytes: number }>;
@@ -237,6 +315,12 @@ interface Outgoing {
237
315
  gone?: number;
238
316
  }
239
317
 
318
+ /** What an ending is for, as the record says it of one that waits for sub-agents (ADR-0162). */
319
+ const FOR_UPDATE = "for an update of the command the runner runs from";
320
+ const FOR_CHANGE = "for the desk's runner.json, which changed";
321
+ const FOR_CHOICE = "for the model or the effort chosen";
322
+ const FOR_RESET = "for the account's own reset";
323
+
240
324
  /** What an event takes of a batch as the console counts one: its JSON, and the ids of its pictures. */
241
325
  const sentBytes = (event: Outgoing): number =>
242
326
  Buffer.byteLength(
@@ -285,6 +369,31 @@ interface OpenSession {
285
369
  * has not is still starting, for all the runner knows: it took nothing it was handed.
286
370
  */
287
371
  took: boolean;
372
+ /**
373
+ * The signals of the messages the product took in the turn under way, a message each, the
374
+ * oldest first, and how many of the last of them the agent has not answered since: none once
375
+ * it said or did anything. A turn that ends on the usage limit left those unread (ADR-0150).
376
+ */
377
+ taken: (readonly RestSignal[])[];
378
+ unread: number;
379
+ /** Whether the agent was handed word that it is back from a usage limit, and has not answered since. */
380
+ returning: boolean;
381
+ /** How many sub-agents are at work in its background, as the driver said last (ADR-0162). */
382
+ background: number;
383
+ /**
384
+ * Whether the product said it began a turn that did not end since. With no turn of the
385
+ * runner's under way, it is one the product started itself, as it does to hand the agent the
386
+ * report of a sub-agent that ended.
387
+ */
388
+ own: boolean;
389
+ /** Until when the product is left to start such a turn: 0 in a session that had no sub-agent in the background. */
390
+ reportBy: number;
391
+ /**
392
+ * Since when the runner holds an ending for what goes on with no turn of its own under way
393
+ * (ADR-0162), and whether the record says that it waits and that it waited in vain.
394
+ */
395
+ heldSince?: number | undefined;
396
+ heldSaid?: "waits" | "over" | undefined;
288
397
  /** The number of the last event of it. */
289
398
  n: number;
290
399
  /** What the product did and the console has not been sent yet, and what that holds of memory. */
@@ -305,7 +414,15 @@ interface OpenSession {
305
414
 
306
415
  type Message =
307
416
  | { readonly t: "signal"; readonly signal: RestSignal }
308
- | { readonly t: "driver"; readonly session: OpenSession; readonly event: DriverEvent }
417
+ | {
418
+ readonly t: "driver";
419
+ readonly session: OpenSession;
420
+ readonly event: DriverEvent;
421
+ /** For an agent that cannot go on: how many of the last messages the product took the agent had not answered. */
422
+ readonly unread?: number | undefined;
423
+ }
424
+ /** The agent answered again, after it was handed word that it is back from a usage limit. */
425
+ | { readonly t: "answered"; readonly session: OpenSession }
309
426
  | { readonly t: "deliver" }
310
427
  | { readonly t: "flush" }
311
428
  | { readonly t: "heartbeat" }
@@ -383,12 +500,16 @@ export function createRunner(options: RunnerOptions): Runner {
383
500
  reconnectMs: RECONNECT_MS,
384
501
  holdMs: HOLD_MS,
385
502
  maxHoldMs: MAX_HOLD_MS,
503
+ resetMarginMs: RESET_MARGIN_MS,
504
+ subagentsMs: SUBAGENTS_MS,
505
+ reportMs: REPORT_MS,
386
506
  ...options.timing,
387
507
  };
388
508
  /** How long what an hour's bound refused is held back: the first time, and twice as long each time after. */
389
509
  const heldFor = (before: { readonly pause: number } | undefined): number =>
390
510
  before === undefined ? timing.holdMs : Math.min(before.pause * 2, timing.maxHoldMs);
391
511
  const bounds = { outboxBytes: MAX_OUTBOX_BYTES, ...options.bounds };
512
+ const moment = options.moment ?? ((iso: string): string => iso);
392
513
 
393
514
  // What keeps failing is said once, and again when what is said of it changes, so that an hour
394
515
  // without the console is a line and not thousands; that it is over is said once too.
@@ -462,8 +583,34 @@ export function createRunner(options: RunnerOptions): Runner {
462
583
  let held = false;
463
584
  /** The agent could not go on: how many tries ended so, and when what arrives by itself goes next. */
464
585
  let waits: { tries: number; until: number } | undefined;
465
- /** The next session begins a new conversation, and says who reset it. */
466
- let resetBy: string | undefined;
586
+ /**
587
+ * The product's usage limit stopped the agent (ADR-0150): since when, until when where the
588
+ * product said, and whether the agent was handed word of it since the product last refused.
589
+ * `tried` is the supervisor's signals that were tried ahead of the reset and refused, by
590
+ * number: each is tried so once, and waits with the rest from then on. It stands until the
591
+ * agent answers again.
592
+ */
593
+ let limited:
594
+ | { since: number; until: number | undefined; handed: boolean; readonly tried: Set<number> }
595
+ | undefined;
596
+ /** What the agent was told of each window of its product's allowance: the mark it had reached, and when that window resets. */
597
+ let usageTold = new Map<string, ToldOfUsage>();
598
+ /** What the product last said of each window of its allowance, which the console is told with the heartbeat (ADR-0156). */
599
+ const usageSeen: UsageSeen = new Map();
600
+ /**
601
+ * The signals a runner before this one kept unread, by number: taken from the stream once
602
+ * more, and until when the runner waits for them before it brings the agent back. And what
603
+ * the state file last said is kept so.
604
+ */
605
+ const reread = new Set<number>();
606
+ let rereadBy = 0;
607
+ let keptSaved = "";
608
+ /** The console is one of before the word `usage_limit`: it is said the nearest word it takes. */
609
+ let plainWords = false;
610
+ /** The next session begins a new conversation, and says who reset it, and under which header why. */
611
+ let resetBy: { by: string; own?: boolean; number?: number } | undefined;
612
+ /** The account's own reset (ADR-0154), which waits for the turn under way to end: owed until then, so not delivered. */
613
+ let ownReset: RestSignal | undefined;
467
614
  /** The open session is to end as soon as no turn is under way: what was chosen for it is taken when one starts. */
468
615
  let renew = false;
469
616
  let deliverAt: number | undefined;
@@ -495,6 +642,12 @@ export function createRunner(options: RunnerOptions): Runner {
495
642
  | undefined;
496
643
  let reconfigure = false;
497
644
  let toldOf: string | undefined;
645
+ /**
646
+ * When the runner last looked at the clock, and the time it did not run in that its agent is
647
+ * still to be told of: said with the next message the agent is handed.
648
+ */
649
+ let lookedAt = options.now();
650
+ let slept: Slept | undefined;
498
651
  /** How each wake source stands, by its name: what the heartbeat says of them. */
499
652
  const sources = new Map<
500
653
  string,
@@ -508,9 +661,37 @@ export function createRunner(options: RunnerOptions): Runner {
508
661
  const sentBefore = new Set<number>();
509
662
  const lastTry = new Set<number>();
510
663
 
664
+ /**
665
+ * The signals this runner alone still holds for the agent: delivered by the record, since the
666
+ * product took them, and to be handed over again, since the agent never read them.
667
+ */
668
+ const keptOf = (): number[] =>
669
+ [
670
+ ...new Set([
671
+ ...reread,
672
+ ...pending.map((signal) => signal.number),
673
+ ...owed,
674
+ // The account's own reset, which waits for its turn to end.
675
+ ...(ownReset === undefined ? [] : [ownReset.number]),
676
+ ]),
677
+ ]
678
+ .filter((number) => number <= delivered)
679
+ .sort((one, other) => one - other)
680
+ .slice(0, MAX_KEPT);
681
+
511
682
  const persist = async (): Promise<void> => {
683
+ const kept = keptOf();
684
+ keptSaved = kept.join(",");
512
685
  try {
513
- await options.state.save({ delivered, conversation, driver: driver.name });
686
+ await options.state.save({
687
+ delivered,
688
+ conversation,
689
+ driver: driver.name,
690
+ ...(limited === undefined
691
+ ? {}
692
+ : { limited: { since: limited.since, until: limited.until } }),
693
+ ...(kept.length === 0 ? {} : { kept }),
694
+ });
514
695
  } catch {
515
696
  log("the runner's state could not be written; it goes on from the console's record");
516
697
  }
@@ -788,13 +969,91 @@ export function createRunner(options: RunnerOptions): Runner {
788
969
  }
789
970
  };
790
971
 
972
+ /** Whether something goes on in a session with no turn of the runner's under way: sub-agents in the background, or a turn the product started or is about to. */
973
+ const goesOn = (target: OpenSession): boolean =>
974
+ target.background > 0 || target.own || options.now() < target.reportBy;
975
+
976
+ /**
977
+ * Whether an ending is held still for what goes on in the session (ADR-0162): for as long as
978
+ * the runner waits for it, counted from when it first held an ending so, and said on the
979
+ * record once where sub-agents are what it waits for, and once more where it waited in vain.
980
+ */
981
+ const within = (target: OpenSession, why: string): boolean => {
982
+ const now = options.now();
983
+ target.heldSince ??= now;
984
+ const waits = now - target.heldSince < timing.subagentsMs;
985
+ const word = waits ? "waits" : "over";
986
+ if (target.background > 0 && target.heldSaid !== word) {
987
+ target.heldSaid = word;
988
+ const many = `${target.background} ${target.background === 1 ? "sub-agent" : "sub-agents"} at work in the background`;
989
+ const most = `${Math.round(timing.subagentsMs / 60_000)} minutes`;
990
+ record(
991
+ target,
992
+ "status",
993
+ waits
994
+ ? `The session is to end ${why}, with ${many}: the runner waits until none is at work, ${most} at most.`
995
+ : `The runner waited ${most} for the sub-agents in the background, and waits no longer: the session ends ${why}, with ${many}.`,
996
+ );
997
+ log(
998
+ `session ${target.id} is to end ${why}, with ${many}: the runner ${waits ? "waits for them" : "waited for long enough"}`,
999
+ );
1000
+ }
1001
+ return waits;
1002
+ };
1003
+
1004
+ /**
1005
+ * Whether a session is at work, for an ending that waits until it is not: a turn is under
1006
+ * way, or sub-agents work on in the background, or the product started a turn of its own,
1007
+ * the last two for as long as the runner waits for them. What a supervisor ends, a stop, a
1008
+ * restart or a reset, asks nothing of it.
1009
+ */
1010
+ const busy = (target: OpenSession | undefined, why: string): boolean =>
1011
+ target !== undefined && (target.turn || (goesOn(target) && within(target, why)));
1012
+
1013
+ /**
1014
+ * Whether the runner is to end for an update and hands nothing more over (ADR-0101). Not
1015
+ * while it waits for sub-agents in the background: that may take an hour, in which the agent
1016
+ * goes on reading what it is sent.
1017
+ */
1018
+ const closing = (): boolean =>
1019
+ updatedTo !== undefined &&
1020
+ !(session !== undefined && session.background > 0 && within(session, FOR_UPDATE));
1021
+
791
1022
  /** Reads what the product does: the blocks are numbered and kept as they arrive, its own words go to the queue. */
792
1023
  const pump = async (target: OpenSession): Promise<void> => {
793
1024
  try {
794
1025
  for await (const event of target.driver.events) {
795
1026
  if (event.type === "event") {
1027
+ // What the agent itself said or did, and no sub-agent of its: it has read what it
1028
+ // was handed before.
1029
+ if (ANSWERS.has(event.kind) && event.data?.parent === undefined) {
1030
+ target.unread = 0;
1031
+ if (target.returning) {
1032
+ target.returning = false;
1033
+ push({ t: "answered", session: target });
1034
+ }
1035
+ }
796
1036
  record(target, event.kind, event.text, event.data, event.pictures);
1037
+ } else if (event.type === "background") {
1038
+ target.background = event.agents;
1039
+ target.reportBy = options.now() + timing.reportMs;
1040
+ } else if (event.type === "turn_started") {
1041
+ target.own = true;
1042
+ } else if (event.type === "cannot_go_on") {
1043
+ target.own = false;
1044
+ // Counted here, in the order the product wrote: the queue is behind what is read.
1045
+ push({ t: "driver", session: target, event, unread: target.unread });
797
1046
  } else {
1047
+ if (event.type === "taken") {
1048
+ target.unread += 1;
1049
+ } else if (event.type === "turn_completed") {
1050
+ target.unread = 0;
1051
+ target.own = false;
1052
+ // A report that came while the turn was under way is read in the next.
1053
+ if (target.reportBy > 0) {
1054
+ target.reportBy = options.now() + timing.reportMs;
1055
+ }
1056
+ }
798
1057
  push({ t: "driver", session: target, event });
799
1058
  }
800
1059
  }
@@ -883,6 +1142,12 @@ export function createRunner(options: RunnerOptions): Runner {
883
1142
  sent: [],
884
1143
  handed: [],
885
1144
  took: false,
1145
+ taken: [],
1146
+ unread: 0,
1147
+ returning: false,
1148
+ background: 0,
1149
+ own: false,
1150
+ reportBy: 0,
886
1151
  n: 0,
887
1152
  outbox: [],
888
1153
  waiting: 0,
@@ -988,16 +1253,60 @@ export function createRunner(options: RunnerOptions): Runner {
988
1253
  }
989
1254
  };
990
1255
 
1256
+ /**
1257
+ * Looks whether the runner ran since it last looked, with every heartbeat's timer and before
1258
+ * a message is handed over. Where the clock is a minute or more past where such a timer
1259
+ * leaves it, the runner did not run in between: the machine was asleep, most likely, whatever
1260
+ * holds it awake. Read from the clock alone, which is the same on every system, and from no
1261
+ * log of one. Said in the runner's own line, and kept for the agent with what was kept before.
1262
+ * A look is the timer's own and waits for no turn of the queue: a step of the runner's that
1263
+ * takes long is no time it did not run in.
1264
+ */
1265
+ const look = (): void => {
1266
+ const now = options.now();
1267
+ const before = lookedAt;
1268
+ lookedAt = now;
1269
+ if (now - before < timing.heartbeatMs + SLEPT_MS) {
1270
+ return;
1271
+ }
1272
+ slept = {
1273
+ from: slept?.from ?? before,
1274
+ to: now,
1275
+ lasted: (slept?.lasted ?? 0) + now - before,
1276
+ times: (slept?.times ?? 0) + 1,
1277
+ };
1278
+ log(
1279
+ `the runner did not run from ${new Date(before).toISOString()} to ${new Date(now).toISOString()}: the machine was asleep, most likely`,
1280
+ );
1281
+ };
1282
+
991
1283
  /** Hands the product what is pending, as one message; begins a session where none is open. */
992
1284
  const deliver = async (priority: "now" | "next"): Promise<void> => {
993
1285
  deliverAt = undefined;
994
1286
  // Nothing more is handed over once the runner is to end for an update: what waits is sent
995
1287
  // again by the console, in order, to the runner started after.
996
- if (held || updatedTo !== undefined || pending.length === 0) {
1288
+ if (held || closing()) {
997
1289
  return;
998
1290
  }
999
- // An agent that could not go on is tried at once for a supervisor, and after the cool-down for the rest.
1000
- if (waits !== undefined && !pending.some((signal) => signal.source === "person")) {
1291
+ // An agent its usage limit stopped is brought back by the runner itself, with nothing to
1292
+ // hand it too: word that it is back is a message of its own.
1293
+ const back = limited !== undefined && !limited.handed;
1294
+ // What a runner before this one kept unread comes from the stream first: the agent is not
1295
+ // brought back without it, for the moment the stream takes.
1296
+ if (reread.size > 0 && options.now() < rereadBy) {
1297
+ scheduleDeliver(rereadBy);
1298
+ return;
1299
+ }
1300
+ if (pending.length === 0 && !back) {
1301
+ return;
1302
+ }
1303
+ // An agent that could not go on is tried at once for a supervisor, and after the cool-down
1304
+ // for the rest: for one a usage limit stopped, when the limit resets. Under a usage limit
1305
+ // a supervisor's signal is tried so once: one the product refused waits with the rest, or
1306
+ // everything that arrived afterwards would hand it to a product that refuses again.
1307
+ const ahead = (signal: RestSignal): boolean =>
1308
+ signal.source === "person" && limited?.tried.has(signal.number) !== true;
1309
+ if (waits !== undefined && !pending.some(ahead)) {
1001
1310
  if (options.now() < waits.until) {
1002
1311
  scheduleDeliver(waits.until);
1003
1312
  return;
@@ -1011,7 +1320,16 @@ export function createRunner(options: RunnerOptions): Runner {
1011
1320
  ((config.conversation === "daily" && signal.key === "day") ||
1012
1321
  (config.conversation !== "continuous" && signal.key === "week")),
1013
1322
  );
1014
- if (anew && session?.turn !== true) {
1323
+ // An agent that is back from a usage limit goes on in the conversation it was stopped in:
1324
+ // what it was doing is there, and the day after begins the next one.
1325
+ // Not with sub-agents at work in its background either (ADR-0162): the conversation they
1326
+ // report to goes on, as it does under a turn.
1327
+ if (
1328
+ anew &&
1329
+ session?.turn !== true &&
1330
+ (session === undefined || !goesOn(session)) &&
1331
+ limited === undefined
1332
+ ) {
1015
1333
  await end("restarted");
1016
1334
  conversation = undefined;
1017
1335
  }
@@ -1022,8 +1340,20 @@ export function createRunner(options: RunnerOptions): Runner {
1022
1340
  scheduleDeliver(waits.until);
1023
1341
  return;
1024
1342
  }
1025
- const batch = pending;
1026
- pending = [];
1343
+ // Under a usage limit, before the runner's own try, a supervisor's signals alone are tried:
1344
+ // what else is kept stays kept, and undelivered, for a product that most likely refuses.
1345
+ // The runner's own try is the one its timer rings for, which may be a moment before the
1346
+ // clock says it is time: taken for a supervisor's, it would be said in the words of a try
1347
+ // that is ahead of the reset, and counted as one.
1348
+ const early =
1349
+ limited !== undefined && waits !== undefined && options.now() < waits.until - TIMER_EARLY_MS;
1350
+ const batch = early ? pending.filter(ahead) : pending;
1351
+ pending = early ? pending.filter((signal) => !ahead(signal)) : [];
1352
+ if (early) {
1353
+ for (const signal of batch) {
1354
+ limited?.tried.add(signal.number);
1355
+ }
1356
+ }
1027
1357
  // The files a supervisor sent, read from the console and written in the desk, under its
1028
1358
  // ignored work/, for the agent to open; a picture is handed to the product as a picture
1029
1359
  // too, where the product takes one. What could not be handed over is said to the agent in
@@ -1086,18 +1416,52 @@ export function createRunner(options: RunnerOptions): Runner {
1086
1416
  time: options.time,
1087
1417
  attached: (signal) => attached.get(signal.number) ?? [],
1088
1418
  });
1089
- const intro = target.first
1090
- ? introOf(target.mark, resetBy === undefined ? undefined : { by: resetBy })
1091
- : undefined;
1092
- const text = [intro, composed.text].filter((part) => part !== undefined).join("\n\n");
1419
+ const intro = target.first ? introOf(target.mark, resetBy) : undefined;
1420
+ // What the runner says of its own goes ahead of the signals, under its own header: that
1421
+ // the agent is back from a usage limit, and a stretch the runner did not run in, which is
1422
+ // said in the turn that follows anyway and in none of its own. The stretch is looked for
1423
+ // here too: a timer that counts no time the machine sleeps in fires a while after it woke.
1424
+ const returned = back ? limited : undefined;
1425
+ look();
1426
+ const told = slept;
1427
+ const text = [
1428
+ intro,
1429
+ returned === undefined
1430
+ ? undefined
1431
+ : runnerSays(
1432
+ target.mark,
1433
+ limitWords(returned, { now: options.now(), moment, follow: batch.length, early }),
1434
+ ),
1435
+ told === undefined ? undefined : sleptOf(told, { mark: target.mark, moment }),
1436
+ composed.text,
1437
+ ]
1438
+ .filter((part) => part !== undefined)
1439
+ .join("\n\n");
1093
1440
  try {
1094
1441
  await target.driver.send({ text, images, priority });
1095
1442
  } catch (error) {
1096
1443
  // Not handed over: kept, and what the product says of itself decides what is next.
1097
1444
  log(`a message could not be handed to the product (${codeOf(error)})`);
1098
- pending = [...batch, ...pending];
1445
+ pending = [...batch, ...pending].sort((one, other) => one.number - other.number);
1099
1446
  return;
1100
1447
  }
1448
+ // Said, once it is handed over, as what the runner says of its own is. A stretch found
1449
+ // while the message was handed over is said with the next one.
1450
+ if (slept === told) {
1451
+ slept = undefined;
1452
+ }
1453
+ if (returned !== undefined) {
1454
+ // Handed over, and not yet read: the agent stands as stopped until it answers.
1455
+ returned.handed = true;
1456
+ target.returning = true;
1457
+ record(
1458
+ target,
1459
+ "status",
1460
+ `The runner handed the agent word that its usage limit stopped it, since ${moment(new Date(returned.since).toISOString())}, with what reached it meanwhile.`,
1461
+ { limit: "back", kept: batch.length },
1462
+ );
1463
+ log(`the agent is handed word of its usage limit, with ${batch.length} kept for it`);
1464
+ }
1101
1465
  if (target.first) {
1102
1466
  target.first = false;
1103
1467
  resetBy = undefined;
@@ -1166,6 +1530,11 @@ export function createRunner(options: RunnerOptions): Runner {
1166
1530
  const take = async (target: OpenSession): Promise<void> => {
1167
1531
  target.took = true;
1168
1532
  const message = target.handed.shift();
1533
+ // Remembered for the turn: one that ends on the usage limit left the last of them unread.
1534
+ target.taken.push(message?.signals ?? []);
1535
+ if (target.taken.length > MAX_TAKEN) {
1536
+ target.taken.shift();
1537
+ }
1169
1538
  if (message !== undefined) {
1170
1539
  if (!message.written) {
1171
1540
  message.write();
@@ -1180,6 +1549,7 @@ export function createRunner(options: RunnerOptions): Runner {
1180
1549
  */
1181
1550
  const settle = async (target: OpenSession): Promise<void> => {
1182
1551
  target.took = true;
1552
+ target.taken = [];
1183
1553
  const counted: RestSignal[] = [];
1184
1554
  for (const message of target.handed.splice(0)) {
1185
1555
  if (!message.written) {
@@ -1311,6 +1681,9 @@ export function createRunner(options: RunnerOptions): Runner {
1311
1681
  if (next > delivered) {
1312
1682
  delivered = next;
1313
1683
  await persist();
1684
+ } else if (keptOf().join(",") !== keptSaved) {
1685
+ // What is kept for the agent changed, and what is delivered did not: written all the same.
1686
+ await persist();
1314
1687
  }
1315
1688
  };
1316
1689
 
@@ -1323,6 +1696,32 @@ export function createRunner(options: RunnerOptions): Runner {
1323
1696
 
1324
1697
  const onSignal = async (signal: RestSignal): Promise<void> => {
1325
1698
  handled = Math.max(handled, signal.number);
1699
+ // What a runner before this one kept unread is taken from the stream once more: for its
1700
+ // words alone, whatever its kind, since it was acted on when it first came.
1701
+ const again = reread.delete(signal.number) && signal.number <= delivered;
1702
+ for (const number of reread) {
1703
+ // The stream is in order: one it passed is not coming.
1704
+ if (number < signal.number) {
1705
+ reread.delete(number);
1706
+ }
1707
+ }
1708
+ if (again) {
1709
+ // The account's own reset, which a runner before this one held for its turn to end: it
1710
+ // is taken as one, once no turn is under way, and never handed over as words alone.
1711
+ if (
1712
+ signal.kind === "reset" &&
1713
+ options.account !== undefined &&
1714
+ signal.by?.id === options.account
1715
+ ) {
1716
+ ownReset = signal;
1717
+ return;
1718
+ }
1719
+ if (!pending.some((kept) => kept.number === signal.number)) {
1720
+ pending = [...pending, signal].sort((one, other) => one.number - other.number);
1721
+ scheduleDeliver();
1722
+ }
1723
+ return;
1724
+ }
1326
1725
  if (
1327
1726
  signal.number <= delivered ||
1328
1727
  owed.has(signal.number) ||
@@ -1340,6 +1739,22 @@ export function createRunner(options: RunnerOptions): Runner {
1340
1739
  await leave(session, session.took ? undefined : "next");
1341
1740
  record(session, "person", signal.text, signalData(signal));
1342
1741
  }
1742
+ // The account's own reset that waits is let go with the stop (ADR-0154), here and not
1743
+ // when the loop next looks: an agent that could not go on is not looked at until it
1744
+ // can, and a restart would then begin the new conversation nobody asked it for.
1745
+ if (ownReset !== undefined) {
1746
+ const gone = ownReset;
1747
+ ownReset = undefined;
1748
+ if (session !== undefined) {
1749
+ record(
1750
+ session,
1751
+ "status",
1752
+ `The account's own reset #${gone.number} was let go: the agent was stopped before it was taken.`,
1753
+ { let_go: `#${gone.number}` },
1754
+ );
1755
+ }
1756
+ log(`#${gone.number} let go: the agent was stopped before its own reset was taken`);
1757
+ }
1343
1758
  await end("stopped");
1344
1759
  await account(signal);
1345
1760
  setState("stopped", "stop");
@@ -1347,12 +1762,39 @@ export function createRunner(options: RunnerOptions): Runner {
1347
1762
  }
1348
1763
  case "restart":
1349
1764
  case "reset": {
1765
+ if (
1766
+ signal.kind === "reset" &&
1767
+ options.account !== undefined &&
1768
+ signal.by?.id === options.account
1769
+ ) {
1770
+ // The account's own: taken by the loop once no turn is under way, the one it was
1771
+ // sent in among them. Counted as delivered at once and kept by this runner until
1772
+ // then, as what the agent never read is: owed, it would hold back the count of every
1773
+ // signal taken after it, and a runner started meanwhile would be sent those again,
1774
+ // into a conversation that knows nothing of having acted on them. A second stands
1775
+ // for the first.
1776
+ const earlier = ownReset;
1777
+ ownReset = signal;
1778
+ if (earlier !== undefined && session !== undefined) {
1779
+ record(
1780
+ session,
1781
+ "status",
1782
+ `The account's own reset #${earlier.number} was let go: #${signal.number} stands for it.`,
1783
+ { let_go: `#${earlier.number}` },
1784
+ );
1785
+ }
1786
+ await account(signal);
1787
+ await persist();
1788
+ return;
1789
+ }
1350
1790
  held = false;
1351
1791
  waits = undefined;
1792
+ // A supervisor starts it now, whatever a limit said: the product says so again where it still stands.
1793
+ limited = undefined;
1352
1794
  await end(signal.kind === "reset" ? "reset" : "restarted");
1353
1795
  if (signal.kind === "reset") {
1354
1796
  conversation = undefined;
1355
- resetBy = by;
1797
+ resetBy = { by, ...(signal.text.trim().length > 0 ? { number: signal.number } : {}) };
1356
1798
  // What a product was handed and never took is tried once more, in the new
1357
1799
  // conversation: a product that does not start with it again is not sent it a
1358
1800
  // third time, so that no signal stands in the way of every one after it for ever.
@@ -1381,9 +1823,9 @@ export function createRunner(options: RunnerOptions): Runner {
1381
1823
  }
1382
1824
  await account(signal);
1383
1825
  if (session !== undefined && !(await session.driver.set(settings))) {
1384
- // Taken when the product starts: the session ends when no turn is under way, and the next has it.
1826
+ // Taken when the product starts: the session ends when it is not at work, and the next has it.
1385
1827
  renew = true;
1386
- if (!session.turn) {
1828
+ if (!busy(session, FOR_CHOICE)) {
1387
1829
  await end("restarted");
1388
1830
  }
1389
1831
  }
@@ -1402,7 +1844,7 @@ export function createRunner(options: RunnerOptions): Runner {
1402
1844
  }
1403
1845
  // Nothing is handed over once the runner is to end for an update: the turn is
1404
1846
  // stopped all the same, and what waits is sent again to the runner started after.
1405
- if (pending.length > 0 && updatedTo === undefined) {
1847
+ if (pending.length > 0 && !closing()) {
1406
1848
  if (stops) {
1407
1849
  await deliver("now");
1408
1850
  } else {
@@ -1415,7 +1857,7 @@ export function createRunner(options: RunnerOptions): Runner {
1415
1857
  return;
1416
1858
  }
1417
1859
  pending.push(signal);
1418
- if (stops && updatedTo !== undefined && session !== undefined) {
1860
+ if (stops && closing() && session !== undefined) {
1419
1861
  // Its words are not handed to a runner that is to end: the turn is stopped, the
1420
1862
  // runner ends for the update, and the console sends them again to the one after.
1421
1863
  await stopTurn(session);
@@ -1437,7 +1879,170 @@ export function createRunner(options: RunnerOptions): Runner {
1437
1879
  }
1438
1880
  };
1439
1881
 
1440
- const onDriver = async (target: OpenSession, event: DriverEvent): Promise<void> => {
1882
+ /**
1883
+ * The product's usage limit stopped the agent (ADR-0150): nothing goes better before a window
1884
+ * of its allowance resets. What the agent was handed and never came to is kept to be handed
1885
+ * over again, the state says why and until when, and the runner brings the agent back by
1886
+ * itself: at the moment the product named, a little after, or after the cool-down where it
1887
+ * named none or one that is past, longer each time the product refuses again.
1888
+ */
1889
+ const limitReached = async (
1890
+ target: OpenSession,
1891
+ until: number | undefined,
1892
+ unread: number,
1893
+ ): Promise<void> => {
1894
+ const now = options.now();
1895
+ // Taken by the product and never answered: on the record, and delivered, so kept by this
1896
+ // runner alone. Handed over and never taken: not delivered, and owed no word any more.
1897
+ const unanswered = unread > 0 ? target.taken.slice(-unread).flat() : [];
1898
+ const untaken = target.handed.splice(0).flatMap((message) => message.signals);
1899
+ for (const signal of untaken) {
1900
+ owed.delete(signal.number);
1901
+ }
1902
+ target.taken = [];
1903
+ target.sent = [];
1904
+ target.returning = false;
1905
+ const again = [...unanswered, ...untaken].filter(
1906
+ (signal, index, all) =>
1907
+ all.findIndex((one) => one.number === signal.number) === index &&
1908
+ !pending.some((kept) => kept.number === signal.number),
1909
+ );
1910
+ pending = [...again, ...pending].sort((one, other) => one.number - other.number);
1911
+ const before = limited;
1912
+ // The first refusal, or the refusal of what the runner tried since: one that follows no
1913
+ // try of the runner's, a message the product still had on its input say, is the same
1914
+ // stretch, and waits no longer for it.
1915
+ const tried = before === undefined || before.handed;
1916
+ // A moment further off than any window lasts is no moment to wait for: the agent would
1917
+ // stand stopped until then with nothing tried, for a number read wrongly.
1918
+ const named =
1919
+ until !== undefined && until > now && until - now <= MAX_LIMIT_MS ? until : undefined;
1920
+ const known = named ?? (tried ? undefined : before.until);
1921
+ if (before === undefined) {
1922
+ // A limit met anew is said in its own word first, whatever a console of before took last.
1923
+ plainWords = false;
1924
+ }
1925
+ limited = {
1926
+ since: before?.since ?? now,
1927
+ until: known,
1928
+ handed: false,
1929
+ // What a supervisor said and the limit kept from being read was tried, and refused with
1930
+ // the limit itself: it waits for the reset as what was tried ahead of it does.
1931
+ tried: new Set([
1932
+ ...(before?.tried ?? []),
1933
+ ...again.filter((signal) => signal.source === "person").map((signal) => signal.number),
1934
+ ]),
1935
+ };
1936
+ if (tried || waits === undefined || known !== before.until) {
1937
+ waits =
1938
+ known === undefined
1939
+ ? cooled(tried ? waits : undefined)
1940
+ : { tries: (waits?.tries ?? 0) + 1, until: known + timing.resetMarginMs };
1941
+ }
1942
+ const when = known === undefined ? undefined : new Date(known).toISOString();
1943
+ // Said once for a stretch: again only where there is something new to say of it.
1944
+ if (tried || again.length > 0 || known !== before.until) {
1945
+ record(
1946
+ target,
1947
+ "status",
1948
+ when === undefined
1949
+ ? "The product's usage limit stopped the agent, and the product did not say when it resets: what reaches the agent meanwhile is kept, and the runner tries again by itself after a while."
1950
+ : `The product's usage limit stopped the agent until ${moment(when)}: what reaches the agent meanwhile is kept, and the runner brings it back then by itself.`,
1951
+ { limit: "reached", until: when ?? null, kept: again.length },
1952
+ );
1953
+ log(
1954
+ `the product's usage limit stopped the agent ${when === undefined ? "and names no reset" : `until ${when}`}: tried again at ${new Date(waits.until).toISOString()}, ${again.length} kept to hand over again`,
1955
+ );
1956
+ }
1957
+ await persist();
1958
+ setState("failed", "usage_limit");
1959
+ scheduleDeliver(waits.until);
1960
+ };
1961
+
1962
+ /** The agent answered again after a usage limit: it is back, and stands as running. */
1963
+ const onAnswered = async (target: OpenSession): Promise<void> => {
1964
+ if (target !== session || limited === undefined) {
1965
+ return;
1966
+ }
1967
+ limited = undefined;
1968
+ waits = undefined;
1969
+ await persist();
1970
+ log("the agent is back from its usage limit");
1971
+ setState("running", "resumed");
1972
+ // What stayed kept while a supervisor's signal was tried is the agent's now.
1973
+ if (pending.length > 0) {
1974
+ scheduleDeliver();
1975
+ }
1976
+ };
1977
+
1978
+ /**
1979
+ * What the product said of its allowance (ADR-0150): the agent is told once for each mark a
1980
+ * window reaches, at once, in the open session. After the tool call under way where a turn is
1981
+ * under way; in a turn of its own where none is, since sub-agents left at work spend the
1982
+ * allowance after the session's own turn ended, and a word kept for the next message may come
1983
+ * after the limit. What cannot be said now is not counted as told: it is said at what the
1984
+ * product says next.
1985
+ */
1986
+ const onUsage = async (
1987
+ target: OpenSession,
1988
+ windows: Extract<DriverEvent, { type: "usage" }>["windows"],
1989
+ ): Promise<void> => {
1990
+ const looked = usageToTell(windows, usageTold, options.now());
1991
+ if (looked.tell.length > 0) {
1992
+ if (target.first || limited !== undefined) {
1993
+ return;
1994
+ }
1995
+ if (!(await sayToAgent(target, usageWords(looked.tell, moment)))) {
1996
+ return;
1997
+ }
1998
+ for (const one of looked.tell) {
1999
+ const used = one.window.used === undefined ? null : Math.floor(one.window.used * 100);
2000
+ const resets =
2001
+ one.window.resetsAt === undefined ? null : new Date(one.window.resetsAt).toISOString();
2002
+ record(
2003
+ target,
2004
+ "status",
2005
+ `The product's allowance is ${used === null ? "near its limit" : `${used}% used`} in its ${one.window.name} window${resets === null ? "" : `, which resets ${moment(resets)}`}: the agent is told.`,
2006
+ { usage: one.window.name, used, resets },
2007
+ );
2008
+ log(
2009
+ `the product's allowance: ${one.window.name} ${used === null ? "near its limit" : `${used}%`}${resets === null ? "" : `, resets ${resets}`}; the agent is told`,
2010
+ );
2011
+ }
2012
+ }
2013
+ usageTold = looked.told;
2014
+ };
2015
+
2016
+ /**
2017
+ * Takes the account's own reset (ADR-0154), once no turn is under way: the open session ends
2018
+ * as reset, and the next begins a new conversation with the account's words, at once. It
2019
+ * changes nothing of how the agent stands: where a supervisor's stop came meanwhile it is let
2020
+ * go, and whoever starts the agent again says with which conversation.
2021
+ */
2022
+ const beginAnew = async (signal: RestSignal): Promise<void> => {
2023
+ ownReset = undefined;
2024
+ if (held) {
2025
+ log(`#${signal.number} let go: the agent was stopped before its own reset was taken`);
2026
+ await account(signal);
2027
+ await persist();
2028
+ return;
2029
+ }
2030
+ await end("reset");
2031
+ conversation = undefined;
2032
+ // Where a supervisor reset the agent meanwhile, the first message says so: the account's
2033
+ // words are read under their own header all the same.
2034
+ resetBy ??= {
2035
+ by: signal.by?.name ?? signal.by?.login ?? "you",
2036
+ own: true,
2037
+ number: signal.number,
2038
+ };
2039
+ pending = [...pending, signal].sort((one, other) => one.number - other.number);
2040
+ await persist();
2041
+ setState("running", "reset");
2042
+ scheduleDeliver();
2043
+ };
2044
+
2045
+ const onDriver = async (target: OpenSession, event: DriverEvent, unread = 0): Promise<void> => {
1441
2046
  if (target !== session) {
1442
2047
  return;
1443
2048
  }
@@ -1472,11 +2077,17 @@ export function createRunner(options: RunnerOptions): Runner {
1472
2077
  lastTry.delete(signal.number);
1473
2078
  }
1474
2079
  target.sent = [];
2080
+ target.returning = false;
2081
+ if (limited !== undefined) {
2082
+ // A turn completed: whatever stopped the agent is over.
2083
+ limited = undefined;
2084
+ await persist();
2085
+ }
1475
2086
  if (waits !== undefined || stands.state !== "running") {
1476
2087
  waits = undefined;
1477
2088
  setState("running", "completed");
1478
2089
  }
1479
- if (renew) {
2090
+ if (renew && !busy(target, FOR_CHOICE)) {
1480
2091
  await end("restarted");
1481
2092
  }
1482
2093
  if (pending.length > 0) {
@@ -1484,9 +2095,25 @@ export function createRunner(options: RunnerOptions): Runner {
1484
2095
  }
1485
2096
  return;
1486
2097
  }
2098
+ case "usage": {
2099
+ noteUsage(usageSeen, event.windows, options.now());
2100
+ await onUsage(target, event.windows);
2101
+ return;
2102
+ }
1487
2103
  case "cannot_go_on": {
1488
2104
  // Reported, and nothing restarted: a supervisor's signal is tried at once, the rest after the cool-down.
1489
2105
  target.turn = false;
2106
+ if (event.reason === "usage_limit") {
2107
+ await limitReached(target, event.until, unread);
2108
+ return;
2109
+ }
2110
+ // What the runner tried after a usage limit ended some other way: the limit is not
2111
+ // what stops the agent now.
2112
+ if (limited?.handed === true) {
2113
+ limited = undefined;
2114
+ target.returning = false;
2115
+ await persist();
2116
+ }
1490
2117
  // A product that did not start, or is not signed in, took nothing: what was sent is tried again.
1491
2118
  if (event.reason === "start" || event.reason === "sign_in") {
1492
2119
  // What a reset gave one more try and the product did not start with again is let
@@ -1534,7 +2161,32 @@ export function createRunner(options: RunnerOptions): Runner {
1534
2161
  return;
1535
2162
  }
1536
2163
  case "ended": {
2164
+ // A product that ended before it took the word that it is back took nothing of what
2165
+ // that word was handed with: it is kept, and handed over again with the word, as what
2166
+ // a limit kept from being read is. Left to the session's end, it would be written as
2167
+ // never read and the agent told that nothing reached it meanwhile.
2168
+ if (limited?.handed === true) {
2169
+ const untaken = target.handed.splice(0).flatMap((message) => message.signals);
2170
+ for (const signal of untaken) {
2171
+ owed.delete(signal.number);
2172
+ }
2173
+ pending = [
2174
+ ...untaken.filter((signal) => !pending.some((kept) => kept.number === signal.number)),
2175
+ ...pending,
2176
+ ].sort((one, other) => one.number - other.number);
2177
+ }
1537
2178
  await end(event.how, true);
2179
+ // A product that ended before it answered the word that it is back, or refused it, was
2180
+ // not brought back: the word is owed still, at the moment the runner waits for, or
2181
+ // after the cool-down where that moment is past, longer each time it ends so.
2182
+ if (limited?.handed === true) {
2183
+ limited.handed = false;
2184
+ if (waits === undefined || options.now() >= waits.until) {
2185
+ waits = cooled(waits);
2186
+ }
2187
+ scheduleDeliver(waits.until);
2188
+ return;
2189
+ }
1538
2190
  if (pending.length > 0 && waits === undefined) {
1539
2191
  scheduleDeliver();
1540
2192
  }
@@ -1615,13 +2267,52 @@ export function createRunner(options: RunnerOptions): Runner {
1615
2267
  }
1616
2268
  };
1617
2269
 
2270
+ /**
2271
+ * Why the agent stands as it does, and until when where the runner knows: when its usage
2272
+ * limit resets. A console of before the word `usage_limit` refuses a heartbeat that says it,
2273
+ * and with it everything else the heartbeat carries: such a console is said `crashed`, the
2274
+ * nearest word it takes, and no moment.
2275
+ */
2276
+ const saidOfState = (): { reason: AgentStateReason; until?: string | null } => {
2277
+ if (stands.reason !== "usage_limit") {
2278
+ return { reason: stands.reason };
2279
+ }
2280
+ if (plainWords) {
2281
+ return { reason: "crashed" };
2282
+ }
2283
+ return {
2284
+ reason: stands.reason,
2285
+ until: limited?.until === undefined ? null : new Date(limited.until).toISOString(),
2286
+ };
2287
+ };
2288
+
2289
+ /**
2290
+ * Whether a heartbeat was refused for the word `usage_limit`, by a console of before it: such
2291
+ * a console is said the nearest word it takes from then on, and the runner says so in a line.
2292
+ */
2293
+ const wordRefused = (error: unknown): boolean => {
2294
+ if (
2295
+ !(error instanceof ApiError) ||
2296
+ error.code !== "request.invalid" ||
2297
+ stands.reason !== "usage_limit" ||
2298
+ plainWords
2299
+ ) {
2300
+ return false;
2301
+ }
2302
+ plainWords = true;
2303
+ log(
2304
+ "the console does not take the word usage_limit, being one of before it: the agent is said to it as failed, crashed, until the console is updated",
2305
+ );
2306
+ return true;
2307
+ };
2308
+
1618
2309
  const beat = async (): Promise<void> => {
1619
2310
  const now = `${stands.state} ${stands.reason} ${session?.id ?? ""}`;
1620
2311
  said = now;
1621
2312
  try {
1622
2313
  const answer = await client.runnerHeartbeat({
1623
2314
  state: stands.state,
1624
- reason: stands.reason,
2315
+ ...saidOfState(),
1625
2316
  delivered,
1626
2317
  session: session?.id ?? null,
1627
2318
  machine: options.machine,
@@ -1635,6 +2326,7 @@ export function createRunner(options: RunnerOptions): Runner {
1635
2326
  effort: choiceOf(session?.running.effort),
1636
2327
  },
1637
2328
  sources: sourcesOf(),
2329
+ usage: usageSaid(usageSeen, options.now()),
1638
2330
  });
1639
2331
  settings = answer.settings;
1640
2332
  tooOldSaid = false;
@@ -1651,6 +2343,13 @@ export function createRunner(options: RunnerOptions): Runner {
1651
2343
  if (stopped) {
1652
2344
  return;
1653
2345
  }
2346
+ if (wordRefused(error)) {
2347
+ // Said again at once in a word that console takes, so that the account is heard from
2348
+ // and its count of what is delivered goes on.
2349
+ said = "";
2350
+ push({ t: "heartbeat" });
2351
+ return;
2352
+ }
1654
2353
  if (error instanceof ApiError && error.code === "client.outdated") {
1655
2354
  if (!tooOldSaid) {
1656
2355
  tooOldSaid = true;
@@ -1806,15 +2505,20 @@ export function createRunner(options: RunnerOptions): Runner {
1806
2505
  }
1807
2506
  const host: WakeHost = {
1808
2507
  secret: async (name) => secretValues.get(name),
2508
+ channels: options.config.channels ?? [],
1809
2509
  raise: async (raised) => {
1810
2510
  // The console takes so many wakes a runner raises itself within an hour (ADR-0132):
1811
2511
  // past that, what the sources raise is let go for a while, longer each time, and said
1812
2512
  // once, so that a source that repeats itself costs the console nothing more.
1813
2513
  if (wakesHeld !== undefined && options.now() < wakesHeld.until) {
1814
- return;
2514
+ return false;
1815
2515
  }
2516
+ // Written in parts whatever the source handed over (ADR-0163): its own lines apart from
2517
+ // what someone else wrote, and a text with no line of the source's as words whole, so
2518
+ // that no word of a message reads as a line of the source's when the signal returns.
2519
+ const text = wakeTextOf("parts" in raised ? raised.parts : [{ words: raised.text }]);
1816
2520
  try {
1817
- await client.raiseWake({ source: "messenger", key: raised.key, text: raised.text });
2521
+ await client.raiseWake({ source: "messenger", key: raised.key, text });
1818
2522
  } catch (error) {
1819
2523
  if (codeOf(error) !== "signal.too_many") {
1820
2524
  throw error;
@@ -1825,18 +2529,30 @@ export function createRunner(options: RunnerOptions): Runner {
1825
2529
  "wakes",
1826
2530
  "the console takes no more wakes of this runner's within the hour (signal.too_many); what its wake sources raise is let go for a while",
1827
2531
  );
1828
- return;
2532
+ return false;
1829
2533
  }
1830
2534
  if (wakesHeld !== undefined) {
1831
2535
  wakesHeld = undefined;
1832
2536
  sayOver("wakes", "the console takes the wakes of this runner's wake sources again");
1833
2537
  }
2538
+ return true;
1834
2539
  },
2540
+ kept: new Map(),
1835
2541
  log,
1836
2542
  stands: (state, why) => sourceStands(source.name, state, why),
1837
2543
  fetch: wakes.fetch,
1838
2544
  socket: wakes.socket,
1839
2545
  wait: pause,
2546
+ // Who wrote, as the console answers the account's own sign-in (ADR-0164), of the
2547
+ // messenger the source is named for. A console that does not know the question, or does
2548
+ // not answer, says nothing, and the source says of an account what the messenger does.
2549
+ ...(client.writers === undefined
2550
+ ? {}
2551
+ : {
2552
+ writers: async (accounts, signal) =>
2553
+ (await client.writers?.({ messenger: source.name, accounts: [...accounts] }, signal))
2554
+ ?.items ?? [],
2555
+ }),
1840
2556
  };
1841
2557
  sourceStands(source.name, "waiting");
1842
2558
  let wait = timing.reconnectMs;
@@ -1912,6 +2628,31 @@ export function createRunner(options: RunnerOptions): Runner {
1912
2628
  `the conversation kept was begun under the driver ${kept.driver}: a new one begins under ${driver.name}`,
1913
2629
  );
1914
2630
  }
2631
+ // What a runner before this one held for the agent alone is taken from the stream once
2632
+ // more, whether or not a limit still stands: a supervisor's restart under a limit lifts
2633
+ // the limit and leaves them kept, and a runner started before they were handed over
2634
+ // again would otherwise read on from after them.
2635
+ for (const number of kept?.kept ?? []) {
2636
+ reread.add(number);
2637
+ }
2638
+ if (kept?.limited !== undefined) {
2639
+ // A usage limit stopped the agent under a runner before this one: it is brought back
2640
+ // all the same, when the limit resets or after the cool-down where no moment is known.
2641
+ const now = options.now();
2642
+ const known =
2643
+ kept.limited.until !== undefined && kept.limited.until - now <= MAX_LIMIT_MS
2644
+ ? kept.limited.until
2645
+ : undefined;
2646
+ limited = { since: kept.limited.since, until: known, handed: false, tried: new Set() };
2647
+ waits = {
2648
+ tries: 1,
2649
+ until: known === undefined ? now + timing.coolDownMs : known + timing.resetMarginMs,
2650
+ };
2651
+ stands = { state: "failed", reason: "usage_limit" };
2652
+ log(
2653
+ `the product's usage limit stopped the agent before this runner started: tried again at ${new Date(waits.until).toISOString()}`,
2654
+ );
2655
+ }
1915
2656
  probe = await driver.probe();
1916
2657
  const left =
1917
2658
  probe.models.length +
@@ -1925,33 +2666,53 @@ export function createRunner(options: RunnerOptions): Runner {
1925
2666
  }
1926
2667
  await readSecrets();
1927
2668
  // The first heartbeat says the runner is there, and learns where the console's record stands.
1928
- try {
1929
- const first = await client.runnerHeartbeat({
1930
- state: "running",
1931
- reason: "started",
1932
- delivered,
1933
- session: null,
1934
- machine: options.machine,
1935
- runner: options.version,
1936
- product: productOf(),
1937
- offers: offersOf(),
1938
- running: { model: null, effort: null },
1939
- });
1940
- settings = first.settings;
1941
- delivered = Math.max(delivered, first.delivered);
1942
- if (first.state === "stopped") {
1943
- held = true;
1944
- stands = { state: "stopped", reason: "stop" };
2669
+ for (;;) {
2670
+ try {
2671
+ const first = await client.runnerHeartbeat({
2672
+ state: stands.state,
2673
+ ...saidOfState(),
2674
+ delivered,
2675
+ session: null,
2676
+ machine: options.machine,
2677
+ runner: options.version,
2678
+ product: productOf(),
2679
+ offers: offersOf(),
2680
+ running: { model: null, effort: null },
2681
+ });
2682
+ settings = first.settings;
2683
+ delivered = Math.max(delivered, first.delivered);
2684
+ if (first.state === "stopped") {
2685
+ held = true;
2686
+ stands = { state: "stopped", reason: "stop" };
2687
+ }
2688
+ break;
2689
+ } catch (error) {
2690
+ // A runner started under a usage limit, at a console of before the word: said once more, in a word it takes.
2691
+ if (wordRefused(error)) {
2692
+ continue;
2693
+ }
2694
+ log(
2695
+ `the console did not take the first heartbeat (${codeOf(error)}); the runner goes on`,
2696
+ );
2697
+ break;
1945
2698
  }
1946
- } catch (error) {
1947
- log(`the console did not take the first heartbeat (${codeOf(error)}); the runner goes on`);
1948
2699
  }
1949
- received = delivered;
2700
+ // From before what a runner before this one kept unread, where it kept any.
2701
+ received = reread.size === 0 ? delivered : Math.min(delivered, Math.min(...reread) - 1);
2702
+ rereadBy = options.now() + timing.reconnectMs;
1950
2703
  handled = delivered;
1951
2704
  said = `${stands.state} ${stands.reason} `;
2705
+ if (waits !== undefined) {
2706
+ scheduleDeliver(waits.until);
2707
+ }
1952
2708
  const listening = listen();
1953
2709
  const sourcing = (options.wakes?.sources ?? []).map((source) => keepSource(source));
1954
- const beating = setInterval(() => push({ t: "heartbeat" }), timing.heartbeatMs);
2710
+ // Counted from here: what the runner waited for before it began is no time it did not run in.
2711
+ lookedAt = options.now();
2712
+ const beating = setInterval(() => {
2713
+ look();
2714
+ push({ t: "heartbeat" });
2715
+ }, timing.heartbeatMs);
1955
2716
  const batching = setInterval(() => push({ t: "flush" }), timing.batchMs);
1956
2717
  log(
1957
2718
  `the runner is there: ${driver.product.name} ${probe.version ?? "of a version it did not say"}, signals after #${delivered}`,
@@ -1966,8 +2727,12 @@ export function createRunner(options: RunnerOptions): Runner {
1966
2727
  try {
1967
2728
  for (;;) {
1968
2729
  // An update is taken between two turns, and at once where none is under way; so is
1969
- // a runner.json that changed.
1970
- if ((updatedTo !== undefined || reconfigure) && session?.turn !== true) {
2730
+ // a runner.json that changed. Neither while sub-agents work on in the background of
2731
+ // the session, for as long as the runner waits for them (ADR-0162).
2732
+ if (
2733
+ (updatedTo !== undefined || reconfigure) &&
2734
+ !busy(session, updatedTo !== undefined ? FOR_UPDATE : FOR_CHANGE)
2735
+ ) {
1971
2736
  how = updatedTo !== undefined ? "updated" : "changed";
1972
2737
  if (session !== undefined) {
1973
2738
  record(
@@ -1988,10 +2753,12 @@ export function createRunner(options: RunnerOptions): Runner {
1988
2753
  if (message.t === "signal") {
1989
2754
  await onSignal(message.signal);
1990
2755
  } else if (message.t === "driver") {
1991
- await onDriver(message.session, message.event);
2756
+ await onDriver(message.session, message.event, message.unread);
2757
+ } else if (message.t === "answered") {
2758
+ await onAnswered(message.session);
1992
2759
  } else if (message.t === "deliver") {
1993
2760
  // A timer may fire a moment before the clock says it is time.
1994
- if (deliverAt !== undefined && options.now() >= deliverAt - 20) {
2761
+ if (deliverAt !== undefined && options.now() >= deliverAt - TIMER_EARLY_MS) {
1995
2762
  await deliver("next");
1996
2763
  }
1997
2764
  } else if (message.t === "flush") {
@@ -1999,6 +2766,11 @@ export function createRunner(options: RunnerOptions): Runner {
1999
2766
  await flush(session);
2000
2767
  }
2001
2768
  } else {
2769
+ // A timer counts no time the machine sleeps in, and rings late by as much: what
2770
+ // was to be handed over at a moment is looked for by the clock at every heartbeat.
2771
+ if (deliverAt !== undefined && options.now() >= deliverAt) {
2772
+ await deliver("next");
2773
+ }
2002
2774
  await lookForUpdate();
2003
2775
  await lookForChange();
2004
2776
  // Said every thirty seconds, and at once when how the agent stands changed.
@@ -2008,6 +2780,44 @@ export function createRunner(options: RunnerOptions): Runner {
2008
2780
  await readSecrets();
2009
2781
  }
2010
2782
  }
2783
+ // The account's own reset is taken between two turns, where the agent can go on:
2784
+ // it changes nothing of how the agent stands, so one that could not go on, the
2785
+ // model having refused or a usage limit standing, waits as it would without it,
2786
+ // and the reset is taken once a turn completed again.
2787
+ if (
2788
+ ownReset !== undefined &&
2789
+ waits === undefined &&
2790
+ limited === undefined &&
2791
+ !busy(session, FOR_RESET)
2792
+ ) {
2793
+ await beginAnew(ownReset);
2794
+ }
2795
+ // A model or an effort the product takes only when it starts, held for what went
2796
+ // on in the session: it ends once nothing does. Not where the agent could not go
2797
+ // on, which keeps its session as it does under a turn.
2798
+ if (
2799
+ renew &&
2800
+ session !== undefined &&
2801
+ stands.state === "running" &&
2802
+ !busy(session, FOR_CHOICE)
2803
+ ) {
2804
+ await end("restarted");
2805
+ if (pending.length > 0) {
2806
+ scheduleDeliver();
2807
+ }
2808
+ }
2809
+ // Nothing waits to end the session: the next thing that does counts from its own
2810
+ // moment how long it waits for the sub-agents.
2811
+ if (
2812
+ session !== undefined &&
2813
+ !renew &&
2814
+ ownReset === undefined &&
2815
+ updatedTo === undefined &&
2816
+ !reconfigure
2817
+ ) {
2818
+ session.heldSince = undefined;
2819
+ session.heldSaid = undefined;
2820
+ }
2011
2821
  } catch (error) {
2012
2822
  log(`the runner could not do what it was about to (${codeOf(error)}); it goes on`);
2013
2823
  }