charness 4.2.0 → 4.3.1

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 (553) hide show
  1. package/CHANGELOG.md +168 -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 +62 -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 +18 -7
  32. package/dist/apiRetryKick.d.ts.map +1 -1
  33. package/dist/apiRetryKick.js +26 -13
  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 +2055 -653
  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 +366 -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 +70 -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 +26 -3
  272. package/dist/requests/sessionTurnProbe.d.ts.map +1 -1
  273. package/dist/requests/sessionTurnProbe.js +22 -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 +26 -5
  284. package/dist/requests/types.d.ts.map +1 -1
  285. package/dist/requests/wakeUpEngine.d.ts +201 -12
  286. package/dist/requests/wakeUpEngine.d.ts.map +1 -1
  287. package/dist/requests/wakeUpEngine.js +514 -44
  288. package/dist/requests/wakeUpEngine.js.map +1 -1
  289. package/dist/requests/wakeUpRules.d.ts +185 -14
  290. package/dist/requests/wakeUpRules.d.ts.map +1 -1
  291. package/dist/requests/wakeUpRules.js +169 -36
  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 +68 -4
  336. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  337. package/dist/scheduler/mcpSurface.js +363 -189
  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/shutdown.d.ts +12 -0
  373. package/dist/shutdown.d.ts.map +1 -1
  374. package/dist/shutdown.js +11 -0
  375. package/dist/shutdown.js.map +1 -1
  376. package/dist/startupPromptBuffer.d.ts +35 -6
  377. package/dist/startupPromptBuffer.d.ts.map +1 -1
  378. package/dist/startupPromptBuffer.js +70 -21
  379. package/dist/startupPromptBuffer.js.map +1 -1
  380. package/dist/state.d.ts +173 -25
  381. package/dist/state.d.ts.map +1 -1
  382. package/dist/state.js +282 -58
  383. package/dist/state.js.map +1 -1
  384. package/dist/testTimings.d.ts +8 -3
  385. package/dist/testTimings.d.ts.map +1 -1
  386. package/dist/testTimings.js +15 -2
  387. package/dist/testTimings.js.map +1 -1
  388. package/dist/threadContextPreamble.d.ts +7 -0
  389. package/dist/threadContextPreamble.d.ts.map +1 -1
  390. package/dist/threadContextPreamble.js +11 -0
  391. package/dist/threadContextPreamble.js.map +1 -1
  392. package/dist/threadRouting.d.ts +12 -0
  393. package/dist/threadRouting.d.ts.map +1 -1
  394. package/dist/threadRouting.js +15 -0
  395. package/dist/threadRouting.js.map +1 -1
  396. package/dist/todos/midTurn.d.ts +15 -41
  397. package/dist/todos/midTurn.d.ts.map +1 -1
  398. package/dist/todos/midTurn.js +27 -171
  399. package/dist/todos/midTurn.js.map +1 -1
  400. package/dist/types.d.ts +147 -23
  401. package/dist/types.d.ts.map +1 -1
  402. package/dist/types.js +10 -0
  403. package/dist/types.js.map +1 -1
  404. package/dist/utils/backendSwitchPlan.d.ts +3 -3
  405. package/dist/utils/backendSwitchPlan.js +3 -3
  406. package/dist/utils/claudeAccountAlert.d.ts +104 -0
  407. package/dist/utils/claudeAccountAlert.d.ts.map +1 -0
  408. package/dist/utils/claudeAccountAlert.js +130 -0
  409. package/dist/utils/claudeAccountAlert.js.map +1 -0
  410. package/dist/utils/claudeAccountPickerPlan.d.ts +7 -0
  411. package/dist/utils/claudeAccountPickerPlan.d.ts.map +1 -1
  412. package/dist/utils/claudeAccountPickerPlan.js +13 -2
  413. package/dist/utils/claudeAccountPickerPlan.js.map +1 -1
  414. package/dist/utils/claudeAuthRefusal.d.ts +122 -0
  415. package/dist/utils/claudeAuthRefusal.d.ts.map +1 -0
  416. package/dist/utils/claudeAuthRefusal.js +228 -0
  417. package/dist/utils/claudeAuthRefusal.js.map +1 -0
  418. package/dist/utils/claudeCompactHook.d.ts +6 -6
  419. package/dist/utils/claudeCompactHook.js +8 -8
  420. package/dist/utils/claudeCompactHook.js.map +1 -1
  421. package/dist/utils/claudeProfileUsageViews.d.ts +54 -2
  422. package/dist/utils/claudeProfileUsageViews.d.ts.map +1 -1
  423. package/dist/utils/claudeProfileUsageViews.js +44 -1
  424. package/dist/utils/claudeProfileUsageViews.js.map +1 -1
  425. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  426. package/dist/utils/claudeProfiles.js +10 -1
  427. package/dist/utils/claudeProfiles.js.map +1 -1
  428. package/dist/utils/claudeRuntimeInfo.d.ts +24 -0
  429. package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -1
  430. package/dist/utils/claudeRuntimeInfo.js +128 -3
  431. package/dist/utils/claudeRuntimeInfo.js.map +1 -1
  432. package/dist/utils/claudeScheduledJobs.d.ts +6 -2
  433. package/dist/utils/claudeScheduledJobs.d.ts.map +1 -1
  434. package/dist/utils/claudeScheduledJobs.js +10 -2
  435. package/dist/utils/claudeScheduledJobs.js.map +1 -1
  436. package/dist/utils/claudeSessionTitle.js +1 -1
  437. package/dist/utils/claudeSessionTitle.js.map +1 -1
  438. package/dist/utils/claudeStreamJson.d.ts +28 -2
  439. package/dist/utils/claudeStreamJson.d.ts.map +1 -1
  440. package/dist/utils/claudeStreamJson.js +33 -3
  441. package/dist/utils/claudeStreamJson.js.map +1 -1
  442. package/dist/utils/claudeTranscriptEpoch.d.ts +14 -0
  443. package/dist/utils/claudeTranscriptEpoch.d.ts.map +1 -1
  444. package/dist/utils/claudeTranscriptEpoch.js +79 -19
  445. package/dist/utils/claudeTranscriptEpoch.js.map +1 -1
  446. package/dist/utils/claudeUsage.d.ts +103 -7
  447. package/dist/utils/claudeUsage.d.ts.map +1 -1
  448. package/dist/utils/claudeUsage.js +108 -15
  449. package/dist/utils/claudeUsage.js.map +1 -1
  450. package/dist/utils/compactOnIdle.d.ts +139 -29
  451. package/dist/utils/compactOnIdle.d.ts.map +1 -1
  452. package/dist/utils/compactOnIdle.js +163 -36
  453. package/dist/utils/compactOnIdle.js.map +1 -1
  454. package/dist/utils/conversationEnding.d.ts +76 -0
  455. package/dist/utils/conversationEnding.d.ts.map +1 -0
  456. package/dist/utils/conversationEnding.js +117 -0
  457. package/dist/utils/conversationEnding.js.map +1 -0
  458. package/dist/utils/doctorLine.d.ts +10 -0
  459. package/dist/utils/doctorLine.d.ts.map +1 -1
  460. package/dist/utils/doctorLine.js +16 -0
  461. package/dist/utils/doctorLine.js.map +1 -1
  462. package/dist/utils/fallbackBridge.d.ts.map +1 -1
  463. package/dist/utils/fallbackBridge.js +2 -1
  464. package/dist/utils/fallbackBridge.js.map +1 -1
  465. package/dist/utils/fallbackChain.d.ts +2 -0
  466. package/dist/utils/fallbackChain.d.ts.map +1 -1
  467. package/dist/utils/fallbackChain.js +4 -3
  468. package/dist/utils/fallbackChain.js.map +1 -1
  469. package/dist/utils/fallbackSwitchNotice.d.ts +11 -4
  470. package/dist/utils/fallbackSwitchNotice.d.ts.map +1 -1
  471. package/dist/utils/fallbackSwitchNotice.js +9 -5
  472. package/dist/utils/fallbackSwitchNotice.js.map +1 -1
  473. package/dist/utils/fileSendService.d.ts +31 -0
  474. package/dist/utils/fileSendService.d.ts.map +1 -1
  475. package/dist/utils/fileSendService.js +45 -2
  476. package/dist/utils/fileSendService.js.map +1 -1
  477. package/dist/utils/jsonStreamHost.d.ts +2 -0
  478. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  479. package/dist/utils/jsonStreamHost.js +4 -1
  480. package/dist/utils/jsonStreamHost.js.map +1 -1
  481. package/dist/utils/jsonStreamPendingWork.d.ts +14 -2
  482. package/dist/utils/jsonStreamPendingWork.d.ts.map +1 -1
  483. package/dist/utils/jsonStreamPendingWork.js +25 -5
  484. package/dist/utils/jsonStreamPendingWork.js.map +1 -1
  485. package/dist/utils/jsonStreamUnconsumedInput.d.ts +80 -0
  486. package/dist/utils/jsonStreamUnconsumedInput.d.ts.map +1 -0
  487. package/dist/utils/jsonStreamUnconsumedInput.js +99 -0
  488. package/dist/utils/jsonStreamUnconsumedInput.js.map +1 -0
  489. package/dist/utils/limitEpisodeRecovery.d.ts +43 -4
  490. package/dist/utils/limitEpisodeRecovery.d.ts.map +1 -1
  491. package/dist/utils/limitEpisodeRecovery.js +107 -20
  492. package/dist/utils/limitEpisodeRecovery.js.map +1 -1
  493. package/dist/utils/limitHeldPrompts.d.ts +21 -11
  494. package/dist/utils/limitHeldPrompts.d.ts.map +1 -1
  495. package/dist/utils/limitHeldPrompts.js +12 -9
  496. package/dist/utils/limitHeldPrompts.js.map +1 -1
  497. package/dist/utils/limitRemindersScreenPlan.d.ts +63 -0
  498. package/dist/utils/limitRemindersScreenPlan.d.ts.map +1 -0
  499. package/dist/utils/limitRemindersScreenPlan.js +121 -0
  500. package/dist/utils/limitRemindersScreenPlan.js.map +1 -0
  501. package/dist/utils/limitSwitchPlan.d.ts +51 -14
  502. package/dist/utils/limitSwitchPlan.d.ts.map +1 -1
  503. package/dist/utils/limitSwitchPlan.js +33 -15
  504. package/dist/utils/limitSwitchPlan.js.map +1 -1
  505. package/dist/utils/limitsBoardPlan.d.ts +16 -7
  506. package/dist/utils/limitsBoardPlan.d.ts.map +1 -1
  507. package/dist/utils/limitsBoardPlan.js +41 -9
  508. package/dist/utils/limitsBoardPlan.js.map +1 -1
  509. package/dist/utils/lostWork.d.ts +16 -2
  510. package/dist/utils/lostWork.d.ts.map +1 -1
  511. package/dist/utils/lostWork.js +16 -3
  512. package/dist/utils/lostWork.js.map +1 -1
  513. package/dist/utils/messageContext.d.ts +2 -2
  514. package/dist/utils/messageContext.js +2 -2
  515. package/dist/utils/midTurnInbox.d.ts +79 -0
  516. package/dist/utils/midTurnInbox.d.ts.map +1 -0
  517. package/dist/utils/midTurnInbox.js +265 -0
  518. package/dist/utils/midTurnInbox.js.map +1 -0
  519. package/dist/utils/promptDelivery.d.ts +70 -22
  520. package/dist/utils/promptDelivery.d.ts.map +1 -1
  521. package/dist/utils/promptDelivery.js +100 -42
  522. package/dist/utils/promptDelivery.js.map +1 -1
  523. package/dist/utils/topicIndicatorPlan.d.ts +13 -3
  524. package/dist/utils/topicIndicatorPlan.d.ts.map +1 -1
  525. package/dist/utils/topicIndicatorPlan.js +26 -4
  526. package/dist/utils/topicIndicatorPlan.js.map +1 -1
  527. package/dist/utils/topicRequest.d.ts +3 -0
  528. package/dist/utils/topicRequest.d.ts.map +1 -1
  529. package/dist/utils/topicRequest.js +4 -0
  530. package/dist/utils/topicRequest.js.map +1 -1
  531. package/dist/utils/workerRoles.d.ts +122 -0
  532. package/dist/utils/workerRoles.d.ts.map +1 -0
  533. package/dist/utils/workerRoles.js +160 -0
  534. package/dist/utils/workerRoles.js.map +1 -0
  535. package/dist/utils/workerRolesScreenPlan.d.ts +118 -0
  536. package/dist/utils/workerRolesScreenPlan.d.ts.map +1 -0
  537. package/dist/utils/workerRolesScreenPlan.js +232 -0
  538. package/dist/utils/workerRolesScreenPlan.js.map +1 -0
  539. package/dist/utils/workingSignals.d.ts +59 -0
  540. package/dist/utils/workingSignals.d.ts.map +1 -0
  541. package/dist/utils/workingSignals.js +60 -0
  542. package/dist/utils/workingSignals.js.map +1 -0
  543. package/licensing.json +88 -0
  544. package/npm-shrinkwrap.json +2 -2
  545. package/package.json +7 -7
  546. package/{remoteRun → runner-scripts}/runner.sh +6 -3
  547. package/LICENSE-COMMERCIAL.md +0 -142
  548. package/dist/agentTrigger.d.ts +0 -28
  549. package/dist/agentTrigger.d.ts.map +0 -1
  550. package/dist/agentTrigger.js +0 -53
  551. package/dist/agentTrigger.js.map +0 -1
  552. /package/{remoteRun → runner-scripts}/ensureNode.sh +0 -0
  553. /package/{remoteRun → runner-scripts}/runner-package-lock.json +0 -0
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.RequestWakeUpEngine = exports.restartWakeStaggerMs = exports.turnActivityPersistStepMs = exports.unwatchedSweepMs = exports.watchedTurnPollMs = void 0;
4
4
  const sessionKey_1 = require("../sessionKey");
