charness 3.11.0 → 3.13.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 (537) hide show
  1. package/.env.example +5 -0
  2. package/CHANGELOG.md +169 -0
  3. package/DEVELOPMENT.md +81 -18
  4. package/README.md +3 -2
  5. package/SETUP.md +71 -25
  6. package/agent-plugin/README.md +15 -6
  7. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +37 -18
  8. package/agent-plugin/skills/charness-delegate-opencode/SKILL.md +10 -6
  9. package/agent-plugin/skills/charness-delivery-loop/SKILL.md +92 -0
  10. package/agent-plugin/skills/charness-orchestration/SKILL.md +116 -0
  11. package/dist/accessControl.d.ts +43 -0
  12. package/dist/accessControl.d.ts.map +1 -1
  13. package/dist/accessControl.js +50 -1
  14. package/dist/accessControl.js.map +1 -1
  15. package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
  16. package/dist/adapters/claudeCliAdapter.js +9 -4
  17. package/dist/adapters/claudeCliAdapter.js.map +1 -1
  18. package/dist/adapters/claudeJsonStreamAdapter.js +1 -1
  19. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  20. package/dist/adapters/claudePlatformFlags.d.ts +4 -3
  21. package/dist/adapters/claudePlatformFlags.d.ts.map +1 -1
  22. package/dist/adapters/claudePlatformFlags.js +4 -3
  23. package/dist/adapters/claudePlatformFlags.js.map +1 -1
  24. package/dist/adapters/openCodeAdapter.d.ts +52 -13
  25. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  26. package/dist/adapters/openCodeAdapter.js +121 -45
  27. package/dist/adapters/openCodeAdapter.js.map +1 -1
  28. package/dist/adapters/terminalAdapter.d.ts.map +1 -1
  29. package/dist/adapters/terminalAdapter.js +5 -3
  30. package/dist/adapters/terminalAdapter.js.map +1 -1
  31. package/dist/agentLogin/agentLogin.d.ts +11 -0
  32. package/dist/agentLogin/agentLogin.d.ts.map +1 -1
  33. package/dist/agentLogin/agentLogin.js +20 -20
  34. package/dist/agentLogin/agentLogin.js.map +1 -1
  35. package/dist/apiErrorRetry.d.ts +5 -0
  36. package/dist/apiErrorRetry.d.ts.map +1 -1
  37. package/dist/apiErrorRetry.js +3 -3
  38. package/dist/apiErrorRetry.js.map +1 -1
  39. package/dist/bot.d.ts +12 -3
  40. package/dist/bot.d.ts.map +1 -1
  41. package/dist/bot.js +634 -153
  42. package/dist/bot.js.map +1 -1
  43. package/dist/cli/claudeProfiles.d.ts +5 -2
  44. package/dist/cli/claudeProfiles.d.ts.map +1 -1
  45. package/dist/cli/claudeProfiles.js +45 -22
  46. package/dist/cli/claudeProfiles.js.map +1 -1
  47. package/dist/cli/claudeProfilesCredit.d.ts +49 -0
  48. package/dist/cli/claudeProfilesCredit.d.ts.map +1 -0
  49. package/dist/cli/claudeProfilesCredit.js +160 -0
  50. package/dist/cli/claudeProfilesCredit.js.map +1 -0
  51. package/dist/cli/flagValue.d.ts +10 -0
  52. package/dist/cli/flagValue.d.ts.map +1 -0
  53. package/dist/cli/flagValue.js +17 -0
  54. package/dist/cli/flagValue.js.map +1 -0
  55. package/dist/connectors/jira/client.js +1 -1
  56. package/dist/connectors/jira/client.js.map +1 -1
  57. package/dist/connectors/jira/config.d.ts +7 -0
  58. package/dist/connectors/jira/config.d.ts.map +1 -1
  59. package/dist/connectors/jira/config.js +12 -1
  60. package/dist/connectors/jira/config.js.map +1 -1
  61. package/dist/connectors/jira/connector.d.ts +7 -0
  62. package/dist/connectors/jira/connector.d.ts.map +1 -1
  63. package/dist/connectors/jira/connector.js +20 -3
  64. package/dist/connectors/jira/connector.js.map +1 -1
  65. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  66. package/dist/connectors/jira/inbound.js +4 -3
  67. package/dist/connectors/jira/inbound.js.map +1 -1
  68. package/dist/connectors/jira/issueBlocks.d.ts +1 -1
  69. package/dist/connectors/jira/trustedGroup.d.ts +21 -6
  70. package/dist/connectors/jira/trustedGroup.d.ts.map +1 -1
  71. package/dist/connectors/jira/trustedGroup.js +46 -6
  72. package/dist/connectors/jira/trustedGroup.js.map +1 -1
  73. package/dist/connectors/telegram/commands/botCore.d.ts +19 -2
  74. package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -1
  75. package/dist/connectors/telegram/commands/botSkills.js +1 -1
  76. package/dist/connectors/telegram/commands/claudeAccounts.d.ts +6 -1
  77. package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
  78. package/dist/connectors/telegram/commands/claudeAccounts.js +9 -6
  79. package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
  80. package/dist/connectors/telegram/commands/compaction.d.ts +16 -3
  81. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  82. package/dist/connectors/telegram/commands/compaction.js +216 -27
  83. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  84. package/dist/connectors/telegram/commands/runners.d.ts +5 -1
  85. package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
  86. package/dist/connectors/telegram/commands/runners.js +146 -31
  87. package/dist/connectors/telegram/commands/runners.js.map +1 -1
  88. package/dist/connectors/telegram/commands/todo.d.ts.map +1 -1
  89. package/dist/connectors/telegram/commands/todo.js +2 -2
  90. package/dist/connectors/telegram/commands/todo.js.map +1 -1
  91. package/dist/connectors/telegram/commands/topicAccess.d.ts +30 -0
  92. package/dist/connectors/telegram/commands/topicAccess.d.ts.map +1 -0
  93. package/dist/connectors/telegram/commands/topicAccess.js +399 -0
  94. package/dist/connectors/telegram/commands/topicAccess.js.map +1 -0
  95. package/dist/connectors/telegram/inbound.d.ts +44 -7
  96. package/dist/connectors/telegram/inbound.d.ts.map +1 -1
  97. package/dist/connectors/telegram/inbound.js +142 -24
  98. package/dist/connectors/telegram/inbound.js.map +1 -1
  99. package/dist/connectors/telegram/runnerPairingMessages.d.ts +2 -7
  100. package/dist/connectors/telegram/runnerPairingMessages.d.ts.map +1 -1
  101. package/dist/connectors/telegram/runnerPairingMessages.js +5 -19
  102. package/dist/connectors/telegram/runnerPairingMessages.js.map +1 -1
  103. package/dist/i18n/de.d.ts.map +1 -1
  104. package/dist/i18n/de.js +120 -8
  105. package/dist/i18n/de.js.map +1 -1
  106. package/dist/i18n/en.d.ts.map +1 -1
  107. package/dist/i18n/en.js +120 -8
  108. package/dist/i18n/en.js.map +1 -1
  109. package/dist/i18n/es.d.ts.map +1 -1
  110. package/dist/i18n/es.js +120 -8
  111. package/dist/i18n/es.js.map +1 -1
  112. package/dist/i18n/fr.d.ts.map +1 -1
  113. package/dist/i18n/fr.js +120 -8
  114. package/dist/i18n/fr.js.map +1 -1
  115. package/dist/i18n/hi.d.ts.map +1 -1
  116. package/dist/i18n/hi.js +120 -8
  117. package/dist/i18n/hi.js.map +1 -1
  118. package/dist/i18n/ja.d.ts.map +1 -1
  119. package/dist/i18n/ja.js +120 -8
  120. package/dist/i18n/ja.js.map +1 -1
  121. package/dist/i18n/ka.d.ts.map +1 -1
  122. package/dist/i18n/ka.js +120 -8
  123. package/dist/i18n/ka.js.map +1 -1
  124. package/dist/i18n/pt.d.ts.map +1 -1
  125. package/dist/i18n/pt.js +120 -8
  126. package/dist/i18n/pt.js.map +1 -1
  127. package/dist/i18n/ru.d.ts.map +1 -1
  128. package/dist/i18n/ru.js +120 -8
  129. package/dist/i18n/ru.js.map +1 -1
  130. package/dist/i18n/uk.d.ts.map +1 -1
  131. package/dist/i18n/uk.js +120 -8
  132. package/dist/i18n/uk.js.map +1 -1
  133. package/dist/i18n/uz.d.ts.map +1 -1
  134. package/dist/i18n/uz.js +120 -8
  135. package/dist/i18n/uz.js.map +1 -1
  136. package/dist/i18n/zh.d.ts.map +1 -1
  137. package/dist/i18n/zh.js +120 -8
  138. package/dist/i18n/zh.js.map +1 -1
  139. package/dist/installManager.d.ts +37 -1
  140. package/dist/installManager.d.ts.map +1 -1
  141. package/dist/installManager.js +208 -14
  142. package/dist/installManager.js.map +1 -1
  143. package/dist/instanceLock.d.ts.map +1 -1
  144. package/dist/instanceLock.js +2 -1
  145. package/dist/instanceLock.js.map +1 -1
  146. package/dist/platform/commandRouter.d.ts +13 -1
  147. package/dist/platform/commandRouter.d.ts.map +1 -1
  148. package/dist/platform/commandRouter.js +14 -2
  149. package/dist/platform/commandRouter.js.map +1 -1
  150. package/dist/platform/inbound.d.ts +2 -0
  151. package/dist/platform/inbound.d.ts.map +1 -1
  152. package/dist/platform/outbound.d.ts +14 -1
  153. package/dist/platform/outbound.d.ts.map +1 -1
  154. package/dist/platform/outbound.js.map +1 -1
  155. package/dist/remoteRun/cleanReport.d.ts +45 -0
  156. package/dist/remoteRun/cleanReport.d.ts.map +1 -0
  157. package/dist/remoteRun/cleanReport.js +84 -0
  158. package/dist/remoteRun/cleanReport.js.map +1 -0
  159. package/dist/remoteRun/cliArgs.d.ts +18 -0
  160. package/dist/remoteRun/cliArgs.d.ts.map +1 -1
  161. package/dist/remoteRun/cliArgs.js +100 -4
  162. package/dist/remoteRun/cliArgs.js.map +1 -1
  163. package/dist/remoteRun/commands.d.ts +30 -1
  164. package/dist/remoteRun/commands.d.ts.map +1 -1
  165. package/dist/remoteRun/commands.js +84 -9
  166. package/dist/remoteRun/commands.js.map +1 -1
  167. package/dist/remoteRun/exitCodes.d.ts +5 -0
  168. package/dist/remoteRun/exitCodes.d.ts.map +1 -1
  169. package/dist/remoteRun/exitCodes.js +6 -1
  170. package/dist/remoteRun/exitCodes.js.map +1 -1
  171. package/dist/remoteRun/foreground.d.ts +6 -0
  172. package/dist/remoteRun/foreground.d.ts.map +1 -1
  173. package/dist/remoteRun/foreground.js +13 -1
  174. package/dist/remoteRun/foreground.js.map +1 -1
  175. package/dist/remoteRun/interrupts.d.ts.map +1 -1
  176. package/dist/remoteRun/interrupts.js +2 -2
  177. package/dist/remoteRun/interrupts.js.map +1 -1
  178. package/dist/remoteRun/jobFiles.d.ts +6 -1
  179. package/dist/remoteRun/jobFiles.d.ts.map +1 -1
  180. package/dist/remoteRun/jobFiles.js +14 -0
  181. package/dist/remoteRun/jobFiles.js.map +1 -1
  182. package/dist/remoteRun/jobId.d.ts +5 -0
  183. package/dist/remoteRun/jobId.d.ts.map +1 -1
  184. package/dist/remoteRun/jobId.js +10 -0
  185. package/dist/remoteRun/jobId.js.map +1 -1
  186. package/dist/remoteRun/jobState.d.ts.map +1 -1
  187. package/dist/remoteRun/jobState.js +3 -2
  188. package/dist/remoteRun/jobState.js.map +1 -1
  189. package/dist/remoteRun/pairedRunners.d.ts +1 -1
  190. package/dist/remoteRun/pairedRunners.d.ts.map +1 -1
  191. package/dist/remoteRun/pairedRunners.js +4 -0
  192. package/dist/remoteRun/pairedRunners.js.map +1 -1
  193. package/dist/remoteRun/pathPatterns.d.ts +1 -1
  194. package/dist/remoteRun/pathPatterns.js +1 -1
  195. package/dist/remoteRun/probe.d.ts +58 -5
  196. package/dist/remoteRun/probe.d.ts.map +1 -1
  197. package/dist/remoteRun/probe.js +107 -11
  198. package/dist/remoteRun/probe.js.map +1 -1
  199. package/dist/remoteRun/probeTiming.d.ts +15 -0
  200. package/dist/remoteRun/probeTiming.d.ts.map +1 -0
  201. package/dist/remoteRun/probeTiming.js +23 -0
  202. package/dist/remoteRun/probeTiming.js.map +1 -0
  203. package/dist/remoteRun/project.d.ts +5 -0
  204. package/dist/remoteRun/project.d.ts.map +1 -1
  205. package/dist/remoteRun/project.js +10 -0
  206. package/dist/remoteRun/project.js.map +1 -1
  207. package/dist/remoteRun/projectConfig.d.ts +8 -1
  208. package/dist/remoteRun/projectConfig.d.ts.map +1 -1
  209. package/dist/remoteRun/projectConfig.js +18 -5
  210. package/dist/remoteRun/projectConfig.js.map +1 -1
  211. package/dist/remoteRun/pruneReport.d.ts +48 -0
  212. package/dist/remoteRun/pruneReport.d.ts.map +1 -0
  213. package/dist/remoteRun/pruneReport.js +80 -0
  214. package/dist/remoteRun/pruneReport.js.map +1 -0
  215. package/dist/remoteRun/remoteRunCli.d.ts +1 -1
  216. package/dist/remoteRun/remoteRunCli.d.ts.map +1 -1
  217. package/dist/remoteRun/remoteRunCli.js +20 -0
  218. package/dist/remoteRun/remoteRunCli.js.map +1 -1
  219. package/dist/remoteRun/runnerClient.d.ts +10 -0
  220. package/dist/remoteRun/runnerClient.d.ts.map +1 -1
  221. package/dist/remoteRun/runnerClient.js +19 -5
  222. package/dist/remoteRun/runnerClient.js.map +1 -1
  223. package/dist/remoteRun/runnerWait.d.ts.map +1 -1
  224. package/dist/remoteRun/runnerWait.js +2 -1
  225. package/dist/remoteRun/runnerWait.js.map +1 -1
  226. package/dist/remoteRun/runners.d.ts +48 -7
  227. package/dist/remoteRun/runners.d.ts.map +1 -1
  228. package/dist/remoteRun/runners.js +105 -40
  229. package/dist/remoteRun/runners.js.map +1 -1
  230. package/dist/remoteRun/runnersConfig.d.ts +24 -0
  231. package/dist/remoteRun/runnersConfig.d.ts.map +1 -1
  232. package/dist/remoteRun/runnersConfig.js +29 -2
  233. package/dist/remoteRun/runnersConfig.js.map +1 -1
  234. package/dist/remoteRun/ssh.d.ts +3 -3
  235. package/dist/remoteRun/ssh.d.ts.map +1 -1
  236. package/dist/remoteRun/ssh.js +19 -5
  237. package/dist/remoteRun/ssh.js.map +1 -1
  238. package/dist/remoteRun/submit.d.ts +1 -1
  239. package/dist/remoteRun/submit.d.ts.map +1 -1
  240. package/dist/remoteRun/submit.js +30 -2
  241. package/dist/remoteRun/submit.js.map +1 -1
  242. package/dist/runnerUtility/adminService.d.ts.map +1 -1
  243. package/dist/runnerUtility/adminService.js +5 -5
  244. package/dist/runnerUtility/adminService.js.map +1 -1
  245. package/dist/runnerUtility/appInstall.d.ts +9 -0
  246. package/dist/runnerUtility/appInstall.d.ts.map +1 -1
  247. package/dist/runnerUtility/appInstall.js +12 -2
  248. package/dist/runnerUtility/appInstall.js.map +1 -1
  249. package/dist/runnerUtility/execEnv.d.ts +1 -1
  250. package/dist/runnerUtility/execEnv.d.ts.map +1 -1
  251. package/dist/runnerUtility/execEnv.js +23 -5
  252. package/dist/runnerUtility/execEnv.js.map +1 -1
  253. package/dist/runnerUtility/guiAgentHeal.d.ts +3 -3
  254. package/dist/runnerUtility/guiAgentHeal.d.ts.map +1 -1
  255. package/dist/runnerUtility/guiAgentHeal.js +4 -2
  256. package/dist/runnerUtility/guiAgentHeal.js.map +1 -1
  257. package/dist/runnerUtility/homeFolders.d.ts +1 -0
  258. package/dist/runnerUtility/homeFolders.d.ts.map +1 -1
  259. package/dist/runnerUtility/homeFolders.js +2 -1
  260. package/dist/runnerUtility/homeFolders.js.map +1 -1
  261. package/dist/runnerUtility/iosCheck.d.ts +2 -0
  262. package/dist/runnerUtility/iosCheck.d.ts.map +1 -1
  263. package/dist/runnerUtility/iosCheck.js +12 -3
  264. package/dist/runnerUtility/iosCheck.js.map +1 -1
  265. package/dist/runnerUtility/keepAwake.d.ts +47 -10
  266. package/dist/runnerUtility/keepAwake.d.ts.map +1 -1
  267. package/dist/runnerUtility/keepAwake.js +108 -31
  268. package/dist/runnerUtility/keepAwake.js.map +1 -1
  269. package/dist/runnerUtility/launcher.d.ts +4 -0
  270. package/dist/runnerUtility/launcher.d.ts.map +1 -1
  271. package/dist/runnerUtility/launcher.js +31 -13
  272. package/dist/runnerUtility/launcher.js.map +1 -1
  273. package/dist/runnerUtility/linkLoop.d.ts +4 -0
  274. package/dist/runnerUtility/linkLoop.d.ts.map +1 -1
  275. package/dist/runnerUtility/linkLoop.js +15 -6
  276. package/dist/runnerUtility/linkLoop.js.map +1 -1
  277. package/dist/runnerUtility/managedNode.d.ts +84 -0
  278. package/dist/runnerUtility/managedNode.d.ts.map +1 -0
  279. package/dist/runnerUtility/managedNode.js +165 -0
  280. package/dist/runnerUtility/managedNode.js.map +1 -0
  281. package/dist/runnerUtility/nodeOnPath.d.ts +10 -0
  282. package/dist/runnerUtility/nodeOnPath.d.ts.map +1 -0
  283. package/dist/runnerUtility/nodeOnPath.js +49 -0
  284. package/dist/runnerUtility/nodeOnPath.js.map +1 -0
  285. package/dist/runnerUtility/nodeUpkeep.d.ts +140 -0
  286. package/dist/runnerUtility/nodeUpkeep.d.ts.map +1 -0
  287. package/dist/runnerUtility/nodeUpkeep.js +348 -0
  288. package/dist/runnerUtility/nodeUpkeep.js.map +1 -0
  289. package/dist/runnerUtility/nodeUpkeepTiming.d.ts +14 -0
  290. package/dist/runnerUtility/nodeUpkeepTiming.d.ts.map +1 -0
  291. package/dist/runnerUtility/nodeUpkeepTiming.js +21 -0
  292. package/dist/runnerUtility/nodeUpkeepTiming.js.map +1 -0
  293. package/dist/runnerUtility/packageManagerShims.d.ts +10 -0
  294. package/dist/runnerUtility/packageManagerShims.d.ts.map +1 -1
  295. package/dist/runnerUtility/packageManagerShims.js +67 -3
  296. package/dist/runnerUtility/packageManagerShims.js.map +1 -1
  297. package/dist/runnerUtility/pueueDaemon.d.ts +73 -8
  298. package/dist/runnerUtility/pueueDaemon.d.ts.map +1 -1
  299. package/dist/runnerUtility/pueueDaemon.js +90 -15
  300. package/dist/runnerUtility/pueueDaemon.js.map +1 -1
  301. package/dist/runnerUtility/runnerCommands.d.ts +7 -1
  302. package/dist/runnerUtility/runnerCommands.d.ts.map +1 -1
  303. package/dist/runnerUtility/runnerCommands.js +119 -16
  304. package/dist/runnerUtility/runnerCommands.js.map +1 -1
  305. package/dist/runnerUtility/runnerHome.d.ts +34 -0
  306. package/dist/runnerUtility/runnerHome.d.ts.map +1 -1
  307. package/dist/runnerUtility/runnerHome.js +17 -3
  308. package/dist/runnerUtility/runnerHome.js.map +1 -1
  309. package/dist/runnerUtility/serviceCommon.d.ts +2 -0
  310. package/dist/runnerUtility/serviceCommon.d.ts.map +1 -1
  311. package/dist/runnerUtility/serviceCommon.js +3 -1
  312. package/dist/runnerUtility/serviceCommon.js.map +1 -1
  313. package/dist/runnerUtility/serviceManager.d.ts.map +1 -1
  314. package/dist/runnerUtility/serviceManager.js +7 -2
  315. package/dist/runnerUtility/serviceManager.js.map +1 -1
  316. package/dist/runnerUtility/simctlGuard.d.ts +38 -0
  317. package/dist/runnerUtility/simctlGuard.d.ts.map +1 -0
  318. package/dist/runnerUtility/simctlGuard.js +166 -0
  319. package/dist/runnerUtility/simctlGuard.js.map +1 -0
  320. package/dist/runners/bootstrapLine.d.ts +3 -4
  321. package/dist/runners/bootstrapLine.d.ts.map +1 -1
  322. package/dist/runners/bootstrapLine.js +108 -83
  323. package/dist/runners/bootstrapLine.js.map +1 -1
  324. package/dist/runners/hubPackage.d.ts +1 -1
  325. package/dist/runners/hubPackage.d.ts.map +1 -1
  326. package/dist/runners/hubPackage.js +5 -6
  327. package/dist/runners/hubPackage.js.map +1 -1
  328. package/dist/runners/hubPairing.d.ts +19 -0
  329. package/dist/runners/hubPairing.d.ts.map +1 -1
  330. package/dist/runners/hubPairing.js +38 -0
  331. package/dist/runners/hubPairing.js.map +1 -1
  332. package/dist/runners/hubRegistry.d.ts +8 -0
  333. package/dist/runners/hubRegistry.d.ts.map +1 -1
  334. package/dist/runners/hubRegistry.js +6 -0
  335. package/dist/runners/hubRegistry.js.map +1 -1
  336. package/dist/runners/pairCode.d.ts +34 -3
  337. package/dist/runners/pairCode.d.ts.map +1 -1
  338. package/dist/runners/pairCode.js +65 -13
  339. package/dist/runners/pairCode.js.map +1 -1
  340. package/dist/runners/runnerGroups.d.ts +22 -0
  341. package/dist/runners/runnerGroups.d.ts.map +1 -0
  342. package/dist/runners/runnerGroups.js +41 -0
  343. package/dist/runners/runnerGroups.js.map +1 -0
  344. package/dist/runners/runnerLock.d.ts +36 -1
  345. package/dist/runners/runnerLock.d.ts.map +1 -1
  346. package/dist/runners/runnerLock.js +94 -30
  347. package/dist/runners/runnerLock.js.map +1 -1
  348. package/dist/runners/runnersCli.d.ts +5 -2
  349. package/dist/runners/runnersCli.d.ts.map +1 -1
  350. package/dist/runners/runnersCli.js +59 -9
  351. package/dist/runners/runnersCli.js.map +1 -1
  352. package/dist/runners/runnersList.d.ts +1 -1
  353. package/dist/runners/runnersList.d.ts.map +1 -1
  354. package/dist/runners/runnersList.js +3 -1
  355. package/dist/runners/runnersList.js.map +1 -1
  356. package/dist/runners/runnersOverview.d.ts.map +1 -1
  357. package/dist/runners/runnersOverview.js +8 -4
  358. package/dist/runners/runnersOverview.js.map +1 -1
  359. package/dist/scheduler/checkRun.d.ts +0 -2
  360. package/dist/scheduler/checkRun.d.ts.map +1 -1
  361. package/dist/scheduler/checkRun.js +0 -10
  362. package/dist/scheduler/checkRun.js.map +1 -1
  363. package/dist/scheduler/checkStatus.d.ts +2 -0
  364. package/dist/scheduler/checkStatus.d.ts.map +1 -1
  365. package/dist/scheduler/checkStatus.js +5 -4
  366. package/dist/scheduler/checkStatus.js.map +1 -1
  367. package/dist/scheduler/delivery.d.ts +2 -1
  368. package/dist/scheduler/delivery.d.ts.map +1 -1
  369. package/dist/scheduler/delivery.js +5 -1
  370. package/dist/scheduler/delivery.js.map +1 -1
  371. package/dist/scheduler/mcpSurface.d.ts +7 -3
  372. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  373. package/dist/scheduler/mcpSurface.js +48 -22
  374. package/dist/scheduler/mcpSurface.js.map +1 -1
  375. package/dist/scheduler/workerWatch.d.ts +33 -10
  376. package/dist/scheduler/workerWatch.d.ts.map +1 -1
  377. package/dist/scheduler/workerWatch.js +37 -11
  378. package/dist/scheduler/workerWatch.js.map +1 -1
  379. package/dist/selfUpdate/bootRollback.d.ts.map +1 -1
  380. package/dist/selfUpdate/bootRollback.js +3 -2
  381. package/dist/selfUpdate/bootRollback.js.map +1 -1
  382. package/dist/selfUpdate/updateRuntime.d.ts.map +1 -1
  383. package/dist/selfUpdate/updateRuntime.js +6 -3
  384. package/dist/selfUpdate/updateRuntime.js.map +1 -1
  385. package/dist/state.d.ts +144 -2
  386. package/dist/state.d.ts.map +1 -1
  387. package/dist/state.js +257 -7
  388. package/dist/state.js.map +1 -1
  389. package/dist/testTimings.d.ts +6 -2
  390. package/dist/testTimings.d.ts.map +1 -1
  391. package/dist/testTimings.js +12 -1
  392. package/dist/testTimings.js.map +1 -1
  393. package/dist/threadContextPreamble.d.ts +15 -1
  394. package/dist/threadContextPreamble.d.ts.map +1 -1
  395. package/dist/threadContextPreamble.js +15 -3
  396. package/dist/threadContextPreamble.js.map +1 -1
  397. package/dist/threadRouting.d.ts +47 -4
  398. package/dist/threadRouting.d.ts.map +1 -1
  399. package/dist/threadRouting.js +31 -4
  400. package/dist/threadRouting.js.map +1 -1
  401. package/dist/todos/projects.d.ts +1 -1
  402. package/dist/todos/projects.d.ts.map +1 -1
  403. package/dist/todos/projects.js +3 -14
  404. package/dist/todos/projects.js.map +1 -1
  405. package/dist/topicTalkerMemory.d.ts +37 -0
  406. package/dist/topicTalkerMemory.d.ts.map +1 -0
  407. package/dist/topicTalkerMemory.js +61 -0
  408. package/dist/topicTalkerMemory.js.map +1 -0
  409. package/dist/topicTalkers.d.ts +123 -0
  410. package/dist/topicTalkers.d.ts.map +1 -0
  411. package/dist/topicTalkers.js +276 -0
  412. package/dist/topicTalkers.js.map +1 -0
  413. package/dist/types.d.ts +7 -5
  414. package/dist/types.d.ts.map +1 -1
  415. package/dist/utils/agentEnvironment.d.ts +23 -0
  416. package/dist/utils/agentEnvironment.d.ts.map +1 -1
  417. package/dist/utils/agentEnvironment.js +33 -1
  418. package/dist/utils/agentEnvironment.js.map +1 -1
  419. package/dist/utils/agentPlugin.d.ts +9 -3
  420. package/dist/utils/agentPlugin.d.ts.map +1 -1
  421. package/dist/utils/agentPlugin.js +13 -6
  422. package/dist/utils/agentPlugin.js.map +1 -1
  423. package/dist/utils/authorMark.d.ts +59 -0
  424. package/dist/utils/authorMark.d.ts.map +1 -0
  425. package/dist/utils/authorMark.js +86 -0
  426. package/dist/utils/authorMark.js.map +1 -0
  427. package/dist/utils/botSkills.d.ts +1 -1
  428. package/dist/utils/claudeApiAgentStop.d.ts +64 -0
  429. package/dist/utils/claudeApiAgentStop.d.ts.map +1 -0
  430. package/dist/utils/claudeApiAgentStop.js +85 -0
  431. package/dist/utils/claudeApiAgentStop.js.map +1 -0
  432. package/dist/utils/claudeApiCredit.d.ts +168 -0
  433. package/dist/utils/claudeApiCredit.d.ts.map +1 -0
  434. package/dist/utils/claudeApiCredit.js +260 -0
  435. package/dist/utils/claudeApiCredit.js.map +1 -0
  436. package/dist/utils/claudeApiCreditRecheck.d.ts +120 -0
  437. package/dist/utils/claudeApiCreditRecheck.d.ts.map +1 -0
  438. package/dist/utils/claudeApiCreditRecheck.js +173 -0
  439. package/dist/utils/claudeApiCreditRecheck.js.map +1 -0
  440. package/dist/utils/claudeCompactHook.d.ts +18 -10
  441. package/dist/utils/claudeCompactHook.d.ts.map +1 -1
  442. package/dist/utils/claudeCompactHook.js +35 -14
  443. package/dist/utils/claudeCompactHook.js.map +1 -1
  444. package/dist/utils/claudeLimitSwitch.d.ts +5 -1
  445. package/dist/utils/claudeLimitSwitch.d.ts.map +1 -1
  446. package/dist/utils/claudeLimitSwitch.js +6 -2
  447. package/dist/utils/claudeLimitSwitch.js.map +1 -1
  448. package/dist/utils/claudeProfileUsageLines.d.ts +14 -2
  449. package/dist/utils/claudeProfileUsageLines.d.ts.map +1 -1
  450. package/dist/utils/claudeProfileUsageLines.js +78 -7
  451. package/dist/utils/claudeProfileUsageLines.js.map +1 -1
  452. package/dist/utils/claudeProfileUsageViews.d.ts +46 -0
  453. package/dist/utils/claudeProfileUsageViews.d.ts.map +1 -0
  454. package/dist/utils/claudeProfileUsageViews.js +114 -0
  455. package/dist/utils/claudeProfileUsageViews.js.map +1 -0
  456. package/dist/utils/claudeProfiles.d.ts +22 -0
  457. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  458. package/dist/utils/claudeProfiles.js +69 -0
  459. package/dist/utils/claudeProfiles.js.map +1 -1
  460. package/dist/utils/claudeUsage.d.ts +145 -51
  461. package/dist/utils/claudeUsage.d.ts.map +1 -1
  462. package/dist/utils/claudeUsage.js +211 -94
  463. package/dist/utils/claudeUsage.js.map +1 -1
  464. package/dist/utils/compactOnIdle.d.ts +140 -15
  465. package/dist/utils/compactOnIdle.d.ts.map +1 -1
  466. package/dist/utils/compactOnIdle.js +209 -23
  467. package/dist/utils/compactOnIdle.js.map +1 -1
  468. package/dist/utils/compactSelfReviewFlags.d.ts +50 -0
  469. package/dist/utils/compactSelfReviewFlags.d.ts.map +1 -0
  470. package/dist/utils/compactSelfReviewFlags.js +120 -0
  471. package/dist/utils/compactSelfReviewFlags.js.map +1 -0
  472. package/dist/utils/fallbackChain.d.ts +18 -7
  473. package/dist/utils/fallbackChain.d.ts.map +1 -1
  474. package/dist/utils/fallbackChain.js +36 -16
  475. package/dist/utils/fallbackChain.js.map +1 -1
  476. package/dist/utils/folderGit.d.ts +9 -0
  477. package/dist/utils/folderGit.d.ts.map +1 -0
  478. package/dist/utils/folderGit.js +33 -0
  479. package/dist/utils/folderGit.js.map +1 -0
  480. package/dist/utils/forwardedMark.d.ts +8 -0
  481. package/dist/utils/forwardedMark.d.ts.map +1 -1
  482. package/dist/utils/forwardedMark.js +2 -0
  483. package/dist/utils/forwardedMark.js.map +1 -1
  484. package/dist/utils/jsonStreamHost.d.ts +2 -1
  485. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  486. package/dist/utils/jsonStreamHost.js +4 -2
  487. package/dist/utils/jsonStreamHost.js.map +1 -1
  488. package/dist/utils/messageContext.d.ts +22 -7
  489. package/dist/utils/messageContext.d.ts.map +1 -1
  490. package/dist/utils/messageContext.js +19 -5
  491. package/dist/utils/messageContext.js.map +1 -1
  492. package/dist/utils/openCodeCompactPlugin.d.ts +28 -7
  493. package/dist/utils/openCodeCompactPlugin.d.ts.map +1 -1
  494. package/dist/utils/openCodeCompactPlugin.js +80 -15
  495. package/dist/utils/openCodeCompactPlugin.js.map +1 -1
  496. package/dist/utils/personLabel.d.ts +13 -0
  497. package/dist/utils/personLabel.d.ts.map +1 -0
  498. package/dist/utils/personLabel.js +15 -0
  499. package/dist/utils/personLabel.js.map +1 -0
  500. package/dist/utils/replyQuote.d.ts +17 -3
  501. package/dist/utils/replyQuote.d.ts.map +1 -1
  502. package/dist/utils/replyQuote.js +25 -2
  503. package/dist/utils/replyQuote.js.map +1 -1
  504. package/dist/utils/runnersScreenPlan.d.ts +51 -20
  505. package/dist/utils/runnersScreenPlan.d.ts.map +1 -1
  506. package/dist/utils/runnersScreenPlan.js +143 -28
  507. package/dist/utils/runnersScreenPlan.js.map +1 -1
  508. package/dist/utils/streamedCompactionSummary.d.ts +65 -0
  509. package/dist/utils/streamedCompactionSummary.d.ts.map +1 -0
  510. package/dist/utils/streamedCompactionSummary.js +108 -0
  511. package/dist/utils/streamedCompactionSummary.js.map +1 -0
  512. package/dist/utils/talkerAccess.d.ts +9 -0
  513. package/dist/utils/talkerAccess.d.ts.map +1 -0
  514. package/dist/utils/talkerAccess.js +20 -0
  515. package/dist/utils/talkerAccess.js.map +1 -0
  516. package/dist/utils/tmuxExec.d.ts +20 -8
  517. package/dist/utils/tmuxExec.d.ts.map +1 -1
  518. package/dist/utils/tmuxExec.js +27 -7
  519. package/dist/utils/tmuxExec.js.map +1 -1
  520. package/dist/utils/topicAccessScreenPlan.d.ts +253 -0
  521. package/dist/utils/topicAccessScreenPlan.d.ts.map +1 -0
  522. package/dist/utils/topicAccessScreenPlan.js +287 -0
  523. package/dist/utils/topicAccessScreenPlan.js.map +1 -0
  524. package/dist/utils/topicLabel.d.ts +12 -0
  525. package/dist/utils/topicLabel.d.ts.map +1 -0
  526. package/dist/utils/topicLabel.js +12 -0
  527. package/dist/utils/topicLabel.js.map +1 -0
  528. package/dist/utils/topicRequest.d.ts +8 -5
  529. package/dist/utils/topicRequest.d.ts.map +1 -1
  530. package/dist/utils/topicRequest.js +9 -7
  531. package/dist/utils/topicRequest.js.map +1 -1
  532. package/npm-shrinkwrap.json +1003 -0
  533. package/package.json +5 -3
  534. package/remoteRun/ensureNode.sh +288 -0
  535. package/remoteRun/runner.sh +2252 -115
  536. package/agent-plugin/skills/charness-manager/SKILL.md +0 -157
  537. package/remoteRun/pickNode.sh +0 -65
