charness 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (545) hide show
  1. package/CHANGELOG.md +157 -2
  2. package/DEVELOPMENT.md +58 -10
  3. package/LICENSE +331 -151
  4. package/MIGRATION_3_TO_4.md +8 -5
  5. package/README.md +21 -9
  6. package/SETUP.md +54 -10
  7. package/agent-plugin/README.md +10 -3
  8. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +18 -27
  9. package/agent-plugin/skills/charness-delegate-opencode/SKILL.md +5 -3
  10. package/agent-plugin/skills/charness-orchestration/SKILL.md +56 -16
  11. package/dist/adapters/claudeCliAdapter.d.ts +4 -0
  12. package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
  13. package/dist/adapters/claudeCliAdapter.js +13 -0
  14. package/dist/adapters/claudeCliAdapter.js.map +1 -1
  15. package/dist/adapters/claudeJsonStreamAdapter.d.ts +136 -10
  16. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  17. package/dist/adapters/claudeJsonStreamAdapter.js +365 -77
  18. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  19. package/dist/adapters/createAdapter.d.ts +12 -3
  20. package/dist/adapters/createAdapter.d.ts.map +1 -1
  21. package/dist/adapters/createAdapter.js +39 -13
  22. package/dist/adapters/createAdapter.js.map +1 -1
  23. package/dist/adapters/openCodeAdapter.d.ts +34 -0
  24. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  25. package/dist/adapters/openCodeAdapter.js +118 -11
  26. package/dist/adapters/openCodeAdapter.js.map +1 -1
  27. package/dist/apiErrorRetry.d.ts +11 -3
  28. package/dist/apiErrorRetry.d.ts.map +1 -1
  29. package/dist/apiErrorRetry.js +33 -3
  30. package/dist/apiErrorRetry.js.map +1 -1
  31. package/dist/apiRetryKick.d.ts +3 -2
  32. package/dist/apiRetryKick.d.ts.map +1 -1
  33. package/dist/apiRetryKick.js +13 -5
  34. package/dist/apiRetryKick.js.map +1 -1
  35. package/dist/bot.d.ts +2 -6
  36. package/dist/bot.d.ts.map +1 -1
  37. package/dist/bot.js +2009 -634
  38. package/dist/bot.js.map +1 -1
  39. package/dist/cli/claudeProfiles.d.ts +28 -6
  40. package/dist/cli/claudeProfiles.d.ts.map +1 -1
  41. package/dist/cli/claudeProfiles.js +89 -22
  42. package/dist/cli/claudeProfiles.js.map +1 -1
  43. package/dist/cli.d.ts.map +1 -1
  44. package/dist/cli.js +2 -1
  45. package/dist/cli.js.map +1 -1
  46. package/dist/connectors/jira/answerSink.d.ts +102 -7
  47. package/dist/connectors/jira/answerSink.d.ts.map +1 -1
  48. package/dist/connectors/jira/answerSink.js +364 -60
  49. package/dist/connectors/jira/answerSink.js.map +1 -1
  50. package/dist/connectors/jira/answerThreads.d.ts +44 -0
  51. package/dist/connectors/jira/answerThreads.d.ts.map +1 -0
  52. package/dist/connectors/jira/answerThreads.js +85 -0
  53. package/dist/connectors/jira/answerThreads.js.map +1 -0
  54. package/dist/connectors/jira/client.d.ts +67 -2
  55. package/dist/connectors/jira/client.d.ts.map +1 -1
  56. package/dist/connectors/jira/client.js +176 -4
  57. package/dist/connectors/jira/client.js.map +1 -1
  58. package/dist/connectors/jira/config.d.ts +6 -0
  59. package/dist/connectors/jira/config.d.ts.map +1 -1
  60. package/dist/connectors/jira/config.js +14 -1
  61. package/dist/connectors/jira/config.js.map +1 -1
  62. package/dist/connectors/jira/connector.d.ts +19 -0
  63. package/dist/connectors/jira/connector.d.ts.map +1 -1
  64. package/dist/connectors/jira/connector.js +68 -6
  65. package/dist/connectors/jira/connector.js.map +1 -1
  66. package/dist/connectors/jira/contextPreamble.d.ts.map +1 -1
  67. package/dist/connectors/jira/contextPreamble.js +6 -1
  68. package/dist/connectors/jira/contextPreamble.js.map +1 -1
  69. package/dist/connectors/jira/inbound.d.ts +21 -6
  70. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  71. package/dist/connectors/jira/inbound.js +22 -16
  72. package/dist/connectors/jira/inbound.js.map +1 -1
  73. package/dist/connectors/jira/issueBlocks.d.ts +8 -1
  74. package/dist/connectors/jira/issueBlocks.d.ts.map +1 -1
  75. package/dist/connectors/jira/issueBlocks.js +38 -2
  76. package/dist/connectors/jira/issueBlocks.js.map +1 -1
  77. package/dist/connectors/jira/operatorIssue.d.ts +28 -0
  78. package/dist/connectors/jira/operatorIssue.d.ts.map +1 -0
  79. package/dist/connectors/jira/operatorIssue.js +81 -0
  80. package/dist/connectors/jira/operatorIssue.js.map +1 -0
  81. package/dist/connectors/jira/outbound.d.ts +8 -4
  82. package/dist/connectors/jira/outbound.d.ts.map +1 -1
  83. package/dist/connectors/jira/outbound.js +16 -8
  84. package/dist/connectors/jira/outbound.js.map +1 -1
  85. package/dist/connectors/jira/outgoingFileCheck.d.ts +37 -0
  86. package/dist/connectors/jira/outgoingFileCheck.d.ts.map +1 -0
  87. package/dist/connectors/jira/outgoingFileCheck.js +279 -0
  88. package/dist/connectors/jira/outgoingFileCheck.js.map +1 -0
  89. package/dist/connectors/jira/outgoingFiles.d.ts +81 -0
  90. package/dist/connectors/jira/outgoingFiles.d.ts.map +1 -0
  91. package/dist/connectors/jira/outgoingFiles.js +268 -0
  92. package/dist/connectors/jira/outgoingFiles.js.map +1 -0
  93. package/dist/connectors/jira/progressComments.d.ts +69 -0
  94. package/dist/connectors/jira/progressComments.d.ts.map +1 -0
  95. package/dist/connectors/jira/progressComments.js +136 -0
  96. package/dist/connectors/jira/progressComments.js.map +1 -0
  97. package/dist/connectors/jira/prompt.d.ts +5 -1
  98. package/dist/connectors/jira/prompt.d.ts.map +1 -1
  99. package/dist/connectors/jira/prompt.js +23 -3
  100. package/dist/connectors/jira/prompt.js.map +1 -1
  101. package/dist/connectors/jira/promptSpill.js +1 -1
  102. package/dist/connectors/jira/promptSpill.js.map +1 -1
  103. package/dist/connectors/jira/trigger.d.ts +13 -5
  104. package/dist/connectors/jira/trigger.d.ts.map +1 -1
  105. package/dist/connectors/jira/trigger.js +13 -7
  106. package/dist/connectors/jira/trigger.js.map +1 -1
  107. package/dist/connectors/jira/uploadedFiles.d.ts +48 -0
  108. package/dist/connectors/jira/uploadedFiles.d.ts.map +1 -0
  109. package/dist/connectors/jira/uploadedFiles.js +123 -0
  110. package/dist/connectors/jira/uploadedFiles.js.map +1 -0
  111. package/dist/connectors/telegram/commands/backendSwitch.d.ts +9 -1
  112. package/dist/connectors/telegram/commands/backendSwitch.d.ts.map +1 -1
  113. package/dist/connectors/telegram/commands/backendSwitch.js +17 -8
  114. package/dist/connectors/telegram/commands/backendSwitch.js.map +1 -1
  115. package/dist/connectors/telegram/commands/botSkills.d.ts +2 -0
  116. package/dist/connectors/telegram/commands/botSkills.d.ts.map +1 -1
  117. package/dist/connectors/telegram/commands/botSkills.js +17 -2
  118. package/dist/connectors/telegram/commands/botSkills.js.map +1 -1
  119. package/dist/connectors/telegram/commands/claudeAccounts.d.ts +6 -0
  120. package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
  121. package/dist/connectors/telegram/commands/claudeAccounts.js +22 -4
  122. package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
  123. package/dist/connectors/telegram/commands/compaction.d.ts +14 -3
  124. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  125. package/dist/connectors/telegram/commands/compaction.js +261 -96
  126. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  127. package/dist/connectors/telegram/commands/limitReminders.d.ts +21 -0
  128. package/dist/connectors/telegram/commands/limitReminders.d.ts.map +1 -0
  129. package/dist/connectors/telegram/commands/limitReminders.js +95 -0
  130. package/dist/connectors/telegram/commands/limitReminders.js.map +1 -0
  131. package/dist/connectors/telegram/commands/limitsBoard.d.ts +4 -0
  132. package/dist/connectors/telegram/commands/limitsBoard.d.ts.map +1 -1
  133. package/dist/connectors/telegram/commands/limitsBoard.js +27 -6
  134. package/dist/connectors/telegram/commands/limitsBoard.js.map +1 -1
  135. package/dist/connectors/telegram/commands/modelProviders.d.ts +2 -2
  136. package/dist/connectors/telegram/commands/modelProviders.d.ts.map +1 -1
  137. package/dist/connectors/telegram/commands/modelProviders.js +27 -16
  138. package/dist/connectors/telegram/commands/modelProviders.js.map +1 -1
  139. package/dist/connectors/telegram/commands/topicCommand.d.ts.map +1 -1
  140. package/dist/connectors/telegram/commands/topicCommand.js +7 -2
  141. package/dist/connectors/telegram/commands/topicCommand.js.map +1 -1
  142. package/dist/connectors/telegram/commands/workerRoles.d.ts +25 -0
  143. package/dist/connectors/telegram/commands/workerRoles.d.ts.map +1 -0
  144. package/dist/connectors/telegram/commands/workerRoles.js +259 -0
  145. package/dist/connectors/telegram/commands/workerRoles.js.map +1 -0
  146. package/dist/connectors/telegram/groupWelcome.d.ts +12 -0
  147. package/dist/connectors/telegram/groupWelcome.d.ts.map +1 -0
  148. package/dist/connectors/telegram/groupWelcome.js +12 -0
  149. package/dist/connectors/telegram/groupWelcome.js.map +1 -0
  150. package/dist/connectors/telegram/inbound.d.ts +7 -0
  151. package/dist/connectors/telegram/inbound.d.ts.map +1 -1
  152. package/dist/connectors/telegram/inbound.js +10 -0
  153. package/dist/connectors/telegram/inbound.js.map +1 -1
  154. package/dist/connectors/telegram/outputFlushPlan.d.ts +12 -0
  155. package/dist/connectors/telegram/outputFlushPlan.d.ts.map +1 -1
  156. package/dist/connectors/telegram/outputFlushPlan.js +12 -0
  157. package/dist/connectors/telegram/outputFlushPlan.js.map +1 -1
  158. package/dist/connectors/telegram/runnerPairingMessages.d.ts +1 -1
  159. package/dist/connectors/telegram/topicIndicator.d.ts +1 -1
  160. package/dist/connectors/telegram/topicIndicator.d.ts.map +1 -1
  161. package/dist/connectors/telegram/topicIndicator.js +103 -5
  162. package/dist/connectors/telegram/topicIndicator.js.map +1 -1
  163. package/dist/effortLevels.d.ts +6 -0
  164. package/dist/effortLevels.d.ts.map +1 -1
  165. package/dist/effortLevels.js +6 -1
  166. package/dist/effortLevels.js.map +1 -1
  167. package/dist/i18n/de.d.ts.map +1 -1
  168. package/dist/i18n/de.js +95 -14
  169. package/dist/i18n/de.js.map +1 -1
  170. package/dist/i18n/en.d.ts.map +1 -1
  171. package/dist/i18n/en.js +95 -14
  172. package/dist/i18n/en.js.map +1 -1
  173. package/dist/i18n/es.d.ts.map +1 -1
  174. package/dist/i18n/es.js +95 -14
  175. package/dist/i18n/es.js.map +1 -1
  176. package/dist/i18n/fr.d.ts.map +1 -1
  177. package/dist/i18n/fr.js +95 -14
  178. package/dist/i18n/fr.js.map +1 -1
  179. package/dist/i18n/hi.d.ts.map +1 -1
  180. package/dist/i18n/hi.js +95 -14
  181. package/dist/i18n/hi.js.map +1 -1
  182. package/dist/i18n/ja.d.ts.map +1 -1
  183. package/dist/i18n/ja.js +95 -14
  184. package/dist/i18n/ja.js.map +1 -1
  185. package/dist/i18n/ka.d.ts.map +1 -1
  186. package/dist/i18n/ka.js +95 -14
  187. package/dist/i18n/ka.js.map +1 -1
  188. package/dist/i18n/pt.d.ts.map +1 -1
  189. package/dist/i18n/pt.js +95 -14
  190. package/dist/i18n/pt.js.map +1 -1
  191. package/dist/i18n/ru.d.ts.map +1 -1
  192. package/dist/i18n/ru.js +95 -14
  193. package/dist/i18n/ru.js.map +1 -1
  194. package/dist/i18n/uk.d.ts.map +1 -1
  195. package/dist/i18n/uk.js +95 -14
  196. package/dist/i18n/uk.js.map +1 -1
  197. package/dist/i18n/uz.d.ts.map +1 -1
  198. package/dist/i18n/uz.js +95 -14
  199. package/dist/i18n/uz.js.map +1 -1
  200. package/dist/i18n/zh.d.ts.map +1 -1
  201. package/dist/i18n/zh.js +95 -14
  202. package/dist/i18n/zh.js.map +1 -1
  203. package/dist/instanceSettings.d.ts +24 -2
  204. package/dist/instanceSettings.d.ts.map +1 -1
  205. package/dist/instanceSettings.js +75 -3
  206. package/dist/instanceSettings.js.map +1 -1
  207. package/dist/limitNotes/engine.d.ts +47 -0
  208. package/dist/limitNotes/engine.d.ts.map +1 -0
  209. package/dist/limitNotes/engine.js +98 -0
  210. package/dist/limitNotes/engine.js.map +1 -0
  211. package/dist/limitNotes/noteText.d.ts +33 -0
  212. package/dist/limitNotes/noteText.d.ts.map +1 -0
  213. package/dist/limitNotes/noteText.js +55 -0
  214. package/dist/limitNotes/noteText.js.map +1 -0
  215. package/dist/limitNotes/plan.d.ts +147 -0
  216. package/dist/limitNotes/plan.d.ts.map +1 -0
  217. package/dist/limitNotes/plan.js +323 -0
  218. package/dist/limitNotes/plan.js.map +1 -0
  219. package/dist/limitNotes/reminderChoices.d.ts +30 -0
  220. package/dist/limitNotes/reminderChoices.d.ts.map +1 -0
  221. package/dist/limitNotes/reminderChoices.js +48 -0
  222. package/dist/limitNotes/reminderChoices.js.map +1 -0
  223. package/dist/limitNotes/service.d.ts +106 -0
  224. package/dist/limitNotes/service.d.ts.map +1 -0
  225. package/dist/limitNotes/service.js +169 -0
  226. package/dist/limitNotes/service.js.map +1 -0
  227. package/dist/openCodeSessionTitle.js +1 -1
  228. package/dist/openCodeSessionTitle.js.map +1 -1
  229. package/dist/outputTrace.d.ts +19 -0
  230. package/dist/outputTrace.d.ts.map +1 -1
  231. package/dist/outputTrace.js +23 -2
  232. package/dist/outputTrace.js.map +1 -1
  233. package/dist/platform/answerSink.d.ts +23 -0
  234. package/dist/platform/answerSink.d.ts.map +1 -1
  235. package/dist/platform/answerSink.js.map +1 -1
  236. package/dist/platform/operatorAlert.d.ts +24 -0
  237. package/dist/platform/operatorAlert.d.ts.map +1 -0
  238. package/dist/platform/operatorAlert.js +9 -0
  239. package/dist/platform/operatorAlert.js.map +1 -0
  240. package/dist/postToSession.d.ts +34 -2
  241. package/dist/postToSession.d.ts.map +1 -1
  242. package/dist/postToSession.js +31 -2
  243. package/dist/postToSession.js.map +1 -1
  244. package/dist/remoteRun/exitCodes.d.ts +2 -2
  245. package/dist/remoteRun/exitCodes.d.ts.map +1 -1
  246. package/dist/remoteRun/exitCodes.js +2 -2
  247. package/dist/remoteRun/exitCodes.js.map +1 -1
  248. package/dist/remoteRun/foreground.d.ts.map +1 -1
  249. package/dist/remoteRun/foreground.js +5 -1
  250. package/dist/remoteRun/foreground.js.map +1 -1
  251. package/dist/remoteRun/runnerClient.d.ts +1 -1
  252. package/dist/remoteRun/runnerClient.d.ts.map +1 -1
  253. package/dist/remoteRun/runnerClient.js +3 -3
  254. package/dist/remoteRun/runnerClient.js.map +1 -1
  255. package/dist/requests/answerRequest.d.ts +3 -0
  256. package/dist/requests/answerRequest.d.ts.map +1 -1
  257. package/dist/requests/answerRequest.js +9 -2
  258. package/dist/requests/answerRequest.js.map +1 -1
  259. package/dist/requests/limitWaitAnswer.d.ts +14 -0
  260. package/dist/requests/limitWaitAnswer.d.ts.map +1 -1
  261. package/dist/requests/limitWaitAnswer.js +26 -4
  262. package/dist/requests/limitWaitAnswer.js.map +1 -1
  263. package/dist/requests/requestHeader.d.ts +37 -5
  264. package/dist/requests/requestHeader.d.ts.map +1 -1
  265. package/dist/requests/requestHeader.js +46 -17
  266. package/dist/requests/requestHeader.js.map +1 -1
  267. package/dist/requests/scheduleWait.d.ts +79 -0
  268. package/dist/requests/scheduleWait.d.ts.map +1 -0
  269. package/dist/requests/scheduleWait.js +101 -0
  270. package/dist/requests/scheduleWait.js.map +1 -0
  271. package/dist/requests/sessionTurnProbe.d.ts +21 -3
  272. package/dist/requests/sessionTurnProbe.d.ts.map +1 -1
  273. package/dist/requests/sessionTurnProbe.js +18 -3
  274. package/dist/requests/sessionTurnProbe.js.map +1 -1
  275. package/dist/requests/topicRequestSettle.d.ts +13 -7
  276. package/dist/requests/topicRequestSettle.d.ts.map +1 -1
  277. package/dist/requests/topicRequestSettle.js +2 -2
  278. package/dist/requests/topicRequestSettle.js.map +1 -1
  279. package/dist/requests/trackerTurnPoster.d.ts +30 -0
  280. package/dist/requests/trackerTurnPoster.d.ts.map +1 -0
  281. package/dist/requests/trackerTurnPoster.js +36 -0
  282. package/dist/requests/trackerTurnPoster.js.map +1 -0
  283. package/dist/requests/types.d.ts +9 -2
  284. package/dist/requests/types.d.ts.map +1 -1
  285. package/dist/requests/wakeUpEngine.d.ts +188 -11
  286. package/dist/requests/wakeUpEngine.d.ts.map +1 -1
  287. package/dist/requests/wakeUpEngine.js +452 -43
  288. package/dist/requests/wakeUpEngine.js.map +1 -1
  289. package/dist/requests/wakeUpRules.d.ts +122 -12
  290. package/dist/requests/wakeUpRules.d.ts.map +1 -1
  291. package/dist/requests/wakeUpRules.js +117 -15
  292. package/dist/requests/wakeUpRules.js.map +1 -1
  293. package/dist/resumeContext.d.ts +2 -2
  294. package/dist/resumeContext.js +3 -3
  295. package/dist/resumeContext.js.map +1 -1
  296. package/dist/runnerUtility/adminService.js +1 -1
  297. package/dist/runnerUtility/adminService.js.map +1 -1
  298. package/dist/runnerUtility/guiAgent.d.ts +1 -1
  299. package/dist/runnerUtility/guiAgent.d.ts.map +1 -1
  300. package/dist/runnerUtility/guiAgent.js +1 -1
  301. package/dist/runnerUtility/guiAgent.js.map +1 -1
  302. package/dist/runnerUtility/managedNode.d.ts +3 -3
  303. package/dist/runnerUtility/managedNode.d.ts.map +1 -1
  304. package/dist/runnerUtility/managedNode.js +2 -2
  305. package/dist/runnerUtility/managedNode.js.map +1 -1
  306. package/dist/runnerUtility/runnerConfig.d.ts +1 -1
  307. package/dist/runnerUtility/runnerHome.d.ts +1 -1
  308. package/dist/runnerUtility/runnerHome.js +1 -1
  309. package/dist/runnerUtility/serviceCommon.d.ts +1 -1
  310. package/dist/runnerUtility/serviceCommon.d.ts.map +1 -1
  311. package/dist/runnerUtility/serviceCommon.js +1 -1
  312. package/dist/runnerUtility/serviceCommon.js.map +1 -1
  313. package/dist/runners/bootstrapLine.js +1 -1
  314. package/dist/runners/hubPackage.d.ts +1 -1
  315. package/dist/runners/hubPackage.js +3 -3
  316. package/dist/runners/hubPackage.js.map +1 -1
  317. package/dist/runners/hubPaths.d.ts +1 -1
  318. package/dist/runners/hubPaths.d.ts.map +1 -1
  319. package/dist/runners/runnerLock.d.ts +2 -2
  320. package/dist/runners/runnerLock.d.ts.map +1 -1
  321. package/dist/runners/runnerLock.js +2 -2
  322. package/dist/runners/runnerLock.js.map +1 -1
  323. package/dist/scheduler/checkRun.d.ts +2 -0
  324. package/dist/scheduler/checkRun.d.ts.map +1 -1
  325. package/dist/scheduler/checkRun.js +5 -1
  326. package/dist/scheduler/checkRun.js.map +1 -1
  327. package/dist/scheduler/delivery.d.ts +57 -0
  328. package/dist/scheduler/delivery.d.ts.map +1 -1
  329. package/dist/scheduler/delivery.js +152 -14
  330. package/dist/scheduler/delivery.js.map +1 -1
  331. package/dist/scheduler/injection.d.ts +6 -0
  332. package/dist/scheduler/injection.d.ts.map +1 -1
  333. package/dist/scheduler/injection.js +10 -0
  334. package/dist/scheduler/injection.js.map +1 -1
  335. package/dist/scheduler/mcpSurface.d.ts +38 -3
  336. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  337. package/dist/scheduler/mcpSurface.js +291 -175
  338. package/dist/scheduler/mcpSurface.js.map +1 -1
  339. package/dist/scheduler/rebindResume.d.ts +24 -0
  340. package/dist/scheduler/rebindResume.d.ts.map +1 -1
  341. package/dist/scheduler/rebindResume.js +32 -0
  342. package/dist/scheduler/rebindResume.js.map +1 -1
  343. package/dist/scheduler/scheduleToolWording.d.ts +29 -0
  344. package/dist/scheduler/scheduleToolWording.d.ts.map +1 -0
  345. package/dist/scheduler/scheduleToolWording.js +117 -0
  346. package/dist/scheduler/scheduleToolWording.js.map +1 -0
  347. package/dist/scheduler/scheduledRunTarget.d.ts +90 -0
  348. package/dist/scheduler/scheduledRunTarget.d.ts.map +1 -0
  349. package/dist/scheduler/scheduledRunTarget.js +92 -0
  350. package/dist/scheduler/scheduledRunTarget.js.map +1 -0
  351. package/dist/scheduler/store.d.ts +2 -0
  352. package/dist/scheduler/store.d.ts.map +1 -1
  353. package/dist/scheduler/store.js +2 -0
  354. package/dist/scheduler/store.js.map +1 -1
  355. package/dist/scheduler/types.d.ts +10 -0
  356. package/dist/scheduler/types.d.ts.map +1 -1
  357. package/dist/scheduler/workerWatch.d.ts +2 -0
  358. package/dist/scheduler/workerWatch.d.ts.map +1 -1
  359. package/dist/scheduler/workerWatch.js +3 -3
  360. package/dist/scheduler/workerWatch.js.map +1 -1
  361. package/dist/selfUpdate/constants.d.ts +2 -0
  362. package/dist/selfUpdate/constants.d.ts.map +1 -1
  363. package/dist/selfUpdate/constants.js +3 -1
  364. package/dist/selfUpdate/constants.js.map +1 -1
  365. package/dist/selfUpdate/emittedSource.d.ts.map +1 -1
  366. package/dist/selfUpdate/emittedSource.js +1 -1
  367. package/dist/selfUpdate/emittedSource.js.map +1 -1
  368. package/dist/selfUpdate/updateRuntime.js +1 -1
  369. package/dist/selfUpdate/updateRuntime.js.map +1 -1
  370. package/dist/sessionPick.d.ts +1 -1
  371. package/dist/sessionPick.js +1 -1
  372. package/dist/startupPromptBuffer.d.ts +35 -6
  373. package/dist/startupPromptBuffer.d.ts.map +1 -1
  374. package/dist/startupPromptBuffer.js +70 -21
  375. package/dist/startupPromptBuffer.js.map +1 -1
  376. package/dist/state.d.ts +173 -25
  377. package/dist/state.d.ts.map +1 -1
  378. package/dist/state.js +282 -58
  379. package/dist/state.js.map +1 -1
  380. package/dist/testTimings.d.ts +8 -3
  381. package/dist/testTimings.d.ts.map +1 -1
  382. package/dist/testTimings.js +15 -2
  383. package/dist/testTimings.js.map +1 -1
  384. package/dist/threadContextPreamble.d.ts +7 -0
  385. package/dist/threadContextPreamble.d.ts.map +1 -1
  386. package/dist/threadContextPreamble.js +11 -0
  387. package/dist/threadContextPreamble.js.map +1 -1
  388. package/dist/threadRouting.d.ts +12 -0
  389. package/dist/threadRouting.d.ts.map +1 -1
  390. package/dist/threadRouting.js +15 -0
  391. package/dist/threadRouting.js.map +1 -1
  392. package/dist/todos/midTurn.d.ts +15 -41
  393. package/dist/todos/midTurn.d.ts.map +1 -1
  394. package/dist/todos/midTurn.js +27 -171
  395. package/dist/todos/midTurn.js.map +1 -1
  396. package/dist/types.d.ts +147 -23
  397. package/dist/types.d.ts.map +1 -1
  398. package/dist/types.js +10 -0
  399. package/dist/types.js.map +1 -1
  400. package/dist/utils/backendSwitchPlan.d.ts +3 -3
  401. package/dist/utils/backendSwitchPlan.js +3 -3
  402. package/dist/utils/claudeAccountAlert.d.ts +104 -0
  403. package/dist/utils/claudeAccountAlert.d.ts.map +1 -0
  404. package/dist/utils/claudeAccountAlert.js +130 -0
  405. package/dist/utils/claudeAccountAlert.js.map +1 -0
  406. package/dist/utils/claudeAccountPickerPlan.d.ts +7 -0
  407. package/dist/utils/claudeAccountPickerPlan.d.ts.map +1 -1
  408. package/dist/utils/claudeAccountPickerPlan.js +13 -2
  409. package/dist/utils/claudeAccountPickerPlan.js.map +1 -1
  410. package/dist/utils/claudeAuthRefusal.d.ts +122 -0
  411. package/dist/utils/claudeAuthRefusal.d.ts.map +1 -0
  412. package/dist/utils/claudeAuthRefusal.js +228 -0
  413. package/dist/utils/claudeAuthRefusal.js.map +1 -0
  414. package/dist/utils/claudeCompactHook.d.ts +6 -6
  415. package/dist/utils/claudeCompactHook.js +8 -8
  416. package/dist/utils/claudeCompactHook.js.map +1 -1
  417. package/dist/utils/claudeProfileUsageViews.d.ts +54 -2
  418. package/dist/utils/claudeProfileUsageViews.d.ts.map +1 -1
  419. package/dist/utils/claudeProfileUsageViews.js +44 -1
  420. package/dist/utils/claudeProfileUsageViews.js.map +1 -1
  421. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  422. package/dist/utils/claudeProfiles.js +10 -1
  423. package/dist/utils/claudeProfiles.js.map +1 -1
  424. package/dist/utils/claudeRuntimeInfo.d.ts +24 -0
  425. package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -1
  426. package/dist/utils/claudeRuntimeInfo.js +128 -3
  427. package/dist/utils/claudeRuntimeInfo.js.map +1 -1
  428. package/dist/utils/claudeScheduledJobs.d.ts +6 -2
  429. package/dist/utils/claudeScheduledJobs.d.ts.map +1 -1
  430. package/dist/utils/claudeScheduledJobs.js +10 -2
  431. package/dist/utils/claudeScheduledJobs.js.map +1 -1
  432. package/dist/utils/claudeSessionTitle.js +1 -1
  433. package/dist/utils/claudeSessionTitle.js.map +1 -1
  434. package/dist/utils/claudeStreamJson.d.ts +28 -2
  435. package/dist/utils/claudeStreamJson.d.ts.map +1 -1
  436. package/dist/utils/claudeStreamJson.js +33 -3
  437. package/dist/utils/claudeStreamJson.js.map +1 -1
  438. package/dist/utils/claudeTranscriptEpoch.d.ts +14 -0
  439. package/dist/utils/claudeTranscriptEpoch.d.ts.map +1 -1
  440. package/dist/utils/claudeTranscriptEpoch.js +79 -19
  441. package/dist/utils/claudeTranscriptEpoch.js.map +1 -1
  442. package/dist/utils/claudeUsage.d.ts +103 -7
  443. package/dist/utils/claudeUsage.d.ts.map +1 -1
  444. package/dist/utils/claudeUsage.js +108 -15
  445. package/dist/utils/claudeUsage.js.map +1 -1
  446. package/dist/utils/compactOnIdle.d.ts +139 -29
  447. package/dist/utils/compactOnIdle.d.ts.map +1 -1
  448. package/dist/utils/compactOnIdle.js +163 -36
  449. package/dist/utils/compactOnIdle.js.map +1 -1
  450. package/dist/utils/conversationEnding.d.ts +76 -0
  451. package/dist/utils/conversationEnding.d.ts.map +1 -0
  452. package/dist/utils/conversationEnding.js +117 -0
  453. package/dist/utils/conversationEnding.js.map +1 -0
  454. package/dist/utils/doctorLine.d.ts +10 -0
  455. package/dist/utils/doctorLine.d.ts.map +1 -1
  456. package/dist/utils/doctorLine.js +16 -0
  457. package/dist/utils/doctorLine.js.map +1 -1
  458. package/dist/utils/fallbackBridge.d.ts.map +1 -1
  459. package/dist/utils/fallbackBridge.js +2 -1
  460. package/dist/utils/fallbackBridge.js.map +1 -1
  461. package/dist/utils/fallbackChain.d.ts +2 -0
  462. package/dist/utils/fallbackChain.d.ts.map +1 -1
  463. package/dist/utils/fallbackChain.js +4 -3
  464. package/dist/utils/fallbackChain.js.map +1 -1
  465. package/dist/utils/fallbackSwitchNotice.d.ts +11 -4
  466. package/dist/utils/fallbackSwitchNotice.d.ts.map +1 -1
  467. package/dist/utils/fallbackSwitchNotice.js +9 -5
  468. package/dist/utils/fallbackSwitchNotice.js.map +1 -1
  469. package/dist/utils/fileSendService.d.ts +31 -0
  470. package/dist/utils/fileSendService.d.ts.map +1 -1
  471. package/dist/utils/fileSendService.js +45 -2
  472. package/dist/utils/fileSendService.js.map +1 -1
  473. package/dist/utils/jsonStreamHost.d.ts +2 -0
  474. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  475. package/dist/utils/jsonStreamHost.js +4 -1
  476. package/dist/utils/jsonStreamHost.js.map +1 -1
  477. package/dist/utils/jsonStreamPendingWork.d.ts +14 -2
  478. package/dist/utils/jsonStreamPendingWork.d.ts.map +1 -1
  479. package/dist/utils/jsonStreamPendingWork.js +25 -5
  480. package/dist/utils/jsonStreamPendingWork.js.map +1 -1
  481. package/dist/utils/jsonStreamUnconsumedInput.d.ts +80 -0
  482. package/dist/utils/jsonStreamUnconsumedInput.d.ts.map +1 -0
  483. package/dist/utils/jsonStreamUnconsumedInput.js +99 -0
  484. package/dist/utils/jsonStreamUnconsumedInput.js.map +1 -0
  485. package/dist/utils/limitEpisodeRecovery.d.ts +43 -4
  486. package/dist/utils/limitEpisodeRecovery.d.ts.map +1 -1
  487. package/dist/utils/limitEpisodeRecovery.js +107 -20
  488. package/dist/utils/limitEpisodeRecovery.js.map +1 -1
  489. package/dist/utils/limitHeldPrompts.d.ts +21 -11
  490. package/dist/utils/limitHeldPrompts.d.ts.map +1 -1
  491. package/dist/utils/limitHeldPrompts.js +12 -9
  492. package/dist/utils/limitHeldPrompts.js.map +1 -1
  493. package/dist/utils/limitRemindersScreenPlan.d.ts +63 -0
  494. package/dist/utils/limitRemindersScreenPlan.d.ts.map +1 -0
  495. package/dist/utils/limitRemindersScreenPlan.js +121 -0
  496. package/dist/utils/limitRemindersScreenPlan.js.map +1 -0
  497. package/dist/utils/limitsBoardPlan.d.ts +16 -7
  498. package/dist/utils/limitsBoardPlan.d.ts.map +1 -1
  499. package/dist/utils/limitsBoardPlan.js +41 -9
  500. package/dist/utils/limitsBoardPlan.js.map +1 -1
  501. package/dist/utils/lostWork.d.ts +16 -2
  502. package/dist/utils/lostWork.d.ts.map +1 -1
  503. package/dist/utils/lostWork.js +16 -3
  504. package/dist/utils/lostWork.js.map +1 -1
  505. package/dist/utils/messageContext.d.ts +2 -2
  506. package/dist/utils/messageContext.js +2 -2
  507. package/dist/utils/midTurnInbox.d.ts +79 -0
  508. package/dist/utils/midTurnInbox.d.ts.map +1 -0
  509. package/dist/utils/midTurnInbox.js +265 -0
  510. package/dist/utils/midTurnInbox.js.map +1 -0
  511. package/dist/utils/promptDelivery.d.ts +70 -22
  512. package/dist/utils/promptDelivery.d.ts.map +1 -1
  513. package/dist/utils/promptDelivery.js +100 -42
  514. package/dist/utils/promptDelivery.js.map +1 -1
  515. package/dist/utils/topicIndicatorPlan.d.ts +13 -3
  516. package/dist/utils/topicIndicatorPlan.d.ts.map +1 -1
  517. package/dist/utils/topicIndicatorPlan.js +26 -4
  518. package/dist/utils/topicIndicatorPlan.js.map +1 -1
  519. package/dist/utils/topicRequest.d.ts +3 -0
  520. package/dist/utils/topicRequest.d.ts.map +1 -1
  521. package/dist/utils/topicRequest.js +4 -0
  522. package/dist/utils/topicRequest.js.map +1 -1
  523. package/dist/utils/workerRoles.d.ts +122 -0
  524. package/dist/utils/workerRoles.d.ts.map +1 -0
  525. package/dist/utils/workerRoles.js +160 -0
  526. package/dist/utils/workerRoles.js.map +1 -0
  527. package/dist/utils/workerRolesScreenPlan.d.ts +118 -0
  528. package/dist/utils/workerRolesScreenPlan.d.ts.map +1 -0
  529. package/dist/utils/workerRolesScreenPlan.js +232 -0
  530. package/dist/utils/workerRolesScreenPlan.js.map +1 -0
  531. package/dist/utils/workingSignals.d.ts +49 -0
  532. package/dist/utils/workingSignals.d.ts.map +1 -0
  533. package/dist/utils/workingSignals.js +41 -0
  534. package/dist/utils/workingSignals.js.map +1 -0
  535. package/licensing.json +88 -0
  536. package/npm-shrinkwrap.json +2 -2
  537. package/package.json +7 -7
  538. package/{remoteRun → runner-scripts}/runner.sh +6 -3
  539. package/LICENSE-COMMERCIAL.md +0 -142
  540. package/dist/agentTrigger.d.ts +0 -28
  541. package/dist/agentTrigger.d.ts.map +0 -1
  542. package/dist/agentTrigger.js +0 -53
  543. package/dist/agentTrigger.js.map +0 -1
  544. /package/{remoteRun → runner-scripts}/ensureNode.sh +0 -0
  545. /package/{remoteRun → runner-scripts}/runner-package-lock.json +0 -0
package/dist/bot.js CHANGED
@@ -60,9 +60,6 @@ const sessionKeyCodec_1 = require("./connectors/telegram/sessionKeyCodec");
60
60
  // Arms the Jira key codec: a Jira conversation's key read back from `state.json`
61
61
  // or a tmux / json-stream name must decode in every boot mode.
62
62
  require("./connectors/jira/sessionKeyCodec");
63
- // Pure parser lives in `./agentTrigger` so it can be unit-tested without
64
- // booting Telegraf (audit S19 / #25).
65
- const agentTrigger_1 = require("./agentTrigger");
66
63
  const sessionPick_1 = require("./sessionPick");
67
64
  const claudeCliAdapter_1 = require("./adapters/claudeCliAdapter");
68
65
  const openCodeAdapter_1 = require("./adapters/openCodeAdapter");
@@ -78,9 +75,15 @@ const waitingTopicRenames_1 = require("./connectors/telegram/waitingTopicRenames
78
75
  const topicIndicatorSources_1 = require("./utils/topicIndicatorSources");
79
76
  const rateLimiter_1 = require("./rateLimiter");
80
77
  const testTimings_1 = require("./testTimings");
78
+ const service_1 = require("./limitNotes/service");
79
+ const engine_1 = require("./limitNotes/engine");
80
+ const noteText_1 = require("./limitNotes/noteText");
81
+ const plan_1 = require("./limitNotes/plan");
82
+ const reminderChoices_1 = require("./limitNotes/reminderChoices");
81
83
  const installManager_1 = require("./installManager");
82
84
  const startupReadiness_1 = require("./utils/startupReadiness");
83
85
  const doctorLine_1 = require("./utils/doctorLine");
86
+ const groupWelcome_1 = require("./connectors/telegram/groupWelcome");
84
87
  const nativeWindows_1 = require("./utils/nativeWindows");
85
88
  const state_1 = require("./state");
86
89
  const diagLog_1 = require("./diagLog");
@@ -127,6 +130,7 @@ const postToSession_1 = require("./postToSession");
127
130
  const limitHeldPrompts_1 = require("./utils/limitHeldPrompts");
128
131
  const adoptReplayGate_1 = require("./utils/adoptReplayGate");
129
132
  const topicRequestSettle_1 = require("./requests/topicRequestSettle");
133
+ const trackerTurnPoster_1 = require("./requests/trackerTurnPoster");
130
134
  const promptDelivery_1 = require("./utils/promptDelivery");
131
135
  const apiRetryKick_1 = require("./apiRetryKick");
132
136
  const limitHeldPromptQueue_1 = require("./utils/limitHeldPromptQueue");
@@ -143,6 +147,7 @@ const sendErrorClassifier_1 = require("./sendErrorClassifier");
143
147
  const pinnedStatus_1 = require("./pinnedStatus");
144
148
  const progressLine_1 = require("./progressLine");
145
149
  const startupPromptBuffer_1 = require("./startupPromptBuffer");
150
+ const conversationEnding_1 = require("./utils/conversationEnding");
146
151
  const renderAgentHtml_1 = require("./connectors/telegram/renderAgentHtml");
147
152
  const messageSplit_1 = require("./connectors/telegram/messageSplit");
148
153
  const foldedMessage_1 = require("./connectors/telegram/foldedMessage");
@@ -220,7 +225,7 @@ const agentEnvironment_1 = require("./utils/agentEnvironment");
220
225
  const folderGit_1 = require("./utils/folderGit");
221
226
  const checkStatus_1 = require("./scheduler/checkStatus");
222
227
  const workerActivity_1 = require("./scheduler/workerActivity");
223
- const engine_1 = require("./scheduler/engine");
228
+ const engine_2 = require("./scheduler/engine");
224
229
  const recurrence_1 = require("./scheduler/recurrence");
225
230
  const mcpSurface_1 = require("./scheduler/mcpSurface");
226
231
  const injection_1 = require("./scheduler/injection");
@@ -236,6 +241,7 @@ const projects_1 = require("./todos/projects");
236
241
  const board_1 = require("./todos/board");
237
242
  const tools_1 = require("./todos/tools");
238
243
  const midTurn_1 = require("./todos/midTurn");
244
+ const midTurnInbox_1 = require("./utils/midTurnInbox");
239
245
  const answerTail_1 = require("./requests/answerTail");
240
246
  const answerSink_1 = require("./connectors/telegram/answerSink");
241
247
  const answerSink_2 = require("./platform/answerSink");
@@ -243,6 +249,7 @@ const sessionTurnProbe_1 = require("./requests/sessionTurnProbe");
243
249
  const limitWaitAnswer_1 = require("./requests/limitWaitAnswer");
244
250
  const localClock_1 = require("./utils/localClock");
245
251
  const wakeUpEngine_1 = require("./requests/wakeUpEngine");
252
+ const scheduleWait_1 = require("./requests/scheduleWait");
246
253
  const wakeUpRules_1 = require("./requests/wakeUpRules");
247
254
  const requestHeader_1 = require("./requests/requestHeader");
248
255
  const directoryThreads_1 = require("./scheduler/directoryThreads");
@@ -263,8 +270,10 @@ const reminders_1 = require("./connectors/telegram/commands/reminders");
263
270
  const modelProviders_1 = require("./connectors/telegram/commands/modelProviders");
264
271
  const callbackToast_2 = require("./connectors/telegram/commands/callbackToast");
265
272
  const compaction_1 = require("./connectors/telegram/commands/compaction");
273
+ const claudeRuntimeInfo_1 = require("./utils/claudeRuntimeInfo");
266
274
  const autoContinueLimits_1 = require("./connectors/telegram/commands/autoContinueLimits");
267
275
  const botSkills_2 = require("./connectors/telegram/commands/botSkills");
276
+ const workerRoles_1 = require("./connectors/telegram/commands/workerRoles");
268
277
  const questionWait_1 = require("./connectors/telegram/commands/questionWait");
269
278
  const topicStatus_1 = require("./connectors/telegram/commands/topicStatus");
270
279
  const topicAccess_1 = require("./connectors/telegram/commands/topicAccess");
@@ -282,7 +291,10 @@ const claudeAccounts_1 = require("./connectors/telegram/commands/claudeAccounts"
282
291
  const claudeProfiles_1 = require("./utils/claudeProfiles");
283
292
  const claudeUsage_1 = require("./utils/claudeUsage");
284
293
  const claudeUsageRefresher_1 = require("./utils/claudeUsageRefresher");
294
+ const workerRoles_2 = require("./utils/workerRoles");
285
295
  const claudeProfileSync_1 = require("./utils/claudeProfileSync");
296
+ const claudeAccountAlert_1 = require("./utils/claudeAccountAlert");
297
+ const claudeAuthRefusal_1 = require("./utils/claudeAuthRefusal");
286
298
  const openCodeUsage_1 = require("./utils/openCodeUsage");
287
299
  const usageRefreshBudget_1 = require("./utils/usageRefreshBudget");
288
300
  const claudeLimitSwitch_1 = require("./utils/claudeLimitSwitch");
@@ -295,6 +307,7 @@ const fallbackChain_1 = require("./utils/fallbackChain");
295
307
  const fallbackBridge_1 = require("./utils/fallbackBridge");
296
308
  const fallbackChain_2 = require("./connectors/telegram/commands/fallbackChain");
297
309
  const limitsBoard_1 = require("./connectors/telegram/commands/limitsBoard");
310
+ const limitReminders_1 = require("./connectors/telegram/commands/limitReminders");
298
311
  const todo_1 = require("./connectors/telegram/commands/todo");
299
312
  const backendSwitch_1 = require("./connectors/telegram/commands/backendSwitch");
300
313
  const operatorSwitchPlan_1 = require("./utils/operatorSwitchPlan");
@@ -626,9 +639,11 @@ const telegramOutbound = (0, outbound_1.createTelegramConnectorOutbound)({
626
639
  * conversation only through {@link getOutboundFor}, so a Jira conversation's
627
640
  * stream never lands in a Telegram send.
628
641
  */
642
+ /** The Jira connector's file send, set once the lazily loaded connector is ready (`send_file_to_user` on an issue). */
643
+ let jiraFileSender = null;
629
644
  const connectorOutbounds = new Map([
630
645
  ['telegram', telegramOutbound],
631
- ['jira', (0, outbound_3.createJiraConnectorOutbound)()],
646
+ ['jira', (0, outbound_3.createJiraConnectorOutbound)(() => jiraFileSender)],
632
647
  ]);
633
648
  function getOutboundFor(key) {
634
649
  return (0, outbound_2.getConnectorOutbound)(connectorOutbounds, key);
@@ -772,6 +787,7 @@ bot.use(async (ctx, next) => {
772
787
  preview: messageText === undefined
773
788
  ? callbackData
774
789
  : (0, recvPreviewRedaction_1.getRecvTracePreview)(messageText, isThreadPendingProviderConnect, awaitedSttStep),
790
+ topicName: (0, outputTrace_1.getForumTopicServiceName)(message),
775
791
  tgDateSec: message?.date,
776
792
  });
777
793
  return next();
@@ -989,9 +1005,11 @@ const noTopicRequest = { header: '', requestId: null };
989
1005
  * `null` intake is a prompt that is not a request by rule — an answer to the
990
1006
  * agent's own question, delivered as a prompt. The intake's requester decides
991
1007
  * which open request, if any, the new one supersedes (`requestGroup.ts`); the
992
- * header then names the replaced ones.
1008
+ * header then names the replaced ones. `onCreated` runs with the new id inside
1009
+ * the create, synchronously with the request appearing open (a person's prompt
1010
+ * marks itself in delivery there: {@link deliverPersonPromptInRequest}).
993
1011
  */
994
- async function openTopicRequest(key, text, intake, messageContext) {
1012
+ async function openTopicRequest(key, text, intake, messageContext, onCreated) {
995
1013
  if (intake === null || !topicRequestLedger || !(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
996
1014
  return noTopicRequest;
997
1015
  const view = state.getDisplayPrefs(key).view;
@@ -1001,7 +1019,10 @@ async function openTopicRequest(key, text, intake, messageContext) {
1001
1019
  // AGAIN when the session never took it in; the raw text would come back without the forwarded mark or the quote.
1002
1020
  const promptBody = getPromptWithThreadMessageContext(key, text, messageContext);
1003
1021
  const request = await topicRequestLedger.createRequest(key, (0, topicRequest_1.getTopicRequestOrigin)(intake), {
1004
- createPrompt: (requestId, supersededRequestIds) => (0, topicRequest_1.buildTopicRequestPrompt)({ requestId, source: intake.source, view, supersededRequestIds, promptBody, sender: messageContext?.nonOperatorSender }),
1022
+ createPrompt: (requestId, supersededRequestIds) => {
1023
+ onCreated?.(requestId);
1024
+ return (0, topicRequest_1.buildTopicRequestPrompt)({ requestId, source: intake.source, view, supersededRequestIds, promptBody, sender: messageContext?.nonOperatorSender });
1025
+ },
1005
1026
  });
1006
1027
  return { header: (0, topicRequest_1.buildTopicRequestHeader)(request.id, intake.source, view, request.supersededRequestIds, messageContext?.nonOperatorSender), requestId: request.id };
1007
1028
  }
@@ -1010,9 +1031,9 @@ async function openTopicRequest(key, text, intake, messageContext) {
1010
1031
  * wake-up engine watches the turn of a prompt that reached a session (or waits behind its start), and a prompt that found no
1011
1032
  * session closes the request it opened. Both ports are read at call time: the engine and the ledger are assigned at boot.
1012
1033
  */
1013
- const { trackTurn: trackTopicRequestTurn, settleAfterDelivery: settleTopicRequestAfterDelivery } = (0, topicRequestSettle_1.createTopicRequestSettler)({
1014
- trackTurn: async (key, requestId) => {
1015
- await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true });
1034
+ const { settleAfterDelivery: settleTopicRequestAfterDelivery } = (0, topicRequestSettle_1.createTopicRequestSettler)({
1035
+ trackTurn: async (key, requestId, { isScheduledRun }) => {
1036
+ await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true, isScheduledRun });
1016
1037
  },
1017
1038
  cancelRequest: async (requestId) => {
1018
1039
  await topicRequestLedger?.closeRequest(requestId, 'cancelled');
@@ -1072,6 +1093,44 @@ const readTodoSettings = (0, instanceSettings_1.createTodoSettingsReader)(() =>
1072
1093
  function getTodoReminderIntervalMsNow() {
1073
1094
  return (0, nag_1.getTodoReminderIntervalMs)(readTodoSettings(), ENV.testTimings.todoReminderIntervalMs);
1074
1095
  }
1096
+ /** `settings.json`'s `limitReminders` (General's interval for the accounts note), re-read when the file changes. */
1097
+ const readLimitRemindersSettings = (0, instanceSettings_1.createLimitRemindersSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
1098
+ /** The worker roles the operator changed (`/workers`): read at every `claude_profiles` call, so a change reaches the next launch. */
1099
+ const readWorkerRolesSettings = (0, instanceSettings_1.createWorkerRolesSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
1100
+ /** The accounts note's interval of a conversation in ms (its own choice, else General's, else 1 h; the test window replaces it); `null` = Off. */
1101
+ function getConversationLimitReminderIntervalMs(key) {
1102
+ return (0, reminderChoices_1.getLimitReminderIntervalMs)((0, reminderChoices_1.resolveLimitRemindersMinutes)(readLimitRemindersSettings(), state.getLimitRemindersOverride(key)), ENV.testTimings.limitReminderIntervalMs);
1103
+ }
1104
+ /** The quiet period, the summary floor and the orchestration window of the accounts note, with the test windows applied. */
1105
+ function getLimitNoteWindows() {
1106
+ return {
1107
+ ...plan_1.defaultLimitNoteWindows,
1108
+ minQuietMs: ENV.testTimings.limitNoteQuietMs ?? plan_1.defaultLimitNoteWindows.minQuietMs,
1109
+ summaryFloorMs: ENV.testTimings.limitNoteSummaryFloorMs ?? plan_1.defaultLimitNoteWindows.summaryFloorMs,
1110
+ };
1111
+ }
1112
+ let limitNotes = null;
1113
+ /**
1114
+ * The accounts note (`limitNotes/`): what a carrier prompt, a bot send tool's result and the two orchestration calls
1115
+ * (`claude_profiles`, a worker watch) say to it. It reads the usage cache and the conversation's record and writes only the record —
1116
+ * it never stamps activity, writes to an agent, wakes a session or opens a request (`limitNotes/README.md` § Lifecycle safety).
1117
+ */
1118
+ function getLimitNotes() {
1119
+ limitNotes ??= (0, service_1.createLimitNotes)({
1120
+ getRecord: (key) => state.getLimitNoteRecord(key),
1121
+ setRecord: (key, record) => state.setLimitNoteRecord(key, record),
1122
+ getIntervalMs: getConversationLimitReminderIntervalMs,
1123
+ getWindows: getLimitNoteWindows,
1124
+ // The report `claude_profiles` answers a new worker's launch with: the same pick and order, never a second ranking.
1125
+ getReport: (nowMs) => (0, claudeProfileUsageViews_1.buildClaudeProfilesCreditReport)(getClaudeProfileUsageViews(), null, nowMs, { chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()) }),
1126
+ getOpenCodeUsage: () => state.getOpenCodeProviderUsages(),
1127
+ getTimezone: getCurrentTimezone,
1128
+ getBackendName: (key) => (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name,
1129
+ getNowMs: Date.now,
1130
+ log: (line) => console.log(line),
1131
+ });
1132
+ return limitNotes;
1133
+ }
1075
1134
  /**
1076
1135
  * The reminder line a prompt forwarded now carries (D11 form a), or `null`; taking it counts as delivered. The lists
1077
1136
  * are a courtesy to the agent: a failure here is logged and the prompt goes on without the line.
@@ -1087,6 +1146,8 @@ function takeTodoPromptReminder(key) {
1087
1146
  }
1088
1147
  /** The staleness reminder's poll (`todos/reminderEngine.ts`), built at boot and started once the sessions are restored. */
1089
1148
  let todoReminderEngine = null;
1149
+ /** The accounts note's mid-turn delivery (`limitNotes/engine.ts`); built at boot, started with the sessions restored. */
1150
+ let limitNotesEngine = null;
1090
1151
  let todoRepositories = null;
1091
1152
  /** Which folders are one git repository (`todos/projects.ts`), cached; the root commits persist in `DATA_DIR/todos`. */
1092
1153
  function getTodoRepositories() {
@@ -1202,12 +1263,21 @@ function noteTodoFreshContext(key) {
1202
1263
  console.error(`[todos] ${(0, sessionKey_1.keyToString)(key)}: the board's seen state could not be reset:`, e instanceof Error ? e.message : e);
1203
1264
  }
1204
1265
  }
1266
+ let midTurnInbox = null;
1267
+ /**
1268
+ * The per-session mid-turn inbox a running Claude agent reads after its next tool call (`utils/midTurnInbox.ts`): the project board's
1269
+ * section and the accounts note's. One `PostToolUse` hook serves both; each section is offered and withdrawn on its own rules.
1270
+ */
1271
+ function getMidTurnInbox() {
1272
+ midTurnInbox ??= (0, midTurnInbox_1.createMidTurnInbox)({ inboxDir: (0, midTurnInbox_1.getMidTurnInboxDir)(getDataDir()) });
1273
+ return midTurnInbox;
1274
+ }
1205
1275
  let todoMidTurn = null;
1206
1276
  /** Mid-turn delivery of the board (`todos/midTurn.ts`): the Claude inbox hook, the note into a running OpenCode turn. */
1207
1277
  function getTodoMidTurn() {
1208
1278
  todoMidTurn ??= (0, midTurn_1.createTodoMidTurn)({
1209
1279
  board: getTodoBoard(),
1210
- inboxDir: (0, midTurn_1.getTodoInboxDir)(getDataDir()),
1280
+ inbox: getMidTurnInbox(),
1211
1281
  getClaudeSessionId: (key) => {
1212
1282
  const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name;
1213
1283
  return adapterName !== undefined && (0, createAdapter_1.checkIsClaudeBackend)(adapterName) ? getResumableSessionId(key) : null;
@@ -1231,6 +1301,18 @@ function discardTodoInbox(key) {
1231
1301
  console.error(`[todos] ${(0, sessionKey_1.keyToString)(key)}: the mid-turn inbox could not be withdrawn:`, e instanceof Error ? e.message : e);
1232
1302
  }
1233
1303
  }
1304
+ /**
1305
+ * A turn start the bot makes, a session boundary: the accounts note's mid-turn section of the inbox is withdrawn unseen — a tool call of
1306
+ * the old turn must not take a note the prompt may carry itself, or one meant for a session that is gone — and the note stays due.
1307
+ */
1308
+ function withdrawAccountsInbox(key) {
1309
+ try {
1310
+ getMidTurnInbox().withdraw(key, 'accounts');
1311
+ }
1312
+ catch (e) {
1313
+ console.error(`[limit-notes] ${(0, sessionKey_1.keyToString)(key)}: the mid-turn inbox could not be withdrawn:`, e instanceof Error ? e.message : e);
1314
+ }
1315
+ }
1234
1316
  /**
1235
1317
  * The board block a prompt forwarded now carries (D20), or `null`; taking it counts as seen. A failure never stops the prompt.
1236
1318
  * Synchronous: it sits between the forward's decision and the write (see `TodoBoard.takePromptBoard`).
@@ -1638,6 +1720,26 @@ const wedgeRecoveryTier = new Map();
1638
1720
  * like one, and a reminder on top would be a second recovery of the same turn.
1639
1721
  */
1640
1722
  const wedgeRecoveriesInFlight = new Set();
1723
+ /**
1724
+ * Threads whose API error the bot is still handling with NOTHING armed — «wait for reset» off, a used-up credit balance, an account
1725
+ * refusal or a logged-out notice ({@link handleApiError}), by how many such errors are in hand: from the error, which the adapter
1726
+ * reports right before the turn's end, until that handling's stop, move or wait has landed. The request wake-up probe reads it as «not
1727
+ * a turn end»: decided at once, the turn that ended on the error would be a silent one, and its reminder written into the limited or
1728
+ * refused session would end on the same error — the second silent turn, the give-up. A branch that arms a retry is held by the timer.
1729
+ */
1730
+ const apiErrorsInHandling = new Map();
1731
+ /** Hold `key`'s turn end ({@link apiErrorsInHandling}) until `handling` — an API error's stop, move or wait — has settled. */
1732
+ function holdTurnEndWhileHandlingApiError(key, handling) {
1733
+ const k = (0, sessionKey_1.keyToString)(key);
1734
+ apiErrorsInHandling.set(k, (apiErrorsInHandling.get(k) ?? 0) + 1);
1735
+ void handling.finally(() => {
1736
+ const count = (apiErrorsInHandling.get(k) ?? 1) - 1;
1737
+ if (count > 0)
1738
+ apiErrorsInHandling.set(k, count);
1739
+ else
1740
+ apiErrorsInHandling.delete(k);
1741
+ });
1742
+ }
1641
1743
  /**
1642
1744
  * @description `apiError` from the adapter — arm (or escalate) an auto-retry, or
1643
1745
  * give up. The pure decision lives in {@link decideRetryAction}; this handler is
@@ -1664,11 +1766,11 @@ function handleApiError(key, cls, options = {}) {
1664
1766
  }
1665
1767
  // A used-up API credit balance: no wait refills it — the account is marked, and the chain or the operator takes over.
1666
1768
  if (cls.kind === 'usageLimit' && cls.isBalanceExhausted === true) {
1667
- void handleBalanceExhausted(key, cls);
1769
+ holdTurnEndWhileHandlingApiError(key, handleBalanceExhausted(key, cls));
1668
1770
  return;
1669
1771
  }
1670
1772
  // An unconfirmed usage limit is probed first; it reaches the wait below only once confirmed.
1671
- if (cls.kind === 'usageLimit' && cls.isUnconfirmed === true && handleUnconfirmedLimit(key))
1773
+ if (cls.kind === 'usageLimit' && cls.isUnconfirmed === true && handleUnconfirmedLimit(key, options.isRecoveredEpisode === true ? options.episodeWrittenAtMs : undefined))
1672
1774
  return;
1673
1775
  if (cls.kind === 'usageLimit' && !state.checkIsAutoContinueOnLimitEnabled(key)) {
1674
1776
  const isFirstOffNotice = !autoContinueOffNoticedThreads.has(k);
@@ -1677,7 +1779,7 @@ function handleApiError(key, cls, options = {}) {
1677
1779
  // Each repeat is offered to the open request: the dedup is per request, so one
1678
1780
  // opened after the first notice still hears about the limit (and is stopped).
1679
1781
  const wait = { kind: 'autoResumeOff' };
1680
- void announceUsageLimitOrSwitch(key, cls, Date.now(), wait, 0, isFirstOffNotice);
1782
+ holdTurnEndWhileHandlingApiError(key, announceUsageLimitOrSwitch(key, cls, Date.now(), wait, 0, isFirstOffNotice));
1681
1783
  return;
1682
1784
  }
1683
1785
  const entry = apiRetryTimers.get(k);
@@ -1691,10 +1793,11 @@ function handleApiError(key, cls, options = {}) {
1691
1793
  now,
1692
1794
  prev,
1693
1795
  });
1694
- // auth / logged out → surface a pinned notice (never a timer). Deduped to one
1695
- // notice per episode inside `surfaceLoggedOutNotice`.
1796
+ // auth / logged out → never a timer. A json-stream Claude conversation moves to another signed-in account and goes on
1797
+ // there (`handleClaudeAuthRefusal`; the frozen tmux backend keeps the notice alone); anything else, or nowhere to go,
1798
+ // surfaces a pinned notice — deduped to one per episode inside `surfaceLoggedOutNotice`.
1696
1799
  if (action.action === 'surface') {
1697
- void surfaceLoggedOutNotice(key);
1800
+ holdTurnEndWhileHandlingApiError(key, (0, createAdapter_1.getThreadAdapter)(key) instanceof claudeJsonStreamAdapter_1.ClaudeJsonStreamAdapter ? handleClaudeAuthRefusal(key, cls) : surfaceLoggedOutNotice(key));
1698
1801
  return;
1699
1802
  }
1700
1803
  if (action.action === 'ignore')
@@ -1768,7 +1871,7 @@ function armApiRetryTimer(key, arming) {
1768
1871
  clearSavedFiredLimitProbe(key);
1769
1872
  const timer = setTimeout(() => {
1770
1873
  void fireApiRetry(key);
1771
- }, Math.min(arming.delayMs, engine_1.maxTimeoutMs));
1874
+ }, Math.min(arming.delayMs, engine_2.maxTimeoutMs));
1772
1875
  timer.unref?.();
1773
1876
  apiRetryTimers.set((0, sessionKey_1.keyToString)(key), {
1774
1877
  timer,
@@ -1785,10 +1888,11 @@ function armApiRetryTimer(key, arming) {
1785
1888
  /**
1786
1889
  * @description An UNCONFIRMED usage limit (`isUnconfirmed`) of `key`: the probe retry it gets first — or `false` when the
1787
1890
  * limit is confirmed and takes the usual usage-limit wait. Confirmed when it came again right after the probe fired, or
1788
- * the topic's account shows a window at 100 % ({@link checkIsTopicAccountUsageExhausted}); a retry already pending —
1789
- * the probe or a short retry — takes it with it (`true`, nothing more to do).
1891
+ * the topic's account shows a window at 100 % ({@link checkIsTopicAccountUsageExhausted}) — in a reading taken no earlier than
1892
+ * `readingNotBeforeMs` when given (a recovered episode's own time); a retry already pending — the probe or a short retry — takes
1893
+ * it with it (`true`, nothing more to do).
1790
1894
  */
1791
- function handleUnconfirmedLimit(key) {
1895
+ function handleUnconfirmedLimit(key, readingNotBeforeMs) {
1792
1896
  const k = (0, sessionKey_1.keyToString)(key);
1793
1897
  const entry = apiRetryTimers.get(k);
1794
1898
  // A retry already pending (the probe itself, or a short retry) takes this error with it — as `decideRetryAction`
@@ -1798,7 +1902,7 @@ function handleUnconfirmedLimit(key) {
1798
1902
  return true;
1799
1903
  }
1800
1904
  const isRepeatAfterProbe = entry?.isLimitProbe === true && entry.firedAt !== null && Date.now() - entry.firedAt <= apiErrorRetry_1.retryRecurrenceGraceMs;
1801
- const action = (0, apiErrorRetry_1.getUnconfirmedLimitAction)({ isRepeatAfterProbe, isUsageExhausted: checkIsTopicAccountUsageExhausted(key) });
1905
+ const action = (0, apiErrorRetry_1.getUnconfirmedLimitAction)({ isRepeatAfterProbe, isUsageExhausted: checkIsTopicAccountUsageExhausted(key, readingNotBeforeMs) });
1802
1906
  if (action === 'waitForReset') {
1803
1907
  console.log(`[apiRetry] ${k}: the unconfirmed usage limit is confirmed (${isRepeatAfterProbe ? 'it came again after the probe' : 'the account is marked limited or reads a window at 100 %'}) — waiting for the reset`);
1804
1908
  return false;
@@ -1811,16 +1915,18 @@ function handleUnconfirmedLimit(key) {
1811
1915
  }
1812
1916
  /**
1813
1917
  * @description Whether the topic's account usage reading proves its limit: a Claude topic's live profile marked limited
1814
- * (a rejected `rate_limit_event`) or showing a window its model drains at 100 %. Other backends carry no reading for the
1815
- * account an unconfirmed wording names: `false`, and only a repeat confirms it.
1918
+ * (a rejected `rate_limit_event`) or showing a window its model drains at 100 % — in a reading taken no earlier than
1919
+ * `readingNotBeforeMs` when given (`checkIsClaudeUsageExhausted`). Other backends carry no reading for the account an
1920
+ * unconfirmed wording names: `false`, and only a repeat confirms it.
1816
1921
  */
1817
- function checkIsTopicAccountUsageExhausted(key) {
1922
+ function checkIsTopicAccountUsageExhausted(key, readingNotBeforeMs) {
1818
1923
  if (!checkIsClaudeProfileBackend(key))
1819
1924
  return false;
1820
1925
  const info = state.getClaudeProfileInfo(resolveLiveClaudeProfileName(key));
1821
1926
  const limitedUntilMs = info?.limitedUntil ? Date.parse(info.limitedUntil) : Number.NaN;
1822
1927
  const nowMs = Date.now();
1823
- return (Number.isFinite(limitedUntilMs) && limitedUntilMs > nowMs) || (0, claudeUsage_1.checkIsClaudeUsageExhausted)(info?.usage, getThreadClaudeModel(key), nowMs);
1928
+ return (Number.isFinite(limitedUntilMs) && limitedUntilMs > nowMs)
1929
+ || (0, claudeUsage_1.checkIsClaudeUsageExhausted)(info?.usage, getThreadClaudeModel(key), nowMs, { readNotBeforeMs: readingNotBeforeMs });
1824
1930
  }
1825
1931
  /**
1826
1932
  * @description R23: hold a prompt that arrives while `key` waits out an ARMED
@@ -1896,14 +2002,14 @@ const apiRetryKickDeps = {
1896
2002
  },
1897
2003
  getResumeMessage: (key, retryKind) => (0, limitHeldPrompts_1.getLimitResumeMessage)({
1898
2004
  continueNudge: (0, i18n_1.t)('apiRetry.continueNudge'),
1899
- untakenRequestPrompt: retryKind === 'usageLimit'
1900
- ? (0, requestHeader_1.joinPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? [])
2005
+ untakenRequestPrompts: retryKind === 'usageLimit'
2006
+ ? (0, requestHeader_1.getPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? [])
1901
2007
  : undefined,
1902
2008
  }),
1903
2009
  // `ensureAgentSession` is already satisfied by a start ANOTHER caller has under way — the session is
1904
2010
  // not there to take the nudge yet, so it goes through the startup buffer, not straight to the adapter.
1905
2011
  // The buffer is in memory: the kick keeps the saved record until the buffer settles the nudge.
1906
- deliverNudge: (key, text, onBufferedSettled) => deliverPromptOrBuffer(key, text, startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)), onBufferedSettled),
2012
+ deliverNudge: (key, text, onBufferedSettled) => deliverPromptOrBuffer(key, text, onBufferedSettled),
1907
2013
  trackContinuation: async (key, options) => {
1908
2014
  await requestWakeUpEngine?.trackContinuationTurn(key, options);
1909
2015
  },
@@ -2034,12 +2140,21 @@ async function handleBalanceExhausted(key, cls) {
2034
2140
  }
2035
2141
  if (plan.action === 'auto') {
2036
2142
  const to = plan.to;
2037
- if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
2038
- await replyToThread(key, notice);
2039
- const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true, isAutomatic: true }).catch((e) => {
2040
- console.warn(`[fallback] ${k}: the auto-switch to ${formatFallbackEntry(to)} failed:`, e instanceof Error ? e.message : e);
2041
- return { isSwitched: false };
2042
- });
2143
+ // A move onto the other backend ends the conversation it leaves, known now: held ahead of the paced notice, so a stop under way
2144
+ // drops what it held instead of resuming the backend whose credit is used up (review 24, own pass).
2145
+ const ending = checkIsFallbackMoveAcrossBackends(key, plan.from, to) ? conversationEndings.hold(key) : undefined;
2146
+ let outcome;
2147
+ try {
2148
+ if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
2149
+ await replyToThread(key, notice);
2150
+ outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true, isAutomatic: true, ending }).catch((e) => {
2151
+ console.warn(`[fallback] ${k}: the auto-switch to ${formatFallbackEntry(to)} failed:`, e instanceof Error ? e.message : e);
2152
+ return { isSwitched: false };
2153
+ });
2154
+ }
2155
+ finally {
2156
+ ending?.release();
2157
+ }
2043
2158
  // The notice is already in the topic; an open request still hears that the work stopped.
2044
2159
  if (!outcome.isSwitched)
2045
2160
  await announceLimitWait(key, stopped, texts, false);
@@ -2076,7 +2191,7 @@ function retargetLimitWait(key, episodeId, earliest) {
2076
2191
  return null;
2077
2192
  const fireAt = earliest.untilMs + apiErrorRetry_1.resetBufferMs;
2078
2193
  clearTimeout(entry.timer);
2079
- entry.timer = setTimeout(() => { void fireApiRetry(key); }, Math.min(Math.max(fireAt - Date.now(), 0), engine_1.maxTimeoutMs));
2194
+ entry.timer = setTimeout(() => { void fireApiRetry(key); }, Math.min(Math.max(fireAt - Date.now(), 0), engine_2.maxTimeoutMs));
2080
2195
  entry.timer.unref?.();
2081
2196
  entry.fireAt = fireAt;
2082
2197
  entry.resumeOn = earliest.entry;
@@ -2223,25 +2338,28 @@ async function handleNoResponseWithLocale(key) {
2223
2338
  await replyToThread(key, (0, i18n_1.t)('agent.session_recovering'));
2224
2339
  }
2225
2340
  else if (action === 'fork') {
2226
- // Restore the last dialog into a fresh, unwedged session.
2341
+ // Restore the last dialog into a fresh, unwedged session — as the conversation's one transition, like every start.
2227
2342
  await replyToThread(key, (0, i18n_1.t)('agent.session_recovering'));
2228
- const forkedId = await adapter.forkSession(key);
2229
- if (forkedId) {
2230
- await persistSessionStart(key, adapter);
2231
- }
2232
- else {
2343
+ const startMsg = await runCommandSessionTransition(key, async () => {
2344
+ const forkedId = await adapter.forkSession(key);
2345
+ if (forkedId) {
2346
+ await persistSessionStart(key, adapter);
2347
+ return '';
2348
+ }
2233
2349
  // Fork failed → fall back immediately to a blank restart this tier.
2234
2350
  await releaseThreadSession(key);
2235
- const startMsg = await startAgentSession(key);
2236
- if (startMsg)
2237
- await replyToThread(key, startMsg);
2238
- }
2351
+ return startAgentSession(key);
2352
+ });
2353
+ if (startMsg)
2354
+ await replyToThread(key, startMsg);
2239
2355
  }
2240
2356
  else {
2241
2357
  // action === 'restart': blank fresh session (dialog dropped).
2242
2358
  await replyToThread(key, (0, i18n_1.t)('agent.session_restarting'));
2243
- await releaseThreadSession(key);
2244
- const startMsg = await startAgentSession(key);
2359
+ const startMsg = await runCommandSessionTransition(key, async () => {
2360
+ await releaseThreadSession(key);
2361
+ return startAgentSession(key);
2362
+ });
2245
2363
  if (startMsg)
2246
2364
  await replyToThread(key, startMsg);
2247
2365
  }
@@ -2473,6 +2591,11 @@ function clearThreadContextMarker(key) {
2473
2591
  // this session will take is withdrawn.
2474
2592
  noteTodoFreshContext(key);
2475
2593
  discardTodoInbox(key);
2594
+ // …and for the accounts notes: a mid-turn note waiting for a tool call of a session that is going away is withdrawn FIRST — a
2595
+ // file the hook already took is counted as delivered there, and that record must not land after the reset below — then the agent no
2596
+ // longer holds the picture its last note showed (the reminder clock stays).
2597
+ withdrawAccountsInbox(key);
2598
+ state.clearLimitNoteFingerprint(key);
2476
2599
  }
2477
2600
  function getThreadMessageState(key) {
2478
2601
  const k = (0, sessionKey_1.keyToString)(key);
@@ -4509,6 +4632,10 @@ function listAvailableSubdirs(workRoot, limit = 200) {
4509
4632
  function stopAllAdaptersFor(key, adapterNames) {
4510
4633
  return (0, createAdapter_1.stopAllAdaptersFor)(key, createAdapter_1.getAdapter, adapterNames);
4511
4634
  }
4635
+ /** {@link stopAllAdaptersFor} that resolves once every process it stopped is gone (`stopSessionAndWait` where the adapter has it). */
4636
+ function stopAndWaitAllAdaptersFor(key, adapterNames) {
4637
+ return (0, createAdapter_1.stopAndWaitAllAdaptersFor)(key, createAdapter_1.getAdapter, adapterNames);
4638
+ }
4512
4639
  /**
4513
4640
  * @description Explicit-stop teardown used by `/new`:
4514
4641
  * sweep every adapter active for the thread, then RELEASE the persisted session
@@ -4572,14 +4699,20 @@ function closeSetAsideQuestionsInBackground(key) {
4572
4699
  *
4573
4700
  * Resolves the work the stop cut off that the agent's next prompt is told about (`null`: none), so a caller's line to
4574
4701
  * the operator is derived from the very record the note lists.
4702
+ *
4703
+ * Onto another agent or a shell it closes the conversation's requests (`cancelEndingConversationRequests`), telling a person whose words
4704
+ * the agent never took in; `options.promptsReachedOrHeld` is a reading of «taken in» a bridged move took ahead of its bridge (absent: read
4705
+ * here, before the old process is stopped). `options.isConversationKept` keeps the set-aside questions (an automatic move).
4575
4706
  */
4576
4707
  async function switchThreadAdapter(key, newName, options = {}) {
4577
4708
  const prevName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
4578
4709
  // Another agent or a shell takes the topic over: the open request belonged to
4579
- // the old conversation, so it closes silently instead of a later wake-up
4580
- // reminding (or, in a terminal, TYPING into) a session that never saw it.
4710
+ // the old conversation, so it closes instead of a later wake-up reminding (or,
4711
+ // in a terminal, TYPING into) a session that never saw it — and a person whose
4712
+ // words the agent never read is told (review 25 #3).
4581
4713
  if (prevName && !(0, createAdapter_1.checkIsSameConversationSwitch)(prevName, newName)) {
4582
- cancelConversationRequest(key);
4714
+ // A bridged move hands in what it read ahead of its bridge, so the reading and the bridge describe the same moment (review 27 nit 5).
4715
+ cancelEndingConversationRequests(key, options.promptsReachedOrHeld);
4583
4716
  // Nor does the conversation left behind get its re-asked question answered: its buttons would send the label into the new one.
4584
4717
  closeReAskedQuestion(key);
4585
4718
  // The same for the questions it had set aside — unless the bot moved the conversation itself (an automatic usage-limit
@@ -4808,23 +4941,20 @@ const adoptedPerTurnStopPollMs = 5000;
4808
4941
  async function startAgentSession(key, args) {
4809
4942
  const kStr = (0, sessionKey_1.keyToString)(key);
4810
4943
  // The bound folder IS the agent's cwd — refuse to start without one. The
4811
- // command/natural-language callers gate on the binding too, but a binding
4944
+ // command callers gate on the binding too, but a binding
4812
4945
  // can vanish (/unbind) between their check and here, so re-check before any
4813
4946
  // side effect (startup window / markers) opens.
4814
4947
  const workDirDecision = getWorkDirStartDecision(key);
4815
- if (!workDirDecision.ok)
4948
+ if (!workDirDecision.ok) {
4949
+ // A failed resume's window this start was to take over has nowhere to go either (a start with no window discards nothing).
4950
+ startupPromptBuffer.discardPrompts(kStr);
4816
4951
  return workDirDecision.message;
4952
+ }
4817
4953
  const workDir = workDirDecision.workDir;
4818
4954
  // Open the startup window synchronously (before the first await) so text
4819
- // typed right after `/claude` / `/opencode` is buffered, not dropped.
4955
+ // typed right after `/claude` / `/opencode` is buffered, not dropped. A failed resume's window may be open already: this start takes
4956
+ // it over, and its replay writes what the resume held.
4820
4957
  startupPromptBuffer.markStarting(kStr);
4821
- // A fresh session is a new conversation — clear any spent compact-on-idle latch
4822
- // (D2) so this session can idle-compact even if the PREVIOUS session in this
4823
- // thread already fired one (its latch persisted). The user starting the agent
4824
- // is the genuine user action that re-arms it.
4825
- if (state.checkIsCompactIdleLatched(key)) {
4826
- void state.setCompactIdleLatched(key, false);
4827
- }
4828
4958
  markNeedsNewMessage(key);
4829
4959
  // Fresh session — the agent's context is empty, so the next prompt must
4830
4960
  // re-carry the thread-context preamble. Forget the last-injected marker.
@@ -4895,11 +5025,10 @@ function getAgentStartFailureText(adapterLabel, error, formatError) {
4895
5025
  /**
4896
5026
  * @description Ensure the thread `key` has an agent session ready to take a
4897
5027
  * prompt, starting one if needed — the single choke point shared by the
4898
- * natural-language-start path, the `/schedule` command (S7), and the scheduler
5028
+ * `/schedule` command (S7), the voice and text prompt routes, and the scheduler
4899
5029
  * delivery (S4). It does NOT itself send any user-facing reply: it returns the
4900
5030
  * outcome (and the message to show) so each caller decides its own messaging
4901
- * (e.g. the natural-language path adds a General-topic guard + a folder picker
4902
- * on `unbound`, the scheduler annotates the run ledger instead).
5031
+ * (e.g. the scheduler annotates the run ledger instead of replying).
4903
5032
  *
4904
5033
  * Cases:
4905
5034
  * - already active → `{ ok: true }` (no message; nothing started).
@@ -4908,11 +5037,10 @@ function getAgentStartFailureText(adapterLabel, error, formatError) {
4908
5037
  * - no session, has binding, but no adapter resolves (no explicit pick, no
4909
5038
  * in-memory/persisted choice, no `fallbackAdapterName`) →
4910
5039
  * `{ ok: false, reason: 'no-adapter' }` — refuse rather than silently launch
4911
- * a default backend (interactive starts always pass `preferredAdapterName`,
4912
- * so this only bites a `/schedule`/scheduler fire on a never-started topic).
4913
- * - no session, has binding → resolve the adapter name (explicit
4914
- * `preferredAdapterName` → in-memory thread pick → persisted
4915
- * `agents[key].name` → `fallbackAdapterName`), `switchThreadAdapter`
5040
+ * a default backend (an interactive start picks its adapter first, so this
5041
+ * only bites a `/schedule`/scheduler fire on a never-started topic).
5042
+ * - no session, has binding → resolve the adapter name (in-memory
5043
+ * thread pick → persisted `agents[key].name` → `fallbackAdapterName`), `switchThreadAdapter`
4916
5044
  * + `startAgentSession`, then report `ok` from whether the session came up.
4917
5045
  */
4918
5046
  async function ensureAgentSession(key, options = {}) {
@@ -4925,14 +5053,45 @@ async function ensureAgentSession(key, options = {}) {
4925
5053
  * {@link ensureAgentSession} and {@link suspendThreadSession}.
4926
5054
  */
4927
5055
  const sessionTransitions = new keyedTransitionQueue_1.KeyedTransitionQueue();
5056
+ /**
5057
+ * @description Run a start or resume a COMMAND makes — `/new`, a first `/claude` / `/opencode`, `/claude_mode`'s switch, `/resume`'s
5058
+ * pick, the wedge recovery's restart or fork — as the conversation's one transition, like an ensure or an idle stop. No two of them
5059
+ * overlap, so no startup window is opened by one and ended by another, and an ensure that comes meanwhile waits for it instead of
5060
+ * starting or resuming a second session beside it (review 20 nit 3). Never call it from inside a transition: the queue would wait for
5061
+ * itself.
5062
+ */
5063
+ function runCommandSessionTransition(key, transition) {
5064
+ return sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
5065
+ await waitForPendingRespawn(key);
5066
+ return transition();
5067
+ });
5068
+ }
5069
+ /**
5070
+ * Conversations a command is about to END or REPLACE — `/new`, a `/resume` pick, `/quit`, leaving the folder, `/quitall`, a move across
5071
+ * backends, a start onto another agent or a shell —, each held from the moment the bot knows the command ends it (ahead of the toast of
5072
+ * its tap, a paced send, a move's bridge: review 24 #1) until its OWN transition begins (`utils/conversationEnding.ts`): a transition
5073
+ * queued ahead of it — a stop's resume for the prompts it held, a start's or a resume's replay of its window — drops those prompts instead
5074
+ * of writing them into the conversation the command ends, where they would start a turn the command then kills, unread and untold; a
5075
+ * person is told, and nothing is resumed or started for them (review 21 nit 4, review 22 nit 3, review 23 #1). Not `/claude_mode`: it
5076
+ * keeps the conversation, and a prompt written to the old backend's process is posted again by the turn's wake (R21).
5077
+ */
5078
+ const conversationEndings = new conversationEnding_1.ConversationEndings({ toConversationKey: sessionKey_1.keyToString, runTransition: runCommandSessionTransition });
5079
+ /**
5080
+ * @description A json-stream re-spawn (a model, effort or account change, a deferred one at a turn's end) replaces the process inside the
5081
+ * adapter, outside this queue, with the process down for seconds: an ensure or a command transition waits for it first, and then reads the
5082
+ * re-spawned process live instead of starting or resuming a second one beside it (review 21 nit 6).
5083
+ */
5084
+ async function waitForPendingRespawn(key) {
5085
+ await (0, createAdapter_1.getThreadAdapter)(key).waitForRespawn?.(key);
5086
+ }
4928
5087
  async function ensureAgentSessionNow(key, options) {
5088
+ await waitForPendingRespawn(key);
4929
5089
  // Resolve which adapter to run. `getThreadAdapterNameRaw` returns the
4930
5090
  // in-memory pick WITHOUT any default fallback, so "no pick yet" stays
4931
5091
  // distinguishable and the chain never silently defaults to a backend. When
4932
5092
  // nothing resolves (bound topic that never picked an agent, no caller
4933
5093
  // fallback) we REFUSE — the user must start/pick an agent first.
4934
- const adapterName = options.preferredAdapterName ??
4935
- (0, createAdapter_1.getThreadAdapterNameRaw)(key) ??
5094
+ const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ??
4936
5095
  state.getAgent(key)?.name ??
4937
5096
  options.fallbackAdapterName ??
4938
5097
  null;
@@ -4944,7 +5103,10 @@ async function ensureAgentSessionNow(key, options) {
4944
5103
  console.log(`[lifecycle] ${(0, sessionKey_1.keyToString)(key)}: the per-turn pick is kept; this session runs without the per-turn stop`);
4945
5104
  }
4946
5105
  const plan = (0, ensureSessionPlan_1.getEnsureSessionPlan)({
4947
- isActive: (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key),
5106
+ // Whether the process takes input, as a prompt reads it: a process the adapter is stopping by itself (a torn stdin frame's suspend,
5107
+ // outside this queue) is resumed — the resume joins that stop — instead of read `ready` while the prompt meets a dying process (review
5108
+ // 25 nit 4). Every other stop runs in this queue and is over before the plan reads.
5109
+ isActive: checkIsAcceptingInput(key),
4948
5110
  isStarting: startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
4949
5111
  hasBinding: state.getBinding(key) !== undefined,
4950
5112
  adapterName,
@@ -4967,14 +5129,20 @@ async function ensureAgentSessionNow(key, options) {
4967
5129
  if (resumeFailure === null)
4968
5130
  return { ok: true, message: '', isFresh: false };
4969
5131
  const failureAction = (0, ensureSessionPlan_1.getResumeFailureAction)(resumeFailure, options.isResumeOnly === true);
5132
+ // The failed resume's window is still open with what it holds (`resumeSleepingSession`): a way that starts nothing ends it here,
5133
+ // its prompts dropped; a fresh start takes it over and its replay writes them into the fresh session.
4970
5134
  if (failureAction === 'reportUnavailable') {
5135
+ startupPromptBuffer.discardPrompts((0, sessionKey_1.keyToString)(key));
4971
5136
  return { ok: false, reason: 'start-failed', message: (0, i18n_1.t)('agent.serverUnavailableNotice', { label: (0, createAdapter_1.getThreadAdapter)(key).label }) };
4972
5137
  }
4973
5138
  if (failureAction === 'fail') {
5139
+ startupPromptBuffer.discardPrompts((0, sessionKey_1.keyToString)(key));
4974
5140
  return { ok: false, reason: 'resume-failed', message: (0, i18n_1.t)('agent.resume_failed_fresh') };
4975
5141
  }
4976
5142
  // The previous conversation is lost to this topic: say so in one line, then start fresh. A fresh start that
4977
- // fails too says only why: "a fresh session was started" would be false.
5143
+ // fails too says only why: "a fresh session was started" would be false. The fresh start writes the people's prompts the resume
5144
+ // held; what the bot made for the lost conversation is dropped, for its caller to post again its own way.
5145
+ startupPromptBuffer.discardBotPrompts((0, sessionKey_1.keyToString)(key));
4978
5146
  const startMessage = await startAgentSession(key, options.args);
4979
5147
  if (!(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key))
4980
5148
  return { ok: false, reason: 'start-failed', message: startMessage };
@@ -5006,13 +5174,17 @@ function getResumableSessionId(key) {
5006
5174
  * @description Resume a sleeping conversation SILENTLY (L-D4): no "started" notice,
5007
5175
  * no recap — the next prompt simply continues it. Opens the startup window first so
5008
5176
  * a message typed meanwhile is buffered and replayed, like a fresh start. The
5009
- * conversation keeps its compaction latch, its thread-context marker and its
5177
+ * conversation keeps its compaction bookkeeping, its thread-context marker and its
5010
5178
  * start time: nothing about it changed, only the process is back. Resolves
5011
5179
  * `null` once resumed, else how it failed — the backend refused the id or the
5012
5180
  * process did not come up, or the backend's server could not be brought up; the
5013
5181
  * caller decides what follows ({@link getResumeFailureAction}).
5182
+ *
5183
+ * A failed resume leaves its window OPEN, with every prompt it holds: the caller ends it — a fresh start that follows takes it over
5184
+ * (its replay writes them into the fresh session), and a way that starts nothing discards them. Settled `dropped` here, they were lost
5185
+ * although a fresh session came up a moment later (review 19 #1).
5014
5186
  */
5015
- async function resumeSleepingSession(key, sessionId) {
5187
+ async function resumeSleepingSession(key, sessionId, resumeOptions = {}) {
5016
5188
  const kStr = (0, sessionKey_1.keyToString)(key);
5017
5189
  const workDirDecision = getWorkDirStartDecision(key);
5018
5190
  if (!workDirDecision.ok)
@@ -5023,29 +5195,38 @@ async function resumeSleepingSession(key, sessionId) {
5023
5195
  try {
5024
5196
  // A conversation the bot saw take a turn whose transcript is now missing is lost, not new: the resume fails.
5025
5197
  const isConversationRecorded = (0, ensureSessionPlan_1.checkIsConversationRecorded)(state.getAgent(key)?.seenWatermark, sessionId);
5026
- await adapter.resumeSession(key, workDirDecision.workDir, sessionId, { isConversationRecorded });
5198
+ await adapter.resumeSession(key, workDirDecision.workDir, sessionId, { ...resumeOptions, isConversationRecorded });
5027
5199
  await persistSessionStart(key, adapter);
5200
+ // A resume that did not come up takes nothing: the window stays for the caller's fresh start, or its discard.
5201
+ if (!adapter.checkIsActive(key))
5202
+ return 'refused';
5028
5203
  console.log(`[ensure] resumed the sleeping session of ${kStr}`);
5029
5204
  void replayBufferedPrompts(key);
5030
- return adapter.checkIsActive(key) ? null : 'refused';
5205
+ return null;
5031
5206
  }
5032
5207
  catch (e) {
5033
5208
  console.warn(`[ensure] could not resume the sleeping session of ${kStr}:`, e instanceof Error ? e.message : e);
5034
- // A fresh start (if the caller takes one) re-opens its own window; otherwise the held prompts have nowhere to go.
5035
- startupPromptBuffer.discardPrompts(kStr);
5036
5209
  return e instanceof backendUnavailableError_1.AgentBackendUnavailableError ? 'backendUnavailable' : 'refused';
5037
5210
  }
5038
5211
  }
5039
5212
  /**
5040
5213
  * @description A command that needs a live agent (`/compact`, `/model`, `/effort`)
5041
- * on a topic whose session sleeps: wake it first. Returns the notice to post
5042
- * (only when the resume failed and a fresh session took its place), `''` when
5043
- * nothing was said, `null` when there was nothing to wake.
5044
- */
5045
- async function wakeSleepingSession(key) {
5046
- if ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) || getResumableSessionId(key) === null)
5047
- return null;
5048
- return (await ensureAgentSession(key)).message;
5214
+ * on a topic whose session sleeps, or is being stopped: wake it first, through the
5215
+ * conversation's queue. Returns the notice to post (only when the resume failed and
5216
+ * a fresh session took its place), `''` when nothing was said (a live session too),
5217
+ * `null` when there is no conversation to wake.
5218
+ */
5219
+ function wakeSleepingSession(key) {
5220
+ // Through the queue even when the process still looks live: a stop under way (the seconds after every per-turn answer) is waited for
5221
+ // and the conversation resumed after it, so the pick that follows applies to the resumed process; a live one is `ready` at once
5222
+ // (review 23 nit 3). Whether there is a conversation to wake is read INSIDE the queue: a release queued ahead (`/quitall` from General)
5223
+ // leaves none, and a fresh agent is not started for the pick; a move hands the topic over first, and the caller reads the adapter
5224
+ // after this (review 24 nit 2). A resume that fails still starts fresh, as any ensure's does.
5225
+ return sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
5226
+ if (getResumableSessionId(key) === null)
5227
+ return null;
5228
+ return (await ensureAgentSessionNow(key, {})).message;
5229
+ });
5049
5230
  }
5050
5231
  /**
5051
5232
  * @description The idle stop (lifecycle plan L3): stop the topic's process, the
@@ -5053,7 +5234,11 @@ async function wakeSleepingSession(key) {
5053
5234
  * The startup window is held open while the process stops, so a prompt arriving
5054
5235
  * meanwhile is buffered instead of written to a dying process; once the process
5055
5236
  * is gone the window closes WITHOUT dropping those prompts, and if any wait the
5056
- * session is resumed for them at once (its own window replays them). The
5237
+ * session is resumed for them at once (its own window replays them) — also when
5238
+ * the stop threw, so a held prompt never waits in a closed buffer. A conversation
5239
+ * a command queued behind it ends or replaces (every release, `/new`, the `/resume` pick,
5240
+ * a move or a start onto another backend: held from the moment the bot knows the command
5241
+ * ends it until its own transition begins) starts nothing for them: they are dropped (a person is told). The
5057
5242
  * "working" check is repeated inside the transition: a turn may have started
5058
5243
  * while the fire waited its turn in the queue.
5059
5244
  */
@@ -5072,32 +5257,72 @@ async function suspendThreadSession(key) {
5072
5257
  return;
5073
5258
  }
5074
5259
  autoStopUnsupportedLoggedKeys.delete(kStr);
5075
- await sessionTransitions.run(kStr, async () => {
5076
- // Decide on what the process wrote up to now, not on the last tail poll: a background task's turn may have just begun.
5077
- adapter.refreshWorkingState?.(key);
5078
- if (!adapter.checkIsActive(key) || adapter.checkIsWorking?.(key))
5079
- return;
5080
- startupPromptBuffer.markStarting(kStr);
5081
- console.log(`[compact-on-idle] ${kStr} stopping the idle process; a prompt that comes meanwhile is held`);
5082
- try {
5083
- await adapter.suspendSession(key);
5084
- console.log(`[compact-on-idle] ${kStr} process stopped; the session sleeps and resumes on the next message`);
5085
- }
5086
- finally {
5087
- startupPromptBuffer.closeWindow(kStr);
5088
- }
5089
- });
5090
- // A sleeping per-turn session with a compaction due gets its idle timer from the persisted stamps (L-D7).
5091
- rearmThreadIdleTimer(key);
5092
- if (startupPromptBuffer.checkHasPrompts(kStr))
5093
- await ensureAgentSession(key);
5260
+ try {
5261
+ await sessionTransitions.run(kStr, async () => {
5262
+ // A json-stream re-spawn under way or about to start (a model, effort or account change) is over first, as for every transition
5263
+ // in the queue: a stop beside it would terminate the process it replaces, and the prompts it held would be left in a closed
5264
+ // buffer (review 22 #1 b). The stop then reads the re-spawned process.
5265
+ await waitForPendingRespawn(key);
5266
+ // Decide on what the process wrote up to now, not on the last tail poll: a background task's turn may have just begun.
5267
+ adapter.refreshWorkingState?.(key);
5268
+ if (!adapter.checkIsActive(key) || adapter.checkIsWorking?.(key))
5269
+ return;
5270
+ startupPromptBuffer.markStarting(kStr);
5271
+ console.log(`[compact-on-idle] ${kStr} stopping the idle process; a prompt that comes meanwhile is held`);
5272
+ try {
5273
+ await adapter.suspendSession(key);
5274
+ console.log(`[compact-on-idle] ${kStr} process stopped; the session sleeps and resumes on the next message`);
5275
+ }
5276
+ finally {
5277
+ startupPromptBuffer.closeWindow(kStr);
5278
+ // Still the stop's transition, also when the stop threw: a start or resume a command makes (`/new`, …) waits for it in the
5279
+ // queue, so the prompts the stop held go to the conversation they were written in (review 20 nit 3).
5280
+ await resumeForHeldPrompts(key);
5281
+ }
5282
+ });
5283
+ }
5284
+ finally {
5285
+ // A sleeping per-turn session with a compaction due gets its idle timer from the persisted stamps (L-D7).
5286
+ rearmThreadIdleTimer(key);
5287
+ }
5288
+ }
5289
+ /**
5290
+ * @description After an idle stop, whatever its end, inside the stop's own transition: the prompts its window held go to the
5291
+ * conversation resumed for them (`ensureAgentSessionNow`: the queued ensure would wait for this very transition). A conversation a
5292
+ * command queued behind the stop ends or replaces — a release, `/new`, a `/resume` pick, a move or a start onto another backend:
5293
+ * {@link conversationEndings} — must not be resumed only to be killed by that command: they are dropped, a person told to send
5294
+ * theirs again, and nothing starts (review 23 #1). A conversation with no id left (its topic deleted) is the same drop, as a guard. A
5295
+ * conversation that is already live when the ensure returns (it found it `ready`) gets them replayed into it; one the ensure could not
5296
+ * bring up without discarding them has them dropped — no way out of a stop leaves them in a closed buffer.
5297
+ */
5298
+ async function resumeForHeldPrompts(key) {
5299
+ const kStr = (0, sessionKey_1.keyToString)(key);
5300
+ if (!startupPromptBuffer.checkHasPrompts(kStr))
5301
+ return;
5302
+ if (conversationEndings.checkIsEnding(kStr) || getResumableSessionId(key) === null) {
5303
+ console.log(`[compact-on-idle] ${kStr}: a command ends the conversation (or it has no id left); the prompts the stop held are dropped`);
5304
+ startupPromptBuffer.discardPrompts(kStr);
5305
+ return;
5306
+ }
5307
+ const ensured = await ensureAgentSessionNow(key, {});
5308
+ // A resume (or the fresh start after a failed one) took them over; nothing is left to do.
5309
+ if (!startupPromptBuffer.checkHasPrompts(kStr) || startupPromptBuffer.checkIsStarting(kStr))
5310
+ return;
5311
+ // The ensure found the conversation already live (`ready`) and replayed nothing: they are written into it here (review 22 #1 c). Not
5312
+ // awaited, as a resume's replay: a write on the adopted-session path may wake the conversation, and that ensure queues behind this very
5313
+ // transition.
5314
+ if (ensured.ok)
5315
+ void replayBufferedPrompts(key);
5316
+ // The ensure failed without discarding them (an unbound or deleted topic, no adapter): dropped, a person told (review 23 nit 6).
5317
+ else
5318
+ startupPromptBuffer.discardPrompts(kStr);
5094
5319
  }
5095
5320
  /** Conversations already told once that their CLI is too old for the auto-stop (L-D10). */
5096
5321
  const autoStopUnsupportedLoggedKeys = new Set();
5097
5322
  /**
5098
5323
  * @description `turnEnded` from a json-stream adapter. The idle countdown runs from
5099
5324
  * the end of the last turn: an idle fire that found the turn still running is not
5100
- * rescheduled (D2), and a turn whose answer went out through `answer_request`
5325
+ * rescheduled (the turn's own end re-arms it), and a turn whose answer went out through `answer_request`
5101
5326
  * produces no later output to re-arm it — the process would never reach its idle
5102
5327
  * compaction and stop, and its pending-work hold would never be enforced. (A
5103
5328
  * bot-issued compaction's own turn end is skipped by the arming's loop guard.)
@@ -5111,17 +5336,48 @@ const autoStopUnsupportedLoggedKeys = new Set();
5111
5336
  * `postToSession` that polled the session idle and ensures it again (`postToSession.ts`) therefore always finds
5112
5337
  * the stop already on the transition queue and runs after it. Keep it that way — an await ahead of the queueing
5113
5338
  * would let that ensure run beside the stop and forward to the process it ends.
5114
- */
5115
- function handleAgentTurnEnded(key) {
5339
+ *
5340
+ * It is also where the next turn's boundary is marked when a prompt was forwarded before this turn ended
5341
+ * (`checkShouldMarkNewMessageAfterTurnEnd`): the adapter emits the turn's closing text synchronously BEFORE this event,
5342
+ * and the group transport queues it in the same tick, so the mark set here is the one the next turn's first text takes.
5343
+ */
5344
+ function handleAgentTurnEnded(key, turnEnd) {
5345
+ // No tool call of this turn is left to take a mid-turn accounts note: withdrawn unseen, it stays due.
5346
+ withdrawAccountsInbox(key);
5347
+ getLimitNotes().noteTurnEnd(key);
5116
5348
  noteThreadActivity(key);
5349
+ // Started here, before the per-turn stop below is queued: the process is read while it is still the session's.
5350
+ noteThreadTurnContext(key);
5117
5351
  topicIndicator.requestRefresh(key);
5118
5352
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
5119
- if (adapter.name !== adapterNames_1.claudePerTurnAdapterName)
5120
- return;
5121
- if (checkIsDeferredCompactionArmed(key) || adapter.checkIsWorking?.(key))
5353
+ // The boundary of the next turn, reported by the adapter: the turn's closing text was queued before this event (the adapter emits it first,
5354
+ // in the same tick), so a mark the forward of the next prompt set earlier is spent by now. Input still on its way is that turn's — after a
5355
+ // turn that ended in an error too.
5356
+ if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) && (0, outputFlushPlan_1.checkShouldMarkNewMessageAfterTurnEnd)({ outputsDeltas: adapter.outputsDeltas === true, hasInputOnItsWay: turnEnd.hasInputOnItsWay }))
5357
+ markNeedsNewMessage(key);
5358
+ if (adapter.name === adapterNames_1.claudePerTurnAdapterName && !checkIsDeferredCompactionArmed(key) && !adapter.checkIsWorking?.(key)) {
5359
+ void suspendThreadSession(key).catch((e) => console.warn(`[lifecycle] the per-turn stop of ${(0, sessionKey_1.keyToString)(key)} failed:`, e instanceof Error ? e.message : e));
5360
+ }
5361
+ // The turn's end is decided at the adapter's own turn-end event (json-stream Claude, both lifecycles) — after the per-turn stop is
5362
+ // queued: its window opens only in a later tick, and once it is over the session is gone, which a watch reads as «tracking lost», never
5363
+ // as an end. A reminder this decides is handed to a post waiting for this turn, which writes its own prompt first; with none waiting it
5364
+ // resumes the session through the ensure, which queues behind the stop (`requests/README.md` § Turn starts).
5365
+ settleEndedTurnsAndHandOver(key);
5366
+ }
5367
+ /**
5368
+ * @description Settle `key`'s watches whose turn already ended (`RequestWakeUpEngine.settleEndedTurnsOf`, synchronous up to the
5369
+ * decisions) and hand the reminders they decided, once persisted, to a post on its way to its write (`deliverOrHandOverWake`), else
5370
+ * deliver them at once — at the adapter's turn end ({@link handleAgentTurnEnded}) and at the write choke point, whose write runs in
5371
+ * this tick, so a reminder follows that write, and a post that waited writes its prompt first. Never rejects.
5372
+ */
5373
+ function settleEndedTurnsAndHandOver(key) {
5374
+ const engine = requestWakeUpEngine;
5375
+ if (!engine)
5122
5376
  return;
5123
- void suspendThreadSession(key).catch((e) => console.warn(`[lifecycle] the per-turn stop of ${(0, sessionKey_1.keyToString)(key)} failed:`, e instanceof Error ? e.message : e));
5377
+ void engine.settleEndedTurnsOf(key).then((deliverSettledWakes) => engine.deliverOrHandOverWake(key, deliverSettledWakes));
5124
5378
  }
5379
+ /** No reminder to deliver: what a settle resolves, and what a post's release is, while the wake-up engine is not up yet. */
5380
+ const deliverNoSettledWakes = async () => { };
5125
5381
  /**
5126
5382
  * @description A prompt (text, voice, file, a re-asked question's answer) arrives
5127
5383
  * in a topic whose conversation sleeps: resume it so the prompt continues it.
@@ -5133,11 +5389,23 @@ function handleAgentTurnEnded(key) {
5133
5389
  async function resumeSleepingSessionForPrompt(key, sendNotice = (text) => replyToThread(key, text)) {
5134
5390
  return (await wakeSleepingSessionForPrompt(key, sendNotice)).isAwake;
5135
5391
  }
5136
- /** @description {@link resumeSleepingSessionForPrompt}, also saying whether it posted a notice (a start that failed says why). */
5392
+ /**
5393
+ * @description {@link resumeSleepingSessionForPrompt}, also saying whether it posted a notice (a start that failed says why). Whether there
5394
+ * is a conversation to wake is read again INSIDE the conversation's queue, as the wake of `/model`, `/effort` and `/compact` does: a release
5395
+ * queued ahead (`/quitall` from General, a `/quit` that a voice note's transcript waited behind) clears the ids, and the wake then starts
5396
+ * nothing — `isEnded`, which a person's prompt is told as the release's refusal — instead of a fresh conversation the operator just quit
5397
+ * (review 25 #2). A resume that fails still starts fresh, as any ensure's does.
5398
+ */
5137
5399
  async function wakeSleepingSessionForPrompt(key, sendNotice = (text) => replyToThread(key, text)) {
5138
5400
  if (checkIsGeneral(key) || !state.getBinding(key) || getResumableSessionId(key) === null)
5139
5401
  return { isAwake: false, isNoticePosted: false };
5140
- const ensured = await ensureAgentSession(key);
5402
+ const ensured = await sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
5403
+ if (!state.getBinding(key) || getResumableSessionId(key) === null)
5404
+ return null;
5405
+ return ensureAgentSessionNow(key, {});
5406
+ });
5407
+ if (ensured === null)
5408
+ return { isAwake: false, isNoticePosted: false, isEnded: true };
5141
5409
  if (ensured.message)
5142
5410
  await sendNotice(ensured.message);
5143
5411
  return { isAwake: ensured.ok && (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key), isNoticePosted: Boolean(ensured.message) };
@@ -5148,29 +5416,50 @@ async function wakeSleepingSessionForPrompt(key, sendNotice = (text) => replyToT
5148
5416
  * routine as a live message (new-message marker + loader + `sendInput`).
5149
5417
  */
5150
5418
  async function replayBufferedPrompts(key) {
5419
+ // A command that ends or replaces the conversation (a release, `/new`, a `/resume` pick, a move or a start onto another backend) waits
5420
+ // behind the start or resume replaying this window: what the window holds was not sent for the conversation the command ends, so it is
5421
+ // dropped — a person told to send it again — not written there (review 22 nit 3, review 23 #1).
5422
+ if (conversationEndings.checkIsEnding((0, sessionKey_1.keyToString)(key))) {
5423
+ console.log(`[startup] ${(0, sessionKey_1.keyToString)(key)}: a command ends the conversation; the prompts its window held are dropped`);
5424
+ startupPromptBuffer.discardPrompts((0, sessionKey_1.keyToString)(key));
5425
+ return;
5426
+ }
5151
5427
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
5152
5428
  const isSessionActive = adapter.checkIsActive(key);
5153
5429
  // The buffer closes the window synchronously and settles every prompt it held (a sender waiting on one,
5154
5430
  // like the API-error retry's nudge, hears whether it reached the session).
5431
+ // The whole replay — the buffered prompts and the held ones after them — is still the start for the wake-up engine's turn probe
5432
+ // (`StartupPromptBuffer.checkIsReplaying`): no watch made during the start is read as a turn that ended (`requests/README.md` § Turn starts).
5155
5433
  await startupPromptBuffer.replayPrompts((0, sessionKey_1.keyToString)(key), {
5156
5434
  isSessionActive,
5157
- forward: async (prompt, isPersonInput) => { await forwardPromptToAgent(key, adapter, prompt, undefined, { isPersonInput }); },
5435
+ forward: async (prompt, options) => {
5436
+ const outcome = await forwardPromptToAgent(key, adapter, prompt, undefined, options);
5437
+ // A guard: the replay writes into the process the start brought up, never an adopted one, so no wake can come up empty here. If
5438
+ // one did, the buffer settles the prompt `dropped` — never «replayed» for a prompt no agent got (review 21, own pass).
5439
+ if (outcome === 'noSession')
5440
+ throw new Error(noSessionForPostError);
5441
+ },
5442
+ afterReplay: async () => {
5443
+ // A command that ends or replaces the conversation runs (a move's own start among them): the held prompts wait for the first
5444
+ // prompt it hands over — a replayable one, which carries them after its own text (R23) — instead of reaching the new agent ahead of
5445
+ // the move's bridge; with none, the next prompt carries them (review 26 #5).
5446
+ if (conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key)))
5447
+ return;
5448
+ // R23: prompts held during a usage-limit wait that ended with the previous
5449
+ // session go to this one — on their own when nothing above carried them. They
5450
+ // are what people asked for meanwhile: a write that fails is told in the topic
5451
+ // like a person's own message, never only logged.
5452
+ const heldText = limitHeldPrompts.releaseAll(key);
5453
+ if (heldText === null)
5454
+ return;
5455
+ try {
5456
+ await forwardPromptToAgent(key, adapter, heldText, undefined, { isPersonInput: true });
5457
+ }
5458
+ catch (err) {
5459
+ console.error('[replayBufferedPrompts] forwarding the held prompts failed:', err);
5460
+ }
5461
+ },
5158
5462
  });
5159
- if (!isSessionActive)
5160
- return;
5161
- // R23: prompts held during a usage-limit wait that ended with the previous
5162
- // session go to this one — on their own when nothing above carried them. They
5163
- // are what people asked for meanwhile: a write that fails is told in the topic
5164
- // like a person's own message, never only logged.
5165
- const heldText = limitHeldPrompts.releaseAll(key);
5166
- if (heldText === null)
5167
- return;
5168
- try {
5169
- await forwardPromptToAgent(key, adapter, heldText, undefined, { isPersonInput: true });
5170
- }
5171
- catch (err) {
5172
- console.error('[replayBufferedPrompts] forwarding the held prompts failed:', err);
5173
- }
5174
5463
  }
5175
5464
  /**
5176
5465
  * @description Forward one user prompt to a live agent: mark the thread for a
@@ -5213,16 +5502,33 @@ async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {})
5213
5502
  // A technical prompt (the standalone todo reminder) goes only into a session that is live and idle now, and is otherwise
5214
5503
  // dropped without a word: never buffered, never a resume, never a "no session" line to the person.
5215
5504
  const isTechnicalPrompt = options.isTechnicalPrompt === true;
5505
+ const isPersonInput = options.isPersonInput === true;
5216
5506
  const outcome = await (0, promptDelivery_1.deliverLatePrompt)({
5217
5507
  isTechnical: isTechnicalPrompt,
5508
+ // A post waits again here, after the replay wait: a move may have begun during it (review 28 nit 2).
5509
+ waitBeforeRoute: options.waitBeforeRoute,
5218
5510
  checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
5219
- checkIsSessionActive: () => adapter.checkIsActive(key) && !(isTechnicalPrompt && (adapter.checkIsBusy?.(key) ?? false)),
5511
+ // Whether the process takes input, as every routing point reads it: one a release or a move is stopping takes nothing (review 25
5512
+ // nit 7). A technical prompt goes only into an idle one.
5513
+ checkIsSessionActive: () => checkIsAcceptingInput(key) && !(isTechnicalPrompt && (adapter.checkIsBusy?.(key) ?? false)),
5514
+ // A person's prompt is refused while a command ends or replaces the conversation, as at its own write (review 25 #1).
5515
+ ...(isPersonInput ? {
5516
+ checkIsRefused: () => checkIsPersonPromptRefused(key, options.requestId ?? null),
5517
+ reportRefused: () => reportDroppedPersonPrompt(key, options.requestId ?? null, true),
5518
+ } : {}),
5220
5519
  buffer: async () => {
5520
+ const bufferedText = `${options.requestHeader ?? ''}${getPromptWithThreadMessageContext(key, text, options.messageContext)}`;
5521
+ // A post's wait is for this delivery's own routing; the startup buffer keeps none for the replay (`deliverPromptOrBuffer`).
5522
+ const bufferedOptions = { isPersonInput: options.isPersonInput, isAccountsNoteCarrier: options.isAccountsNoteCarrier, lostWorkTelling: options.lostWorkTelling, waitBeforeRoute: options.waitBeforeRoute };
5523
+ // A person's prompt that is dropped there is told about and closes its request, as at the person's own buffer.
5524
+ if (isPersonInput) {
5525
+ await deliverPromptOrBuffer(key, bufferedText, createPersonBufferedSettle(key, options.requestId ?? null), bufferedOptions);
5526
+ return;
5527
+ }
5221
5528
  // A bot-made prompt (a wake-up) that waits here counts only once its replay reached the agent, as at any other buffer.
5222
5529
  const buffered = createBufferedOutcome();
5223
- await deliverPromptOrBuffer(key, `${options.requestHeader ?? ''}${getPromptWithThreadMessageContext(key, text, options.messageContext)}`, true, buffered.settle, { isPersonInput: options.isPersonInput });
5224
- if (options.isPersonInput !== true)
5225
- await buffered.assertReplayed();
5530
+ await deliverPromptOrBuffer(key, bufferedText, buffered.settle, bufferedOptions);
5531
+ await buffered.assertReplayed();
5226
5532
  },
5227
5533
  wake: () => wakeSleepingSessionForPrompt(key),
5228
5534
  forward: async () => {
@@ -5241,6 +5547,18 @@ async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {})
5241
5547
  }
5242
5548
  /** @description The forward itself, for a session that is ready to take the prompt: {@link forwardPromptToAgent} minus the replay wait. */
5243
5549
  async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options = {}) {
5550
+ // A new prompt starts or joins a turn: the watches whose turn already ENDED are settled first, synchronously and before the write
5551
+ // (no await may precede it), so the new turn never runs under the watch of the turn before it (`requests/README.md` § Turn starts).
5552
+ // Their reminders are delivered once persisted — after this write, which runs in this tick, or, while a post is on its way to its
5553
+ // write, after that post's prompt (the todo reminder written at a turn end is such a write).
5554
+ settleEndedTurnsAndHandOver(key);
5555
+ // Any write during the replay of a start's buffer — a replayed prompt, the held prompts after them, a prompt written at once while it
5556
+ // runs — goes to the process the replay writes the buffer into (`noteReplayedWrite`); no write outside a replay names anything.
5557
+ if (startupPromptBuffer.checkIsReplaying((0, sessionKey_1.keyToString)(key)))
5558
+ requestWakeUpEngine?.noteReplayedWrite(key);
5559
+ // Every write stamps the process it goes to, so a watch tracked once that process went down (a re-spawn right after a post's write)
5560
+ // is named from the write (review 22 nit 2).
5561
+ requestWakeUpEngine?.noteWrite(key);
5244
5562
  // A forwarded prompt is thread activity — reset the compact-on-idle watchdog (F2).
5245
5563
  noteThreadActivity(key);
5246
5564
  const isTechnicalPrompt = options.isTechnicalPrompt ?? false;
@@ -5281,7 +5599,9 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5281
5599
  // request's reminder included: the wake of a tracker request whose process a restart left behind is how its agent hears.
5282
5600
  const isLostWorkNoteCarried = (isReplayable || options.isRequestReminder === true) && adapter.name !== 'terminal';
5283
5601
  const lostWorkRecord = isLostWorkNoteCarried ? state.getLostWork(key) : undefined;
5284
- const body = lostWorkRecord ? `${(0, lostWork_1.buildLostWorkNote)(lostWorkRecord, (0, i18n_1.getLocaleEndonym)((0, i18n_1.getActiveLang)()))}\n\n${messageBody}` : messageBody;
5602
+ const body = lostWorkRecord
5603
+ ? `${(0, lostWork_1.buildLostWorkNote)(lostWorkRecord, (0, i18n_1.getLocaleEndonym)((0, i18n_1.getActiveLang)()), { telling: options.lostWorkTelling ?? 'plain' })}\n\n${messageBody}`
5604
+ : messageBody;
5285
5605
  // Cache the (reply-folded) prompt so a wedged OpenCode session can be recovered
5286
5606
  // by restarting fresh and replaying it — replaying WITH the quote is correct.
5287
5607
  // A genuine new prompt also opens a fresh recovery episode (clears the guard).
@@ -5311,6 +5631,8 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5311
5631
  // then the todo list's staleness reminder rides the next real prompt from any source (D11 form a) — never a slash
5312
5632
  // command or a shell line; the reminder never rides the standalone reminder itself.
5313
5633
  const isTodoDecorated = !isSlashCommand && adapter.name !== 'terminal';
5634
+ // Any forward is a turn start (a slash command too: `/compact` opens a held turn): the accounts note's mid-turn section goes.
5635
+ withdrawAccountsInbox(key);
5314
5636
  if (isTodoDecorated)
5315
5637
  discardTodoInbox(key);
5316
5638
  const todoBoardBlock = isTodoDecorated ? takeTodoPromptBoard(key) : null;
@@ -5319,6 +5641,14 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5319
5641
  const todoReminderLine = isTodoDecorated && !isTechnicalPrompt ? takeTodoPromptReminder(key) : null;
5320
5642
  if (todoReminderLine !== null)
5321
5643
  promptText = `${promptText}\n\n${todoReminderLine}`;
5644
+ // The accounts note (`limitNotes/`) is the LAST block of a carrier prompt — a turn the person or the scheduler starts — inside the
5645
+ // ONE text written to the agent: never a write of its own, never an activity stamp (`limitNotes/README.md` § Lifecycle safety).
5646
+ // Told only once the prompt that carries it reached a live session, like the lost-work note below.
5647
+ const accountsNote = (0, service_1.checkIsAccountsNoteCarried)({ isCarrier: options.isAccountsNoteCarrier, isSlashCommand, adapterName: adapter.name })
5648
+ ? getLimitNotes().takeTurnStartNote(key, (0, service_1.getAccountsNoteQuietMs)({ lastTurnEndAt: state.getCompactIdleTracking(key).lastTurnEndAt, isBusy: adapter.checkIsBusy?.(key), nowMs: Date.now() }))
5649
+ : null;
5650
+ if (accountsNote !== null)
5651
+ promptText = (0, noteText_1.appendLimitNote)(promptText, accountsNote.text);
5322
5652
  markNeedsNewMessage(key);
5323
5653
  // A new prompt is a new turn: lift the S2 idle-suppress latch and re-base the
5324
5654
  // working-status elapsed so the next busy period shows a fresh 0:00 counter
@@ -5348,6 +5678,11 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5348
5678
  // A backend that can tell whether the prompt reached the agent (the json-stream host's stdin write) is asked to: a
5349
5679
  // write that failed rejects this forward, so its caller — a tracker post, a wake-up — knows the prompt never arrived
5350
5680
  // and retries, instead of believing it delivered. The input is handed over synchronously either way; only its outcome is awaited.
5681
+ // The turn this prompt opens on an idle session is a BOOKKEEPING turn unless a person, a tracker or the scheduler started it (a slash
5682
+ // command is neither: a skill's turn does real work, a compaction's is held open anyway): the mid-turn engine gives such a turn no
5683
+ // reminder, as its start carried none. Read after the interrupt above, so a person's prompt that ended a bookkeeping turn is judged
5684
+ // on its own.
5685
+ getLimitNotes().noteTurnStart(key, { isBookkeeping: options.isAccountsNoteCarrier !== true && !isSlashCommand, isSessionIdle: adapter.checkIsBusy?.(key) === false });
5351
5686
  const written = adapter.sendInputAndWait ? adapter.sendInputAndWait(key, promptText) : (adapter.sendInput(key, promptText), Promise.resolve());
5352
5687
  // S2 busy-onset arm: start the Claude liveness loop the moment the prompt is
5353
5688
  // forwarded — driven by `checkIsBusy`, not by waiting for an opportunistic
@@ -5361,7 +5696,17 @@ async function forwardPromptToLiveAgent(key, adapter, text, sentAtMs, options =
5361
5696
  const noteToldIfDelivered = () => {
5362
5697
  if (lostWorkRecord && adapter.checkIsActive(key))
5363
5698
  void state.clearLostWork(key);
5699
+ // The note is in flight until here: recorded when the session got the prompt, given back when it was gone.
5700
+ if (accountsNote !== null) {
5701
+ if (adapter.checkIsActive(key))
5702
+ accountsNote.markDelivered();
5703
+ else
5704
+ accountsNote.release();
5705
+ }
5364
5706
  };
5707
+ // A write that failed gives the note back too: the next carrier prompt carries it (the failure itself is handled below, as ever).
5708
+ if (accountsNote !== null)
5709
+ void written.catch(() => accountsNote.release());
5365
5710
  // A person's own message never holds the topic's update queue on its write — a CLI that stops reading its input would
5366
5711
  // keep `/esc` and every tap behind it for minutes —: they are told when it failed. Every other prompt (a tracker's post,
5367
5712
  // a wake-up, a scheduled run, a retry's nudge, the todo reminder) awaits it: one that never arrived is retried.
@@ -5485,10 +5830,6 @@ function getPromptWithThreadMessageContext(key, text, messageContext) {
5485
5830
  });
5486
5831
  }
5487
5832
  // ═══════════════════════════════════════════════════════════════════════════════
5488
- // Natural-language start phrases (`claude ...`, `opencode ...`)
5489
- // ═══════════════════════════════════════════════════════════════════════════════
5490
- // (Parser imported up-top — see `parseAgentTrigger` import.)
5491
- // ═══════════════════════════════════════════════════════════════════════════════
5492
5833
  // Model selection helper — used by /model and the numeric-reply flow
5493
5834
  // ═══════════════════════════════════════════════════════════════════════════════
5494
5835
  function formatTimeAgo(date) {
@@ -5567,7 +5908,7 @@ const botCore = {
5567
5908
  cancelConversationRequest,
5568
5909
  wakeSleepingSession,
5569
5910
  };
5570
- const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, markThreadTurnProducedOutput, postOwnCompactionInstructionGaps, routeStreamedCompactionSummaryTail, clearThreadCompaction, rearmThreadIdleTimer, armDeferredCompaction, checkIsDeferredCompactionArmed, threadsCompacting, answerReAskedQuestionByNumber, reAskInterruptedQuestion, restoreReAskedQuestion, closeSavedReAskedQuestion, closeReAskedQuestion, syncThreadCompactSelfReviewFlags, syncAllCompactSelfReviewFlags, registerCompactionCommands, registerCompactionCallbacks, } = (0, compaction_1.createCompaction)({
5911
+ const { checkIsThreadCompacting, noteThreadActivity, noteThreadTurnContext, markThreadTurnProducedOutput, postOwnCompactionInstructionGaps, routeStreamedCompactionSummaryTail, clearThreadCompaction, rearmThreadIdleTimer, armDeferredCompaction, checkIsDeferredCompactionArmed, threadsCompacting, answerReAskedQuestionByNumber, reAskInterruptedQuestion, restoreReAskedQuestion, closeSavedReAskedQuestion, closeReAskedQuestion, syncThreadCompactSelfReviewFlags, syncAllCompactSelfReviewFlags, registerCompactionCommands, registerCompactionCallbacks, } = (0, compaction_1.createCompaction)({
5571
5912
  ...botCore,
5572
5913
  startTypingLoader,
5573
5914
  forwardPromptToAgent: async (key, adapter, text) => { await forwardPromptToAgent(key, adapter, text); },
@@ -5581,6 +5922,7 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
5581
5922
  suspendThreadSession,
5582
5923
  // L-D7: a sleeping per-turn session is woken for its idle compaction — a resume only, never a fresh start.
5583
5924
  resumeSleepingSessionForCompaction: async (key) => (await ensureAgentSession(key, { isResumeOnly: true })).ok && (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key),
5925
+ readSleepingContext: readSleepingConversationContext,
5584
5926
  getThreadAdapter: createAdapter_1.getThreadAdapter,
5585
5927
  // An answer to the agent's own question is never a request (S7), even delivered as a prompt.
5586
5928
  // The label of a re-asked question reaches the agent as a prompt; a topic member's carries their mark, the operator's stays bare.
@@ -6090,43 +6432,35 @@ async function pauseThreadSchedulesOnUnbind(key) {
6090
6432
  }, key);
6091
6433
  }
6092
6434
  /**
6093
- * @description Resume the schedules paused for `'unbound'` on `key` when its
6094
- * topic is rebound (S8): recompute each `nextRunAt` FROM NOW (no catch-up for a
6095
- * deliberate pause), then either un-pause + re-arm, or — for a one-shot whose
6096
- * instant already passed while unbound — drop the record (a past one-shot has no
6097
- * future occurrence, so it cannot be resumed). Posts ONE notice with the resumed
6098
- * count (only when > 0). Jobs paused for other reasons (none exist in v1) are
6099
- * left alone.
6435
+ * @description The scheduler's ports for resuming a conversation's unbound-paused jobs (`scheduler/rebindResume.ts`);
6436
+ * `announceResumed` is the platform's way of saying so.
6437
+ */
6438
+ function createRebindResumePorts(announceResumed) {
6439
+ return {
6440
+ listThreadSchedules: (key) => state.getThreadSchedules(key),
6441
+ removeSchedule: (jobId) => state.removeSchedule(jobId),
6442
+ upsertSchedule: (record) => state.upsertSchedule(record),
6443
+ armJob: (record) => schedulerEngine?.armJob(record),
6444
+ disarmJob: (jobId) => schedulerEngine?.disarmJob(jobId),
6445
+ announceResumed,
6446
+ now: () => Date.now(),
6447
+ };
6448
+ }
6449
+ /**
6450
+ * @description Resume the schedules paused for `'unbound'` on `key` when its topic is rebound (S8), with ONE notice in the
6451
+ * topic carrying the resumed count (`scheduler/rebindResume.ts`).
6100
6452
  */
6101
6453
  async function resumeThreadSchedulesOnRebind(key) {
6102
- const paused = state
6103
- .getThreadSchedules(key)
6104
- .filter((record) => record.isPaused && record.pauseReason === 'unbound');
6105
- if (paused.length === 0)
6106
- return;
6107
- const nowMs = Date.now();
6108
- let resumed = 0;
6109
- for (const record of paused) {
6110
- const action = (0, rebindResume_1.getRebindResumeAction)(record, nowMs);
6111
- if (action.kind === 'remove') {
6112
- await state.removeSchedule(record.id);
6113
- schedulerEngine?.disarmJob(record.id);
6114
- continue;
6115
- }
6116
- const updated = {
6117
- ...record,
6118
- nextRunAt: action.nextRunAt,
6119
- updatedAt: new Date(nowMs).toISOString(),
6120
- };
6121
- delete updated.isPaused;
6122
- delete updated.pauseReason;
6123
- await state.upsertSchedule(updated);
6124
- schedulerEngine?.armJob(updated);
6125
- resumed += 1;
6126
- }
6127
- if (resumed > 0) {
6128
- await replyToThread(key, (0, i18n_1.t)('schedule.resumedRebind', { count: resumed }));
6129
- }
6454
+ await (0, rebindResume_1.resumeSchedulesPausedForUnbound)(createRebindResumePorts((count) => replyToThread(key, (0, i18n_1.t)('schedule.resumedRebind', { count })).then(() => undefined)), key);
6455
+ }
6456
+ /**
6457
+ * @description Resume the jobs a tracker conversation's fire paused for a folder it could not use, once a request of the issue
6458
+ * finds the folder usable again — what `/bind` does in a topic. The bot posts nothing on an issue: the resume is one log line.
6459
+ */
6460
+ async function resumeTrackerSchedulesOnRebind(key) {
6461
+ await (0, rebindResume_1.resumeSchedulesPausedForUnbound)(createRebindResumePorts(async (count) => {
6462
+ console.log(`[scheduler] ${count} job(s) of ${(0, sessionKey_1.keyToString)(key)} resumed: its folder is usable again`);
6463
+ }), key);
6130
6464
  }
6131
6465
  /**
6132
6466
  * @description Arm a thread's await-folder-name mode for the `/bind`
@@ -6287,16 +6621,21 @@ command('bind', async (_ctx, key, parsed) => {
6287
6621
  * pinned banner, release persisted session ids, pause the thread's schedules,
6288
6622
  * then wipe the binding. Shared by the `/bind` picker's «leave current dir»
6289
6623
  * button (the old `/unbind` command was folded into it). Safe to call only on a
6290
- * BOUND, non-General topic — the leave button only renders there.
6624
+ * BOUND, non-General topic — the leave button only renders there. `ending` is the
6625
+ * tap's hold on the conversation, taken ahead of its toast (review 24 #1).
6291
6626
  */
6292
- async function unbindThread(key) {
6627
+ async function unbindThread(key, ending) {
6293
6628
  // Mark this thread as in-flight unbinding so the adapter's synchronous
6294
6629
  // `stopped` event doesn't race us and re-pin a stale "idle" banner over
6295
6630
  // the message we're about to delete.
6296
6631
  const kStr = (0, sessionKey_1.keyToString)(key);
6297
6632
  unbindingKeys.add(kStr);
6298
- // Leaving the folder ends the conversation's work: its open request closes silently.
6299
- cancelConversationRequest(key);
6633
+ // Leaving the folder ends the conversation's work: its open requests close, a person whose words the agent never read told (review 26
6634
+ // #2) — read now, ahead of the stop.
6635
+ cancelEndingConversationRequests(key);
6636
+ // Refused until the binding is gone, past the hold's transition: a post that waited (`waitForConversationChange`) then meets an unbound
6637
+ // topic and pauses its job, instead of starting a fresh agent in the folder being left (review 27 nit 4).
6638
+ const stopRefusingMessages = conversationEndings.refuseMessages(key);
6300
6639
  try {
6301
6640
  // Order matters: drop the pin FIRST (while binding.pinnedStatusMessageId
6302
6641
  // is still readable), then stop the session, then wipe the binding.
@@ -6307,24 +6646,35 @@ async function unbindThread(key) {
6307
6646
  if (pendingQuestions.has(kStr))
6308
6647
  await retirePendingQuestion(key);
6309
6648
  // Stop any running session before discarding the binding so we don't leave
6310
- // an orphan tmux/SSE stream pointing at a directory we no longer track.
6311
- const adapter = (0, createAdapter_1.getThreadAdapter)(key);
6312
- if (adapter.checkIsActive(key)) {
6313
- // Close any still-pending OpenCode question on the server BEFORE stopping
6314
- // the session — a stopped session can't accept the reject, and an
6315
- // unrejected question re-surfaces on the next reattach. No-op for Claude /
6316
- // no pending question.
6317
- adapter.rejectQuestion?.(key);
6318
- try {
6319
- adapter.stopSession(key);
6320
- }
6321
- catch (e) {
6322
- console.warn(`[unbind] stopSession failed for ${kStr}:`, e);
6649
+ // an orphan tmux/SSE stream pointing at a directory we no longer track. As the
6650
+ // conversation's one transition, after a re-spawn: a start, a resume or a
6651
+ // re-spawn in flight is over first, so none brings a process back for the
6652
+ // conversation released here (review 22, own pass). Held as ending it since the
6653
+ // tap, ahead of the toast, the unpin and the question's retirement above: a stop
6654
+ // queued ahead drops what it held (review 23 #1, review 24 #1). The stop is waited
6655
+ // for, so nothing queued behind writes into a process still exiting (review 23 nit 4).
6656
+ await ending.run(async () => {
6657
+ const adapter = (0, createAdapter_1.getThreadAdapter)(key);
6658
+ if (adapter.checkIsActive(key)) {
6659
+ // Close any still-pending OpenCode question on the server BEFORE stopping
6660
+ // the session — a stopped session can't accept the reject, and an
6661
+ // unrejected question re-surfaces on the next reattach. No-op for Claude /
6662
+ // no pending question.
6663
+ adapter.rejectQuestion?.(key);
6664
+ try {
6665
+ if (adapter.stopSessionAndWait)
6666
+ await adapter.stopSessionAndWait(key);
6667
+ else
6668
+ adapter.stopSession(key);
6669
+ }
6670
+ catch (e) {
6671
+ console.warn(`[unbind] stopSession failed for ${kStr}:`, e);
6672
+ }
6323
6673
  }
6324
- }
6325
- // Release persisted session ids too — otherwise re-binding this thread
6326
- // later + a bot restart would resurrect the old session the user unbound.
6327
- await releaseConversationIds(key);
6674
+ // Release persisted session ids too — otherwise re-binding this thread
6675
+ // later + a bot restart would resurrect the old session the user unbound.
6676
+ await releaseConversationIds(key);
6677
+ });
6328
6678
  // Pause this thread's schedules BEFORE dropping the binding: a fire against
6329
6679
  // an unbound topic can't deliver, so the jobs park (paused + disarmed) and
6330
6680
  // the next /bind resumes them. `removeBinding` only touches bindings/agents/
@@ -6338,6 +6688,7 @@ async function unbindThread(key) {
6338
6688
  await replyToThread(key, (0, i18n_1.t)('thread.unbound'));
6339
6689
  }
6340
6690
  finally {
6691
+ stopRefusingMessages();
6341
6692
  unbindingKeys.delete(kStr);
6342
6693
  }
6343
6694
  }
@@ -6433,19 +6784,29 @@ command('new', async (_ctx, key) => {
6433
6784
  await replyToThread(key, (0, i18n_1.t)('thread.bind_required'));
6434
6785
  return;
6435
6786
  }
6436
- // A fresh session does not know the old one's request: it closes silently.
6437
- cancelConversationRequest(key);
6787
+ // A fresh session does not know the old one's requests: they close, a person whose words the agent never read told (review 26 #2).
6788
+ cancelEndingConversationRequests(key);
6438
6789
  // Release the current session (sweep + clear ids) via `releaseThreadSession`.
6439
6790
  // The fresh start below uses the thread's current adapter, so we keep the
6440
- // adapter selection untouched.
6441
- await releaseThreadSession(key);
6791
+ // adapter selection untouched. Both as the conversation's one transition: an idle stop under way ends first — dropping what it held,
6792
+ // the person told, since this command holds the conversation as ending (review 25 nit 6) —, and no ensure starts a second session beside
6793
+ // this one.
6442
6794
  // `startAgentSession` handles startup buffering, the typing-loader boot, and
6443
6795
  // the preamble-marker reset. It returns `''` for a self-greeting agent (Claude
6444
6796
  // prints its own banner) — show a notice only for a non-empty ready text.
6445
- const msg = await startAgentSession(key);
6797
+ // Held as ending the conversation while it waits: a stop under way drops what it held instead of resuming the old conversation (review
6798
+ // 21 nit 4); a person's message is refused until the fresh start is over (review 25 #1).
6799
+ const msg = await startFreshSessionForNew(key);
6446
6800
  if (msg)
6447
6801
  await replyToThread(key, msg);
6448
6802
  });
6803
+ /** `/new`'s release and fresh start, as the conversation's one transition, the conversation held as ending until that transition begins. */
6804
+ function startFreshSessionForNew(key) {
6805
+ return conversationEndings.hold(key).run(async () => {
6806
+ await releaseThreadSession(key);
6807
+ return startAgentSession(key);
6808
+ });
6809
+ }
6449
6810
  // ═══════════════════════════════════════════════════════════════════════════════
6450
6811
  // /whoami /version /help /status (global) — debug & onboarding
6451
6812
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -6714,7 +7075,7 @@ async function sendBindingWelcome(key, subdir, notes = {}) {
6714
7075
  if (welcomeMessageId !== null)
6715
7076
  openWelcomeMessages.remember((0, sessionKey_1.keyToString)(key), welcomeMessageId, Date.now());
6716
7077
  // Every bind ends in this welcome, so every bind sweeps here — after the welcome, and NOT waited for: what follows a bind
6717
- // (an agent start, when the first message was a start phrase) must not hang on the deletions and edits, which are paced sends.
7078
+ // (an agent start) must not hang on the deletions and edits, which are paced sends.
6718
7079
  void stripWelcomeKeyboards(key, outdatedWelcomeIds);
6719
7080
  void closeOpenBindMessages(key);
6720
7081
  }
@@ -6750,6 +7111,7 @@ async function runDoctor() {
6750
7111
  lines.push(nativeWindowsLine);
6751
7112
  // 1. Bot admin permissions in the configured group.
6752
7113
  const groupId = getAllowedGroupId();
7114
+ let isBotAdmin = false;
6753
7115
  if (groupId === null) {
6754
7116
  lines.push({ status: 'warn', label: (0, i18n_1.t)('doctor.bot_admin'), hint: (0, i18n_1.t)('pair.not_paired') });
6755
7117
  }
@@ -6758,6 +7120,7 @@ async function runDoctor() {
6758
7120
  const botId = bot.botInfo?.id ?? (await bot.telegram.getMe()).id;
6759
7121
  const member = await bot.telegram.getChatMember(groupId, botId);
6760
7122
  if (member.status === 'administrator') {
7123
+ isBotAdmin = true;
6761
7124
  lines.push({ status: 'ok', label: (0, i18n_1.t)('doctor.bot_admin') });
6762
7125
  lines.push({
6763
7126
  status: member.can_manage_topics ? 'ok' : 'fail',
@@ -6790,15 +7153,13 @@ async function runDoctor() {
6790
7153
  hint: (0, i18n_1.t)('doctor.no_admin_info'),
6791
7154
  });
6792
7155
  }
6793
- // 2. Privacy mode (heuristic — Bot API doesn't expose the flag directly,
6794
- // but `getMe().can_read_all_group_messages === false` indicates it's on).
7156
+ // 2. Privacy mode — only a non-admin bot depends on it (`getPrivacyDoctorLine`). The Bot API doesn't expose the mode itself,
7157
+ // but `getMe().can_read_all_group_messages === false` indicates it's on.
6795
7158
  try {
6796
7159
  const me = await bot.telegram.getMe();
6797
- lines.push({
6798
- status: me.can_read_all_group_messages ? 'ok' : 'fail',
6799
- label: (0, i18n_1.t)('doctor.privacy_off'),
6800
- hint: (0, i18n_1.t)('doctor.privacy_hint'),
6801
- });
7160
+ const privacyLine = (0, doctorLine_1.getPrivacyDoctorLine)({ isBotAdmin, canReadAllGroupMessages: me.can_read_all_group_messages }, i18n_1.t);
7161
+ if (privacyLine)
7162
+ lines.push(privacyLine);
6802
7163
  }
6803
7164
  catch { /* skip silently — covered by admin check above */ }
6804
7165
  // 3. WORK_ROOT.
@@ -6923,15 +7284,18 @@ command('mcp', async (_ctx, key) => {
6923
7284
  *
6924
7285
  * `adapterName` is typed `string` because the button passes a raw callback match;
6925
7286
  * an unknown name makes `getThreadAdapter` throw, which the caller wrapping this
6926
- * (the `agent_*` action) turns into a "unknown agent" answer.
7287
+ * (the `agent_*` action) turns into a "unknown agent" answer. `ending` is the
7288
+ * caller's hold on the conversation when it already knows the start leaves it
7289
+ * (an agent button onto a shell, held ahead of its toast); without one the start
7290
+ * holds it itself once it knows.
6927
7291
  */
6928
- async function handleAgentStart(key, adapterName, args) {
7292
+ async function handleAgentStart(key, adapterName, args, ending) {
6929
7293
  if (checkIsGeneral(key)) {
6930
7294
  await replyToThread(key, (0, i18n_1.t)('error.start_in_general'));
6931
7295
  return;
6932
7296
  }
6933
- // Refuse to start an agent without a binding — same rationale as the
6934
- // natural-language path in the text handler (plan §11 Этап 4).
7297
+ // Refuse to start an agent without a binding: starting without one would silently launch against WORK_ROOT,
7298
+ // which is almost never wanted (plan §11 Этап 4).
6935
7299
  if (!state.getBinding(key)) {
6936
7300
  const subdirs = listAvailableSubdirs(ENV.workRoot);
6937
7301
  const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
@@ -6945,19 +7309,51 @@ async function handleAgentStart(key, adapterName, args) {
6945
7309
  const targetFamily = (0, backendSwitchPlan_1.getBackendFamily)(adapterName);
6946
7310
  if (targetFamily !== null && await askBeforeCrossBackendSwitch(key, targetFamily, args))
6947
7311
  return;
6948
- await switchThreadAdapter(key, adapterName);
6949
- const adapter = (0, createAdapter_1.getThreadAdapter)(key);
6950
- if (adapter.checkIsActive(key)) {
6951
- await replyToThread(key, (0, i18n_1.t)('agent.already_active', { label: adapter.label }));
6952
- return;
7312
+ // The switch runs as the conversation's one transition, after a re-spawn — a start or resume of the old backend in flight is over first
7313
+ // and none comes back beside the new one — and, when it leaves the conversation (another agent or a shell), held as ending it from here,
7314
+ // as a move is (review 23 nit 2), unless the caller held it already.
7315
+ const switchAdapter = () => switchThreadAdapter(key, adapterName);
7316
+ const isLeavingConversation = checkIsStartLeavingConversation(key, adapterName);
7317
+ // A start that leaves the conversation refuses a person's message until the new agent's start is over, as a move does until its first
7318
+ // prompt reached the other backend: between the switch and that start no agent takes it, and the start's window belongs to an agent that
7319
+ // does not know the conversation (review 25 #1, own pass).
7320
+ const stopRefusingMessages = isLeavingConversation ? conversationEndings.refuseMessages(key) : null;
7321
+ let msg;
7322
+ try {
7323
+ if (isLeavingConversation) {
7324
+ await (ending ?? conversationEndings.hold(key)).run(switchAdapter);
7325
+ }
7326
+ else {
7327
+ ending?.release();
7328
+ await runCommandSessionTransition(key, switchAdapter);
7329
+ }
7330
+ const adapter = (0, createAdapter_1.getThreadAdapter)(key);
7331
+ if (adapter.checkIsActive(key)) {
7332
+ await replyToThread(key, (0, i18n_1.t)('agent.already_active', { label: adapter.label }));
7333
+ return;
7334
+ }
7335
+ // A sleeping conversation is woken, not replaced (L-D4): `/new` is the fresh start. A first start is the conversation's one
7336
+ // transition too, and finds a session another trigger started meanwhile instead of starting a second one beside it.
7337
+ msg = getResumableSessionId(key) !== null
7338
+ ? (await ensureAgentSession(key, { args })).message
7339
+ : await runCommandSessionTransition(key, async () => ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)
7340
+ ? (0, i18n_1.t)('agent.already_active', { label: (0, createAdapter_1.getThreadAdapter)(key).label })
7341
+ : startAgentSession(key, args)));
7342
+ }
7343
+ finally {
7344
+ stopRefusingMessages?.();
6953
7345
  }
6954
- // A sleeping conversation is woken, not replaced (L-D4): `/new` is the fresh start.
6955
- const msg = getResumableSessionId(key) !== null
6956
- ? (await ensureAgentSession(key, { args })).message
6957
- : await startAgentSession(key, args);
6958
7346
  if (msg)
6959
7347
  await replyToThread(key, msg);
6960
7348
  }
7349
+ /**
7350
+ * @description Whether starting `startAdapterName` (already resolved, `resolveStartAdapterName`) leaves the conversation the topic holds:
7351
+ * onto another agent or a shell. A switch within the Claude family keeps it (`checkIsSameConversationSwitch`).
7352
+ */
7353
+ function checkIsStartLeavingConversation(key, startAdapterName) {
7354
+ const previousName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
7355
+ return previousName !== undefined && !(0, createAdapter_1.checkIsSameConversationSwitch)(previousName, startAdapterName);
7356
+ }
6961
7357
  /**
6962
7358
  * @description Thin wrapper extracting the trailing args from the command text
6963
7359
  * for {@link handleAgentStart}. The args are everything after the command word
@@ -7024,6 +7420,12 @@ async function applyClaudeBackendSwitch(key, target) {
7024
7420
  if (refusal)
7025
7421
  return (0, i18n_1.t)('claudeMode.perTurn_refused', { version: refusal.version, min: claudeCodeVersion_1.minAutoStopClaudeCodeVersion });
7026
7422
  }
7423
+ // As the conversation's one transition: the stop of the old backend and the resume on the new one never overlap an ensure or an idle
7424
+ // stop (review 20 nit 3).
7425
+ return runCommandSessionTransition(key, () => switchClaudeBackendNow(key, target, label));
7426
+ }
7427
+ /** {@link applyClaudeBackendSwitch}'s switch itself, inside the conversation's transition. */
7428
+ async function switchClaudeBackendNow(key, target, label) {
7027
7429
  const wasActive = (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key);
7028
7430
  const sessionId = state.getAgent(key)?.claudeSessionId;
7029
7431
  // Stops the previous backend, records the pick, keeps `claudeSessionId`.
@@ -7035,19 +7437,16 @@ async function applyClaudeBackendSwitch(key, target) {
7035
7437
  const decision = getWorkDirStartDecision(key);
7036
7438
  if (!decision.ok)
7037
7439
  return `${decision.message}${backgroundStoppedSuffix}`;
7038
- const targetAdapter = (0, createAdapter_1.getThreadAdapter)(key);
7039
7440
  sendThreadTypingIndicator(key).catch(() => { });
7040
- if (sessionId && targetAdapter.resumeSession) {
7041
- markNeedsNewMessage(key);
7441
+ if (sessionId) {
7042
7442
  clearThreadContextMarker(key);
7043
- try {
7044
- await targetAdapter.resumeSession(key, decision.workDir, sessionId, { isWithRecentContext: true });
7045
- await persistSessionStart(key, targetAdapter);
7443
+ // The resume opens its startup window as a wake's does: a prompt that comes meanwhile waits and is replayed (review 20 nit 3).
7444
+ if ((await resumeSleepingSession(key, sessionId, { isWithRecentContext: true })) === null) {
7046
7445
  return `${(0, i18n_1.t)('claudeMode.switched_resumed', { label })}${backgroundStoppedSuffix}`;
7047
7446
  }
7048
- catch (e) {
7049
- console.error('[claude_mode] resume failed, starting fresh:', e instanceof Error ? e.message : e);
7050
- }
7447
+ console.error(`[claude_mode] ${(0, sessionKey_1.keyToString)(key)}: the resume on the new backend failed; starting fresh`);
7448
+ // The fresh start takes the failed resume's window over, as after a failed wake: the people's prompts go to the fresh session.
7449
+ startupPromptBuffer.discardBotPrompts((0, sessionKey_1.keyToString)(key));
7051
7450
  }
7052
7451
  const msg = await startAgentSession(key);
7053
7452
  return `${msg || (0, i18n_1.t)('claudeMode.switched_fresh', { label })}${backgroundStoppedSuffix}`;
@@ -7119,9 +7518,29 @@ const { applyAutoContinueLimits, consumeAutoContinueLimitsPicker, registerAutoCo
7119
7518
  getRequestWakeUpEngine: () => requestWakeUpEngine,
7120
7519
  });
7121
7520
  registerAutoContinueLimitsCommands();
7521
+ // ── The worker roles (`/workers`): `connectors/telegram/commands/workerRoles.ts`, `utils/workerRolesScreenPlan.ts`, `utils/workerRoles.ts` ──
7522
+ const { registerWorkerRolesCommands, registerWorkerRolesCallbacks, openScreen: openWorkerRolesScreen } = (0, workerRoles_1.createWorkerRoles)({
7523
+ ...botCore,
7524
+ readWorkerRoles: readWorkerRolesSettings,
7525
+ saveWorkerRoles: (workerRoles) => (0, instanceSettings_1.saveInstanceSettingsChange)((0, instanceSettings_1.getInstanceSettingsPath)(), { workerRoles }),
7526
+ getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
7527
+ listOpenCodeModels: async () => (await readOpenCodeCatalogForWorker()) ?? [],
7528
+ getOpenCodeModelVariants: async (model) => {
7529
+ try {
7530
+ return (await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getCatalogModelVariants?.(model)) ?? [];
7531
+ }
7532
+ catch (e) {
7533
+ console.warn('[workers] reading the variants of an OpenCode model failed:', e instanceof Error ? e.message : e);
7534
+ return [];
7535
+ }
7536
+ },
7537
+ readIsBotSkillsEnabled: () => (0, botSkills_1.readBotSkillsInstanceValue)(botSkillsSources).isEnabled,
7538
+ });
7539
+ registerWorkerRolesCommands();
7122
7540
  // ── «Bot skills» switch (`/bot_skills`): `connectors/telegram/commands/botSkills.ts`, `utils/botSkills.ts` ──
7123
7541
  const { registerBotSkillsCommands, registerBotSkillsCallbacks } = (0, botSkills_2.createBotSkills)({
7124
7542
  ...botCore,
7543
+ openWorkerRolesScreen,
7125
7544
  readBotSkills: botSkillsReader,
7126
7545
  readBotSkillsInstanceValue: () => (0, botSkills_1.readBotSkillsInstanceValue)(botSkillsSources),
7127
7546
  checkIsOpenCodeTopic: (key) => ((0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name) === adapterNames_1.openCodeAdapterName,
@@ -7219,7 +7638,7 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
7219
7638
  applyGroups: (runner) => (0, runnerGroups_1.applyRunnerGroups)(runnersHub, runner, runnersCacheDir),
7220
7639
  readRunnerHost: (0, instanceSettings_1.createRunnerHostReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line)),
7221
7640
  saveRunnerHost: (address) => (0, instanceSettings_1.saveInstanceSettingsChange)((0, instanceSettings_1.getInstanceSettingsPath)(), { runnerHost: address }),
7222
- getBotLabel: () => (bot.botInfo?.username === undefined ? os.hostname() : `@${bot.botInfo.username}`),
7641
+ getBotLabel,
7223
7642
  readOverview: (nowMs) => (0, runnersOverview_1.readRunnersOverview)(runnersHub, runnersCacheDir, nowMs),
7224
7643
  // The 20 s deadline of the live probe, which the test seam may shorten (a flow that must see a BUSY machine cannot wait it out).
7225
7644
  probeOverview: (overview, nowMs) => (0, runnersOverview_1.probeRunnersOverview)(runnersHub, overview, runnersCacheDir, nowMs, ENV.testTimings.remoteRunProbeDeadlineMs),
@@ -7241,20 +7660,433 @@ function repairClaudeProfileFolder(configDir) {
7241
7660
  (0, claudeProfiles_1.repairClaudeProfileFolderForLaunch)({ dataDir: (0, state_1.resolveDataDir)(), configDir });
7242
7661
  }
7243
7662
  /**
7244
- * @description The Claude config directory a conversation's NEXT process starts with: its resolved account
7245
- * profile's directory, `null` for the default profile. Registered as the adapters' reader at boot, and read by
7246
- * every spawn, so the folder is repaired here ({@link repairClaudeProfileFolder}). A profile
7247
- * whose directory vanished (a hand-cleaned `DATA_DIR`) runs on the default rather than failing the spawn.
7663
+ * @description The Claude config directory a conversation's NEXT process starts with: its account profile's directory
7664
+ * ({@link resolveThreadClaudeProfileForLaunch}: never one known not to work), `null` for the default profile. Registered as the
7665
+ * adapters' reader at boot, and read by every spawn, so the folder is repaired here ({@link repairClaudeProfileFolder}). A profile
7666
+ * whose directory vanished (a hand-cleaned `DATA_DIR`) runs on the default rather than failing the spawn.
7667
+ */
7668
+ function resolveThreadClaudeConfigDir(key) {
7669
+ const name = resolveThreadClaudeProfileForLaunch(key);
7670
+ const dir = (0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name);
7671
+ if (dir !== null && !fs.existsSync(dir)) {
7672
+ console.warn(`[account] ${(0, sessionKey_1.keyToString)(key)}: the directory of profile ${name} is missing; its process runs on the default profile`);
7673
+ return null;
7674
+ }
7675
+ repairClaudeProfileFolder(dir);
7676
+ return dir;
7677
+ }
7678
+ /**
7679
+ * @description The account profile a conversation's next Claude process starts on — start, resume and account switch alike (the
7680
+ * reader every spawn goes through, {@link resolveThreadClaudeConfigDir}): the profile it resolves to, unless that account is known
7681
+ * not to work — not signed in by its last probe, or refused by the CLI since (`utils/claudeAuthRefusal.ts`). Then the conversation
7682
+ * goes where `claude_profiles` sends a session leaving that account (`resolveClaudeProfileForLaunch`), recorded as its own
7683
+ * pick the way the limit move records it: a resume carries the same conversation onto the other account, and it stays there when
7684
+ * the first one is signed in again. With no other account usable it stays (and the refusal is surfaced as before).
7685
+ */
7686
+ function resolveThreadClaudeProfileForLaunch(key) {
7687
+ const resolved = state.resolveClaudeProfileName(key);
7688
+ settleClaudeAuthRefusal(resolved);
7689
+ const record = state.getClaudeProfileInfo(resolved);
7690
+ // The common case reads nothing more: the views and the `/limits` list only matter for an account that cannot run.
7691
+ if (!(0, claudeAuthRefusal_1.checkIsClaudeProfileKnownUnusable)(record))
7692
+ return resolved;
7693
+ const launch = (0, claudeProfileUsageViews_1.resolveClaudeProfileForLaunch)({ ...getClaudeConversationPickContext(key), resolved, record });
7694
+ if (!launch.isMoved)
7695
+ return resolved;
7696
+ const reason = (0, claudeAuthRefusal_1.describeClaudeProfileUsability)((0, claudeAuthRefusal_1.getClaudeProfileUsability)(record));
7697
+ console.log(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: profile ${resolved} cannot run it (${reason}) — the session starts on ${launch.name}`);
7698
+ void state.setClaudeProfileOverride(key, launch.name).catch((e) => console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: recording the move to ${launch.name} failed:`, e instanceof Error ? e.message : e));
7699
+ return launch.name;
7700
+ }
7701
+ /**
7702
+ * @description What picking the account a Claude conversation goes to reads (`utils/claudeProfileUsageViews.ts`: the account
7703
+ * `claude_profiles` names for a session leaving one it cannot run on): every profile's view as of now, the conversation's model
7704
+ * (`null` = none named: a new conversation), the `/limits` list's word on the accounts.
7705
+ */
7706
+ function getClaudeConversationPickContext(key) {
7707
+ return {
7708
+ views: getClaudeProfileUsageViews(),
7709
+ model: key === null ? null : getThreadClaudeModel(key),
7710
+ nowMs: Date.now(),
7711
+ chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()),
7712
+ };
7713
+ }
7714
+ /**
7715
+ * @description End the CLI's refusal of the account `name` once it is over (`getClaudeAuthRefusalEnd`): a new login in its folder, or —
7716
+ * a bare 401 / 403 not held until a new login — a probe after it that found the account signed in, which is kept as such (no sign-in
7717
+ * happened: a repeat is held, and nobody is told «signed in again»). Cheap — one small file read, only for a refused account — so every
7718
+ * launch on the account and every profile scan run it.
7719
+ */
7720
+ function settleClaudeAuthRefusal(name) {
7721
+ const record = state.getClaudeProfileInfo(name);
7722
+ const refusal = record?.authRefusal;
7723
+ if (!record || !refusal)
7724
+ return;
7725
+ const loginStamp = (0, claudeAuthRefusal_1.readClaudeLoginStamp)((0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name));
7726
+ const end = (0, claudeAuthRefusal_1.getClaudeAuthRefusalEnd)({ refusal, loginStamp, loggedIn: record.loggedIn, statusCheckedAt: record.statusCheckedAt });
7727
+ if (end === null)
7728
+ return;
7729
+ const ending = end === 'statusCheck'
7730
+ ? state.endClaudeProfileAuthRefusalByStatusCheck(name, new Date().toISOString())
7731
+ : state.setClaudeProfileAuthRefusal(name, null);
7732
+ void ending.catch((e) => console.warn(`[accounts] profile ${name}: ending its refusal failed:`, e instanceof Error ? e.message : e));
7733
+ noteClaudeProfileUsability();
7734
+ }
7735
+ /**
7736
+ * The CLI's refusal of the account `name` now (`buildClaudeAuthRefusalMark`): the stamp of the login it refused, the CLI's words, and
7737
+ * held until a new login when it repeats a bare 401 / 403 a status check ended lately.
7738
+ */
7739
+ function buildClaudeAuthRefusal(name, reason, cliText) {
7740
+ return (0, claudeAuthRefusal_1.buildClaudeAuthRefusalMark)({
7741
+ reason,
7742
+ login: (0, claudeAuthRefusal_1.readClaudeLoginStamp)((0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name)),
7743
+ detail: cliText === undefined ? null : (0, claudeAccountAlert_1.getClaudeAccountAlertDetail)(cliText),
7744
+ nowMs: Date.now(),
7745
+ endedByStatusCheck: state.getClaudeProfileInfo(name)?.authRefusalEndedByStatusCheck,
7746
+ });
7747
+ }
7748
+ /** The last state of each account the log said ({@link noteClaudeProfileUsability}); in memory — a restart says the unusable ones again. */
7749
+ const loggedClaudeProfileUsability = new Map();
7750
+ /**
7751
+ * @description Say in the log, once per change, that an account stopped or started being usable for a conversation
7752
+ * (`[accounts] profile default: not signed in — new sessions go to second`). Run after every profile scan and every refusal
7753
+ * mark or end, so a sign-out the poll finds, a refusal on a turn and a sign-in again each leave one line.
7754
+ */
7755
+ function noteClaudeProfileUsability() {
7756
+ const current = new Map();
7757
+ const backByStatusCheck = new Set();
7758
+ const nowMs = Date.now();
7759
+ for (const view of getClaudeProfileUsageViews()) {
7760
+ const record = state.getClaudeProfileInfo(view.name);
7761
+ current.set(view.name, (0, claudeAuthRefusal_1.getClaudeProfileUsability)(record));
7762
+ if ((0, claudeAuthRefusal_1.checkIsClaudeProfileBackByStatusCheck)(record, nowMs))
7763
+ backByStatusCheck.add(view.name);
7764
+ }
7765
+ const lines = (0, claudeAuthRefusal_1.listClaudeProfileUsabilityLines)({
7766
+ previous: loggedClaudeProfileUsability,
7767
+ current,
7768
+ getInstead: (name) => (0, claudeProfileUsageViews_1.pickClaudeProfileInstead)({ ...getClaudeConversationPickContext(null), currentProfile: name }),
7769
+ backByStatusCheck,
7770
+ });
7771
+ for (const line of lines)
7772
+ console.log(line);
7773
+ loggedClaudeProfileUsability.clear();
7774
+ for (const [name, usability] of current)
7775
+ loggedClaudeProfileUsability.set(name, usability);
7776
+ if (!isOperatorAlertOpen)
7777
+ return;
7778
+ tellOperatorAboutClaudeAccounts(current, backByStatusCheck);
7779
+ void resumeConversationsWaitingForAccount();
7780
+ }
7781
+ /** The channels besides General that operator alerts go to (a connector's own: Jira's operator issue); set at boot. */
7782
+ let operatorAlertChannels = [];
7783
+ /**
7784
+ * Until the boot has restored the sessions and knows its channels, a change of the accounts is only logged: nobody is told yet (the
7785
+ * persisted record keeps the change for the first round after) and no waiting conversation is resumed.
7786
+ */
7787
+ let isOperatorAlertOpen = false;
7788
+ /** At boot, once the sessions are restored and the connectors' channels are known: the first round tells and resumes. */
7789
+ function openOperatorAlerts() {
7790
+ isOperatorAlertOpen = true;
7791
+ noteClaudeProfileUsability();
7792
+ }
7793
+ /**
7794
+ * @description Tell the operator, once per change, about the accounts that cannot work because of their sign-in and those usable again
7795
+ * (`utils/claudeAccountAlert.ts`): the record of what was told is kept in the same tick, so two rounds close together never tell it
7796
+ * twice, and a round that changes nothing writes nothing.
7797
+ */
7798
+ function tellOperatorAboutClaudeAccounts(current, backByStatusCheck) {
7799
+ const details = new Map();
7800
+ for (const name of current.keys()) {
7801
+ const detail = state.getClaudeProfileInfo(name)?.authRefusal?.detail;
7802
+ if (detail)
7803
+ details.set(name, detail);
7804
+ }
7805
+ const previous = state.getClaudeAccountAlertState();
7806
+ const { alert, next } = (0, claudeAccountAlert_1.planClaudeAccountAlert)({
7807
+ previous,
7808
+ current,
7809
+ details,
7810
+ defaultProfile: state.getClaudeProfileGlobalDefault(),
7811
+ instead: (0, claudeProfileUsageViews_1.pickClaudeProfileInstead)({ ...getClaudeConversationPickContext(null), currentProfile: null }),
7812
+ backByStatusCheck,
7813
+ });
7814
+ if (alert === null && JSON.stringify(previous) === JSON.stringify(next))
7815
+ return;
7816
+ void state.setClaudeAccountAlertState(next).catch((e) => console.warn('[accounts] keeping what the operator was told failed:', e instanceof Error ? e.message : e));
7817
+ if (alert !== null)
7818
+ void deliverClaudeAccountAlert(alert);
7819
+ // An account back by a status check alone leaves quietly: with no told account left, the pin goes all the same.
7820
+ else
7821
+ void releaseClaudeAccountAlertPin();
7822
+ }
7823
+ /**
7824
+ * @description Unpin the account alert in General once no told account is left unusable; nothing while one is, or when none is
7825
+ * pinned. Changes only the pin of the record as it is now.
7826
+ */
7827
+ async function releaseClaudeAccountAlertPin() {
7828
+ const current = state.getClaudeAccountAlertState();
7829
+ const pinnedMessageId = current?.pinnedMessageId;
7830
+ if (!current || current.alerted.length > 0 || pinnedMessageId === undefined)
7831
+ return;
7832
+ await state.setClaudeAccountAlertPinnedMessageId(null);
7833
+ const generalKey = ENV.isTelegramServed ? getOperatorGeneralKey() : null;
7834
+ if (generalKey !== null)
7835
+ void unpinMessageQuiet(generalKey, pinnedMessageId);
7836
+ }
7837
+ /**
7838
+ * @description How to sign an account in again on the bot's host, for a channel read outside Telegram (the Jira operator issue): the
7839
+ * CLI's own sign-in under the account's folder, as the bot's OS user.
7840
+ */
7841
+ function getHostClaudeSignInHow(name) {
7842
+ const dir = (0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name);
7843
+ const command = dir === null ? 'claude auth login' : `CLAUDE_CONFIG_DIR=${dir} claude auth login`;
7844
+ return `\`${command}\` on the bot's host, as its OS user`;
7845
+ }
7846
+ /**
7847
+ * @description Post an account alert to the operator: in General (Telegram, the chat's language, pinned while it asks to act) and on
7848
+ * every connector's channel (English). A failed post is logged, never retried — an alert told twice is worse.
7849
+ */
7850
+ async function deliverClaudeAccountAlert(alert) {
7851
+ const lost = alert.lost.map((loss) => `${loss.name} (${loss.usability})`).join(', ');
7852
+ console.log(`[accounts] operator alert: ${lost ? `cannot work: ${lost}; conversations go to ${alert.instead ?? 'no account — they wait'}` : ''}${alert.back.length > 0 ? `${lost ? '; ' : ''}usable again: ${alert.back.join(', ')}` : ''}`);
7853
+ const posts = [];
7854
+ if (ENV.isTelegramServed)
7855
+ posts.push(postClaudeAccountAlertToTelegram(alert));
7856
+ const isActionRequired = alert.lost.length > 0;
7857
+ for (const channel of operatorAlertChannels) {
7858
+ const text = (0, i18n_1.runWithLocale)('en', () => (0, claudeAccountAlert_1.renderClaudeAccountAlert)(alert, getHostClaudeSignInHow));
7859
+ posts.push(channel.post(text, { isActionRequired }).then((result) => {
7860
+ if (!result.ok)
7861
+ console.warn(`[accounts] the operator alert did not reach ${channel.label}: ${result.error}`);
7862
+ }));
7863
+ }
7864
+ await Promise.all(posts);
7865
+ }
7866
+ /**
7867
+ * @description The account alert in General, like the updater's: worded in that chat's language, the sign-in named as
7868
+ * `/accounts login <name>`; an alert that asks to act is pinned (the pin is what reaches a muted operator) in place of the previous
7869
+ * one, and once no told account is left unusable the pin goes. `isPrivateChatClosed`: Telegram refused the private message about a
7870
+ * signed-out account (403) — the alert then also asks the operator to open a private chat with the bot.
7871
+ */
7872
+ async function postClaudeAccountAlertToGeneral(alert, options) {
7873
+ const generalKey = getOperatorGeneralKey();
7874
+ if (generalKey === null) {
7875
+ console.log('[accounts] no General topic to post the account alert in');
7876
+ return;
7877
+ }
7878
+ const renderOptions = options.isPrivateChatClosed ? { closedPrivateChatBot: getBotLabel() } : {};
7879
+ const text = withThreadLocale(generalKey, () => (0, claudeAccountAlert_1.renderClaudeAccountAlert)(alert, (name) => `/accounts login ${name}`, renderOptions));
7880
+ const messageId = await replyToThread(generalKey, text);
7881
+ if (alert.lost.length === 0 || messageId === null) {
7882
+ await releaseClaudeAccountAlertPin();
7883
+ return;
7884
+ }
7885
+ await pinMessageQuiet(generalKey, messageId, { disableNotification: false });
7886
+ // Read AFTER the waits, and only the pin is written: a round in between may have told another account, and that must stay told.
7887
+ const previousPinnedId = state.getClaudeAccountAlertState()?.pinnedMessageId;
7888
+ await state.setClaudeAccountAlertPinnedMessageId(messageId);
7889
+ if (previousPinnedId !== undefined && previousPinnedId !== messageId)
7890
+ void unpinMessageQuiet(generalKey, previousPinnedId);
7891
+ }
7892
+ /**
7893
+ * @description The account alert on Telegram. The private messages go FIRST — General's notice has to know whether Telegram refused them
7894
+ * (a person who never opened the bot's private chat), because then it also asks the operator to open one — and the accounts signed in
7895
+ * again get their earlier private message turned into «signed in again» beside General's post.
7896
+ */
7897
+ async function postClaudeAccountAlertToTelegram(alert) {
7898
+ const isPrivateChatClosed = await sendClaudeAccountSignOutDms(alert);
7899
+ await Promise.all([postClaudeAccountAlertToGeneral(alert, { isPrivateChatClosed }), settleClaudeAccountSignOutDms(alert)]);
7900
+ }
7901
+ /**
7902
+ * @description Tell the operator, in a PRIVATE message from the bot, about each account that is signed out in this alert: one short
7903
+ * line naming it and a button that starts its sign-in (`acct_signin_<name>`, the 🔑 of `/accounts`) — General is muted for the operator,
7904
+ * a private message is not. It rides the alert, so it is sent once per sign-out (not per refusal), and again only after the account was
7905
+ * signed in again and signed out again; the General notice is posted as before. The message's id is kept (`signOutMessageIds`) so it can
7906
+ * be turned into «signed in again» later. Nothing is sent when the operator's private chat is not a surface the bot serves (no
7907
+ * `OWNER_USER_ID`, `CHAT_MODE=group`) or already IS where General's notice went (`CHAT_MODE=dm`); a person who never opened the bot's
7908
+ * private chat cannot be written to (Telegram's 403): that is said in the log and returned (`true`), and General's notice says so.
7909
+ * Never retried — a second send could tell it twice.
7910
+ */
7911
+ async function sendClaudeAccountSignOutDms(alert) {
7912
+ const names = (0, claudeAccountAlert_1.listClaudeAccountSignOutNames)(alert);
7913
+ if (names.length === 0)
7914
+ return false;
7915
+ const privateKey = getOperatorPrivateChatKey();
7916
+ if (privateKey === null) {
7917
+ console.log(`[accounts] no private chat with the operator to tell them ${names.join(', ')} is signed out (General has it)`);
7918
+ return false;
7919
+ }
7920
+ let isPrivateChatClosed = false;
7921
+ for (const name of names) {
7922
+ const dm = withThreadLocale(privateKey, () => (0, claudeAccountAlert_1.renderClaudeAccountSignOutDm)(name));
7923
+ const outcome = await replyToThreadDetailed(privateKey, dm.text, telegraf_1.Markup.inlineKeyboard([[telegraf_1.Markup.button.callback(dm.buttonLabel, dm.callbackData)]]));
7924
+ if (outcome.kind === 'sent') {
7925
+ console.log(`[accounts] told the operator in a private message that ${name} is signed out`);
7926
+ await state.setClaudeAccountAlertSignOutMessageId(name, outcome.messageId);
7927
+ // The account may have been signed in again while the message was on its way: it is out of date already.
7928
+ if ((0, claudeAuthRefusal_1.getClaudeProfileUsability)(state.getClaudeProfileInfo(name)) === 'usable')
7929
+ await markClaudeAccountSignOutDmSignedIn(privateKey, name, outcome.messageId);
7930
+ }
7931
+ else if (outcome.kind === 'failed' && outcome.isForbidden === true) {
7932
+ isPrivateChatClosed = true;
7933
+ console.log(`[accounts] the operator's private chat is closed to the bot (they never opened it, or blocked it): ${name} is signed out, General has it`);
7934
+ }
7935
+ else {
7936
+ console.warn(`[accounts] the private message to the operator about ${name} did not go out (${outcome.kind})`);
7937
+ }
7938
+ }
7939
+ return isPrivateChatClosed;
7940
+ }
7941
+ /** The earlier private sign-out messages of the accounts this alert says are signed in again become «signed in again» (`alert.backMessageIds`). */
7942
+ async function settleClaudeAccountSignOutDms(alert) {
7943
+ const messageIds = Object.entries(alert.backMessageIds ?? {});
7944
+ const privateKey = messageIds.length === 0 ? null : getOperatorPrivateChatKey();
7945
+ if (privateKey === null)
7946
+ return;
7947
+ for (const [name, messageId] of messageIds)
7948
+ await markClaudeAccountSignOutDmSignedIn(privateKey, name, messageId);
7949
+ }
7950
+ /**
7951
+ * @description Turn the private sign-out message of `name` into «signed in again»: its text is the one of General's «signed in again» line
7952
+ * and the edit leaves it no button (the Bot API drops the keyboard of a message edited without one), so a tap on a message that is no
7953
+ * longer true is impossible. Best-effort, never retried: a message that stays as it was is harmless — its button only starts a sign-in.
7954
+ */
7955
+ async function markClaudeAccountSignOutDmSignedIn(privateKey, name, messageId) {
7956
+ await state.setClaudeAccountAlertSignOutMessageId(name, null);
7957
+ const text = withThreadLocale(privateKey, () => (0, i18n_1.t)('accounts.alert.back', { name }));
7958
+ if (await editThreadMessage(privateKey, messageId, text))
7959
+ console.log(`[accounts] the private message about ${name} now says it is signed in again`);
7960
+ else
7961
+ console.warn(`[accounts] the private message about ${name} could not be turned into «signed in again»`);
7962
+ }
7963
+ /** A resume of the conversations waiting for an account runs one at a time. */
7964
+ let isResumingAccountWaits = false;
7965
+ /**
7966
+ * @description The conversations a refused turn left with no account to move to (`claudeAccountWaits`) go on once one can work:
7967
+ * each is moved onto the account it resolves to now (the launch pick leaves the refused one) and gets the continue prompt — or its
7968
+ * open requests' prompts not taken in — with its requests woken again, as after a usage-limit wait. Run after every round of the
7969
+ * accounts' states; nothing happens while no account is usable.
7970
+ */
7971
+ async function resumeConversationsWaitingForAccount() {
7972
+ if (isResumingAccountWaits)
7973
+ return;
7974
+ const waiting = state.listClaudeAccountWaits();
7975
+ if (waiting.length === 0)
7976
+ return;
7977
+ if ((0, claudeProfileUsageViews_1.pickClaudeProfileInstead)({ ...getClaudeConversationPickContext(null), currentProfile: null }) === null)
7978
+ return;
7979
+ isResumingAccountWaits = true;
7980
+ try {
7981
+ for (const key of waiting) {
7982
+ await state.setWaitingForClaudeAccount(key, false);
7983
+ if (!(0, connectorSet_1.checkIsServedConversation)(key, ENV.servedPlatforms) || !checkIsClaudeProfileBackend(key))
7984
+ continue;
7985
+ try {
7986
+ await applyClaudeProfileToThread(key, { isAfterLimit: true });
7987
+ console.log(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: a Claude account can work again — the conversation goes on (${state.resolveClaudeProfileName(key)})`);
7988
+ await resumeTopicOnNewSession(key, {
7989
+ modelToPin: null,
7990
+ getFirstPrompt: () => (0, limitHeldPrompts_1.getLimitResumeMessage)({
7991
+ continueNudge: (0, i18n_1.t)('apiRetry.continueNudge'),
7992
+ untakenRequestPrompts: (0, requestHeader_1.getPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? []),
7993
+ }),
7994
+ });
7995
+ }
7996
+ catch (e) {
7997
+ console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: resuming the conversation failed:`, e instanceof Error ? e.message : e);
7998
+ }
7999
+ }
8000
+ }
8001
+ finally {
8002
+ isResumingAccountWaits = false;
8003
+ }
8004
+ }
8005
+ /**
8006
+ * @description The profile scan (`utils/claudeProfileSync.ts`) the usage poll and `/accounts` run, followed by the refusals it may
8007
+ * end: an account signed in again since the CLI refused it is usable again from here.
8008
+ */
8009
+ async function syncClaudeProfilesAndRefusals(options = {}) {
8010
+ const result = await claudeProfileSync.sync(options);
8011
+ for (const name of Object.keys(state.getAllClaudeProfileInfos()))
8012
+ settleClaudeAuthRefusal(name);
8013
+ noteClaudeProfileUsability();
8014
+ return result;
8015
+ }
8016
+ /**
8017
+ * @description The CLI refused the account a json-stream Claude conversation runs on (an `auth` error: signed out, a login expired
8018
+ * or revoked, its organization turned Claude subscription use off, a bare 401 / 403). The account is marked refused
8019
+ * (`utils/claudeAuthRefusal.ts`) until it is signed in again, and the conversation makes the limit move
8020
+ * ({@link switchTopicToFallbackEntry}, same conversation) to the account `claude_profiles` names for it
8021
+ * (`planClaudeAuthRefusalMove`); the dead turn goes on there — the continue prompt, or the open requests' prompts not
8022
+ * taken in. Not tied to the auto-switch setting: a refused account comes back by no wait. With no other account usable, a move
8023
+ * that fails, or an error replayed from before this boot (the login may have been fixed since; it is not marked), the pinned
8024
+ * logged-out notice as before.
8025
+ */
8026
+ async function handleClaudeAuthRefusal(key, cls) {
8027
+ const k = (0, sessionKey_1.keyToString)(key);
8028
+ const from = getTopicFallbackPosition(key);
8029
+ if (from?.backend !== 'claude') {
8030
+ await surfaceLoggedOutNotice(key);
8031
+ return;
8032
+ }
8033
+ const reason = cls.authReason ?? 'signedOut';
8034
+ const refusal = buildClaudeAuthRefusal(from.profile, reason, cls.authDetail);
8035
+ const plan = (0, claudeProfileUsageViews_1.planClaudeAuthRefusalMove)({ ...getClaudeConversationPickContext(key), refused: from.profile, refusal, isReplayed: cls.isReplayed === true });
8036
+ if (!plan.isMarked) {
8037
+ await surfaceLoggedOutNotice(key);
8038
+ return;
8039
+ }
8040
+ await state.setClaudeProfileAuthRefusal(from.profile, refusal);
8041
+ noteClaudeProfileUsability();
8042
+ const instead = plan.to;
8043
+ if (instead === null) {
8044
+ console.log(`[accounts] ${k}: profile ${from.profile} was refused (${claudeAuthRefusal_1.claudeAuthRefusalWords[reason]}) and no other account can take the conversation over — it waits for one`);
8045
+ await waitForClaudeAccount(key);
8046
+ return;
8047
+ }
8048
+ console.log(`[accounts] ${k}: profile ${from.profile} was refused (${claudeAuthRefusal_1.claudeAuthRefusalWords[reason]}) — moving the conversation to ${instead}`);
8049
+ const to = { backend: 'claude', profile: instead, model: null };
8050
+ // A topic hears it from the move's own notice; a tracker issue from the bot's answer to its open requests, in plain words.
8051
+ if (!(0, sessionKeyCodec_1.checkIsTelegramKey)(key) && requestLimitWaitAnswerDeps) {
8052
+ await (0, limitWaitAnswer_1.answerOpenRequestsWithBotNotice)(requestLimitWaitAnswerDeps, key, {
8053
+ identity: `claudeAccountMove:${instead}`,
8054
+ body: (0, i18n_1.t)('requests.account.movedAnswer', { from: from.profile, reason: (0, claudeAccountAlert_1.formatClaudeAccountRefusal)(reason), to: instead }),
8055
+ isWakeStopped: false,
8056
+ }).catch((e) => console.warn(`[accounts] ${k}: telling the requests about the move failed:`, e instanceof Error ? e.message : e));
8057
+ }
8058
+ try {
8059
+ await switchTopicToFallbackEntry(key, from, to, { isAnnounced: true, isAutomatic: true, reason: 'signIn' });
8060
+ }
8061
+ catch (e) {
8062
+ console.warn(`[accounts] ${k}: moving the conversation to ${instead} failed:`, e instanceof Error ? e.message : e);
8063
+ await surfaceLoggedOutNotice(key);
8064
+ }
8065
+ }
8066
+ /**
8067
+ * @description A refused turn with no other Claude account to move to: the conversation WAITS for one (`claudeAccountWaits`) — its
8068
+ * requests are no longer woken (a reminder would only meet the same refusal, and its give-up would read as the agent's silence), a
8069
+ * topic gets the pinned logged-out notice, a tracker issue the bot's own answer saying in plain words that no account of the AI can
8070
+ * work, why, that the operator was told, and that the work goes on once one is signed in again
8071
+ * ({@link resumeConversationsWaitingForAccount}).
7248
8072
  */
7249
- function resolveThreadClaudeConfigDir(key) {
7250
- const name = state.resolveClaudeProfileName(key);
7251
- const dir = (0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name);
7252
- if (dir !== null && !fs.existsSync(dir)) {
7253
- console.warn(`[account] ${(0, sessionKey_1.keyToString)(key)}: the directory of profile ${name} is missing; its process runs on the default profile`);
7254
- return null;
8073
+ async function waitForClaudeAccount(key) {
8074
+ await state.setWaitingForClaudeAccount(key, true);
8075
+ await requestWakeUpEngine?.stopWakingForLimitWait(key);
8076
+ if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || !requestLimitWaitAnswerDeps) {
8077
+ await surfaceLoggedOutNotice(key);
8078
+ return;
7255
8079
  }
7256
- repairClaudeProfileFolder(dir);
7257
- return dir;
8080
+ const reasons = getClaudeProfileUsageViews()
8081
+ .map((view) => ({ name: view.name, usability: (0, claudeAuthRefusal_1.getClaudeProfileUsability)(state.getClaudeProfileInfo(view.name)) }))
8082
+ .flatMap(({ name, usability }) => (usability === 'usable' ? [] : [`«${name}» ${(0, claudeAccountAlert_1.formatClaudeAccountRefusal)(usability)}`]))
8083
+ .join('; ');
8084
+ await (0, limitWaitAnswer_1.answerOpenRequestsWithBotNotice)(requestLimitWaitAnswerDeps, key, {
8085
+ // One wait, one answer per request: a later refused turn of the same wait (a new request's prompt) answers only the new request.
8086
+ identity: 'claudeAccountWait',
8087
+ body: (0, i18n_1.t)('requests.account.noneUsableAnswer', { reasons }),
8088
+ isWakeStopped: true,
8089
+ }).catch((e) => console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: telling the requests about the wait failed:`, e instanceof Error ? e.message : e));
7258
8090
  }
7259
8091
  /**
7260
8092
  * `claude auth status --json` under `configDir` (`null` = `~/.claude`) as its sessions see it: never through an
@@ -7353,7 +8185,7 @@ const claudeProfileSync = (0, claudeProfileSync_1.createClaudeProfileSync)({
7353
8185
  * `rate_limit_event` frames the json-stream sessions report. Snapshots live on the profile records.
7354
8186
  */
7355
8187
  const claudeUsageRefresher = (0, claudeUsageRefresher_1.createClaudeUsageRefresher)({
7356
- syncProfiles: () => claudeProfileSync.sync(),
8188
+ syncProfiles: () => syncClaudeProfilesAndRefusals(),
7357
8189
  listProfiles: () => [
7358
8190
  {
7359
8191
  name: claudeProfiles_1.defaultClaudeProfileName, configDir: null,
@@ -7515,7 +8347,7 @@ function readStatusAccountSource(name) {
7515
8347
  syncClaudeApiCreditAnchors();
7516
8348
  const info = state.getClaudeProfileInfo(name);
7517
8349
  return {
7518
- name, email: info?.email ?? null, loggedIn: info?.loggedIn, limitedUntil: info?.limitedUntil ?? null,
8350
+ name, email: info?.email ?? null, loggedIn: (0, claudeAuthRefusal_1.getClaudeProfileSignedIn)(info), limitedUntil: info?.limitedUntil ?? null,
7519
8351
  billing: info?.billing ?? null, creditExhaustedAt: info?.creditExhaustedAt ?? null, ...(info?.apiSpend ? { apiSpend: info.apiSpend } : {}),
7520
8352
  };
7521
8353
  }
@@ -7616,16 +8448,20 @@ function getConversationAccountState(key) {
7616
8448
  return { isLimited: checkIsFuture(info?.limitedUntil) || info?.creditExhaustedAt !== undefined, isApiBilled: info?.billing === 'api' };
7617
8449
  }
7618
8450
  /**
7619
- * @description A person wrote in the conversation (a message, voice, file, album; an issue's request): the
7620
- * compact-on-idle latch clears (D2), the todo reminder's silence after ignored reminders ends (D13), and a question the
8451
+ * @description A person wrote in the conversation (a message, voice, file, album; an issue's request): the idle countdown
8452
+ * restarts, the todo reminder's silence after ignored reminders ends (D13), and a question the
7621
8453
  * idle compaction re-asked is closed as unanswered — they wrote something else instead of tapping it, like a live
7622
8454
  * question a message cancels, and its buttons must not be tapped later onto whatever the agent asks next. A tap on the
7623
8455
  * re-asked question takes its record before it gets here, so it is not closed by its own answer.
7624
8456
  */
7625
8457
  function notePersonActivity(key) {
7626
- noteThreadUserActivity(key);
8458
+ noteThreadActivity(key);
7627
8459
  getTodoRegistry().notePersonActivity(key);
7628
8460
  closeReAskedQuestion(key);
8461
+ // Their words go to the agent now — on an account that works, or back into the wait if none does — so no later resume adds a nudge.
8462
+ if (state.checkIsWaitingForClaudeAccount(key)) {
8463
+ void state.setWaitingForClaudeAccount(key, false).catch((e) => console.warn(`[accounts] ${(0, sessionKey_1.keyToString)(key)}: ending the wait for an account failed:`, e instanceof Error ? e.message : e));
8464
+ }
7629
8465
  }
7630
8466
  /**
7631
8467
  * @description What a usage limit on `key` leads to (`utils/fallbackChain.ts`): the rung the topic is on is
@@ -7712,8 +8548,8 @@ function getFallbackResetTime(from) {
7712
8548
  * The «switched» notice (`utils/fallbackSwitchNotice.ts`), with the reset of the exhausted rung when known — and, onto
7713
8549
  * an account billed to API credits, the line that it costs money per request and what it has spent so far.
7714
8550
  */
7715
- function getFallbackSwitchedNotice(from, to, runningModel) {
7716
- const notice = (0, fallbackSwitchNotice_1.buildFallbackSwitchedNotice)({ from, to, resetTime: getFallbackResetTime(from), runningModel });
8551
+ function getFallbackSwitchedNotice(from, to, runningModel, reason = 'limit') {
8552
+ const notice = (0, fallbackSwitchNotice_1.buildFallbackSwitchedNotice)({ from, to, resetTime: getFallbackResetTime(from), runningModel, reason });
7717
8553
  const info = to.backend === 'claude' ? state.getClaudeProfileInfo(to.profile) : undefined;
7718
8554
  if (to.backend !== 'claude' || info?.billing !== 'api')
7719
8555
  return notice;
@@ -7805,14 +8641,29 @@ function formatThreadBackend(key) {
7805
8641
  * deliver it. After a limit the turn is dead, so a working Claude session is moved at once; only one that cannot
7806
8642
  * be re-spawned yet (a tmux session with nothing to resume) keeps its wait and moves at turn end. Returns whether
7807
8643
  * the work continues now and the notice that says so (posted here only when `isAnnounced` — the auto-switch has no
7808
- * other voice, while a tapped button's notice is edited into the same line by its handler).
8644
+ * other voice, while a tapped button's notice is edited into the same line by its handler). `reason: 'signIn'` is the same
8645
+ * move off a Claude account the CLI refused ({@link handleClaudeAuthRefusal}): only its notices and log line differ.
8646
+ *
8647
+ * A move onto the other backend refuses a person's message from here — nothing is awaited before — until it ends: its first prompt has
8648
+ * reached the new backend, or it failed (`ConversationEndings.refuseMessages`, review 25 #1). Written into the backend being left, the
8649
+ * message would be lost with it; written into the new one ahead of the bridge, it would reach an agent that does not know the
8650
+ * conversation yet; and between the two there is no agent to take it.
7809
8651
  */
7810
8652
  async function switchTopicToFallbackEntry(key, from, to, options) {
8653
+ const stopRefusingMessages = checkIsFallbackMoveAcrossBackends(key, from, to) ? conversationEndings.refuseMessages(key) : null;
8654
+ try {
8655
+ return await switchTopicToFallbackEntryNow(key, from, to, options);
8656
+ }
8657
+ finally {
8658
+ stopRefusingMessages?.();
8659
+ }
8660
+ }
8661
+ /** @description {@link switchTopicToFallbackEntry} itself, under the refusal its caller took for a move onto the other backend. */
8662
+ async function switchTopicToFallbackEntryNow(key, from, to, options) {
8663
+ const reason = options.reason ?? 'limit';
7811
8664
  const k = (0, sessionKey_1.keyToString)(key);
7812
8665
  const fromLabel = from ? formatFallbackEntry(from) : '?';
7813
8666
  const toLabel = formatFallbackEntry(to);
7814
- // An OpenCode topic on the server's default model has no rung (`from` is null), yet it is on OpenCode all the same.
7815
- const isSameFamily = (from?.backend ?? getTopicBackendFamily(key)) === to.backend;
7816
8667
  const runningModel = readRunningModelBeforeMove(key, from, to);
7817
8668
  // The notice is a topic message: a conversation of another platform (a Jira issue) hears nothing — the log line below says it — and
7818
8669
  // its work simply continues.
@@ -7842,7 +8693,7 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
7842
8693
  }
7843
8694
  if (outcome === 'deferred' || outcome === 'restartRequired') {
7844
8695
  fallbackSwitchOffers.delete(k);
7845
- const notice = (0, fallbackSwitchNotice_1.buildFallbackDeferredNotice)(from, to);
8696
+ const notice = (0, fallbackSwitchNotice_1.buildFallbackDeferredNotice)(from, to, reason);
7846
8697
  await say(notice);
7847
8698
  return { isSwitched: false, notice };
7848
8699
  }
@@ -7852,26 +8703,38 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
7852
8703
  if (cutOffWork)
7853
8704
  await foldLostWorkIntoNextPrompt(key, { ...cutOffWork, reason: 'restarted', lostAt: Date.now() });
7854
8705
  }
7855
- else if (isSameFamily && to.backend === 'opencode') {
8706
+ else if (to.backend === 'opencode' && !checkIsFallbackMoveAcrossBackends(key, from, to)) {
7856
8707
  const error = await (0, createAdapter_1.getThreadAdapter)(key).setModel?.(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
7857
8708
  if (error)
7858
8709
  return fail(error);
7859
8710
  }
7860
8711
  else {
7861
- const bridge = await buildFallbackBridge(key, {
7862
- fromLabel: from ? formatFallbackEntry(from) : formatThreadBackend(key),
7863
- toLabel: toLabel,
7864
- reason: 'limit',
7865
- resetsAtText: getFallbackResetTime(from),
7866
- });
7867
- // An automatic fallback keeps the conversation (parked, bridged): the questions it had set aside stay open for a late answer.
7868
- isStoppingBackground = await moveTopicToOtherBackend(key, to.backend, to.backend === 'claude' ? to.profile : null, { isConversationKept: options.isAutomatic === true });
8712
+ // Onto the other backend, which ends the conversation the move leaves: held from here — nothing above awaits —, ahead of the bridge,
8713
+ // unless the caller held it already, so a stop under way drops what it held instead of resuming the backend being left (review 24 #1).
8714
+ const ending = options.ending ?? conversationEndings.hold(key);
8715
+ // What the agent took in, read at the moment the bridge reads its transcript: a message it takes in later is in neither (review 27
8716
+ // nit 5).
8717
+ const promptsReachedOrHeld = requestWakeUpEngine?.readPromptsReachedOrHeld(key);
8718
+ let bridge;
8719
+ try {
8720
+ bridge = await buildFallbackBridge(key, {
8721
+ fromLabel: from ? formatFallbackEntry(from) : formatThreadBackend(key),
8722
+ toLabel: toLabel,
8723
+ reason: 'limit',
8724
+ resetsAtText: getFallbackResetTime(from),
8725
+ });
8726
+ // An automatic fallback keeps the conversation (parked, bridged): the questions it had set aside stay open for a late answer.
8727
+ isStoppingBackground = await moveTopicToOtherBackend(key, ending, to.backend, to.backend === 'claude' ? to.profile : null, { isConversationKept: options.isAutomatic === true, promptsReachedOrHeld });
8728
+ }
8729
+ finally {
8730
+ ending.release();
8731
+ }
7869
8732
  if (to.backend === 'opencode') {
7870
8733
  const error = await (0, createAdapter_1.getThreadAdapter)(key).setModel?.(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
7871
8734
  if (error)
7872
8735
  return fail(error);
7873
8736
  }
7874
- firstPrompt = { text: bridge, isRequestPrompt: false };
8737
+ firstPrompt = { text: bridge, carriedRequestIds: [] };
7875
8738
  }
7876
8739
  // From the end of the wait until the continue prompt is forwarded, the idle the limit left behind is not a turn end (the
7877
8740
  // same hold a retry kick has): the model pin below re-spawns the session for seconds, and a wake-up engine that polled
@@ -7881,15 +8744,15 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
7881
8744
  apiRetryKicksInFlight.add(k);
7882
8745
  try {
7883
8746
  cancelApiRetry(key); // retires the offer too: the switch consumed it
7884
- const notice = `${getFallbackSwitchedNotice(from, to, runningModel)}${isStoppingBackground ? `\n${(0, i18n_1.t)('fallback.backgroundStopped')}` : ''}`;
7885
- console.log(`[fallback] ${k}: switched from ${fromLabel} to ${toLabel} after a usage limit${firstPrompt ? ' (cross-backend, bridged)' : ''}; resuming`);
8747
+ const notice = `${getFallbackSwitchedNotice(from, to, runningModel, reason)}${isStoppingBackground ? `\n${(0, i18n_1.t)('fallback.backgroundStopped')}` : ''}`;
8748
+ console.log(`[fallback] ${k}: switched from ${fromLabel} to ${toLabel} after ${reason === 'signIn' ? 'its account was refused' : 'a usage limit'}${firstPrompt ? ' (cross-backend, bridged)' : ''}; resuming`);
7886
8749
  await say(notice);
7887
8750
  await resumeTopicOnNewSession(key, {
7888
8751
  modelToPin: (0, fallbackChain_1.getFallbackModelToPin)(to, runningModel),
7889
8752
  // Read after the session is up: the open requests may have changed while it started.
7890
8753
  getFirstPrompt: () => firstPrompt ?? (0, limitHeldPrompts_1.getLimitResumeMessage)({
7891
8754
  continueNudge: (0, i18n_1.t)('apiRetry.continueNudge'),
7892
- untakenRequestPrompt: (0, requestHeader_1.joinPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? []),
8755
+ untakenRequestPrompts: (0, requestHeader_1.getPromptsNotTakenIn)(requestLimitWaitAnswerDeps?.ledger.listOpenRequestsOf(key) ?? []),
7893
8756
  }),
7894
8757
  });
7895
8758
  return { isSwitched: true, notice };
@@ -7899,18 +8762,37 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
7899
8762
  apiRetryKicksInFlight.delete(k);
7900
8763
  }
7901
8764
  }
8765
+ /**
8766
+ * @description Whether {@link switchTopicToFallbackEntry} moves `key` from `from` onto `to` ACROSS backends — the move that ends the
8767
+ * conversation it leaves — rather than to another Claude account or another OpenCode model of the same conversation.
8768
+ */
8769
+ function checkIsFallbackMoveAcrossBackends(key, from, to) {
8770
+ if (from?.backend === 'claude' && to.backend === 'claude')
8771
+ return false;
8772
+ // An OpenCode topic on the server's default model has no rung (`from` is null), yet it is on OpenCode all the same.
8773
+ const isSameFamily = (from?.backend ?? getTopicBackendFamily(key)) === to.backend;
8774
+ return !(isSameFamily && to.backend === 'opencode');
8775
+ }
7902
8776
  /**
7903
8777
  * @description The move ACROSS backends both the usage-limit switch and the operator's manual switch make, first
7904
8778
  * half: record `account` as the topic's own Claude pick when one is given (the chain's rung, the operator's pick — a
7905
8779
  * switch that only names the account the topic follows passes `null`), then `switchThreadAdapter` stops the old
7906
8780
  * session, parks its id and brings back the target family's parked one. The context bridge is built BEFORE this, while
7907
- * the adapter being left still runs. Resolves whether the stop took background work with it — the caller tells the
7908
- * operator (the agent is told by the next prompt, `switchThreadAdapter`).
8781
+ * the adapter being left still runs, and the caller's `ending` holds the conversation from before the bridge.
8782
+ * `options.promptsReachedOrHeld` is what the agent took in, read when the bridge was built: it is handed to `switchThreadAdapter`'s close
8783
+ * of the requests, so a message is either carried by the bridge or told, never neither (review 27 nit 5). Resolves
8784
+ * whether the stop took background work with it — the caller tells the operator (the agent is told by the next prompt,
8785
+ * `switchThreadAdapter`).
7909
8786
  */
7910
- async function moveTopicToOtherBackend(key, backend, account, options = {}) {
8787
+ async function moveTopicToOtherBackend(key, ending, backend, account, options = {}) {
7911
8788
  if (account !== null)
7912
8789
  await state.setClaudeProfileOverride(key, account);
7913
- return (0, lostWork_1.checkHasLostBackgroundWork)(await switchThreadAdapter(key, backend === 'claude' ? (0, createAdapter_1.resolveClaudeBackendName)(key) : adapterNames_1.openCodeAdapterName, options));
8790
+ // The old backend's stop and the id parking run as the conversation's one transition, after a re-spawn: a start or resume of the
8791
+ // old backend in flight is over first, and none comes back beside the new one (review 22, own pass). Held as ending the conversation
8792
+ // it leaves: what a stop queued ahead held is dropped with the line, never resumed into the backend being left — the bridge was built
8793
+ // before the move and never carries it (review 23 #1, review 24 #1).
8794
+ const lostWork = await ending.run(() => switchThreadAdapter(key, backend === 'claude' ? (0, createAdapter_1.resolveClaudeBackendName)(key) : adapterNames_1.openCodeAdapterName, options));
8795
+ return (0, lostWork_1.checkHasLostBackgroundWork)(lostWork);
7914
8796
  }
7915
8797
  /**
7916
8798
  * @description The second half, after a move (across backends or between accounts): start or resume the topic's
@@ -7933,8 +8815,24 @@ async function resumeTopicOnNewSession(key, options) {
7933
8815
  const prompt = options.getFirstPrompt();
7934
8816
  if (prompt === null)
7935
8817
  return;
7936
- await deliverPromptOrBuffer(key, prompt.text, startupPromptBuffer.checkIsStarting(k));
7937
- await requestWakeUpEngine?.trackContinuationTurn(key, { isCountersReset: true, isRequestPrompt: prompt.isRequestPrompt });
8818
+ // The move's continuation is tracked — every open request's counters reset, a limit stop lifted — only once its first prompt reached a
8819
+ // session: at once when forwarded, at its replay when it waited in a startup window. One that reached none (no session left, or a
8820
+ // window that dropped it) starts no turn, and a watch tracked for it would wait for good (review 20 #1).
8821
+ // The requests whose prompts it carries are named as it was built, never read again at its replay (review 21 nit 3).
8822
+ const trackContinuation = () => requestWakeUpEngine?.trackContinuationTurn(key, { isCountersReset: true, carriedRequestIds: prompt.carriedRequestIds }) ?? Promise.resolve();
8823
+ const delivery = await deliverPromptOrBuffer(key, prompt.text, (outcome) => {
8824
+ if (outcome === 'replayed') {
8825
+ trackContinuation().catch((e) => console.error(`[fallback] ${k}: tracking the move's replayed first prompt failed:`, e instanceof Error ? e.message : e));
8826
+ return;
8827
+ }
8828
+ console.warn(`[fallback] ${k}: the first prompt after the move waited for a session start that dropped it; no turn is tracked for it`);
8829
+ });
8830
+ if (delivery === 'noSession') {
8831
+ console.warn(`[fallback] ${k}: the first prompt after the move reached no session; no turn is tracked for it`);
8832
+ return;
8833
+ }
8834
+ if (delivery === 'forwarded')
8835
+ await trackContinuation();
7938
8836
  }
7939
8837
  // ── a MANUAL switch between the two backends (`utils/backendSwitchPlan.ts`, `commands/backendSwitch.ts`) ──
7940
8838
  /** The backend family the topic's agent runs on now (its in-memory pick, else the persisted one); `null` for none or a shell. */
@@ -7967,7 +8865,7 @@ async function resolveBackendSwitchTarget(key, backend) {
7967
8865
  }
7968
8866
  /**
7969
8867
  * @description The gate every MANUAL start of the other backend goes through (`/claude`, `/opencode`, the agent
7970
- * buttons, the natural-language "start …" phrases): when the topic runs the other backend and holds a conversation,
8868
+ * buttons): when the topic runs the other backend and holds a conversation,
7971
8869
  * ask first and let the answer make the switch. Returns whether it asked — the caller then stops; `false` means
7972
8870
  * nothing to hand over (a fresh topic, the same backend, a shell) and the caller goes ahead as it always did.
7973
8871
  * `userMessage` is the text typed with the command; the switch passes it on inside the context bridge.
@@ -7992,25 +8890,45 @@ async function askBeforeCrossBackendSwitch(key, backend, userMessage) {
7992
8890
  * `/claude` / `/opencode` do. `userMessage` rides inside the bridge.
7993
8891
  */
7994
8892
  async function executeBackendSwitch(key, target, options) {
7995
- const bridge = options.isBridged
7996
- ? await buildFallbackBridge(key, {
7997
- fromLabel: formatThreadBackend(key),
7998
- toLabel: (0, backendSwitchPlan_1.formatBackendSwitchBridgeLabel)(target),
7999
- reason: 'manual',
8000
- resetsAtText: null,
8001
- userMessage: options.userMessage,
8002
- })
8003
- : null;
8004
- const isStoppingBackground = await moveTopicToOtherBackend(key, target.backend, target.backend === 'claude' && target.isProfilePicked ? target.profile : null);
8005
- // The operator hears that the background work died with the old session; its agent hears it in the first prompt.
8006
- if (isStoppingBackground)
8007
- await replyToThread(key, (0, i18n_1.t)('fallback.backgroundStopped'));
8008
- cancelApiRetry(key); // a wait armed for the backend just left is over
8009
- await resumeTopicOnNewSession(key, {
8010
- modelToPin: (0, backendSwitchPlan_1.getBackendSwitchModelToPin)(target),
8011
- getFirstPrompt: () => (bridge === null ? null : { text: bridge, isRequestPrompt: false }),
8012
- args: bridge === null ? options.userMessage : undefined,
8013
- });
8893
+ // A person's message is refused from here until the new backend took the move's first prompt (the bridge, or the start that carries the
8894
+ // text typed with the command), as in the limit move (review 25 #1) — the tap's hold refuses it until this takes over.
8895
+ const stopRefusingMessages = conversationEndings.refuseMessages(key);
8896
+ try {
8897
+ // The move ends the conversation it leaves: held from here, ahead of the bridge, unless the tap that asked for it holds it already —
8898
+ // a stop under way drops what it held instead of resuming the backend being left (review 24 #1).
8899
+ const ending = options.ending ?? conversationEndings.hold(key);
8900
+ // What the agent took in, read at the moment the bridge reads its transcript (review 27 nit 5).
8901
+ const promptsReachedOrHeld = requestWakeUpEngine?.readPromptsReachedOrHeld(key);
8902
+ let bridge;
8903
+ let isStoppingBackground;
8904
+ try {
8905
+ bridge = options.isBridged
8906
+ ? await buildFallbackBridge(key, {
8907
+ fromLabel: formatThreadBackend(key),
8908
+ toLabel: (0, backendSwitchPlan_1.formatBackendSwitchBridgeLabel)(target),
8909
+ reason: 'manual',
8910
+ resetsAtText: null,
8911
+ userMessage: options.userMessage,
8912
+ })
8913
+ : null;
8914
+ isStoppingBackground = await moveTopicToOtherBackend(key, ending, target.backend, target.backend === 'claude' && target.isProfilePicked ? target.profile : null, { promptsReachedOrHeld });
8915
+ }
8916
+ finally {
8917
+ ending.release();
8918
+ }
8919
+ // The operator hears that the background work died with the old session; its agent hears it in the first prompt.
8920
+ if (isStoppingBackground)
8921
+ await replyToThread(key, (0, i18n_1.t)('fallback.backgroundStopped'));
8922
+ cancelApiRetry(key); // a wait armed for the backend just left is over
8923
+ await resumeTopicOnNewSession(key, {
8924
+ modelToPin: (0, backendSwitchPlan_1.getBackendSwitchModelToPin)(target),
8925
+ getFirstPrompt: () => (bridge === null ? null : { text: bridge, carriedRequestIds: [] }),
8926
+ args: bridge === null ? options.userMessage : undefined,
8927
+ });
8928
+ }
8929
+ finally {
8930
+ stopRefusingMessages();
8931
+ }
8014
8932
  }
8015
8933
  /**
8016
8934
  * @description Whether a pick, made while a usage-limit wait is armed, names another model of the SAME Claude account that the
@@ -8056,7 +8974,9 @@ async function switchTopicByOperator(key, to) {
8056
8974
  from,
8057
8975
  to,
8058
8976
  currentFamily,
8059
- hasConversation: currentFamily !== null && currentFamily !== to.backend && await checkHasConversationToHandOver(key),
8977
+ // Read only where it decides: with a wait armed a pick on the other backend is the limit move whatever it finds, so nothing is read
8978
+ // ahead of the move's hold on the conversation (review 24, own pass).
8979
+ hasConversation: !isUsageLimitWaitArmed && currentFamily !== null && currentFamily !== to.backend && await checkHasConversationToHandOver(key),
8060
8980
  isPickBeyondLimit: isUsageLimitWaitArmed && await checkIsPickBeyondLimit(from, to),
8061
8981
  });
8062
8982
  const target = buildBackendSwitchTargetOfRung(to);
@@ -8072,8 +8992,7 @@ async function switchTopicByOperator(key, to) {
8072
8992
  }
8073
8993
  case 'sameFamily': {
8074
8994
  if (to.backend === 'opencode') {
8075
- const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8076
- const { isOk, message, setModelError } = await applyModelSelection(adapter, key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
8995
+ const { isOk, message, setModelError } = await applyModelSelection(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
8077
8996
  return isOk ? { kind: 'switched', text: message, label } : { kind: 'refused', text: (0, i18n_1.t)('cb.model_error', { error: setModelError ?? message }) };
8078
8997
  }
8079
8998
  const runningModel = readRunningModelBeforeMove(key, from, to);
@@ -8089,7 +9008,7 @@ async function switchTopicByOperator(key, to) {
8089
9008
  const modelToPin = (0, fallbackChain_1.getFallbackModelToPin)(to, runningModel);
8090
9009
  if (modelToPin === null)
8091
9010
  return { kind: 'switched', text: switchedText === '' && to.model !== null ? (0, i18n_1.t)('cb.model_set', { model: to.model }) : switchedText, label };
8092
- const { isOk, message, setModelError } = await applyModelSelection((0, createAdapter_1.getThreadAdapter)(key), key, modelToPin);
9011
+ const { isOk, message, setModelError } = await applyModelSelection(key, modelToPin);
8093
9012
  if (!isOk)
8094
9013
  return { kind: 'refused', text: (0, i18n_1.t)('cb.model_error', { error: setModelError ?? message }) };
8095
9014
  return { kind: 'switched', text: switchedText === '' ? message : `${switchedText}\n${message}`, label };
@@ -8110,7 +9029,8 @@ async function switchTopicByOperator(key, to) {
8110
9029
  const { askBackendSwitch, registerBackendSwitchCallbacks } = (0, backendSwitch_1.createBackendSwitch)({
8111
9030
  ...botCore,
8112
9031
  getCurrentFamily: getTopicBackendFamily,
8113
- performBackendSwitch: (key, target, options) => executeBackendSwitch(key, target, { isBridged: true, userMessage: options.userMessage }),
9032
+ holdConversationEnding: (key) => conversationEndings.hold(key),
9033
+ performBackendSwitch: (key, target, options) => executeBackendSwitch(key, target, { isBridged: true, userMessage: options.userMessage, ending: options.ending }),
8114
9034
  });
8115
9035
  /**
8116
9036
  * @description A tap on a «switch to …» button of a limit notice: honoured only while the thread's open offer
@@ -8134,20 +9054,52 @@ async function takeFallbackSwitchOffer(key, episodeId, index) {
8134
9054
  * refuses for the balance; otherwise the account is just kept off agents for an hour. The check runs beside the usage refresh
8135
9055
  * with a timeout of its own, so the answer is held for the longer of the two, never their sum. The refresh is waited for only
8136
9056
  * up to `claudeLaunchRefreshBudgetMs`; past it the cached figures are answered (an agent that waits on a silent tool call is
8137
- * dropped by its own client after 300 s).
9057
+ * dropped by its own client after 300 s). A query by worker ROLE (`/workers`, `utils/workerRoles.ts`) reads the role's default first:
9058
+ * a Claude role's model goes into the pick (the Fable window counts for a Fable role); an OpenCode role's model is checked against
9059
+ * the catalog, read beside the refresh within the same budget — an unread catalog never makes the role unavailable.
8138
9060
  */
8139
9061
  async function listClaudeProfilesForAgent(query) {
9062
+ const workerRoles = readWorkerRolesSettings();
9063
+ const isOpenCodeRole = query.role !== null && (0, workerRoles_2.resolveWorkerRole)(workerRoles, query.role).value.cli === 'opencode';
8140
9064
  // The agent launches its worker under whichever folder the answer names, so every folder is put right before it is named.
8141
9065
  for (const view of getClaudeProfileUsageViews())
8142
9066
  repairClaudeProfileFolder(view.configDir);
8143
9067
  const stoppedApiProfile = (0, claudeApiAgentStop_1.getApiProfileStoppedByAgent)(getClaudeProfileUsageViews(), query, Date.now());
8144
- await Promise.all([
9068
+ const [openCodeCatalog] = await Promise.all([
9069
+ isOpenCodeRole ? readOpenCodeCatalogForWorker() : Promise.resolve(null),
8145
9070
  (0, claudeUsageRefresher_1.refreshClaudeUsageForLaunch)(claudeUsageRefresher, { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, maxAgeMs: claudeUsageRefresher_1.claudeUsageOnDemandMaxAgeMs }),
8146
9071
  stoppedApiProfile === null
8147
9072
  ? Promise.resolve()
8148
9073
  : (0, claudeApiAgentStop_1.verifyClaudeApiAgentStop)(stoppedApiProfile, claudeApiAgentStopPorts).then(() => undefined, (e) => console.warn(`[credit] ${stoppedApiProfile}: checking an agent's stop report failed:`, e instanceof Error ? e.message : e)),
8149
9074
  ]);
8150
- return (0, claudeProfileUsageViews_1.buildClaudeProfilesCreditReport)(getClaudeProfileUsageViews(), query.model, Date.now(), { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()) });
9075
+ const report = (0, claudeProfileUsageViews_1.buildClaudeProfilesCreditReport)(getClaudeProfileUsageViews(), (0, workerRoles_2.getWorkerRolePickModel)(workerRoles, query.role, query.model), Date.now(), {
9076
+ currentProfile: query.currentProfile,
9077
+ isStoppedByLimit: query.isStoppedByLimit,
9078
+ lastRunEndedAtMs: query.lastRunEndedAtMs,
9079
+ chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()),
9080
+ });
9081
+ const worker = (0, workerRoles_2.buildWorkerRoleReportForQuery)(workerRoles, query.role, report.profiles, openCodeCatalog);
9082
+ return worker === null ? report : { ...report, worker };
9083
+ }
9084
+ /**
9085
+ * The OpenCode catalog for a worker role's check, waited for at most the launch refresh budget; `null` when it could not be read in
9086
+ * time (or failed) — the role is then NOT called unavailable. The adapter caches the list, so a recent read answers at once.
9087
+ */
9088
+ async function readOpenCodeCatalogForWorker() {
9089
+ let budgetTimer;
9090
+ const budget = new Promise((resolve) => {
9091
+ budgetTimer = setTimeout(() => resolve(null), claudeUsageRefresher_1.claudeLaunchRefreshBudgetMs);
9092
+ });
9093
+ const read = (async () => (await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getAvailableModels?.()) ?? null)().catch((e) => {
9094
+ console.warn('[workers] the OpenCode catalog is unavailable:', e instanceof Error ? e.message : e);
9095
+ return null;
9096
+ });
9097
+ try {
9098
+ return await Promise.race([read, budget]);
9099
+ }
9100
+ finally {
9101
+ clearTimeout(budgetTimer);
9102
+ }
8151
9103
  }
8152
9104
  const { registerFallbackChainCommands, registerFallbackChainCallbacks, openAutoSwitchView, runAutoSwitchCommand, applyAutoSwitch } = (0, fallbackChain_2.createFallbackChain)({
8153
9105
  ...botCore,
@@ -8168,6 +9120,12 @@ const { registerTodoCommands, registerTodoCallbacks } = (0, todo_1.createTodo)({
8168
9120
  getConversationLabel: getTodoConversationLabel,
8169
9121
  checkIsConversationAsleep: (conversationKey) => getTodoSessionActivity(conversationKey) === 'asleep',
8170
9122
  });
9123
+ // ── The limit reminders (`/limits_reminders`): `connectors/telegram/commands/limitReminders.ts`, `utils/limitRemindersScreenPlan.ts` ──
9124
+ const { registerLimitRemindersCommands, registerLimitRemindersCallbacks, openPicker: openLimitRemindersPicker, getRowLabel: getLimitRemindersRowLabel } = (0, limitReminders_1.createLimitReminders)({
9125
+ ...botCore,
9126
+ readInstanceLimitReminders: readLimitRemindersSettings,
9127
+ getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
9128
+ });
8171
9129
  const { registerLimitsBoardCommands, registerLimitsBoardCallbacks } = (0, limitsBoard_1.createLimitsBoard)({
8172
9130
  ...botCore,
8173
9131
  getInstanceTimezone: getCurrentTimezone,
@@ -8179,17 +9137,20 @@ const { registerLimitsBoardCommands, registerLimitsBoardCallbacks } = (0, limits
8179
9137
  listClaudeModels: async (key) => (await (0, createAdapter_1.getThreadAdapter)(key).getAvailableModels?.()) ?? [],
8180
9138
  runAutoSwitchCommand,
8181
9139
  getArmedLimitRetryFireAt,
9140
+ getRemindersRowLabel: getLimitRemindersRowLabel,
9141
+ openRemindersPicker: openLimitRemindersPicker,
8182
9142
  });
8183
9143
  const { registerClaudeAccountCommands, registerClaudeAccountCallbacks, checkIsAwaitingProfileName, cancelProfileNameCapture, submitProfileName, pickClaudeAccount, onClaudeProfileAuthStatus: recordClaudeProfileAuthStatus, onClaudeProfileApiKey: storeClaudeProfileApiKey, } = (0, claudeAccounts_1.createClaudeAccounts)({
8184
9144
  ...botCore,
8185
9145
  getDataDir: state_1.resolveDataDir,
8186
9146
  getInstanceTimezone: getCurrentTimezone,
8187
9147
  refreshClaudeUsage: (options) => claudeUsageRefresher.refreshAll(options),
8188
- syncClaudeProfiles: (options) => claudeProfileSync.sync(options),
9148
+ syncClaudeProfiles: (options) => syncClaudeProfilesAndRefusals(options),
8189
9149
  readClaudeAuthStatus: readClaudeAuthStatusUnder,
8190
9150
  startClaudeProfileLogin: (key, profile) => startClaudeAuthLogin(key, profile),
8191
9151
  applyClaudeProfile: applyClaudePickToThread,
8192
9152
  applyClaudeProfileEverywhere,
9153
+ noteClaudeAccountsChanged: () => noteClaudeProfileUsability(),
8193
9154
  switchTopicByOperator,
8194
9155
  detectOpenCodeProviders: async () => (0, fallbackChain_1.listOpenCodeProviders)((await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getAvailableModels?.()) ?? []),
8195
9156
  listOpenCodeModels: async () => (await (0, createAdapter_1.getAdapter)(adapterNames_1.openCodeAdapterName).getAvailableModels?.()) ?? [],
@@ -8230,6 +9191,7 @@ registerClaudeAccountCommands();
8230
9191
  registerTopicCommand();
8231
9192
  registerFallbackChainCommands();
8232
9193
  registerLimitsBoardCommands();
9194
+ registerLimitRemindersCommands();
8233
9195
  registerTodoCommands();
8234
9196
  registerSttCommands();
8235
9197
  const { registerSelfUpdateCommands, registerSelfUpdateCallbacks } = (0, selfUpdate_1.createSelfUpdate)({
@@ -8325,15 +9287,28 @@ async function handleSessionsList(key) {
8325
9287
  * Recovers the full session id from `threadSessionLists`; if the cache was
8326
9288
  * lost (bot restarted between showing the list and the pick), reports it
8327
9289
  * via `onExpired`. Returns the user-facing result message to send, or
8328
- * `null` when `onExpired` already handled the stale-cache case.
8329
- */
8330
- async function resumeSessionByIndex(key, idx, onExpired) {
8331
- const list = threadSessionLists.get((0, sessionKey_1.keyToString)(key));
8332
- if (!list || idx < 0 || idx >= list.length) {
9290
+ * `null` when `onExpired` already handled the stale-cache case. `ending` is the
9291
+ * button's hold on the conversation, taken ahead of its toast; the digit reply
9292
+ * has none, and the pick holds it here (review 24 #1).
9293
+ */
9294
+ async function resumeSessionByIndex(key, idx, onExpired, ending) {
9295
+ const sessionId = getListedSessionId(key, idx);
9296
+ if (sessionId === null) {
9297
+ ending?.release();
8333
9298
  await onExpired();
8334
9299
  return null;
8335
9300
  }
8336
- const sessionId = list[idx];
9301
+ // As the conversation's one transition: no ensure resumes the old conversation beside the pick, and no idle stop runs under it
9302
+ // (review 20 nit 3). A prompt that comes meanwhile routes to a wake, whose ensure waits for the pick in the same queue.
9303
+ return (ending ?? conversationEndings.hold(key)).run(() => resumePickedSession(key, sessionId));
9304
+ }
9305
+ /** The session id at `idx` in the thread's last shown `/sessions` list; `null` when that list is gone (a restart) or holds no such row. */
9306
+ function getListedSessionId(key, idx) {
9307
+ const list = threadSessionLists.get((0, sessionKey_1.keyToString)(key));
9308
+ return list !== undefined && idx >= 0 && idx < list.length ? list[idx] : null;
9309
+ }
9310
+ /** {@link resumeSessionByIndex}'s resume of the picked session, inside the conversation's transition. */
9311
+ async function resumePickedSession(key, sessionId) {
8337
9312
  // Pick-mode is armed only by `handleSessionsList` (binding-gated), but a
8338
9313
  // binding can vanish (/unbind) between listing and picking — resume must
8339
9314
  // never run against an unbound thread (no WORK_ROOT fallback).
@@ -8343,13 +9318,17 @@ async function resumeSessionByIndex(key, idx, onExpired) {
8343
9318
  const workDir = workDirDecision.workDir;
8344
9319
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8345
9320
  markNeedsNewMessage(key);
9321
+ // What the conversation being left took in, read off its process before the resume replaces it: the requests close only once the pick
9322
+ // came up (a failed pick keeps the conversation it meant to leave), and by then the probe reads the picked one (review 26 #1).
9323
+ const promptsReachedOrHeld = requestWakeUpEngine?.readPromptsReachedOrHeld(key);
8346
9324
  try {
8347
9325
  // The ONLY resume path that posts the "last N messages" context block —
8348
9326
  // silent re-attach (bot restart) and crash recovery must stay quiet.
8349
9327
  await adapter.resumeSession(key, workDir, sessionId, { isWithRecentContext: true });
8350
- // Another session took over this topic; it does not know the open request, and the question the idle compaction re-asked
8351
- // for the conversation it replaces would send its label into the picked one.
8352
- cancelConversationRequest(key);
9328
+ // Another session took over this topic; it does not know the open requests — a person whose words the agent never read is told
9329
+ // (review 26 #2) —, and the question the idle compaction re-asked for the conversation it replaces would send its label into the
9330
+ // picked one.
9331
+ cancelEndingConversationRequests(key, promptsReachedOrHeld);
8353
9332
  closeReAskedQuestion(key);
8354
9333
  closeSetAsideQuestionsInBackground(key);
8355
9334
  // Persist the PICKED id — without this the next restart re-attaches to
@@ -8395,14 +9374,20 @@ command('quitall', async (_ctx, key) => {
8395
9374
  let stopped = 0;
8396
9375
  let active = 0;
8397
9376
  // A Telegram command stops Telegram sessions only: a Jira issue's work is not this topic's to stop (J2b, R3).
8398
- for (const { key: bKey } of (0, foreignKeyFallbacks_1.getTelegramConversations)(state.listBindings())) {
8399
- cancelConversationRequest(bKey);
8400
- const result = stopAllAdaptersFor(bKey);
9377
+ const conversations = (0, foreignKeyFallbacks_1.getTelegramConversations)(state.listBindings());
9378
+ // Each topic as its one transition, after a re-spawn and marked as ended, as `/quit` (review 22 own pass, review 23 #1); the topics side
9379
+ // by side, so one waiting behind a long resume holds no other back, and each waits for its own processes' exits (review 23 nit 4).
9380
+ await Promise.all(conversations.map(async ({ key: bKey }) => {
9381
+ cancelEndingConversationRequests(bKey);
9382
+ const result = await conversationEndings.hold(bKey).run(async () => {
9383
+ const swept = await stopAndWaitAllAdaptersFor(bKey);
9384
+ // Same release-for-good semantics as `/quit`, per swept thread.
9385
+ await releaseConversationIds(bKey);
9386
+ return swept;
9387
+ });
8401
9388
  active += result.attempted;
8402
9389
  stopped += result.stopped.length;
8403
- // Same release-for-good semantics as `/quit`, per swept thread.
8404
- await releaseConversationIds(bKey);
8405
- }
9390
+ }));
8406
9391
  if (active === 0) {
8407
9392
  await replyToThread(key, (0, i18n_1.t)('quit_all.none_active'));
8408
9393
  return;
@@ -8440,54 +9425,58 @@ command(['quit', 'q'], async (_ctx, key) => {
8440
9425
  // does NOT go through releaseThreadSession (it stops adapters + clears ids
8441
9426
  // inline), so the cancel is wired here explicitly.
8442
9427
  cancelApiRetry(key);
8443
- cancelConversationRequest(key); // /quit ends the work → its open request closes silently
9428
+ // /quit ends the work: its open requests close, a person whose words the agent never read told (review 26 #2) — read now, while the
9429
+ // process is still the one that took them in or not.
9430
+ cancelEndingConversationRequests(key);
8444
9431
  cancelClaudeAuthLogin(key); // /quit teardown → kill any in-flight /login pty
8445
9432
  cancelOpenCodeOAuthLogin(key); // /quit teardown → kill any in-flight /connect oauth pty
8446
9433
  clearAuthNotice(key); // /quit teardown → retire any pinned logged-out notice
8447
- const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8448
- const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
8449
- const primaryActive = adapter.checkIsActive(key);
8450
- // Defensive: any *other* adapter that's also active for this thread is
8451
- // a leftover from a previous botched switch. Kill it first so it can't
8452
- // keep streaming after the user's "quit". Re-using the sweep helper
8453
- // instead of an open-coded loop avoids drift between the call sites.
8454
- const otherAdapters = (0, createAdapter_1.getKnownAdapterNames)().filter(n => n !== adapterName);
8455
- stopAllAdaptersFor(key, otherAdapters);
8456
- if (!primaryActive) {
8457
- // A sleeping conversation is released for good: the next message starts a fresh one.
8458
- if (getResumableSessionId(key) !== null) {
8459
- await releaseConversationIds(key);
8460
- await replyToThread(key, (0, i18n_1.t)('agent.sleeping_released'));
8461
- return;
9434
+ // As the conversation's one transition (it waits for a json-stream re-spawn first): a start, a resume or a re-spawn in flight is
9435
+ // over before /quit reads what runs, so none brings a process back for a conversation /quit released (review 22, own pass), and a
9436
+ // start or resume that comes after waits behind it. Marked as ending the conversation: a stop queued ahead drops what it held instead
9437
+ // of resuming the conversation for it (review 23 #1).
9438
+ const reply = await conversationEndings.hold(key).run(async () => {
9439
+ const adapter = (0, createAdapter_1.getThreadAdapter)(key);
9440
+ const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
9441
+ const primaryActive = adapter.checkIsActive(key);
9442
+ // Defensive: any *other* adapter that's also active for this thread is
9443
+ // a leftover from a previous botched switch. Kill it first so it can't
9444
+ // keep streaming after the user's "quit". Re-using the sweep helper
9445
+ // instead of an open-coded loop avoids drift between the call sites.
9446
+ const otherAdapters = (0, createAdapter_1.getKnownAdapterNames)().filter(n => n !== adapterName);
9447
+ stopAllAdaptersFor(key, otherAdapters);
9448
+ if (!primaryActive) {
9449
+ // A sleeping conversation is released for good: the next message gets the no-agent hint, /claude or /opencode starts a fresh one.
9450
+ if (getResumableSessionId(key) !== null) {
9451
+ await releaseConversationIds(key);
9452
+ return (0, i18n_1.t)('agent.sleeping_released');
9453
+ }
9454
+ return 'No agent running';
8462
9455
  }
8463
- await replyToThread(key, 'No agent running');
8464
- return;
8465
- }
8466
- markNeedsNewMessage(key);
8467
- // Close any still-pending OpenCode question on the server BEFORE the teardown
8468
- // below (a stopped session can't accept the reject; an unrejected question
8469
- // re-surfaces on the next reattach). No-op for Claude / no pending question.
8470
- adapter.rejectQuestion?.(key);
8471
- if (adapterName === 'claude') {
8472
- adapter.sendSignal(key, 'SIGINT');
8473
- await new Promise((r) => setTimeout(r, CLAUDE_DOUBLE_SIGINT_GAP_MS));
8474
- adapter.sendSignal(key, 'SIGINT');
8475
- // Explicit quit releases the session for good — no auto-reattach later.
8476
- await state.clearAgentSessionIds(key);
8477
- await replyToThread(key, (0, i18n_1.t)('agent.exit_signal_sent', { label: adapter.label }));
8478
- return;
8479
- }
8480
- // OpenCode, terminal, any future adapter: tear down via stopSession. «Stopped» is said once it is: a `/claude` sent on the
8481
- // reply must find the session gone, not «already running» — as one transition, so a start or resume waits behind it.
8482
- await sessionTransitions.run((0, sessionKey_1.keyToString)(key), async () => {
9456
+ markNeedsNewMessage(key);
9457
+ // Close any still-pending OpenCode question on the server BEFORE the teardown
9458
+ // below (a stopped session can't accept the reject; an unrejected question
9459
+ // re-surfaces on the next reattach). No-op for Claude / no pending question.
9460
+ adapter.rejectQuestion?.(key);
9461
+ if (adapterName === 'claude') {
9462
+ adapter.sendSignal(key, 'SIGINT');
9463
+ await new Promise((r) => setTimeout(r, CLAUDE_DOUBLE_SIGINT_GAP_MS));
9464
+ adapter.sendSignal(key, 'SIGINT');
9465
+ // Explicit quit releases the session for good — no auto-reattach later.
9466
+ await state.clearAgentSessionIds(key);
9467
+ return (0, i18n_1.t)('agent.exit_signal_sent', { label: adapter.label });
9468
+ }
9469
+ // OpenCode, terminal, any future adapter: tear down via stopSession. «Stopped» is said once it is: a `/claude` sent on the
9470
+ // reply must find the session gone, not «already running».
8483
9471
  if (adapter.stopSessionAndWait)
8484
9472
  await adapter.stopSessionAndWait(key);
8485
9473
  else
8486
9474
  adapter.stopSession(key);
9475
+ // Explicit quit releases the session for good — no auto-reattach later.
9476
+ await state.clearAgentSessionIds(key);
9477
+ return (0, i18n_1.t)('agent.stopped', { label: adapter.label });
8487
9478
  });
8488
- // Explicit quit releases the session for good — no auto-reattach later.
8489
- await state.clearAgentSessionIds(key);
8490
- await replyToThread(key, (0, i18n_1.t)('agent.stopped', { label: adapter.label }));
9479
+ await replyToThread(key, reply);
8491
9480
  });
8492
9481
  // ── tmux-style controls (Claude CLI) ──
8493
9482
  command('c', async (_ctx, key) => {
@@ -8726,8 +9715,8 @@ command('timestamps', async (_ctx, key, parsed) => {
8726
9715
  * Routing mirrors the plain-text handler via the shared choke points:
8727
9716
  * `ensureAgentSession` does the bind-check + start (returns `unbound` →
8728
9717
  * bind-required reply, same as every agent-facing path), then
8729
- * `deliverPromptOrBuffer` forwards (active) or buffers (mid-startup), reading
8730
- * the startup window AFTER the ensure so a freshly-started session forwards.
9718
+ * `deliverPromptByState` opens the request and routes the prompt at its write:
9719
+ * forwarded (active) or buffered (mid-startup, or behind a stop).
8731
9720
  */
8732
9721
  command('schedule', async (ctx, key, parsed) => {
8733
9722
  const text = parsed.argsText;
@@ -8755,10 +9744,7 @@ command('schedule', async (ctx, key, parsed) => {
8755
9744
  // Fresh-start notice (empty when the session was already active / starting).
8756
9745
  if (result.message)
8757
9746
  await replyToThread(key, result.message);
8758
- const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
8759
- const opening = await openTopicRequest(key, wrappedPrompt, { source: 'schedule', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) });
8760
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${wrappedPrompt}`, isStarting, undefined, { isPersonInput: true });
8761
- await settleTopicRequestAfterDelivery(key, opening, delivery);
9747
+ await deliverPromptByState(key, wrappedPrompt, { source: 'schedule', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) });
8762
9748
  });
8763
9749
  const reminderWizards = new Map();
8764
9750
  const { cancelReminderWizard, claimReminderTextCapture, expireReminderWizard, finishReminderWizard, registerReminderCommands, registerReminderCallbacks, } = (0, reminders_1.createReminders)({
@@ -8847,7 +9833,7 @@ const botCommands = new Set([
8847
9833
  'start', 'claude', 'opencode', 'oc', 'terminal', 'agent', 'sessions', 'resume', 'cancel', 'model', 'connect',
8848
9834
  'disconnect', 'stop', 'stopall', 'stop-all', 'quit-all', 'status', 'c', 'y', 'n', 'enter', 'up', 'down', 'tab', 'esc', 'escape', 'interrupt', 'output', 'clear_messages',
8849
9835
  'bind', 'topic', 'unbind', 'where', 'ls', 'list', 'new', 'whoami', 'version', 'help', 'language', 'lang',
8850
- 'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'compact_self_review', 'bot_skills', 'question_wait', 'topic_status', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
9836
+ 'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'compact_self_review', 'bot_skills', 'workers', 'worker_models', 'question_wait', 'topic_status', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'limits_reminders', 'limit_reminders', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
8851
9837
  'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update', 'access',
8852
9838
  ]);
8853
9839
  /**
@@ -8861,7 +9847,7 @@ const forwardedClearCommand = '/clear';
8861
9847
  // Text message handler — main conversational entrypoint
8862
9848
  // ═══════════════════════════════════════════════════════════════════════════════
8863
9849
  /**
8864
- * @description A talker's text — the one early branch, so no armed step, command, start phrase or guide of the admin path
9850
+ * @description A talker's text — the one early branch, so no armed step, command or guide of the admin path
8865
9851
  * can be reached by checks spread through the handler. What it does: it is refused if it is a slash text (agent slash
8866
9852
  * commands control the conversation, and the commands the bot owns were decided before the message got here); a pasted
8867
9853
  * OAuth callback URL is deleted as a secret, whoever sent it; a raw-shell topic is refused; otherwise it is a prompt like any
@@ -8899,8 +9885,8 @@ async function handleTalkerText(ctx, key) {
8899
9885
  const messageContext = getMessageContext(key, ctx.message);
8900
9886
  const intake = { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) };
8901
9887
  const sentAtMs = ctx.message.date * 1000;
8902
- if (startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key))) {
8903
- await bufferPromptDuringStartup(key, text, intake, messageContext);
9888
+ if (checkIsArrivalRoutedAtWrite(key)) {
9889
+ await deliverPromptDuringStartup(key, text, intake, messageContext);
8904
9890
  return;
8905
9891
  }
8906
9892
  if (adapter.checkIsActive(key)) {
@@ -8950,7 +9936,7 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
8950
9936
  const text = (0, utils_1.stripCommandBotMention)(ctx.message.text.trim());
8951
9937
  const kStr = (0, sessionKey_1.keyToString)(key);
8952
9938
  // A FORWARDED message is content, never control input: its words are somebody else's, so a `/quit` in it is not an
8953
- // order, a bare digit is not a pick or an answer, a phrase is not a start — the mark the agent reads says so. The routes
9939
+ // order, a bare digit is not a pick or an answer — the mark the agent reads says so. The routes
8954
9940
  // that take text as an ANSWER the bot asked for (a pasted code, a name, a key, a reminder's text) still take it.
8955
9941
  const isForwarded = (0, inbound_1.checkIsTelegramForward)(ctx.message);
8956
9942
  const isSlashText = !isForwarded && text.startsWith('/');
@@ -9071,13 +10057,15 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
9071
10057
  if (ctx.from !== undefined && (await handleRunnersAddressText(key, text, ctx.from)))
9072
10058
  return;
9073
10059
  // Session is mid-startup → buffer the prompt and replay it once the agent is
9074
- // ready, instead of dropping it into the "no agent running" guidance below.
9075
- if (startupPromptBuffer.checkIsStarting(kStr)) {
9076
- await bufferPromptDuringStartup(key, text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, getMessageContext(key, ctx.message));
10060
+ // ready, instead of dropping it into the "no agent running" guidance below. A
10061
+ // command ending or replacing the conversation → refused at the write, never the
10062
+ // guidance nor a write into the agent it ends (review 25 #1).
10063
+ if (checkIsArrivalRoutedAtWrite(key)) {
10064
+ await deliverPromptDuringStartup(key, text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, getMessageContext(key, ctx.message));
9077
10065
  return;
9078
10066
  }
9079
10067
  // Set when this very message bound the topic: its welcome is already the answer, so the idle-thread hint at the end
9080
- // stays out — but the message itself is still read as what it is (a start phrase starts the agent).
10068
+ // stays out.
9081
10069
  let isJustAutoBound = false;
9082
10070
  // Audit S2 / #5: if `forum_topic_created` was emitted by a non-allowed
9083
10071
  // admin, we stashed the topic name in `pendingTopicNames` without
@@ -9130,12 +10118,11 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
9130
10118
  // Numeric model selection after `/model`.
9131
10119
  // Audit S12 / #20: previous code returned only when `adapter.setModel` was
9132
10120
  // truthy; on adapters that don't implement it (legacy void return) execution
9133
- // fell through and the same numeric reply was re-processed as a
9134
- // natural-language start + forwarded to the agent. `applyNumberedModelPick`
10121
+ // fell through and the same numeric reply was forwarded to the agent as a prompt. `applyNumberedModelPick`
9135
10122
  // always replies (even for the unsupported case), so we always return after a
9136
10123
  // numeric pick — the user clearly intended a model pick, not a prompt.
9137
10124
  if (!isForwarded && /^\d+$/.test(text) && awaitingModelSelection.has(kStr)) {
9138
- await applyNumberedModelPick(adapter, key, parseInt(text, 10));
10125
+ await applyNumberedModelPick(key, parseInt(text, 10));
9139
10126
  return;
9140
10127
  }
9141
10128
  // Session-pick mode (armed by `/sessions` / `/resume`). Only while the
@@ -9166,41 +10153,6 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
9166
10153
  // passthrough: not a number — exit pick-mode and let normal handling run.
9167
10154
  awaitingSessionSelection.delete(kStr);
9168
10155
  }
9169
- // Natural-language start.
9170
- if (!isForwarded && !adapter.checkIsActive(key)) {
9171
- const startMatch = (0, agentTrigger_1.parseAgentTrigger)(text);
9172
- if (startMatch.isMatch && startMatch.adapterName) {
9173
- if (checkIsGeneral(key)) {
9174
- await replyToThread(key, (0, i18n_1.t)('error.start_in_general'));
9175
- return;
9176
- }
9177
- // The other backend, with a conversation to hand over: ask first (a shell is no backend to hand over to).
9178
- const requestedFamily = (0, backendSwitchPlan_1.getBackendFamily)(startMatch.adapterName);
9179
- if (requestedFamily !== null && state.getBinding(key) && await askBeforeCrossBackendSwitch(key, requestedFamily, startMatch.args))
9180
- return;
9181
- // The shared `ensureAgentSession` does the bind-check + switch + start.
9182
- // The explicit matched adapter wins (`preferredAdapterName`), named the way
9183
- // `/claude` names it: `claude` is the topic's Claude backend, never the bare
9184
- // tmux one. The phrase's trailing args ride along. On `unbound` we keep this
9185
- // path's own reply: the folder picker (plan §11 Этап 4 — starting without a
9186
- // binding would silently launch against WORK_ROOT, which is almost never wanted).
9187
- const result = await ensureAgentSession(key, {
9188
- preferredAdapterName: (0, createAdapter_1.resolveStartAdapterName)(key, startMatch.adapterName),
9189
- args: startMatch.args,
9190
- });
9191
- if (!result.ok && result.reason === 'unbound') {
9192
- const subdirs = listAvailableSubdirs(ENV.workRoot);
9193
- const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
9194
- await replyToThread(key, (0, i18n_1.t)('thread.no_binding'), extra);
9195
- return;
9196
- }
9197
- // Empty when a self-greeting agent started (its banner is the cue) — guard
9198
- // like the /schedule consumer so we never post a blank message.
9199
- if (result.message)
9200
- await replyToThread(key, result.message);
9201
- return;
9202
- }
9203
- }
9204
10156
  // Claude TUI prompt on screen + a bare control reply (option digit or y/n)
9205
10157
  // → drive it in place. `getClaudeReplyRoute` decides precedence: a real
9206
10158
  // AskUserQuestion SELECTOR wins for a control reply; free-form prose breaks
@@ -9331,7 +10283,7 @@ bot.on((0, filters_1.message)('voice'), async (ctx) => {
9331
10283
  });
9332
10284
  /**
9333
10285
  * @description Background worker for a single voice note: download → transcribe
9334
- * → status emit → (buffer / start-agent-phrase / binding checks / forward).
10286
+ * → status emit → (buffer / binding checks / forward).
9335
10287
  * Byte-for-byte the old voice handler's post-gate body — moved verbatim out of
9336
10288
  * the handler so it runs OFF the telegraf update loop (per-thread serialized).
9337
10289
  * Uses only `key`/`bot`, never the request `ctx`, so it survives past the
@@ -9401,7 +10353,7 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
9401
10353
  return;
9402
10354
  // `/reminders` step 4 accepts a voice note as well as typed text, so the
9403
10355
  // transcript is routed here — right after the 🎤 echo and BEFORE the
9404
- // startup-buffer / natural-language-start / binding gates, which would
10356
+ // startup-buffer / binding gates, which would
9405
10357
  // otherwise treat it as a prompt. Same single creation path as the text side.
9406
10358
  // The step is an ADMIN's: a topic member's voice note neither fills it nor closes it when it has expired — it goes on as a prompt.
9407
10359
  const reminderVoiceRoute = (0, messageContext_1.checkIsForeignWords)(messageContext) ? null : claimReminderTextCapture(key);
@@ -9411,41 +10363,12 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
9411
10363
  }
9412
10364
  if (reminderVoiceRoute === 'expired')
9413
10365
  await expireReminderWizard(key);
9414
- // Session is mid-startup → buffer the transcript and replay it once ready.
9415
- if (startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key))) {
9416
- await bufferPromptDuringStartup(key, transcript, { source: 'voice', requesterId }, messageContext);
10366
+ // Session is mid-startup → buffer the transcript and replay it once ready; a command ends or replaces the conversation → refused at
10367
+ // the write (review 25 #1: a transcript is ready seconds after its voice note, often while a move or a release runs).
10368
+ if (checkIsArrivalRoutedAtWrite(key)) {
10369
+ await deliverPromptDuringStartup(key, transcript, { source: 'voice', requesterId }, messageContext);
9417
10370
  return;
9418
10371
  }
9419
- // A FORWARDED voice note saying «Claude», or a topic member's, is somebody else's words, not the operator's order to start an agent.
9420
- if (!(0, messageContext_1.checkIsForeignWords)(messageContext) && !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)) {
9421
- const startMatch = (0, agentTrigger_1.parseAgentTrigger)(transcript);
9422
- if (startMatch.isMatch && startMatch.adapterName) {
9423
- if (checkIsGeneral(key)) {
9424
- await replyToThread(key, (0, i18n_1.t)('error.start_in_general'));
9425
- return;
9426
- }
9427
- const requestedFamily = (0, backendSwitchPlan_1.getBackendFamily)(startMatch.adapterName);
9428
- if (requestedFamily !== null && state.getBinding(key) && await askBeforeCrossBackendSwitch(key, requestedFamily, startMatch.args))
9429
- return;
9430
- // Same choke point as the text trigger (L-D4): a sleeping conversation is
9431
- // woken, never replaced by a fresh start; `unbound` keeps the folder picker.
9432
- const result = await ensureAgentSession(key, {
9433
- preferredAdapterName: (0, createAdapter_1.resolveStartAdapterName)(key, startMatch.adapterName),
9434
- args: startMatch.args,
9435
- });
9436
- if (!result.ok && result.reason === 'unbound') {
9437
- const subdirs = listAvailableSubdirs(ENV.workRoot);
9438
- const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
9439
- await replyToThread(key, (0, i18n_1.t)('thread.no_binding'), extra);
9440
- return;
9441
- }
9442
- // Empty for a self-greeting agent (Claude self-announces) — the typing
9443
- // loader covers the gap; show a notice only when there's ready text.
9444
- if (result.message)
9445
- await replyToThread(key, result.message);
9446
- return;
9447
- }
9448
- }
9449
10372
  // A voice prompt wakes a sleeping conversation like a text one does (L-D4).
9450
10373
  if (!(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) && !(await resumeSleepingSessionForPrompt(key))) {
9451
10374
  await sendNoAgentGuidance(key, messageContext?.nonOperatorSender !== undefined, (text, extra) => replyToThread(key, text, extra));
@@ -9522,9 +10445,13 @@ async function sendNoAgentGuidance(key, isFromTalker, sendHint) {
9522
10445
  * album path can dedupe it to once-per-album; the single-file path passes
9523
10446
  * `replyToThread` verbatim.
9524
10447
  */
9525
- async function checkFileIntakeGatePassed(key, isStarting, sendHint, isFromTalker) {
9526
- const adapter = (0, createAdapter_1.getThreadAdapter)(key);
9527
- if (isStarting || adapter.checkIsActive(key))
10448
+ async function checkFileIntakeGatePassed(key, sendHint, isFromTalker) {
10449
+ // A command ends or replaces the conversation: the file is not delivered, and nothing is downloaded for it (review 25 #1).
10450
+ if (conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key))) {
10451
+ await sendHint((0, i18n_1.t)('agent.queued_prompt_dropped_by_command'));
10452
+ return false;
10453
+ }
10454
+ if (startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)) || (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key))
9528
10455
  return true;
9529
10456
  // A file sent to a sleeping conversation wakes it (L-D4) and is taken in by the resumed session.
9530
10457
  if (await resumeSleepingSessionForPrompt(key, sendHint))
@@ -9583,31 +10510,57 @@ async function downloadIncomingFile(ctx, key, meta, onError) {
9583
10510
  }
9584
10511
  }
9585
10512
  /**
9586
- * @description Deliver one already-built prompt to the thread's agent,
9587
- * honouring the startup window (`utils/promptDelivery.ts`): mid-startup the
9588
- * prompt is buffered, otherwise it is forwarded immediately through the normal
9589
- * choke point. This is the single "buffer-or-forward" unit shared by the text and
9590
- * voice handlers' mid-startup buffering, file/album intake, the `/schedule` command
9591
- * (S7), the Jira connector's posts and an API-error retry's "continue" nudge, so the
9592
- * startup-window handling never drifts between them.
10513
+ * @description Deliver one already-built prompt to the thread's agent, routed at the moment of the write
10514
+ * (`utils/promptDelivery.ts`): behind an open start or stop window it is buffered, into a live session it is forwarded through the
10515
+ * normal choke point, and a conversation with neither is woken first. The single "buffer-or-forward" unit of every prompt that may
10516
+ * meet a start or a stop — the person's prompts through {@link deliverPromptByState}'s buffer step, a scheduled run, the Jira
10517
+ * connector's posts, the lost-work post, an API-error retry's "continue" nudge and a move's first prompt — so the window handling
10518
+ * never drifts between them, and no caller hands it a state it read before an await.
9593
10519
  */
9594
10520
  const promptDeliveryDeps = {
9595
10521
  startupBuffer: startupPromptBuffer,
9596
- forwardPrompt: (key, text, options) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isPersonInput: options.isPersonInput }),
10522
+ forwardPrompt: (key, text, options) => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isPersonInput: options.isPersonInput, isAccountsNoteCarrier: options.isAccountsNoteCarrier, lostWorkTelling: options.lostWorkTelling, waitBeforeRoute: options.waitBeforeRoute }),
10523
+ checkIsSessionActive: (key) => checkIsAcceptingInput(key),
10524
+ // A tracker conversation has no topic to say a resume's notice in: it is logged.
10525
+ wakeSession: (key) => ((0, sessionKeyCodec_1.checkIsTelegramKey)(key)
10526
+ ? wakeSleepingSessionForPrompt(key)
10527
+ : wakeSleepingSessionForPrompt(key, async (notice) => { console.log(`[promptDelivery] ${(0, sessionKey_1.keyToString)(key)}: ${notice}`); })),
10528
+ checkIsRefusingMessages: (key) => conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key)),
10529
+ reportNoSession: async (key, isAlreadyTold, options) => {
10530
+ console.warn(`[promptDelivery] ${(0, sessionKey_1.keyToString)(key)}: no session is left to take the prompt, and nothing could be woken for it`);
10531
+ // Only a person's own prompt is theirs to be told about; what the bot made says so in its own way (its caller reads `noSession`).
10532
+ if (options.isPersonInput === true && !isAlreadyTold)
10533
+ await replyToThread(key, (0, i18n_1.t)('agent.no_session'));
10534
+ },
10535
+ reportRefused: async (key, options) => {
10536
+ console.warn(`[promptDelivery] ${(0, sessionKey_1.keyToString)(key)}: a command ends or replaces the conversation; the prompt is not delivered`);
10537
+ if (options.isPersonInput === true)
10538
+ await replyToThread(key, (0, i18n_1.t)('agent.queued_prompt_dropped_by_command'));
10539
+ },
9597
10540
  announceQueued: async (key) => {
9598
10541
  await replyToThread(key, (0, i18n_1.t)('agent.queued_starting', { label: (0, createAdapter_1.getThreadAdapter)(key).label }));
9599
10542
  },
9600
10543
  };
9601
- function deliverPromptOrBuffer(key, promptText, isStarting, onBufferedSettled, options = {}) {
9602
- return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, isStarting, onBufferedSettled, options);
10544
+ /**
10545
+ * @description Whether a prompt written now reaches `key`'s live process (`AgentAdapter.checkIsAcceptingInput`, else `checkIsActive`): a
10546
+ * process a release or a move is stopping opens no window, and a prompt written into it is abandoned while its request reads it as
10547
+ * written — routed as no live session, it wakes the conversation, whose ensure waits behind that stop (review 24 nit 3).
10548
+ */
10549
+ function checkIsAcceptingInput(key) {
10550
+ const adapter = (0, createAdapter_1.getThreadAdapter)(key);
10551
+ return adapter.checkIsAcceptingInput?.(key) ?? adapter.checkIsActive(key);
10552
+ }
10553
+ function deliverPromptOrBuffer(key, promptText, onBufferedSettled, options = {}) {
10554
+ return (0, promptDelivery_1.deliverPromptOrBuffer)(promptDeliveryDeps, key, promptText, onBufferedSettled, options);
9603
10555
  }
9604
10556
  /**
9605
10557
  * @description Per-(thread, media_group) album batcher. Telegram delivers an
9606
10558
  * album as N messages sharing `media_group_id` in a quick burst; this coalesces
9607
10559
  * them so the agent gets ONE combined prompt after the burst settles, and gating
9608
- * / error hints fire once per album. The flush forwards the combined prompt
9609
- * through {@link deliverPromptOrBuffer}, re-reading the startup state AT FLUSH TIME
9610
- * so a session that finished booting mid-burst forwards instead of buffers.
10560
+ * / error hints fire once per album. The flush delivers the combined prompt
10561
+ * through {@link deliverPromptByState}, routed at its write — after the flush's
10562
+ * request is opened — so a session that finished booting (or stopping) mid-burst
10563
+ * takes it the way it stands then.
9611
10564
  */
9612
10565
  const albumCollector = (0, mediaGroupCollector_1.createMediaGroupCollector)({
9613
10566
  debounceMs: ALBUM_DEBOUNCE_MS,
@@ -9623,17 +10576,13 @@ const albumCollector = (0, mediaGroupCollector_1.createMediaGroupCollector)({
9623
10576
  const caption = orderedItems.find((item) => item.caption && item.caption.trim())?.caption;
9624
10577
  const messageContext = orderedItems.find((item) => item.messageContext)?.messageContext;
9625
10578
  const promptText = (0, fileIntake_1.buildAlbumPromptText)(files, caption);
9626
- const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
9627
10579
  // User took over (album upload) before a pending API-error retry fired →
9628
10580
  // cancel it silently, like the text/voice handlers.
9629
10581
  cancelApiRetry(key);
9630
- // A user album is genuine user activity → clear the compact-on-idle latch (D2).
10582
+ // A user album is genuine user activity: the idle countdown restarts.
9631
10583
  notePersonActivity(key);
9632
10584
  try {
9633
- const opening = await openTopicRequest(key, promptText, { source: 'album', requesterId: orderedItems[0].requesterId }, messageContext);
9634
- const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
9635
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
9636
- await settleTopicRequestAfterDelivery(key, opening, delivery);
10585
+ await deliverPromptByState(key, promptText, { source: 'album', requesterId: orderedItems[0].requesterId }, undefined, messageContext);
9637
10586
  }
9638
10587
  catch (err) {
9639
10588
  // The files were downloaded already (each item before the flush): what failed is the album's prompt.
@@ -9663,10 +10612,9 @@ function parseAlbumGroupKey(groupKey) {
9663
10612
  */
9664
10613
  async function handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker) {
9665
10614
  const groupKey = buildAlbumGroupKey(key, mediaGroupId);
9666
- const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
9667
10615
  // Gate per item, but reply at most once per album. The guard is claimed
9668
10616
  // lazily so a passing gate never burns the one-shot slot.
9669
- const gatePassed = await checkFileIntakeGatePassed(key, isStarting, async (text, extra) => {
10617
+ const gatePassed = await checkFileIntakeGatePassed(key, async (text, extra) => {
9670
10618
  if (albumCollector.checkShouldAnnounceOnce(groupKey)) {
9671
10619
  await replyToThread(key, text, extra);
9672
10620
  }
@@ -9701,8 +10649,7 @@ async function handleIncomingFile(ctx, key, isFromTalker) {
9701
10649
  await handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker);
9702
10650
  return;
9703
10651
  }
9704
- const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
9705
- const gatePassed = await checkFileIntakeGatePassed(key, isStarting, (text, extra) => replyToThread(key, text, extra), isFromTalker);
10652
+ const gatePassed = await checkFileIntakeGatePassed(key, (text, extra) => replyToThread(key, text, extra), isFromTalker);
9706
10653
  if (!gatePassed)
9707
10654
  return;
9708
10655
  const savedPath = await downloadIncomingFile(ctx, key, meta, (text) => replyToThread(key, text));
@@ -9712,14 +10659,11 @@ async function handleIncomingFile(ctx, key, isFromTalker) {
9712
10659
  // User took over (file upload) before a pending API-error retry fired →
9713
10660
  // cancel it silently, like the text/voice handlers.
9714
10661
  cancelApiRetry(key);
9715
- // A user file is genuine user activity → clear the compact-on-idle latch (D2).
10662
+ // A user file is genuine user activity: the idle countdown restarts.
9716
10663
  notePersonActivity(key);
9717
10664
  // A file sent as a REPLY carries the message it answers, a forwarded one its origin, as a typed or spoken message does.
9718
10665
  const messageContext = getMessageContext(key, ctx.message);
9719
- const opening = await openTopicRequest(key, promptText, { source: 'file', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, messageContext);
9720
- const quotedPrompt = getPromptWithThreadMessageContext(key, promptText, messageContext);
9721
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${quotedPrompt}`, isStarting, undefined, { isPersonInput: true });
9722
- await settleTopicRequestAfterDelivery(key, opening, delivery);
10666
+ await deliverPromptByState(key, promptText, { source: 'file', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, undefined, messageContext);
9723
10667
  }
9724
10668
  bot.on(
9725
10669
  // anyOf-composed per-kind filter — `message('photo', 'document', …)` would
@@ -9763,34 +10707,36 @@ bot.on('edited_message', async (ctx) => {
9763
10707
  // my_chat_member — auto-welcome when the bot is added to the group (§20.2)
9764
10708
  // ═══════════════════════════════════════════════════════════════════════════════
9765
10709
  /**
9766
- * @description Detect when *this* bot is added to the configured group and
9767
- * post a setup checklist into General. Without this, a fresh deployment is
10710
+ * @description Detect when *this* bot JOINS the configured group and
10711
+ * post the greeting into General (`formatGroupWelcome`: what the bot is, the
10712
+ * version that runs, the setup steps). Without this, a fresh deployment is
9768
10713
  * silent: the user adds the bot, sees nothing, and has to dig through the
9769
- * README to find out what permissions / privacy flags they need to flip.
10714
+ * README to find out what rights the bot needs.
9770
10715
  *
9771
10716
  * Filters:
9772
10717
  * - chat must be the allowlisted group (we don't react in foreign chats),
9773
10718
  * - the member that changed must be us (other admins being promoted etc.
9774
10719
  * are not interesting),
9775
- * - new status must be `member` or `administrator` — `kicked`/`left`
9776
- * events would only generate noise.
10720
+ * - the change must be a join (`checkHasJoinedGroup`): out of the group
10721
+ * before, a member or an administrator now. The greeting's own steps —
10722
+ * make the bot an admin, add a right `/doctor` asked for — are
10723
+ * `my_chat_member` changes too, and must not bring it back.
9777
10724
  */
9778
10725
  bot.on('my_chat_member', async (ctx) => {
9779
10726
  const chat = ctx.chat;
9780
10727
  if (!chat || chat.id !== getAllowedGroupId())
9781
10728
  return;
9782
10729
  const upd = ctx.update.my_chat_member;
9783
- const newMember = upd.new_chat_member;
9784
10730
  const botId = bot.botInfo?.id;
9785
- if (!botId || newMember.user.id !== botId)
10731
+ if (!botId || upd.new_chat_member.user.id !== botId)
9786
10732
  return;
9787
- if (newMember.status !== 'member' && newMember.status !== 'administrator')
10733
+ if (!(0, inbound_1.checkHasJoinedGroup)(upd.old_chat_member, upd.new_chat_member))
9788
10734
  return;
9789
10735
  // We don't know which message_thread_id General actually has on this
9790
10736
  // group (it can be 1, or undefined for non-forum chats). For a forum
9791
10737
  // supergroup it's always the constant `GENERAL_THREAD_ID = 1`.
9792
10738
  const generalKey = (0, sessionKeyCodec_1.makeTelegramKey)(chat.id, threadRouting_1.GENERAL_THREAD_ID);
9793
- await replyToThread(generalKey, (0, i18n_1.t)('onboarding.welcome', { workRoot: ENV.workRoot }), { parse_mode: 'Markdown' });
10739
+ await replyToThread(generalKey, (0, groupWelcome_1.formatGroupWelcome)(i18n_1.t, { workRoot: ENV.workRoot }), { parse_mode: 'Markdown' });
9794
10740
  });
9795
10741
  // ═══════════════════════════════════════════════════════════════════════════════
9796
10742
  // chat_member — admin promotion/demotion invalidates the admin cache
@@ -9911,7 +10857,7 @@ bot.on((0, filters_1.message)('forum_topic_edited'), async (ctx) => {
9911
10857
  // The bot's OWN rename (its status mark) comes back as this service message: never an owner's rename (stored as a name) nor a
9912
10858
  // stranger's (a `[security]` line) — only a line to delete, so the topic shows no trace of the change.
9913
10859
  if (userId !== undefined && userId === bot.botInfo?.id) {
9914
- await topicIndicator.handleOwnRenameLine(key, ctx.message.message_id);
10860
+ await topicIndicator.handleOwnRenameLine(key, ctx.message.message_id, newName);
9915
10861
  return;
9916
10862
  }
9917
10863
  if (!userId || !(await checkIsAllowedUser(ctx))) {
@@ -9964,7 +10910,7 @@ async function applyRenamesThatWaitedForColdStart() {
9964
10910
  continue;
9965
10911
  const senderId = renamed.from?.id;
9966
10912
  if (senderId !== undefined && senderId === botUserId) {
9967
- await topicIndicator.handleOwnRenameLine(key, renamed.message_id);
10913
+ await topicIndicator.handleOwnRenameLine(key, renamed.message_id, renamed.forum_topic_edited.name);
9968
10914
  continue;
9969
10915
  }
9970
10916
  if (!state.getBinding(key))
@@ -10112,8 +11058,16 @@ bot.action(bindPicker_1.bindLeaveCurrentCallback, async (ctx) => {
10112
11058
  // Claimed like a bind: two taps in a row unbind once, and a picker a bind holds is no more a place to leave from.
10113
11059
  const pickerMessageId = (0, callbackMessage_1.getCallbackMessageId)(ctx);
10114
11060
  const run = await bindPickerClaims.runClaimed(key, pickerMessageId, async () => {
10115
- await (0, callbackToast_1.answerCallbackQuerySafely)(ctx);
10116
- await unbindThread(key);
11061
+ // Leaving the folder ends the conversation, known at the tap: held from here, ahead of the toast and the leave's paced sends, so a stop
11062
+ // under way drops what it held instead of resuming the conversation for it in the folder being left (review 24 #1).
11063
+ const ending = conversationEndings.hold(key);
11064
+ try {
11065
+ await (0, callbackToast_1.answerCallbackQuerySafely)(ctx);
11066
+ await unbindThread(key, ending);
11067
+ }
11068
+ finally {
11069
+ ending.release();
11070
+ }
10117
11071
  if (pickerMessageId !== null)
10118
11072
  await removeBindPicker(key, pickerMessageId);
10119
11073
  await closeOpenBindMessages(key);
@@ -10296,6 +11250,7 @@ registerCompactionCallbacks();
10296
11250
  registerQuestionSetAsideCallbacks(bot);
10297
11251
  registerAutoContinueLimitsCallbacks();
10298
11252
  registerBotSkillsCallbacks();
11253
+ registerWorkerRolesCallbacks();
10299
11254
  registerQuestionWaitCallbacks();
10300
11255
  registerTopicStatusCallbacks();
10301
11256
  registerTopicAccessCallbacks();
@@ -10305,6 +11260,7 @@ registerBackendSwitchCallbacks();
10305
11260
  registerClaudeAccountCallbacks();
10306
11261
  registerFallbackChainCallbacks();
10307
11262
  registerLimitsBoardCallbacks();
11263
+ registerLimitRemindersCallbacks();
10308
11264
  registerTodoCallbacks();
10309
11265
  registerSttCallbacks();
10310
11266
  registerSelfUpdateCallbacks();
@@ -10376,12 +11332,21 @@ bot.action(/^agent_(.+)$/, async (ctx) => {
10376
11332
  // Resolve up-front so an unknown name throws into the catch (→ "unknown
10377
11333
  // agent") before any side effect, and so the toast can name the label.
10378
11334
  const adapter = (0, createAdapter_1.getAdapter)(adapterName);
10379
- await ctx.answerCbQuery((0, i18n_1.t)('cb.agent_switched', { label: adapter.label }));
10380
- // One-tap start: switch + start the agent (was select-only — the user then
10381
- // had to type /claude). `handleAgentStart` owns the General / binding /
10382
- // already-active guards and the self-greeting ready-text suppression, and
10383
- // `switchThreadAdapter` inside it persists the adapter choice.
10384
- await handleAgentStart(key, adapterName);
11335
+ // A tap onto a shell from an agent's conversation ends it, known now: held ahead of the toast, so a stop under way drops what it held
11336
+ // instead of resuming the conversation for it (review 24, own pass). Onto the other agent the hand-over read decides first.
11337
+ const startAdapterName = (0, createAdapter_1.resolveStartAdapterName)(key, adapterName);
11338
+ const ending = (0, backendSwitchPlan_1.getBackendFamily)(startAdapterName) === null && checkIsStartLeavingConversation(key, startAdapterName) ? conversationEndings.hold(key) : undefined;
11339
+ try {
11340
+ await ctx.answerCbQuery((0, i18n_1.t)('cb.agent_switched', { label: adapter.label }));
11341
+ // One-tap start: switch + start the agent (was select-only — the user then
11342
+ // had to type /claude). `handleAgentStart` owns the General / binding /
11343
+ // already-active guards and the self-greeting ready-text suppression, and
11344
+ // `switchThreadAdapter` inside it persists the adapter choice.
11345
+ await handleAgentStart(key, adapterName, undefined, ending);
11346
+ }
11347
+ finally {
11348
+ ending?.release();
11349
+ }
10385
11350
  if (state.getBinding(key)) {
10386
11351
  await updatePinnedStatus(key).catch(() => { });
10387
11352
  }
@@ -10408,15 +11373,23 @@ bot.action(/^resume_(\d+)$/, async (ctx) => {
10408
11373
  await ctx.answerCbQuery((0, i18n_1.t)('cb.access_denied'));
10409
11374
  return;
10410
11375
  }
10411
- await ctx.answerCbQuery();
10412
11376
  const idx = Number(ctx.match[1]);
10413
- // A pick from the button also closes pick-mode (mirrors a digit reply).
10414
- awaitingSessionSelection.delete((0, sessionKey_1.keyToString)(key));
10415
- const result = await resumeSessionByIndex(key, idx, async () => {
10416
- await replyToThread(key, (0, i18n_1.t)('session.expired'));
10417
- });
10418
- if (result !== null)
10419
- await replyToThread(key, result);
11377
+ // The pick replaces the conversation, known at the tap: held ahead of the toast, so a stop under way drops what it held instead of
11378
+ // resuming the conversation the pick leaves (review 24 #1). A row the list no longer has replaces nothing.
11379
+ const ending = getListedSessionId(key, idx) === null ? undefined : conversationEndings.hold(key);
11380
+ try {
11381
+ await ctx.answerCbQuery();
11382
+ // A pick from the button also closes pick-mode (mirrors a digit reply).
11383
+ awaitingSessionSelection.delete((0, sessionKey_1.keyToString)(key));
11384
+ const result = await resumeSessionByIndex(key, idx, async () => {
11385
+ await replyToThread(key, (0, i18n_1.t)('session.expired'));
11386
+ }, ending);
11387
+ if (result !== null)
11388
+ await replyToThread(key, result);
11389
+ }
11390
+ finally {
11391
+ ending?.release();
11392
+ }
10420
11393
  });
10421
11394
  // The agent's own question buttons (`qa_`, and `reask_` in the compaction module) are the taps a talker may make: they answer the
10422
11395
  // agent, so they ask the speaker gate; every other button — `opt_`, which types a digit into whatever a Claude TUI shows, included —
@@ -10492,14 +11465,26 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
10492
11465
  }
10493
11466
  });
10494
11467
  /**
10495
- * @description Buffer a free-form prompt (text OR voice) that arrived while the
10496
- * thread's session is starting — the startup twin of {@link deliverActivePrompt}.
10497
- * The request is opened at capture time (S7), so the buffered text carries its
10498
- * header; the message-context block is folded in here too, since the replay forwards
10499
- * the buffered text as is and a REPLY or a FORWARD made during the boot would
10500
- * otherwise reach the agent without the message it points at, or as the operator's own words.
11468
+ * @description Whether a person's text or voice note that arrives now takes {@link deliverPromptDuringStartup}'s route — routed only at
11469
+ * its write — rather than the live-agent route or the no-agent guidance: the session is starting or being stopped (its window open), or a
11470
+ * command ends or replaces the conversation (`ConversationEndings.checkIsRefusingMessages`: the write refuses it, its request closed and
11471
+ * the person told — never written into the agent the command ends, never «Run /claude or /opencode» while a move starts the next one,
11472
+ * review 25 #1).
10501
11473
  */
10502
- async function bufferPromptDuringStartup(key, text, intake, messageContext) {
11474
+ function checkIsArrivalRoutedAtWrite(key) {
11475
+ const conversationKey = (0, sessionKey_1.keyToString)(key);
11476
+ return startupPromptBuffer.checkIsStarting(conversationKey) || conversationEndings.checkIsRefusingMessages(conversationKey);
11477
+ }
11478
+ /**
11479
+ * @description Deliver a free-form prompt (text OR voice) that ARRIVED while the thread's session is starting or being stopped, or while a
11480
+ * command ends or replaces the conversation ({@link checkIsArrivalRoutedAtWrite}) — the startup twin of {@link deliverActivePrompt}: no
11481
+ * pending question or wedged turn is looked at (a session in its window has none to answer). The window it arrived in only chose this
11482
+ * route: the prompt itself is routed by {@link deliverPromptByState} when it is written, after its request was opened, so a window that
11483
+ * closed meanwhile never keeps it — it goes to the session that window brought up, or wakes the one its stop left asleep — and a command
11484
+ * still running then refuses it. A buffered prompt carries its request's header and its message-context block
11485
+ * (`deliverPersonPromptAtWrite`), since the replay forwards the buffered text as is.
11486
+ */
11487
+ async function deliverPromptDuringStartup(key, text, intake, messageContext) {
10503
11488
  // The same for a bare option number typed in that window: it answers the question asked again. A FORWARDED "1" is somebody
10504
11489
  // else's words, not the operator's pick: it is delivered, marked, like any other message. A topic member's number DOES
10505
11490
  // answer — the one thing foreign words may do here: members answer the agent's questions, and only that (every other
@@ -10507,13 +11492,10 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
10507
11492
  if (messageContext?.isForwarded !== true && await answerReAskedQuestionByNumber(key, text, messageContext))
10508
11493
  return;
10509
11494
  // A person wrote, in a window where the session is starting or being stopped: it counts like a message that reaches
10510
- // `deliverActivePrompt` — the idle latch clears, and a question the idle compaction re-asked is closed (the idle fire
11495
+ // `deliverActivePrompt` — the idle countdown restarts, and a question the idle compaction re-asked is closed (the idle fire
10511
11496
  // posts it just before the stop, so this window is where a message instead of a tap most often lands).
10512
11497
  notePersonActivity(key);
10513
- const opening = await openTopicRequest(key, text, intake, messageContext);
10514
- const quotedText = getPromptWithThreadMessageContext(key, text, messageContext);
10515
- await deliverPromptOrBuffer(key, `${opening.header}${quotedText}`, true, undefined, { isPersonInput: true });
10516
- trackTopicRequestTurn(key, opening);
11498
+ await deliverPromptByState(key, text, intake, undefined, messageContext);
10517
11499
  }
10518
11500
  /**
10519
11501
  * @description The single choke point for delivering a free-form prompt (text OR
@@ -10543,8 +11525,7 @@ options = {}) {
10543
11525
  // A bare option number answers the question the idle compaction asked again (a tap's own label comes in with no intake).
10544
11526
  if (intake !== null && !isForwarded && await answerReAskedQuestionByNumber(key, text, messageContext))
10545
11527
  return null;
10546
- // A genuine USER message (text or voice) — clear the compact-on-idle latch so
10547
- // the next idle period can compact again (D2), whether it answers a pending
11528
+ // A genuine USER message (text or voice) — the idle countdown restarts, whether it answers a pending
10548
11529
  // question or is a fresh prompt.
10549
11530
  notePersonActivity(key);
10550
11531
  const pending = pendingQuestions.get((0, sessionKey_1.keyToString)(key));
@@ -10565,9 +11546,7 @@ options = {}) {
10565
11546
  return null;
10566
11547
  }
10567
11548
  // Free-form text cancels the question and is a fresh prompt — a request (S7).
10568
- const opening = await openTopicRequest(key, text, intake, messageContext);
10569
- const delivery = await cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext, opening.header);
10570
- await settleTopicRequestAfterDelivery(key, opening, delivery);
11549
+ await deliverPersonPromptInRequest(key, text, intake, messageContext, (opening) => cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext, opening, intake !== null));
10571
11550
  return null;
10572
11551
  }
10573
11552
  // A bare `/clear` forwarded to the agent wipes its context (Claude TUI), so
@@ -10591,38 +11570,140 @@ options = {}) {
10591
11570
  adapter.sendSignal(key, 'SIGINT');
10592
11571
  await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
10593
11572
  }
10594
- return deliverPromptByState(key, adapter, text, intake, sentAtMs, messageContext);
11573
+ return deliverPromptByState(key, text, intake, sentAtMs, messageContext);
10595
11574
  }
10596
11575
  /**
10597
- * @description The end of {@link deliverActivePrompt}, shared with the delivery of a late answer ({@link deliverLateAnswerPrompt}): open
10598
- * the request the prompt belongs to (none for `intake` null — an answer to the agent's own question is never a request), deliver it by
10599
- * the state of the session NOW — buffered behind a start, waking a sleeping conversation, or forwarded to the live one — and settle
10600
- * the request. It touches no pending question and no wedged turn: that is the caller's.
11576
+ * @description The ONE way a person's prompt is delivered — text, voice, a file, an album, `/schedule`, a re-asked question's label, a
11577
+ * late answer (the end of {@link deliverActivePrompt} and {@link deliverPromptDuringStartup}): open the request the prompt belongs to
11578
+ * (none for `intake` null — an answer to the agent's own question is never a request), deliver it by the state of the session at the
11579
+ * write ({@link deliverPersonPromptAtWrite}), and settle the request. It touches no pending question and no wedged turn: that is the
11580
+ * caller's.
10601
11581
  */
10602
- async function deliverPromptByState(key, adapter, text, intake, sentAtMs, messageContext) {
11582
+ async function deliverPromptByState(key, text, intake, sentAtMs, messageContext) {
10603
11583
  // The request (S7) is opened AFTER the user takeover cancelled an armed limit
10604
11584
  // wait (the handlers' `cancelApiRetry`) and before the forward, so its id is
10605
11585
  // durable by the time the agent reads it.
10606
- const opening = await openTopicRequest(key, text, intake, messageContext);
10607
- // Routed now, not when the message arrived: the idle stop may have begun or ended during the awaits since.
10608
- // The forward can itself end in no session — a prompt that waited for an adopt replay found the session gone and nothing to wake;
10609
- // it has told the person already (`forwardPromptToAgent`), so what is left here is the request this prompt opened.
10610
- const outcome = await (0, promptDelivery_1.deliverLatePrompt)({
11586
+ // A person's prompt that opens a request starts a turn that may carry the accounts note; the answer to the agent's own question
11587
+ // (`intake` null) is bookkeeping and never does.
11588
+ return deliverPersonPromptInRequest(key, text, intake, messageContext, (opening) => deliverPersonPromptAtWrite(key, text, { opening, sentAtMs, messageContext, isAccountsNoteCarrier: intake !== null }));
11589
+ }
11590
+ /**
11591
+ * The person's prompts on their way to their write, request id → conversation: from the moment the request is created — inside the
11592
+ * create, synchronously with it appearing open — until the prompt's delivery is settled. An ending command's cancel does not tell them:
11593
+ * the prompt's own route tells its person (refused while the command runs, refused once it is over because the command closed its request
11594
+ * — {@link personPromptsEndedInDelivery} —, or with no session), and the command telling it too gave the person the line twice, or a false
11595
+ * one (review 27 #1).
11596
+ */
11597
+ const personPromptsInDelivery = new Map();
11598
+ /**
11599
+ * The requests of {@link personPromptsInDelivery} an ending command closed (`cancelEndingConversationRequests`, marked at its call): the
11600
+ * prompt is refused at its write even once the command is over, never written into the conversation that follows under a request that is
11601
+ * closed — unwatched, and naming a request its agent cannot answer (review 28 nit 4).
11602
+ */
11603
+ const personPromptsEndedInDelivery = new Set();
11604
+ /**
11605
+ * @description Open a person's prompt's request (`openTopicRequest`), `deliver` the prompt and settle the request by where it went,
11606
+ * the request marked in delivery ({@link personPromptsInDelivery}) from its creation until the settle is over, on every way out. The one
11607
+ * way a person's prompt that may open a request is delivered: {@link deliverPromptByState} and the free text that cancels a question.
11608
+ */
11609
+ async function deliverPersonPromptInRequest(key, text, intake, messageContext, deliver) {
11610
+ const marked = { requestId: null };
11611
+ try {
11612
+ const opening = await openTopicRequest(key, text, intake, messageContext, (requestId) => {
11613
+ marked.requestId = requestId;
11614
+ personPromptsInDelivery.set(requestId, (0, sessionKey_1.keyToString)(key));
11615
+ });
11616
+ const outcome = await deliver(opening);
11617
+ await settleTopicRequestAfterDelivery(key, opening, outcome);
11618
+ return outcome;
11619
+ }
11620
+ finally {
11621
+ if (marked.requestId !== null) {
11622
+ personPromptsInDelivery.delete(marked.requestId);
11623
+ personPromptsEndedInDelivery.delete(marked.requestId);
11624
+ }
11625
+ }
11626
+ }
11627
+ /**
11628
+ * @description Whether a person's prompt is refused at its write: a command ends or replaces the conversation now (review 25 #1), or one
11629
+ * closed the prompt's request while it was in delivery — then it is refused once the command is over as well (review 28 nit 4).
11630
+ */
11631
+ function checkIsPersonPromptRefused(key, requestId) {
11632
+ return conversationEndings.checkIsRefusingMessages((0, sessionKey_1.keyToString)(key)) || (requestId !== null && personPromptsEndedInDelivery.has(requestId));
11633
+ }
11634
+ /**
11635
+ * @description Write a person's prompt by the state of the session NOW (`deliverLatePrompt`), never by one read before an await: the
11636
+ * idle stop or a start may have begun or ended during the caller's awaits (its request opened, a file downloaded, a question
11637
+ * cancelled). A command that ends or replaces the conversation runs → refused, ahead of any window: its request closed, the person told
11638
+ * (review 25 #1); a start's or a stop's window open → buffered behind it, its header and message-context block folded in (the replay
11639
+ * forwards the text as is); a live session → forwarded; neither → the sleeping conversation is woken, then forwarded. A wake that finds
11640
+ * nothing tells the person, unless it said why itself; one that found the conversation ended by a release while it waited says that
11641
+ * (review 25 #2). The forward can itself end in no session — a prompt that waited for an adopt replay found the session gone and nothing
11642
+ * to wake; it has told the person already (`forwardPromptToAgent`).
11643
+ */
11644
+ function deliverPersonPromptAtWrite(key, text, options) {
11645
+ const { opening, sentAtMs, messageContext, isAccountsNoteCarrier } = options;
11646
+ const { header: requestHeader, requestId } = opening;
11647
+ return (0, promptDelivery_1.deliverLatePrompt)({
10611
11648
  checkIsWindowOpen: () => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
10612
- checkIsSessionActive: () => adapter.checkIsActive(key),
11649
+ checkIsSessionActive: () => checkIsAcceptingInput(key),
11650
+ // A command ends or replaces the conversation, or one closed this prompt's request while it was in delivery: the prompt is not
11651
+ // delivered — read ahead of any window (review 25 #1, review 28 nit 4).
11652
+ checkIsRefused: () => checkIsPersonPromptRefused(key, requestId),
11653
+ // The request closes here, ahead of the line, so a switch closing the conversation's requests meanwhile does not tell it again; the
11654
+ // caller's own close of a `noSession` prompt then finds it closed.
11655
+ reportRefused: () => reportDroppedPersonPrompt(key, requestId, true),
10613
11656
  buffer: async () => {
10614
- await deliverPromptOrBuffer(key, `${opening.header}${getPromptWithThreadMessageContext(key, text, messageContext)}`, true, undefined, { isPersonInput: true });
11657
+ const bufferedText = `${requestHeader}${getPromptWithThreadMessageContext(key, text, messageContext)}`;
11658
+ await deliverPromptOrBuffer(key, bufferedText, createPersonBufferedSettle(key, requestId), { isPersonInput: true, isAccountsNoteCarrier });
10615
11659
  },
10616
11660
  wake: () => wakeSleepingSessionForPrompt(key),
10617
- forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader: opening.header, isPersonInput: true }),
11661
+ forward: () => forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, sentAtMs, { messageContext, requestHeader, requestId, isPersonInput: true, isAccountsNoteCarrier }),
10618
11662
  reportNoSession: async (isAlreadyTold) => {
10619
11663
  if (!isAlreadyTold)
10620
11664
  await replyToThread(key, (0, i18n_1.t)('agent.no_session'));
10621
11665
  },
10622
11666
  });
10623
- await settleTopicRequestAfterDelivery(key, opening, outcome);
10624
- return outcome;
10625
11667
  }
11668
+ /**
11669
+ * @description The settle of a person's prompt that waits in a startup buffer. One its window's end DROPPED — the start failed, nothing
11670
+ * started after a failed resume, its replay's write threw, a command that ends or replaces the conversation waits behind it — never
11671
+ * reached the agent, and nothing else will post it: the request it opened closes (`cancelled`, like a prompt that found no session; its
11672
+ * watch goes with it) and the person, who was told it is queued, is told why: that the agent was starting, or — read at the drop, while
11673
+ * the command holds the conversation — that the conversation was being ended or switched (review 24 nit 5). Fire and forget: a failure
11674
+ * is logged.
11675
+ */
11676
+ function createPersonBufferedSettle(key, requestId) {
11677
+ return (outcome) => {
11678
+ if (outcome !== 'dropped')
11679
+ return;
11680
+ const isDroppedForEndingCommand = conversationEndings.checkIsEnding((0, sessionKey_1.keyToString)(key));
11681
+ void withThreadLocale(key, () => reportDroppedPersonPrompt(key, requestId, isDroppedForEndingCommand)).catch((e) => console.error(`[startupPromptBuffer] ${(0, sessionKey_1.keyToString)(key)}: reporting a dropped message failed:`, e));
11682
+ };
11683
+ }
11684
+ /**
11685
+ * @description A person's prompt that never reached the agent — dropped from a window, or refused while a command ends or replaces the
11686
+ * conversation: its request closes and the person is told why. Marked in {@link personDropsBeingTold} from the call (synchronously, in the
11687
+ * drop's own tick) until the request is closed and the line out, so a switch that closes the conversation's requests meanwhile does not
11688
+ * tell the same message again.
11689
+ */
11690
+ async function reportDroppedPersonPrompt(key, requestId, isDroppedForEndingCommand) {
11691
+ if (requestId !== null)
11692
+ personDropsBeingTold.add(requestId);
11693
+ try {
11694
+ console.warn(`[startupPromptBuffer] ${(0, sessionKey_1.keyToString)(key)}: a message never reached the agent${isDroppedForEndingCommand ? ' (a command ends the conversation)' : ''}; ${requestId ?? 'no request'} is closed`);
11695
+ await settleTopicRequestAfterDelivery(key, { requestId }, 'noSession');
11696
+ await replyToThread(key, isDroppedForEndingCommand
11697
+ ? (0, i18n_1.t)('agent.queued_prompt_dropped_by_command')
11698
+ : (0, i18n_1.t)('agent.queued_prompt_dropped', { label: (0, createAdapter_1.getThreadAdapter)(key).label }));
11699
+ }
11700
+ finally {
11701
+ if (requestId !== null)
11702
+ personDropsBeingTold.delete(requestId);
11703
+ }
11704
+ }
11705
+ /** The requests whose person's drop is being told right now ({@link reportDroppedPersonPrompt}): a switch's close tells none of them. */
11706
+ const personDropsBeingTold = new Set();
10626
11707
  /**
10627
11708
  * @description Deliver a LATE ANSWER to the agent — what the owner chose for a question the bot set aside, worded by
10628
11709
  * `buildLateAnswerPrompt` — as a message of the owner's: written to a live session behind whatever it is doing, buffered behind a
@@ -10636,8 +11717,8 @@ async function deliverLateAnswerPrompt(key, text) {
10636
11717
  // The owner took over, like with any message they type: an armed usage-limit wait is over (the answer is not written INTO it, and its
10637
11718
  // own «continue» nudge would come on top of the answer later).
10638
11719
  cancelApiRetry(key);
10639
- noteThreadUserActivity(key);
10640
- return deliverPromptByState(key, (0, createAdapter_1.getThreadAdapter)(key), text, null);
11720
+ noteThreadActivity(key);
11721
+ return deliverPromptByState(key, text, null);
10641
11722
  }
10642
11723
  /**
10643
11724
  * @description Close the on-screen state of a pending question that ends without an answer: clear the bot's
@@ -10678,7 +11759,9 @@ function retirePendingQuestionInBackground(key) {
10678
11759
  * close it on the server, abort the wedged OpenCode turn (`SIGINT` → `/session/:id/
10679
11760
  * abort`), post the "previous question cancelled" notice, then forward.
10680
11761
  */
10681
- async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext, requestHeader) {
11762
+ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, messageContext, opening = noTopicRequest,
11763
+ /** The prompt opened a request (a person's free text, not the label of a tap): it may carry the accounts note. */
11764
+ isAccountsNoteCarrier = false) {
10682
11765
  // When the question bubble itself was closed with its «not answered» note, that IS the
10683
11766
  // cancellation notice — a second standalone "previous question cancelled" line is
10684
11767
  // pure noise (the reported triple message). The standalone notice is kept only
@@ -10697,7 +11780,8 @@ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, mes
10697
11780
  if (!didLabelQuestionMessage) {
10698
11781
  await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
10699
11782
  }
10700
- return forwardPromptToAgent(key, adapter, text, sentAtMs, { messageContext, requestHeader, isPersonInput: true });
11783
+ // Routed at the write: the SIGINT ended the turn, and a per-turn topic's stop may have begun (or ended) during the notice.
11784
+ return deliverPersonPromptAtWrite(key, text, { opening, sentAtMs, messageContext, isAccountsNoteCarrier });
10701
11785
  }
10702
11786
  /**
10703
11787
  * @description Record one answer for the CURRENTLY shown OpenCode question and
@@ -11360,9 +12444,11 @@ function handleAgentToolResult(key, payload) {
11360
12444
  const action = (0, toolResultRender_1.getToolResultRenderAction)(state.getDisplayPrefs(key).toolResults);
11361
12445
  if (action === 'drop')
11362
12446
  return;
12447
+ // The accounts note rides the END of a bot send tool's result for the agent only (`limitNotes/noteText.ts`): the topic never shows it.
12448
+ const output = (0, injection_1.checkIsBotMcpToolName)(payload.tool) ? (0, noteText_1.stripLimitNote)(payload.output) : payload.output;
11363
12449
  const { text, isTruncated } = action === 'truncated'
11364
- ? (0, toolResultRender_1.getTruncatedToolResult)(payload.output)
11365
- : { text: payload.output, isTruncated: false };
12450
+ ? (0, toolResultRender_1.getTruncatedToolResult)(output)
12451
+ : { text: output, isTruncated: false };
11366
12452
  const header = payload.title ? `🔧 ${payload.tool} → ${payload.title}` : `🔧 ${payload.tool} →`;
11367
12453
  const footer = isTruncated ? `\n${(0, i18n_1.t)('toolResults.truncated_footer')}` : '';
11368
12454
  void sendStandaloneAgentMessage(key, `${header}\n${(0, toolResultRender_1.buildFencedToolResultBody)(text)}${footer}`);
@@ -11983,6 +13069,8 @@ function handleQuestionGone(key) {
11983
13069
  void unpinThreadQuestion(key);
11984
13070
  }
11985
13071
  function handleAgentClosed(key) {
13072
+ // A process that is gone takes no mid-turn accounts note.
13073
+ withdrawAccountsInbox(key);
11986
13074
  // What the process held that died with it (its own background work), taken before the cleanup below.
11987
13075
  const lostWork = takeLostWorkOf(key);
11988
13076
  // Session is gone — the not-yet-sent output gets its ONE final attempt (a 429
@@ -12071,7 +13159,7 @@ async function noteLostWork(key, lostWork, reason) {
12071
13159
  planText = 'its open request is woken, and the note rides that wake';
12072
13160
  console.log(`[lost-work] ${kStr}: the process ended (${reason}) with the agent's own work pending (${record.backgroundTasks.length} background task(s), ${record.scheduledJobCount} scheduled job(s)${record.hasUnreadTaskResult ? ', an unread task result' : ''}${record.wasTurnInFlight ? ', a cut-off turn' : ''}); ${planText}`);
12073
13161
  if (plan.isRequestWake)
12074
- scheduleTrackerRestartWake(key, `its process ended (${reason}) with its own work pending`);
13162
+ scheduleTrackerRestartWake(key, `its process ended (${reason}) with its own work pending`, { isLostWork: true });
12075
13163
  let linePlan = plan;
12076
13164
  if (plan.isAutoResume) {
12077
13165
  await state.setLostWorkResumedAt(key, now);
@@ -12088,7 +13176,7 @@ async function noteLostWork(key, lostWork, reason) {
12088
13176
  * lost-work path and is never woken here. The lost-work cooldown guards it as well: a conversation woken
12089
13177
  * automatically within it is left to the backstop, so a crash loop is no wake loop.
12090
13178
  */
12091
- function scheduleTrackerRestartWake(key, why) {
13179
+ function scheduleTrackerRestartWake(key, why, options = {}) {
12092
13180
  if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key) || !requestWakeUpEngine)
12093
13181
  return;
12094
13182
  const lastAutoResumeAt = state.getLostWorkResumedAt(key);
@@ -12096,8 +13184,12 @@ function scheduleTrackerRestartWake(key, why) {
12096
13184
  console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; it was woken automatically less than ${lostWork_1.lostWorkResumeCooldownMs / 60_000} min ago, so the backstop takes it`);
12097
13185
  return;
12098
13186
  }
12099
- if (requestWakeUpEngine.scheduleRestartWake(key))
13187
+ if (requestWakeUpEngine.scheduleRestartWake(key, options)) {
12100
13188
  console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; its open request is woken shortly`);
13189
+ return;
13190
+ }
13191
+ // Said, not silent: the caller's own line may have promised a wake (`noteLostWork`).
13192
+ console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: ${why}; no wake was scheduled (one is already waiting, or no open request needs it: each is held by a watch that owes nobody an answer, as at a boot)`);
12101
13193
  }
12102
13194
  /**
12103
13195
  * @description The boot's pass over the open requests of tracker conversations: one whose process did not come back
@@ -12135,22 +13227,27 @@ async function resumeConversationForLostWork(key) {
12135
13227
  await state.setLostWork(key, (0, lostWork_1.mergeLostWorkRecords)(state.getLostWork(key), record));
12136
13228
  return false;
12137
13229
  }
13230
+ /** Why a session post failed when its prompt found no session at the write and nothing to wake (`deliverPromptOrBuffer` → `noSession`). */
13231
+ const noSessionForPostError = 'the session went away before the prompt was written, and nothing could be woken for it';
12138
13232
  /** The session post of a lost-work note: a bot note to the agent, not a request — no request is opened for it. */
12139
13233
  function createLostWorkPostDeps() {
12140
13234
  return {
12141
13235
  ...createSessionPostDeps(),
12142
13236
  forwardPrompt: async (conversationKey, text) => {
12143
13237
  const buffered = createBufferedOutcome();
12144
- const delivery = await deliverPromptOrBuffer((0, sessionKey_1.keyFromString)(conversationKey), text, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
13238
+ const delivery = await deliverPostPrompt((0, sessionKey_1.keyFromString)(conversationKey), text, buffered.settle);
12145
13239
  if (delivery === 'buffered')
12146
13240
  await buffered.assertReplayed();
13241
+ if (delivery === 'noSession')
13242
+ throw new Error(noSessionForPostError);
12147
13243
  },
12148
13244
  };
12149
13245
  }
12150
13246
  /**
12151
13247
  * @description How a prompt that waited in the startup buffer ended, for a post that must know it reached the session:
12152
- * `settle` is the buffer's callback, `assertReplayed` resolves once it was replayed into the session and rejects when it
12153
- * was dropped — the start failed, or its write did not reach the agent.
13248
+ * `settle` is the buffer's callback; `getOutcome` resolves with that outcome (`replayed` or `dropped`) for a caller that acts on
13249
+ * either (the scheduler's request a fire opened closes on `dropped`); `assertReplayed` resolves once it was replayed into the session
13250
+ * and rejects when it was dropped — the start failed, or its write did not reach the agent.
12154
13251
  */
12155
13252
  function createBufferedOutcome() {
12156
13253
  let settle = () => { };
@@ -12159,12 +13256,15 @@ function createBufferedOutcome() {
12159
13256
  });
12160
13257
  return {
12161
13258
  settle: (result) => settle(result),
13259
+ getOutcome: () => outcome,
12162
13260
  assertReplayed: async () => {
12163
13261
  if ((await outcome) !== 'replayed')
12164
- throw new Error('the prompt waited for the session to start and never reached the agent');
13262
+ throw new Error(bufferedPromptDroppedError);
12165
13263
  },
12166
13264
  };
12167
13265
  }
13266
+ /** Why a post whose prompt waited for a session start failed: the window dropped it. */
13267
+ const bufferedPromptDroppedError = 'the prompt waited for the session to start and never reached the agent';
12168
13268
  function handleAgentError(key, error) {
12169
13269
  console.error(`[Bot] adapter error ${(0, sessionKey_1.keyToString)(key)}:`, error.message);
12170
13270
  topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
@@ -12194,6 +13294,8 @@ function clearForeignSessionState(key) {
12194
13294
  * and `openCodeAdapter` (`emit('started', key)`).
12195
13295
  */
12196
13296
  function handleAgentStarted(key) {
13297
+ // A note written for the session this one replaces is never taken by the new one.
13298
+ withdrawAccountsInbox(key);
12197
13299
  updatePinnedStatus(key).catch(() => { });
12198
13300
  // A fresh/adopted session arms the compact-on-idle watchdog (F2); it won't fire
12199
13301
  // until a turn produces output AND the topic then sits idle (no catch-up burst).
@@ -12281,6 +13383,7 @@ function dropLostConversationWatermark(key) {
12281
13383
  * Posts nothing — `/status` says the agent sleeps.
12282
13384
  */
12283
13385
  function handleAgentSuspended(key) {
13386
+ withdrawAccountsInbox(key);
12284
13387
  clearGoneProcessFrames(key);
12285
13388
  updatePinnedStatus(key).catch(() => { });
12286
13389
  // An idle stop takes pending work with it only once the hold ran out.
@@ -12318,6 +13421,7 @@ exports.COMMANDS_MENU = [
12318
13421
  { command: 'compact_summary', description: '📄 Post the compaction summary (toggle)' },
12319
13422
  { command: 'compact_self_review', description: '💡 Agent self-review on compaction: its mistakes and what to change in its instructions' },
12320
13423
  { command: 'bot_skills', description: '🧰 The bot\'s own skills for agents (on/off)' },
13424
+ { command: 'workers', description: '🛠 Worker models and effort per role' },
12321
13425
  { command: 'question_wait', description: '⏳ How long the agent waits for your answer to its question' },
12322
13426
  { command: 'topic_status', description: '❓ Marks at the end of topic names: question, working, finished, asleep' },
12323
13427
  { command: 'task_agents', description: '🧵 How many tracker task agents work at once' },
@@ -12325,6 +13429,7 @@ exports.COMMANDS_MENU = [
12325
13429
  { command: 'accounts', description: '👤 Claude accounts and OpenCode providers (switch, add, re-login, remove, connect, disconnect)' },
12326
13430
  { command: 'limits', description: '🚧 Usage limits — switch this topic' },
12327
13431
  { command: 'limits_autoswitch', description: '🔁 Automatic switching on a usage limit' },
13432
+ { command: 'limits_reminders', description: '🔔 How often agents are reminded of the accounts\' limits' },
12328
13433
  { command: 'stt', description: '🎙 Voice recognition: engines, language, local engine' },
12329
13434
  { command: 'update', description: '🔄 Bot updates: automatic, notify only, off' },
12330
13435
  { command: 'schedule', description: '⏰ Schedule a prompt (agent does the work)' },
@@ -12943,29 +14048,66 @@ function restoreApiRetries() {
12943
14048
  console.log(`[reattach] api retries: re-armed ${restored}`);
12944
14049
  }
12945
14050
  /**
12946
- * @description Record a json-stream conversation's stdout log, as it is now, as a limit episode already handled
12947
- * (`limitEpisodesRecovered`, the stamp {@link recoverLimitEpisodesFromDisk} checks). A live wait that ends without
12948
- * its resume — «⏭ Skip once», a give-up, a takeover — leaves the error it waited on as the log's last terminal frame,
12949
- * and the next boot's recovery armed it again: only the recovery itself wrote the stamp. A later turn writes to the
12950
- * log and changes its identity, so a NEW parked error is still recovered.
14051
+ * @description What a json-stream conversation's `stdout.jsonl` says of a limit episode now: the log's identity (ONE stat:
14052
+ * size and mtime describe the same instant) and the error it is parked on, with that error's place in the log
14053
+ * (`findParkedTerminalError` over the tail — never the whole log). `null` when there is no log; `parked` is `null` when the log
14054
+ * is not parked on an error, or its tail could not be read (`tailError` says why).
12951
14055
  */
12952
- function markLimitEpisodeSettled(key) {
12953
- const agent = state.getAgent(key);
12954
- if (!agent || !(0, adapterNames_1.checkIsJsonStreamBackend)(agent.name))
12955
- return;
12956
- const { stdoutFile } = (0, jsonStreamHost_1.getJsonStreamSessionPaths)((0, jsonStreamHost_1.resolveJsonStreamSessionDir)(getDataDir(), key));
14056
+ function readLimitEpisodeEvidence(stdoutFile) {
12957
14057
  let log;
12958
14058
  try {
12959
14059
  const stat = fs.statSync(stdoutFile);
12960
14060
  log = { sizeBytes: stat.size, mtimeMs: stat.mtimeMs };
12961
14061
  }
12962
14062
  catch {
12963
- return; // no stdout log for this thread — nothing a boot could recover
14063
+ return null; // no stdout log for this thread — nothing a boot could recover
14064
+ }
14065
+ if (log.sizeBytes === 0)
14066
+ return { log, parked: null };
14067
+ try {
14068
+ const tailStart = Math.max(0, log.sizeBytes - limitEpisodeRecovery_1.limitEpisodeTailMaxBytes);
14069
+ return { log, parked: (0, limitEpisodeRecovery_1.findParkedTerminalError)((0, jsonStreamHost_1.readFileByteRange)(stdoutFile, tailStart, log.sizeBytes), tailStart) };
12964
14070
  }
14071
+ catch (tailError) {
14072
+ return { log, parked: null, tailError };
14073
+ }
14074
+ }
14075
+ /**
14076
+ * @description Record a json-stream conversation's parked limit error, as the log holds it now, as an episode already handled
14077
+ * (`limitEpisodesRecovered`, the marker {@link recoverLimitEpisodesFromDisk} checks). A live wait that ends without its resume —
14078
+ * «⏭ Skip once», a give-up, a used-up balance — leaves the error it waited on as the log's last terminal frame, and the next
14079
+ * boot's recovery armed it again: only the recovery itself wrote the marker. The marker names that error's place in the log, so
14080
+ * the frames a later boot appends after it (its `mcp_status` reply) leave it handled, while a NEW parked error is still recovered.
14081
+ */
14082
+ function markLimitEpisodeSettled(key) {
14083
+ const agent = state.getAgent(key);
14084
+ if (!agent || !(0, adapterNames_1.checkIsJsonStreamBackend)(agent.name))
14085
+ return;
14086
+ const { stdoutFile } = (0, jsonStreamHost_1.getJsonStreamSessionPaths)((0, jsonStreamHost_1.resolveJsonStreamSessionDir)(getDataDir(), key));
14087
+ const evidence = readLimitEpisodeEvidence(stdoutFile);
14088
+ if (evidence === null)
14089
+ return;
12965
14090
  void state
12966
- .setLimitEpisodeRecovered(key, log)
14091
+ .setLimitEpisodeRecovered(key, (0, limitEpisodeRecovery_1.buildLimitEpisodeMarker)(evidence.log, evidence.parked))
12967
14092
  .catch((e) => console.error('[limitRecovery] marker persist failed:', e));
12968
14093
  }
14094
+ /**
14095
+ * @description What a conversation whose process is STOPPED (a sleeping per-turn session) weighs, read from its Claude transcript by the
14096
+ * session id and work folder the bot persisted — a stopped session has no live adapter state to ask. The idle compaction measures it
14097
+ * at its mark, before it decides to resume the session for a compaction. `null` when there is no session id or folder or no transcript.
14098
+ */
14099
+ async function readSleepingConversationContext(key, isBaselineNeeded) {
14100
+ const claudeSessionId = state.getAgent(key)?.claudeSessionId;
14101
+ const workDirDecision = getWorkDirStartDecision(key);
14102
+ if (!claudeSessionId || !workDirDecision.ok)
14103
+ return null;
14104
+ const transcriptPath = (0, claudeCliAdapter_1.getClaudeTranscriptPath)(workDirDecision.workDir, claudeSessionId);
14105
+ const [lastContextTokens, firstCallContextTokens] = await Promise.all([
14106
+ (0, claudeRuntimeInfo_1.readClaudeContextUsedTokens)(transcriptPath),
14107
+ isBaselineNeeded ? (0, claudeRuntimeInfo_1.readClaudeFirstCallContextTokens)(transcriptPath) : null,
14108
+ ]);
14109
+ return { lastContextTokens, firstCallContextTokens };
14110
+ }
12969
14111
  /**
12970
14112
  * @description When the parked `errorText` of a json-stream conversation was written, from its Claude transcript's
12971
14113
  * API-error entry ({@link readTranscriptErrorWrittenAtMs}); `null` when the transcript tail cannot be read or holds no such
@@ -13003,11 +14145,20 @@ const limitEpisodesOwnedByRecovery = new Set();
13003
14145
  * error's own time) resumes at once: the retry plan clamps the negative delay to
13004
14146
  * zero, and {@link handleApiError} announces no limit for a window that is over.
13005
14147
  *
13006
- * Each arming STAMPS the log's identity (`state.json` `limitEpisodesRecovered`), so
14148
+ * Each arming STAMPS the episode (`state.json` `limitEpisodesRecovered`): the parked
14149
+ * error's place in the log and a stamp of its whole `result` line (`buildLimitEpisodeMarker`), so
13007
14150
  * an episode is recovered at most once: «⏭ Skip once», a user takeover and a
13008
14151
  * give-up all clear the armed record while leaving the same trailing error in the
13009
14152
  * log, and hot mode reloads the bot on every code change — without the stamp each
13010
- * reload resurrected the settled wait.
14153
+ * reload resurrected the settled wait. The place, not the log's size and mtime:
14154
+ * every boot asks an adopted session for its `mcp_status`, whose reply lands in the
14155
+ * log AFTER this step, so a stamp of the whole log was out of date by the next boot
14156
+ * and each restart re-armed the same parked error.
14157
+ *
14158
+ * The usage poll of this boot runs beside the reattach, so a recovered UNCONFIRMED
14159
+ * wording must not be confirmed by a reading the poll has not re-read or marked stale
14160
+ * yet: a reading older than the error proves nothing about it (`episodeWrittenAtMs`,
14161
+ * {@link handleUnconfirmedLimit}) — it is probed, and the probe's repeat confirms it.
13011
14162
  */
13012
14163
  function recoverLimitEpisodesFromDisk() {
13013
14164
  const now = Date.now();
@@ -13025,30 +14176,22 @@ function recoverLimitEpisodesFromDisk() {
13025
14176
  continue;
13026
14177
  const keyStr = (0, sessionKey_1.keyToString)(key);
13027
14178
  const { stdoutFile } = (0, jsonStreamHost_1.getJsonStreamSessionPaths)((0, jsonStreamHost_1.resolveJsonStreamSessionDir)(getDataDir(), key));
13028
- // ONE stat: size and mtime must describe the same instant, because together
13029
- // they are the episode identity persisted below.
13030
- let log;
13031
- try {
13032
- const stat = fs.statSync(stdoutFile);
13033
- log = { sizeBytes: stat.size, mtimeMs: stat.mtimeMs };
13034
- }
13035
- catch {
14179
+ const evidence = readLimitEpisodeEvidence(stdoutFile);
14180
+ if (evidence === null || evidence.log.sizeBytes === 0)
13036
14181
  continue; // no stdout log for this thread (yet) — nothing to recover
13037
- }
13038
- if (log.sizeBytes === 0)
13039
- continue;
13040
- let errorText = null;
13041
- try {
13042
- const tail = (0, jsonStreamHost_1.readFileByteRange)(stdoutFile, Math.max(0, log.sizeBytes - limitEpisodeRecovery_1.limitEpisodeTailMaxBytes), log.sizeBytes);
13043
- errorText = (0, limitEpisodeRecovery_1.getLastTerminalErrorText)(tail.toString('utf8'));
13044
- }
13045
- catch (e) {
13046
- console.warn(`[limitRecovery] ${keyStr}: cannot read stdout tail:`, e instanceof Error ? e.message : e);
14182
+ if (evidence.tailError !== undefined) {
14183
+ const reason = evidence.tailError;
14184
+ console.warn(`[limitRecovery] ${keyStr}: cannot read stdout tail:`, reason instanceof Error ? reason.message : reason);
13047
14185
  continue;
13048
14186
  }
14187
+ const { log, parked } = evidence;
14188
+ const errorText = parked?.text ?? null;
14189
+ const errorWrittenAtMs = errorText === null ? null : readParkedErrorWrittenAtMs(key, agent.claudeSessionId, errorText);
13049
14190
  const decision = (0, limitEpisodeRecovery_1.decideLimitEpisodeRecovery)({
13050
14191
  errorText,
13051
- errorWrittenAtMs: errorText === null ? null : readParkedErrorWrittenAtMs(key, agent.claudeSessionId, errorText),
14192
+ errorEndOffset: parked?.endOffset ?? null,
14193
+ errorStamp: parked?.stamp ?? null,
14194
+ errorWrittenAtMs,
13052
14195
  log,
13053
14196
  handled: state.getLimitEpisodeRecovered(key),
13054
14197
  now,
@@ -13060,17 +14203,20 @@ function recoverLimitEpisodesFromDisk() {
13060
14203
  continue;
13061
14204
  }
13062
14205
  console.log(`[limitRecovery] ${keyStr}: re-arming a limit wait left over from before the restart`);
13063
- // Stamp the log identity BEFORE arming: this trailing error is now handled, so
13064
- // a later boot must not recover it again even once the armed record is gone
13065
- // («⏭ Skip once», a user takeover, or a give-up all clear it).
14206
+ // Stamp the episode BEFORE arming: this parked error is now handled, so a later boot must not recover it again even
14207
+ // once the armed record is gone («⏭ Skip once», a user takeover, or a give-up all clear it) — nor once frames that are
14208
+ // no turn (this very boot's `mcp_status` reply) land after it: the marker names the error's place, not the log's size.
13066
14209
  void state
13067
- .setLimitEpisodeRecovered(key, log)
14210
+ .setLimitEpisodeRecovered(key, (0, limitEpisodeRecovery_1.buildLimitEpisodeMarker)(log, parked))
13068
14211
  .catch(e => console.error('[limitRecovery] marker persist failed:', e));
13069
14212
  // This episode is the recovery's alone: the adopt replays the same error once the boot releases its output (after this
13070
14213
  // step), and `handleApiError` leaves that copy out until the replay is over.
13071
14214
  limitEpisodesOwnedByRecovery.add(keyStr);
13072
14215
  void ((0, createAdapter_1.getAdapter)(agent.name).whenAdoptReplayed?.(key) ?? Promise.resolve()).then(() => limitEpisodesOwnedByRecovery.delete(keyStr));
13073
- void withThreadLocale(key, () => handleApiError(key, decision.cls, { isRecoveredEpisode: true }));
14216
+ // A usage reading older than the error proves nothing about it (an unconfirmed wording is probed, not confirmed by it):
14217
+ // this boot's usage poll, started before the reattach, may not have re-read the account or marked its reading stale yet.
14218
+ const episodeWrittenAtMs = errorWrittenAtMs ?? log.mtimeMs;
14219
+ void withThreadLocale(key, () => handleApiError(key, decision.cls, { isRecoveredEpisode: true, episodeWrittenAtMs }));
13074
14220
  recovered += 1;
13075
14221
  }
13076
14222
  if (recovered > 0)
@@ -13299,8 +14445,11 @@ let connectorConversationHooks = new Map();
13299
14445
  * {@link clearThreadContextMarker}, which a stop clears too.
13300
14446
  */
13301
14447
  function noteConversationContextReset(key, reason) {
13302
- // A completed compaction or a fresh session: the agent forgot the board too (D20).
14448
+ // A completed compaction or a fresh session: the agent forgot the board too (D20), and the picture of the accounts' limits.
13303
14449
  noteTodoFreshContext(key);
14450
+ // The accounts note's inbox first (see `clearThreadContextMarker`): a note the hook took before the compaction is recorded, then forgotten.
14451
+ withdrawAccountsInbox(key);
14452
+ state.clearLimitNoteFingerprint(key);
13304
14453
  connectorConversationHooks.get(key.platform)?.onContextReset(key, reason);
13305
14454
  }
13306
14455
  /**
@@ -13348,9 +14497,14 @@ async function prepareRequestWakeUpSession(key, message, fallbackAdapterName) {
13348
14497
  */
13349
14498
  async function forwardRequestWakeUp(key, _request, message) {
13350
14499
  // The request's own prompt re-posted (R21) counts as that prompt, not a reminder.
13351
- await forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), message.text, undefined, {
14500
+ const outcome = await forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), message.text, undefined, {
13352
14501
  isRequestReminder: !message.isRequestPrompt,
14502
+ lostWorkTelling: message.isAnswerOptional === true ? 'watchHeld' : 'plain',
13353
14503
  });
14504
+ // A wake that waited for an adopted session's replay and then found no session reached no agent: a failed wake (a post retry later,
14505
+ // the backstop for a restart wake, else `wakeFailed`), never a delivered one whose turn the engine would watch (review 21, own pass).
14506
+ if (outcome === 'noSession')
14507
+ throw new Error(noSessionForPostError);
13354
14508
  }
13355
14509
  /**
13356
14510
  * @description Remind the agent, in its own session, of what it wrote after its
@@ -13361,8 +14515,8 @@ async function remindAnswerTail(key, text) {
13361
14515
  const ensured = await ensureAgentSession(key, { isResumeOnly: true });
13362
14516
  if (!ensured.ok || !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key))
13363
14517
  return false;
13364
- await forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isRequestReminder: true });
13365
- return true;
14518
+ // `false` when it waited for an adopted session's replay and then found no session (review 21, own pass).
14519
+ return (await forwardPromptToAgent(key, (0, createAdapter_1.getThreadAdapter)(key), text, undefined, { isRequestReminder: true })) !== 'noSession';
13366
14520
  }
13367
14521
  /**
13368
14522
  * @description How a conversation's session stands right now (`requests/sessionTurnProbe.ts`) — the one probe the
@@ -13376,7 +14530,9 @@ const probeThreadTurn = (0, sessionTurnProbe_1.createSessionTurnProbe)({
13376
14530
  getApiRetryTimer: (keyString) => apiRetryTimers.get(keyString)?.timer,
13377
14531
  checkIsWedgeRecoveryInFlight: (keyString) => wedgeRecoveriesInFlight.has(keyString),
13378
14532
  checkIsRetryKickInFlight: (keyString) => apiRetryKicksInFlight.has(keyString),
14533
+ checkIsApiErrorInHandling: (keyString) => apiErrorsInHandling.has(keyString),
13379
14534
  checkIsSessionStarting: (keyString) => startupPromptBuffer.checkIsStarting(keyString),
14535
+ checkIsReplayingBufferedPrompts: (keyString) => startupPromptBuffer.checkIsReplaying(keyString),
13380
14536
  serializeKey: sessionKey_1.keyToString,
13381
14537
  });
13382
14538
  /**
@@ -13395,18 +14551,53 @@ async function postTodoReminder(key, text) {
13395
14551
  return isPosted && !isDropped;
13396
14552
  }
13397
14553
  /**
13398
- * @description The person took over the conversation (interrupt, quit, restart,
13399
- * switch or resume of the session, a switch to another agent or a shell, leaving
13400
- * the folder): its open request closes silently and nothing wakes it. Safe before
13401
- * the engine exists (early boot).
14554
+ * @description The person interrupted the turn (`/esc` and its aliases, `/c`): the conversation goes on, but its open requests close
14555
+ * silently and nothing wakes them. A command that ends or replaces the conversation closes them through
14556
+ * {@link cancelEndingConversationRequests} instead, which tells a person whose words were never read. Safe before the engine exists
14557
+ * (early boot).
13402
14558
  */
13403
14559
  function cancelConversationRequest(key) {
13404
14560
  void requestWakeUpEngine?.cancelConversation(key).catch((e) => console.warn(`[requests] cancelling the request of ${(0, sessionKey_1.keyToString)(key)} failed:`, e instanceof Error ? e.message : e));
13405
14561
  }
14562
+ /**
14563
+ * @description A command that ends or replaces the conversation — `/new`, the `/resume` pick, `/quit`, leaving the folder, each `/quitall`
14564
+ * topic, a move across backends, a start onto another agent or a shell (`switchThreadAdapter`) — closes its open requests, and a person
14565
+ * whose words the agent never took in is told: nobody reads them (review 25 #3; one rule for every such command, review 26 #2). A request
14566
+ * the agent took in closes in silence: its words are in the conversation it had. «Taken in» is the persisted mark or what the live process
14567
+ * says NOW (`readPromptsReachedOrHeld`, read synchronously here — call it before the command stops the process — or handed in by a command
14568
+ * that reads it earlier: the `/resume` pick ahead of the resume that replaces the process, a bridged move ahead of its bridge, so the
14569
+ * reading and the bridge describe the same moment): the mark lags until a settle or the 10-second poll (review 26 #1, review 27 nit 5).
14570
+ * Three prompts are not told here, so each person is told once: one waiting in a window — that window's drop tells it; one on its way to
14571
+ * its write ({@link personPromptsInDelivery}) — its own route refuses it, also once this command is over, since its request is closed here
14572
+ * ({@link personPromptsEndedInDelivery}, marked at this call; review 27 #1, review 28 nit 4); and one whose drop is already being told
14573
+ * (`personDropsBeingTold`). Fire and forget. An interrupt keeps {@link cancelConversationRequest}'s silent close.
14574
+ */
14575
+ function cancelEndingConversationRequests(key, reachedOrHeld) {
14576
+ const engine = requestWakeUpEngine;
14577
+ if (!engine)
14578
+ return;
14579
+ // Not the cancel's to tell: what the live process took in or a window holds, and a person's prompt on its way to its write (review 27 #1)
14580
+ // — which its own route refuses, even once this command is over, since the cancel closes its request (review 28 nit 4).
14581
+ const promptsReachedOrHeld = new Set([...(reachedOrHeld ?? engine.readPromptsReachedOrHeld(key)), ...personPromptsInDelivery.keys()]);
14582
+ for (const [requestId, conversationKey] of personPromptsInDelivery) {
14583
+ if (conversationKey === (0, sessionKey_1.keyToString)(key))
14584
+ personPromptsEndedInDelivery.add(requestId);
14585
+ }
14586
+ void (async () => {
14587
+ const unreadRequestIds = (await engine.cancelConversation(key, promptsReachedOrHeld)).filter((requestId) => !personDropsBeingTold.has(requestId));
14588
+ // A topic line: a tracker conversation never moves to another agent (its fallback stays within Claude).
14589
+ if (unreadRequestIds.length === 0 || !(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
14590
+ return;
14591
+ console.warn(`[requests] ${(0, sessionKey_1.keyToString)(key)}: the conversation ended before its agent read ${unreadRequestIds.join(', ')}; the requests are closed and the topic told`);
14592
+ await withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('agent.queued_prompt_dropped_by_command')));
14593
+ })().catch((e) => console.warn(`[requests] cancelling the requests of ${(0, sessionKey_1.keyToString)(key)} as its conversation ends failed:`, e instanceof Error ? e.message : e));
14594
+ }
13406
14595
  /**
13407
14596
  * @description How a prompt is posted into a conversation's session — the deps of
13408
14597
  * {@link postToSession}, shared by the scheduler's fire and the Jira connector's
13409
- * requests (Jira plan J5, D21).
14598
+ * requests (Jira plan J5, D21). The forward opens no request: a Jira request arrives with its request open and its header in the
14599
+ * text, and a scheduled run meets a topic's requests through the scheduler's own topic ports ({@link forwardScheduledRun},
14600
+ * {@link forwardTopicSchedulerRequestRun}).
13410
14601
  */
13411
14602
  function createSessionPostDeps() {
13412
14603
  return {
@@ -13425,21 +14616,120 @@ function createSessionPostDeps() {
13425
14616
  return { ok: false, reason };
13426
14617
  },
13427
14618
  forwardPrompt: async (conversationKey, text) => {
13428
- const key = (0, sessionKey_1.keyFromString)(conversationKey);
13429
- // A scheduled run in a topic with requests on is a request (S7); a tracker's
13430
- // post arrives with its request already open and its header in the text.
13431
- const opening = await openTopicRequest(key, text, { source: 'scheduledRun', requesterId: topicRequest_1.scheduledRunRequester });
13432
14619
  const buffered = createBufferedOutcome();
13433
- const delivery = await deliverPromptOrBuffer(key, `${opening.header}${text}`, startupPromptBuffer.checkIsStarting(conversationKey), buffered.settle);
13434
- await settleTopicRequestAfterDelivery(key, opening, delivery);
14620
+ const delivery = await deliverPostPrompt((0, sessionKey_1.keyFromString)(conversationKey), text, buffered.settle, { isAccountsNoteCarrier: true });
13435
14621
  // A prompt that waited for the session's start counts only once it reached it: a replay whose write failed is a failed post.
13436
14622
  if (delivery === 'buffered')
13437
14623
  await buffered.assertReplayed();
14624
+ // The session the post ensured went to sleep before the write, and nothing could be woken for it: no turn will take the prompt.
14625
+ if (delivery === 'noSession')
14626
+ throw new Error(noSessionForPostError);
13438
14627
  },
14628
+ // The watches whose turn ended are settled before the post picks a request and builds its text; the reminders they decided, and the
14629
+ // ones handed to the post while it waited, are delivered after the post's own write (`requests/README.md` § Turn starts).
14630
+ settleEndedTurns: (conversationKey) => requestWakeUpEngine?.settleEndedTurnsForPost((0, sessionKey_1.keyFromString)(conversationKey)) ?? Promise.resolve(deliverNoSettledWakes),
14631
+ notePostInFlight: (conversationKey) => requestWakeUpEngine?.notePostInFlight((0, sessionKey_1.keyFromString)(conversationKey)) ?? deliverNoSettledWakes,
14632
+ // A command that ends or replaces the conversation runs: the post waits for it to be over, then goes to what follows — in a move,
14633
+ // after the bridge its own ensure would otherwise overtake (review 26 #5).
14634
+ waitForConversationChange: (conversationKey) => conversationEndings.waitForMessagesAccepted(conversationKey),
13439
14635
  now: () => Date.now(),
13440
14636
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
13441
14637
  };
13442
14638
  }
14639
+ /**
14640
+ * @description A bot-made post's write: the last await before EACH routing of it waits while a command ends or replaces the
14641
+ * conversation (`ConversationEndings.waitForMessagesAccepted`, handed to the route as `waitBeforeRoute`) — before the first routing, and
14642
+ * again after a wake brought the conversation back or an adopt replay was waited out, with only synchronous code between each wait and
14643
+ * its routing. The post's earlier waits (`postToSession`) come before its ensures; after them a topic fire still queues behind the
14644
+ * topic's previous fire, may open the scheduler's request, or wakes the conversation — a move that began meanwhile would otherwise get
14645
+ * the prompt written into the backend it leaves, past the bridge it already built, and the run lost while recorded as delivered (review 27
14646
+ * nit 2, review 28 nit 2). A scheduled run's `headerRequest` — the request its header names, and the conversation's refusal serial when
14647
+ * that request was picked — is refused at a routing whose serial moved and whose request is closed (mini-review of round 28, #3; of round
14648
+ * 29, #2).
14649
+ */
14650
+ function deliverPostPrompt(key, text, onBufferedSettled, options = {}, headerRequest = null) {
14651
+ const conversationKey = (0, sessionKey_1.keyToString)(key);
14652
+ return deliverPromptOrBuffer(key, text, onBufferedSettled, {
14653
+ ...options,
14654
+ waitBeforeRoute: async () => {
14655
+ await conversationEndings.waitForMessagesAccepted(conversationKey);
14656
+ // A command ran since the pick — during this wait, or one that began and ended between two routings (an adopt replay's wait, a
14657
+ // wake's notice) — and closed the request this run's header names: written now, the agent that follows would read a request it
14658
+ // cannot answer, in a turn nothing watches. Refused before it routes; the fire picks again.
14659
+ if (headerRequest !== null && checkIsHeaderRequestClosedByCommand(conversationKey, headerRequest)) {
14660
+ throw new delivery_1.ScheduledRunTargetClosedError(headerRequest.requestId);
14661
+ }
14662
+ },
14663
+ });
14664
+ }
14665
+ /**
14666
+ * @description The header's request of a Telegram topic's scheduled run, with the refusal serial read at its pick (by default now: call it
14667
+ * synchronously with the pick). A tracker conversation stays out (`null`): it never takes a refusal, a move across backends being a
14668
+ * topic's only.
14669
+ */
14670
+ function getScheduledRunHeaderRequest(key, requestId, refusalSerialAtPick = conversationEndings.readRefusalSerial((0, sessionKey_1.keyToString)(key))) {
14671
+ if (requestId === null || !(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
14672
+ return null;
14673
+ return { requestId, refusalSerialAtPick };
14674
+ }
14675
+ /** @description Whether a command ran since the header's request was picked and that request is closed now. */
14676
+ function checkIsHeaderRequestClosedByCommand(conversationKey, headerRequest) {
14677
+ return conversationEndings.readRefusalSerial(conversationKey) !== headerRequest.refusalSerialAtPick
14678
+ && topicRequestLedger?.getOpenRequestById(headerRequest.requestId) === undefined;
14679
+ }
14680
+ /**
14681
+ * @description Write a scheduled run's prompt into a conversation's session and watch the turn it starts as the scheduled run of
14682
+ * the request it RIDES (`ridden`; `null` when none is open — a tracker's — so no turn is watched): a Jira issue's open request, or a
14683
+ * topic's job request or scheduler's request, told whether the fire's job is one of that request's own (`isRequestJob`). It goes through
14684
+ * the buffer-or-forward unit and opens no request: the request it rides owes the answer (`scheduler/scheduledRunTarget.ts`). A prompt
14685
+ * that never reached the agent — its window dropped it, or it found no session and nothing to wake — fails the post, as every session
14686
+ * post does: its run records the error, and a check's failure wake clears `isCheckFailing` so its next failing run wakes the agent again
14687
+ * (review 21 #2). No turn is watched for it.
14688
+ */
14689
+ async function forwardScheduledRun(conversationKey, text, ridden) {
14690
+ const key = (0, sessionKey_1.keyFromString)(conversationKey);
14691
+ // Read in the tick of the pick (the caller picked `ridden` and called here with no await between).
14692
+ const headerRequest = getScheduledRunHeaderRequest(key, ridden?.requestId ?? null);
14693
+ const buffered = createBufferedOutcome();
14694
+ // A tracker fire whose ridden request owes nothing, or with none open: its header says when to answer, so a lost-work note riding it
14695
+ // defers to it and claims no watch (a comment notifies the requester and the issue's watchers). A topic keeps its own resume and wording.
14696
+ const lostWorkTelling = !(0, sessionKeyCodec_1.checkIsTelegramKey)(key) && ridden?.isAnswerOwed !== true ? 'runHeader' : 'plain';
14697
+ const delivery = await deliverPostPrompt(key, text, buffered.settle, { isAccountsNoteCarrier: true, lostWorkTelling }, headerRequest);
14698
+ // A prompt that waited for the session's start counts only once it reached it: a replay whose write failed is a failed post.
14699
+ if (delivery === 'buffered')
14700
+ await buffered.assertReplayed();
14701
+ if (delivery === 'noSession')
14702
+ throw new Error(noSessionForPostError);
14703
+ if (ridden !== null) {
14704
+ await requestWakeUpEngine?.trackForwardedTurn(key, ridden.requestId, { isRequestPrompt: false, isScheduledRun: true, isRequestJob: ridden.isRequestJob });
14705
+ }
14706
+ }
14707
+ /**
14708
+ * @description A topic's scheduled run with no request to ride (`pickTopicRunTarget` → `ownRequest`): open the scheduler's request
14709
+ * (S7, the scheduler's requester — it replaces only one the bot gave up on), forward the prompt behind its header and settle it as
14710
+ * the request's own scheduled run — the turn is tracked as one. A prompt that never reached the agent (its window dropped it, or it
14711
+ * found no session) closes the request nobody was told about and fails the post, as {@link forwardScheduledRun} does (review 21 #2).
14712
+ */
14713
+ async function forwardTopicSchedulerRequestRun(conversationKey, text) {
14714
+ const key = (0, sessionKey_1.keyFromString)(conversationKey);
14715
+ // Read at the pick, ahead of the open: a command during the open's flush closes the request it opens, and counts.
14716
+ const refusalSerialAtPick = conversationEndings.readRefusalSerial(conversationKey);
14717
+ const opening = await openTopicRequest(key, text, { source: 'scheduledRun', requesterId: topicRequest_1.scheduledRunRequester });
14718
+ const buffered = createBufferedOutcome();
14719
+ const headerRequest = getScheduledRunHeaderRequest(key, opening.requestId, refusalSerialAtPick);
14720
+ const delivery = await deliverPostPrompt(key, `${opening.header}${text}`, buffered.settle, { isAccountsNoteCarrier: true }, headerRequest);
14721
+ // A prompt that waited for the session's start counts only once it reached it, and only then is its turn watched (a watch made in
14722
+ // the window would wait for good if the window dropped it). Dropped, the scheduler's request nobody was told about closes like one
14723
+ // that found no session, and the post fails.
14724
+ if (delivery === 'buffered' && (await buffered.getOutcome()) === 'dropped') {
14725
+ await settleTopicRequestAfterDelivery(key, opening, 'noSession');
14726
+ throw new Error(bufferedPromptDroppedError);
14727
+ }
14728
+ await settleTopicRequestAfterDelivery(key, { ...opening, isScheduledRun: true }, delivery);
14729
+ // Closed by the settle when no session was left to take the prompt: the post fails, not read as delivered.
14730
+ if (delivery === 'noSession')
14731
+ throw new Error(noSessionForPostError);
14732
+ }
13443
14733
  /**
13444
14734
  * @description Construct the scheduler stack (S8): run ledger → delivery (thin
13445
14735
  * lambdas over the bot's existing send/session functions) → timer engine
@@ -13505,6 +14795,34 @@ function wireScheduler(wiring) {
13505
14795
  return decision.kind === 'proceed' ? (0, workerActivity_1.readWorkerActivity)(path.resolve(decision.workDir, runDir)) : null;
13506
14796
  },
13507
14797
  statusIntervalOverrideMs: ENV.testTimings.checkStatusIntervalMs,
14798
+ // A topic whose view has requests: a fire rides the job's request or the scheduler's, and opens the scheduler's only when there is
14799
+ // none to ride (`scheduler/scheduledRunTarget.ts`).
14800
+ topicRun: {
14801
+ getRequestView: (threadKeyStr) => {
14802
+ const key = (0, sessionKey_1.keyFromString)(threadKeyStr);
14803
+ if (!(0, sessionKeyCodec_1.checkIsTelegramKey)(key))
14804
+ return null;
14805
+ const { view } = state.getDisplayPrefs(key);
14806
+ return (0, topicView_1.checkAreRequestsEnabled)(view) ? { isPlainTextHidden: !(0, topicView_1.checkIsStreamShown)(view) } : null;
14807
+ },
14808
+ listOpenRequests: (threadKeyStr) => wiring.requestLedger.listOpenRequestsOf((0, sessionKey_1.keyFromString)(threadKeyStr)),
14809
+ forwardRun: forwardScheduledRun,
14810
+ forwardOwnRequestRun: forwardTopicSchedulerRequestRun,
14811
+ },
14812
+ // A Jira issue's fires post nothing there and ride the open request (`scheduler/scheduledRunTarget.ts`).
14813
+ ...(jiraConnector
14814
+ ? {
14815
+ trackerRun: {
14816
+ describeConversation: (threadKeyStr) => {
14817
+ const key = (0, sessionKey_1.keyFromString)(threadKeyStr);
14818
+ return key.platform === 'jira' ? jiraConnector.describeConversation(key) : null;
14819
+ },
14820
+ listOpenRequests: (threadKeyStr) => wiring.requestLedger.listOpenRequestsOf((0, sessionKey_1.keyFromString)(threadKeyStr)),
14821
+ forwardRun: forwardScheduledRun,
14822
+ fallbackAdapterName: jiraConnector.adapterName,
14823
+ },
14824
+ }
14825
+ : {}),
13508
14826
  });
13509
14827
  /**
13510
14828
  * The engine's deliver callback: the S4 pipeline plus the S8 unbound-pause
@@ -13518,11 +14836,15 @@ function wireScheduler(wiring) {
13518
14836
  if (outcome.status === 'failed' && outcome.error === delivery_1.unboundDeliveryError) {
13519
14837
  await state.setSchedulePaused(job.id, true, 'unbound');
13520
14838
  schedulerEngine?.disarmJob(job.id);
13521
- await withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('schedule.pausedUnbound', { count: 1 }))).catch(() => { });
14839
+ // The bot posts nothing on an issue: a tracker conversation's pause is a log line, and its jobs resume with its next usable bind.
14840
+ if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
14841
+ await withThreadLocale(key, () => replyToThread(key, (0, i18n_1.t)('schedule.pausedUnbound', { count: 1 }))).catch(() => { });
14842
+ else
14843
+ console.log(`[scheduler] job ${job.id} of ${job.threadKey} paused: its folder is not usable; it resumes when a request finds the folder usable again`);
13522
14844
  }
13523
14845
  return outcome;
13524
14846
  };
13525
- schedulerEngine = (0, engine_1.createSchedulerEngine)({
14847
+ schedulerEngine = (0, engine_2.createSchedulerEngine)({
13526
14848
  store: state,
13527
14849
  ledger,
13528
14850
  deliver,
@@ -13557,11 +14879,45 @@ function wireScheduler(wiring) {
13557
14879
  sendMessagesToThread,
13558
14880
  compactConversation: (threadKeyStr) => armDeferredCompaction((0, sessionKey_1.keyFromString)(threadKeyStr)),
13559
14881
  listClaudeProfiles: listClaudeProfilesForAgent,
14882
+ // The accounts note (`limitNotes/`): the send tools' results carry it, and the two calls that mark a conversation as launching workers record it.
14883
+ takeLimitNoteForSend: (threadKeyStr) => {
14884
+ const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
14885
+ return key === null ? null : getLimitNotes().takeSendResultNote(key);
14886
+ },
14887
+ noteLimitProfilesCall: (threadKeyStr) => {
14888
+ const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
14889
+ if (key === null)
14890
+ return;
14891
+ // The agent looks now: a reminder still waiting in its inbox is stale before it is read — the hook runs after this tool's result —
14892
+ // so it is withdrawn (a file the hook already took is recorded first), then the look is recorded over it.
14893
+ withdrawAccountsInbox(key);
14894
+ getLimitNotes().noteProfilesCall(key);
14895
+ },
14896
+ noteLimitWorkerWatch: (threadKeyStr) => {
14897
+ const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
14898
+ if (key !== null)
14899
+ getLimitNotes().noteWorkerWatch(key);
14900
+ },
14901
+ // The request a job is armed under (`ScheduleRecord.requestId`): the one the agent works on — the request whose forward started the
14902
+ // running turn (the scheduler's request too, when its fire did); the scheduler's request is passed over only where no turn tells.
14903
+ getArmingRequestId: (threadKeyStr) => {
14904
+ const key = (0, sessionKey_1.tryKeyFromString)(threadKeyStr);
14905
+ if (key === null)
14906
+ return undefined;
14907
+ return requestWakeUpEngine?.getArmingRequestIdOf(key) ?? (0, scheduleWait_1.pickRequestToArmUnder)(wiring.requestLedger.listOpenRequestsOf(key), []);
14908
+ },
13560
14909
  getRemoteRunRunnerLines: () => (0, runnerSummary_1.getRunnerSummaryLines)(),
13561
14910
  // A refused tool call leaves one line in the bounded diagnostic log (agent-diag.log): the SDK refuses before the bot sees it.
13562
14911
  logDiagnostic: diagLog_1.appendDiagLog,
13563
14912
  ...(jiraConnector
13564
- ? { fetchJiraAttachment: (threadKeyStr, attachmentId) => jiraConnector.fetchAttachment((0, sessionKey_1.keyFromString)(threadKeyStr), attachmentId) }
14913
+ ? {
14914
+ fetchJiraAttachment: (threadKeyStr, attachmentId) => jiraConnector.fetchAttachment((0, sessionKey_1.keyFromString)(threadKeyStr), attachmentId),
14915
+ // Through the issue's outbound, like a topic's file send: the agent-facing tool is a connector delivery.
14916
+ sendJiraFiles: (threadKeyStr, request) => {
14917
+ const key = (0, sessionKey_1.keyFromString)(threadKeyStr);
14918
+ return getOutboundFor(key).deliverFile(key, request);
14919
+ },
14920
+ }
13565
14921
  : {}),
13566
14922
  // Read per request: General can turn the shared lists off, and the tools go with them.
13567
14923
  get todos() {
@@ -13621,6 +14977,14 @@ function getOperatorGeneralKey() {
13621
14977
  const ownerUserId = getOwnerUserId();
13622
14978
  return Number.isFinite(ownerUserId) ? (0, sessionKeyCodec_1.makeTelegramKey)(ownerUserId, threadRouting_1.DM_GENERAL_THREAD_ID) : null;
13623
14979
  }
14980
+ /** How the bot is named to the operator: its `@username`, else the host it runs on. */
14981
+ function getBotLabel() {
14982
+ return bot.botInfo?.username === undefined ? os.hostname() : `@${bot.botInfo.username}`;
14983
+ }
14984
+ /** The operator's private chat to message them in (`resolveOperatorPrivateChatKey`); `null` when none would do. */
14985
+ function getOperatorPrivateChatKey() {
14986
+ return (0, threadRouting_1.resolveOperatorPrivateChatKey)({ isDmSurfaceActive: checkIsDmSurfaceActive(), ownerUserId: getOwnerUserId(), generalKey: getOperatorGeneralKey() });
14987
+ }
13624
14988
  /**
13625
14989
  * @description Say an update message in General, worded in that chat's language: pinned when it asks the operator to act, with
13626
14990
  * the install tap (the version printed on the button is the version it installs) when it offers one. A failed send or pin is
@@ -13803,32 +15167,20 @@ function createJiraSessionDeps(requestLedger, slots, adapterName) {
13803
15167
  bindConversation: async (key, folder) => {
13804
15168
  if (state.getBinding(key)?.subdir !== folder)
13805
15169
  await state.setBinding(key, folder);
15170
+ // A fire that found no usable folder paused its job; a request that finds it usable resumes it, as `/bind` does in a topic.
15171
+ if ((0, validation_1.resolveBoundWorkDir)(ENV.workRoot, state.getBinding(key)).kind === 'proceed') {
15172
+ await resumeTrackerSchedulesOnRebind(key).catch((e) => console.warn(`[scheduler] resume-on-rebind failed for ${(0, sessionKey_1.keyToString)(key)}:`, e));
15173
+ }
13806
15174
  },
13807
15175
  createRequest: (key, origin, createPrompt) => requestLedger.createRequest(key, origin, { createPrompt }),
13808
15176
  listOpenRequests: (key) => requestLedger.listOpenRequestsOf(key),
13809
- postRequest: async (key, requestId, prompt) => {
13810
- // A request is the issue's "user message" (L-D5): it clears the spent idle-compaction
13811
- // latch like a topic's message does, or the issue would never compact again.
13812
- notePersonActivity(key);
13813
- const posted = await (0, postToSession_1.postToSession)(sessionPostDeps, (0, sessionKey_1.keyToString)(key), prompt, adapterName);
13814
- if (!posted.ok) {
13815
- // R28: retried at about 1, 5 and 15 min, outside the wake-up cap.
13816
- await requestWakeUpEngine?.notePostFailed(key, requestId);
13817
- throw new Error(posted.reason === 'forward-failed' ? posted.error : `session ${posted.reason}`);
13818
- }
13819
- // A held request is tracked when the wait's resume, or else its next wake-up, posts its prompt (R21).
13820
- if (!posted.isHeld)
13821
- await requestWakeUpEngine?.trackForwardedTurn(key, requestId, { isRequestPrompt: true });
13822
- },
13823
- // An issue update (a comment for an open hand-over request) opens no request: the turn it starts is that request's.
13824
- postUpdate: async (key, prompt, getTargetRequestId) => {
13825
- notePersonActivity(key);
13826
- const posted = await (0, postToSession_1.postToSession)(sessionPostDeps, (0, sessionKey_1.keyToString)(key), prompt, adapterName);
13827
- if (!posted.ok)
13828
- throw new Error(posted.reason === 'forward-failed' ? posted.error : `session ${posted.reason}`);
13829
- if (!posted.isHeld)
13830
- await requestWakeUpEngine?.trackForwardedTurn(key, getTargetRequestId());
13831
- },
15177
+ // A request is the issue's "user message" (L-D5): posting it restarts the idle countdown, like a topic's message does. An issue
15178
+ // update (a comment for an open hand-over request) opens no request: the turn it starts is that request's.
15179
+ ...(0, trackerTurnPoster_1.createTrackerTurnPoster)({
15180
+ post: (key, prompt, options) => (0, postToSession_1.postToSession)(sessionPostDeps, (0, sessionKey_1.keyToString)(key), prompt, adapterName, options),
15181
+ notePersonActivity,
15182
+ getEngine: () => requestWakeUpEngine,
15183
+ }),
13832
15184
  };
13833
15185
  }
13834
15186
  async function startBot() {
@@ -13888,7 +15240,10 @@ async function startBot() {
13888
15240
  (0, claudeApiCreditRecheck_1.startClaudeApiCreditRechecks)(claudeApiCreditRecheckPorts, ENV.testTimings.creditRecheckPollMs ?? claudeApiCreditRecheck_1.claudeApiCreditRecheckPollMs);
13889
15241
  const jiraConnector = ENV.servedPlatforms.has('jira') ? await prepareJiraConnectorOrExit() : null;
13890
15242
  todoJiraConversations = jiraConnector;
15243
+ // The operator issue plays General's part for the alerts only the operator can act on (a Claude account signed out).
15244
+ operatorAlertChannels = jiraConnector?.operatorChannel ? [jiraConnector.operatorChannel] : [];
13891
15245
  if (jiraConnector) {
15246
+ jiraFileSender = (key, request) => jiraConnector.sendFiles(key, request);
13892
15247
  const { launchDefaults } = jiraConnector;
13893
15248
  (0, createAdapter_1.registerSessionLaunchDefaultsReader)((key) => (key.platform === 'jira' ? launchDefaults : null));
13894
15249
  }
@@ -13927,6 +15282,7 @@ async function startBot() {
13927
15282
  requestWakeUpEngine = new wakeUpEngine_1.RequestWakeUpEngine({
13928
15283
  ledger: requestLedger,
13929
15284
  probeTurn: probeThreadTurn,
15285
+ refreshProcessState: (key) => (0, createAdapter_1.getThreadAdapter)(key).refreshWorkingState?.(key),
13930
15286
  prepareWakeUpSession: (key, message) => prepareRequestWakeUpSession(key, message, key.platform === 'jira' ? jiraConnector?.adapterName : undefined),
13931
15287
  forwardWakeUp: forwardRequestWakeUp,
13932
15288
  deliverAlert: async (key, request, reason) => {
@@ -13947,6 +15303,9 @@ async function startBot() {
13947
15303
  pollIntervalMs: ENV.testTimings.requestTurnPollMs,
13948
15304
  sweepIntervalMs: ENV.testTimings.requestSweepIntervalMs,
13949
15305
  firstPostRetryDelayMs: ENV.testTimings.requestFirstPostRetryDelayMs,
15306
+ progressFollowUpMs: ENV.testTimings.progressFollowUpMs,
15307
+ // A request waits for its schedule while a job armed under it counts (`requests/scheduleWait.ts`): read when a decision is made.
15308
+ getScheduleWait: (key, request) => (0, scheduleWait_1.getRequestScheduleWait)(state.getThreadSchedules(key), request),
13950
15309
  // Only a Telegram topic in the answers-only view hides the stream from someone who expects to see the work.
13951
15310
  checkIsAnswerTailWatched: (key) => (0, sessionKeyCodec_1.checkIsTelegramKey)(key) && !(0, topicView_1.checkIsStreamShown)(state.getDisplayPrefs(key).view),
13952
15311
  remindAnswerTail,
@@ -13969,7 +15328,19 @@ async function startBot() {
13969
15328
  midTurn: getTodoMidTurn(),
13970
15329
  pollIntervalMs: ENV.testTimings.todoReminderPollMs,
13971
15330
  });
13972
- getTodoMidTurn().clearInboxes();
15331
+ // The accounts note's mid-turn delivery polls the same turns, for Claude on the json-stream host only (`limitNotes/engine.ts`).
15332
+ limitNotesEngine = new engine_1.LimitNotesEngine({
15333
+ listConversations: () => state.listBindings().map(({ key }) => key),
15334
+ getClaudeSessionId: (key) => {
15335
+ const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name;
15336
+ return adapterName !== undefined && (0, adapterNames_1.checkIsJsonStreamBackend)(adapterName) ? getResumableSessionId(key) : null;
15337
+ },
15338
+ probeTurn: probeThreadTurn,
15339
+ notes: getLimitNotes(),
15340
+ inbox: getMidTurnInbox(),
15341
+ pollIntervalMs: ENV.testTimings.limitNoteEnginePollMs,
15342
+ });
15343
+ getMidTurnInbox().clearAll();
13973
15344
  warmTodoProjects();
13974
15345
  // Snapshot the persisted transient status-frame ids (S2) NOW, before reattach
13975
15346
  // can run any frame-id setter. A reattached session's first frame lifecycle
@@ -14074,11 +15445,11 @@ async function startBot() {
14074
15445
  }),
14075
15446
  onStopped: (key) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'stopped', () => withThreadLocale(key, () => handleAgentStopped(key)), () => clearForeignSessionState(key)),
14076
15447
  onSuspended: (key) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'suspended', () => withThreadLocale(key, () => handleAgentSuspended(key)), () => scheduleLostWorkNote(key, takeLostWorkOf(key), 'holdExpired')),
14077
- onTurnEnded: (key) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'turnEnded', () => {
15448
+ onTurnEnded: (key, turnEnd) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'turnEnded', () => {
14078
15449
  // Every platform's (the route is `all`): the todo reminder's turn end, which the per-turn stop below would
14079
15450
  // otherwise hide from its poll.
14080
15451
  void todoReminderEngine?.noteAdapterTurnEnd(key).catch((e) => console.warn(`[todos] the turn end of ${(0, sessionKey_1.keyToString)(key)} was not noted:`, e instanceof Error ? e.message : e));
14081
- handleAgentTurnEnded(key);
15452
+ handleAgentTurnEnded(key, turnEnd);
14082
15453
  }),
14083
15454
  onContextCompacted: (key, trigger) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'contextCompacted', () => {
14084
15455
  noteConversationContextReset(key, `compaction (${trigger ?? 'bot'})`);
@@ -14245,7 +15616,10 @@ async function startBot() {
14245
15616
  // A tracker conversation whose process did not survive the downtime resumes its open request now, not at the backstop.
14246
15617
  scheduleRestartWakesAtBoot(requestLedger);
14247
15618
  todoReminderEngine?.start();
15619
+ limitNotesEngine?.start();
14248
15620
  jiraConnector?.start(createJiraSessionDeps(requestLedger, slots, jiraConnector.adapterName));
15621
+ // The accounts' changes found while booting are told now, and the conversations waiting for an account may go on.
15622
+ openOperatorAlerts();
14249
15623
  },
14250
15624
  healActiveSessions: () => {
14251
15625
  // When this boot ADOPTED an already-running opencode, that server may
@@ -14471,6 +15845,7 @@ async function startBot() {
14471
15845
  schedulerEngine?.shutdown();
14472
15846
  requestWakeUpEngine?.stop();
14473
15847
  todoReminderEngine?.stop();
15848
+ limitNotesEngine?.stop();
14474
15849
  topicIndicator.stop();
14475
15850
  jiraConnector?.stop();
14476
15851
  if (isSchedulerMcpStarted)