charness 0.0.0-stage → 3.0.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 (988) hide show
  1. package/.env.example +88 -0
  2. package/DEVELOPMENT.md +110 -0
  3. package/LICENSE +21 -0
  4. package/MIGRATION_1_TO_2.md +24 -0
  5. package/README.md +1024 -2
  6. package/dist/accessControl.d.ts +71 -0
  7. package/dist/accessControl.d.ts.map +1 -0
  8. package/dist/accessControl.js +108 -0
  9. package/dist/accessControl.js.map +1 -0
  10. package/dist/adapters/adapterEventRouting.d.ts +51 -0
  11. package/dist/adapters/adapterEventRouting.d.ts.map +1 -0
  12. package/dist/adapters/adapterEventRouting.js +74 -0
  13. package/dist/adapters/adapterEventRouting.js.map +1 -0
  14. package/dist/adapters/adapterNames.d.ts +19 -0
  15. package/dist/adapters/adapterNames.d.ts.map +1 -0
  16. package/dist/adapters/adapterNames.js +25 -0
  17. package/dist/adapters/adapterNames.js.map +1 -0
  18. package/dist/adapters/claudeCliAdapter.d.ts +1336 -0
  19. package/dist/adapters/claudeCliAdapter.d.ts.map +1 -0
  20. package/dist/adapters/claudeCliAdapter.js +4204 -0
  21. package/dist/adapters/claudeCliAdapter.js.map +1 -0
  22. package/dist/adapters/claudeJsonStreamAdapter.d.ts +548 -0
  23. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -0
  24. package/dist/adapters/claudeJsonStreamAdapter.js +1810 -0
  25. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -0
  26. package/dist/adapters/claudePlatformFlags.d.ts +35 -0
  27. package/dist/adapters/claudePlatformFlags.d.ts.map +1 -0
  28. package/dist/adapters/claudePlatformFlags.js +46 -0
  29. package/dist/adapters/claudePlatformFlags.js.map +1 -0
  30. package/dist/adapters/createAdapter.d.ts +252 -0
  31. package/dist/adapters/createAdapter.d.ts.map +1 -0
  32. package/dist/adapters/createAdapter.js +475 -0
  33. package/dist/adapters/createAdapter.js.map +1 -0
  34. package/dist/adapters/openCodeAdapter.d.ts +1446 -0
  35. package/dist/adapters/openCodeAdapter.d.ts.map +1 -0
  36. package/dist/adapters/openCodeAdapter.js +4540 -0
  37. package/dist/adapters/openCodeAdapter.js.map +1 -0
  38. package/dist/adapters/sessionLaunchDefaults.d.ts +28 -0
  39. package/dist/adapters/sessionLaunchDefaults.d.ts.map +1 -0
  40. package/dist/adapters/sessionLaunchDefaults.js +15 -0
  41. package/dist/adapters/sessionLaunchDefaults.js.map +1 -0
  42. package/dist/adapters/terminalAdapter.d.ts +68 -0
  43. package/dist/adapters/terminalAdapter.d.ts.map +1 -0
  44. package/dist/adapters/terminalAdapter.js +371 -0
  45. package/dist/adapters/terminalAdapter.js.map +1 -0
  46. package/dist/agentLogin/agentLogin.d.ts +31 -0
  47. package/dist/agentLogin/agentLogin.d.ts.map +1 -0
  48. package/dist/agentLogin/agentLogin.js +493 -0
  49. package/dist/agentLogin/agentLogin.js.map +1 -0
  50. package/dist/agentTrigger.d.ts +28 -0
  51. package/dist/agentTrigger.d.ts.map +1 -0
  52. package/dist/agentTrigger.js +53 -0
  53. package/dist/agentTrigger.js.map +1 -0
  54. package/dist/apiErrorRetry.d.ts +209 -0
  55. package/dist/apiErrorRetry.d.ts.map +1 -0
  56. package/dist/apiErrorRetry.js +351 -0
  57. package/dist/apiErrorRetry.js.map +1 -0
  58. package/dist/apiRetryKick.d.ts +148 -0
  59. package/dist/apiRetryKick.d.ts.map +1 -0
  60. package/dist/apiRetryKick.js +158 -0
  61. package/dist/apiRetryKick.js.map +1 -0
  62. package/dist/bootClassifier.d.ts +46 -0
  63. package/dist/bootClassifier.d.ts.map +1 -0
  64. package/dist/bootClassifier.js +43 -0
  65. package/dist/bootClassifier.js.map +1 -0
  66. package/dist/bot.d.ts +207 -0
  67. package/dist/bot.d.ts.map +1 -0
  68. package/dist/bot.js +10611 -0
  69. package/dist/bot.js.map +1 -0
  70. package/dist/botFileStorage.d.ts +60 -0
  71. package/dist/botFileStorage.d.ts.map +1 -0
  72. package/dist/botFileStorage.js +205 -0
  73. package/dist/botFileStorage.js.map +1 -0
  74. package/dist/cli/applyDnsFix.d.ts +7 -0
  75. package/dist/cli/applyDnsFix.d.ts.map +1 -0
  76. package/dist/cli/applyDnsFix.js +46 -0
  77. package/dist/cli/applyDnsFix.js.map +1 -0
  78. package/dist/cli/bot.d.ts +27 -0
  79. package/dist/cli/bot.d.ts.map +1 -0
  80. package/dist/cli/bot.js +98 -0
  81. package/dist/cli/bot.js.map +1 -0
  82. package/dist/cli/botEntry.d.ts +3 -0
  83. package/dist/cli/botEntry.d.ts.map +1 -0
  84. package/dist/cli/botEntry.js +11 -0
  85. package/dist/cli/botEntry.js.map +1 -0
  86. package/dist/cli/connectorGuards.d.ts +31 -0
  87. package/dist/cli/connectorGuards.d.ts.map +1 -0
  88. package/dist/cli/connectorGuards.js +159 -0
  89. package/dist/cli/connectorGuards.js.map +1 -0
  90. package/dist/cli/envLoader.d.ts +34 -0
  91. package/dist/cli/envLoader.d.ts.map +1 -0
  92. package/dist/cli/envLoader.js +132 -0
  93. package/dist/cli/envLoader.js.map +1 -0
  94. package/dist/cli/hot.d.ts +82 -0
  95. package/dist/cli/hot.d.ts.map +1 -0
  96. package/dist/cli/hot.js +323 -0
  97. package/dist/cli/hot.js.map +1 -0
  98. package/dist/cli.d.ts +3 -0
  99. package/dist/cli.d.ts.map +1 -0
  100. package/dist/cli.js +130 -0
  101. package/dist/cli.js.map +1 -0
  102. package/dist/connectors/jira/adf.d.ts +72 -0
  103. package/dist/connectors/jira/adf.d.ts.map +1 -0
  104. package/dist/connectors/jira/adf.js +407 -0
  105. package/dist/connectors/jira/adf.js.map +1 -0
  106. package/dist/connectors/jira/agentBinaries.d.ts +14 -0
  107. package/dist/connectors/jira/agentBinaries.d.ts.map +1 -0
  108. package/dist/connectors/jira/agentBinaries.js +75 -0
  109. package/dist/connectors/jira/agentBinaries.js.map +1 -0
  110. package/dist/connectors/jira/answerSink.d.ts +52 -0
  111. package/dist/connectors/jira/answerSink.d.ts.map +1 -0
  112. package/dist/connectors/jira/answerSink.js +220 -0
  113. package/dist/connectors/jira/answerSink.js.map +1 -0
  114. package/dist/connectors/jira/attachmentDownload.d.ts +41 -0
  115. package/dist/connectors/jira/attachmentDownload.d.ts.map +1 -0
  116. package/dist/connectors/jira/attachmentDownload.js +92 -0
  117. package/dist/connectors/jira/attachmentDownload.js.map +1 -0
  118. package/dist/connectors/jira/attachmentTool.d.ts +43 -0
  119. package/dist/connectors/jira/attachmentTool.d.ts.map +1 -0
  120. package/dist/connectors/jira/attachmentTool.js +150 -0
  121. package/dist/connectors/jira/attachmentTool.js.map +1 -0
  122. package/dist/connectors/jira/client.d.ts +490 -0
  123. package/dist/connectors/jira/client.d.ts.map +1 -0
  124. package/dist/connectors/jira/client.js +453 -0
  125. package/dist/connectors/jira/client.js.map +1 -0
  126. package/dist/connectors/jira/config.d.ts +117 -0
  127. package/dist/connectors/jira/config.d.ts.map +1 -0
  128. package/dist/connectors/jira/config.js +350 -0
  129. package/dist/connectors/jira/config.js.map +1 -0
  130. package/dist/connectors/jira/configFile.d.ts +10 -0
  131. package/dist/connectors/jira/configFile.d.ts.map +1 -0
  132. package/dist/connectors/jira/configFile.js +50 -0
  133. package/dist/connectors/jira/configFile.js.map +1 -0
  134. package/dist/connectors/jira/connector.d.ts +68 -0
  135. package/dist/connectors/jira/connector.d.ts.map +1 -0
  136. package/dist/connectors/jira/connector.js +257 -0
  137. package/dist/connectors/jira/connector.js.map +1 -0
  138. package/dist/connectors/jira/contextLedger.d.ts +59 -0
  139. package/dist/connectors/jira/contextLedger.d.ts.map +1 -0
  140. package/dist/connectors/jira/contextLedger.js +194 -0
  141. package/dist/connectors/jira/contextLedger.js.map +1 -0
  142. package/dist/connectors/jira/contextPreamble.d.ts +18 -0
  143. package/dist/connectors/jira/contextPreamble.d.ts.map +1 -0
  144. package/dist/connectors/jira/contextPreamble.js +31 -0
  145. package/dist/connectors/jira/contextPreamble.js.map +1 -0
  146. package/dist/connectors/jira/inbound.d.ts +132 -0
  147. package/dist/connectors/jira/inbound.d.ts.map +1 -0
  148. package/dist/connectors/jira/inbound.js +316 -0
  149. package/dist/connectors/jira/inbound.js.map +1 -0
  150. package/dist/connectors/jira/issueBlocks.d.ts +51 -0
  151. package/dist/connectors/jira/issueBlocks.d.ts.map +1 -0
  152. package/dist/connectors/jira/issueBlocks.js +182 -0
  153. package/dist/connectors/jira/issueBlocks.js.map +1 -0
  154. package/dist/connectors/jira/issueContext.d.ts +25 -0
  155. package/dist/connectors/jira/issueContext.d.ts.map +1 -0
  156. package/dist/connectors/jira/issueContext.js +53 -0
  157. package/dist/connectors/jira/issueContext.js.map +1 -0
  158. package/dist/connectors/jira/issueDelta.d.ts +35 -0
  159. package/dist/connectors/jira/issueDelta.d.ts.map +1 -0
  160. package/dist/connectors/jira/issueDelta.js +50 -0
  161. package/dist/connectors/jira/issueDelta.js.map +1 -0
  162. package/dist/connectors/jira/mediaPlaceholders.d.ts +20 -0
  163. package/dist/connectors/jira/mediaPlaceholders.d.ts.map +1 -0
  164. package/dist/connectors/jira/mediaPlaceholders.js +92 -0
  165. package/dist/connectors/jira/mediaPlaceholders.js.map +1 -0
  166. package/dist/connectors/jira/outbound.d.ts +6 -0
  167. package/dist/connectors/jira/outbound.d.ts.map +1 -0
  168. package/dist/connectors/jira/outbound.js +38 -0
  169. package/dist/connectors/jira/outbound.js.map +1 -0
  170. package/dist/connectors/jira/prompt.d.ts +37 -0
  171. package/dist/connectors/jira/prompt.d.ts.map +1 -0
  172. package/dist/connectors/jira/prompt.js +99 -0
  173. package/dist/connectors/jira/prompt.js.map +1 -0
  174. package/dist/connectors/jira/promptSpill.d.ts +50 -0
  175. package/dist/connectors/jira/promptSpill.d.ts.map +1 -0
  176. package/dist/connectors/jira/promptSpill.js +157 -0
  177. package/dist/connectors/jira/promptSpill.js.map +1 -0
  178. package/dist/connectors/jira/promptText.d.ts +7 -0
  179. package/dist/connectors/jira/promptText.d.ts.map +1 -0
  180. package/dist/connectors/jira/promptText.js +26 -0
  181. package/dist/connectors/jira/promptText.js.map +1 -0
  182. package/dist/connectors/jira/sessionKeyCodec.d.ts +16 -0
  183. package/dist/connectors/jira/sessionKeyCodec.d.ts.map +1 -0
  184. package/dist/connectors/jira/sessionKeyCodec.js +101 -0
  185. package/dist/connectors/jira/sessionKeyCodec.js.map +1 -0
  186. package/dist/connectors/jira/trigger.d.ts +50 -0
  187. package/dist/connectors/jira/trigger.d.ts.map +1 -0
  188. package/dist/connectors/jira/trigger.js +93 -0
  189. package/dist/connectors/jira/trigger.js.map +1 -0
  190. package/dist/connectors/jira/triggerLog.d.ts +51 -0
  191. package/dist/connectors/jira/triggerLog.d.ts.map +1 -0
  192. package/dist/connectors/jira/triggerLog.js +78 -0
  193. package/dist/connectors/jira/triggerLog.js.map +1 -0
  194. package/dist/connectors/jira/unconfirmedPosts.d.ts +58 -0
  195. package/dist/connectors/jira/unconfirmedPosts.d.ts.map +1 -0
  196. package/dist/connectors/jira/unconfirmedPosts.js +105 -0
  197. package/dist/connectors/jira/unconfirmedPosts.js.map +1 -0
  198. package/dist/connectors/telegram/answerSink.d.ts +46 -0
  199. package/dist/connectors/telegram/answerSink.d.ts.map +1 -0
  200. package/dist/connectors/telegram/answerSink.js +71 -0
  201. package/dist/connectors/telegram/answerSink.js.map +1 -0
  202. package/dist/connectors/telegram/commands/autoContinueLimits.d.ts +31 -0
  203. package/dist/connectors/telegram/commands/autoContinueLimits.d.ts.map +1 -0
  204. package/dist/connectors/telegram/commands/autoContinueLimits.js +142 -0
  205. package/dist/connectors/telegram/commands/autoContinueLimits.js.map +1 -0
  206. package/dist/connectors/telegram/commands/botCore.d.ts +46 -0
  207. package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -0
  208. package/dist/connectors/telegram/commands/botCore.js +3 -0
  209. package/dist/connectors/telegram/commands/botCore.js.map +1 -0
  210. package/dist/connectors/telegram/commands/callbackMessage.d.ts +12 -0
  211. package/dist/connectors/telegram/commands/callbackMessage.d.ts.map +1 -0
  212. package/dist/connectors/telegram/commands/callbackMessage.js +13 -0
  213. package/dist/connectors/telegram/commands/callbackMessage.js.map +1 -0
  214. package/dist/connectors/telegram/commands/compaction.d.ts +47 -0
  215. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -0
  216. package/dist/connectors/telegram/commands/compaction.js +868 -0
  217. package/dist/connectors/telegram/commands/compaction.js.map +1 -0
  218. package/dist/connectors/telegram/commands/displayModes.d.ts +13 -0
  219. package/dist/connectors/telegram/commands/displayModes.d.ts.map +1 -0
  220. package/dist/connectors/telegram/commands/displayModes.js +335 -0
  221. package/dist/connectors/telegram/commands/displayModes.js.map +1 -0
  222. package/dist/connectors/telegram/commands/modelProviders.d.ts +95 -0
  223. package/dist/connectors/telegram/commands/modelProviders.d.ts.map +1 -0
  224. package/dist/connectors/telegram/commands/modelProviders.js +841 -0
  225. package/dist/connectors/telegram/commands/modelProviders.js.map +1 -0
  226. package/dist/connectors/telegram/commands/reminders.d.ts +54 -0
  227. package/dist/connectors/telegram/commands/reminders.d.ts.map +1 -0
  228. package/dist/connectors/telegram/commands/reminders.js +624 -0
  229. package/dist/connectors/telegram/commands/reminders.js.map +1 -0
  230. package/dist/connectors/telegram/fileIntake.d.ts +166 -0
  231. package/dist/connectors/telegram/fileIntake.d.ts.map +1 -0
  232. package/dist/connectors/telegram/fileIntake.js +304 -0
  233. package/dist/connectors/telegram/fileIntake.js.map +1 -0
  234. package/dist/connectors/telegram/fileSendGateway.d.ts +57 -0
  235. package/dist/connectors/telegram/fileSendGateway.d.ts.map +1 -0
  236. package/dist/connectors/telegram/fileSendGateway.js +221 -0
  237. package/dist/connectors/telegram/fileSendGateway.js.map +1 -0
  238. package/dist/connectors/telegram/foreignKeyFallbacks.d.ts +52 -0
  239. package/dist/connectors/telegram/foreignKeyFallbacks.d.ts.map +1 -0
  240. package/dist/connectors/telegram/foreignKeyFallbacks.js +71 -0
  241. package/dist/connectors/telegram/foreignKeyFallbacks.js.map +1 -0
  242. package/dist/connectors/telegram/inbound.d.ts +131 -0
  243. package/dist/connectors/telegram/inbound.d.ts.map +1 -0
  244. package/dist/connectors/telegram/inbound.js +278 -0
  245. package/dist/connectors/telegram/inbound.js.map +1 -0
  246. package/dist/connectors/telegram/languagePicker.d.ts +32 -0
  247. package/dist/connectors/telegram/languagePicker.d.ts.map +1 -0
  248. package/dist/connectors/telegram/languagePicker.js +55 -0
  249. package/dist/connectors/telegram/languagePicker.js.map +1 -0
  250. package/dist/connectors/telegram/messageSplit.d.ts +62 -0
  251. package/dist/connectors/telegram/messageSplit.d.ts.map +1 -0
  252. package/dist/connectors/telegram/messageSplit.js +119 -0
  253. package/dist/connectors/telegram/messageSplit.js.map +1 -0
  254. package/dist/connectors/telegram/outbound.d.ts +62 -0
  255. package/dist/connectors/telegram/outbound.d.ts.map +1 -0
  256. package/dist/connectors/telegram/outbound.js +116 -0
  257. package/dist/connectors/telegram/outbound.js.map +1 -0
  258. package/dist/connectors/telegram/output/createOutputTransport.d.ts +34 -0
  259. package/dist/connectors/telegram/output/createOutputTransport.d.ts.map +1 -0
  260. package/dist/connectors/telegram/output/createOutputTransport.js +77 -0
  261. package/dist/connectors/telegram/output/createOutputTransport.js.map +1 -0
  262. package/dist/connectors/telegram/output/dmOutputTransport.d.ts +47 -0
  263. package/dist/connectors/telegram/output/dmOutputTransport.d.ts.map +1 -0
  264. package/dist/connectors/telegram/output/dmOutputTransport.js +412 -0
  265. package/dist/connectors/telegram/output/dmOutputTransport.js.map +1 -0
  266. package/dist/connectors/telegram/outputBacklogGlue.d.ts +38 -0
  267. package/dist/connectors/telegram/outputBacklogGlue.d.ts.map +1 -0
  268. package/dist/connectors/telegram/outputBacklogGlue.js +49 -0
  269. package/dist/connectors/telegram/outputBacklogGlue.js.map +1 -0
  270. package/dist/connectors/telegram/outputFlushPlan.d.ts +93 -0
  271. package/dist/connectors/telegram/outputFlushPlan.d.ts.map +1 -0
  272. package/dist/connectors/telegram/outputFlushPlan.js +120 -0
  273. package/dist/connectors/telegram/outputFlushPlan.js.map +1 -0
  274. package/dist/connectors/telegram/questionKeyboards.d.ts +30 -0
  275. package/dist/connectors/telegram/questionKeyboards.d.ts.map +1 -0
  276. package/dist/connectors/telegram/questionKeyboards.js +37 -0
  277. package/dist/connectors/telegram/questionKeyboards.js.map +1 -0
  278. package/dist/connectors/telegram/renderAgentHtml.d.ts +27 -0
  279. package/dist/connectors/telegram/renderAgentHtml.d.ts.map +1 -0
  280. package/dist/connectors/telegram/renderAgentHtml.js +97 -0
  281. package/dist/connectors/telegram/renderAgentHtml.js.map +1 -0
  282. package/dist/connectors/telegram/sessionKeyCodec.d.ts +28 -0
  283. package/dist/connectors/telegram/sessionKeyCodec.d.ts.map +1 -0
  284. package/dist/connectors/telegram/sessionKeyCodec.js +107 -0
  285. package/dist/connectors/telegram/sessionKeyCodec.js.map +1 -0
  286. package/dist/connectors/telegram/telegramCallGuard.d.ts +19 -0
  287. package/dist/connectors/telegram/telegramCallGuard.d.ts.map +1 -0
  288. package/dist/connectors/telegram/telegramCallGuard.js +35 -0
  289. package/dist/connectors/telegram/telegramCallGuard.js.map +1 -0
  290. package/dist/connectors/telegram/timezonePicker.d.ts +85 -0
  291. package/dist/connectors/telegram/timezonePicker.d.ts.map +1 -0
  292. package/dist/connectors/telegram/timezonePicker.js +142 -0
  293. package/dist/connectors/telegram/timezonePicker.js.map +1 -0
  294. package/dist/connectors/telegram/updateDispatcher.d.ts +85 -0
  295. package/dist/connectors/telegram/updateDispatcher.d.ts.map +1 -0
  296. package/dist/connectors/telegram/updateDispatcher.js +159 -0
  297. package/dist/connectors/telegram/updateDispatcher.js.map +1 -0
  298. package/dist/connectors/test/connector.d.ts +52 -0
  299. package/dist/connectors/test/connector.d.ts.map +1 -0
  300. package/dist/connectors/test/connector.js +143 -0
  301. package/dist/connectors/test/connector.js.map +1 -0
  302. package/dist/connectors/test/sessionKeyCodec.d.ts +25 -0
  303. package/dist/connectors/test/sessionKeyCodec.d.ts.map +1 -0
  304. package/dist/connectors/test/sessionKeyCodec.js +50 -0
  305. package/dist/connectors/test/sessionKeyCodec.js.map +1 -0
  306. package/dist/diagLog.d.ts +6 -0
  307. package/dist/diagLog.d.ts.map +1 -0
  308. package/dist/diagLog.js +58 -0
  309. package/dist/diagLog.js.map +1 -0
  310. package/dist/effortLevels.d.ts +68 -0
  311. package/dist/effortLevels.d.ts.map +1 -0
  312. package/dist/effortLevels.js +114 -0
  313. package/dist/effortLevels.js.map +1 -0
  314. package/dist/folderName.d.ts +42 -0
  315. package/dist/folderName.d.ts.map +1 -0
  316. package/dist/folderName.js +51 -0
  317. package/dist/folderName.js.map +1 -0
  318. package/dist/i18n/de.d.ts +2 -0
  319. package/dist/i18n/de.d.ts.map +1 -0
  320. package/dist/i18n/de.js +537 -0
  321. package/dist/i18n/de.js.map +1 -0
  322. package/dist/i18n/en.d.ts +7 -0
  323. package/dist/i18n/en.d.ts.map +1 -0
  324. package/dist/i18n/en.js +566 -0
  325. package/dist/i18n/en.js.map +1 -0
  326. package/dist/i18n/es.d.ts +2 -0
  327. package/dist/i18n/es.d.ts.map +1 -0
  328. package/dist/i18n/es.js +537 -0
  329. package/dist/i18n/es.js.map +1 -0
  330. package/dist/i18n/fr.d.ts +2 -0
  331. package/dist/i18n/fr.d.ts.map +1 -0
  332. package/dist/i18n/fr.js +537 -0
  333. package/dist/i18n/fr.js.map +1 -0
  334. package/dist/i18n/hi.d.ts +2 -0
  335. package/dist/i18n/hi.d.ts.map +1 -0
  336. package/dist/i18n/hi.js +537 -0
  337. package/dist/i18n/hi.js.map +1 -0
  338. package/dist/i18n/ja.d.ts +2 -0
  339. package/dist/i18n/ja.d.ts.map +1 -0
  340. package/dist/i18n/ja.js +537 -0
  341. package/dist/i18n/ja.js.map +1 -0
  342. package/dist/i18n/ka.d.ts +2 -0
  343. package/dist/i18n/ka.d.ts.map +1 -0
  344. package/dist/i18n/ka.js +537 -0
  345. package/dist/i18n/ka.js.map +1 -0
  346. package/dist/i18n/pt.d.ts +2 -0
  347. package/dist/i18n/pt.d.ts.map +1 -0
  348. package/dist/i18n/pt.js +537 -0
  349. package/dist/i18n/pt.js.map +1 -0
  350. package/dist/i18n/ru.d.ts +6 -0
  351. package/dist/i18n/ru.d.ts.map +1 -0
  352. package/dist/i18n/ru.js +540 -0
  353. package/dist/i18n/ru.js.map +1 -0
  354. package/dist/i18n/uk.d.ts +8 -0
  355. package/dist/i18n/uk.d.ts.map +1 -0
  356. package/dist/i18n/uk.js +542 -0
  357. package/dist/i18n/uk.js.map +1 -0
  358. package/dist/i18n/uz.d.ts +2 -0
  359. package/dist/i18n/uz.d.ts.map +1 -0
  360. package/dist/i18n/uz.js +537 -0
  361. package/dist/i18n/uz.js.map +1 -0
  362. package/dist/i18n/zh.d.ts +2 -0
  363. package/dist/i18n/zh.d.ts.map +1 -0
  364. package/dist/i18n/zh.js +537 -0
  365. package/dist/i18n/zh.js.map +1 -0
  366. package/dist/i18n.d.ts +115 -0
  367. package/dist/i18n.d.ts.map +1 -0
  368. package/dist/i18n.js +233 -0
  369. package/dist/i18n.js.map +1 -0
  370. package/dist/index.d.ts +3 -0
  371. package/dist/index.d.ts.map +1 -0
  372. package/dist/index.js +10 -0
  373. package/dist/index.js.map +1 -0
  374. package/dist/installManager.d.ts +99 -0
  375. package/dist/installManager.d.ts.map +1 -0
  376. package/dist/installManager.js +943 -0
  377. package/dist/installManager.js.map +1 -0
  378. package/dist/instanceLock.d.ts +161 -0
  379. package/dist/instanceLock.d.ts.map +1 -0
  380. package/dist/instanceLock.js +388 -0
  381. package/dist/instanceLock.js.map +1 -0
  382. package/dist/mcpConfig.d.ts +76 -0
  383. package/dist/mcpConfig.d.ts.map +1 -0
  384. package/dist/mcpConfig.js +270 -0
  385. package/dist/mcpConfig.js.map +1 -0
  386. package/dist/openCodeOpenQuestion.d.ts +44 -0
  387. package/dist/openCodeOpenQuestion.d.ts.map +1 -0
  388. package/dist/openCodeOpenQuestion.js +64 -0
  389. package/dist/openCodeOpenQuestion.js.map +1 -0
  390. package/dist/openCodeQuestionFlow.d.ts +105 -0
  391. package/dist/openCodeQuestionFlow.d.ts.map +1 -0
  392. package/dist/openCodeQuestionFlow.js +143 -0
  393. package/dist/openCodeQuestionFlow.js.map +1 -0
  394. package/dist/openCodeSessionRouting.d.ts +133 -0
  395. package/dist/openCodeSessionRouting.d.ts.map +1 -0
  396. package/dist/openCodeSessionRouting.js +253 -0
  397. package/dist/openCodeSessionRouting.js.map +1 -0
  398. package/dist/openCodeSessionTitle.d.ts +50 -0
  399. package/dist/openCodeSessionTitle.d.ts.map +1 -0
  400. package/dist/openCodeSessionTitle.js +84 -0
  401. package/dist/openCodeSessionTitle.js.map +1 -0
  402. package/dist/outputTrace.d.ts +108 -0
  403. package/dist/outputTrace.d.ts.map +1 -0
  404. package/dist/outputTrace.js +430 -0
  405. package/dist/outputTrace.js.map +1 -0
  406. package/dist/pendingQuestionRepost.d.ts +47 -0
  407. package/dist/pendingQuestionRepost.d.ts.map +1 -0
  408. package/dist/pendingQuestionRepost.js +29 -0
  409. package/dist/pendingQuestionRepost.js.map +1 -0
  410. package/dist/pinnedStatus.d.ts +52 -0
  411. package/dist/pinnedStatus.d.ts.map +1 -0
  412. package/dist/pinnedStatus.js +36 -0
  413. package/dist/pinnedStatus.js.map +1 -0
  414. package/dist/platform/answerSink.d.ts +93 -0
  415. package/dist/platform/answerSink.d.ts.map +1 -0
  416. package/dist/platform/answerSink.js +31 -0
  417. package/dist/platform/answerSink.js.map +1 -0
  418. package/dist/platform/capabilityFallback.d.ts +39 -0
  419. package/dist/platform/capabilityFallback.d.ts.map +1 -0
  420. package/dist/platform/capabilityFallback.js +55 -0
  421. package/dist/platform/capabilityFallback.js.map +1 -0
  422. package/dist/platform/commandRouter.d.ts +51 -0
  423. package/dist/platform/commandRouter.d.ts.map +1 -0
  424. package/dist/platform/commandRouter.js +53 -0
  425. package/dist/platform/commandRouter.js.map +1 -0
  426. package/dist/platform/connectorSet.d.ts +39 -0
  427. package/dist/platform/connectorSet.d.ts.map +1 -0
  428. package/dist/platform/connectorSet.js +55 -0
  429. package/dist/platform/connectorSet.js.map +1 -0
  430. package/dist/platform/inbound.d.ts +147 -0
  431. package/dist/platform/inbound.d.ts.map +1 -0
  432. package/dist/platform/inbound.js +18 -0
  433. package/dist/platform/inbound.js.map +1 -0
  434. package/dist/platform/outbound.d.ts +225 -0
  435. package/dist/platform/outbound.d.ts.map +1 -0
  436. package/dist/platform/outbound.js +30 -0
  437. package/dist/platform/outbound.js.map +1 -0
  438. package/dist/platform/unservedStateGuard.d.ts +27 -0
  439. package/dist/platform/unservedStateGuard.d.ts.map +1 -0
  440. package/dist/platform/unservedStateGuard.js +42 -0
  441. package/dist/platform/unservedStateGuard.js.map +1 -0
  442. package/dist/postToSession.d.ts +94 -0
  443. package/dist/postToSession.d.ts.map +1 -0
  444. package/dist/postToSession.js +56 -0
  445. package/dist/postToSession.js.map +1 -0
  446. package/dist/progressLine.d.ts +180 -0
  447. package/dist/progressLine.d.ts.map +1 -0
  448. package/dist/progressLine.js +293 -0
  449. package/dist/progressLine.js.map +1 -0
  450. package/dist/rateLimiter.d.ts +246 -0
  451. package/dist/rateLimiter.d.ts.map +1 -0
  452. package/dist/rateLimiter.js +555 -0
  453. package/dist/rateLimiter.js.map +1 -0
  454. package/dist/requests/answerRequest.d.ts +57 -0
  455. package/dist/requests/answerRequest.d.ts.map +1 -0
  456. package/dist/requests/answerRequest.js +96 -0
  457. package/dist/requests/answerRequest.js.map +1 -0
  458. package/dist/requests/answerTail.d.ts +83 -0
  459. package/dist/requests/answerTail.d.ts.map +1 -0
  460. package/dist/requests/answerTail.js +102 -0
  461. package/dist/requests/answerTail.js.map +1 -0
  462. package/dist/requests/limitWaitAnswer.d.ts +87 -0
  463. package/dist/requests/limitWaitAnswer.d.ts.map +1 -0
  464. package/dist/requests/limitWaitAnswer.js +83 -0
  465. package/dist/requests/limitWaitAnswer.js.map +1 -0
  466. package/dist/requests/requestGroup.d.ts +44 -0
  467. package/dist/requests/requestGroup.d.ts.map +1 -0
  468. package/dist/requests/requestGroup.js +63 -0
  469. package/dist/requests/requestGroup.js.map +1 -0
  470. package/dist/requests/requestHeader.d.ts +70 -0
  471. package/dist/requests/requestHeader.d.ts.map +1 -0
  472. package/dist/requests/requestHeader.js +83 -0
  473. package/dist/requests/requestHeader.js.map +1 -0
  474. package/dist/requests/requestLedger.d.ts +217 -0
  475. package/dist/requests/requestLedger.d.ts.map +1 -0
  476. package/dist/requests/requestLedger.js +468 -0
  477. package/dist/requests/requestLedger.js.map +1 -0
  478. package/dist/requests/sessionTurnProbe.d.ts +52 -0
  479. package/dist/requests/sessionTurnProbe.d.ts.map +1 -0
  480. package/dist/requests/sessionTurnProbe.js +29 -0
  481. package/dist/requests/sessionTurnProbe.js.map +1 -0
  482. package/dist/requests/types.d.ts +181 -0
  483. package/dist/requests/types.d.ts.map +1 -0
  484. package/dist/requests/types.js +9 -0
  485. package/dist/requests/types.js.map +1 -0
  486. package/dist/requests/wakeUpEngine.d.ts +160 -0
  487. package/dist/requests/wakeUpEngine.d.ts.map +1 -0
  488. package/dist/requests/wakeUpEngine.js +399 -0
  489. package/dist/requests/wakeUpEngine.js.map +1 -0
  490. package/dist/requests/wakeUpRules.d.ts +151 -0
  491. package/dist/requests/wakeUpRules.d.ts.map +1 -0
  492. package/dist/requests/wakeUpRules.js +167 -0
  493. package/dist/requests/wakeUpRules.js.map +1 -0
  494. package/dist/resumeContext.d.ts +87 -0
  495. package/dist/resumeContext.d.ts.map +1 -0
  496. package/dist/resumeContext.js +114 -0
  497. package/dist/resumeContext.js.map +1 -0
  498. package/dist/scheduler/checkRun.d.ts +95 -0
  499. package/dist/scheduler/checkRun.d.ts.map +1 -0
  500. package/dist/scheduler/checkRun.js +172 -0
  501. package/dist/scheduler/checkRun.js.map +1 -0
  502. package/dist/scheduler/delivery.d.ts +99 -0
  503. package/dist/scheduler/delivery.d.ts.map +1 -0
  504. package/dist/scheduler/delivery.js +212 -0
  505. package/dist/scheduler/delivery.js.map +1 -0
  506. package/dist/scheduler/deliveryKind.d.ts +29 -0
  507. package/dist/scheduler/deliveryKind.d.ts.map +1 -0
  508. package/dist/scheduler/deliveryKind.js +39 -0
  509. package/dist/scheduler/deliveryKind.js.map +1 -0
  510. package/dist/scheduler/directoryThreads.d.ts +19 -0
  511. package/dist/scheduler/directoryThreads.d.ts.map +1 -0
  512. package/dist/scheduler/directoryThreads.js +28 -0
  513. package/dist/scheduler/directoryThreads.js.map +1 -0
  514. package/dist/scheduler/engine.d.ts +77 -0
  515. package/dist/scheduler/engine.d.ts.map +1 -0
  516. package/dist/scheduler/engine.js +337 -0
  517. package/dist/scheduler/engine.js.map +1 -0
  518. package/dist/scheduler/injection.d.ts +102 -0
  519. package/dist/scheduler/injection.d.ts.map +1 -0
  520. package/dist/scheduler/injection.js +122 -0
  521. package/dist/scheduler/injection.js.map +1 -0
  522. package/dist/scheduler/mcpBoot.d.ts +65 -0
  523. package/dist/scheduler/mcpBoot.d.ts.map +1 -0
  524. package/dist/scheduler/mcpBoot.js +60 -0
  525. package/dist/scheduler/mcpBoot.js.map +1 -0
  526. package/dist/scheduler/mcpSurface.d.ts +355 -0
  527. package/dist/scheduler/mcpSurface.d.ts.map +1 -0
  528. package/dist/scheduler/mcpSurface.js +1257 -0
  529. package/dist/scheduler/mcpSurface.js.map +1 -0
  530. package/dist/scheduler/rebindResume.d.ts +27 -0
  531. package/dist/scheduler/rebindResume.d.ts.map +1 -0
  532. package/dist/scheduler/rebindResume.js +17 -0
  533. package/dist/scheduler/rebindResume.js.map +1 -0
  534. package/dist/scheduler/recurrence.d.ts +58 -0
  535. package/dist/scheduler/recurrence.d.ts.map +1 -0
  536. package/dist/scheduler/recurrence.js +210 -0
  537. package/dist/scheduler/recurrence.js.map +1 -0
  538. package/dist/scheduler/runLedger.d.ts +59 -0
  539. package/dist/scheduler/runLedger.d.ts.map +1 -0
  540. package/dist/scheduler/runLedger.js +54 -0
  541. package/dist/scheduler/runLedger.js.map +1 -0
  542. package/dist/scheduler/store.d.ts +97 -0
  543. package/dist/scheduler/store.d.ts.map +1 -0
  544. package/dist/scheduler/store.js +124 -0
  545. package/dist/scheduler/store.js.map +1 -0
  546. package/dist/scheduler/timezoneRecompute.d.ts +61 -0
  547. package/dist/scheduler/timezoneRecompute.d.ts.map +1 -0
  548. package/dist/scheduler/timezoneRecompute.js +46 -0
  549. package/dist/scheduler/timezoneRecompute.js.map +1 -0
  550. package/dist/scheduler/types.d.ts +139 -0
  551. package/dist/scheduler/types.d.ts.map +1 -0
  552. package/dist/scheduler/types.js +8 -0
  553. package/dist/scheduler/types.js.map +1 -0
  554. package/dist/sendErrorClassifier.d.ts +45 -0
  555. package/dist/sendErrorClassifier.d.ts.map +1 -0
  556. package/dist/sendErrorClassifier.js +65 -0
  557. package/dist/sendErrorClassifier.js.map +1 -0
  558. package/dist/sessionKey.d.ts +136 -0
  559. package/dist/sessionKey.d.ts.map +1 -0
  560. package/dist/sessionKey.js +153 -0
  561. package/dist/sessionKey.js.map +1 -0
  562. package/dist/sessionPick.d.ts +42 -0
  563. package/dist/sessionPick.d.ts.map +1 -0
  564. package/dist/sessionPick.js +39 -0
  565. package/dist/sessionPick.js.map +1 -0
  566. package/dist/shutdown.d.ts +126 -0
  567. package/dist/shutdown.d.ts.map +1 -0
  568. package/dist/shutdown.js +164 -0
  569. package/dist/shutdown.js.map +1 -0
  570. package/dist/startupPromptBuffer.d.ts +85 -0
  571. package/dist/startupPromptBuffer.d.ts.map +1 -0
  572. package/dist/startupPromptBuffer.js +123 -0
  573. package/dist/startupPromptBuffer.js.map +1 -0
  574. package/dist/state.d.ts +1245 -0
  575. package/dist/state.d.ts.map +1 -0
  576. package/dist/state.js +1830 -0
  577. package/dist/state.js.map +1 -0
  578. package/dist/threadContextPreamble.d.ts +89 -0
  579. package/dist/threadContextPreamble.d.ts.map +1 -0
  580. package/dist/threadContextPreamble.js +102 -0
  581. package/dist/threadContextPreamble.js.map +1 -0
  582. package/dist/threadRouting.d.ts +164 -0
  583. package/dist/threadRouting.d.ts.map +1 -0
  584. package/dist/threadRouting.js +182 -0
  585. package/dist/threadRouting.js.map +1 -0
  586. package/dist/types.d.ts +1015 -0
  587. package/dist/types.d.ts.map +1 -0
  588. package/dist/types.js +3 -0
  589. package/dist/types.js.map +1 -0
  590. package/dist/utils/abortableFifo.d.ts +10 -0
  591. package/dist/utils/abortableFifo.d.ts.map +1 -0
  592. package/dist/utils/abortableFifo.js +55 -0
  593. package/dist/utils/abortableFifo.js.map +1 -0
  594. package/dist/utils/adoptedToolList.d.ts +27 -0
  595. package/dist/utils/adoptedToolList.d.ts.map +1 -0
  596. package/dist/utils/adoptedToolList.js +22 -0
  597. package/dist/utils/adoptedToolList.js.map +1 -0
  598. package/dist/utils/agentEnvironment.d.ts +42 -0
  599. package/dist/utils/agentEnvironment.d.ts.map +1 -0
  600. package/dist/utils/agentEnvironment.js +122 -0
  601. package/dist/utils/agentEnvironment.js.map +1 -0
  602. package/dist/utils/ansiClean.d.ts +11 -0
  603. package/dist/utils/ansiClean.d.ts.map +1 -0
  604. package/dist/utils/ansiClean.js +139 -0
  605. package/dist/utils/ansiClean.js.map +1 -0
  606. package/dist/utils/autoContinueOnLimit.d.ts +49 -0
  607. package/dist/utils/autoContinueOnLimit.d.ts.map +1 -0
  608. package/dist/utils/autoContinueOnLimit.js +69 -0
  609. package/dist/utils/autoContinueOnLimit.js.map +1 -0
  610. package/dist/utils/canonicalPathContainment.d.ts +7 -0
  611. package/dist/utils/canonicalPathContainment.d.ts.map +1 -0
  612. package/dist/utils/canonicalPathContainment.js +48 -0
  613. package/dist/utils/canonicalPathContainment.js.map +1 -0
  614. package/dist/utils/claudeAuthLogin.d.ts +71 -0
  615. package/dist/utils/claudeAuthLogin.d.ts.map +1 -0
  616. package/dist/utils/claudeAuthLogin.js +93 -0
  617. package/dist/utils/claudeAuthLogin.js.map +1 -0
  618. package/dist/utils/claudeChunkClassifier.d.ts +97 -0
  619. package/dist/utils/claudeChunkClassifier.d.ts.map +1 -0
  620. package/dist/utils/claudeChunkClassifier.js +254 -0
  621. package/dist/utils/claudeChunkClassifier.js.map +1 -0
  622. package/dist/utils/claudeCodeVersion.d.ts +31 -0
  623. package/dist/utils/claudeCodeVersion.d.ts.map +1 -0
  624. package/dist/utils/claudeCodeVersion.js +62 -0
  625. package/dist/utils/claudeCodeVersion.js.map +1 -0
  626. package/dist/utils/claudeCompactHook.d.ts +64 -0
  627. package/dist/utils/claudeCompactHook.d.ts.map +1 -0
  628. package/dist/utils/claudeCompactHook.js +98 -0
  629. package/dist/utils/claudeCompactHook.js.map +1 -0
  630. package/dist/utils/claudeLivenessAction.d.ts +208 -0
  631. package/dist/utils/claudeLivenessAction.d.ts.map +1 -0
  632. package/dist/utils/claudeLivenessAction.js +135 -0
  633. package/dist/utils/claudeLivenessAction.js.map +1 -0
  634. package/dist/utils/claudeMcpHeal.d.ts +92 -0
  635. package/dist/utils/claudeMcpHeal.d.ts.map +1 -0
  636. package/dist/utils/claudeMcpHeal.js +91 -0
  637. package/dist/utils/claudeMcpHeal.js.map +1 -0
  638. package/dist/utils/claudeRelayRouting.d.ts +86 -0
  639. package/dist/utils/claudeRelayRouting.d.ts.map +1 -0
  640. package/dist/utils/claudeRelayRouting.js +159 -0
  641. package/dist/utils/claudeRelayRouting.js.map +1 -0
  642. package/dist/utils/claudeRuntimeInfo.d.ts +26 -0
  643. package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -0
  644. package/dist/utils/claudeRuntimeInfo.js +151 -0
  645. package/dist/utils/claudeRuntimeInfo.js.map +1 -0
  646. package/dist/utils/claudeScrapeShapes.d.ts +256 -0
  647. package/dist/utils/claudeScrapeShapes.d.ts.map +1 -0
  648. package/dist/utils/claudeScrapeShapes.js +290 -0
  649. package/dist/utils/claudeScrapeShapes.js.map +1 -0
  650. package/dist/utils/claudeSessionTitle.d.ts +27 -0
  651. package/dist/utils/claudeSessionTitle.d.ts.map +1 -0
  652. package/dist/utils/claudeSessionTitle.js +90 -0
  653. package/dist/utils/claudeSessionTitle.js.map +1 -0
  654. package/dist/utils/claudeStreamJson.d.ts +202 -0
  655. package/dist/utils/claudeStreamJson.d.ts.map +1 -0
  656. package/dist/utils/claudeStreamJson.js +351 -0
  657. package/dist/utils/claudeStreamJson.js.map +1 -0
  658. package/dist/utils/claudeSubagentTail.d.ts +93 -0
  659. package/dist/utils/claudeSubagentTail.d.ts.map +1 -0
  660. package/dist/utils/claudeSubagentTail.js +136 -0
  661. package/dist/utils/claudeSubagentTail.js.map +1 -0
  662. package/dist/utils/clearThreadOutputQueues.d.ts +43 -0
  663. package/dist/utils/clearThreadOutputQueues.d.ts.map +1 -0
  664. package/dist/utils/clearThreadOutputQueues.js +39 -0
  665. package/dist/utils/clearThreadOutputQueues.js.map +1 -0
  666. package/dist/utils/compactCommandRoute.d.ts +45 -0
  667. package/dist/utils/compactCommandRoute.d.ts.map +1 -0
  668. package/dist/utils/compactCommandRoute.js +36 -0
  669. package/dist/utils/compactCommandRoute.js.map +1 -0
  670. package/dist/utils/compactOnIdle.d.ts +329 -0
  671. package/dist/utils/compactOnIdle.d.ts.map +1 -0
  672. package/dist/utils/compactOnIdle.js +379 -0
  673. package/dist/utils/compactOnIdle.js.map +1 -0
  674. package/dist/utils/consoleFileTap.d.ts +51 -0
  675. package/dist/utils/consoleFileTap.d.ts.map +1 -0
  676. package/dist/utils/consoleFileTap.js +86 -0
  677. package/dist/utils/consoleFileTap.js.map +1 -0
  678. package/dist/utils/displayVerbosity.d.ts +44 -0
  679. package/dist/utils/displayVerbosity.d.ts.map +1 -0
  680. package/dist/utils/displayVerbosity.js +75 -0
  681. package/dist/utils/displayVerbosity.js.map +1 -0
  682. package/dist/utils/download.d.ts +72 -0
  683. package/dist/utils/download.d.ts.map +1 -0
  684. package/dist/utils/download.js +216 -0
  685. package/dist/utils/download.js.map +1 -0
  686. package/dist/utils/draftFinalize.d.ts +110 -0
  687. package/dist/utils/draftFinalize.d.ts.map +1 -0
  688. package/dist/utils/draftFinalize.js +100 -0
  689. package/dist/utils/draftFinalize.js.map +1 -0
  690. package/dist/utils/draftId.d.ts +36 -0
  691. package/dist/utils/draftId.d.ts.map +1 -0
  692. package/dist/utils/draftId.js +46 -0
  693. package/dist/utils/draftId.js.map +1 -0
  694. package/dist/utils/draftPacer.d.ts +72 -0
  695. package/dist/utils/draftPacer.d.ts.map +1 -0
  696. package/dist/utils/draftPacer.js +53 -0
  697. package/dist/utils/draftPacer.js.map +1 -0
  698. package/dist/utils/effortStartupKeystroke.d.ts +20 -0
  699. package/dist/utils/effortStartupKeystroke.d.ts.map +1 -0
  700. package/dist/utils/effortStartupKeystroke.js +28 -0
  701. package/dist/utils/effortStartupKeystroke.js.map +1 -0
  702. package/dist/utils/ensureSessionPlan.d.ts +70 -0
  703. package/dist/utils/ensureSessionPlan.d.ts.map +1 -0
  704. package/dist/utils/ensureSessionPlan.js +54 -0
  705. package/dist/utils/ensureSessionPlan.js.map +1 -0
  706. package/dist/utils/fileSendPlan.d.ts +217 -0
  707. package/dist/utils/fileSendPlan.d.ts.map +1 -0
  708. package/dist/utils/fileSendPlan.js +291 -0
  709. package/dist/utils/fileSendPlan.js.map +1 -0
  710. package/dist/utils/fileSendService.d.ts +94 -0
  711. package/dist/utils/fileSendService.d.ts.map +1 -0
  712. package/dist/utils/fileSendService.js +387 -0
  713. package/dist/utils/fileSendService.js.map +1 -0
  714. package/dist/utils/groupFinalizePlan.d.ts +38 -0
  715. package/dist/utils/groupFinalizePlan.d.ts.map +1 -0
  716. package/dist/utils/groupFinalizePlan.js +35 -0
  717. package/dist/utils/groupFinalizePlan.js.map +1 -0
  718. package/dist/utils/identicalOutputGuard.d.ts +83 -0
  719. package/dist/utils/identicalOutputGuard.d.ts.map +1 -0
  720. package/dist/utils/identicalOutputGuard.js +99 -0
  721. package/dist/utils/identicalOutputGuard.js.map +1 -0
  722. package/dist/utils/isoTimestamp.d.ts +16 -0
  723. package/dist/utils/isoTimestamp.d.ts.map +1 -0
  724. package/dist/utils/isoTimestamp.js +34 -0
  725. package/dist/utils/isoTimestamp.js.map +1 -0
  726. package/dist/utils/jsonStreamBusyWatchdog.d.ts +130 -0
  727. package/dist/utils/jsonStreamBusyWatchdog.d.ts.map +1 -0
  728. package/dist/utils/jsonStreamBusyWatchdog.js +122 -0
  729. package/dist/utils/jsonStreamBusyWatchdog.js.map +1 -0
  730. package/dist/utils/jsonStreamHost.d.ts +227 -0
  731. package/dist/utils/jsonStreamHost.d.ts.map +1 -0
  732. package/dist/utils/jsonStreamHost.js +417 -0
  733. package/dist/utils/jsonStreamHost.js.map +1 -0
  734. package/dist/utils/keyedTransitionQueue.d.ts +18 -0
  735. package/dist/utils/keyedTransitionQueue.d.ts.map +1 -0
  736. package/dist/utils/keyedTransitionQueue.js +34 -0
  737. package/dist/utils/keyedTransitionQueue.js.map +1 -0
  738. package/dist/utils/limitEpisodeRecovery.d.ts +92 -0
  739. package/dist/utils/limitEpisodeRecovery.d.ts.map +1 -0
  740. package/dist/utils/limitEpisodeRecovery.js +133 -0
  741. package/dist/utils/limitEpisodeRecovery.js.map +1 -0
  742. package/dist/utils/limitHeldPromptQueue.d.ts +48 -0
  743. package/dist/utils/limitHeldPromptQueue.d.ts.map +1 -0
  744. package/dist/utils/limitHeldPromptQueue.js +59 -0
  745. package/dist/utils/limitHeldPromptQueue.js.map +1 -0
  746. package/dist/utils/limitHeldPrompts.d.ts +58 -0
  747. package/dist/utils/limitHeldPrompts.d.ts.map +1 -0
  748. package/dist/utils/limitHeldPrompts.js +65 -0
  749. package/dist/utils/limitHeldPrompts.js.map +1 -0
  750. package/dist/utils/linkPreviewSuppression.d.ts +18 -0
  751. package/dist/utils/linkPreviewSuppression.d.ts.map +1 -0
  752. package/dist/utils/linkPreviewSuppression.js +37 -0
  753. package/dist/utils/linkPreviewSuppression.js.map +1 -0
  754. package/dist/utils/localClock.d.ts +15 -0
  755. package/dist/utils/localClock.d.ts.map +1 -0
  756. package/dist/utils/localClock.js +29 -0
  757. package/dist/utils/localClock.js.map +1 -0
  758. package/dist/utils/markdownTableRender.d.ts +83 -0
  759. package/dist/utils/markdownTableRender.d.ts.map +1 -0
  760. package/dist/utils/markdownTableRender.js +298 -0
  761. package/dist/utils/markdownTableRender.js.map +1 -0
  762. package/dist/utils/mediaGroupCollector.d.ts +51 -0
  763. package/dist/utils/mediaGroupCollector.d.ts.map +1 -0
  764. package/dist/utils/mediaGroupCollector.js +90 -0
  765. package/dist/utils/mediaGroupCollector.js.map +1 -0
  766. package/dist/utils/messageSendService.d.ts +136 -0
  767. package/dist/utils/messageSendService.d.ts.map +1 -0
  768. package/dist/utils/messageSendService.js +165 -0
  769. package/dist/utils/messageSendService.js.map +1 -0
  770. package/dist/utils/minutesOverride.d.ts +7 -0
  771. package/dist/utils/minutesOverride.d.ts.map +1 -0
  772. package/dist/utils/minutesOverride.js +16 -0
  773. package/dist/utils/minutesOverride.js.map +1 -0
  774. package/dist/utils/modelPickerPlan.d.ts +119 -0
  775. package/dist/utils/modelPickerPlan.d.ts.map +1 -0
  776. package/dist/utils/modelPickerPlan.js +171 -0
  777. package/dist/utils/modelPickerPlan.js.map +1 -0
  778. package/dist/utils/modelSetReplyDecision.d.ts +67 -0
  779. package/dist/utils/modelSetReplyDecision.d.ts.map +1 -0
  780. package/dist/utils/modelSetReplyDecision.js +27 -0
  781. package/dist/utils/modelSetReplyDecision.js.map +1 -0
  782. package/dist/utils/openCodeAuthLogin.d.ts +181 -0
  783. package/dist/utils/openCodeAuthLogin.d.ts.map +1 -0
  784. package/dist/utils/openCodeAuthLogin.js +393 -0
  785. package/dist/utils/openCodeAuthLogin.js.map +1 -0
  786. package/dist/utils/openCodeCompactPlugin.d.ts +81 -0
  787. package/dist/utils/openCodeCompactPlugin.d.ts.map +1 -0
  788. package/dist/utils/openCodeCompactPlugin.js +146 -0
  789. package/dist/utils/openCodeCompactPlugin.js.map +1 -0
  790. package/dist/utils/openCodeTurnActivity.d.ts +67 -0
  791. package/dist/utils/openCodeTurnActivity.d.ts.map +1 -0
  792. package/dist/utils/openCodeTurnActivity.js +27 -0
  793. package/dist/utils/openCodeTurnActivity.js.map +1 -0
  794. package/dist/utils/outputDebounce.d.ts +24 -0
  795. package/dist/utils/outputDebounce.d.ts.map +1 -0
  796. package/dist/utils/outputDebounce.js +30 -0
  797. package/dist/utils/outputDebounce.js.map +1 -0
  798. package/dist/utils/outputFlushTiming.d.ts +54 -0
  799. package/dist/utils/outputFlushTiming.d.ts.map +1 -0
  800. package/dist/utils/outputFlushTiming.js +48 -0
  801. package/dist/utils/outputFlushTiming.js.map +1 -0
  802. package/dist/utils/paginateList.d.ts +25 -0
  803. package/dist/utils/paginateList.d.ts.map +1 -0
  804. package/dist/utils/paginateList.js +32 -0
  805. package/dist/utils/paginateList.js.map +1 -0
  806. package/dist/utils/paneDiff.d.ts +55 -0
  807. package/dist/utils/paneDiff.d.ts.map +1 -0
  808. package/dist/utils/paneDiff.js +88 -0
  809. package/dist/utils/paneDiff.js.map +1 -0
  810. package/dist/utils/paneResizeGuard.d.ts +69 -0
  811. package/dist/utils/paneResizeGuard.d.ts.map +1 -0
  812. package/dist/utils/paneResizeGuard.js +91 -0
  813. package/dist/utils/paneResizeGuard.js.map +1 -0
  814. package/dist/utils/persistAdapterSessionIds.d.ts +39 -0
  815. package/dist/utils/persistAdapterSessionIds.d.ts.map +1 -0
  816. package/dist/utils/persistAdapterSessionIds.js +28 -0
  817. package/dist/utils/persistAdapterSessionIds.js.map +1 -0
  818. package/dist/utils/pinnedBannerSkipDecision.d.ts +44 -0
  819. package/dist/utils/pinnedBannerSkipDecision.d.ts.map +1 -0
  820. package/dist/utils/pinnedBannerSkipDecision.js +20 -0
  821. package/dist/utils/pinnedBannerSkipDecision.js.map +1 -0
  822. package/dist/utils/pollBackoff.d.ts +45 -0
  823. package/dist/utils/pollBackoff.d.ts.map +1 -0
  824. package/dist/utils/pollBackoff.js +44 -0
  825. package/dist/utils/pollBackoff.js.map +1 -0
  826. package/dist/utils/promptDelivery.d.ts +46 -0
  827. package/dist/utils/promptDelivery.d.ts.map +1 -0
  828. package/dist/utils/promptDelivery.js +49 -0
  829. package/dist/utils/promptDelivery.js.map +1 -0
  830. package/dist/utils/providerDisconnectPlan.d.ts +82 -0
  831. package/dist/utils/providerDisconnectPlan.d.ts.map +1 -0
  832. package/dist/utils/providerDisconnectPlan.js +110 -0
  833. package/dist/utils/providerDisconnectPlan.js.map +1 -0
  834. package/dist/utils/rateLimitLog.d.ts +48 -0
  835. package/dist/utils/rateLimitLog.d.ts.map +1 -0
  836. package/dist/utils/rateLimitLog.js +43 -0
  837. package/dist/utils/rateLimitLog.js.map +1 -0
  838. package/dist/utils/recentRelayWindow.d.ts +165 -0
  839. package/dist/utils/recentRelayWindow.d.ts.map +1 -0
  840. package/dist/utils/recentRelayWindow.js +284 -0
  841. package/dist/utils/recentRelayWindow.js.map +1 -0
  842. package/dist/utils/recvPreviewRedaction.d.ts +23 -0
  843. package/dist/utils/recvPreviewRedaction.d.ts.map +1 -0
  844. package/dist/utils/recvPreviewRedaction.js +39 -0
  845. package/dist/utils/recvPreviewRedaction.js.map +1 -0
  846. package/dist/utils/reminderFlow.d.ts +148 -0
  847. package/dist/utils/reminderFlow.d.ts.map +1 -0
  848. package/dist/utils/reminderFlow.js +122 -0
  849. package/dist/utils/reminderFlow.js.map +1 -0
  850. package/dist/utils/reminderScheduleText.d.ts +87 -0
  851. package/dist/utils/reminderScheduleText.d.ts.map +1 -0
  852. package/dist/utils/reminderScheduleText.js +135 -0
  853. package/dist/utils/reminderScheduleText.js.map +1 -0
  854. package/dist/utils/reminderWizard.d.ts +710 -0
  855. package/dist/utils/reminderWizard.d.ts.map +1 -0
  856. package/dist/utils/reminderWizard.js +1164 -0
  857. package/dist/utils/reminderWizard.js.map +1 -0
  858. package/dist/utils/replyQuote.d.ts +111 -0
  859. package/dist/utils/replyQuote.d.ts.map +1 -0
  860. package/dist/utils/replyQuote.js +122 -0
  861. package/dist/utils/replyQuote.js.map +1 -0
  862. package/dist/utils/resolveBinary.d.ts +25 -0
  863. package/dist/utils/resolveBinary.d.ts.map +1 -0
  864. package/dist/utils/resolveBinary.js +99 -0
  865. package/dist/utils/resolveBinary.js.map +1 -0
  866. package/dist/utils/retryAfterHeader.d.ts +7 -0
  867. package/dist/utils/retryAfterHeader.d.ts.map +1 -0
  868. package/dist/utils/retryAfterHeader.js +17 -0
  869. package/dist/utils/retryAfterHeader.js.map +1 -0
  870. package/dist/utils/rotatingJsonlFile.d.ts +40 -0
  871. package/dist/utils/rotatingJsonlFile.d.ts.map +1 -0
  872. package/dist/utils/rotatingJsonlFile.js +106 -0
  873. package/dist/utils/rotatingJsonlFile.js.map +1 -0
  874. package/dist/utils/rotatingLogFile.d.ts +25 -0
  875. package/dist/utils/rotatingLogFile.d.ts.map +1 -0
  876. package/dist/utils/rotatingLogFile.js +74 -0
  877. package/dist/utils/rotatingLogFile.js.map +1 -0
  878. package/dist/utils/sendRateTracker.d.ts +59 -0
  879. package/dist/utils/sendRateTracker.d.ts.map +1 -0
  880. package/dist/utils/sendRateTracker.js +144 -0
  881. package/dist/utils/sendRateTracker.js.map +1 -0
  882. package/dist/utils/serialQueue.d.ts +5 -0
  883. package/dist/utils/serialQueue.d.ts.map +1 -0
  884. package/dist/utils/serialQueue.js +14 -0
  885. package/dist/utils/serialQueue.js.map +1 -0
  886. package/dist/utils/sseStreamLifecycle.d.ts +32 -0
  887. package/dist/utils/sseStreamLifecycle.d.ts.map +1 -0
  888. package/dist/utils/sseStreamLifecycle.js +41 -0
  889. package/dist/utils/sseStreamLifecycle.js.map +1 -0
  890. package/dist/utils/startupReadiness.d.ts +119 -0
  891. package/dist/utils/startupReadiness.d.ts.map +1 -0
  892. package/dist/utils/startupReadiness.js +148 -0
  893. package/dist/utils/startupReadiness.js.map +1 -0
  894. package/dist/utils/statusFlushDecision.d.ts +18 -0
  895. package/dist/utils/statusFlushDecision.d.ts.map +1 -0
  896. package/dist/utils/statusFlushDecision.js +53 -0
  897. package/dist/utils/statusFlushDecision.js.map +1 -0
  898. package/dist/utils/subagentRender.d.ts +52 -0
  899. package/dist/utils/subagentRender.d.ts.map +1 -0
  900. package/dist/utils/subagentRender.js +66 -0
  901. package/dist/utils/subagentRender.js.map +1 -0
  902. package/dist/utils/subagentStatusRender.d.ts +90 -0
  903. package/dist/utils/subagentStatusRender.d.ts.map +1 -0
  904. package/dist/utils/subagentStatusRender.js +124 -0
  905. package/dist/utils/subagentStatusRender.js.map +1 -0
  906. package/dist/utils/telegramError.d.ts +2 -0
  907. package/dist/utils/telegramError.d.ts.map +1 -0
  908. package/dist/utils/telegramError.js +16 -0
  909. package/dist/utils/telegramError.js.map +1 -0
  910. package/dist/utils/terminalEmitPlan.d.ts +74 -0
  911. package/dist/utils/terminalEmitPlan.d.ts.map +1 -0
  912. package/dist/utils/terminalEmitPlan.js +86 -0
  913. package/dist/utils/terminalEmitPlan.js.map +1 -0
  914. package/dist/utils/thinkingRender.d.ts +74 -0
  915. package/dist/utils/thinkingRender.d.ts.map +1 -0
  916. package/dist/utils/thinkingRender.js +85 -0
  917. package/dist/utils/thinkingRender.js.map +1 -0
  918. package/dist/utils/threadStatusReport.d.ts +55 -0
  919. package/dist/utils/threadStatusReport.d.ts.map +1 -0
  920. package/dist/utils/threadStatusReport.js +65 -0
  921. package/dist/utils/threadStatusReport.js.map +1 -0
  922. package/dist/utils/threadToggle.d.ts +29 -0
  923. package/dist/utils/threadToggle.d.ts.map +1 -0
  924. package/dist/utils/threadToggle.js +39 -0
  925. package/dist/utils/threadToggle.js.map +1 -0
  926. package/dist/utils/timezone.d.ts +125 -0
  927. package/dist/utils/timezone.d.ts.map +1 -0
  928. package/dist/utils/timezone.js +278 -0
  929. package/dist/utils/timezone.js.map +1 -0
  930. package/dist/utils/tmuxExec.d.ts +61 -0
  931. package/dist/utils/tmuxExec.d.ts.map +1 -0
  932. package/dist/utils/tmuxExec.js +109 -0
  933. package/dist/utils/tmuxExec.js.map +1 -0
  934. package/dist/utils/tmuxSessionName.d.ts +34 -0
  935. package/dist/utils/tmuxSessionName.d.ts.map +1 -0
  936. package/dist/utils/tmuxSessionName.js +51 -0
  937. package/dist/utils/tmuxSessionName.js.map +1 -0
  938. package/dist/utils/toolResultRender.d.ts +61 -0
  939. package/dist/utils/toolResultRender.d.ts.map +1 -0
  940. package/dist/utils/toolResultRender.js +62 -0
  941. package/dist/utils/toolResultRender.js.map +1 -0
  942. package/dist/utils/topicRequest.d.ts +61 -0
  943. package/dist/utils/topicRequest.d.ts.map +1 -0
  944. package/dist/utils/topicRequest.js +68 -0
  945. package/dist/utils/topicRequest.js.map +1 -0
  946. package/dist/utils/topicView.d.ts +55 -0
  947. package/dist/utils/topicView.d.ts.map +1 -0
  948. package/dist/utils/topicView.js +56 -0
  949. package/dist/utils/topicView.js.map +1 -0
  950. package/dist/utils/transcribeAudio.d.ts +89 -0
  951. package/dist/utils/transcribeAudio.d.ts.map +1 -0
  952. package/dist/utils/transcribeAudio.js +249 -0
  953. package/dist/utils/transcribeAudio.js.map +1 -0
  954. package/dist/utils/transientFrames.d.ts +52 -0
  955. package/dist/utils/transientFrames.d.ts.map +1 -0
  956. package/dist/utils/transientFrames.js +41 -0
  957. package/dist/utils/transientFrames.js.map +1 -0
  958. package/dist/utils/typingActive.d.ts +35 -0
  959. package/dist/utils/typingActive.d.ts.map +1 -0
  960. package/dist/utils/typingActive.js +22 -0
  961. package/dist/utils/typingActive.js.map +1 -0
  962. package/dist/utils/typingLoopBackstop.d.ts +64 -0
  963. package/dist/utils/typingLoopBackstop.d.ts.map +1 -0
  964. package/dist/utils/typingLoopBackstop.js +68 -0
  965. package/dist/utils/typingLoopBackstop.js.map +1 -0
  966. package/dist/utils/verbosityRender.d.ts +18 -0
  967. package/dist/utils/verbosityRender.d.ts.map +1 -0
  968. package/dist/utils/verbosityRender.js +17 -0
  969. package/dist/utils/verbosityRender.js.map +1 -0
  970. package/dist/utils/wedgeRecovery.d.ts +57 -0
  971. package/dist/utils/wedgeRecovery.d.ts.map +1 -0
  972. package/dist/utils/wedgeRecovery.js +24 -0
  973. package/dist/utils/wedgeRecovery.js.map +1 -0
  974. package/dist/utils.d.ts +30 -0
  975. package/dist/utils.d.ts.map +1 -0
  976. package/dist/utils.js +61 -0
  977. package/dist/utils.js.map +1 -0
  978. package/dist/validation.d.ts +113 -0
  979. package/dist/validation.d.ts.map +1 -0
  980. package/dist/validation.js +226 -0
  981. package/dist/validation.js.map +1 -0
  982. package/dist/voiceQueue.d.ts +7 -0
  983. package/dist/voiceQueue.d.ts.map +1 -0
  984. package/dist/voiceQueue.js +33 -0
  985. package/dist/voiceQueue.js.map +1 -0
  986. package/examples/.env.example +17 -0
  987. package/examples/docker-compose.yml +36 -0
  988. package/package.json +83 -4