package/dist/bot.js CHANGED
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.COMMANDS_MENU = exports.telegramInbound = exports.routedCommandTriggerDeps = void 0;
37
37
  exports.getStartReadyMessage = getStartReadyMessage;
38
38
  exports.checkIsRoutedCommand = checkIsRoutedCommand;
39
+ exports.getTalkerAllowedCommandNames = getTalkerAllowedCommandNames;
39
40
  exports.handleRoutedCommandMessage = handleRoutedCommandMessage;
40
41
  exports.deliverRoutedCommand = deliverRoutedCommand;
41
42
  exports.postReattachRecap = postReattachRecap;
@@ -101,6 +102,10 @@ const folderName_1 = require("./folderName");
101
102
  const threadRouting_1 = require("./threadRouting");
102
103
  const accessControl_1 = require("./accessControl");
103
104
  const inbound_1 = require("./connectors/telegram/inbound");
105
+ const topicTalkerMemory_1 = require("./topicTalkerMemory");
106
+ const talkerAccess_1 = require("./utils/talkerAccess");
107
+ const authorMark_1 = require("./utils/authorMark");
108
+ const personLabel_1 = require("./utils/personLabel");
104
109
  const outbound_1 = require("./connectors/telegram/outbound");
105
110
  const commandRouter_1 = require("./platform/commandRouter");