5
+ const scheduleWait_1 = require("./scheduleWait");
5
6
  const requestHeader_1 = require("./requestHeader");
6
7
  const answerTail_1 = require("./answerTail");
7
8
  const wakeUpRules_1 = require("./wakeUpRules");
@@ -23,6 +24,12 @@ const wakeUpRules_1 = require("./wakeUpRules");
23
24
  *
24
25
  * A wake-up is a reminder forwarded into the SAME session — never a request.
25
26
  * The answer tails are in memory as well: a restart forgets them.
27
+ *
28
+ * A request waits for its schedule while a job armed under it counts (`scheduleWait.ts`, read through the optional
29
+ * `getScheduleWait` port at every decision): the rules then neither prod it nor wake it at a restart, and a turn a scheduler
30
+ * fire started (`isScheduledRun`) that ends without an answer is not silence. A request that owes a person an answer
31
+ * (`checkIsAnswerOwed`) is never held: it is read from the persisted request, so a turn whose watch a restart lost still reaches the
32
+ * backstop. The complete table is `README.md` § Wake-ups.
26
33
  */
27
34
  /** How often a watched turn is polled for its end. */
28
35
  exports.watchedTurnPollMs = 10_000;
@@ -36,23 +43,71 @@ exports.turnActivityPersistStepMs = 60_000;
36
43
  * whose post never settled, superseding the old one — has the time to run before anything is woken.
37
44
  */
38
45
  exports.restartWakeStaggerMs = 30_000;