package/dist/state.js ADDED
@@ -0,0 +1,1830 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports._fsForTests = exports.StateStore = exports.KeyLock = exports.compactIdleTrackingPersistStepMs = exports.STATE_SCHEMA_VERSION = void 0;
37
+ exports.writeFileAtomic = writeFileAtomic;
38
+ exports.loadStateFile = loadStateFile;
39
+ exports.migrateLegacyMessageIdsFile = migrateLegacyMessageIdsFile;
40
+ exports.resolveDataDir = resolveDataDir;
41
+ exports.getStateStore = getStateStore;
42
+ exports._resetStateStoreSingletonForTests = _resetStateStoreSingletonForTests;
43
+ const fs = __importStar(require("fs"));
44
+ exports._fsForTests = fs;
45
+ const fs_1 = require("fs");
46
+ const path = __importStar(require("path"));
47
+ const os = __importStar(require("os"));
48
+ const node_crypto_1 = require("node:crypto");
49
+ const sessionKey_1 = require("./sessionKey");
50
+ const displayVerbosity_1 = require("./utils/displayVerbosity");
51
+ const topicView_1 = require("./utils/topicView");
52
+ const compactOnIdle_1 = require("./utils/compactOnIdle");
53
+ const autoContinueOnLimit_1 = require("./utils/autoContinueOnLimit");
54
+ const requestGroup_1 = require("./requests/requestGroup");
55
+ /**
56
+ * @description On-disk state for the multi-thread telegram bot.
57
+ *
58
+ * Replaces the legacy `~/.telegram-bot-messages.json` (which only persisted
59
+ * `messageIds` per user) with a richer per-`SessionKey` schema:
60
+ *
61
+ * - `bindings[key]` → thread is attached to a subdir under `WORK_ROOT`
62
+ * - `agents[key]` → which adapter the thread is using, model, session ids
63
+ * - `messages[key]` → message ids tracked by `/clear`
64
+ *
65
+ * Schema source: plan §9. Field additions for D14 (`claudeSessionId`), §13.19
66
+ * (`opencodeSessionId`) and D49 (`bindings[key].closed`) are inlined here.
67
+ *
68
+ * The file is rewritten atomically (`writeFile(tmp) → fsync(fd) → rename →
69
+ * fsync(parentDir)`, plan §13.14, T4). Concurrent mutations to the same
70
+ * `SessionKey` are serialised by a per-key async lock (plan §13.15, E3).
71
+ *
72
+ * **This module is intentionally NOT yet imported from `bot.ts`.** Plan §11
73
+ * Этап 2 wires state in only on the following commit (Этап 3) — keeping the
74
+ * landing surgical.
75
+ */
76
+ /** Current schema version stamped into `state.json`. Bump on breaking layout changes. */
77
+ exports.STATE_SCHEMA_VERSION = 1;
78
+ /** Default debounce window (ms) for batched saves. Overridable via the store constructor for tests. */
79
+ const DEFAULT_SAVE_DEBOUNCE_MS = 500;
80
+ /**
81
+ * Coarse step (ms) the activity/turn stamps must move past the last PERSISTED
82
+ * value before a save is scheduled. Load-bearing for cost, not correctness:
83
+ * those two stamps are written on EVERY agent output chunk, and `state.json` is
84
+ * rewritten WHOLE (atomically, with fsync) per save — so a `scheduleSave()` per
85
+ * chunk would turn a streaming turn into a debounced disk-rewrite loop. A
86
+ * 60-second granularity is irrelevant against the 55-minute idle threshold.
87
+ */
88
+ exports.compactIdleTrackingPersistStepMs = 60_000;
89
+ /** Empty state used both for fresh installs and after a corruption-archive event. */
90
+ function emptyState() {
91
+ return {
92
+ version: exports.STATE_SCHEMA_VERSION,
93
+ bindings: {},
94
+ agents: {},
95
+ messages: {},
96
+ };
97
+ }
98
+ /** Per-thread message-id cap — older ids beyond this are dropped to keep state small. */
99
+ const MESSAGE_ID_RING_CAP = 500;
100
+ /** Byte length of the lazily-minted scheduler MCP HMAC secret (32 bytes → 64 hex chars). */
101
+ const schedulerMcpSecretByteLength = 32;
102
+ /**
103
+ * @description Promise-chain per-key lock. The map holds the tail of each
104
+ * key's queue; new callers attach to the tail and append themselves. Errors
105
+ * in one task don't poison followers — the chain only carries scheduling,
106
+ * not values. See plan §13.15 (E3).
107
+ *
108
+ * Exported for unit tests (plan §11 Этап 7, R5).
109
+ */
110
+ class KeyLock {
111
+ chains = new Map();
112
+ async withLock(keyStr, fn) {
113
+ const prev = this.chains.get(keyStr);
114
+ const run = async () => {
115
+ if (prev) {
116
+ try {
117
+ await prev;
118
+ }
119
+ catch {
120
+ // Swallow predecessor failures — they shouldn't cascade to followers.
121
+ }
122
+ }
123
+ return fn();
124
+ };
125
+ const current = run();
126
+ // Store a swallowed-error variant so this.chains.get() always resolves.
127
+ const tracked = current.then(() => undefined, () => undefined);
128
+ this.chains.set(keyStr, tracked);
129
+ try {
130
+ return await current;
131
+ }
132
+ finally {
133
+ // If no follower has overwritten our slot, drop the entry to avoid leaks.
134
+ if (this.chains.get(keyStr) === tracked) {
135
+ this.chains.delete(keyStr);
136
+ }
137
+ }
138
+ }
139
+ }
140
+ exports.KeyLock = KeyLock;
141
+ /**
142
+ * @description Best-effort atomic write of `content` to `finalPath`.
143
+ *
144
+ * Sequence: `writeFile(tmp)` → `fsync(tmp)` → `rename(tmp, final)` →
145
+ * `fsync(parentDir)`. The last step is critical: without it, `rename`
146
+ * survives crashes but the new directory entry can be lost on a power
147
+ * cut on ext4 (plan §13.14, fix to T4).
148
+ *
149
+ * Tmp files are colocated with the final file so `rename` stays on the
150
+ * same filesystem (cross-fs rename would degrade to copy+unlink and break
151
+ * atomicity). Permissions on the tmp default to `0600` so a state file
152
+ * containing model preferences / session ids isn't world-readable on a
153
+ * shared host.
154
+ *
155
+ * Directory `fsync` is wrapped in a soft try/catch: on Windows opening a
156
+ * directory for read isn't supported and would throw. Our deployment
157
+ * target is Linux/Mac (plan §17.4 «Windows: not our case»), so logging
158
+ * and continuing is the right trade.
159
+ */
160
+ async function writeFileAtomic(finalPath, content, options = {}) {
161
+ const mode = options.mode ?? 0o600;
162
+ const dir = path.dirname(finalPath);
163
+ const tmp = path.join(dir, `.${path.basename(finalPath)}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
164
+ // 1. write + fsync the tmp file
165
+ const fh = await fs_1.promises.open(tmp, 'w', mode);
166
+ try {
167
+ await fh.writeFile(content);
168
+ await fh.sync();
169
+ }
170
+ finally {
171
+ await fh.close();
172
+ }
173
+ // 2. atomic rename
174
+ try {
175
+ await fs_1.promises.rename(tmp, finalPath);
176
+ }
177
+ catch (e) {
178
+ // Try to clean up the tmp if rename fails so we don't litter the dir.
179
+ await fs_1.promises.unlink(tmp).catch(() => { });
180
+ throw e;
181
+ }
182
+ // 3. fsync the parent directory so the rename hits disk
183
+ try {
184
+ const dh = await fs_1.promises.open(dir, 'r');
185
+ try {
186
+ await dh.sync();
187
+ }
188
+ finally {
189
+ await dh.close();
190
+ }
191
+ }
192
+ catch (e) {
193
+ // EISDIR / ENOTSUP on Windows, AIX etc. We document Linux/Mac so this is benign.
194
+ const code = e.code;
195
+ if (code !== 'EISDIR' && code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EINVAL') {
196
+ console.warn(`[state] parent dir fsync failed (${code}):`, e);
197
+ }
198
+ }
199
+ }
200
+ /**
201
+ * @description Try to load the state file. On a successful parse return the
202
+ * structured state. On parse failure archive the broken file to
203
+ * `state.json.corrupted-<iso>` and return `null` so the caller can start fresh.
204
+ *
205
+ * Three cases the caller cares about:
206
+ *
207
+ * 1. File doesn't exist → `null`, no archive. Fresh install.
208
+ * 2. File exists, parses → state object.
209
+ * 3. File exists, parses fails → archived, `null` returned.
210
+ * We also handle EPERM / EACCES on read here for completeness — same
211
+ * treatment: archive (if possible) and start fresh.
212
+ *
213
+ * Exported for unit tests (plan §11 Этап 7, R6).
214
+ */
215
+ async function loadStateFile(filePath) {
216
+ let raw;
217
+ try {
218
+ raw = await fs_1.promises.readFile(filePath, 'utf-8');
219
+ }
220
+ catch (e) {
221
+ const code = e.code;
222
+ if (code === 'ENOENT')
223
+ return { ok: false, reason: 'missing' };
224
+ // Unreadable (perms, disk error) — treat like corruption so the bot can boot.
225
+ return {
226
+ ok: false,
227
+ reason: 'corrupted',
228
+ archivedTo: null,
229
+ error: `read failed (${code}): ${e.message}`,
230
+ };
231
+ }
232
+ try {
233
+ const parsed = JSON.parse(raw);
234
+ // Light shape validation — full migrations would land here on a version bump.
235
+ if (typeof parsed === 'object' && parsed !== null &&
236
+ typeof parsed.version === 'number' &&
237
+ parsed.bindings && typeof parsed.bindings === 'object' &&
238
+ parsed.agents && typeof parsed.agents === 'object' &&
239
+ parsed.messages && typeof parsed.messages === 'object') {
240
+ return { ok: true, state: parsed };
241
+ }
242
+ throw new Error('shape mismatch');
243
+ }
244
+ catch (e) {
245
+ const archivedTo = await archiveCorruptedFile(filePath);
246
+ return {
247
+ ok: false,
248
+ reason: 'corrupted',
249
+ archivedTo,
250
+ error: e.message,
251
+ };
252
+ }
253
+ }
254
+ /**
255
+ * @description Rename a corrupted state file out of the way so the bot
256
+ * can boot with a fresh state without losing forensic evidence.
257
+ *
258
+ * Returns the archive path on success, `null` if archival itself failed
259
+ * (in which case we'll log and the caller proceeds with fresh state anyway).
260
+ */
261
+ async function archiveCorruptedFile(filePath) {
262
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
263
+ const archive = `${filePath}.corrupted-${ts}`;
264
+ try {
265
+ await fs_1.promises.rename(filePath, archive);
266
+ return archive;
267
+ }
268
+ catch (e) {
269
+ console.error(`[state] failed to archive corrupted file ${filePath}:`, e);
270
+ return null;
271
+ }
272
+ }
273
+ /**
274
+ * @description Migrate the legacy single-folder bot's message-id file.
275
+ *
276
+ * Old layout: `~/.telegram-bot-messages.json` keyed by raw user id.
277
+ * The 2.0 release intentionally doesn't try to merge those ids into the
278
+ * new `SessionKey`-keyed schema — the routing model changed too much for
279
+ * a clean mapping (plan §9). We just rename the file so it's preserved
280
+ * for the user's records and so it stops being read on every boot.
281
+ *
282
+ * Returns the archive path if migration happened, `null` otherwise.
283
+ */
284
+ async function migrateLegacyMessageIdsFile() {
285
+ const legacy = path.join(os.homedir(), '.telegram-bot-messages.json');
286
+ try {
287
+ await fs_1.promises.access(legacy);
288
+ }
289
+ catch {
290
+ return null;
291
+ }
292
+ const backup = `${legacy}.bak`;
293
+ try {
294
+ await fs_1.promises.rename(legacy, backup);
295
+ return backup;
296
+ }
297
+ catch (e) {
298
+ console.warn(`[state] failed to archive legacy ${legacy}:`, e);
299
+ return null;
300
+ }
301
+ }
302
+ /**
303
+ * @description Stateful, async-safe store for `state.json`.
304
+ *
305
+ * Construction is cheap (no I/O). Call `init()` once at boot before any
306
+ * setters fire; init loads or initialises the file, performs the legacy
307
+ * migration, and resolves. Setters return promises so callers can await
308
+ * the resulting persisted state when correctness matters more than
309
+ * throughput; non-critical writes are debounced.
310
+ */
311
+ class StateStore {
312
+ dataDir;
313
+ statePath;
314
+ saveDebounceMs;
315
+ state = emptyState();
316
+ /** True if the previous on-disk state file was unreadable / corrupt. */
317
+ corruptedOnLoad = false;
318
+ /** Archive path if the previous on-disk state was corrupted. */
319
+ corruptedArchivePath = null;
320
+ /** Backup path if the legacy file was migrated. */
321
+ legacyMigrationPath = null;
322
+ saveTimer = null;
323
+ /** Tail of the chained writes so two flushes don't try to rename simultaneously. */
324
+ writeChain = Promise.resolve();
325
+ /**
326
+ * Last compact-on-idle activity/turn stamp each thread actually asked to
327
+ * PERSIST, used to apply {@link compactIdleTrackingPersistStepMs}. In-memory
328
+ * only and deliberately NOT written to disk — it is bookkeeping ABOUT the
329
+ * bookkeeping, and after a restart the first stamp simply schedules one save.
330
+ */
331
+ compactIdleTrackingSavedAt = new Map();
332
+ keyLock = new KeyLock();
333
+ constructor(dataDir, options = {}) {
334
+ this.dataDir = dataDir;
335
+ this.statePath = path.join(dataDir, 'state.json');
336
+ this.saveDebounceMs = options.saveDebounceMs ?? DEFAULT_SAVE_DEBOUNCE_MS;
337
+ }
338
+ /**
339
+ * @description One-shot boot. Creates `dataDir` if missing, performs
340
+ * legacy migration, loads the existing state file (or starts fresh on
341
+ * corruption).
342
+ */
343
+ async init() {
344
+ await fs_1.promises.mkdir(this.dataDir, { recursive: true, mode: 0o700 });
345
+ // `mkdir`'s mode applies only when the dir is CREATED — an existing deploy
346
+ // (or a dir created earlier in this boot by the console tap / trace writer)
347
+ // keeps its old bits. Heal to owner-only: DATA_DIR holds state.json, traces
348
+ // and console logs that quote prompts/session ids. Best-effort — an exotic
349
+ // filesystem may refuse chmod, which must not block boot.
350
+ try {
351
+ await fs_1.promises.chmod(this.dataDir, 0o700);
352
+ }
353
+ catch (e) {
354
+ console.warn(`[state] could not chmod DATA_DIR to owner-only:`, e instanceof Error ? e.message : e);
355
+ }
356
+ this.legacyMigrationPath = await migrateLegacyMessageIdsFile();
357
+ const loaded = await loadStateFile(this.statePath);
358
+ if (loaded.ok) {
359
+ this.state = loaded.state;
360
+ // Top up missing fields if loaded from an older v1 file.
361
+ this.state.bindings ??= {};
362
+ this.state.agents ??= {};
363
+ this.state.messages ??= {};
364
+ }
365
+ else if (loaded.reason === 'missing') {
366
+ this.state = emptyState();
367
+ // No save: nothing yet to persist. First setter will trigger a debounce.
368
+ }
369
+ else {
370
+ this.corruptedOnLoad = true;
371
+ this.corruptedArchivePath = loaded.archivedTo;
372
+ console.error(`[state] previous state.json was corrupted (${loaded.error}); ` +
373
+ `archived to ${loaded.archivedTo ?? '(archive failed)'}, starting fresh`);
374
+ this.state = emptyState();
375
+ await this.flush();
376
+ }
377
+ }
378
+ /** Path of the live state file (for logging / docs / smoke-tests). */
379
+ get stateFilePath() {
380
+ return this.statePath;
381
+ }
382
+ /** True iff the previous boot's state file was unreadable on this start. */
383
+ wasCorruptedOnLoad() {
384
+ return this.corruptedOnLoad;
385
+ }
386
+ /** Where the previous corrupted file was moved, if archival succeeded. */
387
+ getCorruptedArchivePath() {
388
+ return this.corruptedArchivePath;
389
+ }
390
+ /** Where the legacy `~/.telegram-bot-messages.json` was archived, if it existed. */
391
+ getLegacyMigrationPath() {
392
+ return this.legacyMigrationPath;
393
+ }
394
+ // ── locking ──
395
+ /**
396
+ * @description Run `fn` while holding the per-key lock for `key`. Concurrent
397
+ * calls for the SAME key are serialised; calls for different keys run in
398
+ * parallel. Failure in one holder does NOT propagate to followers (the lock
399
+ * is for serialisation only; error handling is each caller's job).
400
+ */
401
+ withLock(key, fn) {
402
+ return this.keyLock.withLock((0, sessionKey_1.keyToString)(key), fn);
403
+ }
404
+ // ── bindings ──
405
+ getBinding(key) {
406
+ return this.state.bindings[(0, sessionKey_1.keyToString)(key)] ?? null;
407
+ }
408
+ async setBinding(key, subdir, options = {}) {
409
+ const k = (0, sessionKey_1.keyToString)(key);
410
+ await this.withLock(key, async () => {
411
+ const existing = this.state.bindings[k];
412
+ // Audit S20 / #44: previous code path used `existing?.closed ? …`,
413
+ // which falsy-collapsed an explicit `closed: false` and dropped
414
+ // the field entirely. Now we carry `closed` through verbatim,
415
+ // letting `false` and `true` round-trip independently.
416
+ const next = {
417
+ subdir,
418
+ createdAt: existing?.createdAt ?? new Date().toISOString(),
419
+ };
420
+ if (options.closed !== undefined) {
421
+ next.closed = options.closed;
422
+ }
423
+ else if (existing?.closed !== undefined) {
424
+ next.closed = existing.closed;
425
+ }
426
+ if (existing?.pinnedStatusMessageId !== undefined) {
427
+ next.pinnedStatusMessageId = existing.pinnedStatusMessageId;
428
+ }
429
+ // Carry the known topic name through a re-bind. A caller that learned
430
+ // the name (e.g. `/new`, deferred pending-name copy) passes it
431
+ // explicitly; otherwise we keep whatever was already stored.
432
+ if (options.topicName !== undefined) {
433
+ next.topicName = options.topicName;
434
+ }
435
+ else if (existing?.topicName !== undefined) {
436
+ next.topicName = existing.topicName;
437
+ }
438
+ this.state.bindings[k] = next;
439
+ this.scheduleSave();
440
+ });
441
+ }
442
+ /**
443
+ * @description Persist the forum-topic display name for a thread. Used by
444
+ * `forum_topic_edited` (rename) when a binding already exists. No-op (no
445
+ * save) when the binding is absent or the name is unchanged — symmetric to
446
+ * {@link setBindingPinnedStatusText}.
447
+ */
448
+ async setBindingTopicName(key, topicName) {
449
+ const k = (0, sessionKey_1.keyToString)(key);
450
+ await this.withLock(key, async () => {
451
+ const existing = this.state.bindings[k];
452
+ if (!existing)
453
+ return;
454
+ if (existing.topicName === topicName)
455
+ return;
456
+ this.state.bindings[k] = { ...existing, topicName };
457
+ this.scheduleSave();
458
+ });
459
+ }
460
+ async setBindingClosed(key, closed) {
461
+ const k = (0, sessionKey_1.keyToString)(key);
462
+ await this.withLock(key, async () => {
463
+ const existing = this.state.bindings[k];
464
+ if (!existing)
465
+ return;
466
+ this.state.bindings[k] = { ...existing, closed };
467
+ this.scheduleSave();
468
+ });
469
+ }
470
+ /**
471
+ * @description Persist the pinned status banner's message id for a thread,
472
+ * or clear it (pass `null`). Skipped if the binding doesn't exist — we
473
+ * don't ever want a pinned-message row dangling without a parent binding.
474
+ *
475
+ * Caller is expected to actually pin / unpin in Telegram around this
476
+ * call; this method only updates the on-disk pointer. Plan §20.5.
477
+ */
478
+ async setBindingPinnedStatusMessageId(key, messageId) {
479
+ const k = (0, sessionKey_1.keyToString)(key);
480
+ await this.withLock(key, async () => {
481
+ const existing = this.state.bindings[k];
482
+ if (!existing)
483
+ return;
484
+ if (messageId === null) {
485
+ if (existing.pinnedStatusMessageId === undefined)
486
+ return;
487
+ const { pinnedStatusMessageId: _drop, ...rest } = existing;
488
+ this.state.bindings[k] = rest;
489
+ }
490
+ else {
491
+ if (existing.pinnedStatusMessageId === messageId)
492
+ return;
493
+ this.state.bindings[k] = { ...existing, pinnedStatusMessageId: messageId };
494
+ }
495
+ this.scheduleSave();
496
+ });
497
+ }
498
+ /**
499
+ * @description Persist the last banner text sent/edited for a thread, or
500
+ * clear it (pass `null`). Mirrors {@link setBindingPinnedStatusMessageId}:
501
+ * skipped if the binding doesn't exist, and a no-op (no save) when the value
502
+ * is unchanged. Read back at boot to seed `pinnedStatusTextCache` so the
503
+ * startup refresh wave skips identical-banner edits (B8).
504
+ */
505
+ async setBindingPinnedStatusText(key, text) {
506
+ const k = (0, sessionKey_1.keyToString)(key);
507
+ await this.withLock(key, async () => {
508
+ const existing = this.state.bindings[k];
509
+ if (!existing)
510
+ return;
511
+ if (text === null) {
512
+ if (existing.pinnedStatusText === undefined)
513
+ return;
514
+ const { pinnedStatusText: _drop, ...rest } = existing;
515
+ this.state.bindings[k] = rest;
516
+ }
517
+ else {
518
+ if (existing.pinnedStatusText === text)
519
+ return;
520
+ this.state.bindings[k] = { ...existing, pinnedStatusText: text };
521
+ }
522
+ this.scheduleSave();
523
+ });
524
+ }
525
+ async removeBinding(key) {
526
+ const k = (0, sessionKey_1.keyToString)(key);
527
+ await this.withLock(key, async () => {
528
+ delete this.state.bindings[k];
529
+ delete this.state.agents[k];
530
+ delete this.state.messages[k];
531
+ // The thread is gone (unbind / deleted topic) → so is anything a boot
532
+ // recovery could resume for it, and the record of its pinned answer.
533
+ this.dropLimitEpisodeRecovered(k);
534
+ this.dropOptionalMapEntry('answerPins', k);
535
+ this.scheduleSave();
536
+ });
537
+ }
538
+ listBindings() {
539
+ const out = [];
540
+ for (const [keyStr, data] of Object.entries(this.state.bindings)) {
541
+ const key = (0, sessionKey_1.tryKeyFromString)(keyStr);
542
+ if (key)
543
+ out.push({ key, data });
544
+ }
545
+ return out;
546
+ }
547
+ /**
548
+ * @description Find every thread currently bound to a given subdir.
549
+ * Plan §10.6 names this for `/bind` UX warning «📁 уже работают треды: ...»
550
+ * — one folder may be reached from several threads (D7).
551
+ */
552
+ listKeysForSubdir(subdir) {
553
+ const out = [];
554
+ for (const [keyStr, data] of Object.entries(this.state.bindings)) {
555
+ if (data.subdir === subdir) {
556
+ const key = (0, sessionKey_1.tryKeyFromString)(keyStr);
557
+ if (key)
558
+ out.push(key);
559
+ }
560
+ }
561
+ return out;
562
+ }
563
+ // ── agents ──
564
+ getAgent(key) {
565
+ return this.state.agents[(0, sessionKey_1.keyToString)(key)] ?? null;
566
+ }
567
+ /**
568
+ * @description Upsert agent state for a thread. `name` is required (we
569
+ * don't keep an agent record without a backend choice); the rest of the
570
+ * fields are patched onto whatever exists.
571
+ */
572
+ async setAgent(key, data) {
573
+ const k = (0, sessionKey_1.keyToString)(key);
574
+ await this.withLock(key, async () => {
575
+ const existing = this.state.agents[k];
576
+ this.state.agents[k] = { ...existing, ...data };
577
+ this.scheduleSave();
578
+ });
579
+ }
580
+ async removeAgent(key) {
581
+ const k = (0, sessionKey_1.keyToString)(key);
582
+ await this.withLock(key, async () => {
583
+ delete this.state.agents[k];
584
+ this.scheduleSave();
585
+ });
586
+ }
587
+ getClaudeSessionId(key) {
588
+ return this.state.agents[(0, sessionKey_1.keyToString)(key)]?.claudeSessionId ?? null;
589
+ }
590
+ /**
591
+ * @description Persist the Claude `--session-id` UUID for `key`.
592
+ *
593
+ * If the thread already has an agent record, only the `claudeSessionId`
594
+ * field is patched — we keep whatever `name` was previously chosen so a
595
+ * thread currently set to `opencode` doesn't get silently flipped to
596
+ * `claude` just because we recorded a UUID. The bot picks the adapter
597
+ * via {@link setAgent} or `setThreadAdapter` — those are the right
598
+ * places to change `name`.
599
+ */
600
+ async setClaudeSessionId(key, uuid) {
601
+ const k = (0, sessionKey_1.keyToString)(key);
602
+ await this.withLock(key, async () => {
603
+ const existing = this.state.agents[k];
604
+ this.state.agents[k] = existing
605
+ ? { ...existing, claudeSessionId: uuid }
606
+ : { name: 'claude', claudeSessionId: uuid };
607
+ this.scheduleSave();
608
+ });
609
+ }
610
+ getOpenCodeSessionId(key) {
611
+ return this.state.agents[(0, sessionKey_1.keyToString)(key)]?.opencodeSessionId ?? null;
612
+ }
613
+ /** Symmetric to {@link setClaudeSessionId} — does not flip `agent.name`. */
614
+ async setOpenCodeSessionId(key, id) {
615
+ const k = (0, sessionKey_1.keyToString)(key);
616
+ await this.withLock(key, async () => {
617
+ const existing = this.state.agents[k];
618
+ this.state.agents[k] = existing
619
+ ? { ...existing, opencodeSessionId: id }
620
+ : { name: 'opencode', opencodeSessionId: id };
621
+ this.scheduleSave();
622
+ });
623
+ }
624
+ /**
625
+ * @description Advance the per-thread {@link SeenWatermark} (set at each turn
626
+ * end by the adapters via the injected writer). Merges onto the EXISTING agent
627
+ * row only — never flips `agent.name` (symmetric to
628
+ * {@link setClaudeSessionId} / {@link setOpenCodeSessionId}) and, unlike them,
629
+ * never CREATES a row: a watermark is meaningless without a live agent session
630
+ * (which always recorded its row first), so a write for an unknown thread is a
631
+ * no-op, not a dangling agent row.
632
+ */
633
+ async setSeenWatermark(key, watermark) {
634
+ const k = (0, sessionKey_1.keyToString)(key);
635
+ await this.withLock(key, async () => {
636
+ const existing = this.state.agents[k];
637
+ if (!existing)
638
+ return;
639
+ this.state.agents[k] = { ...existing, seenWatermark: watermark };
640
+ this.scheduleSave();
641
+ });
642
+ }
643
+ /**
644
+ * @description Persist the json-stream stdout tail offset (advanced by the
645
+ * adapter's tail poller through the injected writer, sealed by the shutdown
646
+ * `flush()`). Merge-only like {@link setSeenWatermark}: never flips
647
+ * `agent.name` and never creates a row — an offset is meaningless without
648
+ * the agent row its session recorded first.
649
+ */
650
+ async setJsonStreamTail(key, tail) {
651
+ const k = (0, sessionKey_1.keyToString)(key);
652
+ await this.withLock(key, async () => {
653
+ const existing = this.state.agents[k];
654
+ if (!existing)
655
+ return;
656
+ this.state.agents[k] = { ...existing, jsonStreamTail: tail };
657
+ this.scheduleSave();
658
+ });
659
+ }
660
+ /**
661
+ * @description Persist the session-start timestamp (a local-offset ISO string;
662
+ * see {@link AgentData.startedAt}). Merge-only like {@link setSeenWatermark}:
663
+ * never flips `agent.name` and never CREATES a row — the caller records the
664
+ * agent row (via `setAgent` / `persistAdapterSessionIds`) first, so a write
665
+ * for an unknown thread is a no-op rather than a dangling agent row.
666
+ */
667
+ async setAgentStartedAt(key, startedAt) {
668
+ const k = (0, sessionKey_1.keyToString)(key);
669
+ await this.withLock(key, async () => {
670
+ const existing = this.state.agents[k];
671
+ if (!existing)
672
+ return;
673
+ this.state.agents[k] = { ...existing, startedAt };
674
+ this.scheduleSave();
675
+ });
676
+ }
677
+ /** Persist the tool digest a json-stream process was started with (see {@link AgentData.mcpToolDigest}); merge-only. */
678
+ async setAgentMcpToolDigest(key, mcpToolDigest) {
679
+ const k = (0, sessionKey_1.keyToString)(key);
680
+ await this.withLock(key, async () => {
681
+ const existing = this.state.agents[k];
682
+ if (!existing)
683
+ return;
684
+ this.state.agents[k] = { ...existing, mcpToolDigest };
685
+ this.scheduleSave();
686
+ });
687
+ }
688
+ /**
689
+ * @description Release both persisted session ids (and the json-stream tail
690
+ * offset, which is meaningless without its session; plus the session-start
691
+ * timestamp, which belongs to the session going away) for `key` while keeping
692
+ * `name` / `model`. Called on explicit user stop (`/quit`, `/quit-all`,
693
+ * `/new`, `/unbind`) so a later bot restart won't auto-reattach a session
694
+ * the user deliberately ended. No-op when the thread has no agent record.
695
+ */
696
+ async clearAgentSessionIds(key) {
697
+ const k = (0, sessionKey_1.keyToString)(key);
698
+ await this.withLock(key, async () => {
699
+ // A released session can never be the one a boot recovery resumes (it checks
700
+ // `checkIsActive` + the persisted session id), so its handled-limit-episode
701
+ // marker becomes a dead key — drop it with the ids instead of letting
702
+ // `state.json` accumulate one per retired session.
703
+ const droppedMarker = this.dropLimitEpisodeRecovered(k);
704
+ const existing = this.state.agents[k];
705
+ if (!existing) {
706
+ if (droppedMarker)
707
+ this.scheduleSave();
708
+ return;
709
+ }
710
+ const { claudeSessionId, opencodeSessionId, jsonStreamTail, startedAt, mcpToolDigest, ...rest } = existing;
711
+ this.state.agents[k] = rest;
712
+ this.scheduleSave();
713
+ });
714
+ }
715
+ // ── messages (`/clear` support) ──
716
+ getMessageIds(key) {
717
+ return this.state.messages[(0, sessionKey_1.keyToString)(key)]?.slice() ?? [];
718
+ }
719
+ /** Append IDs to the bounded in-memory ring while the caller holds the key lock. */
720
+ appendMessageIds(keyStr, messageIds) {
721
+ const list = (this.state.messages[keyStr] ??= []);
722
+ list.push(...messageIds);
723
+ if (list.length > MESSAGE_ID_RING_CAP) {
724
+ this.state.messages[keyStr] = list.slice(-MESSAGE_ID_RING_CAP);
725
+ }
726
+ }
727
+ /**
728
+ * @description Append a message id to the per-thread tracking list and
729
+ * trim to the most recent `MESSAGE_ID_RING_CAP`. Anything older falls off
730
+ * the end — Telegram won't let `deleteMessages` touch messages older than
731
+ * 48h anyway (plan §11 Этап 3, U2).
732
+ */
733
+ async pushMessageId(key, msgId) {
734
+ const k = (0, sessionKey_1.keyToString)(key);
735
+ await this.withLock(key, async () => {
736
+ this.appendMessageIds(k, [msgId]);
737
+ this.scheduleSave();
738
+ });
739
+ }
740
+ /** Atomically append and durably persist one Telegram response's message IDs. */
741
+ async pushMessageIds(key, messageIds) {
742
+ if (messageIds.length === 0)
743
+ return;
744
+ const k = (0, sessionKey_1.keyToString)(key);
745
+ await this.withLock(key, async () => {
746
+ this.appendMessageIds(k, messageIds);
747
+ await this.flush();
748
+ });
749
+ }
750
+ /** Atomically hand tracked IDs to `/clear_messages` while later pushes remain tracked. */
751
+ async takeMessageIds(key, additionalIds = []) {
752
+ const k = (0, sessionKey_1.keyToString)(key);
753
+ return this.withLock(key, async () => {
754
+ const messageIds = [...(this.state.messages[k] ?? []), ...additionalIds];
755
+ if (this.state.messages[k] !== undefined) {
756
+ delete this.state.messages[k];
757
+ this.scheduleSave();
758
+ }
759
+ return messageIds;
760
+ });
761
+ }
762
+ // ── heartbeat (hot-reload vs cold-start detection) ──
763
+ /**
764
+ * @description Stamp `lastHeartbeatAt = now` (ms) and schedule a debounced
765
+ * save. Called by the bot on a ~10s interval while running so the next
766
+ * boot can tell a hot reload (gap < threshold) from a real cold start
767
+ * (gap large, or no stamp at all on a fresh install).
768
+ *
769
+ * Cheap by design: a one-field mutation that piggy-backs on the existing
770
+ * debounced save loop. We don't `flush()` here — losing the last 10s
771
+ * heartbeat on a hard crash just biases the next boot toward
772
+ * "cold start", which is the conservative direction.
773
+ */
774
+ touchHeartbeat(now = Date.now()) {
775
+ this.state.lastHeartbeatAt = now;
776
+ this.scheduleSave();
777
+ }
778
+ /**
779
+ * @description Time since the last persisted heartbeat in ms, or `null`
780
+ * if the state file has no heartbeat stamp (fresh install, or pre-feature
781
+ * state file). `null` should be treated as "unknown → assume cold start".
782
+ *
783
+ * Read at boot to decide hot-vs-cold-start, ideally BEFORE the first
784
+ * `touchHeartbeat()` call or `state.flush()` (otherwise the value
785
+ * compares against ourselves and always looks like a hot reload).
786
+ */
787
+ getDowntimeMs(now = Date.now()) {
788
+ const last = this.state.lastHeartbeatAt;
789
+ if (typeof last !== 'number' || !Number.isFinite(last))
790
+ return null;
791
+ return Math.max(0, now - last);
792
+ }
793
+ // ── paired group id (auto-pairing) ──
794
+ /** The auto-paired forum supergroup id, or `null` if never paired. */
795
+ getPairedGroupId() {
796
+ return this.state.pairedGroupId ?? null;
797
+ }
798
+ /**
799
+ * @description Persist the auto-paired group id and flush immediately.
800
+ *
801
+ * Unlike per-thread mutations this is a rare, one-shot critical write:
802
+ * if the process dies right after pairing we must not lose the id and
803
+ * fall back into pairing mode on the next boot. So we `flush()` rather
804
+ * than debounce.
805
+ */
806
+ async setPairedGroupId(groupId) {
807
+ this.state.pairedGroupId = groupId;
808
+ await this.flush();
809
+ }
810
+ // ── output-trace toggle (`/trace`) ──
811
+ /**
812
+ * @description Current persisted trace toggle. `threadKeys` are the
813
+ * {@link SessionKey} strings opted into tracing; `allThreads` traces
814
+ * everything. `allThreads` defaults to TRUE on a fresh or pre-feature state
815
+ * file (always-on observability — only an explicit `/trace off all` turns it
816
+ * off, stored as a durable `false`); `threadKeys` defaults empty. Read at boot
817
+ * to seed `outputTrace.ts`.
818
+ */
819
+ getTraceConfig() {
820
+ return {
821
+ allThreads: this.state.traceAllThreads ?? true,
822
+ threadKeys: this.state.tracedThreads?.slice() ?? [],
823
+ };
824
+ }
825
+ /**
826
+ * @description Persist the trace toggle. Not crash-critical (a debug aid), so
827
+ * it rides the debounced save loop rather than an immediate `flush()`. The
828
+ * `tracedThreads` array is normalised to a deduped, sorted form so the
829
+ * on-disk shape is stable across toggles; an empty list is dropped.
830
+ *
831
+ * `traceAllThreads` is stored EXPLICITLY as a boolean (including `false`):
832
+ * the all-threads default is now ON ({@link getTraceConfig}), so a `/trace
833
+ * off all` must be DURABLE and distinguishable from "never set" (which reads
834
+ * back as the ON default). Dropping it on `false` would silently re-enable
835
+ * tracing on the next boot.
836
+ */
837
+ async setTraceConfig(config) {
838
+ const uniqueKeys = [...new Set(config.threadKeys)].sort();
839
+ if (uniqueKeys.length > 0)
840
+ this.state.tracedThreads = uniqueKeys;
841
+ else
842
+ delete this.state.tracedThreads;
843
+ this.state.traceAllThreads = config.allThreads;
844
+ this.scheduleSave();
845
+ }
846
+ // ── per-chat locale (`/language`) ──
847
+ getChatLocaleOverride(chatId) {
848
+ return this.state.chatLocaleOverrides?.[chatId.toString()] ?? null;
849
+ }
850
+ getChatTelegramLocale(chatId) {
851
+ return this.state.chatTelegramLocales?.[chatId.toString()] ?? null;
852
+ }
853
+ async setChatLocaleOverride(chatId, locale) {
854
+ const chatIdKey = chatId.toString();
855
+ if (locale === null) {
856
+ if (!this.state.chatLocaleOverrides?.[chatIdKey])
857
+ return;
858
+ delete this.state.chatLocaleOverrides[chatIdKey];
859
+ if (Object.keys(this.state.chatLocaleOverrides).length === 0) {
860
+ delete this.state.chatLocaleOverrides;
861
+ }
862
+ this.scheduleSave();
863
+ return;
864
+ }
865
+ if (this.state.chatLocaleOverrides?.[chatIdKey] === locale)
866
+ return;
867
+ (this.state.chatLocaleOverrides ??= {})[chatIdKey] = locale;
868
+ this.scheduleSave();
869
+ }
870
+ async setChatTelegramLocale(chatId, locale) {
871
+ const chatIdKey = chatId.toString();
872
+ if (this.state.chatTelegramLocales?.[chatIdKey] === locale)
873
+ return;
874
+ (this.state.chatTelegramLocales ??= {})[chatIdKey] = locale;
875
+ this.scheduleSave();
876
+ }
877
+ // ── per-thread prompt-timestamp toggle (`/timestamps`) ──
878
+ /**
879
+ * @description Whether `/timestamps` is ON for `key` (default OFF). When ON,
880
+ * `forwardPromptToAgent` prepends the send-time as a local-offset ISO top
881
+ * line to every forwarded prompt.
882
+ */
883
+ checkIsTimestampsEnabled(key) {
884
+ return this.state.timestampThreads?.includes((0, sessionKey_1.keyToString)(key)) ?? false;
885
+ }
886
+ /**
887
+ * @description Persist the per-thread `/timestamps` toggle. Mirrors
888
+ * {@link setTraceConfig}'s shape discipline: the list is deduped + sorted so
889
+ * the on-disk form is stable, and an empty list is dropped (an all-defaults
890
+ * install leaves no trace in `state.json`). Not crash-critical, so it rides
891
+ * the debounced save loop.
892
+ */
893
+ async setTimestampsEnabled(key, isEnabled) {
894
+ const keyStr = (0, sessionKey_1.keyToString)(key);
895
+ const current = new Set(this.state.timestampThreads ?? []);
896
+ if (isEnabled)
897
+ current.add(keyStr);
898
+ else
899
+ current.delete(keyStr);
900
+ const uniqueKeys = [...current].sort();
901
+ if (uniqueKeys.length > 0)
902
+ this.state.timestampThreads = uniqueKeys;
903
+ else
904
+ delete this.state.timestampThreads;
905
+ this.scheduleSave();
906
+ }
907
+ // ── hidden `/model` providers (global, not per-thread) ──
908
+ /**
909
+ * @description Providers currently hidden from the `/model` picker, in the
910
+ * stable sorted on-disk order. Empty when nothing is hidden (the default).
911
+ */
912
+ getHiddenModelProviders() {
913
+ return this.state.hiddenModelProviders?.slice() ?? [];
914
+ }
915
+ /**
916
+ * @description Hide/show one provider in the `/model` picker. Mirrors
917
+ * {@link setTimestampsEnabled}'s shape discipline: deduped + sorted so the
918
+ * on-disk form is stable across toggles, and an empty list is dropped (a
919
+ * default install leaves no trace in `state.json`). A picker preference is
920
+ * not crash-critical, so it rides the debounced save loop.
921
+ */
922
+ async setModelProviderHidden(provider, isHidden) {
923
+ const current = new Set(this.state.hiddenModelProviders ?? []);
924
+ if (isHidden)
925
+ current.add(provider);
926
+ else
927
+ current.delete(provider);
928
+ const uniqueProviders = [...current].sort();
929
+ if (uniqueProviders.length > 0)
930
+ this.state.hiddenModelProviders = uniqueProviders;
931
+ else
932
+ delete this.state.hiddenModelProviders;
933
+ this.scheduleSave();
934
+ }
935
+ // ── compact-on-idle toggle (`/compact_on_idle`) ──
936
+ /**
937
+ * @description The instance-wide compact-on-idle default (driven from the
938
+ * General topic). ON when unset — same always-on default as
939
+ * {@link getTraceConfig}'s `allThreads`.
940
+ */
941
+ getCompactOnIdleGlobalDefault() {
942
+ return this.state.compactOnIdleEnabled ?? true;
943
+ }
944
+ /**
945
+ * @description The per-thread compact-on-idle override, or `undefined` when the
946
+ * thread follows the instance default. A present value (true OR false) wins.
947
+ */
948
+ getCompactOnIdleOverride(key) {
949
+ return this.state.compactOnIdleOverrides?.[(0, sessionKey_1.keyToString)(key)];
950
+ }
951
+ /**
952
+ * @description Whether compact-on-idle is effectively enabled for `key`: the
953
+ * per-thread override if set, else the instance default (OFF when unset).
954
+ */
955
+ checkIsCompactOnIdleEnabled(key) {
956
+ return (0, compactOnIdle_1.resolveCompactOnIdleEnabled)(this.state.compactOnIdleEnabled, this.getCompactOnIdleOverride(key));
957
+ }
958
+ /**
959
+ * @description Set the instance-wide compact-on-idle default (from General).
960
+ * Stored EXPLICITLY as a boolean (incl. `false`) so a «Disable» is durable and
961
+ * distinguishable from "never set" (which reads back as the ON default) —
962
+ * mirrors {@link setTraceConfig}'s `traceAllThreads` discipline. Debounced (a
963
+ * preference, not crash-critical).
964
+ */
965
+ async setCompactOnIdleGlobalDefault(enabled) {
966
+ if (this.state.compactOnIdleEnabled === enabled)
967
+ return;
968
+ this.state.compactOnIdleEnabled = enabled;
969
+ this.scheduleSave();
970
+ }
971
+ /**
972
+ * @description Set the per-thread compact-on-idle override (from a regular
973
+ * topic). Stored explicitly (a present true/false wins over the global
974
+ * default); the whole map is dropped once empty so an all-default instance
975
+ * leaves a clean `state.json`. Debounced.
976
+ */
977
+ async setCompactOnIdleOverride(key, enabled) {
978
+ const k = (0, sessionKey_1.keyToString)(key);
979
+ await this.withLock(key, async () => {
980
+ if (this.state.compactOnIdleOverrides?.[k] === enabled)
981
+ return;
982
+ (this.state.compactOnIdleOverrides ??= {})[k] = enabled;
983
+ this.scheduleSave();
984
+ });
985
+ }
986
+ // ── full-summary toggle (`/compact_summary`) ──
987
+ /**
988
+ * @description The instance-wide full-compaction-summary default (driven from the
989
+ * General topic). OFF when unset, unlike {@link getCompactOnIdleGlobalDefault}:
990
+ * a compaction ends in one short line unless the summary is turned on.
991
+ */
992
+ getCompactSummaryGlobalDefault() {
993
+ return this.state.compactSummaryEnabled ?? false;
994
+ }
995
+ /**
996
+ * @description The per-thread full-summary override, or `undefined` when the
997
+ * thread follows the instance default. A present value (true OR false) wins.
998
+ */
999
+ getCompactSummaryOverride(key) {
1000
+ return this.state.compactSummaryOverrides?.[(0, sessionKey_1.keyToString)(key)];
1001
+ }
1002
+ /**
1003
+ * @description Whether the full compaction summary is posted for `key`: the
1004
+ * per-thread override if set, else the instance default (ON when unset).
1005
+ */
1006
+ checkIsCompactSummaryEnabled(key) {
1007
+ return (0, compactOnIdle_1.resolveCompactSummaryEnabled)(this.state.compactSummaryEnabled, this.getCompactSummaryOverride(key));
1008
+ }
1009
+ /**
1010
+ * @description Set the instance-wide full-summary default (from General). Stored
1011
+ * EXPLICITLY as a boolean (incl. `false`) so a choice is durable and
1012
+ * distinguishable from "never set", which reads back as the OFF default. Debounced
1013
+ * (a preference, not crash-critical) — mirrors
1014
+ * {@link setCompactOnIdleGlobalDefault}.
1015
+ */
1016
+ async setCompactSummaryGlobalDefault(enabled) {
1017
+ if (this.state.compactSummaryEnabled === enabled)
1018
+ return;
1019
+ this.state.compactSummaryEnabled = enabled;
1020
+ this.scheduleSave();
1021
+ }
1022
+ /**
1023
+ * @description Set the per-thread full-summary override (from a regular topic).
1024
+ * Stored explicitly (a present true/false wins over the global default).
1025
+ * Debounced — mirrors {@link setCompactOnIdleOverride}.
1026
+ */
1027
+ async setCompactSummaryOverride(key, enabled) {
1028
+ const k = (0, sessionKey_1.keyToString)(key);
1029
+ await this.withLock(key, async () => {
1030
+ if (this.state.compactSummaryOverrides?.[k] === enabled)
1031
+ return;
1032
+ (this.state.compactSummaryOverrides ??= {})[k] = enabled;
1033
+ this.scheduleSave();
1034
+ });
1035
+ }
1036
+ /**
1037
+ * @description Whether `key`'s compact-on-idle user-latch is spent (D2): an
1038
+ * idle-compaction already fired this user-active period and no genuine USER
1039
+ * message has re-armed it since. Read by the idle watchdog's fire guard and by
1040
+ * the timer-arming path (a latched thread never re-arms — so a restart can't
1041
+ * re-fire). Default `false` (never latched).
1042
+ */
1043
+ checkIsCompactIdleLatched(key) {
1044
+ return this.state.compactIdleLatchedThreads?.includes((0, sessionKey_1.keyToString)(key)) ?? false;
1045
+ }
1046
+ /**
1047
+ * @description Set/clear `key`'s compact-on-idle user-latch (D2). Set on a
1048
+ * fire, cleared on a genuine USER message / fresh session start. Mirrors
1049
+ * {@link setTimestampsEnabled}'s shape discipline (deduped + sorted, dropped
1050
+ * when empty) and rides the debounced save loop — the persistence is only a
1051
+ * restart guard, so losing the last <=500ms is at worst one extra fire.
1052
+ */
1053
+ async setCompactIdleLatched(key, isLatched) {
1054
+ const keyStr = (0, sessionKey_1.keyToString)(key);
1055
+ const current = new Set(this.state.compactIdleLatchedThreads ?? []);
1056
+ if (isLatched)
1057
+ current.add(keyStr);
1058
+ else
1059
+ current.delete(keyStr);
1060
+ const uniqueKeys = [...current].sort();
1061
+ if (uniqueKeys.length > 0)
1062
+ this.state.compactIdleLatchedThreads = uniqueKeys;
1063
+ else
1064
+ delete this.state.compactIdleLatchedThreads;
1065
+ this.scheduleSave();
1066
+ }
1067
+ // ── compact-on-idle per-thread bookkeeping (the countdown's restart guard) ──
1068
+ /**
1069
+ * @description `key`'s persisted compact-on-idle instants, with every absent
1070
+ * field read back as `0`. `0` is the explicit "no history" value both readers
1071
+ * rely on: the arming path takes it as "use the full idle window" and the fire
1072
+ * guard's `lastTurnEndAt > lastCompactionAt` as "nothing to compress" — so a
1073
+ * pre-feature state file behaves exactly like an untracked thread.
1074
+ *
1075
+ * All zeros are ALSO returned whenever the entry does not belong to the thread's
1076
+ * CURRENT agent session (a different `sessionId`, or either id unknown): the
1077
+ * instants describe one session's context, so a session swap must reset the
1078
+ * marker, and deciding that here — rather than in a teardown handler — makes it
1079
+ * true regardless of which lifecycle events fired (a killed process emits none).
1080
+ * Unknown-means-zero is conservative in the right direction: at worst the topic
1081
+ * waits one more full idle window.
1082
+ */
1083
+ getCompactIdleTracking(key) {
1084
+ const k = (0, sessionKey_1.keyToString)(key);
1085
+ const entry = this.state.compactIdleTracking?.[k];
1086
+ const sessionId = this.getAgentSessionId(k);
1087
+ if (!entry || !sessionId || entry.sessionId !== sessionId) {
1088
+ return { lastActivityAt: 0, lastTurnEndAt: 0, lastCompactionAt: 0 };
1089
+ }
1090
+ return {
1091
+ lastActivityAt: entry.lastActivityAt ?? 0,
1092
+ lastTurnEndAt: entry.lastTurnEndAt ?? 0,
1093
+ lastCompactionAt: entry.lastCompactionAt ?? 0,
1094
+ };
1095
+ }
1096
+ /**
1097
+ * @description Stamp `key`'s last REAL activity — the instant the idle
1098
+ * countdown is measured from. Called on every agent output chunk, so the write
1099
+ * is COARSE: the in-memory value is always assigned (readers are exact), but a
1100
+ * save is scheduled only once the value has moved a full
1101
+ * {@link compactIdleTrackingPersistStepMs} past what was last persisted. The
1102
+ * assigned value also rides along for free on the next save the ~10s
1103
+ * {@link touchHeartbeat} loop schedules, so the coarse step costs nothing in
1104
+ * correctness — at worst the persisted stamp trails the live one by under a
1105
+ * minute, against a 55-minute threshold.
1106
+ */
1107
+ noteCompactIdleActivity(key, now = Date.now()) {
1108
+ this.stampCompactIdleTracking(key, 'lastActivityAt', now);
1109
+ }
1110
+ /**
1111
+ * @description Stamp that an agent turn produced output for `key` — the proof
1112
+ * there is something to compress (the fire guard compares this against
1113
+ * `lastCompactionAt`). Same per-chunk call frequency and therefore the same
1114
+ * coarse-save rule as {@link noteCompactIdleActivity}.
1115
+ */
1116
+ noteCompactIdleTurnEnd(key, now = Date.now()) {
1117
+ this.stampCompactIdleTracking(key, 'lastTurnEndAt', now);
1118
+ }
1119
+ /**
1120
+ * @description Stamp that `key` was just compacted (any trigger: manual
1121
+ * `/compact`, the F1 tool, an F2 idle fire), closing the fire guard until the
1122
+ * next turn produces output. Rare, so it always schedules a save — persisting it
1123
+ * is what stops a restart from re-compacting a session nothing has touched
1124
+ * since.
1125
+ */
1126
+ async setCompactIdleCompactedAt(key, now = Date.now()) {
1127
+ const k = (0, sessionKey_1.keyToString)(key);
1128
+ await this.withLock(key, async () => {
1129
+ const sessionId = this.getAgentSessionId(k);
1130
+ if (!sessionId)
1131
+ return; // nothing to bind the marker to — see `getAgentSessionId`
1132
+ const tracking = (this.state.compactIdleTracking ??= {});
1133
+ const existing = tracking[k];
1134
+ // A stamp under a DIFFERENT session starts the entry fresh: the previous
1135
+ // session's instants describe a context this one no longer has.
1136
+ const base = existing?.sessionId === sessionId ? existing : {};
1137
+ tracking[k] = { ...base, sessionId, lastCompactionAt: now };
1138
+ this.scheduleSave();
1139
+ });
1140
+ }
1141
+ /**
1142
+ * @description Drop `key`'s compact-on-idle bookkeeping (session teardown:
1143
+ * `/new`, `/quit`, unbind). Deliberately a full delete rather than a reset —
1144
+ * with no entry the next session start finds `lastActivityAt === 0` and gets
1145
+ * the FULL idle window, which is exactly the wanted behaviour for a fresh
1146
+ * session, so no special case is needed on the start path. The whole map is
1147
+ * dropped once empty so an idle bot leaves a clean `state.json`.
1148
+ */
1149
+ async clearCompactIdleTracking(key) {
1150
+ const k = (0, sessionKey_1.keyToString)(key);
1151
+ this.compactIdleTrackingSavedAt.delete(k);
1152
+ await this.withLock(key, async () => {
1153
+ if (!this.state.compactIdleTracking?.[k])
1154
+ return;
1155
+ delete this.state.compactIdleTracking[k];
1156
+ if (Object.keys(this.state.compactIdleTracking).length === 0) {
1157
+ delete this.state.compactIdleTracking;
1158
+ }
1159
+ this.scheduleSave();
1160
+ });
1161
+ }
1162
+ /**
1163
+ * Assign one high-frequency compact-on-idle stamp in memory and schedule a save
1164
+ * only past the coarse step (see {@link noteCompactIdleActivity}). Synchronous
1165
+ * (no key lock) on purpose: it runs on the output hot path, and a single-field
1166
+ * assignment cannot interleave with another write the way a read-modify-write
1167
+ * of a whole record can.
1168
+ */
1169
+ stampCompactIdleTracking(key, field, now) {
1170
+ const k = (0, sessionKey_1.keyToString)(key);
1171
+ const sessionId = this.getAgentSessionId(k);
1172
+ if (!sessionId)
1173
+ return; // nothing to bind the marker to — see `getAgentSessionId`
1174
+ const tracking = (this.state.compactIdleTracking ??= {});
1175
+ const existing = tracking[k];
1176
+ // A stamp under a DIFFERENT session REPLACES the entry rather than merging
1177
+ // into it — the old session's instants must not survive the swap.
1178
+ const isFreshSession = !existing || existing.sessionId !== sessionId;
1179
+ const entry = existing && !isFreshSession ? existing : { sessionId };
1180
+ tracking[k] = entry;
1181
+ entry[field] = now;
1182
+ // A fresh session's first stamp always persists, so the new binding reaches
1183
+ // disk instead of waiting out the coarse step behind a stale one.
1184
+ const savedAt = isFreshSession ? 0 : this.compactIdleTrackingSavedAt.get(k) ?? 0;
1185
+ if (now - savedAt < exports.compactIdleTrackingPersistStepMs)
1186
+ return;
1187
+ this.compactIdleTrackingSavedAt.set(k, now);
1188
+ this.scheduleSave();
1189
+ }
1190
+ /**
1191
+ * The thread's CURRENT agent session id — `claudeSessionId` else
1192
+ * `opencodeSessionId` from the persisted {@link AgentData} — or `undefined` when
1193
+ * the thread has neither. A raw `/terminal` shell has no session id and cannot be
1194
+ * compacted anyway, so "no id" means the compact-on-idle marker has nothing to
1195
+ * bind to: reads return zeros and stamps are skipped, keeping `state.json` clean.
1196
+ */
1197
+ getAgentSessionId(keyStr) {
1198
+ const agent = this.state.agents[keyStr];
1199
+ return agent?.claudeSessionId ?? agent?.opencodeSessionId;
1200
+ }
1201
+ // ── limit auto-continue toggle (`/auto_continue_limits`) ──
1202
+ /**
1203
+ * @description The instance-wide limit-auto-continue default (driven from the
1204
+ * General topic). ON when unset — the auto-resume was unconditional before the
1205
+ * toggle, so the default must preserve it.
1206
+ */
1207
+ getAutoContinueOnLimitGlobalDefault() {
1208
+ return this.state.autoContinueOnLimitEnabled ?? true;
1209
+ }
1210
+ /**
1211
+ * @description The per-thread limit-auto-continue override, or `undefined` when
1212
+ * the thread follows the instance default. A present value (true OR false) wins.
1213
+ */
1214
+ getAutoContinueOnLimitOverride(key) {
1215
+ return this.state.autoContinueOnLimitOverrides?.[(0, sessionKey_1.keyToString)(key)];
1216
+ }
1217
+ /**
1218
+ * @description Whether limit auto-continue is effectively enabled for `key`: the
1219
+ * per-thread override if set, else the instance default (ON when unset).
1220
+ */
1221
+ checkIsAutoContinueOnLimitEnabled(key) {
1222
+ return (0, autoContinueOnLimit_1.resolveAutoContinueOnLimitEnabled)(this.state.autoContinueOnLimitEnabled, this.getAutoContinueOnLimitOverride(key));
1223
+ }
1224
+ /**
1225
+ * @description Set the instance-wide limit-auto-continue default (from General).
1226
+ * Stored EXPLICITLY as a boolean (incl. `false`) so a «Disable» is durable and
1227
+ * distinguishable from "never set" (which reads back as the ON default) —
1228
+ * mirrors {@link setCompactOnIdleGlobalDefault}. Debounced (a preference, not
1229
+ * crash-critical).
1230
+ */
1231
+ async setAutoContinueOnLimitGlobalDefault(enabled) {
1232
+ if (this.state.autoContinueOnLimitEnabled === enabled)
1233
+ return;
1234
+ this.state.autoContinueOnLimitEnabled = enabled;
1235
+ this.scheduleSave();
1236
+ }
1237
+ /**
1238
+ * @description Set the per-thread limit-auto-continue override (from a regular
1239
+ * topic). Stored explicitly (a present true/false wins over the global
1240
+ * default); the map is created lazily on the first override, so an all-default
1241
+ * instance leaves a clean `state.json`. Debounced.
1242
+ */
1243
+ async setAutoContinueOnLimitOverride(key, enabled) {
1244
+ const k = (0, sessionKey_1.keyToString)(key);
1245
+ await this.withLock(key, async () => {
1246
+ if (this.state.autoContinueOnLimitOverrides?.[k] === enabled) {
1247
+ return;
1248
+ }
1249
+ (this.state.autoContinueOnLimitOverrides ??= {})[k] = enabled;
1250
+ this.scheduleSave();
1251
+ });
1252
+ }
1253
+ // ── instance-wide timezone (`/timezone`) ──
1254
+ /**
1255
+ * @description The stored operator timezone, or `null` when none is set (the
1256
+ * caller then falls back to the host zone — see `utils/timezone.ts`
1257
+ * `getEffectiveTimezone`). Deliberately NOT defaulted here: the store reports
1258
+ * what is on disk, the resolution rule lives in one place outside it.
1259
+ */
1260
+ getTimezone() {
1261
+ return this.state.timezone ?? null;
1262
+ }
1263
+ /**
1264
+ * @description Store the operator timezone, or drop the field on `null`
1265
+ * (reset to the host zone) so a default install leaves no trace in
1266
+ * `state.json` — same shape discipline as {@link setModelProviderHidden}.
1267
+ *
1268
+ * Flushed eagerly rather than riding the debounced save loop: a zone change
1269
+ * immediately recomputes every schedule's `nextRunAt`, and losing the zone
1270
+ * while keeping the recomputed fire times would leave the two disagreeing
1271
+ * after a crash.
1272
+ */
1273
+ async setTimezone(timezone) {
1274
+ if (timezone === null)
1275
+ delete this.state.timezone;
1276
+ else
1277
+ this.state.timezone = timezone;
1278
+ await this.flush();
1279
+ }
1280
+ // ── per-thread display preferences (`/thinking`, `/tool-results`, `/subagent`) ──
1281
+ /**
1282
+ * @description Fully-resolved display preferences for `key`: every field is
1283
+ * present because the locked default (`minimal` for all three) is applied
1284
+ * wherever the persisted record omits it. The SSE hot path reads this, so it
1285
+ * must never hand back an `undefined` field.
1286
+ *
1287
+ * Read-time normalization: a `state.json` written before the vocabulary was
1288
+ * unified may still hold legacy names (`detailed`/`brief`/`hide`/`compact`)
1289
+ * — those map onto the new vocabulary here, and an unrecognized value falls
1290
+ * back to the default, so old files keep working without a migration pass.
1291
+ */
1292
+ getDisplayPrefs(key) {
1293
+ const stored = this.state.displayPrefs?.[(0, sessionKey_1.keyToString)(key)];
1294
+ return {
1295
+ thinking: (0, displayVerbosity_1.normalizeDisplayVerbosityMode)(stored?.thinking) ?? displayVerbosity_1.defaultDisplayVerbosityMode,
1296
+ toolResults: (0, displayVerbosity_1.normalizeDisplayVerbosityMode)(stored?.toolResults) ?? displayVerbosity_1.defaultDisplayVerbosityMode,
1297
+ subagent: (0, displayVerbosity_1.normalizeDisplayVerbosityMode)(stored?.subagent) ?? displayVerbosity_1.defaultDisplayVerbosityMode,
1298
+ view: (0, topicView_1.parseTopicView)(stored?.view) ?? topicView_1.defaultTopicView,
1299
+ };
1300
+ }
1301
+ /**
1302
+ * @description Persist one display-preference field for `key`. Setting a
1303
+ * field to its locked default DELETES the override (and drops the whole
1304
+ * record / map once empty) so an all-defaults thread leaves a clean
1305
+ * `state.json` — same delete-when-default idiom as {@link setTraceConfig}.
1306
+ * Not crash-critical (a rendering preference), so it rides the debounced
1307
+ * save loop rather than an immediate `flush()`. Callers pass an
1308
+ * already-normalized value — legacy names never reach the store on the write
1309
+ * path. The `view` field (S6) rides the same record and the same idiom, with
1310
+ * its own locked default.
1311
+ */
1312
+ async setDisplayPref(key, field, value) {
1313
+ const k = (0, sessionKey_1.keyToString)(key);
1314
+ await this.withLock(key, async () => {
1315
+ const isDefault = value === (field === 'view' ? topicView_1.defaultTopicView : displayVerbosity_1.defaultDisplayVerbosityMode);
1316
+ const existing = this.state.displayPrefs?.[k];
1317
+ if (isDefault) {
1318
+ // Clear the override; drop the record (and the map) once empty so an
1319
+ // all-defaults thread leaves no trace in state.json.
1320
+ if (!existing || existing[field] === undefined)
1321
+ return;
1322
+ const { [field]: _drop, ...rest } = existing;
1323
+ if (Object.keys(rest).length === 0) {
1324
+ delete this.state.displayPrefs[k];
1325
+ if (Object.keys(this.state.displayPrefs).length === 0) {
1326
+ delete this.state.displayPrefs;
1327
+ }
1328
+ }
1329
+ else {
1330
+ this.state.displayPrefs[k] = rest;
1331
+ }
1332
+ this.scheduleSave();
1333
+ return;
1334
+ }
1335
+ if (existing?.[field] === value)
1336
+ return;
1337
+ (this.state.displayPrefs ??= {})[k] = { ...existing, [field]: value };
1338
+ this.scheduleSave();
1339
+ });
1340
+ }
1341
+ // ── scheduled jobs (`/schedule`) ──
1342
+ /**
1343
+ * @description Every persisted schedule across all threads, keyed by id.
1344
+ * Read at boot by the engine to re-arm timers. Returns a shallow copy of the
1345
+ * map so callers can't mutate the live state object.
1346
+ */
1347
+ getSchedules() {
1348
+ return { ...(this.state.schedules ?? {}) };
1349
+ }
1350
+ /** Schedules owned by `key`, in insertion order. Empty array when none. */
1351
+ getThreadSchedules(key) {
1352
+ const target = (0, sessionKey_1.keyToString)(key);
1353
+ const all = this.state.schedules ?? {};
1354
+ return Object.values(all).filter(record => record.threadKey === target);
1355
+ }
1356
+ /**
1357
+ * @description Upsert a schedule by its id. The record's `threadKey` is the
1358
+ * source of truth for ownership; callers build it via the scheduler module's
1359
+ * `createScheduleRecord`. Crash-critical fields (`nextRunAt`) ride the
1360
+ * debounced save like every other mutation — the engine calls
1361
+ * {@link flush} explicitly after a fire when the new `nextRunAt` must hit disk
1362
+ * before the process can die.
1363
+ */
1364
+ async upsertSchedule(record) {
1365
+ const target = (0, sessionKey_1.tryKeyFromString)(record.threadKey);
1366
+ if (!target)
1367
+ return;
1368
+ await this.withLock(target, async () => {
1369
+ (this.state.schedules ??= {})[record.id] = record;
1370
+ this.scheduleSave();
1371
+ });
1372
+ }
1373
+ /** Remove a schedule by id. No-op (no save) when absent. */
1374
+ async removeSchedule(id) {
1375
+ const existing = this.state.schedules?.[id];
1376
+ if (!existing)
1377
+ return;
1378
+ const owner = (0, sessionKey_1.tryKeyFromString)(existing.threadKey);
1379
+ const run = async () => {
1380
+ if (this.state.schedules) {
1381
+ delete this.state.schedules[id];
1382
+ if (Object.keys(this.state.schedules).length === 0)
1383
+ delete this.state.schedules;
1384
+ }
1385
+ this.scheduleSave();
1386
+ };
1387
+ if (owner)
1388
+ await this.withLock(owner, run);
1389
+ else
1390
+ await run();
1391
+ }
1392
+ /**
1393
+ * @description Set the paused flag for a schedule (used by /unbind pause and
1394
+ * /bind resume in S8). Clearing the pause drops both `isPaused` and
1395
+ * `pauseReason` so the on-disk shape stays clean. No-op when the id is absent.
1396
+ */
1397
+ async setSchedulePaused(id, paused, reason) {
1398
+ const existing = this.state.schedules?.[id];
1399
+ if (!existing)
1400
+ return;
1401
+ const owner = (0, sessionKey_1.tryKeyFromString)(existing.threadKey);
1402
+ const run = async () => {
1403
+ const current = this.state.schedules?.[id];
1404
+ if (!current)
1405
+ return;
1406
+ if (paused) {
1407
+ current.isPaused = true;
1408
+ if (reason !== undefined)
1409
+ current.pauseReason = reason;
1410
+ }
1411
+ else {
1412
+ delete current.isPaused;
1413
+ delete current.pauseReason;
1414
+ }
1415
+ current.updatedAt = new Date().toISOString();
1416
+ this.scheduleSave();
1417
+ };
1418
+ if (owner)
1419
+ await this.withLock(owner, run);
1420
+ else
1421
+ await run();
1422
+ }
1423
+ // ── scheduler MCP secret ──
1424
+ /**
1425
+ * @description The HMAC secret keying the scheduler MCP tokens, created lazily
1426
+ * on first read and persisted immediately. Generated once with
1427
+ * `crypto.randomBytes` (32 bytes, hex) so the tokens the bot injects into
1428
+ * agent sessions survive restarts. The first-time write is flushed eagerly
1429
+ * (not debounced) so a crash right after minting the first token can't lose
1430
+ * the secret that token was signed with.
1431
+ */
1432
+ async getSchedulerMcpSecret() {
1433
+ if (this.state.schedulerMcpSecret)
1434
+ return this.state.schedulerMcpSecret;
1435
+ const secret = (0, node_crypto_1.randomBytes)(schedulerMcpSecretByteLength).toString('hex');
1436
+ this.state.schedulerMcpSecret = secret;
1437
+ await this.flush();
1438
+ return secret;
1439
+ }
1440
+ // ── scheduler MCP port (reuse across restarts) ──
1441
+ /**
1442
+ * @description The scheduler MCP listen port persisted from a prior boot, or
1443
+ * `undefined` if never persisted (fresh / pre-feature state file). Reused so an
1444
+ * ephemeral port keeps its value across restarts (see
1445
+ * {@link StateV1.schedulerMcpPort}).
1446
+ */
1447
+ getPersistedSchedulerMcpPort() {
1448
+ return this.state.schedulerMcpPort;
1449
+ }
1450
+ /**
1451
+ * @description Persist the actually-bound scheduler MCP port and flush eagerly.
1452
+ * Eager (not debounced) mirrors {@link getSchedulerMcpSecret}: the injected
1453
+ * registrations point at this port, so a crash right after binding must not lose
1454
+ * it and hand the next boot a stale port. Called once at boot, only when the
1455
+ * value changed and the operator did not fix the port via env.
1456
+ */
1457
+ async setSchedulerMcpPort(port) {
1458
+ this.state.schedulerMcpPort = port;
1459
+ await this.flush();
1460
+ }
1461
+ // ── pending interactive questions (restart survival) ──
1462
+ /**
1463
+ * @description Every persisted pending question across all threads, keyed by
1464
+ * {@link SessionKey} string. Read at boot to re-arm the in-memory map for
1465
+ * threads whose session reattached. Returns a shallow copy so callers can't
1466
+ * mutate the live state object.
1467
+ */
1468
+ getPendingQuestions() {
1469
+ return { ...(this.state.pendingQuestions ?? {}) };
1470
+ }
1471
+ /**
1472
+ * @description Persist (upsert) the pending question for `key`, mirroring the
1473
+ * in-memory `pendingQuestions.set(...)` in `bot.ts` so memory and disk never
1474
+ * drift. Crash-window is acceptable on the debounced save: the worst case
1475
+ * (process dies in the <=500ms before the flush) just falls back to the
1476
+ * pre-fix behaviour for that one question. The `messageId` patch goes through
1477
+ * here too, so the persisted record always carries the live button message.
1478
+ */
1479
+ async setPendingQuestion(key, value) {
1480
+ const k = (0, sessionKey_1.keyToString)(key);
1481
+ await this.withLock(key, async () => {
1482
+ (this.state.pendingQuestions ??= {})[k] = value;
1483
+ this.scheduleSave();
1484
+ });
1485
+ }
1486
+ /**
1487
+ * @description Remove the pending question for `key`. Mirrors every in-memory
1488
+ * `pendingQuestions.delete(...)` in `bot.ts`. No-op (no save) when absent. The
1489
+ * whole map is dropped once empty so an idle bot leaves a clean `state.json`.
1490
+ */
1491
+ async clearPendingQuestion(key) {
1492
+ const k = (0, sessionKey_1.keyToString)(key);
1493
+ await this.withLock(key, async () => {
1494
+ if (!this.state.pendingQuestions?.[k])
1495
+ return;
1496
+ delete this.state.pendingQuestions[k];
1497
+ if (Object.keys(this.state.pendingQuestions).length === 0) {
1498
+ delete this.state.pendingQuestions;
1499
+ }
1500
+ this.scheduleSave();
1501
+ });
1502
+ }
1503
+ // ── armed API-error auto-retries (restart survival) ──
1504
+ /**
1505
+ * @description Every persisted armed auto-retry across all threads, keyed by
1506
+ * {@link SessionKey} string. Read at boot to re-arm the in-memory map after
1507
+ * sessions reattach. Returns a shallow copy so callers can't mutate the live
1508
+ * state object.
1509
+ */
1510
+ getApiRetries() {
1511
+ return { ...(this.state.apiRetries ?? {}) };
1512
+ }
1513
+ /**
1514
+ * @description Persist (upsert) the armed retry for `key`, mirroring the
1515
+ * in-memory `apiRetries.set(...)` in `bot.ts` so memory and disk never drift.
1516
+ * Crash-window is acceptable on the debounced save: the worst case (process
1517
+ * dies in the <=500ms before the flush) just loses that one armed retry, which
1518
+ * falls back to the pre-fix behaviour for that thread. Each re-arm (next
1519
+ * attempt) goes through here too, so the persisted record always carries the
1520
+ * latest attempt and `fireAt`.
1521
+ */
1522
+ async setApiRetry(key, value) {
1523
+ const k = (0, sessionKey_1.keyToString)(key);
1524
+ await this.withLock(key, async () => {
1525
+ (this.state.apiRetries ??= {})[k] = value;
1526
+ this.scheduleSave();
1527
+ });
1528
+ }
1529
+ /**
1530
+ * @description Remove the armed retry for `key`. Mirrors every in-memory
1531
+ * `apiRetries.delete(...)` in `bot.ts`. No-op (no save) when absent. The whole
1532
+ * map is dropped once empty so an idle bot leaves a clean `state.json`.
1533
+ */
1534
+ async clearApiRetry(key) {
1535
+ const k = (0, sessionKey_1.keyToString)(key);
1536
+ await this.withLock(key, async () => {
1537
+ if (!this.state.apiRetries?.[k])
1538
+ return;
1539
+ delete this.state.apiRetries[k];
1540
+ if (Object.keys(this.state.apiRetries).length === 0) {
1541
+ delete this.state.apiRetries;
1542
+ }
1543
+ this.scheduleSave();
1544
+ });
1545
+ }
1546
+ // ── prompts held during a usage-limit wait (R23) ──
1547
+ /** @description The prompts held for `key`, oldest first; `[]` when none. A copy. */
1548
+ getLimitHeldPrompts(key) {
1549
+ return (this.state.limitHeldPrompts?.[(0, sessionKey_1.keyToString)(key)] ?? []).map((prompt) => ({ ...prompt }));
1550
+ }
1551
+ /**
1552
+ * @description Replace the prompts held for `key`; `[]` drops the entry (and
1553
+ * the map once empty). Synchronous in memory — a take must be atomic against
1554
+ * a concurrent hold — and saved debounced like the retry record it outlives.
1555
+ */
1556
+ setLimitHeldPrompts(key, prompts) {
1557
+ const k = (0, sessionKey_1.keyToString)(key);
1558
+ if (prompts.length > 0) {
1559
+ (this.state.limitHeldPrompts ??= {})[k] = prompts.map((prompt) => ({ ...prompt }));
1560
+ }
1561
+ else {
1562
+ if (!this.state.limitHeldPrompts?.[k])
1563
+ return;
1564
+ delete this.state.limitHeldPrompts[k];
1565
+ if (Object.keys(this.state.limitHeldPrompts).length === 0)
1566
+ delete this.state.limitHeldPrompts;
1567
+ }
1568
+ this.scheduleSave();
1569
+ }
1570
+ // ── open requests (request ledger) ──
1571
+ /**
1572
+ * @description Every open request across all conversations, keyed by the
1573
+ * serialized {@link RequestGroupKey}. Returns a shallow copy so callers can't
1574
+ * mutate the live state object.
1575
+ */
1576
+ getOpenRequests() {
1577
+ return { ...(this.state.openRequests ?? {}) };
1578
+ }
1579
+ /** @description The open request of `group`, or `undefined`. */
1580
+ getOpenRequest(group) {
1581
+ return this.state.openRequests?.[(0, requestGroup_1.requestGroupKeyToString)(group)];
1582
+ }
1583
+ /**
1584
+ * @description Replace the open request of `group` with what `mutate` returns
1585
+ * for the current one (`undefined` removes it), under the lock of the group's
1586
+ * CONVERSATION — so a read-decide-write (supersede, close, counter update) is
1587
+ * atomic against a concurrent one for the same conversation, whichever of its
1588
+ * groups it touches. `mutate` runs
1589
+ * synchronously inside the lock; a side effect it performs (the ledger's
1590
+ * history append) therefore happens before any other writer sees the result.
1591
+ * The whole map is dropped once empty so an idle bot leaves a clean
1592
+ * `state.json`.
1593
+ */
1594
+ async updateOpenRequest(group, mutate) {
1595
+ const k = (0, requestGroup_1.requestGroupKeyToString)(group);
1596
+ await this.withLock(group.conversation, async () => {
1597
+ const current = this.state.openRequests?.[k];
1598
+ const next = mutate(current);
1599
+ if (next === current)
1600
+ return;
1601
+ if (next === undefined) {
1602
+ if (!this.dropOptionalMapEntry('openRequests', k))
1603
+ return;
1604
+ }
1605
+ else {
1606
+ (this.state.openRequests ??= {})[k] = next;
1607
+ }
1608
+ this.scheduleSave();
1609
+ });
1610
+ }
1611
+ /** @description The alerts of closed requests still to release (a copy). */
1612
+ getUnreleasedRequestAlerts() {
1613
+ return { ...(this.state.unreleasedRequestAlerts ?? {}) };
1614
+ }
1615
+ /**
1616
+ * @description Record that a closed request's alert still needs releasing.
1617
+ * Synchronous on purpose: the ledger calls it inside the close's own locked
1618
+ * step, so it rides the same save as the close.
1619
+ */
1620
+ addUnreleasedRequestAlert(requestId, alert) {
1621
+ (this.state.unreleasedRequestAlerts ??= {})[requestId] = alert;
1622
+ this.scheduleSave();
1623
+ }
1624
+ /** @description The alert of `requestId` was released; forget it. */
1625
+ removeUnreleasedRequestAlert(requestId) {
1626
+ if (!this.state.unreleasedRequestAlerts?.[requestId])
1627
+ return;
1628
+ delete this.state.unreleasedRequestAlerts[requestId];
1629
+ if (Object.keys(this.state.unreleasedRequestAlerts).length === 0)
1630
+ delete this.state.unreleasedRequestAlerts;
1631
+ this.scheduleSave();
1632
+ }
1633
+ // ── pinned answers (S8) ──
1634
+ /** @description The message id of the latest pinned answer in `key`'s conversation, or `undefined`. */
1635
+ getAnswerPinMessageId(key) {
1636
+ return this.state.answerPins?.[(0, sessionKey_1.keyToString)(key)];
1637
+ }
1638
+ /**
1639
+ * @description Remember the latest pinned answer of `key`'s conversation; the
1640
+ * record goes away with the thread's binding. Rides the debounced save: a lost
1641
+ * write leaves one extra pinned answer behind, never a wrong unpin.
1642
+ */
1643
+ async setAnswerPinMessageId(key, messageId) {
1644
+ const k = (0, sessionKey_1.keyToString)(key);
1645
+ await this.withLock(key, async () => {
1646
+ if (this.state.answerPins?.[k] === messageId)
1647
+ return;
1648
+ (this.state.answerPins ??= {})[k] = messageId;
1649
+ this.scheduleSave();
1650
+ });
1651
+ }
1652
+ /**
1653
+ * Drop `k` from one of the optional per-conversation maps, and the map itself
1654
+ * with its last entry (an idle bot leaves a clean `state.json`). `false` when
1655
+ * there was no entry. Caller must hold the key lock.
1656
+ */
1657
+ dropOptionalMapEntry(field, k) {
1658
+ const map = this.state[field];
1659
+ if (map?.[k] === undefined)
1660
+ return false;
1661
+ delete map[k];
1662
+ if (Object.keys(map).length === 0)
1663
+ delete this.state[field];
1664
+ return true;
1665
+ }
1666
+ // ── handled limit episodes (boot-recovery marker) ──
1667
+ /**
1668
+ * @description The `stdout.jsonl` identity recorded when the boot recovery last
1669
+ * armed a limit wait for `key`, or `undefined` when it never did. Compared
1670
+ * against the live stat so an UNCHANGED log is not recovered twice — see
1671
+ * {@link LimitEpisodeMarker}.
1672
+ */
1673
+ getLimitEpisodeRecovered(key) {
1674
+ return this.state.limitEpisodesRecovered?.[(0, sessionKey_1.keyToString)(key)];
1675
+ }
1676
+ /**
1677
+ * @description Record the log identity the boot recovery just armed from.
1678
+ * Debounced (a restart guard, not crash-critical: losing the last <=500ms costs
1679
+ * at worst one repeated recovery). NOT cleared by `cancelApiRetry` on purpose —
1680
+ * that fires on «⏭ Skip once» and on every inbound message, which is exactly the
1681
+ * settled-episode case the marker has to outlive.
1682
+ */
1683
+ async setLimitEpisodeRecovered(key, value) {
1684
+ const k = (0, sessionKey_1.keyToString)(key);
1685
+ await this.withLock(key, async () => {
1686
+ (this.state.limitEpisodesRecovered ??= {})[k] = value;
1687
+ this.scheduleSave();
1688
+ });
1689
+ }
1690
+ /**
1691
+ * Drop `keyStr`'s handled-episode marker (and the whole map once empty). Returns
1692
+ * whether anything changed. Caller must hold the key lock.
1693
+ */
1694
+ dropLimitEpisodeRecovered(keyStr) {
1695
+ return this.dropOptionalMapEntry('limitEpisodesRecovered', keyStr);
1696
+ }
1697
+ // ── transient status-frame ids (restart cleanup) ──
1698
+ /**
1699
+ * @description Every persisted transient status-frame id list across all
1700
+ * threads, keyed by {@link SessionKey} string. Read at boot (after reattach) to
1701
+ * delete any frame left on screen by an UNGRACEFUL exit. Returns a shallow copy
1702
+ * so callers can't mutate the live state object.
1703
+ */
1704
+ getTransientFrames() {
1705
+ return { ...(this.state.transientFrames ?? {}) };
1706
+ }
1707
+ /**
1708
+ * @description Replace the persisted transient status-frame ids for `key`
1709
+ * (the live "✽ working…" status frame, the thinking indicator, the sub-agent
1710
+ * status — whichever are currently on screen). Mirrors the in-memory
1711
+ * `ThreadMessageState` write in `bot.ts`'s frame-id setters so disk can clean
1712
+ * up what the graceful sweep would have. Debounced (NOT flushed): the frames
1713
+ * are cosmetic. An empty list drops the key (and the whole map once empty) so an
1714
+ * idle bot leaves a clean `state.json`. A no-op (no save) when the id list is
1715
+ * unchanged, so the per-turn create/delete churn doesn't reset the save timer
1716
+ * on every identical re-persist.
1717
+ */
1718
+ async setTransientFrames(key, ids) {
1719
+ const k = (0, sessionKey_1.keyToString)(key);
1720
+ await this.withLock(key, async () => {
1721
+ const existing = this.state.transientFrames?.[k];
1722
+ if (ids.length === 0) {
1723
+ if (!existing)
1724
+ return;
1725
+ delete this.state.transientFrames[k];
1726
+ if (Object.keys(this.state.transientFrames).length === 0) {
1727
+ delete this.state.transientFrames;
1728
+ }
1729
+ this.scheduleSave();
1730
+ return;
1731
+ }
1732
+ if (existing && existing.length === ids.length && existing.every((v, i) => v === ids[i])) {
1733
+ return;
1734
+ }
1735
+ (this.state.transientFrames ??= {})[k] = ids.slice();
1736
+ this.scheduleSave();
1737
+ });
1738
+ }
1739
+ // ── persistence ──
1740
+ /** Schedule a save in `saveDebounceMs`. Repeated calls reset the timer. */
1741
+ scheduleSave() {
1742
+ if (this.saveTimer)
1743
+ clearTimeout(this.saveTimer);
1744
+ this.saveTimer = setTimeout(() => {
1745
+ this.saveTimer = null;
1746
+ // Errors are logged inside flush; we don't want to crash the timer chain.
1747
+ this.flush().catch(e => console.error('[state] background flush failed:', e));
1748
+ }, this.saveDebounceMs);
1749
+ }
1750
+ /**
1751
+ * @description Force a save right now and await on-disk persistence.
1752
+ *
1753
+ * Used by:
1754
+ * - shutdown handlers — to guarantee no in-memory state is lost,
1755
+ * - critical paths (initial corruption-archived fresh-start),
1756
+ * - tests.
1757
+ *
1758
+ * Internally serialises against any in-flight write — only one rename
1759
+ * happens at a time per store.
1760
+ */
1761
+ async flush() {
1762
+ if (this.saveTimer) {
1763
+ clearTimeout(this.saveTimer);
1764
+ this.saveTimer = null;
1765
+ }
1766
+ const snapshot = JSON.stringify(this.state, null, 2);
1767
+ const writeNow = () => writeFileAtomic(this.statePath, snapshot);
1768
+ const next = this.writeChain.then(writeNow, writeNow);
1769
+ this.writeChain = next.catch(() => { });
1770
+ await next;
1771
+ }
1772
+ }
1773
+ exports.StateStore = StateStore;
1774
+ // ─── singleton wiring ────────────────────────────────────────────────
1775
+ let singleton = null;
1776
+ let singletonInFlight = null;
1777
+ /**
1778
+ * @description Resolve the default `DATA_DIR` for the running bot.
1779
+ *
1780
+ * Priority:
1781
+ * 1. `process.env.DATA_DIR` (set by the operator — required for the
1782
+ * two-instance setup, plan §10.7).
1783
+ * 2. `~/.telegramCode` — single-instance default.
1784
+ *
1785
+ * Two bots on the same host MUST set distinct `DATA_DIR` values, otherwise
1786
+ * they'd silently share `state.json` and corrupt each other. Plan §16.2
1787
+ * adds a startup `.lock` check; that lives in `bot.ts` (Этап 3), not here.
1788
+ */
1789
+ function resolveDataDir() {
1790
+ return process.env.DATA_DIR || path.join(os.homedir(), '.telegramCode');
1791
+ }
1792
+ /**
1793
+ * @description Create-or-fetch the singleton store. The first call performs
1794
+ * `init()` and persists archival/migration side-effects; subsequent calls
1795
+ * just return the cached instance.
1796
+ *
1797
+ * The in-flight promise is cached to keep concurrent first-callers from
1798
+ * each constructing a separate `StateStore` (two stores → two competing
1799
+ * write chains → corrupted JSON). Production triggers only one call from
1800
+ * `startBot()`, but the cost of the guard is trivial.
1801
+ *
1802
+ * Tests should instantiate `new StateStore(...)` directly instead.
1803
+ */
1804
+ async function getStateStore() {
1805
+ if (singleton)
1806
+ return singleton;
1807
+ if (singletonInFlight)
1808
+ return singletonInFlight;
1809
+ singletonInFlight = (async () => {
1810
+ const store = new StateStore(resolveDataDir());
1811
+ await store.init();
1812
+ singleton = store;
1813
+ return store;
1814
+ })();
1815
+ try {
1816
+ return await singletonInFlight;
1817
+ }
1818
+ finally {
1819
+ singletonInFlight = null;
1820
+ }
1821
+ }
1822
+ /**
1823
+ * @description Reset the singleton — only for tests. Production code should
1824
+ * never call this; doing so would leak in-flight write promises.
1825
+ */
1826
+ function _resetStateStoreSingletonForTests() {
1827
+ singleton = null;
1828
+ singletonInFlight = null;
1829
+ }
1830
+ //# sourceMappingURL=state.js.map