106
111
  const outbound_2 = require("./platform/outbound");
@@ -157,6 +162,8 @@ const adoptedToolList_1 = require("./utils/adoptedToolList");
157
162
  const lostWork_1 = require("./utils/lostWork");
158
163
  const jsonStreamPendingWork_1 = require("./utils/jsonStreamPendingWork");
159
164
  const compactOnIdle_1 = require("./utils/compactOnIdle");
165
+ const compactSelfReviewFlags_1 = require("./utils/compactSelfReviewFlags");
166
+ const openCodeCompactPlugin_1 = require("./utils/openCodeCompactPlugin");
160
167
  const fileSendService_1 = require("./utils/fileSendService");
161
168
  const messageSendService_1 = require("./utils/messageSendService");
162
169
  const fileSendGateway_1 = require("./connectors/telegram/fileSendGateway");
@@ -198,6 +205,8 @@ const jsonStreamHost_1 = require("./utils/jsonStreamHost");
198
205
  const runLedger_1 = require("./scheduler/runLedger");
199
206
  const delivery_1 = require("./scheduler/delivery");
200
207
  const checkRun_1 = require("./scheduler/checkRun");
208
+ const agentEnvironment_1 = require("./utils/agentEnvironment");
209
+ const folderGit_1 = require("./utils/folderGit");
201
210
  const checkStatus_1 = require("./scheduler/checkStatus");
202
211
  const workerActivity_1 = require("./scheduler/workerActivity");
203
212
  const engine_1 = require("./scheduler/engine");
@@ -244,6 +253,7 @@ const callbackToast_2 = require("./connectors/telegram/commands/callbackToast");
244
253
  const compaction_1 = require("./connectors/telegram/commands/compaction");
245
254
  const autoContinueLimits_1 = require("./connectors/telegram/commands/autoContinueLimits");
246
255
  const botSkills_2 = require("./connectors/telegram/commands/botSkills");
256
+ const topicAccess_1 = require("./connectors/telegram/commands/topicAccess");
247
257
  const taskAgents_1 = require("./connectors/telegram/commands/taskAgents");
248
258
  const runners_1 = require("./connectors/telegram/commands/runners");
249
259
  const gateWrapper_1 = require("./runners/gateWrapper");
@@ -251,6 +261,7 @@ const hubAddress_1 = require("./runners/hubAddress");
251
261
  const hubAddressCandidates_1 = require("./runners/hubAddressCandidates");
252
262
  const hubPaths_1 = require("./runners/hubPaths");
253
263
  const hubPairing_1 = require("./runners/hubPairing");
264
+ const runnerGroups_1 = require("./runners/runnerGroups");
254
265
  const runnersOverview_1 = require("./runners/runnersOverview");
255
266
  const ssh_1 = require("./remoteRun/ssh");
256
267
  const claudeAccounts_1 = require("./connectors/telegram/commands/claudeAccounts");
@@ -275,6 +286,10 @@ const backendSwitchPlan_1 = require("./utils/backendSwitchPlan");
275
286
  const selfUpdate_1 = require("./connectors/telegram/commands/selfUpdate");
276
287
  const stt_1 = require("./connectors/telegram/commands/stt");
277
288
  const claudeApiSpend_1 = require("./utils/claudeApiSpend");
289
+ const claudeProfileUsageViews_1 = require("./utils/claudeProfileUsageViews");
290
+ const claudeApiAgentStop_1 = require("./utils/claudeApiAgentStop");
291
+ const claudeApiCredit_1 = require("./utils/claudeApiCredit");
292
+ const claudeApiCreditRecheck_1 = require("./utils/claudeApiCreditRecheck");
278
293
  const claudeProfileUsageLines_1 = require("./utils/claudeProfileUsageLines");
279
294
  const resolveBinary_1 = require("./utils/resolveBinary");
280
295
  const runnerSummary_1 = require("./remoteRun/runnerSummary");