46
+ /**
47
+ * R21's test: the live process the request prompt was written to has taken it in (a process that replaced it — a re-spawn — lists
48
+ * nothing unread, and that is not the prompt read; one never written to any process is not taken in).
49
+ */
50
+ function checkIsPromptConsumedByLiveProcess(turn, probe) {
51
+ const isAnotherProcess = turn.writtenToProcess !== undefined && probe.processGeneration !== undefined && turn.writtenToProcess !== probe.processGeneration;
52
+ return turn.isRequestPrompt && probe.isActive && !isAnotherProcess && (0, wakeUpRules_1.checkIsTurnInputConsumed)(turn, probe);
53
+ }
54
+ /**
55
+ * Whether a request prompt is in the conversation the agent had at this moment — what an ending command reads to tell a person whose
56
+ * words nobody will read ({@link RequestWakeUpEngine.readPromptsReachedOrHeld}): taken in by the live process it was written to (R21, on
57
+ * the backend's own unread signal — the json-stream Claude's echo, OpenCode's count of the prompts not yet seen as a user message), or,
58
+ * on the one backend with no such signal (the tmux Claude), written to it — it keeps what was typed in its own conversation, where a
59
+ * move's bridge or a later resume reads it, busy or output seen yet or not (review 27 nit 3).
60
+ */
61
+ function checkIsPromptTakenInNow(turn, probe) {
62
+ if (probe.hasUnconsumedInput !== null)
63
+ return checkIsPromptConsumedByLiveProcess(turn, probe);
64
+ return turn.isRequestPrompt && probe.isActive && turn.writtenToProcess !== undefined && turn.writtenToProcess === probe.processGeneration;
65
+ }
66
+ /** Whether a request prompt waits in a start's or a stop's window (no process named yet): that window's end delivers or drops it. */
67
+ function checkIsPromptWaitingInWindow(turn, probe) {
68
+ return turn.isRequestPrompt && turn.writtenToProcess === undefined && probe.isWindowOpen === true;
69
+ }
70
+ /**
71
+ * Marks a tracker's watch that sees the agent's own work outlive its turn (`WatchedRequestTurn.hasSeenOwnWork`): still RUNNING while no
72
+ * turn runs (`hasOwnLastingWork`). Read at every poll AND every settle (the adapter's turn end): a short command that outlives the turn
73
+ * is seen at the turn end it held open, however soon after it ends. Work the agent starts and finishes inside a turn the bot started
74
+ * is not — nor the notice of its end, which reads as pending for up to 30 s after it, nor the turn the CLI starts for that notice: that
75
+ * work woke nothing, and counted, a nudged agent that ran such a check in every turn would restart the stall count for ever and never
76
+ * be given up. Never under a topic's rules.
77
+ */
78
+ function noteOwnWorkSeen(turn, probe, rules) {
79
+ if (rules === 'tracker' && probe.hasOwnLastingWork === true && !probe.isBusy)
80
+ turn.hasSeenOwnWork = true;
81
+ }
39
82
  class RequestWakeUpEngine {
40
83
  deps;
41
84
  now;
42
85
  /** The watched turns by REQUEST id (a conversation may hold one per requester). */
43
86
  watched = new Map();
87
+ /**
88
+ * The process the last prompt written into each conversation went to (serialized key → process), stamped at the write choke point
89
+ * ({@link noteWrite}): a watch tracked after that process went down — a re-spawn takes it down right after a post's write, and the
90
+ * post tracks several awaits later — is named from it, never left unnamed (review 22 nit 2).
91
+ */
92
+ writtenProcesses = new Map();
44
93
  /** Last persisted live-turn activity per request id, for the persist step. */
45
94
  activityPersistedAt = new Map();
46
95
  /** The tail after the latest final answer, by serialized conversation key. */
47
96
  answerTails = new Map();
48
97
  /** The request whose tail was last reminded and how often, by serialized conversation key (the reminder cap). */
49
98
  answerTailReminders = new Map();
99
+ /** How many posts are on their way to their write, by serialized conversation key ({@link notePostInFlight}). */
100
+ postsInFlight = new Map();
101
+ /** The wake-up deliveries handed to a post in flight, by serialized conversation key, in the order they were decided. */
102
+ wakesHandedToPost = new Map();
50
103
  pollTimer = null;
51
104
  sweepTimer = null;
52
105
  isPolling = false;
53
106
  isSweeping = false;
54
107
  /** The `restarted` wakes waiting for their turn, by serialized conversation key (one per conversation). */
55
108
  restartWakeTimers = new Map();
109
+ /** Conversations whose pending restart wake was asked for by a LOST-WORK loss, not by a boot: no watch holds that one. */
110
+ lostWorkWakes = new Set();
56
111
  /** When the last scheduled `restarted` wake is due: the next one is a stagger after it. */
57
112
  lastRestartWakeDueAt = 0;
58
113
  constructor(deps) {
@@ -85,24 +140,39 @@ class RequestWakeUpEngine {
85
140
  for (const timer of this.restartWakeTimers.values())
86
141
  clearTimeout(timer);
87
142
  this.restartWakeTimers.clear();
143
+ this.lostWorkWakes.clear();
88
144
  }
89
145
  /**
90
146
  * @description The conversation's process is gone while it holds open requests (a boot that did not find it, or a
91
147
  * process that died with its own work pending): wake them `restarted`, a stagger after the last wake scheduled so,
92
148
  * instead of at the backstop. One wake per conversation at a time — a second call while one waits changes nothing.
93
149
  * Whether the requests still need it is decided when it is due (`decideRestartWake`). Returns `false` when one
94
- * was already waiting. The timer is unref'd: it never keeps the process alive.
150
+ * was already waiting, or when every open request is held by a watch that is not failing and owes nobody an answer
151
+ * (`checkIsHeldBetweenTurns`: a BOOT wakes nobody then, as in a topic). `isLostWork` — the process ended with the agent's own work
152
+ * pending — is the other event: a topic resumes on it whatever is armed, so no watch holds the wake, and a boot wake already
153
+ * waiting becomes one (the flag is remembered, the call still returns `false`). The timer is unref'd: it never keeps the process alive.
95
154
  */
96
- scheduleRestartWake(key) {
155
+ scheduleRestartWake(key, options = {}) {
97
156
  const conversationKey = (0, sessionKey_1.keyToString)(key);
98
- if (this.restartWakeTimers.has(conversationKey))
157
+ const isLostWork = options.isLostWork === true;
158
+ if (this.restartWakeTimers.has(conversationKey)) {
159
+ if (isLostWork)
160
+ this.lostWorkWakes.add(conversationKey);
161
+ return false;
162
+ }
163
+ // Every open request is held by a watch that is not failing and owes nobody an answer: nobody is woken at a boot, and no stagger slot is spent on it.
164
+ const openRequests = this.deps.ledger.listOpenRequestsOf(key);
165
+ if (!isLostWork && openRequests.length > 0 && openRequests.every((request) => (0, scheduleWait_1.checkIsHeldBetweenTurns)(request, this.getScheduleWait(key, request))))
99
166
  return false;
167
+ if (isLostWork)
168
+ this.lostWorkWakes.add(conversationKey);
100
169
  const staggerMs = this.deps.restartWakeStaggerMs ?? exports.restartWakeStaggerMs;
101
170
  const dueAt = Math.max(this.now(), this.lastRestartWakeDueAt) + staggerMs;
102
171
  this.lastRestartWakeDueAt = dueAt;
103
172
  const timer = setTimeout(() => {
104
173
  this.restartWakeTimers.delete(conversationKey);
105
- void this.wakeAfterRestart(key).catch((e) => logWakeUpFailure(`the restart wake of ${conversationKey}`, e));
174
+ const isLostWorkWake = this.lostWorkWakes.delete(conversationKey);
175
+ void this.wakeAfterRestart(key, { isLostWork: isLostWorkWake }).catch((e) => logWakeUpFailure(`the restart wake of ${conversationKey}`, e));
106
176
  }, dueAt - this.now());
107
177
  timer.unref?.();
108
178
  this.restartWakeTimers.set(conversationKey, timer);
@@ -115,14 +185,14 @@ class RequestWakeUpEngine {
115
185
  * continuation nudge's turn is. A request at the cap gets its alert instead. A delivery that fails is logged and
116
186
  * left to the backstop (counted from now): no alert of its own. Exported for tests (the timer calls it).
117
187
  */
118
- async wakeAfterRestart(key) {
188
+ async wakeAfterRestart(key, options = {}) {
119
189
  const probe = this.deps.probeTurn(key);
120
190
  const nowMs = this.now();
121
191
  const woken = [];
122
192
  for (const request of this.deps.ledger.listOpenRequestsOf(key)) {
123
193
  if (this.watched.has(request.id))
124
194
  continue;
125
- const decision = (0, wakeUpRules_1.decideRestartWake)(request, probe, nowMs);
195
+ const decision = (0, wakeUpRules_1.decideRestartWake)(request, probe, nowMs, this.getScheduleWait(key, request), options.isLostWork === true);
126
196
  if (decision.kind === 'alert') {
127
197
  await this.applyDecision(key, request, decision);
128
198
  continue;
@@ -137,11 +207,25 @@ class RequestWakeUpEngine {
137
207
  if (updated && !isStoppedMeanwhile)
138
208
  woken.push(updated);
139
209
  }
140
- if (woken.length === 0)
210
+ if (woken.length === 0) {
211
+ // The bot already said the conversation is woken for its lost work: when no request could be, say so (each skip is a decision of
212
+ // `decideRestartWake`: a request given up on, at the cap, with a post retry or a follow-up that can still fire, busy or blocked).
213
+ if (options.isLostWork === true)
214
+ console.warn(`[requests] ${(0, sessionKey_1.keyToString)(key)}: the lost-work wake woke no request; the note rides the next prompt`);
141
215
  return;
216
+ }
217
+ // A lost-work wake of a request a passing watch holds and that owes nobody: the agent is asked to answer only with what the requester
218
+ // must know (the fire header's wording). Every other request — a boot's, one that owes an answer — gets the plain «answer it».
219
+ const isAnswerOptional = (request) => options.isLostWork === true && (0, scheduleWait_1.checkIsHeldBetweenTurns)(request, this.getScheduleWait(key, request));
142
220
  const buildMessage = (requests) => {
143
- const messages = requests.map((request) => (0, requestHeader_1.getWakeUpMessage)(request, 'restarted'));
144
- return { reason: 'restarted', text: messages.map((message) => message.text).join('\n\n'), isRequestPrompt: messages.some((message) => message.isRequestPrompt) };
221
+ const messages = requests.map((request) => (0, requestHeader_1.getWakeUpMessage)(request, 'restarted', { isAnswerOptional: isAnswerOptional(request) }));
222
+ return {
223
+ reason: 'restarted',
224
+ text: messages.map((message) => message.text).join('\n\n'),
225
+ isRequestPrompt: messages.some((message) => message.isRequestPrompt),
226
+ // The one lost-work note rides the whole forward: optional only when EVERY request in it is.
227
+ ...(messages.every((message) => message.isAnswerOptional === true) ? { isAnswerOptional: true } : {}),
228
+ };
145
229
  };
146
230
  try {
147
231
  if (!(await this.deps.prepareWakeUpSession(key, buildMessage(woken)))) {
@@ -158,7 +242,10 @@ class RequestWakeUpEngine {
158
242
  this.deps.noteRestartWakeDelivered?.(key);
159
243
  console.log(`[requests] ${(0, sessionKey_1.keyToString)(key)}: woken after a restart for ${current.map((request) => request.id).join(', ')}`);
160
244
  for (const request of current) {
161
- await this.trackForwardedTurn(key, request.id, { isRequestPrompt: (0, requestHeader_1.getWakeUpMessage)(request, 'restarted').isRequestPrompt });
245
+ await this.trackForwardedTurn(key, request.id, {
246
+ isRequestPrompt: (0, requestHeader_1.getWakeUpMessage)(request, 'restarted').isRequestPrompt,
247
+ isConversationForward: current.length > 1,
248
+ });
162
249
  }
163
250
  }
164
251
  catch (e) {
@@ -170,6 +257,27 @@ class RequestWakeUpEngine {
170
257
  const entry = this.deps.ledger.getOpenRequestById(requestId);
171
258
  return entry && (0, sessionKey_1.keyToString)(entry.key) === (0, sessionKey_1.keyToString)(key) ? entry.request : undefined;
172
259
  }
260
+ /** The ids of the requests whose turns the engine watches in `key`'s conversation: the requests the agent is working on right now. */
261
+ getWatchedRequestIdsOf(key) {
262
+ return this.getWatchedTurnsOf(key).map((turn) => turn.requestId);
263
+ }
264
+ /**
265
+ * The watched requests of `key`'s conversation whose watch a forward of their OWN started (not a conversation-wide nudge), the
266
+ * oldest own forward first: the first is the request whose forward started the running turn.
267
+ */
268
+ getOwnForwardWatchedRequestIdsOf(key) {
269
+ return this.getWatchedTurnsOf(key)
270
+ .filter((turn) => turn.isOwnForward)
271
+ .sort((first, second) => (first.ownForwardStartedAt ?? 0) - (second.ownForwardStartedAt ?? 0))
272
+ .map((turn) => turn.requestId);
273
+ }
274
+ /**
275
+ * @description The request a job armed NOW in `key`'s conversation is armed under (`pickRequestToArmUnder` over the ledger's open
276
+ * requests and this engine's watches); `undefined` when no request is open.
277
+ */
278
+ getArmingRequestIdOf(key) {
279
+ return (0, scheduleWait_1.pickRequestToArmUnder)(this.deps.ledger.listOpenRequestsOf(key), this.getWatchedRequestIdsOf(key), this.getOwnForwardWatchedRequestIdsOf(key));
280
+ }
173
281
  /** The watched turns of `key`'s conversation. */
174
282
  getWatchedTurnsOf(key) {
175
283
  const conversationKey = (0, sessionKey_1.keyToString)(key);
@@ -178,9 +286,22 @@ class RequestWakeUpEngine {
178
286
  /**
179
287
  * @description A request's message (or a reminder for it) was just forwarded to
180
288
  * the conversation's session: watch the turn it starts. A watch already there
181
- * for the SAME request is replaced — its newest message is the one that counts;
182
- * another requester's request in the conversation keeps its own watch. A post
183
- * retry still pending is moot from now on (R28): the session has the request.
289
+ * for the SAME request is MERGED with it (the forward joined a turn that still runs: one that ended was settled before the write,
290
+ * `settleEndedTurnsOf`): the progress count keeps
291
+ * its earlier start, and the turn is the alarm's only if both were — except for the bot's own «continue»
292
+ * (`isContinuation`: the nudge after an API error or a limit wait), which keeps the alarm's kind but
293
+ * starts the progress count afresh: a note sent before the error is not this turn's — and for a person's
294
+ * words that join the running turn, which start the count afresh too: a note sent before them is not their answer. Another requester's
295
+ * request in the conversation keeps its own watch. Whether the turn is a scheduled run's (`isScheduledRun`) is said by the FORWARD
296
+ * that started it — a fire riding the request, or the fire that opened the scheduler's request — and never read from the request's
297
+ * state: an answered request's fire turn is a fire's as much as an unanswered one's (`src/requests/README.md` § Scheduled runs).
298
+ * A fire of ANOTHER job that only rides the request (`isRequestJob` false) is not the request's activity: its forward records none,
299
+ * and its watch keeps that (a merge is the request's own if either side is; a «continue» keeps what the turn was), so its busy time and
300
+ * its quiet end leave the request's follow-up and backstop alone (`src/requests/README.md` § Scheduled runs).
301
+ * A post retry still pending is moot from now on (R28): the session has the request — unless the forward is a fire riding the
302
+ * request, which carries none of its prompt. A forward that carries a person's words (a request prompt, an issue update) marks the
303
+ * request as owing an answer (`isPersonInputUnanswered`, persisted): that, not the kind of the turn, is
304
+ * what stops the turn's end from reading as a quiet one (`decideTurnEnd`).
184
305
  */
185
306
  async trackForwardedTurn(key, requestId, options = { isRequestPrompt: false }) {
186
307
  const request = this.getOpenRequestOf(key, requestId);
@@ -188,17 +309,77 @@ class RequestWakeUpEngine {
188
309
  return;
189
310
  // The agent works on an open request now: what it writes is owed to that one, not a tail.
190
311
  this.answerTails.delete((0, sessionKey_1.keyToString)(key));
312
+ const previous = this.watched.get(requestId);
313
+ const isFireForward = options.isScheduledRun === true;
314
+ // The scheduler's request (a Telegram topic's `scheduledRun`) is no person's: its prompt carries no person's words.
315
+ const isSchedulerRequest = request.origin.kind === 'scheduledRun';
316
+ const carriesPersonWords = options.isRequestPrompt || options.isPersonInput === true;
317
+ // A person's words that reach the agent — not a fire's prompt, not the scheduler's request's.
318
+ const isPersonWordsForward = carriesPersonWords && !isFireForward && !isSchedulerRequest;
319
+ const isOwnForward = options.isConversationForward !== true || previous?.isOwnForward === true;
320
+ const ownForwardStartedAt = previous?.ownForwardStartedAt ?? (isOwnForward ? this.now() : undefined);
321
+ // A fire's turn stays one through a fire that joins it and through the bot's «continue»; a person's words or a reminder that joined
322
+ // it make it theirs.
323
+ const isScheduledRun = previous === undefined
324
+ ? isFireForward
325
+ : previous.isScheduledRun === true && (isFireForward || (options.isContinuation === true && !isPersonWordsForward));
326
+ // Whose turn it is: another job's fire says «not the request's own», a «continue» says nothing (it continues the turn it joins), any
327
+ // other forward — a person's words, a reminder, the request's own job's fire — is the request's own.
328
+ const isOtherJobFireForward = isFireForward && options.isRequestJob === false;
329
+ const isForwardOwn = options.isContinuation === true && !isPersonWordsForward ? undefined : !isOtherJobFireForward;
330
+ const isRequestJob = previous === undefined ? isForwardOwn !== false : previous.isRequestJob !== false || isForwardOwn === true;
331
+ // Where the request's prompt now is: a forward that carries it was written to the live process (none named while a window holds it
332
+ // in the buffer, for its replay to name); one that does not carry it leaves the prompt where it was. A process that went down since
333
+ // the write — no live one, and no window — is the one the write stamped.
334
+ const probe = this.deps.probeTurn(key);
335
+ const writtenNow = probe.processGeneration ?? (probe.isWindowOpen === true ? undefined : this.writtenProcesses.get((0, sessionKey_1.keyToString)(key)));
336
+ const writtenToProcess = previous === undefined || options.isRequestPrompt ? writtenNow : previous.writtenToProcess;
191
337
  this.watched.set(requestId, {
192
338
  key,
193
339
  requestId,
194
- progressCountAtTurnStart: request.progressAnswerCount,
340
+ // The progress count starts afresh at a «continue» and at words that join a turn already running: a note sent before them is
341
+ // not their answer (it would end the turn as a «progress» one — quiet under a watch, and the words left to the 90-minute backstop).
342
+ progressCountAtTurnStart: options.isContinuation === true || (previous !== undefined && isPersonWordsForward)
343
+ ? request.progressAnswerCount
344
+ : (previous?.progressCountAtTurnStart ?? request.progressAnswerCount),
195
345
  hasSeenBusy: false,
196
346
  hasSeenOutput: false,
197
- isRequestPrompt: options.isRequestPrompt,
347
+ isRequestPrompt: options.isRequestPrompt || previous?.isRequestPrompt === true,
348
+ isScheduledRun,
349
+ isRequestJob,
350
+ isOwnForward,
351
+ ...(ownForwardStartedAt === undefined ? {} : { ownForwardStartedAt }),
352
+ ...(previous?.hasSeenOwnWork === true ? { hasSeenOwnWork: true } : {}),
353
+ ...(writtenToProcess === undefined ? {} : { writtenToProcess }),
198
354
  });
199
- if (request.nextPostRetryAt !== undefined)
200
- await this.deps.ledger.updateOpenRequest(request.id, { nextPostRetryAt: undefined });
201
- await this.recordTurnActivity(request, true);
355
+ // A fire RIDING the request carries none of its prompt; the fire that opened the scheduler's request carries its own.
356
+ const isMoot = request.nextPostRetryAt !== undefined && (!isFireForward || options.isRequestPrompt);
357
+ const isPersonWordsOwed = isPersonWordsForward && request.isPersonInputUnanswered !== true;
358
+ // A person's words start a tracker request's stall count again: the turn they start is a new chance, nudged on its own if it stalls.
359
+ const isStallCountReset = isPersonWordsForward && (request.stalledTurnCount ?? 0) > 0;
360
+ if (isMoot || isPersonWordsOwed || isStallCountReset) {
361
+ await this.deps.ledger.updateOpenRequest(request.id, {
362
+ ...(isMoot ? { nextPostRetryAt: undefined } : {}),
363
+ ...(isPersonWordsOwed ? { isPersonInputUnanswered: true } : {}),
364
+ ...(isStallCountReset ? { stalledTurnCount: undefined } : {}),
365
+ });
366
+ }
367
+ // Keyed on the watch just stored, so a fire of another job AND a «continue» of its turn alike write nothing on the request.
368
+ if (isRequestJob)
369
+ await this.recordTurnActivity(request, true);
370
+ }
371
+ /**
372
+ * @description A person's words for the request were HELD — an armed usage-limit wait keeps them back, and they reach the agent
373
+ * only inside whatever prompt the wait's end forwards first (a «continue», a scheduled run, the operator's next message). No
374
+ * turn starts for them now, so nothing is tracked, but the request owes an answer from this moment: persisted, so the turn
375
+ * that finally carries the words — under any watch, or none after a restart during the wait — is read against it
376
+ * (`checkIsAnswerOwed`). A request that owes it already, and a scheduler fire's own request, are left as they are.
377
+ */
378
+ async notePersonInputHeld(key, requestId) {
379
+ const request = this.getOpenRequestOf(key, requestId);
380
+ if (!request || request.isPersonInputUnanswered === true || request.origin.kind === 'scheduledRun')
381
+ return;
382
+ await this.deps.ledger.updateOpenRequest(request.id, { isPersonInputUnanswered: true });
202
383
  }
203
384
  /**
204
385
  * @description The request's prompt could not be posted to the session (no
@@ -259,38 +440,84 @@ class RequestWakeUpEngine {
259
440
  this.watched.delete(turn.requestId);
260
441
  this.answerTails.delete((0, sessionKey_1.keyToString)(key));
261
442
  }
443
+ /**
444
+ * @description The requests of `key` whose prompt is NOT lost if the conversation ends now, read off its live process at this moment:
445
+ * a prompt the process took in — R21's own test ({@link checkIsPromptTakenInNow}) on a probe taken now, once what the process wrote so
446
+ * far is read (`refreshProcessState`), which the persisted mark lags behind until a settle or the 10-second poll (review 26 #1) — and a
447
+ * prompt still waiting in a start's or a stop's window, whose window's drop tells its person. Synchronous: a command reads it BEFORE it
448
+ * stops or replaces the process (the default of {@link cancelConversation}; the `/resume` pick ahead of its resume).
449
+ */
450
+ readPromptsReachedOrHeld(key) {
451
+ // What the process already wrote counts: a switch moments after a message, before the poll read its echo, told its person the
452
+ // agent never read it while the bridge carried it.
453
+ this.deps.refreshProcessState?.(key);
454
+ const probe = this.deps.probeTurn(key);
455
+ const requestIds = new Set();
456
+ for (const turn of this.getWatchedTurnsOf(key)) {
457
+ if (checkIsPromptTakenInNow(turn, probe) || checkIsPromptWaitingInWindow(turn, probe))
458
+ requestIds.add(turn.requestId);
459
+ }
460
+ return requestIds;
461
+ }
262
462
  /**
263
463
  * @description The person took over (interrupted, quit, restarted, switched or
264
464
  * resumed the session, left the folder): every open request of the
265
- * conversation closes silently and nothing wakes them.
465
+ * conversation closes and nothing wakes them. Resolves the ids of the requests
466
+ * this call closed that carry a person's words the agent never took in (not the
467
+ * scheduler's request, whose prompt is no person's): a command that ends or replaces the
468
+ * conversation tells those people, since nobody reads their words (review 25 #3, review 26 #2);
469
+ * an interrupt closes silently. «Never taken in» reads the persisted mark and `reachedOrHeld`
470
+ * ({@link readPromptsReachedOrHeld}), read by default when this is called — synchronously, before
471
+ * the first await, so off the process the command has not stopped yet.
266
472
  */
267
- async cancelConversation(key) {
473
+ async cancelConversation(key, reachedOrHeld = this.readPromptsReachedOrHeld(key)) {
268
474
  this.unwatchConversation(key);
269
- for (const request of this.deps.ledger.listOpenRequestsOf(key))
270
- await this.deps.ledger.closeRequest(request.id, 'cancelled');
475
+ // The conversation's writes end with it: its next watch is named from a write of the next conversation (review 23 nit 6).
476
+ this.writtenProcesses.delete((0, sessionKey_1.keyToString)(key));
477
+ const unreadRequestIds = [];
478
+ for (const request of this.deps.ledger.listOpenRequestsOf(key)) {
479
+ const isUnreadPersonWords = request.origin.kind !== 'scheduledRun' && (0, requestHeader_1.getPromptNotTakenIn)(request) !== undefined && !reachedOrHeld.has(request.id);
480
+ // Named only when THIS close closed it: one another path closed meanwhile is that path's to tell.
481
+ const closed = await this.deps.ledger.closeRequest(request.id, 'cancelled');
482
+ if (closed !== null && isUnreadPersonWords)
483
+ unreadRequestIds.push(request.id);
484
+ }
485
+ return unreadRequestIds;
271
486
  }
272
487
  /**
273
488
  * @description The bot itself forwarded a "continue" nudge into the session (an
274
- * API-error retry fired, or a usage-limit wait ended): watch the turn it starts
275
- * as a fresh one, so the idle the error left behind is never read as its end.
489
+ * API-error retry fired, or a usage-limit wait ended): watch the turn it starts, so the idle the
490
+ * error left behind is never read as its end. The nudge carries no person's words and is no alarm,
491
+ * so it KEEPS the alarm's kind of the turn it continues but its progress count starts afresh: a progress
492
+ * note sent before the error does not make a silent continuation a «progress» turn. What the turn owes a
493
+ * person is not its kind but the persisted request (`checkIsAnswerOwed`): words answered before the error
494
+ * are owed no more, words still unanswered stay owed.
276
495
  * `isCountersReset` (the end of a limit wait) starts every open request's
277
496
  * wake-up bookkeeping from zero — the wait was not the agent's silence — and
278
497
  * lifts a limit stop: the work continues, so does the waking. A request the
279
498
  * rules already gave up on stays given up. The one session turn the nudge
280
499
  * starts is watched for every open request of the conversation.
500
+ * `carriedRequestIds` — the requests whose prompts the message carries, never taken in (R21: a limit or account resume re-posts
501
+ * them) — is a fact about EACH request, named when the message was BUILT (`getPromptsNotTakenIn`): only such a request has its words
502
+ * in the message (they are owed an answer, as any request prompt's), every other open request gets the plain «continue». It is
503
+ * never read again here: a buffered message is tracked at its replay, and a request opened in between did not ride it (review 21
504
+ * nit 3). A carried request whose prompt the session took in meanwhile is a plain «continue» too.
281
505
  */
282
506
  async trackContinuationTurn(key, options) {
283
507
  for (const request of this.deps.ledger.listOpenRequestsOf(key)) {
508
+ // Read before the counters update below: it never touches `isPromptTakenIn`, but the request's words are what is asked here.
509
+ const isOwnPromptCarried = options.carriedRequestIds?.includes(request.id) === true && (0, requestHeader_1.getPromptNotTakenIn)(request) !== undefined;
284
510
  if (options.isCountersReset) {
285
511
  await this.deps.ledger.updateOpenRequest(request.id, {
286
512
  silentTurnCount: 0,
287
513
  wakeCount: 0,
514
+ stalledTurnCount: undefined,
288
515
  nextWakeAt: undefined,
289
516
  isLimitStopped: undefined,
290
517
  limitWaitAnsweredFor: undefined,
291
518
  });
292
519
  }
293
- await this.trackForwardedTurn(key, request.id, { isRequestPrompt: options.isRequestPrompt === true });
520
+ await this.trackForwardedTurn(key, request.id, { isRequestPrompt: isOwnPromptCarried, isContinuation: true, isConversationForward: true });
294
521
  }
295
522
  }
296
523
  /**
@@ -328,6 +555,174 @@ class RequestWakeUpEngine {
328
555
  this.isPolling = false;
329
556
  }
330
557
  }
558
+ /**
559
+ * @description A new prompt is about to be written into `key`'s conversation: settle every watch of it whose turn has already
560
+ * ENDED, on a probe taken now — before the write — exactly as the poll's next tick would have. A prompt that waited behind a running
561
+ * turn is forwarded within seconds of its end (`postToSession` polls busy every 5 s, this engine every 10 s), usually before the tick
562
+ * saw the idle; the old watch would then read the NEW turn as its own: arm its jobs under the old request, count its busy time as
563
+ * the old request's activity, and decide the old request only at the new turn's end. A watch whose turn still runs is left — the
564
+ * forward joins it (`trackForwardedTurn` merges), its prompt marked taken in if the live process took it (R21, as the poll marks); a
565
+ * session that is gone is left to the poll.
566
+ * Synchronous up to the decisions: the ended watches are dropped and decided against the request as it is NOW, so a forward that
567
+ * does not await (a write must run in its caller's tick) is never read into them. The decisions are persisted after, in order; the
568
+ * returned promise resolves once they are (a post that picks a request awaits it first, so the pick and the header see the result)
569
+ * with the delivery of the wake-ups they decided. The CALLER delivers them — after its own write, so the prompt it writes starts the
570
+ * turn and a reminder joins it, as the tick would have reminded seconds later; a call with no write of its own (the adapter's turn end)
571
+ * hands them to a post on its way to its write, else delivers them at once ({@link deliverOrHandOverWake}). Never rejects, and neither
572
+ * does the delivery.
573
+ */
574
+ settleEndedTurnsOf(key) {
575
+ const probe = this.deps.probeTurn(key);
576
+ const persisting = [];
577
+ for (const turn of this.getWatchedTurnsOf(key)) {
578
+ const request = this.getOpenRequestOf(key, turn.requestId);
579
+ if (!request) {
580
+ this.watched.delete(turn.requestId);
581
+ continue;
582
+ }
583
+ if (probe.isBusy)
584
+ turn.hasSeenBusy = true;
585
+ const rules = this.getRules(key);
586
+ noteOwnWorkSeen(turn, probe, rules);
587
+ const isHeldByOwnWork = (0, wakeUpRules_1.checkIsHeldByOwnWork)(request, probe, rules, this.now());
588
+ if ((0, wakeUpRules_1.getWatchedTurnState)(turn, probe, isHeldByOwnWork) !== 'ended') {
589
+ // A turn still running, or held, may have taken its prompt in already: marked now (R21), as the poll would. The process that took
590
+ // it may be gone before the poll's next tick — a deferred account switch re-spawns it one timer tick after the turn's end, the
591
+ // per-turn stop ends it — and a prompt is read as taken in only off the process it was written to.
592
+ persisting.push(this.markPromptTakenIn(turn, request, probe).then(() => null, (e) => {
593
+ logWakeUpFailure(`marking the prompt of ${turn.requestId} taken in`, e);
594
+ return null;
595
+ }));
596
+ continue;
597
+ }
598
+ this.watched.delete(turn.requestId);
599
+ const decision = this.decideWatchedTurnEnd(turn, request, probe);
600
+ persisting.push(this.persistEndedTurn(turn, request, probe, decision).catch((e) => {
601
+ logWakeUpFailure(`settling the turn of ${turn.requestId}`, e);
602
+ return null;
603
+ }));
604
+ }
605
+ return Promise.all(persisting).then((deliveries) => async () => {
606
+ for (const deliver of deliveries)
607
+ await deliver?.().catch((e) => logWakeUpFailure(`delivering a settled turn's wake-up in ${(0, sessionKey_1.keyToString)(key)}`, e));
608
+ });
609
+ }
610
+ /**
611
+ * @description A post (`postToSession`) is on its way to write a prompt into `key`'s conversation, waiting for the running turn's
612
+ * idle maybe. Until the returned release, a wake-up decided for the conversation — at the adapter's turn end, by the poll, by the sweep
613
+ * ({@link deliverOrHandOverWake}) — is HANDED to the post instead of written at once: the post takes it with its settle
614
+ * ({@link settleEndedTurnsForPost}) and delivers it after its own write, so the prompt that waited for the turn starts the next one and
615
+ * the reminder joins it (written first, the reminder would start that turn and the reminded request would read as its starter). The
616
+ * release delivers what is still handed over once the last post in flight is done: one that never took it (held over a limit wait,
617
+ * an ensure that failed) or a wake decided after its settle. It never rejects, and a second call does nothing.
618
+ */
619
+ notePostInFlight(key) {
620
+ const conversationKey = (0, sessionKey_1.keyToString)(key);
621
+ this.postsInFlight.set(conversationKey, (this.postsInFlight.get(conversationKey) ?? 0) + 1);
622
+ let isReleased = false;
623
+ return async () => {
624
+ if (isReleased)
625
+ return;
626
+ isReleased = true;
627
+ const count = (this.postsInFlight.get(conversationKey) ?? 1) - 1;
628
+ if (count > 0) {
629
+ this.postsInFlight.set(conversationKey, count);
630
+ return;
631
+ }
632
+ this.postsInFlight.delete(conversationKey);
633
+ await this.takeWakesHandedToPost(conversationKey)();
634
+ };
635
+ }
636
+ /** @description Deliver a decided wake-up now, or hand it to a post in flight in `key`'s conversation ({@link notePostInFlight}). Never rejects. */
637
+ async deliverOrHandOverWake(key, deliver) {
638
+ const conversationKey = (0, sessionKey_1.keyToString)(key);
639
+ if (this.postsInFlight.has(conversationKey)) {
640
+ this.wakesHandedToPost.set(conversationKey, [...(this.wakesHandedToPost.get(conversationKey) ?? []), deliver]);
641
+ return;
642
+ }
643
+ await deliver().catch((e) => logWakeUpFailure(`delivering a wake-up in ${conversationKey}`, e));
644
+ }
645
+ /**
646
+ * @description A write into `key`'s live process (the write choke point, synchronously before the adapter write): the process it goes
647
+ * to is stamped, for a watch that is tracked only after that process went down ({@link writtenProcesses}). Synchronous; a probe that
648
+ * names no process (a window holds the prompt) stamps nothing.
649
+ */
650
+ noteWrite(key) {
651
+ const { processGeneration } = this.deps.probeTurn(key);
652
+ if (processGeneration !== undefined)
653
+ this.writtenProcesses.set((0, sessionKey_1.keyToString)(key), processGeneration);
654
+ }
655
+ /**
656
+ * @description A write into `key`'s live process during the replay of a start's buffer (the write choke point, right after its settle;
657
+ * the bot calls it at every write while `StartupPromptBuffer.checkIsReplaying`: a replayed prompt, the held prompts after them, a prompt
658
+ * written at once while the replay runs — all go to the process the replay writes into). A watch tracked while its prompt waited in that
659
+ * buffer names no process yet, and the replay took the whole buffer to write it into this process, so its prompt is in this one. Never
660
+ * called for a write outside a replay: a watch whose buffer was DROPPED stays unnamed — its prompt reached no process
661
+ * (`checkIsPromptNeverWritten`) — and the request it opened is closed with the person told (`bot.ts`, the person's buffered prompt's
662
+ * settle). Only a person's prompt is tracked before its replay: every bot-made caller watches its turn once its prompt reached a session
663
+ * (`src/requests/README.md`, the callers table). Synchronous; a session with no process named does nothing.
664
+ */
665
+ noteReplayedWrite(key) {
666
+ const { processGeneration } = this.deps.probeTurn(key);
667
+ if (processGeneration === undefined)
668
+ return;
669
+ for (const turn of this.getWatchedTurnsOf(key)) {
670
+ if (turn.writtenToProcess === undefined)
671
+ turn.writtenToProcess = processGeneration;
672
+ }
673
+ }
674
+ /**
675
+ * @description The settle of a post about to write ({@link settleEndedTurnsOf}): resolves ONE delivery for the post to run after its
676
+ * write — the wake-ups handed to it so far, in order, then this settle's own. Never rejects, and neither does the delivery.
677
+ */
678
+ settleEndedTurnsForPost(key) {
679
+ const deliverHandedOver = this.takeWakesHandedToPost((0, sessionKey_1.keyToString)(key));
680
+ return this.settleEndedTurnsOf(key).then((deliverSettled) => async () => {
681
+ await deliverHandedOver();
682
+ await deliverSettled();
683
+ });
684
+ }
685
+ /** The delivery of the wake-ups handed to a post in `conversationKey`, taken (a later post or release finds none of them). */
686
+ takeWakesHandedToPost(conversationKey) {
687
+ const handedOver = this.wakesHandedToPost.get(conversationKey) ?? [];
688
+ this.wakesHandedToPost.delete(conversationKey);
689
+ return async () => {
690
+ for (const deliver of handedOver)
691
+ await deliver().catch((e) => logWakeUpFailure(`delivering a wake-up handed to a post in ${conversationKey}`, e));
692
+ };
693
+ }
694
+ /** The decision at the end of `turn`, read against `request` and its jobs as they are now. */
695
+ decideWatchedTurnEnd(turn, request, probe) {
696
+ return (0, wakeUpRules_1.decideTurnEnd)(request, turn.progressCountAtTurnStart, this.now(), {
697
+ isScheduledRun: turn.isScheduledRun === true,
698
+ isRequestJob: turn.isRequestJob !== false,
699
+ scheduleWait: this.getScheduleWait(turn.key, request),
700
+ progressFollowUpMs: this.deps.progressFollowUpMs,
701
+ rules: this.getRules(turn.key),
702
+ // Still running: the hold no longer applies (an owed answer, or it lapsed). Gone after a hold: it ended by itself.
703
+ ...(probe.hasOwnLastingWork === true ? { ownWork: 'pending' } : turn.hasSeenOwnWork === true ? { ownWork: 'ended' } : {}),
704
+ });
705
+ }
706
+ /** R21 for a request prompt the ended turn took in (a later wake-up is a reminder), then `decision` persisted; resolves its wake's delivery. */
707
+ async persistEndedTurn(turn, request, probe, decision) {
708
+ await this.markPromptTakenIn(turn, request, probe);
709
+ return this.persistDecision(turn.key, request, decision);
710
+ }
711
+ /**
712
+ * R21: once the backend took a request prompt in, a wake-up is a reminder — the agent has read the request. A held turn end is read like
713
+ * any other: what the backend still lists as unread is unread. A prompt queued behind a turn that ended in an error result stays listed
714
+ * until its own echo (the json-stream adapter keeps it; the CLI runs it as its next turn, measured), and the prompt of the turn that
715
+ * failed was read by it — a resume that posted it again would repeat words the agent already has.
716
+ * Read only off the process the prompt was written to (`writtenToProcess`): a re-spawn that replaced it — an account move after a limit,
717
+ * a model change — kills a message still queued there, and the new process lists nothing unread. Left unmarked, the prompt is posted
718
+ * again: by the resume's «continue» (`getPromptNotTakenIn`), or as the wake-up of the turn's end. A prompt that names no process while
719
+ * one is live never reached any (`checkIsTurnInputConsumed`): nothing is marked.
720
+ */
721
+ async markPromptTakenIn(turn, request, probe) {
722
+ if (request.isPromptTakenIn !== true && checkIsPromptConsumedByLiveProcess(turn, probe)) {
723
+ await this.deps.ledger.updateOpenRequest(request.id, { isPromptTakenIn: true });
724
+ }
725
+ }
331
726
  async pollWatchedTurn(turn) {
332
727
  // Replaced or dropped since this poll took its snapshot: the newer watch (if any) decides.
333
728
  if (this.watched.get(turn.requestId) !== turn)
@@ -341,24 +736,35 @@ class RequestWakeUpEngine {
341
736
  const probe = this.deps.probeTurn(turn.key);
342
737
  if (probe.isBusy)
343
738
  turn.hasSeenBusy = true;
344
- if (turn.isRequestPrompt && request.isPromptTakenIn !== true && probe.isActive && (0, wakeUpRules_1.checkIsTurnInputConsumed)(turn, probe)) {
345
- // R21: from now on a wake-up is a reminder — the agent has read the request.
346
- await this.deps.ledger.updateOpenRequest(request.id, { isPromptTakenIn: true });
347
- }
348
- const turnState = (0, wakeUpRules_1.getWatchedTurnState)(turn, probe);
739
+ await this.markPromptTakenIn(turn, request, probe);
740
+ // Settled by a forward, or replaced by a new watch, during that write: the watch present now decides, not this one.
741
+ if (this.watched.get(turn.requestId) !== turn)
742
+ return;
743
+ const rules = this.getRules(turn.key);
744
+ noteOwnWorkSeen(turn, probe, rules);
745
+ const isHeldByOwnWork = (0, wakeUpRules_1.checkIsHeldByOwnWork)(request, probe, rules, this.now());
746
+ const turnState = (0, wakeUpRules_1.getWatchedTurnState)(turn, probe, isHeldByOwnWork);
349
747
  if (turnState === 'running') {
350
- if (probe.isBusy)
351
- await this.recordTurnActivity(request, false);
352
- // Its end can no longer be seen: the sweep's backstop takes the request over.
353
- else if ((0, wakeUpRules_1.checkIsWatchedTurnStale)(request, probe, this.now(), this.deps.backstopMs))
748
+ if (probe.isBusy) {
749
+ // Another job's fire that only rides the request keeps the session busy for its own work, not for this request's — and so does
750
+ // any turn while this request's prompt has reached no process (`checkIsPromptNeverWritten`): that busy time is another turn's.
751
+ // Once a tracker's watch saw the agent's own work outlive its turn, a turn the CLI starts by itself (that work's, a loop's fire)
752
+ // is no activity either: counted, a self-renewing job would renew the hold it bounds (`ownWorkHoldMaxMs`).
753
+ const isOwnWorkTurn = turn.hasSeenOwnWork === true && probe.isCliOwnTurn === true;
754
+ if (turn.isRequestJob !== false && !(0, wakeUpRules_1.checkIsPromptNeverWritten)(turn, probe) && !isOwnWorkTurn)
755
+ await this.recordTurnActivity(request, false);
756
+ }
757
+ else if ((0, wakeUpRules_1.checkIsWatchedTurnStale)(request, probe, this.now(), this.deps.backstopMs, rules)) {
758
+ // Its end can no longer be seen: the sweep's backstop takes the request over.
354
759
  this.watched.delete(turn.requestId);
760
+ }
355
761
  return;
356
762
  }
357
763
  this.watched.delete(turn.requestId);
358
764
  // A dead session is not a turn end: the backstop resumes it later.
359
765
  if (turnState === 'sessionGone')
360
766
  return;
361
- await this.applyDecision(turn.key, request, (0, wakeUpRules_1.decideTurnEnd)(request, turn.progressCountAtTurnStart, this.now()));
767
+ await this.applyDecision(turn.key, request, this.decideWatchedTurnEnd(turn, request, probe));
362
768
  }
363
769
  /** @description One sweep over the open requests nobody watches; exported for tests. */
364
770
  async sweepUnwatchedRequests() {
@@ -389,10 +795,50 @@ class RequestWakeUpEngine {
389
795
  async sweepOpenRequest(key, request) {
390
796
  const probe = this.deps.probeTurn(key);
391
797
  if (probe.isBusy) {
392
- await this.recordTurnActivity(request, false);
798
+ // A busy session is activity of THIS request's own lost turn — so a long-running one is not prodded mid-work — but only while no
799
+ // turn is watched in the conversation: then the busy time is that turn's, never this request's, whatever it owes. A recurring
800
+ // job's fires keep the session busy every few minutes, so recorded they would push this request's backstop ahead for good — a
801
+ // requester's lost message, or a watch that fired and nobody handled (`armed`), would never be taken back. A request a watch
802
+ // holds ignores the backstop anyway, and a due follow-up is woken by `nextWakeAt`, which activity does not move. The same for a
803
+ // turn the CLI started by itself (`isCliOwnTurn`: a finished task's, a session `CronCreate` job's): only a turn the bot wrote can
804
+ // be the request's lost one, and a looping job would otherwise push an owed request's backstop ahead for as long as it loops.
805
+ if (this.getWatchedTurnsOf(key).length === 0 && probe.isCliOwnTurn !== true)
806
+ await this.recordTurnActivity(request, false);
393
807
  return;
394
808
  }
395
- await this.applyDecision(key, request, (0, wakeUpRules_1.decideUnwatchedRequest)(request, probe, this.now(), this.deps.backstopMs));
809
+ if ((0, wakeUpRules_1.checkIsHeldByOwnWork)(request, probe, this.getRules(key), this.now()) && this.watchTurnOfOwnWork(key, request, probe))
810
+ return;
811
+ await this.applyDecision(key, request, (0, wakeUpRules_1.decideUnwatchedRequest)(request, probe, this.now(), this.deps.backstopMs, this.getScheduleWait(key, request)));
812
+ }
813
+ /**
814
+ * ANY tracker request of the conversation nobody watches while the agent's own pending work holds it (`checkIsHeldByOwnWork`) — a
815
+ * restart dropped the watch that held it, or the work is another request's (one request's work holds every open request of the
816
+ * conversation that owes nobody an answer; the work's end nudges each one left open with nothing armed): watch it, so the turn that
817
+ * work starts by itself is decided when it ends, not left to the backstop. Not while its prompt waits for a post retry (that forward
818
+ * is watched: the sweep's decision runs it), nor once nothing may wake it. `true` — it is watched now.
819
+ */
820
+ watchTurnOfOwnWork(key, request, probe) {
821
+ if (!probe.isActive || request.nextPostRetryAt !== undefined || (0, wakeUpRules_1.checkIsWakingStopped)(request))
822
+ return false;
823
+ this.watched.set(request.id, {
824
+ key,
825
+ requestId: request.id,
826
+ progressCountAtTurnStart: request.progressAnswerCount,
827
+ hasSeenBusy: false,
828
+ hasSeenOutput: false,
829
+ isRequestPrompt: false,
830
+ isOwnForward: false,
831
+ ...(probe.hasOwnLastingWork === true ? { hasSeenOwnWork: true } : {}),
832
+ });
833
+ return true;
834
+ }
835
+ /** The rule set `key`'s conversation is woken under; a topic's when the port is not wired. */
836
+ getRules(key) {
837
+ return this.deps.getWakeUpRules?.(key) ?? 'topic';
838
+ }
839
+ /** The request's reading of its armed jobs now; `none` when the port is not wired. */
840
+ getScheduleWait(key, request) {
841
+ return this.deps.getScheduleWait?.(key, request) ?? 'none';
396
842
  }
397
843
  async sweepAnswerTail(conversationKey, entry) {
398
844
  if (this.answerTails.get(conversationKey) !== entry)
@@ -424,8 +870,23 @@ class RequestWakeUpEngine {
424
870
  await this.deps.ledger.updateOpenRequest(request.id, { lastTurnActivityAt: nowMs });
425
871
  }
426
872
  async applyDecision(key, request, decision) {
873
+ const deliverWake = await this.persistDecision(key, request, decision);
874
+ // A post on its way to its write takes it and writes it after its own prompt (`notePostInFlight`).
875
+ if (deliverWake)
876
+ await this.deliverOrHandOverWake(key, deliverWake);
877
+ }
878
+ /**
879
+ * Persist `decision` (an alert is raised here too) and resolve the delivery of its wake-up, or `null` when it decided none or the
880
+ * request changed meanwhile. Split from the delivery so a settle before a write can persist at once and deliver after the write.
881
+ */
882
+ async persistDecision(key, request, decision) {
427
883
  if (decision.kind === 'none')
428
- return;
884
+ return null;
885
+ if (decision.kind === 'quiet' && decision.isRequestSettled === true) {
886
+ // The alarm's own request, left unanswered by an agent with nothing to report: closed without a word, never woken at the backstop.
887
+ await this.deps.ledger.closeRequest(request.id, 'cancelled');
888
+ return null;
889
+ }
429
890
  let isStoppedMeanwhile = false;
430
891
  const updated = await this.deps.ledger.updateOpenRequest(request.id, (current) => {
431
892
  // `request` is a snapshot: a limit wait may have stopped the wake-ups since (no alert either).
@@ -434,14 +895,19 @@ class RequestWakeUpEngine {
434
895
  });
435
896
  // Closed or superseded while we decided: the decision belonged to the old one.
436
897
  if (!updated || isStoppedMeanwhile)
437
- return;
438
- if (decision.kind === 'followUpLater')
439
- return;
898
+ return null;
899
+ if (decision.kind === 'followUpLater' || decision.kind === 'quiet')
900
+ return null;
440
901
  if (decision.kind === 'alert') {
441
902
  await this.raiseAlert(key, updated, decision.reason);
442
- return;
903
+ return null;
443
904
  }
444
- const message = (0, requestHeader_1.getWakeUpMessage)(updated, decision.reason);
905
+ const { reason } = decision;
906
+ return () => this.deliverWake(key, updated, reason);
907
+ }
908
+ /** Deliver a persisted wake-up: the reminder (or the request's prompt again, R21), then its turn watched, or the failure handled. */
909
+ async deliverWake(key, updated, reason) {
910
+ const message = (0, requestHeader_1.getWakeUpMessage)(updated, reason);
445
911
  const outcome = await this.deliverWakeUpSafely(key, updated, message);
446
912
  if (outcome === 'delivered') {
447
913
  await this.trackForwardedTurn(key, updated.id, { isRequestPrompt: message.isRequestPrompt });
@@ -449,7 +915,7 @@ class RequestWakeUpEngine {
449
915
  }
450
916
  if (outcome === 'requestGone')
451
917
  return;
452
- if (decision.reason === 'postRetry') {
918
+ if (reason === 'postRetry') {
453
919
  // R28: a retry that failed again tries later; once spent, the backstop decides — no alert yet.
454
920
  const retry = (0, wakeUpRules_1.getPostRetryUpdate)(updated, this.now(), this.deps.firstPostRetryDelayMs);
455
921
  if (retry)
@@ -473,6 +939,10 @@ class RequestWakeUpEngine {
473
939
  const current = this.getOpenRequestOf(key, request.id);
474
940
  if (!current || (0, wakeUpRules_1.checkIsWakingStopped)(current))
475
941
  return 'requestGone';
942
+ // A tracker's nudge is moot once a person's words for the request reached the agent after it was decided (a comment that waited
943
+ // for the stalled turn and was written right before the nudge's delivery): their turn is the request's next, decided on its own.
944
+ if (message.reason === 'nothingArmed' && current.isPersonInputUnanswered === true)
945
+ return 'requestGone';
476
946
  await this.deps.forwardWakeUp(key, request, message);
477
947
  return 'delivered';
478
948
  }