@@ -324,7 +339,8 @@ function parseEnv() {
324
339
  // (without it the DM surface would have no access authority — any user can DM a
325
340
  // bot). For `both` it is OPTIONAL: set → the DM surface is active; unset → the
326
341
  // DM surface is INERT (group-only) and boot logs a notice, so default `both`
327
- // stays backward-compatible with a bare group-only deploy. Ignored in `group`.
342
+ // stays backward-compatible with a bare group-only deploy. In `group` it only
343
+ // decides who may pair the bot with a group (`getPairingRefusal`).
328
344
  const ownerUserIdRaw = (process.env.OWNER_USER_ID ?? '').trim();
329
345
  let ownerUserId = NaN;
330
346
  if (ownerUserIdRaw) {
@@ -608,8 +624,21 @@ const adminCache = new accessControl_1.AdminCache({
608
624
  return Promise.resolve([]);
609
625
  return telegramInbound.listMembersWithElevatedRights(groupId.toString());
610
626
  },
627
+ // The admins' @usernames, refreshed with the ids: `/access add @name` refuses an admin it has not seen write.
628
+ fetchElevatedMemberHandles: () => {
629
+ const groupId = getAllowedGroupId();
630
+ if (groupId === null)
631
+ return Promise.resolve([]);
632
+ return telegramInbound.listHandlesOfMembersWithElevatedRights(groupId.toString());
633
+ },
611
634
  ttlMs: accessControl_1.ADMIN_CACHE_TTL_MS,
612
635
  });
636
+ /**
637
+ * The people who wrote in a topic and were ignored, and the @usernames seen writing in the served group
638
+ * (`topicTalkerMemory.ts`): in memory only, a convenience for an admin adding a talker. Fed by `noteServedGroupSender`.
639
+ */
640
+ const recentTopicWriters = (0, topicTalkerMemory_1.createRecentWriters)();
641
+ const seenGroupSenders = (0, topicTalkerMemory_1.createSeenSenders)();
613
642
  /**
614
643
  * @description True iff the sender of `ctx` may use the bot — decided PER CHAT,
615
644
  * which is the single source of truth for access on each surface:
@@ -646,6 +675,45 @@ async function checkIsForumAdmin(chatId, userId) {
646
675
  return false;
647
676
  }
648
677
  }
678
+ /**
679
+ * @description Whether `userId` created group `chatId` (Telegram's `creator` status). A member read that fails is told apart:
680
+ * the group itself not answering (deleted, the bot removed from it) is `unreadable`; a group that answers is `notCreator` —
681
+ * a sender who is no member at all reads that way too.
682
+ */
683
+ async function readGroupCreatorship(chatId, userId) {
684
+ try {
685
+ return (await bot.telegram.getChatMember(chatId, userId)).status === 'creator' ? 'creator' : 'notCreator';
686
+ }
687
+ catch (memberError) {
688
+ try {
689
+ await bot.telegram.getChat(chatId);
690
+ return 'notCreator';
691
+ }
692
+ catch (groupError) {
693
+ console.warn(`[pair] the served group ${chatId} cannot be read:`, groupError instanceof Error ? groupError.message : groupError, '— member read:', memberError instanceof Error ? memberError.message : memberError);
694
+ return 'unreadable';
695
+ }
696
+ }
697
+ }
698
+ /**
699
+ * @description Why `senderId` may not pair the bot with `targetGroupId` (`null`: allowed) — the rule is
700
+ * {@link getPairingRefusal}'s, fed with this instance's owner, the group served now and the Telegram reads it needs.
701
+ */
702
+ function getPairingRefusalFor(senderId, targetGroupId) {
703
+ const ownerUserId = getOwnerUserId();
704
+ const currentGroupId = getAllowedGroupId();
705
+ return (0, threadRouting_1.getPairingRefusal)({ ownerUserId: Number.isFinite(ownerUserId) ? ownerUserId : null, senderId, currentGroupId, targetGroupId }, {
706
+ checkIsTargetGroupAdmin: () => checkIsForumAdmin(targetGroupId, senderId),
707
+ readCurrentGroupCreatorship: () => (currentGroupId === null ? Promise.resolve('notCreator') : readGroupCreatorship(currentGroupId, senderId)),
708
+ });
709
+ }
710
+ /** The refusal each {@link PairingRefusal} answers `/pair` with. */
711
+ const pairingRefusalTextKeys = {
712
+ notOwner: 'pair.not_owner',
713
+ notCurrentCreator: 'pair.not_current_creator',
714
+ currentGroupUnreadable: 'pair.current_group_unreadable',
715
+ notAdmin: 'pair.not_admin',
716
+ };
649
717
  // Telegraf builds a NEW `Telegram` client for every update (`ctx.telegram`, behind every `ctx.reply`, `ctx.answerCbQuery`
650
718
  // and `ctx.editMessageText`) from `bot.telegram.options`, so the wiring of `bot.telegram` does not reach it and an
651
719
  // `http://` root drops the agent again. Wire it before any handler can use it.
@@ -705,6 +773,30 @@ bot.use(async (ctx, next) => {
705
773
  await tryAutoPair(ctx);
706
774
  return next();
707
775
  });
776
+ // What the bot learns from every message of the served group, before any handler gates it: the sender's name and @username
777
+ // (a talker's entries keep up with a rename), an invitation that waited for this person's first message turns into a grant — so
778
+ // a message that comes with it is already a talker's — and a stranger's message is remembered for the add screen.
779
+ bot.use(async (ctx, next) => {
780
+ try {
781
+ await noteServedGroupSender(ctx);
782
+ }
783
+ catch (e) {
784
+ console.warn('[access] noting the sender of an update failed:', e instanceof Error ? e.message : e);
785
+ }
786
+ return next();
787
+ });
788
+ // Default-deny for talkers on buttons: a person an admin let talk to the agent here may tap only the agent's own question
789
+ // buttons (`checkIsTalkerCallback`). Every other tap is refused with one toast, here, so no handler or module has to know a
790
+ // talker exists — each of them keeps asking the admin gate.
791
+ bot.use(async (ctx, next) => {
792
+ if (ctx.callbackQuery && (await checkIsTalkerTapRefused(ctx))) {
793
+ await ctx.answerCbQuery((0, i18n_1.t)('access.adminOnlyButtonToast')).catch((e) => {
794
+ console.warn('[access] answering a refused tap failed:', e instanceof Error ? e.message : e);
795
+ });
796
+ return;
797
+ }
798
+ return next();
799
+ });
708
800
  // ═══════════════════════════════════════════════════════════════════════════════
709
801
  // Constants
710
802
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -870,9 +962,9 @@ async function openTopicRequest(key, text, intake, messageContext) {
870
962
  // AGAIN when the session never took it in; the raw text would come back without the forwarded mark or the quote.
871
963
  const promptBody = getPromptWithThreadMessageContext(key, text, messageContext);
872
964
  const request = await topicRequestLedger.createRequest(key, (0, topicRequest_1.getTopicRequestOrigin)(intake), {
873
- createPrompt: (requestId, supersededRequestIds) => (0, topicRequest_1.buildTopicRequestPrompt)({ requestId, source: intake.source, view, supersededRequestIds, promptBody }),
965
+ createPrompt: (requestId, supersededRequestIds) => (0, topicRequest_1.buildTopicRequestPrompt)({ requestId, source: intake.source, view, supersededRequestIds, promptBody, sender: messageContext?.nonOperatorSender }),
874
966
  });
875
- return { header: (0, topicRequest_1.buildTopicRequestHeader)(request.id, intake.source, view, request.supersededRequestIds), requestId: request.id };
967
+ return { header: (0, topicRequest_1.buildTopicRequestHeader)(request.id, intake.source, view, request.supersededRequestIds, messageContext?.nonOperatorSender), requestId: request.id };
876
968
  }
877
969
  /**
878
970
  * @description Where a topic request goes once its prompt came back from the prompt path (`requests/topicRequestSettle.ts`): the
@@ -2202,6 +2294,7 @@ const { cancelPendingLogin, checkIsAuthLoginAwaitingCode, cancelClaudeAuthLogin,
2202
2294
  execFileAsync,
2203
2295
  onClaudeProfileAuthStatus: (key, profile, status) => claudeProfileAuthStatusSink?.(key, profile, status) ?? Promise.resolve(),
2204
2296
  onClaudeProfileApiKey: (key, profile, apiKey) => claudeProfileApiKeySink?.(key, profile, apiKey) ?? Promise.resolve((0, i18n_1.t)('account.apiKeyNoDirectory', { name: profile.name })),
2297
+ checkIsProfileMissingFromLimitsList: (name) => (0, fallbackChain_1.checkIsClaudeProfileMissingFromChain)(state.getFallbackChain(), name),
2205
2298
  });
2206
2299
  /**
2207
2300
  * @description Buffers prompts typed while an agent session is still booting so
@@ -2607,10 +2700,11 @@ async function tryAutoPair(ctx) {
2607
2700
  return;
2608
2701
  const chat = getRouteChat(ctx);
2609
2702
  // While unpaired, log every incoming update so the operator can see
2610
- // exactly what reaches the bot. Without this, the three ways pairing
2611
- // can silently fail — privacy mode (no update at all), a non-forum chat,
2612
- // or a sender who isn't a group admin — are indistinguishable from "bot
2613
- // is broken". Gated to pairing mode so normal operation stays quiet.
2703
+ // exactly what reaches the bot. Without this, the ways pairing can
2704
+ // silently fail — privacy mode (no update at all), a non-forum chat, or a
2705
+ // sender who may not pair (not the owner, not a group admin) — are
2706
+ // indistinguishable from "bot is broken". Gated to pairing mode so normal
2707
+ // operation stays quiet.
2614
2708
  if (!isGroupLockedByEnv && getAllowedGroupId() === null) {
2615
2709
  console.log(`[pair] incoming ${ctx.updateType} update: chat=${chat?.id} type=${chat?.type} ` +
2616
2710
  `is_forum=${chat?.is_forum} from=${ctx.from?.id}`);
@@ -2622,15 +2716,18 @@ async function tryAutoPair(ctx) {
2622
2716
  });
2623
2717
  if (candidate === null)
2624
2718
  return;
2625
- // Authority probe: only a creator/administrator of the candidate group may
2626
- // pair the bot, so a random group the bot is added to can't hijack it.
2719
+ // Who may pair (`getPairingRefusal`): with an owner set, the owner alone; without one, an administrator of the group —
2720
+ // the first pairing only, which is all auto-pairing ever is. Administering the group alone proves nothing: anyone who
2721
+ // makes a group and adds the bot is its creator.
2627
2722
  const userId = ctx.from?.id;
2628
- if (!userId || !(await checkIsForumAdmin(candidate, userId))) {
2629
- console.warn(`[pair] ignored pairing from chat ${candidate} user ${userId ?? '?'} (not a group admin)`);
2723
+ const refusal = userId ? await getPairingRefusalFor(userId, candidate) : 'notAdmin';
2724
+ if (refusal !== null) {
2725
+ console.warn(`[pair] ignored pairing from chat ${candidate} user ${userId ?? '?'} (${refusal})`);
2630
2726
  return;
2631
2727
  }
2632
2728
  effectiveGroupId = candidate;
2633
2729
  await state.setPairedGroupId(candidate);
2730
+ await state.dropTopicTalkersOfOtherChats(candidate);
2634
2731
  adminCache.invalidate();
2635
2732
  console.log(`[pair] auto-paired forum supergroup ${candidate} (persisted to state.json)`);
2636
2733
  const key = getThreadKey(ctx) ?? (0, sessionKeyCodec_1.makeTelegramKey)(candidate, threadRouting_1.GENERAL_THREAD_ID);
@@ -2659,15 +2756,101 @@ async function authoriseContext(ctx) {
2659
2756
  }
2660
2757
  return null;
2661
2758
  }
2662
- // Refresh the group-title cache from this authorised update — supergroups
2663
- // always carry `chat.title`. Feeds the thread-context preamble (S2). Cheap,
2664
- // idempotent, and the only place every accepted update funnels through. A
2665
- // private chat (DM key) has no `title`, so there is nothing to cache (the
2666
- // preamble falls back to the bot name) — skip it explicitly.
2759
+ noteGroupTitle(ctx, key);
2760
+ return key;
2761
+ }
2762
+ /**
2763
+ * Refresh the group-title cache from an accepted update — supergroups always carry `chat.title`. Feeds the thread-context
2764
+ * preamble (S2). Cheap, idempotent, and the one place every accepted update funnels through. A private chat (DM key) has
2765
+ * no `title`, so there is nothing to cache (the preamble falls back to the bot name) — skip it explicitly.
2766
+ */
2767
+ function noteGroupTitle(ctx, key) {
2667
2768
  if (!checkIsDmKey(key) && ctx.chat && 'title' in ctx.chat && ctx.chat.title) {
2668
2769
  groupTitleCache.set(ctx.chat.id, ctx.chat.title);
2669
2770
  }
2670
- return key;
2771
+ }
2772
+ /** The General topic of the group `key` is in — the one whose talker list is group-wide. */
2773
+ function getGroupGeneralKey(key) {
2774
+ return (0, sessionKeyCodec_1.makeTelegramKey)((0, sessionKeyCodec_1.getTelegramChatId)(key), threadRouting_1.GENERAL_THREAD_ID);
2775
+ }
2776
+ /**
2777
+ * @description What the sender of a group update is to the bot in its topic — an admin, a talker, or nobody — with the
2778
+ * topic's key; `null` outside a group topic (a foreign chat, no sender, the owner's DM, which has no talkers). The ONE place
2779
+ * the role is computed: the speaker gate, the sender tracking and the button check all read it.
2780
+ */
2781
+ async function getGroupSpeakerRole(ctx) {
2782
+ const userId = ctx.from?.id;
2783
+ if (userId === undefined)
2784
+ return null;
2785
+ const key = getThreadKey(ctx);
2786
+ if (key === null || checkIsDmKey(key))
2787
+ return null;
2788
+ const role = (0, accessControl_1.getSenderRole)({
2789
+ userId: userId.toString(),
2790
+ adminIds: await adminCache.getAdminIds(),
2791
+ talkerIds: state.getEffectiveTalkerIds(key, getGroupGeneralKey(key)),
2792
+ });
2793
+ return { key, role };
2794
+ }
2795
+ /**
2796
+ * @description The speaker gate: an admin anywhere (the owner in the DM), or a talker in the group topic whose list — or
2797
+ * General's — holds them; nobody else. It sits NEXT TO {@link authoriseContext}, which stays the admin-only gate: only the
2798
+ * routes a talker may use call this one (talking to the agent: text, voice, files, albums; answering its questions), and the
2799
+ * role travels from here as a value, so a route cannot ask «is this a talker?» a second way. Everything else keeps asking
2800
+ * `authoriseContext` and so refuses a talker without knowing one exists.
2801
+ */
2802
+ async function authoriseTopicSpeaker(ctx) {
2803
+ const groupSpeaker = await getGroupSpeakerRole(ctx);
2804
+ if (groupSpeaker?.role === 'talker') {
2805
+ noteGroupTitle(ctx, groupSpeaker.key);
2806
+ return { key: groupSpeaker.key, role: 'talker' };
2807
+ }
2808
+ const adminKey = await authoriseContext(ctx);
2809
+ return adminKey === null ? null : { key: adminKey, role: 'admin' };
2810
+ }
2811
+ /** @description Whether a tap is a talker's on a button that is not the agent's own question — refused with a toast, never handled. */
2812
+ async function checkIsTalkerTapRefused(ctx) {
2813
+ const callbackData = ctx.callbackQuery && 'data' in ctx.callbackQuery ? ctx.callbackQuery.data : undefined;
2814
+ if ((0, talkerAccess_1.checkIsTalkerCallback)(callbackData))
2815
+ return false;
2816
+ return (await getGroupSpeakerRole(ctx))?.role === 'talker';
2817
+ }
2818
+ /**
2819
+ * @description Learn from a message of the served group, whoever sent it and whatever the gates later decide: remember the
2820
+ * @username (so `/access add @name` can name a person the Bot API cannot look up), keep a talker's entries in step with a
2821
+ * rename, turn an invitation that waited for this person into a grant (announced in the topic that waited), and — for a
2822
+ * stranger — remember the topic they wrote in. An admin is never invited and never offered as a stranger; a bot is nobody's talker.
2823
+ */
2824
+ async function noteServedGroupSender(ctx) {
2825
+ const user = ctx.from;
2826
+ // A post made as a channel or as the group (a linked channel's post carries Telegram's service user in `from`) is no person: it is
2827
+ // never remembered, never offered as a stranger to add, never an invitation's match.
2828
+ if (!ctx.message || !user || user.is_bot || ctx.message.sender_chat)
2829
+ return;
2830
+ // A join or a leave is not writing: `from` of such a service message is a person who only came or went, and an invitation that
2831
+ // waits for «the first message» must not be spent on it (nor the person offered as a writer, nor announced while leaving).
2832
+ if (!(0, inbound_1.checkIsWrittenMessage)(ctx.message))
2833
+ return;
2834
+ const groupSpeaker = await getGroupSpeakerRole(ctx);
2835
+ if (groupSpeaker === null)
2836
+ return;
2837
+ const person = { userId: user.id.toString(), username: user.username, name: (0, inbound_1.getDisplayName)(user) };
2838
+ seenGroupSenders.noteSender(person);
2839
+ state.updateTalkerIdentity(person);
2840
+ if (groupSpeaker.role === 'admin')
2841
+ return;
2842
+ const grants = await state.resolveTopicInvites(person);
2843
+ for (const grant of grants) {
2844
+ const topicKey = (0, sessionKey_1.tryKeyFromString)(grant.threadKey);
2845
+ if (topicKey === null)
2846
+ continue;
2847
+ await replyToThread(topicKey, withThreadLocale(topicKey, () => (0, i18n_1.t)('access.inviteResolvedNotice', { person: (0, personLabel_1.formatPersonLabel)(person) })));
2848
+ }
2849
+ // The role is read AGAIN: a grant that came from General's invitation makes the person a talker in this topic too, and one for
2850
+ // another topic does not.
2851
+ const isTalkerNow = state.getEffectiveTalkerIds(groupSpeaker.key, getGroupGeneralKey(groupSpeaker.key)).has(person.userId);
2852
+ if (groupSpeaker.role === 'none' && !isTalkerNow)
2853
+ recentTopicWriters.noteIgnoredWriter((0, sessionKey_1.keyToString)(groupSpeaker.key), person);
2671
2854
  }
2672
2855
  // ═══════════════════════════════════════════════════════════════════════════════
2673
2856
  // Send helpers — replyToThread + auto-track + error routing
@@ -4418,6 +4601,8 @@ function getPerTurnRefusal(key) {
4418
4601
  */
4419
4602
  async function persistSessionStart(key, adapter) {
4420
4603
  await (0, persistAdapterSessionIds_1.persistAdapterSessionIds)(key, adapter, state);
4604
+ // The session id is new or changed: the hook's and the plugin's flags for it (`/compact_self_review`) are due.
4605
+ syncThreadCompactSelfReviewFlags(key);
4421
4606
  if ((0, adapterNames_1.checkIsJsonStreamBackend)(adapter.name) && botMcpToolDigestReader) {
4422
4607
  await state.setAgentMcpToolDigest(key, botMcpToolDigestReader(key));
4423
4608
  }
@@ -5042,6 +5227,7 @@ function getPromptWithThreadContext(key, text) {
5042
5227
  key,
5043
5228
  subdir,
5044
5229
  timezone: getCurrentTimezone(),
5230
+ hasTalkers: (0, sessionKeyCodec_1.checkIsTelegramKey)(key) && getMessageAccess(key).talkerIds.size > 0,
5045
5231
  });
5046
5232
  const kStr = (0, sessionKey_1.keyToString)(key);
5047
5233
  if (!(0, threadContextPreamble_1.checkShouldInjectPreamble)(preamble, threadContextMarkers.get(kStr))) {
@@ -5062,7 +5248,19 @@ function getPromptWithThreadContext(key, text) {
5062
5248
  * is looked up among the files this thread took in.
5063
5249
  */
5064
5250
  function getMessageContext(key, message) {
5065
- return (0, inbound_1.getTelegramMessageContext)(message, { userId: bot.botInfo?.id }, (meta) => findThreadSavedFile(key, meta));
5251
+ return (0, inbound_1.getTelegramMessageContext)(message, { userId: bot.botInfo?.id }, getMessageAccess(key), (meta) => findThreadSavedFile(key, meta));
5252
+ }
5253
+ /**
5254
+ * @description Who is the operator and who may talk in the conversation `key`: the two sets the agent-facing marks tell the
5255
+ * operator's words from anyone else's by (a talker's message, a reply to a stranger's). Read synchronously off the admin cache
5256
+ * the gate refreshed a moment ago and the talker lists, so a route cannot be handed a role that disagrees with the gate's, and
5257
+ * none can forget to ask. The DM surface is the owner's private chat: the owner is the operator and nobody else writes there.
5258
+ * In a group the talkers are the topic's own list plus General's, which is group-wide.
5259
+ */
5260
+ function getMessageAccess(key) {
5261
+ if (checkIsDmKey(key))
5262
+ return { adminIds: new Set([getOwnerUserId().toString()]), talkerIds: new Set() };
5263
+ return { adminIds: adminCache.getCachedAdminIds(), talkerIds: state.getEffectiveTalkerIds(key, getGroupGeneralKey(key)) };
5066
5264
  }
5067
5265
  /**
5068
5266
  * @description The bot's saved copy of a file sent to this thread earlier
@@ -5151,8 +5349,8 @@ void telegramInbound.start(async (event) => {
5151
5349
  * command handlers stop reading the telegraf context and move into
5152
5350
  * `connectors/telegram/` — the follow-up decomposition, not a typing change.
5153
5351
  */
5154
- function command(name, handler) {
5155
- commandRouter.register(name, (event, parsed) => handler(event.raw, event.key, parsed));
5352
+ function command(name, handler, options) {
5353
+ commandRouter.register(name, (event, parsed) => handler(event.raw, event.key, parsed), options);
5156
5354
  }
5157
5355
  /**
5158
5356
  * The ports the Telegram command modules (`connectors/telegram/commands/`) take from this file. `state` is
@@ -5169,13 +5367,14 @@ const botCore = {
5169
5367
  deleteThreadMessage,
5170
5368
  deleteThreadMessageDetailed,
5171
5369
  authoriseContext,
5370
+ authoriseSpeaker: authoriseTopicSpeaker,
5172
5371
  withThreadLocale,
5173
5372
  checkIsGeneral,
5174
5373
  updatePinnedStatus,
5175
5374
  cancelConversationRequest,
5176
5375
  wakeSleepingSession,
5177
5376
  };
5178
- const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, markThreadTurnProducedOutput, clearThreadCompaction, rearmThreadIdleTimer, armDeferredCompaction, checkIsDeferredCompactionArmed, threadsCompacting, answerReAskedQuestionByNumber, reAskInterruptedQuestion, restoreReAskedQuestion, closeSavedReAskedQuestion, closeReAskedQuestion, registerCompactionCommands, registerCompactionCallbacks, } = (0, compaction_1.createCompaction)({
5377
+ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, markThreadTurnProducedOutput, postOwnCompactionInstructionGaps, routeStreamedCompactionSummaryTail, clearThreadCompaction, rearmThreadIdleTimer, armDeferredCompaction, checkIsDeferredCompactionArmed, threadsCompacting, answerReAskedQuestionByNumber, reAskInterruptedQuestion, restoreReAskedQuestion, closeSavedReAskedQuestion, closeReAskedQuestion, syncThreadCompactSelfReviewFlags, syncAllCompactSelfReviewFlags, registerCompactionCommands, registerCompactionCallbacks, } = (0, compaction_1.createCompaction)({
5179
5378
  ...botCore,
5180
5379
  startTypingLoader,
5181
5380
  forwardPromptToAgent: async (key, adapter, text) => { await forwardPromptToAgent(key, adapter, text); },
@@ -5189,11 +5388,13 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
5189
5388
  resumeSleepingSessionForCompaction: async (key) => (await ensureAgentSession(key, { isResumeOnly: true })).ok && (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key),
5190
5389
  getThreadAdapter: createAdapter_1.getThreadAdapter,
5191
5390
  // An answer to the agent's own question is never a request (S7), even delivered as a prompt.
5192
- deliverLabel: (key, label) => withThreadLocale(key, () => deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), label, null)),
5391
+ // The label of a re-asked question reaches the agent as a prompt; a topic member's carries their mark, the operator's stays bare.
5392
+ deliverLabel: (key, label, messageContext) => withThreadLocale(key, () => deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), label, null, undefined, messageContext)),
5193
5393
  resumeSleepingSessionForPrompt: (key) => resumeSleepingSessionForPrompt(key),
5194
5394
  checkIsStarting: (key) => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
5195
5395
  closeOrphanQuestionMessage,
5196
5396
  notePersonActivity,
5397
+ compactSelfReviewFlagDirs: (0, compactSelfReviewFlags_1.getCompactSelfReviewFlagDirs)((0, state_1.resolveDataDir)(), (0, openCodeCompactPlugin_1.resolveOpenCodeGlobalPluginDir)(process.env)),
5197
5398
  });
5198
5399
  /**
5199
5400
  * @description True iff the neutral router owns `name`, i.e. a `/name` message
@@ -5206,6 +5407,13 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
5206
5407
  function checkIsRoutedCommand(name) {
5207
5408
  return commandRouter.checkIsRegistered(name);
5208
5409
  }
5410
+ /**
5411
+ * The names a talker may run, sorted. Exported so a test pins the exact set against the REAL registration table: a new command
5412
+ * is admin-only unless somebody flags it on purpose, and the flag cannot be added unnoticed.
5413
+ */
5414
+ function getTalkerAllowedCommandNames() {
5415
+ return commandRouter.listTalkerAllowedNames();
5416
+ }
5209
5417
  /** `/esc` and its other names: the interrupt, which also cancels a pending sign-in or `/topic` prompt first. */
5210
5418
  const escapeCommandNames = ['esc', 'escape', 'interrupt'];
5211
5419
  /** @description Whether `messageText` is one of the {@link escapeCommandNames} (`@botmention` tolerated). */
@@ -5264,10 +5472,20 @@ async function handleRoutedCommandMessage(ctx, next, deps) {
5264
5472
  const parsed = deps.getCommand(ctx.message);
5265
5473
  if (!parsed || !deps.checkIsRegistered(parsed.name))
5266
5474
  return next();
5267
- const key = await deps.authorise(ctx);
5268
- if (!key)
5475
+ const speaker = await deps.authorise(ctx);
5476
+ if (!speaker)
5269
5477
  return;
5270
- await deps.exitPendingInputModes(key, ctx.message.text);
5478
+ const { key } = speaker;
5479
+ if (speaker.role === 'talker') {
5480
+ if (!deps.checkIsTalkerAllowed(parsed.name)) {
5481
+ await deps.refuseTalkerCommand(key);
5482
+ return;
5483
+ }
5484
+ // A talker's command never ends an input step an admin armed: it is not the admin's own next word.
5485
+ }
5486
+ else {
5487
+ await deps.exitPendingInputModes(key, ctx.message.text);
5488
+ }
5271
5489
  deps.noteActivity(key);
5272
5490
  await deps.deliverInbound(ctx, key);
5273
5491
  }
@@ -5294,7 +5512,11 @@ function deliverRoutedCommand(ctx, key) {
5294
5512
  exports.routedCommandTriggerDeps = {
5295
5513
  getCommand: (message) => (0, inbound_1.getTelegramCommand)(message, { username: bot.botInfo?.username }),
5296
5514
  checkIsRegistered: checkIsRoutedCommand,
5297
- authorise: authoriseContext,
5515
+ authorise: authoriseTopicSpeaker,
5516
+ checkIsTalkerAllowed: (name) => commandRouter.checkIsTalkerAllowed(name),
5517
+ refuseTalkerCommand: async (key) => {
5518
+ await replyToThread(key, (0, i18n_1.t)('access.adminOnlyCommandRefusal'));
5519
+ },
5298
5520
  exitPendingInputModes,
5299
5521
  noteActivity: noteThreadActivity,
5300
5522
  deliverInbound: deliverRoutedCommand,
@@ -5399,7 +5621,7 @@ command('status', async (_ctx, key) => {
5399
5621
  timezone,
5400
5622
  timezoneNow: (0, timezone_1.formatZoneNow)(timezone, nowMs),
5401
5623
  }));
5402
- });
5624
+ }, { isTalkerAllowed: true });
5403
5625
  /** The `/language` argument: the first token, lower-cased (locale codes are case-insensitive). */
5404
5626
  function getLanguageCommandArg(parsed) {
5405
5627
  return (parsed.args[0] ?? '').toLowerCase();
@@ -6051,24 +6273,28 @@ command('version', async (_ctx, key) => {
6051
6273
  command('whoami', async (ctx, key) => {
6052
6274
  const userId = ctx.from?.id ?? 0;
6053
6275
  // Per-chat authority is the single source of truth now (owner for a DM chat,
6054
- // the served group's admins for the group chat); `checkIsAllowedUser` already
6055
- // encodes the surface gate, so no extra group-id clause is needed.
6056
- const allowed = await checkIsAllowedUser(ctx);
6276
+ // the served group's admins for the group chat); the speaker gate already
6277
+ // encodes the surface gate, so no extra group-id clause is needed. A talker is
6278
+ // told what they are here: allowed to talk in THIS topic, nothing more.
6279
+ const speaker = await authoriseTopicSpeaker(ctx);
6280
+ const allowed = speaker?.role === 'talker' ? (0, i18n_1.t)('access.whoamiTalkerRole') : speaker ? 'yes' : 'no';
6057
6281
  const binding = state.getBinding(key);
6058
6282
  await replyToThread(key, (0, i18n_1.t)('whoami.report', {
6059
6283
  userId,
6060
6284
  chatId: (0, sessionKeyCodec_1.getTelegramChatId)(key),
6061
6285
  threadId: (0, sessionKeyCodec_1.getTelegramThreadId)(key),
6062
- allowed: allowed ? 'yes' : 'no',
6286
+ allowed,
6063
6287
  binding: binding ? `\`${binding.subdir}\`` : (0, i18n_1.t)('whoami.binding_unbound'),
6064
6288
  }), { parse_mode: 'Markdown' });
6065
- });
6289
+ }, { isTalkerAllowed: true });
6066
6290
  /**
6067
6291
  * @description Re-point the bot to the forum supergroup this command was
6068
6292
  * sent in. Registered raw (not via the group-gated `command()` wrapper) so
6069
6293
  * it can switch the bot from one group to another. Refused when the id is
6070
- * locked by `ALLOWED_GROUP_ID` env. Only a creator/administrator of the target
6071
- * group may pair, so a random group can't hijack the binding.
6294
+ * locked by `ALLOWED_GROUP_ID` env. Who may pair is `getPairingRefusal`'s rule:
6295
+ * with an owner set, only the owner; without one, once a group is served,
6296
+ * only that group's creator — never merely an administrator of the new group,
6297
+ * which whoever made it is.
6072
6298
  */
6073
6299
  bot.command('pair', async (ctx, next) => {
6074
6300
  // A forwarded `/pair` is somebody else's words: it re-points the bot to no group, and it is not swallowed either —
@@ -6100,18 +6326,26 @@ bot.command('pair', async (ctx, next) => {
6100
6326
  await replyToThread(replyKey, (0, i18n_1.t)('pair.only_forum')).catch(() => { });
6101
6327
  return;
6102
6328
  }
6103
- if (!(await checkIsForumAdmin(routeChat.id, userId))) {
6104
- await replyToThread(replyKey, (0, i18n_1.t)('pair.not_admin')).catch(() => { });
6329
+ const refusal = await getPairingRefusalFor(userId, routeChat.id);
6330
+ if (refusal !== null) {
6331
+ console.warn(`[pair] refused /pair from chat ${routeChat.id} user ${userId} (${refusal})`);
6332
+ await replyToThread(replyKey, (0, i18n_1.t)(pairingRefusalTextKeys[refusal])).catch(() => { });
6105
6333
  return;
6106
6334
  }
6107
6335
  effectiveGroupId = routeChat.id;
6108
6336
  await state.setPairedGroupId(routeChat.id);
6337
+ await state.dropTopicTalkersOfOtherChats(routeChat.id);
6109
6338
  adminCache.invalidate();
6110
6339
  console.log(`[pair] re-paired to forum supergroup ${routeChat.id} via /pair`);
6111
6340
  const key = getThreadKey(ctx) ?? (0, sessionKeyCodec_1.makeTelegramKey)(routeChat.id, threadRouting_1.GENERAL_THREAD_ID);
6112
6341
  await replyToThread(key, (0, i18n_1.t)('pair.success', { groupId: routeChat.id }));
6113
6342
  });
6114
- command('help', async (_ctx, key) => {
6343
+ command('help', async (ctx, key) => {
6344
+ // A talker is shown what they may do — talk to the agent and four commands — never the admin command list.
6345
+ if ((await authoriseTopicSpeaker(ctx))?.role === 'talker') {
6346
+ await replyToThread(key, (0, i18n_1.t)('access.helpTalker'));
6347
+ return;
6348
+ }
6115
6349
  if (checkIsGeneral(key)) {
6116
6350
  await replyToThread(key, (0, i18n_1.t)('help.general'), { parse_mode: 'Markdown' });
6117
6351
  return;
@@ -6127,7 +6361,7 @@ command('help', async (_ctx, key) => {
6127
6361
  return;
6128
6362
  }
6129
6363
  await replyToThread(key, (0, i18n_1.t)('help.thread_bound', { subdir: binding.subdir }), { parse_mode: 'Markdown' });
6130
- });
6364
+ }, { isTalkerAllowed: true });
6131
6365
  function formatBytes(n) {
6132
6366
  if (n < 1024)
6133
6367
  return `${n} B`;
@@ -6135,6 +6369,8 @@ function formatBytes(n) {
6135
6369
  return `${(n / 1024).toFixed(1)} KB`;
6136
6370
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
6137
6371
  }
6372
+ /** How long one git read of the bind's welcome may take: a slow repository only loses its row. */
6373
+ const bindingGitTimeoutMs = 1500;
6138
6374
  /**
6139
6375
  * @description Collect a short factual summary of a bound project folder for
6140
6376
  * the welcome message — what onboarding context Claude would actually pick
@@ -6173,22 +6409,11 @@ async function getBindingStats(workDir) {
6173
6409
  catch {
6174
6410
  return out;
6175
6411
  }
6176
- try {
6177
- const { stdout } = await execFileAsync('git', ['symbolic-ref', '--short', 'HEAD'], {
6178
- cwd: workDir, timeout: 1500,
6179
- });
6180
- out.gitBranch = stdout.trim() || 'HEAD';
6181
- }
6182
- catch {
6183
- out.gitBranch = 'HEAD';
6184
- }
6185
- try {
6186
- const { stdout } = await execFileAsync('git', ['status', '--porcelain'], {
6187
- cwd: workDir, timeout: 1500,
6188
- });
6189
- out.gitClean = stdout.trim().length === 0;
6190
- }
6191
- catch { /* keep null = unknown */ }
6412
+ // The folder's git configuration is the agent's to write: `runGitInAgentFolder` runs git without the bot's secrets.
6413
+ out.gitBranch = (await (0, folderGit_1.runGitInAgentFolder)(workDir, ['symbolic-ref', '--short', 'HEAD'], bindingGitTimeoutMs)) || 'HEAD';
6414
+ const status = await (0, folderGit_1.runGitInAgentFolder)(workDir, ['status', '--porcelain'], bindingGitTimeoutMs);
6415
+ if (status !== null)
6416
+ out.gitClean = status.length === 0;
6192
6417
  return out;
6193
6418
  }
6194
6419
  /**
@@ -6254,6 +6479,11 @@ async function sendBindingWelcome(key, subdir, notes = {}) {
6254
6479
  const moreLabel = sharedMore > 0 ? (0, i18n_1.t)('binding.welcome.sharedMore', { count: sharedMore }) : null;
6255
6480
  lines.push((0, i18n_1.t)('binding.welcome.shared', { threads: (0, bindingWelcome_1.formatSharedTopicList)(notes.sharedWith ?? [], moreLabel) }));
6256
6481
  }
6482
+ // The list of people who may talk to the agent belongs to the TOPIC, not the folder: after a bind they reach the agent of the
6483
+ // folder it is bound to now — those on the topic's own list, on General's (group-wide) and the invited who have not written yet.
6484
+ const reachCount = state.getTopicReachCount(key, getGroupGeneralKey(key));
6485
+ if (reachCount > 0)
6486
+ lines.push((0, i18n_1.t)('access.bindNote', { count: reachCount, subdir }));
6257
6487
  lines.push('');
6258
6488
  lines.push((0, i18n_1.t)('binding.welcome.start_prompt'));
6259
6489
  const welcomeMessageId = await replyToThread(key, lines.join('\n'), {
@@ -6676,6 +6906,19 @@ const { registerBotSkillsCommands, registerBotSkillsCallbacks } = (0, botSkills_
6676
6906
  checkIsOpenCodeTopic: (key) => ((0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name) === adapterNames_1.openCodeAdapterName,
6677
6907
  });
6678
6908
  registerBotSkillsCommands();
6909
+ // ── Who may talk to the agent in a topic (`/access`): `connectors/telegram/commands/topicAccess.ts`, `topicTalkers.ts` ──
6910
+ const { registerTopicAccessCommands, registerTopicAccessCallbacks } = (0, topicAccess_1.createTopicAccess)({
6911
+ ...botCore,
6912
+ getAdminIds: () => adminCache.getAdminIds(),
6913
+ getAdminUsernames: () => adminCache.getAdminHandles(),
6914
+ getBotUserId: () => bot.botInfo?.id,
6915
+ getBotUsername: () => bot.botInfo?.username,
6916
+ getGroupGeneralKey,
6917
+ checkIsDmKey,
6918
+ recentWriters: recentTopicWriters,
6919
+ seenSenders: seenGroupSenders,
6920
+ });
6921
+ registerTopicAccessCommands();
6679
6922
  // ── The cap on tracker task agents (`/task_agents`): `connectors/telegram/commands/taskAgents.ts`, `trackers/` ──
6680
6923
  const { registerTaskAgentsCommands, registerTaskAgentsCallbacks } = (0, taskAgents_1.createTaskAgents)({
6681
6924
  ...botCore,
@@ -6700,11 +6943,13 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
6700
6943
  getGeneralKey: () => getOperatorGeneralKey(),
6701
6944
  pinMessage: (key, messageId) => pinMessageQuiet(key, messageId, { disableNotification: false }),
6702
6945
  sweepExpiredCodes: async (nowMs) => { await (0, hubPairing_1.sweepExpiredPairings)(runnersHub, nowMs); },
6946
+ applyGroups: (runner) => (0, runnerGroups_1.applyRunnerGroups)(runnersHub, runner, runnersCacheDir),
6703
6947
  readRunnerHost: (0, instanceSettings_1.createRunnerHostReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line)),
6704
6948
  saveRunnerHost: (address) => (0, instanceSettings_1.saveInstanceSettingsChange)((0, instanceSettings_1.getInstanceSettingsPath)(), { runnerHost: address }),
6705
6949
  getBotLabel: () => (bot.botInfo?.username === undefined ? os.hostname() : `@${bot.botInfo.username}`),
6706
6950
  readOverview: (nowMs) => (0, runnersOverview_1.readRunnersOverview)(runnersHub, runnersCacheDir, nowMs),
6707
- probeOverview: (overview, nowMs) => (0, runnersOverview_1.probeRunnersOverview)(runnersHub, overview, runnersCacheDir, nowMs),
6951
+ // The 20 s deadline of the live probe, which the test seam may shorten (a flow that must see a BUSY machine cannot wait it out).
6952
+ probeOverview: (overview, nowMs) => (0, runnersOverview_1.probeRunnersOverview)(runnersHub, overview, runnersCacheDir, nowMs, ENV.testTimings.remoteRunProbeDeadlineMs),
6708
6953
  listAddressCandidates: () => (0, hubAddressCandidates_1.listPublicAddressCandidates)(),
6709
6954
  scanHostKey: hubAddress_1.scanHostKey,
6710
6955
  ensureGateWrapper: () => { (0, gateWrapper_1.ensureGateWrapper)(runnersHub); },
@@ -6732,10 +6977,7 @@ function resolveThreadClaudeConfigDir(key) {
6732
6977
  * the probe fails.
6733
6978
  */
6734
6979
  async function readClaudeAuthStatusUnder(configDir) {
6735
- const env = { ...process.env };
6736
- delete env.ANTHROPIC_API_KEY;
6737
- if (configDir !== null)
6738
- env[claudeProfiles_1.claudeConfigDirVariableName] = configDir;
6980
+ const env = (0, claudeProfiles_1.getClaudeAuthCommandEnvironment)(configDir);
6739
6981
  try {
6740
6982
  const args = [...(0, claudeApiKeyHelper_1.buildClaudeAuthProbeSettingsArgs)(configDir), 'auth', 'status', '--json'];
6741
6983
  const { stdout } = await execFileAsync((0, resolveBinary_1.resolveClaudeBinary)(), args, { timeout: claudeAuthStatusProbeTimeoutMs, env });
@@ -6822,6 +7064,56 @@ const claudeUsageRefresher = (0, claudeUsageRefresher_1.createClaudeUsageRefresh
6822
7064
  refreshOpenCode: (options) => openCodeUsagePoller.refreshAll(options),
6823
7065
  markOpenCodeStale: (reason) => openCodeUsagePoller.markAllStale(reason),
6824
7066
  });
7067
+ /**
7068
+ * What the daily recheck of a used-up API credit (`utils/claudeApiCreditRecheck.ts`) reads and does in the bot: the profiles
7069
+ * with their marks (after the operator's newer figures have ended the marks they supersede), their own keys, and the state it
7070
+ * writes — the attempt BEFORE the request, the renewal after an answer.
7071
+ */
7072
+ const claudeApiCreditRecheckPorts = {
7073
+ nowMs: () => Date.now(),
7074
+ intervalMs: ENV.testTimings.creditRecheckIntervalMs ?? claudeApiCreditRecheck_1.claudeApiCreditRecheckIntervalMs,
7075
+ listProfiles: () => {
7076
+ syncClaudeApiCreditAnchors();
7077
+ return Object.entries(state.getAllClaudeProfileInfos()).map(([name, record]) => ({
7078
+ name,
7079
+ billing: record.billing ?? null,
7080
+ // The refusal the operator acted on awaits its answer too: the account is in use again, but nothing has confirmed the credit.
7081
+ creditExhaustedAt: record.creditExhaustedAt ?? record.creditUnconfirmedSince ?? null,
7082
+ creditRecheckedAt: record.creditRecheckedAt ?? null,
7083
+ }));
7084
+ },
7085
+ readApiKey: (name) => {
7086
+ if (name === claudeProfiles_1.defaultClaudeProfileName)
7087
+ return (0, claudeProfiles_1.readDefaultClaudeProfileApiKey)(state.getClaudeProfileInfo(name)?.isConsoleLoginKey === true);
7088
+ const configDir = (0, claudeProfiles_1.resolveClaudeProfileDir)((0, state_1.resolveDataDir)(), name);
7089
+ return configDir === null ? null : (0, claudeProfiles_1.readClaudeProfileApiKey)(configDir);
7090
+ },
7091
+ probe: (apiKey) => (0, claudeApiCreditRecheck_1.probeClaudeApiCredit)(apiKey),
7092
+ markRechecked: (name, atIso) => state.setClaudeProfileCreditRechecked(name, atIso),
7093
+ onRenewed: (name, atIso) => {
7094
+ if (!state.setClaudeProfileCreditRenewed(name, atIso))
7095
+ console.log(`[credit] ${name}: a refusal came in while the recheck was running, so the credit is not marked renewed`);
7096
+ },
7097
+ log: (line) => console.log(line),
7098
+ warn: (line) => console.warn(line),
7099
+ };
7100
+ /**
7101
+ * What the check of an agent's stop report on an API account (`utils/claudeApiAgentStop.ts`) reads and does in the bot: the same
7102
+ * key, attempt record and probe as the daily recheck above, a probe with a timeout of its own, and — instead of an unverified
7103
+ * used-up mark — a mark only on a refusal for the balance, an hour off AGENTS (their own field, never the topics' limit mark) otherwise.
7104
+ */
7105
+ const claudeApiAgentStopPorts = {
7106
+ nowMs: () => Date.now(),
7107
+ readApiKey: (name) => claudeApiCreditRecheckPorts.readApiKey(name),
7108
+ probe: (apiKey, timeoutMs) => (0, claudeApiCreditRecheck_1.probeClaudeApiCredit)(apiKey, { timeoutMs }),
7109
+ markRechecked: (name, atIso) => state.setClaudeProfileCreditRechecked(name, atIso),
7110
+ markUsedUp: (name, atIso) => state.setClaudeProfileCreditExhausted(name, atIso),
7111
+ holdOff: (name, untilIso) => state.setClaudeProfileAgentHoldUntil(name, untilIso),
7112
+ checkIsRenewalAwaited: (name) => state.getClaudeProfileInfo(name)?.creditUnconfirmedSince !== undefined,
7113
+ onRenewed: (name, atIso) => claudeApiCreditRecheckPorts.onRenewed(name, atIso),
7114
+ log: (line) => console.log(line),
7115
+ warn: (line) => console.warn(line),
7116
+ };
6825
7117
  /** The profile that owns a config directory (`null` = default); `null` for a directory outside the profiles root. */
6826
7118
  function resolveClaudeProfileNameForDir(configDir) {
6827
7119
  if (configDir === null)
@@ -6861,14 +7153,52 @@ function onClaudeTurnCost(key, configDir, report) {
6861
7153
  const name = resolveClaudeProfileNameForDir(configDir);
6862
7154
  if (name === null)
6863
7155
  return;
7156
+ // Read first: a figure newer than the account's used-up evidence ends it before this turn is judged against it.
7157
+ const creditAnchors = syncClaudeApiCreditAnchors();
6864
7158
  const info = state.getClaudeProfileInfo(name);
7159
+ // The refusal the operator acted on (picked the account again) is still evidence: the turn that now goes through renews.
6865
7160
  const outcome = (0, claudeApiSpend_1.getClaudeTurnCostOutcome)({
6866
- billing: info?.billing ?? null, isCreditExhausted: info?.creditExhaustedAt !== undefined, isError: report.isError, turnCostUsd,
7161
+ billing: info?.billing ?? null,
7162
+ isCreditExhausted: info?.creditExhaustedAt !== undefined || info?.creditUnconfirmedSince !== undefined,
7163
+ isError: report.isError,
7164
+ turnCostUsd,
6867
7165
  });
6868
- if (outcome.isCreditMarkCleared)
6869
- state.setClaudeProfileCreditExhausted(name, null);
6870
- if (outcome.spendUsd !== null)
6871
- state.setClaudeProfileApiSpend(name, (0, claudeApiSpend_1.addClaudeApiSpend)(info?.apiSpend, outcome.spendUsd, new Date().toISOString()));
7166
+ const nowIso = new Date().toISOString();
7167
+ // A billed turn that goes through on an API account marked used up — or one the operator picked again after the refusal — is
7168
+ // the proof the daily recheck looks for: the credit is back, and the account's spend counter starts over from this turn.
7169
+ if (outcome.isCreditMarkCleared && info?.billing === 'api')
7170
+ state.setClaudeProfileCreditRenewed(name, nowIso);
7171
+ else if (outcome.isCreditMarkCleared)
7172
+ state.liftClaudeProfileCreditExhaustion(name);
7173
+ if (outcome.spendUsd === null)
7174
+ return;
7175
+ const apiSpend = (0, claudeApiSpend_1.addClaudeApiSpend)(info?.apiSpend, outcome.spendUsd, nowIso);
7176
+ state.setClaudeProfileApiSpend(name, apiSpend);
7177
+ // The same spend also counts in the account's credit period (`utils/claudeApiCredit.ts`), read AFTER a renewal above.
7178
+ const period = (0, claudeApiCredit_1.getClaudeApiCreditPeriod)({ anchor: creditAnchors[name], renewedAt: state.getClaudeProfileInfo(name)?.creditRenewedAt, apiSpend });
7179
+ const creditSpend = (0, claudeApiCredit_1.addClaudeApiCreditSpend)(state.getClaudeProfileInfo(name)?.creditSpend, period, outcome.spendUsd);
7180
+ if (creditSpend)
7181
+ state.setClaudeProfileCreditSpend(name, creditSpend);
7182
+ }
7183
+ /**
7184
+ * Read the operator's credit figures (`utils/claudeApiCredit.ts`) AND settle what they supersede: a figure newer than an
7185
+ * account's used-up evidence (the mark, or the refusal the operator acted on) ends that evidence — the operator saying there is
7186
+ * money is the signal a billed turn going through is — so the stored mark, the fallback chain and the screens never contradict
7187
+ * the figure. It writes state: a call whose result is dropped is meant (a read path that must see the settled marks).
7188
+ */
7189
+ function syncClaudeApiCreditAnchors() {
7190
+ const anchors = (0, claudeApiCredit_1.readClaudeApiCreditAnchors)((0, state_1.resolveDataDir)());
7191
+ for (const name of (0, claudeApiCredit_1.listProfilesWithSupersededCreditEvidence)(state.getAllClaudeProfileInfos(), anchors))
7192
+ state.clearClaudeProfileCreditEvidence(name);
7193
+ return anchors;
7194
+ }
7195
+ /** Every Claude profile's usage view as the bot knows it now: its record plus the operator's credit figures. */
7196
+ function getClaudeProfileUsageViews() {
7197
+ return (0, claudeProfileUsageViews_1.buildClaudeProfileUsageViews)({ dataDir: (0, state_1.resolveDataDir)(), records: state.getAllClaudeProfileInfos(), creditAnchors: syncClaudeApiCreditAnchors() });
7198
+ }
7199
+ /** One profile's usage view — the very one `/limits` renders, for the rows of `/accounts`. */
7200
+ function getClaudeProfileUsageView(name) {
7201
+ return (0, claudeProfileUsageViews_1.buildClaudeProfileUsageView)({ dataDir: (0, state_1.resolveDataDir)(), name, record: state.getClaudeProfileInfo(name), creditAnchor: syncClaudeApiCreditAnchors()[name] });
6872
7202
  }
6873
7203
  /** The model a topic's Claude session runs (or last ran), for the usage ranking's choice of windows. */
6874
7204
  function getThreadClaudeModel(key) {
@@ -6876,6 +7206,7 @@ function getThreadClaudeModel(key) {
6876
7206
  }
6877
7207
  /** What `/status` names of a Claude profile: its last probed sign-in and email, and its limit mark (none until probed). */
6878
7208
  function readStatusAccountSource(name) {
7209
+ syncClaudeApiCreditAnchors();
6879
7210
  const info = state.getClaudeProfileInfo(name);
6880
7211
  return {
6881
7212
  name, email: info?.email ?? null, loggedIn: info?.loggedIn, limitedUntil: info?.limitedUntil ?? null,
@@ -6907,7 +7238,7 @@ async function detectFallbackOptions() {
6907
7238
  console.warn('[fallback] the OpenCode catalog is unavailable:', e instanceof Error ? e.message : e);
6908
7239
  }
6909
7240
  return {
6910
- claudeProfiles: (0, claudeUsage_1.buildClaudeProfileUsageViews)({ dataDir: (0, state_1.resolveDataDir)(), records: state.getAllClaudeProfileInfos() }),
7241
+ claudeProfiles: getClaudeProfileUsageViews(),
6911
7242
  openCodeModels,
6912
7243
  recentOpenCodeModels: (0, openCodeAdapter_1.listSavedOpenCodeModelLabels)().reverse(),
6913
7244
  openCodeLimits: state.getOpenCodeModelLimits(),
@@ -6974,6 +7305,7 @@ function getConversationAccountState(key) {
6974
7305
  const checkIsFuture = (instant) => instant !== undefined && Date.parse(instant) > nowMs;
6975
7306
  if (position.backend === 'opencode')
6976
7307
  return { isLimited: checkIsFuture(state.getOpenCodeModelLimitedUntil((0, fallbackChain_1.buildOpenCodeModelLabel)(position))), isApiBilled: false };
7308
+ syncClaudeApiCreditAnchors();
6977
7309
  const info = state.getClaudeProfileInfo(position.profile);
6978
7310
  return { isLimited: checkIsFuture(info?.limitedUntil) || info?.creditExhaustedAt !== undefined, isApiBilled: info?.billing === 'api' };
6979
7311
  }
@@ -7382,7 +7714,7 @@ async function checkIsPickBeyondLimit(from, to) {
7382
7714
  if (from?.backend !== 'claude' || to.backend !== 'claude' || to.model === null || from.profile !== to.profile)
7383
7715
  return false;
7384
7716
  await (0, usageRefreshBudget_1.refreshUsageWithinBudget)((options) => claudeUsageRefresher.refreshAll(options));
7385
- return (0, claudeUsage_1.checkIsClaudeModelClearOfLimit)(state.getClaudeProfileInfo(to.profile)?.usage, from.model, to.model);
7717
+ return (0, claudeUsage_1.checkIsClaudeModelClearOfLimit)(state.getClaudeProfileInfo(to.profile)?.usage, from.model, to.model, Date.now());
7386
7718
  }
7387
7719
  /** The rung as a manual switch's target: a picked Claude account (+ model alias), or an OpenCode model, both named in the question. */
7388
7720
  function buildBackendSwitchTargetOfRung(to) {
@@ -7403,9 +7735,10 @@ function buildBackendSwitchTargetOfRung(to) {
7403
7735
  */
7404
7736
  async function switchTopicByOperator(key, to) {
7405
7737
  // The operator's own pick of an account whose API credits were used up is the act that ends that mark (topped up, or
7406
- // trying anyway): a failing request marks it again.
7738
+ // trying anyway): a failing request marks it again. An API account keeps the refusal as unconfirmed, so the first turn that
7739
+ // goes through still records the renewal.
7407
7740
  if (to.backend === 'claude')
7408
- state.setClaudeProfileCreditExhausted(to.profile, null);
7741
+ state.liftClaudeProfileCreditExhaustion(to.profile);
7409
7742
  const currentFamily = getTopicBackendFamily(key);
7410
7743
  const from = getTopicFallbackPosition(key);
7411
7744
  const isUsageLimitWaitArmed = getArmedApiRetry(key)?.kind === 'usageLimit';
@@ -7486,13 +7819,23 @@ async function takeFallbackSwitchOffer(key, episodeId, index) {
7486
7819
  /**
7487
7820
  * The `claude_profiles` MCP tool's answer: snapshots refreshed on demand (a minute's cache; the account a resumed session
7488
7821
  * was stopped on is re-read at once), then the launch pick — a new agent, or the session's own account when it is warm.
7489
- * The accounts the operator switched off in the `/limits` list are never picked for a new agent. The refresh is waited for
7490
- * only up to `claudeLaunchRefreshBudgetMs`; past it the cached figures are answered (an agent that waits on a silent tool
7491
- * call is dropped by its own client after 300 s).
7822
+ * Only the accounts the operator's `/limits` list holds with an enabled rung are named once it lists any Claude account (an
7823
+ * account billed to API credits among them goes first, `getClaudeLaunchPick`). A resumed session reported stopped on an API
7824
+ * account is CHECKED, not believed (`verifyClaudeApiAgentStop`): one probe on its key marks the credit used up only if the API
7825
+ * refuses for the balance; otherwise the account is just kept off agents for an hour. The check runs beside the usage refresh
7826
+ * with a timeout of its own, so the answer is held for the longer of the two, never their sum. The refresh is waited for only
7827
+ * up to `claudeLaunchRefreshBudgetMs`; past it the cached figures are answered (an agent that waits on a silent tool call is
7828
+ * dropped by its own client after 300 s).
7492
7829
  */
7493
7830
  async function listClaudeProfilesForAgent(query) {
7494
- await (0, claudeUsageRefresher_1.refreshClaudeUsageForLaunch)(claudeUsageRefresher, { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, maxAgeMs: claudeUsageRefresher_1.claudeUsageOnDemandMaxAgeMs });
7495
- return (0, claudeUsage_1.buildClaudeProfilesReport)((0, claudeUsage_1.buildClaudeProfileUsageViews)({ dataDir: (0, state_1.resolveDataDir)(), records: state.getAllClaudeProfileInfos() }), query.model, Date.now(), { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, excludedNames: (0, fallbackChain_1.getDisabledClaudeProfileNames)(state.getFallbackChain()) });
7831
+ const stoppedApiProfile = (0, claudeApiAgentStop_1.getApiProfileStoppedByAgent)(getClaudeProfileUsageViews(), query, Date.now());
7832
+ await Promise.all([
7833
+ (0, claudeUsageRefresher_1.refreshClaudeUsageForLaunch)(claudeUsageRefresher, { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, maxAgeMs: claudeUsageRefresher_1.claudeUsageOnDemandMaxAgeMs }),
7834
+ stoppedApiProfile === null
7835
+ ? Promise.resolve()
7836
+ : (0, claudeApiAgentStop_1.verifyClaudeApiAgentStop)(stoppedApiProfile, claudeApiAgentStopPorts).then(() => undefined, (e) => console.warn(`[credit] ${stoppedApiProfile}: checking an agent's stop report failed:`, e instanceof Error ? e.message : e)),
7837
+ ]);
7838
+ return (0, claudeProfileUsageViews_1.buildClaudeProfilesCreditReport)(getClaudeProfileUsageViews(), query.model, Date.now(), { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, chainScope: (0, fallbackChain_1.getClaudeLaunchChainScope)(state.getFallbackChain()) });
7496
7839
  }
7497
7840
  const { registerFallbackChainCommands, registerFallbackChainCallbacks, openAutoSwitchView, runAutoSwitchCommand, applyAutoSwitch } = (0, fallbackChain_2.createFallbackChain)({
7498
7841
  ...botCore,
@@ -7542,6 +7885,8 @@ const { registerClaudeAccountCommands, registerClaudeAccountCallbacks, checkIsAw
7542
7885
  startOpenCodeConnect: showConnectMethodPicker,
7543
7886
  applyAutoSwitch,
7544
7887
  verifyAnthropicApiKey: (apiKey) => (0, anthropicApiKeyCheck_1.verifyAnthropicApiKey)(apiKey),
7888
+ getProfileUsageView: getClaudeProfileUsageView,
7889
+ checkIsProfileMissingFromLimitsList: (name) => (0, fallbackChain_1.checkIsClaudeProfileMissingFromChain)(state.getFallbackChain(), name),
7545
7890
  });
7546
7891
  claudeProfileAuthStatusSink = recordClaudeProfileAuthStatus;
7547
7892
  claudeProfileApiKeySink = storeClaudeProfileApiKey;
@@ -7884,20 +8229,24 @@ command('tab', async (_ctx, key) => {
7884
8229
  else
7885
8230
  await replyToThread(key, `Not supported for ${adapter.label}`);
7886
8231
  });
7887
- command(escapeCommandNames, async (_ctx, key) => {
7888
- // A pending «Add account» name prompt, a pending sign-in (`/login`, `/connect` OAuth) and a `/topic` wizard take
7889
- // priority: the first /esc only cancels it, so the topic stops waiting for typed input.
7890
- if (cancelProfileNameCapture(key)) {
7891
- await replyToThread(key, (0, i18n_1.t)('account.askNameCancelled'));
7892
- return;
7893
- }
7894
- if (cancelPendingLogin(key)) {
7895
- await replyToThread(key, (0, i18n_1.t)('login.cancelled'));
7896
- return;
8232
+ command(escapeCommandNames, async (ctx, key) => {
8233
+ // A talker's /esc only interrupts the running turn: the prompts below are an admin's (a sign-in, a name for an account or a
8234
+ // topic), and ending one is the admin's own word.
8235
+ if ((await authoriseTopicSpeaker(ctx))?.role !== 'talker') {
8236
+ // A pending «Add account» name prompt, a pending sign-in (`/login`, `/connect` OAuth) and a `/topic` wizard take
8237
+ // priority: the first /esc only cancels it, so the topic stops waiting for typed input.
8238
+ if (cancelProfileNameCapture(key)) {
8239
+ await replyToThread(key, (0, i18n_1.t)('account.askNameCancelled'));
8240
+ return;
8241
+ }
8242
+ if (cancelPendingLogin(key)) {
8243
+ await replyToThread(key, (0, i18n_1.t)('login.cancelled'));
8244
+ return;
8245
+ }
8246
+ // A `/topic` wizard is ended at whatever step it waits (it says so itself).
8247
+ if (await cancelTopicWizard(key))
8248
+ return;
7897
8249
  }
7898
- // A `/topic` wizard is ended at whatever step it waits (it says so itself).
7899
- if (await cancelTopicWizard(key))
7900
- return;
7901
8250
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
7902
8251
  if (adapter.sendEscape) {
7903
8252
  // The operator interrupted the turn: its open request closes silently.
@@ -7914,7 +8263,7 @@ command(escapeCommandNames, async (_ctx, key) => {
7914
8263
  else {
7915
8264
  await replyToThread(key, `Not supported for ${adapter.label}`);
7916
8265
  }
7917
- });
8266
+ }, { isTalkerAllowed: true });
7918
8267
  command('output', async (_ctx, key) => {
7919
8268
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
7920
8269
  if (!adapter.getFullOutput) {
@@ -8184,8 +8533,8 @@ const botCommands = new Set([
8184
8533
  'start', 'claude', 'opencode', 'oc', 'terminal', 'agent', 'sessions', 'resume', 'cancel', 'model', 'connect',
8185
8534
  'disconnect', 'stop', 'stopall', 'stop-all', 'quit-all', 'status', 'c', 'y', 'n', 'enter', 'up', 'down', 'tab', 'esc', 'escape', 'interrupt', 'output', 'clear_messages',
8186
8535
  'bind', 'topic', 'unbind', 'where', 'ls', 'list', 'new', 'whoami', 'version', 'help', 'language', 'lang',
8187
- 'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'bot_skills', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
8188
- 'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update',
8536
+ 'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'compact_self_review', 'bot_skills', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
8537
+ 'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update', 'access',
8189
8538
  ]);
8190
8539
  /**
8191
8540
  * @description The bare `/clear` is no longer bot-owned (it was renamed to
@@ -8197,10 +8546,79 @@ const forwardedClearCommand = '/clear';
8197
8546
  // ═══════════════════════════════════════════════════════════════════════════════
8198
8547
  // Text message handler — main conversational entrypoint
8199
8548
  // ═══════════════════════════════════════════════════════════════════════════════
8549
+ /**
8550
+ * @description A talker's text — the one early branch, so no armed step, command, start phrase or guide of the admin path
8551
+ * can be reached by checks spread through the handler. What it does: it is refused if it is a slash text (agent slash
8552
+ * commands control the conversation, and the commands the bot owns were decided before the message got here); a pasted
8553
+ * OAuth callback URL is deleted as a secret, whoever sent it; a raw-shell topic is refused; otherwise it is a prompt like any
8554
+ * other — buffered behind a session start, delivered to a live agent, or waking a sleeping conversation — and with no agent
8555
+ * at all the talker is told so (never offered the folder picker, never starting one). It never feeds an input step an admin
8556
+ * armed (a sign-in code, a key, a name, a reminder's text): those routes are not here — and while an admin's tmux `/login` code box
8557
+ * is open the message is refused, since a prompt would end that sign-in. A message refused anywhere above changes nothing.
8558
+ */
8559
+ async function handleTalkerText(ctx, key) {
8560
+ const text = (0, utils_1.stripCommandBotMention)(ctx.message.text.trim());
8561
+ // A FORWARDED message is content: its `/…` is words like any other. A slash the talker typed is refused.
8562
+ if (!(0, inbound_1.checkIsTelegramForward)(ctx.message) && text.startsWith('/')) {
8563
+ await replyToThread(key, (0, i18n_1.t)('access.adminOnlyCommandRefusal'));
8564
+ return;
8565
+ }
8566
+ await state.pushMessageId(key, ctx.message.message_id);
8567
+ // The safety net for a pasted OAuth callback URL holds for everybody: it is a secret, never a prompt.
8568
+ if ((0, openCodeAuthLogin_1.parseOAuthCallbackFromReply)(text)) {
8569
+ await deleteThreadMessage(key, ctx.message.message_id);
8570
+ await replyToThread(key, (0, i18n_1.t)('connect.oauth_callback_no_flow'));
8571
+ return;
8572
+ }
8573
+ if (await refuseTalkerInTerminalTopic(key))
8574
+ return;
8575
+ const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8576
+ // An admin's tmux `/login` paste box is open: a prompt would press Escape first and end the sign-in the admin is in the middle of
8577
+ // (the admin's own text is typed into the box instead — that route is not a talker's).
8578
+ if (adapter.isLoginPastePending?.(key)) {
8579
+ await replyToThread(key, (0, i18n_1.t)('access.loginPendingForTalkerNotice'));
8580
+ return;
8581
+ }
8582
+ // The talker took over before a pending API-error retry fired, as any sender does — only now: a message that was refused above
8583
+ // changed nothing, so a usage-limit wait armed for the topic is still armed (it would otherwise end without its resume).
8584
+ cancelApiRetry(key);
8585
+ const messageContext = getMessageContext(key, ctx.message);
8586
+ const intake = { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) };
8587
+ const sentAtMs = ctx.message.date * 1000;
8588
+ if (startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key))) {
8589
+ await bufferPromptDuringStartup(key, text, intake, messageContext);
8590
+ return;
8591
+ }
8592
+ if (adapter.checkIsActive(key)) {
8593
+ await deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext);
8594
+ return;
8595
+ }
8596
+ // A sleeping conversation is resumed by the message itself, as for anybody (L-D4).
8597
+ if (await resumeSleepingSessionForPrompt(key)) {
8598
+ await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, intake, sentAtMs, messageContext);
8599
+ return;
8600
+ }
8601
+ await replyToThread(key, (0, i18n_1.t)('access.noAgentForTalkerNotice'));
8602
+ }
8603
+ /**
8604
+ * @description A raw-shell topic takes no talker: what is typed into a shell reaches it with no label, so none of the marks
8605
+ * and guards that tell the agent whose words these are can apply. Posts the refusal and answers `true` for such a topic.
8606
+ */
8607
+ async function refuseTalkerInTerminalTopic(key, sendRefusal = (text) => replyToThread(key, text)) {
8608
+ if ((0, createAdapter_1.getThreadAdapter)(key).name !== 'terminal')
8609
+ return false;
8610
+ await sendRefusal((0, i18n_1.t)('access.terminalTopicRefusal'));
8611
+ return true;
8612
+ }
8200
8613
  bot.on((0, filters_1.message)('text'), async (ctx) => {
8201
- const key = await authoriseContext(ctx);
8202
- if (!key)
8614
+ const speaker = await authoriseTopicSpeaker(ctx);
8615
+ if (!speaker)
8203
8616
  return;
8617
+ const { key } = speaker;
8618
+ if (speaker.role === 'talker') {
8619
+ await handleTalkerText(ctx, key);
8620
+ return;
8621
+ }
8204
8622
  // User took over before a pending API-error retry fired → cancel it silently
8205
8623
  // (no give-up notice). Fires for EVERY authorised inbound text — a plain
8206
8624
  // prompt AND an owned slash-command — before the bot-command early-return.
@@ -8547,8 +8965,12 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
8547
8965
  // Voice message handler
8548
8966
  // ═══════════════════════════════════════════════════════════════════════════════
8549
8967
  bot.on((0, filters_1.message)('voice'), async (ctx) => {
8550
- const key = await authoriseContext(ctx);
8551
- if (!key)
8968
+ const speaker = await authoriseTopicSpeaker(ctx);
8969
+ if (!speaker)
8970
+ return;
8971
+ const { key } = speaker;
8972
+ // A talker's voice note goes to the agent like their text does — marked as theirs — but never into a raw shell.
8973
+ if (speaker.role === 'talker' && await refuseTalkerInTerminalTopic(key))
8552
8974
  return;
8553
8975
  // User took over (voice note) before a pending API-error retry fired → cancel
8554
8976
  // it silently, like the text handler.
@@ -8655,7 +9077,8 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
8655
9077
  // transcript is routed here — right after the 🎤 echo and BEFORE the
8656
9078
  // startup-buffer / natural-language-start / binding gates, which would
8657
9079
  // otherwise treat it as a prompt. Same single creation path as the text side.
8658
- const reminderVoiceRoute = claimReminderTextCapture(key);
9080
+ // The step is an ADMIN's: a topic member's voice note neither fills it nor closes it when it has expired — it goes on as a prompt.
9081
+ const reminderVoiceRoute = (0, messageContext_1.checkIsForeignWords)(messageContext) ? null : claimReminderTextCapture(key);
8659
9082
  if (reminderVoiceRoute === 'capture') {
8660
9083
  await finishReminderWizard(key, transcript);
8661
9084
  return;
@@ -8667,8 +9090,8 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
8667
9090
  await bufferPromptDuringStartup(key, transcript, { source: 'voice', requesterId }, messageContext);
8668
9091
  return;
8669
9092
  }
8670
- // A FORWARDED voice note saying «Claude» is somebody else's words, not the operator's order to start an agent.
8671
- if (messageContext?.isForwarded !== true && !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)) {
9093
+ // A FORWARDED voice note saying «Claude», or a topic member's, is somebody else's words, not the operator's order to start an agent.
9094
+ if (!(0, messageContext_1.checkIsForeignWords)(messageContext) && !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)) {
8672
9095
  const startMatch = (0, agentTrigger_1.parseAgentTrigger)(transcript);
8673
9096
  if (startMatch.isMatch && startMatch.adapterName) {
8674
9097
  if (checkIsGeneral(key)) {
@@ -8699,18 +9122,7 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
8699
9122
  }
8700
9123
  // A voice prompt wakes a sleeping conversation like a text one does (L-D4).
8701
9124
  if (!(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) && !(await resumeSleepingSessionForPrompt(key))) {
8702
- if (checkIsGeneral(key)) {
8703
- await replyToThread(key, (0, i18n_1.t)('thread.general_no_agent'));
8704
- return;
8705
- }
8706
- const binding = state.getBinding(key);
8707
- if (!binding) {
8708
- const subdirs = listAvailableSubdirs(ENV.workRoot);
8709
- const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
8710
- await replyToThread(key, (0, i18n_1.t)('thread.no_binding'), extra);
8711
- return;
8712
- }
8713
- await replyToThread(key, (0, i18n_1.t)('thread.no_agent_with_binding', { subdir: binding.subdir }));
9125
+ await sendNoAgentGuidance(key, messageContext?.nonOperatorSender !== undefined, (text, extra) => replyToThread(key, text, extra));
8714
9126
  return;
8715
9127
  }
8716
9128
  // Same choke point as text: a voice transcript while a question is pending
@@ -8752,6 +9164,29 @@ function checkIsFileTooBigApiError(err) {
8752
9164
  * an agent is active (or mid-startup) — an idle/unbound thread gets the hint
8753
9165
  * and nothing hits disk, per the locked decision.
8754
9166
  */
9167
+ /**
9168
+ * @description What a message gets when no agent works or sleeps in its topic: General is no place for an agent; an unbound topic is
9169
+ * offered the folder picker, a bound one the hint to start an agent. A TALKER gets one line — an admin starts the agent —
9170
+ * and never the picker: they bind and start nothing. `sendHint` is how the line is sent (an album sends it once).
9171
+ */
9172
+ async function sendNoAgentGuidance(key, isFromTalker, sendHint) {
9173
+ if (isFromTalker) {
9174
+ await sendHint((0, i18n_1.t)('access.noAgentForTalkerNotice'));
9175
+ return;
9176
+ }
9177
+ if (checkIsGeneral(key)) {
9178
+ await sendHint((0, i18n_1.t)('thread.general_no_agent'));
9179
+ return;
9180
+ }
9181
+ const binding = state.getBinding(key);
9182
+ if (!binding) {
9183
+ const subdirs = listAvailableSubdirs(ENV.workRoot);
9184
+ const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
9185
+ await sendHint((0, i18n_1.t)('thread.no_binding'), extra);
9186
+ return;
9187
+ }
9188
+ await sendHint((0, i18n_1.t)('thread.no_agent_with_binding', { subdir: binding.subdir }));
9189
+ }
8755
9190
  /**
8756
9191
  * @description Evaluate the file-intake gate for a thread: an idle thread (no
8757
9192
  * active agent and not mid-startup) gets the same friendly guidance as the text
@@ -8761,25 +9196,14 @@ function checkIsFileTooBigApiError(err) {
8761
9196
  * album path can dedupe it to once-per-album; the single-file path passes
8762
9197
  * `replyToThread` verbatim.
8763
9198
  */
8764
- async function checkFileIntakeGatePassed(key, isStarting, sendHint) {
9199
+ async function checkFileIntakeGatePassed(key, isStarting, sendHint, isFromTalker) {
8765
9200
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8766
9201
  if (isStarting || adapter.checkIsActive(key))
8767
9202
  return true;
8768
9203
  // A file sent to a sleeping conversation wakes it (L-D4) and is taken in by the resumed session.
8769
9204
  if (await resumeSleepingSessionForPrompt(key, sendHint))
8770
9205
  return true;
8771
- if (checkIsGeneral(key)) {
8772
- await sendHint((0, i18n_1.t)('thread.general_no_agent'));
8773
- return false;
8774
- }
8775
- const binding = state.getBinding(key);
8776
- if (!binding) {
8777
- const subdirs = listAvailableSubdirs(ENV.workRoot);
8778
- const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
8779
- await sendHint((0, i18n_1.t)('thread.no_binding'), extra);
8780
- return false;
8781
- }
8782
- await sendHint((0, i18n_1.t)('thread.no_agent_with_binding', { subdir: binding.subdir }));
9206
+ await sendNoAgentGuidance(key, isFromTalker, sendHint);
8783
9207
  return false;
8784
9208
  }
8785
9209
  /**
@@ -8910,7 +9334,7 @@ function parseAlbumGroupKey(groupKey) {
8910
9334
  * {@link albumCollector}). A successful download is buffered into the collector;
8911
9335
  * a failed one still lets the album flush announce the rest.
8912
9336
  */
8913
- async function handleAlbumFile(ctx, key, meta, mediaGroupId) {
9337
+ async function handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker) {
8914
9338
  const groupKey = buildAlbumGroupKey(key, mediaGroupId);
8915
9339
  const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
8916
9340
  // Gate per item, but reply at most once per album. The guard is claimed
@@ -8919,7 +9343,7 @@ async function handleAlbumFile(ctx, key, meta, mediaGroupId) {
8919
9343
  if (albumCollector.checkShouldAnnounceOnce(groupKey)) {
8920
9344
  await replyToThread(key, text, extra);
8921
9345
  }
8922
- });
9346
+ }, isFromTalker);
8923
9347
  if (!gatePassed)
8924
9348
  return;
8925
9349
  const savedPath = await downloadIncomingFile(ctx, key, meta, async (text) => {
@@ -8937,7 +9361,7 @@ async function handleAlbumFile(ctx, key, meta, mediaGroupId) {
8937
9361
  requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from),
8938
9362
  });
8939
9363
  }
8940
- async function handleIncomingFile(ctx, key) {
9364
+ async function handleIncomingFile(ctx, key, isFromTalker) {
8941
9365
  const meta = (0, fileIntake_1.getTelegramFileMeta)(ctx.message);
8942
9366
  if (!meta)
8943
9367
  return; // Not one of the six kinds (e.g. sticker) — ignore.
@@ -8947,11 +9371,11 @@ async function handleIncomingFile(ctx, key) {
8947
9371
  // combined prompt instead of N prompts that abort each other.
8948
9372
  const mediaGroupId = (0, fileIntake_1.getMediaGroupId)(ctx.message);
8949
9373
  if (mediaGroupId) {
8950
- await handleAlbumFile(ctx, key, meta, mediaGroupId);
9374
+ await handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker);
8951
9375
  return;
8952
9376
  }
8953
9377
  const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
8954
- const gatePassed = await checkFileIntakeGatePassed(key, isStarting, (text, extra) => replyToThread(key, text, extra));
9378
+ const gatePassed = await checkFileIntakeGatePassed(key, isStarting, (text, extra) => replyToThread(key, text, extra), isFromTalker);
8955
9379
  if (!gatePassed)
8956
9380
  return;
8957
9381
  const savedPath = await downloadIncomingFile(ctx, key, meta, (text) => replyToThread(key, text));
@@ -8975,11 +9399,21 @@ bot.on(
8975
9399
  // be an AND over the fields and never match a real media message (see
8976
9400
  // incomingFileMessageFilter).
8977
9401
  fileIntake_1.incomingFileMessageFilter, async (ctx) => {
8978
- const key = await authoriseContext(ctx);
8979
- if (!key)
9402
+ const speaker = await authoriseTopicSpeaker(ctx);
9403
+ if (!speaker)
9404
+ return;
9405
+ const { key } = speaker;
9406
+ const isFromTalker = speaker.role === 'talker';
9407
+ // A talker's file goes to the agent like their text does — marked as theirs — but never into a raw shell. An album is refused once,
9408
+ // not once per item.
9409
+ const mediaGroupId = (0, fileIntake_1.getMediaGroupId)(ctx.message);
9410
+ if (isFromTalker && await refuseTalkerInTerminalTopic(key, async (text) => {
9411
+ if (!mediaGroupId || albumCollector.checkShouldAnnounceOnce(buildAlbumGroupKey(key, mediaGroupId)))
9412
+ await replyToThread(key, text);
9413
+ }))
8980
9414
  return;
8981
9415
  try {
8982
- await handleIncomingFile(ctx, key);
9416
+ await handleIncomingFile(ctx, key, isFromTalker);
8983
9417
  }
8984
9418
  catch (err) {
8985
9419
  console.error('[Bot] File handling error:', err);
@@ -8990,9 +9424,10 @@ fileIntake_1.incomingFileMessageFilter, async (ctx) => {
8990
9424
  // Edited message — explicit UX hint instead of silent ignore
8991
9425
  // ═══════════════════════════════════════════════════════════════════════════════
8992
9426
  bot.on('edited_message', async (ctx) => {
8993
- const key = await authoriseContext(ctx);
8994
- if (!key)
9427
+ const speaker = await authoriseTopicSpeaker(ctx);
9428
+ if (!speaker)
8995
9429
  return;
9430
+ const { key } = speaker;
8996
9431
  // Reply once per edit so the user isn't left wondering. The bot does NOT
8997
9432
  // treat the edit as a re-prompt to the agent (plan §16.3, E6).
8998
9433
  await replyToThread(key, (0, i18n_1.t)('edited.hint'));
@@ -9042,10 +9477,16 @@ bot.on('my_chat_member', async (ctx) => {
9042
9477
  * (`checkShouldInvalidateAdminCache`). Requires `chat_member` in
9043
9478
  * `allowed_updates` (NOT in Telegram's default set — see `botAllowedUpdates`).
9044
9479
  */
9045
- bot.on('chat_member', (ctx) => {
9480
+ bot.on('chat_member', async (ctx) => {
9046
9481
  if (ctx.chat?.id !== getAllowedGroupId())
9047
9482
  return;
9048
9483
  const { old_chat_member, new_chat_member } = ctx.update.chat_member;
9484
+ // A person who left, was removed or banned loses every talker entry and waiting invitation: coming back needs a new grant.
9485
+ if ((0, inbound_1.checkHasLeftGroup)(new_chat_member)) {
9486
+ const { user } = new_chat_member;
9487
+ await state.removeUserFromAllTopics({ userId: user.id.toString(), username: user.username, name: (0, inbound_1.getDisplayName)(user) })
9488
+ .catch((e) => console.warn('[access] dropping the talker entries of a member who left failed:', e instanceof Error ? e.message : e));
9489
+ }
9049
9490
  if (!(0, inbound_1.checkShouldInvalidateAdminCache)(old_chat_member.status, new_chat_member.status))
9050
9491
  return;
9051
9492
  adminCache.invalidate();
@@ -9466,6 +9907,7 @@ registerModelCallbacks();
9466
9907
  registerCompactionCallbacks();
9467
9908
  registerAutoContinueLimitsCallbacks();
9468
9909
  registerBotSkillsCallbacks();
9910
+ registerTopicAccessCallbacks();
9469
9911
  registerTaskAgentsCallbacks();
9470
9912
  registerRunnersCallbacks();
9471
9913
  registerBackendSwitchCallbacks();
@@ -9585,6 +10027,9 @@ bot.action(/^resume_(\d+)$/, async (ctx) => {
9585
10027
  if (result !== null)
9586
10028
  await replyToThread(key, result);
9587
10029
  });
10030
+ // The agent's own question buttons (`qa_`, and `reask_` in the compaction module) are the taps a talker may make: they answer the
10031
+ // agent, so they ask the speaker gate; every other button — `opt_`, which types a digit into whatever a Claude TUI shows, included —
10032
+ // keeps asking the admin gate.
9588
10033
  bot.action(/^opt_(\d+)$/, async (ctx) => {
9589
10034
  const key = await authoriseContext(ctx);
9590
10035
  if (!key) {
@@ -9603,11 +10048,12 @@ bot.action(/^opt_(\d+)$/, async (ctx) => {
9603
10048
  }
9604
10049
  });
9605
10050
  bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
9606
- const key = await authoriseContext(ctx);
9607
- if (!key) {
10051
+ const speaker = await authoriseTopicSpeaker(ctx);
10052
+ if (!speaker) {
9608
10053
  await ctx.answerCbQuery((0, i18n_1.t)('cb.access_denied'));
9609
10054
  return;
9610
10055
  }
10056
+ const { key } = speaker;
9611
10057
  const qIdx = parseInt(ctx.match[1], 10);
9612
10058
  const optIdx = parseInt(ctx.match[2], 10);
9613
10059
  const kStr = (0, sessionKey_1.keyToString)(key);
@@ -9629,7 +10075,9 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
9629
10075
  return;
9630
10076
  }
9631
10077
  const selectedLabel = question.options[optIdx].label;
9632
- const isAnswerShown = await applyQuestionAnswer(key, [selectedLabel]);
10078
+ // The agent's question is its way to ask the OPERATOR: an answer a topic member chose says so, in the answer itself.
10079
+ const answeredBy = speaker.role === 'talker' && ctx.from ? (0, inbound_1.getTelegramTalkerContext)(ctx.from).nonOperatorSender : undefined;
10080
+ const isAnswerShown = await applyQuestionAnswer(key, [selectedLabel], answeredBy);
9633
10081
  if (isAnswerShown) {
9634
10082
  // The question message was just edited to carry the whole answer under the question: the toast only
9635
10083
  // confirms the tap, so a label too long for it is cut there and not posted a second time.
@@ -9651,8 +10099,10 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
9651
10099
  */
9652
10100
  async function bufferPromptDuringStartup(key, text, intake, messageContext) {
9653
10101
  // The same for a bare option number typed in that window: it answers the question asked again. A FORWARDED "1" is somebody
9654
- // else's words, not the operator's pick: it is delivered, marked, like any other message.
9655
- if (messageContext?.isForwarded !== true && await answerReAskedQuestionByNumber(key, text))
10102
+ // else's words, not the operator's pick: it is delivered, marked, like any other message. A topic member's number DOES
10103
+ // answer — the one thing foreign words may do here: members answer the agent's questions, and only that (every other
10104
+ // control guard asks `checkIsForeignWords`).
10105
+ if (messageContext?.isForwarded !== true && await answerReAskedQuestionByNumber(key, text, messageContext))
9656
10106
  return;
9657
10107
  // A person wrote, in a window where the session is starting or being stopped: it counts like a message that reaches
9658
10108
  // `deliverActivePrompt` — the idle latch clears, and a question the idle compaction re-asked is closed (the idle fire
@@ -9682,9 +10132,12 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
9682
10132
  */
9683
10133
  async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext) {
9684
10134
  // A FORWARDED message is content, never control input: it answers no question and purges no context, whatever its words are.
10135
+ // A topic member's words are not the operator's either — but a bare option number of theirs DOES answer the agent's question
10136
+ // (members may answer questions, the one thing foreign words may do here), so the two answer routes below ask `isForwarded`
10137
+ // alone, while the context wipe asks `checkIsForeignWords`.
9685
10138
  const isForwarded = messageContext?.isForwarded === true;
9686
10139
  // A bare option number answers the question the idle compaction asked again (a tap's own label comes in with no intake).
9687
- if (intake !== null && !isForwarded && await answerReAskedQuestionByNumber(key, text))
10140
+ if (intake !== null && !isForwarded && await answerReAskedQuestionByNumber(key, text, messageContext))
9688
10141
  return null;
9689
10142
  // A genuine USER message (text or voice) — clear the compact-on-idle latch so
9690
10143
  // the next idle period can compact again (D2), whether it answers a pending
@@ -9699,7 +10152,7 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
9699
10152
  // the quote — the reply context is deliberately dropped here. Not a request
9700
10153
  // either: the turn it unblocks continues under the open one. A forwarded digit
9701
10154
  // is not a pick: it falls to the free-form route below and reaches the agent marked.
9702
- await applyQuestionAnswer(key, route.labels);
10155
+ await applyQuestionAnswer(key, route.labels, messageContext?.nonOperatorSender);
9703
10156
  return null;
9704
10157
  }
9705
10158
  // Free-form text cancels the question and is a fresh prompt — a request (S7).
@@ -9713,7 +10166,7 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
9713
10166
  // before forwarding — the slash text itself never gets a preamble. The agent's
9714
10167
  // context is gone, so any intake files it might reference are now useless —
9715
10168
  // purge the thread's files dir in the same breath.
9716
- if (text === forwardedClearCommand && !isForwarded) {
10169
+ if (text === forwardedClearCommand && !(0, messageContext_1.checkIsForeignWords)(messageContext)) {
9717
10170
  clearThreadContextMarker(key);
9718
10171
  await (0, botFileStorage_1.purgeThreadFiles)(getDataDir(), key).catch((e) => console.warn(`[file] purge on /clear failed for ${(0, sessionKey_1.keyToString)(key)}:`, e));
9719
10172
  }
@@ -9819,21 +10272,25 @@ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, mes
9819
10272
  * inline-button (`qa_`) and custom-text answer paths so both collect answers
9820
10273
  * locally instead of closing the request on the first answer with empties.
9821
10274
  */
9822
- async function applyQuestionAnswer(key, answerForCurrent) {
10275
+ async function applyQuestionAnswer(key, answerForCurrent, answeredBy) {
9823
10276
  // Serialized: an in-flight re-post (delete+re-send) must fully finish before
9824
10277
  // the answer reads `messageId` for its ✅-edit — otherwise the edit targets
9825
10278
  // a message the re-post just deleted (live 2026-06-10: "message to edit not
9826
10279
  // found" + the next question never reached the topic).
9827
- return runQuestionLifecycleOp(key, () => applyQuestionAnswerInner(key, answerForCurrent));
10280
+ return runQuestionLifecycleOp(key, () => applyQuestionAnswerInner(key, answerForCurrent, answeredBy));
9828
10281
  }
9829
- /** Resolves to whether the topic now shows the whole answer: the answered question's message was edited to carry it. */
9830
- async function applyQuestionAnswerInner(key, answerForCurrent) {
10282
+ /**
10283
+ * Resolves to whether the topic now shows the whole answer: the answered question's message was edited to carry it.
10284
+ * `answeredBy` (the description of a person who is not the operator) rides in the answer the agent reads — each part of a
10285
+ * question of several parts says who chose it — and never in the note the topic shows, which stays the chosen label.
10286
+ */
10287
+ async function applyQuestionAnswerInner(key, answerForCurrent, answeredBy) {
9831
10288
  const kStr = (0, sessionKey_1.keyToString)(key);
9832
10289
  const pending = pendingQuestions.get(kStr);
9833
10290
  if (!pending)
9834
10291
  return false;
9835
10292
  const answeredQuestion = pending.data.questions[pending.currentIndex];
9836
- const { nextState, action } = (0, openCodeQuestionFlow_1.recordAnswerAndAdvance)(pending, answerForCurrent);
10293
+ const { nextState, action } = (0, openCodeQuestionFlow_1.recordAnswerAndAdvance)(pending, answeredBy === undefined ? answerForCurrent : (0, authorMark_1.getAnswerWithAttribution)(answerForCurrent, answeredBy));
9837
10294
  // Mark the answered question's message as done: the question stays as asked, the chosen answer takes the place of
9838
10295
  // its buttons.
9839
10296
  const isAnswerShown = pending.messageId !== null && answeredQuestion !== undefined && await editQuestionMessageToClosed(key, pending.messageId, answeredQuestion, (0, i18n_1.t)('agent.question_answered_note', { answer: answerForCurrent.join(', ') }));
@@ -9891,10 +10348,23 @@ function handleAgentOutput(key, output, meta) {
9891
10348
  // skip while THIS thread's own compaction streams (loop guard).
9892
10349
  markThreadTurnProducedOutput(key);
9893
10350
  noteThreadActivity(key);
9894
- // A backend's own streamed compaction summary (OpenCode) obeys `/compact_summary`, like the
9895
- // summary the bot posts for the other backends: off → the compaction ends in its short notices.
9896
- if (meta?.isCompactionSummary && !state.checkIsCompactSummaryEnabled(key))
10351
+ // A backend's own streamed compaction summary (OpenCode) obeys `/compact_summary`, like the summary the bot posts for the
10352
+ // other backends: off → the compaction ends in its short notices, plus the summary's self-review section, which is
10353
+ // shown in hide mode too; on → the summary is shown without the marker lines the agent was asked to write.
10354
+ if (meta?.isCompactionSummary) {
10355
+ const summaryTail = routeStreamedCompactionSummaryTail(key, output, meta);
10356
+ if (summaryTail === null)
10357
+ return;
10358
+ deliverAgentOutput(key, summaryTail.text, { ...meta, isContinuation: summaryTail.isContinuation });
9897
10359
  return;
10360
+ }
10361
+ deliverAgentOutput(key, output, meta);
10362
+ }
10363
+ /**
10364
+ * @description The rest of {@link handleAgentOutput} for the text that is going to the topic: the answers-only view, the
10365
+ * sub-agent chunks, the questions and the answer itself.
10366
+ */
10367
+ function deliverAgentOutput(key, output, meta) {
9898
10368
  // Answers-only view (S9): the agent's text — sub-agent chunks and progress
9899
10369
  // bursts included — never reaches the topic; a native question still does (it
9900
10370
  // falls through to its branch below). A real answer still retires a pinned
@@ -11284,6 +11754,7 @@ exports.COMMANDS_MENU = [
11284
11754
  { command: 'compact', description: '🧹 Compact agent context' },
11285
11755
  { command: 'compact_on_idle', description: '🧹 Auto-compact after idle (toggle)' },
11286
11756
  { command: 'compact_summary', description: '📄 Post the compaction summary (toggle)' },
11757
+ { command: 'compact_self_review', description: '💡 Agent self-review on compaction: its mistakes and what to change in its instructions' },
11287
11758
  { command: 'bot_skills', description: '🧰 The bot\'s own skills for agents (on/off)' },
11288
11759
  { command: 'task_agents', description: '🧵 How many tracker task agents work at once' },
11289
11760
  { command: 'runners', description: '🖥 Runners — machines for the agents\' tests and builds' },
@@ -11301,6 +11772,7 @@ exports.COMMANDS_MENU = [
11301
11772
  { command: 'timestamps', description: '🕒 Prepend send time to forwarded prompts' },
11302
11773
  { command: 'language', description: '🌐 Bot language for this chat/group' },
11303
11774
  { command: 'timezone', description: '🌍 Timezone for schedules and time context' },
11775
+ { command: 'access', description: '🔑 Who may talk to the agent in this topic (without being an admin)' },
11304
11776
  { command: 'whoami', description: '🪪 Show debug ids' },
11305
11777
  { command: 'pair', description: '🔗 Bind this group to the bot' },
11306
11778
  { command: 'version', description: 'ℹ️ Versions of bot + CLI tools' },
@@ -12393,7 +12865,8 @@ function wireScheduler(wiring) {
12393
12865
  const decision = (0, validation_1.resolveBoundWorkDir)(ENV.workRoot, state.getBinding((0, sessionKey_1.keyFromString)(threadKeyStr)));
12394
12866
  if (decision.kind !== 'proceed')
12395
12867
  return null;
12396
- return (0, checkRun_1.runCheckCommand)({ command, cwd: decision.workDir, timeoutMs, env: (0, checkRun_1.buildCheckEnv)(process.env) });
12868
+ // A check runs what an agent wrote, and its output is posted into the topic: never with the bot's own secrets.
12869
+ return (0, checkRun_1.runCheckCommand)({ command, cwd: decision.workDir, timeoutMs, env: (0, agentEnvironment_1.getChildProcessEnvironment)() });
12397
12870
  },
12398
12871
  setCheckFailing: async (jobId, isFailing) => {
12399
12872
  const record = state.getSchedules()[jobId];
@@ -12774,6 +13247,8 @@ async function startBot() {
12774
13247
  (0, createAdapter_1.registerClaudeConfigDirReader)(resolveThreadClaudeConfigDir);
12775
13248
  // The «Bot skills» switch (`/bot_skills`): every agent start, the OpenCode server's start and the bot MCP's instructions read it.
12776
13249
  (0, botSkills_1.setBotSkillsReader)(botSkillsReader);
13250
+ // The flags the CLI's and OpenCode's own compactions read for `/compact_self_review` follow the saved settings from the start.
13251
+ syncAllCompactSelfReviewFlags();
12777
13252
  (0, createAdapter_1.registerClaudeRateLimitSink)(onClaudeRateLimitEvent);
12778
13253
  (0, createAdapter_1.registerClaudeTurnCostSink)(onClaudeTurnCost);
12779
13254
  if (ENV.testTimings.openCodeServerUpBudgetMs !== undefined)
@@ -12781,6 +13256,8 @@ async function startBot() {
12781
13256
  // The usage cache: a first poll now (off the boot path), then the timer.
12782
13257
  claudeUsageRefresher.start();
12783
13258
  void claudeUsageRefresher.refreshAll();
13259
+ // The daily recheck of API accounts marked used up (`utils/claudeApiCreditRecheck.ts`): a pass now — a day may have passed while the bot was down — then the timer.
13260
+ (0, claudeApiCreditRecheck_1.startClaudeApiCreditRechecks)(claudeApiCreditRecheckPorts, ENV.testTimings.creditRecheckPollMs ?? claudeApiCreditRecheck_1.claudeApiCreditRecheckPollMs);
12784
13261
  const jiraConnector = ENV.servedPlatforms.has('jira') ? await prepareJiraConnectorOrExit() : null;
12785
13262
  todoJiraConversations = jiraConnector;
12786
13263
  if (jiraConnector) {
@@ -12963,7 +13440,11 @@ async function startBot() {
12963
13440
  void todoReminderEngine?.noteAdapterTurnEnd(key).catch((e) => console.warn(`[todos] the turn end of ${(0, sessionKey_1.keyToString)(key)} was not noted:`, e instanceof Error ? e.message : e));
12964
13441
  handleAgentTurnEnded(key);
12965
13442
  }),
12966
- onContextCompacted: (key, trigger) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'contextCompacted', () => noteConversationContextReset(key, `compaction (${trigger ?? 'bot'})`)),
13443
+ onContextCompacted: (key, trigger) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'contextCompacted', () => {
13444
+ noteConversationContextReset(key, `compaction (${trigger ?? 'bot'})`);
13445
+ // The CLI's own overflow compaction: nobody else posts its self-review section (a bot-issued one is its caller's).
13446
+ void postOwnCompactionInstructionGaps(key).catch((e) => console.warn(`[compact] ${(0, sessionKey_1.keyToString)(key)} the self-review section of the CLI's own compaction was not posted:`, e instanceof Error ? e.message : e));
13447
+ }),
12967
13448
  onConversationLost: (key) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'conversationLost', () => withThreadLocale(key, () => handleConversationLost(key)), () => { dropLostConversationWatermark(key); noteConversationContextReset(key, 'its transcript was lost'); }),
12968
13449
  onError: (key, error) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'error', () => withThreadLocale(key, () => handleAgentError(key, error)), () => {
12969
13450
  console.error(`[Bot] adapter error ${(0, sessionKey_1.keyToString)(key)}:`, error.message);
@@ -13119,13 +13600,13 @@ async function startBot() {
13119
13600
  // generation pointing at a now-dead port. Reconcile against the live MCP
13120
13601
  // status and force-refresh any directory that is not `connected`.
13121
13602
  // Fire-and-forget: boot must not block on opencode HTTP round-trips
13122
- // before `bot.launch()`. The skills step (a server started without the
13123
- // bot's skills folder is replaced) and the compaction-plugin step go FIRST:
13603
+ // before `bot.launch()`. The launch step (a server started without the
13604
+ // bot's skills folder or without a password is replaced) and the compaction-plugin step go FIRST:
13124
13605
  // a replaced server or a recreated directory instance drops the MCP
13125
13606
  // registration, which this same reconcile then restores.
13126
13607
  const openCodeAdapter = (0, createAdapter_1.getAdapter)('opencode');
13127
13608
  void (async () => {
13128
- await openCodeAdapter.activateAgentSkillsForServer?.();
13609
+ await openCodeAdapter.replaceMislaunchedServer?.();
13129
13610
  await openCodeAdapter.activateCompactionPluginForActiveSessions?.();
13130
13611
  await openCodeAdapter.reconcileSchedulerMcpForActiveSessions?.();
13131
13612
  })().catch((e) => console.warn('[scheduler] MCP reconcile failed:', e instanceof Error ? e.message : e));