charness 3.12.0 → 3.14.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 (295) hide show
  1. package/.env.example +5 -0
  2. package/CHANGELOG.md +40 -0
  3. package/DEVELOPMENT.md +80 -16
  4. package/README.md +2 -1
  5. package/SETUP.md +65 -20
  6. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +14 -5
  7. package/dist/accessControl.d.ts +43 -0
  8. package/dist/accessControl.d.ts.map +1 -1
  9. package/dist/accessControl.js +50 -1
  10. package/dist/accessControl.js.map +1 -1
  11. package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
  12. package/dist/adapters/claudeCliAdapter.js +17 -19
  13. package/dist/adapters/claudeCliAdapter.js.map +1 -1
  14. package/dist/adapters/claudeJsonStreamAdapter.d.ts +29 -10
  15. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  16. package/dist/adapters/claudeJsonStreamAdapter.js +73 -28
  17. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  18. package/dist/adapters/claudePlatformFlags.d.ts +4 -3
  19. package/dist/adapters/claudePlatformFlags.d.ts.map +1 -1
  20. package/dist/adapters/claudePlatformFlags.js +4 -3
  21. package/dist/adapters/claudePlatformFlags.js.map +1 -1
  22. package/dist/adapters/openCodeAdapter.d.ts +111 -24
  23. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  24. package/dist/adapters/openCodeAdapter.js +288 -83
  25. package/dist/adapters/openCodeAdapter.js.map +1 -1
  26. package/dist/adapters/terminalAdapter.d.ts.map +1 -1
  27. package/dist/adapters/terminalAdapter.js +5 -3
  28. package/dist/adapters/terminalAdapter.js.map +1 -1
  29. package/dist/agentLogin/agentLogin.d.ts.map +1 -1
  30. package/dist/agentLogin/agentLogin.js +2 -14
  31. package/dist/agentLogin/agentLogin.js.map +1 -1
  32. package/dist/bot.d.ts +12 -3
  33. package/dist/bot.d.ts.map +1 -1
  34. package/dist/bot.js +504 -144
  35. package/dist/bot.js.map +1 -1
  36. package/dist/cli/claudeProfiles.js +2 -2
  37. package/dist/cli/claudeProfiles.js.map +1 -1
  38. package/dist/connectors/jira/client.js +1 -1
  39. package/dist/connectors/jira/client.js.map +1 -1
  40. package/dist/connectors/jira/config.d.ts +7 -0
  41. package/dist/connectors/jira/config.d.ts.map +1 -1
  42. package/dist/connectors/jira/config.js +12 -1
  43. package/dist/connectors/jira/config.js.map +1 -1
  44. package/dist/connectors/jira/connector.d.ts +7 -0
  45. package/dist/connectors/jira/connector.d.ts.map +1 -1
  46. package/dist/connectors/jira/connector.js +20 -3
  47. package/dist/connectors/jira/connector.js.map +1 -1
  48. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  49. package/dist/connectors/jira/inbound.js +4 -3
  50. package/dist/connectors/jira/inbound.js.map +1 -1
  51. package/dist/connectors/jira/issueBlocks.d.ts +1 -1
  52. package/dist/connectors/jira/trustedGroup.d.ts +21 -6
  53. package/dist/connectors/jira/trustedGroup.d.ts.map +1 -1
  54. package/dist/connectors/jira/trustedGroup.js +46 -6
  55. package/dist/connectors/jira/trustedGroup.js.map +1 -1
  56. package/dist/connectors/telegram/commands/botCore.d.ts +19 -2
  57. package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -1
  58. package/dist/connectors/telegram/commands/compaction.d.ts +5 -3
  59. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  60. package/dist/connectors/telegram/commands/compaction.js +21 -6
  61. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  62. package/dist/connectors/telegram/commands/todo.d.ts.map +1 -1
  63. package/dist/connectors/telegram/commands/todo.js +2 -2
  64. package/dist/connectors/telegram/commands/todo.js.map +1 -1
  65. package/dist/connectors/telegram/commands/topicAccess.d.ts +30 -0
  66. package/dist/connectors/telegram/commands/topicAccess.d.ts.map +1 -0
  67. package/dist/connectors/telegram/commands/topicAccess.js +399 -0
  68. package/dist/connectors/telegram/commands/topicAccess.js.map +1 -0
  69. package/dist/connectors/telegram/inbound.d.ts +44 -7
  70. package/dist/connectors/telegram/inbound.d.ts.map +1 -1
  71. package/dist/connectors/telegram/inbound.js +142 -24
  72. package/dist/connectors/telegram/inbound.js.map +1 -1
  73. package/dist/i18n/de.d.ts.map +1 -1
  74. package/dist/i18n/de.js +68 -0
  75. package/dist/i18n/de.js.map +1 -1
  76. package/dist/i18n/en.d.ts.map +1 -1
  77. package/dist/i18n/en.js +68 -0
  78. package/dist/i18n/en.js.map +1 -1
  79. package/dist/i18n/es.d.ts.map +1 -1
  80. package/dist/i18n/es.js +68 -0
  81. package/dist/i18n/es.js.map +1 -1
  82. package/dist/i18n/fr.d.ts.map +1 -1
  83. package/dist/i18n/fr.js +68 -0
  84. package/dist/i18n/fr.js.map +1 -1
  85. package/dist/i18n/hi.d.ts.map +1 -1
  86. package/dist/i18n/hi.js +68 -0
  87. package/dist/i18n/hi.js.map +1 -1
  88. package/dist/i18n/ja.d.ts.map +1 -1
  89. package/dist/i18n/ja.js +68 -0
  90. package/dist/i18n/ja.js.map +1 -1
  91. package/dist/i18n/ka.d.ts.map +1 -1
  92. package/dist/i18n/ka.js +68 -0
  93. package/dist/i18n/ka.js.map +1 -1
  94. package/dist/i18n/pt.d.ts.map +1 -1
  95. package/dist/i18n/pt.js +68 -0
  96. package/dist/i18n/pt.js.map +1 -1
  97. package/dist/i18n/ru.d.ts.map +1 -1
  98. package/dist/i18n/ru.js +68 -0
  99. package/dist/i18n/ru.js.map +1 -1
  100. package/dist/i18n/uk.d.ts.map +1 -1
  101. package/dist/i18n/uk.js +68 -0
  102. package/dist/i18n/uk.js.map +1 -1
  103. package/dist/i18n/uz.d.ts.map +1 -1
  104. package/dist/i18n/uz.js +68 -0
  105. package/dist/i18n/uz.js.map +1 -1
  106. package/dist/i18n/zh.d.ts.map +1 -1
  107. package/dist/i18n/zh.js +68 -0
  108. package/dist/i18n/zh.js.map +1 -1
  109. package/dist/installManager.d.ts +37 -1
  110. package/dist/installManager.d.ts.map +1 -1
  111. package/dist/installManager.js +205 -14
  112. package/dist/installManager.js.map +1 -1
  113. package/dist/legacyNames.d.ts +8 -0
  114. package/dist/legacyNames.d.ts.map +1 -1
  115. package/dist/legacyNames.js +9 -1
  116. package/dist/legacyNames.js.map +1 -1
  117. package/dist/mcpConfig.d.ts +4 -1
  118. package/dist/mcpConfig.d.ts.map +1 -1
  119. package/dist/mcpConfig.js +27 -2
  120. package/dist/mcpConfig.js.map +1 -1
  121. package/dist/platform/commandRouter.d.ts +13 -1
  122. package/dist/platform/commandRouter.d.ts.map +1 -1
  123. package/dist/platform/commandRouter.js +14 -2
  124. package/dist/platform/commandRouter.js.map +1 -1
  125. package/dist/platform/inbound.d.ts +2 -0
  126. package/dist/platform/inbound.d.ts.map +1 -1
  127. package/dist/runnerUtility/launcher.d.ts.map +1 -1
  128. package/dist/runnerUtility/launcher.js +11 -3
  129. package/dist/runnerUtility/launcher.js.map +1 -1
  130. package/dist/runners/runnerLock.d.ts +36 -1
  131. package/dist/runners/runnerLock.d.ts.map +1 -1
  132. package/dist/runners/runnerLock.js +94 -30
  133. package/dist/runners/runnerLock.js.map +1 -1
  134. package/dist/scheduler/checkRun.d.ts +0 -2
  135. package/dist/scheduler/checkRun.d.ts.map +1 -1
  136. package/dist/scheduler/checkRun.js +0 -10
  137. package/dist/scheduler/checkRun.js.map +1 -1
  138. package/dist/scheduler/injection.d.ts +7 -3
  139. package/dist/scheduler/injection.d.ts.map +1 -1
  140. package/dist/scheduler/injection.js +7 -3
  141. package/dist/scheduler/injection.js.map +1 -1
  142. package/dist/scheduler/mcpBoot.d.ts +10 -1
  143. package/dist/scheduler/mcpBoot.d.ts.map +1 -1
  144. package/dist/scheduler/mcpBoot.js +6 -1
  145. package/dist/scheduler/mcpBoot.js.map +1 -1
  146. package/dist/scheduler/mcpSurface.js +1 -1
  147. package/dist/scheduler/mcpSurface.js.map +1 -1
  148. package/dist/scheduler/workerActivity.d.ts.map +1 -1
  149. package/dist/scheduler/workerActivity.js +2 -1
  150. package/dist/scheduler/workerActivity.js.map +1 -1
  151. package/dist/selfUpdate/bootRollback.d.ts.map +1 -1
  152. package/dist/selfUpdate/bootRollback.js +3 -2
  153. package/dist/selfUpdate/bootRollback.js.map +1 -1
  154. package/dist/selfUpdate/updateRuntime.d.ts.map +1 -1
  155. package/dist/selfUpdate/updateRuntime.js +6 -3
  156. package/dist/selfUpdate/updateRuntime.js.map +1 -1
  157. package/dist/state.d.ts +50 -1
  158. package/dist/state.d.ts.map +1 -1
  159. package/dist/state.js +112 -0
  160. package/dist/state.js.map +1 -1
  161. package/dist/stateFile.d.ts.map +1 -1
  162. package/dist/stateFile.js +2 -1
  163. package/dist/stateFile.js.map +1 -1
  164. package/dist/testTimings.d.ts +3 -2
  165. package/dist/testTimings.d.ts.map +1 -1
  166. package/dist/testTimings.js +8 -1
  167. package/dist/testTimings.js.map +1 -1
  168. package/dist/threadContextPreamble.d.ts +15 -1
  169. package/dist/threadContextPreamble.d.ts.map +1 -1
  170. package/dist/threadContextPreamble.js +15 -3
  171. package/dist/threadContextPreamble.js.map +1 -1
  172. package/dist/threadRouting.d.ts +47 -4
  173. package/dist/threadRouting.d.ts.map +1 -1
  174. package/dist/threadRouting.js +31 -4
  175. package/dist/threadRouting.js.map +1 -1
  176. package/dist/todos/projects.d.ts +1 -1
  177. package/dist/todos/projects.d.ts.map +1 -1
  178. package/dist/todos/projects.js +3 -14
  179. package/dist/todos/projects.js.map +1 -1
  180. package/dist/topicTalkerMemory.d.ts +37 -0
  181. package/dist/topicTalkerMemory.d.ts.map +1 -0
  182. package/dist/topicTalkerMemory.js +61 -0
  183. package/dist/topicTalkerMemory.js.map +1 -0
  184. package/dist/topicTalkers.d.ts +123 -0
  185. package/dist/topicTalkers.d.ts.map +1 -0
  186. package/dist/topicTalkers.js +276 -0
  187. package/dist/topicTalkers.js.map +1 -0
  188. package/dist/types.d.ts +16 -12
  189. package/dist/types.d.ts.map +1 -1
  190. package/dist/utils/adoptReplayGate.d.ts +7 -5
  191. package/dist/utils/adoptReplayGate.d.ts.map +1 -1
  192. package/dist/utils/adoptReplayGate.js +7 -5
  193. package/dist/utils/adoptReplayGate.js.map +1 -1
  194. package/dist/utils/agentEnvironment.d.ts +23 -0
  195. package/dist/utils/agentEnvironment.d.ts.map +1 -1
  196. package/dist/utils/agentEnvironment.js +33 -1
  197. package/dist/utils/agentEnvironment.js.map +1 -1
  198. package/dist/utils/agentPlugin.d.ts +7 -2
  199. package/dist/utils/agentPlugin.d.ts.map +1 -1
  200. package/dist/utils/agentPlugin.js +11 -5
  201. package/dist/utils/agentPlugin.js.map +1 -1
  202. package/dist/utils/authorMark.d.ts +59 -0
  203. package/dist/utils/authorMark.d.ts.map +1 -0
  204. package/dist/utils/authorMark.js +86 -0
  205. package/dist/utils/authorMark.js.map +1 -0
  206. package/dist/utils/checkIsRecord.d.ts +6 -0
  207. package/dist/utils/checkIsRecord.d.ts.map +1 -0
  208. package/dist/utils/checkIsRecord.js +11 -0
  209. package/dist/utils/checkIsRecord.js.map +1 -0
  210. package/dist/utils/claudeCompactSummary.js +4 -4
  211. package/dist/utils/claudeCompactSummary.js.map +1 -1
  212. package/dist/utils/claudeLimitSwitch.d.ts +5 -1
  213. package/dist/utils/claudeLimitSwitch.d.ts.map +1 -1
  214. package/dist/utils/claudeLimitSwitch.js +6 -2
  215. package/dist/utils/claudeLimitSwitch.js.map +1 -1
  216. package/dist/utils/claudeMcpHeal.d.ts +18 -3
  217. package/dist/utils/claudeMcpHeal.d.ts.map +1 -1
  218. package/dist/utils/claudeMcpHeal.js +19 -4
  219. package/dist/utils/claudeMcpHeal.js.map +1 -1
  220. package/dist/utils/claudeProfileUsageLines.d.ts +1 -1
  221. package/dist/utils/claudeProfileUsageLines.js +3 -3
  222. package/dist/utils/claudeProfileUsageLines.js.map +1 -1
  223. package/dist/utils/claudeProfiles.d.ts +7 -0
  224. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  225. package/dist/utils/claudeProfiles.js +15 -0
  226. package/dist/utils/claudeProfiles.js.map +1 -1
  227. package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -1
  228. package/dist/utils/claudeRuntimeInfo.js +4 -6
  229. package/dist/utils/claudeRuntimeInfo.js.map +1 -1
  230. package/dist/utils/claudeStreamJson.d.ts +0 -3
  231. package/dist/utils/claudeStreamJson.d.ts.map +1 -1
  232. package/dist/utils/claudeStreamJson.js +21 -26
  233. package/dist/utils/claudeStreamJson.js.map +1 -1
  234. package/dist/utils/claudeSubagentTail.d.ts.map +1 -1
  235. package/dist/utils/claudeSubagentTail.js +4 -11
  236. package/dist/utils/claudeSubagentTail.js.map +1 -1
  237. package/dist/utils/claudeUsage.d.ts +56 -20
  238. package/dist/utils/claudeUsage.d.ts.map +1 -1
  239. package/dist/utils/claudeUsage.js +89 -48
  240. package/dist/utils/claudeUsage.js.map +1 -1
  241. package/dist/utils/fallbackChain.d.ts.map +1 -1
  242. package/dist/utils/fallbackChain.js +8 -4
  243. package/dist/utils/fallbackChain.js.map +1 -1
  244. package/dist/utils/folderGit.d.ts +9 -0
  245. package/dist/utils/folderGit.d.ts.map +1 -0
  246. package/dist/utils/folderGit.js +33 -0
  247. package/dist/utils/folderGit.js.map +1 -0
  248. package/dist/utils/forwardedMark.d.ts +8 -0
  249. package/dist/utils/forwardedMark.d.ts.map +1 -1
  250. package/dist/utils/forwardedMark.js +2 -0
  251. package/dist/utils/forwardedMark.js.map +1 -1
  252. package/dist/utils/jsonStreamHost.d.ts +2 -1
  253. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  254. package/dist/utils/jsonStreamHost.js +4 -2
  255. package/dist/utils/jsonStreamHost.js.map +1 -1
  256. package/dist/utils/messageContext.d.ts +22 -7
  257. package/dist/utils/messageContext.d.ts.map +1 -1
  258. package/dist/utils/messageContext.js +19 -5
  259. package/dist/utils/messageContext.js.map +1 -1
  260. package/dist/utils/openCodeUsage.d.ts.map +1 -1
  261. package/dist/utils/openCodeUsage.js +8 -10
  262. package/dist/utils/openCodeUsage.js.map +1 -1
  263. package/dist/utils/personLabel.d.ts +13 -0
  264. package/dist/utils/personLabel.d.ts.map +1 -0
  265. package/dist/utils/personLabel.js +15 -0
  266. package/dist/utils/personLabel.js.map +1 -0
  267. package/dist/utils/replyQuote.d.ts +17 -3
  268. package/dist/utils/replyQuote.d.ts.map +1 -1
  269. package/dist/utils/replyQuote.js +25 -2
  270. package/dist/utils/replyQuote.js.map +1 -1
  271. package/dist/utils/talkerAccess.d.ts +9 -0
  272. package/dist/utils/talkerAccess.d.ts.map +1 -0
  273. package/dist/utils/talkerAccess.js +20 -0
  274. package/dist/utils/talkerAccess.js.map +1 -0
  275. package/dist/utils/telegramError.d.ts.map +1 -1
  276. package/dist/utils/telegramError.js +5 -7
  277. package/dist/utils/telegramError.js.map +1 -1
  278. package/dist/utils/tmuxExec.d.ts +20 -8
  279. package/dist/utils/tmuxExec.d.ts.map +1 -1
  280. package/dist/utils/tmuxExec.js +27 -7
  281. package/dist/utils/tmuxExec.js.map +1 -1
  282. package/dist/utils/topicAccessScreenPlan.d.ts +253 -0
  283. package/dist/utils/topicAccessScreenPlan.d.ts.map +1 -0
  284. package/dist/utils/topicAccessScreenPlan.js +287 -0
  285. package/dist/utils/topicAccessScreenPlan.js.map +1 -0
  286. package/dist/utils/topicLabel.d.ts +12 -0
  287. package/dist/utils/topicLabel.d.ts.map +1 -0
  288. package/dist/utils/topicLabel.js +12 -0
  289. package/dist/utils/topicLabel.js.map +1 -0
  290. package/dist/utils/topicRequest.d.ts +8 -5
  291. package/dist/utils/topicRequest.d.ts.map +1 -1
  292. package/dist/utils/topicRequest.js +9 -7
  293. package/dist/utils/topicRequest.js.map +1 -1
  294. package/npm-shrinkwrap.json +1003 -0
  295. package/package.json +4 -2
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");
@@ -200,12 +205,15 @@ const jsonStreamHost_1 = require("./utils/jsonStreamHost");
200
205
  const runLedger_1 = require("./scheduler/runLedger");
201
206
  const delivery_1 = require("./scheduler/delivery");
202
207
  const checkRun_1 = require("./scheduler/checkRun");
208
+ const agentEnvironment_1 = require("./utils/agentEnvironment");
209
+ const folderGit_1 = require("./utils/folderGit");
203
210
  const checkStatus_1 = require("./scheduler/checkStatus");
204
211
  const workerActivity_1 = require("./scheduler/workerActivity");
205
212
  const engine_1 = require("./scheduler/engine");
206
213
  const recurrence_1 = require("./scheduler/recurrence");
207
214
  const mcpSurface_1 = require("./scheduler/mcpSurface");
208
215
  const injection_1 = require("./scheduler/injection");
216
+ const legacyNames_1 = require("./legacyNames");
209
217
  const mcpBoot_1 = require("./scheduler/mcpBoot");
210
218
  const requestLedger_1 = require("./requests/requestLedger");
211
219
  const answerRequest_1 = require("./requests/answerRequest");
@@ -246,6 +254,7 @@ const callbackToast_2 = require("./connectors/telegram/commands/callbackToast");
246
254
  const compaction_1 = require("./connectors/telegram/commands/compaction");
247
255
  const autoContinueLimits_1 = require("./connectors/telegram/commands/autoContinueLimits");
248
256
  const botSkills_2 = require("./connectors/telegram/commands/botSkills");
257
+ const topicAccess_1 = require("./connectors/telegram/commands/topicAccess");
249
258
  const taskAgents_1 = require("./connectors/telegram/commands/taskAgents");
250
259
  const runners_1 = require("./connectors/telegram/commands/runners");
251
260
  const gateWrapper_1 = require("./runners/gateWrapper");
@@ -331,7 +340,8 @@ function parseEnv() {
331
340
  // (without it the DM surface would have no access authority — any user can DM a
332
341
  // bot). For `both` it is OPTIONAL: set → the DM surface is active; unset → the
333
342
  // DM surface is INERT (group-only) and boot logs a notice, so default `both`
334
- // stays backward-compatible with a bare group-only deploy. Ignored in `group`.
343
+ // stays backward-compatible with a bare group-only deploy. In `group` it only
344
+ // decides who may pair the bot with a group (`getPairingRefusal`).
335
345
  const ownerUserIdRaw = (process.env.OWNER_USER_ID ?? '').trim();
336
346
  let ownerUserId = NaN;
337
347
  if (ownerUserIdRaw) {
@@ -615,8 +625,21 @@ const adminCache = new accessControl_1.AdminCache({
615
625
  return Promise.resolve([]);
616
626
  return telegramInbound.listMembersWithElevatedRights(groupId.toString());
617
627
  },
628
+ // The admins' @usernames, refreshed with the ids: `/access add @name` refuses an admin it has not seen write.
629
+ fetchElevatedMemberHandles: () => {
630
+ const groupId = getAllowedGroupId();
631
+ if (groupId === null)
632
+ return Promise.resolve([]);
633
+ return telegramInbound.listHandlesOfMembersWithElevatedRights(groupId.toString());
634
+ },
618
635
  ttlMs: accessControl_1.ADMIN_CACHE_TTL_MS,
619
636
  });
637
+ /**
638
+ * The people who wrote in a topic and were ignored, and the @usernames seen writing in the served group
639
+ * (`topicTalkerMemory.ts`): in memory only, a convenience for an admin adding a talker. Fed by `noteServedGroupSender`.
640
+ */
641
+ const recentTopicWriters = (0, topicTalkerMemory_1.createRecentWriters)();
642
+ const seenGroupSenders = (0, topicTalkerMemory_1.createSeenSenders)();
620
643
  /**
621
644
  * @description True iff the sender of `ctx` may use the bot — decided PER CHAT,
622
645
  * which is the single source of truth for access on each surface:
@@ -653,6 +676,45 @@ async function checkIsForumAdmin(chatId, userId) {
653
676
  return false;
654
677
  }
655
678
  }
679
+ /**
680
+ * @description Whether `userId` created group `chatId` (Telegram's `creator` status). A member read that fails is told apart:
681
+ * the group itself not answering (deleted, the bot removed from it) is `unreadable`; a group that answers is `notCreator` —
682
+ * a sender who is no member at all reads that way too.
683
+ */
684
+ async function readGroupCreatorship(chatId, userId) {
685
+ try {
686
+ return (await bot.telegram.getChatMember(chatId, userId)).status === 'creator' ? 'creator' : 'notCreator';
687
+ }
688
+ catch (memberError) {
689
+ try {
690
+ await bot.telegram.getChat(chatId);
691
+ return 'notCreator';
692
+ }
693
+ catch (groupError) {
694
+ console.warn(`[pair] the served group ${chatId} cannot be read:`, groupError instanceof Error ? groupError.message : groupError, '— member read:', memberError instanceof Error ? memberError.message : memberError);
695
+ return 'unreadable';
696
+ }
697
+ }
698
+ }
699
+ /**
700
+ * @description Why `senderId` may not pair the bot with `targetGroupId` (`null`: allowed) — the rule is
701
+ * {@link getPairingRefusal}'s, fed with this instance's owner, the group served now and the Telegram reads it needs.
702
+ */
703
+ function getPairingRefusalFor(senderId, targetGroupId) {
704
+ const ownerUserId = getOwnerUserId();
705
+ const currentGroupId = getAllowedGroupId();
706
+ return (0, threadRouting_1.getPairingRefusal)({ ownerUserId: Number.isFinite(ownerUserId) ? ownerUserId : null, senderId, currentGroupId, targetGroupId }, {
707
+ checkIsTargetGroupAdmin: () => checkIsForumAdmin(targetGroupId, senderId),
708
+ readCurrentGroupCreatorship: () => (currentGroupId === null ? Promise.resolve('notCreator') : readGroupCreatorship(currentGroupId, senderId)),
709
+ });
710
+ }
711
+ /** The refusal each {@link PairingRefusal} answers `/pair` with. */
712
+ const pairingRefusalTextKeys = {
713
+ notOwner: 'pair.not_owner',
714
+ notCurrentCreator: 'pair.not_current_creator',
715
+ currentGroupUnreadable: 'pair.current_group_unreadable',
716
+ notAdmin: 'pair.not_admin',
717
+ };
656
718
  // Telegraf builds a NEW `Telegram` client for every update (`ctx.telegram`, behind every `ctx.reply`, `ctx.answerCbQuery`
657
719
  // and `ctx.editMessageText`) from `bot.telegram.options`, so the wiring of `bot.telegram` does not reach it and an
658
720
  // `http://` root drops the agent again. Wire it before any handler can use it.
@@ -712,6 +774,30 @@ bot.use(async (ctx, next) => {
712
774
  await tryAutoPair(ctx);
713
775
  return next();
714
776
  });
777
+ // What the bot learns from every message of the served group, before any handler gates it: the sender's name and @username
778
+ // (a talker's entries keep up with a rename), an invitation that waited for this person's first message turns into a grant — so
779
+ // a message that comes with it is already a talker's — and a stranger's message is remembered for the add screen.
780
+ bot.use(async (ctx, next) => {
781
+ try {
782
+ await noteServedGroupSender(ctx);
783
+ }
784
+ catch (e) {
785
+ console.warn('[access] noting the sender of an update failed:', e instanceof Error ? e.message : e);
786
+ }
787
+ return next();
788
+ });
789
+ // Default-deny for talkers on buttons: a person an admin let talk to the agent here may tap only the agent's own question
790
+ // buttons (`checkIsTalkerCallback`). Every other tap is refused with one toast, here, so no handler or module has to know a
791
+ // talker exists — each of them keeps asking the admin gate.
792
+ bot.use(async (ctx, next) => {
793
+ if (ctx.callbackQuery && (await checkIsTalkerTapRefused(ctx))) {
794
+ await ctx.answerCbQuery((0, i18n_1.t)('access.adminOnlyButtonToast')).catch((e) => {
795
+ console.warn('[access] answering a refused tap failed:', e instanceof Error ? e.message : e);
796
+ });
797
+ return;
798
+ }
799
+ return next();
800
+ });
715
801
  // ═══════════════════════════════════════════════════════════════════════════════
716
802
  // Constants
717
803
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -877,9 +963,9 @@ async function openTopicRequest(key, text, intake, messageContext) {
877
963
  // AGAIN when the session never took it in; the raw text would come back without the forwarded mark or the quote.
878
964
  const promptBody = getPromptWithThreadMessageContext(key, text, messageContext);
879
965
  const request = await topicRequestLedger.createRequest(key, (0, topicRequest_1.getTopicRequestOrigin)(intake), {
880
- createPrompt: (requestId, supersededRequestIds) => (0, topicRequest_1.buildTopicRequestPrompt)({ requestId, source: intake.source, view, supersededRequestIds, promptBody }),
966
+ createPrompt: (requestId, supersededRequestIds) => (0, topicRequest_1.buildTopicRequestPrompt)({ requestId, source: intake.source, view, supersededRequestIds, promptBody, sender: messageContext?.nonOperatorSender }),
881
967
  });
882
- return { header: (0, topicRequest_1.buildTopicRequestHeader)(request.id, intake.source, view, request.supersededRequestIds), requestId: request.id };
968
+ return { header: (0, topicRequest_1.buildTopicRequestHeader)(request.id, intake.source, view, request.supersededRequestIds, messageContext?.nonOperatorSender), requestId: request.id };
883
969
  }
884
970
  /**
885
971
  * @description Where a topic request goes once its prompt came back from the prompt path (`requests/topicRequestSettle.ts`): the
@@ -2615,10 +2701,11 @@ async function tryAutoPair(ctx) {
2615
2701
  return;
2616
2702
  const chat = getRouteChat(ctx);
2617
2703
  // While unpaired, log every incoming update so the operator can see
2618
- // exactly what reaches the bot. Without this, the three ways pairing
2619
- // can silently fail — privacy mode (no update at all), a non-forum chat,
2620
- // or a sender who isn't a group admin — are indistinguishable from "bot
2621
- // is broken". Gated to pairing mode so normal operation stays quiet.
2704
+ // exactly what reaches the bot. Without this, the ways pairing can
2705
+ // silently fail — privacy mode (no update at all), a non-forum chat, or a
2706
+ // sender who may not pair (not the owner, not a group admin) — are
2707
+ // indistinguishable from "bot is broken". Gated to pairing mode so normal
2708
+ // operation stays quiet.
2622
2709
  if (!isGroupLockedByEnv && getAllowedGroupId() === null) {
2623
2710
  console.log(`[pair] incoming ${ctx.updateType} update: chat=${chat?.id} type=${chat?.type} ` +
2624
2711
  `is_forum=${chat?.is_forum} from=${ctx.from?.id}`);
@@ -2630,15 +2717,18 @@ async function tryAutoPair(ctx) {
2630
2717
  });
2631
2718
  if (candidate === null)
2632
2719
  return;
2633
- // Authority probe: only a creator/administrator of the candidate group may
2634
- // pair the bot, so a random group the bot is added to can't hijack it.
2720
+ // Who may pair (`getPairingRefusal`): with an owner set, the owner alone; without one, an administrator of the group —
2721
+ // the first pairing only, which is all auto-pairing ever is. Administering the group alone proves nothing: anyone who
2722
+ // makes a group and adds the bot is its creator.
2635
2723
  const userId = ctx.from?.id;
2636
- if (!userId || !(await checkIsForumAdmin(candidate, userId))) {
2637
- console.warn(`[pair] ignored pairing from chat ${candidate} user ${userId ?? '?'} (not a group admin)`);
2724
+ const refusal = userId ? await getPairingRefusalFor(userId, candidate) : 'notAdmin';
2725
+ if (refusal !== null) {
2726
+ console.warn(`[pair] ignored pairing from chat ${candidate} user ${userId ?? '?'} (${refusal})`);
2638
2727
  return;
2639
2728
  }
2640
2729
  effectiveGroupId = candidate;
2641
2730
  await state.setPairedGroupId(candidate);
2731
+ await state.dropTopicTalkersOfOtherChats(candidate);
2642
2732
  adminCache.invalidate();
2643
2733
  console.log(`[pair] auto-paired forum supergroup ${candidate} (persisted to state.json)`);
2644
2734
  const key = getThreadKey(ctx) ?? (0, sessionKeyCodec_1.makeTelegramKey)(candidate, threadRouting_1.GENERAL_THREAD_ID);
@@ -2667,15 +2757,101 @@ async function authoriseContext(ctx) {
2667
2757
  }
2668
2758
  return null;
2669
2759
  }
2670
- // Refresh the group-title cache from this authorised update — supergroups
2671
- // always carry `chat.title`. Feeds the thread-context preamble (S2). Cheap,
2672
- // idempotent, and the only place every accepted update funnels through. A
2673
- // private chat (DM key) has no `title`, so there is nothing to cache (the
2674
- // preamble falls back to the bot name) — skip it explicitly.
2760
+ noteGroupTitle(ctx, key);
2761
+ return key;
2762
+ }
2763
+ /**
2764
+ * Refresh the group-title cache from an accepted update — supergroups always carry `chat.title`. Feeds the thread-context
2765
+ * preamble (S2). Cheap, idempotent, and the one place every accepted update funnels through. A private chat (DM key) has
2766
+ * no `title`, so there is nothing to cache (the preamble falls back to the bot name) — skip it explicitly.
2767
+ */
2768
+ function noteGroupTitle(ctx, key) {
2675
2769
  if (!checkIsDmKey(key) && ctx.chat && 'title' in ctx.chat && ctx.chat.title) {
2676
2770
  groupTitleCache.set(ctx.chat.id, ctx.chat.title);
2677
2771
  }
2678
- return key;
2772
+ }
2773
+ /** The General topic of the group `key` is in — the one whose talker list is group-wide. */
2774
+ function getGroupGeneralKey(key) {
2775
+ return (0, sessionKeyCodec_1.makeTelegramKey)((0, sessionKeyCodec_1.getTelegramChatId)(key), threadRouting_1.GENERAL_THREAD_ID);
2776
+ }
2777
+ /**
2778
+ * @description What the sender of a group update is to the bot in its topic — an admin, a talker, or nobody — with the
2779
+ * topic's key; `null` outside a group topic (a foreign chat, no sender, the owner's DM, which has no talkers). The ONE place
2780
+ * the role is computed: the speaker gate, the sender tracking and the button check all read it.
2781
+ */
2782
+ async function getGroupSpeakerRole(ctx) {
2783
+ const userId = ctx.from?.id;
2784
+ if (userId === undefined)
2785
+ return null;
2786
+ const key = getThreadKey(ctx);
2787
+ if (key === null || checkIsDmKey(key))
2788
+ return null;
2789
+ const role = (0, accessControl_1.getSenderRole)({
2790
+ userId: userId.toString(),
2791
+ adminIds: await adminCache.getAdminIds(),
2792
+ talkerIds: state.getEffectiveTalkerIds(key, getGroupGeneralKey(key)),
2793
+ });
2794
+ return { key, role };
2795
+ }
2796
+ /**
2797
+ * @description The speaker gate: an admin anywhere (the owner in the DM), or a talker in the group topic whose list — or
2798
+ * General's — holds them; nobody else. It sits NEXT TO {@link authoriseContext}, which stays the admin-only gate: only the
2799
+ * routes a talker may use call this one (talking to the agent: text, voice, files, albums; answering its questions), and the
2800
+ * role travels from here as a value, so a route cannot ask ÂĢis this a talker?Âģ a second way. Everything else keeps asking
2801
+ * `authoriseContext` and so refuses a talker without knowing one exists.
2802
+ */
2803
+ async function authoriseTopicSpeaker(ctx) {
2804
+ const groupSpeaker = await getGroupSpeakerRole(ctx);
2805
+ if (groupSpeaker?.role === 'talker') {
2806
+ noteGroupTitle(ctx, groupSpeaker.key);
2807
+ return { key: groupSpeaker.key, role: 'talker' };
2808
+ }
2809
+ const adminKey = await authoriseContext(ctx);
2810
+ return adminKey === null ? null : { key: adminKey, role: 'admin' };
2811
+ }
2812
+ /** @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. */
2813
+ async function checkIsTalkerTapRefused(ctx) {
2814
+ const callbackData = ctx.callbackQuery && 'data' in ctx.callbackQuery ? ctx.callbackQuery.data : undefined;
2815
+ if ((0, talkerAccess_1.checkIsTalkerCallback)(callbackData))
2816
+ return false;
2817
+ return (await getGroupSpeakerRole(ctx))?.role === 'talker';
2818
+ }
2819
+ /**
2820
+ * @description Learn from a message of the served group, whoever sent it and whatever the gates later decide: remember the
2821
+ * @username (so `/access add @name` can name a person the Bot API cannot look up), keep a talker's entries in step with a
2822
+ * rename, turn an invitation that waited for this person into a grant (announced in the topic that waited), and — for a
2823
+ * stranger — remember the topic they wrote in. An admin is never invited and never offered as a stranger; a bot is nobody's talker.
2824
+ */
2825
+ async function noteServedGroupSender(ctx) {
2826
+ const user = ctx.from;
2827
+ // 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
2828
+ // never remembered, never offered as a stranger to add, never an invitation's match.
2829
+ if (!ctx.message || !user || user.is_bot || ctx.message.sender_chat)
2830
+ return;
2831
+ // 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
2832
+ // waits for ÂĢthe first messageÂģ must not be spent on it (nor the person offered as a writer, nor announced while leaving).
2833
+ if (!(0, inbound_1.checkIsWrittenMessage)(ctx.message))
2834
+ return;
2835
+ const groupSpeaker = await getGroupSpeakerRole(ctx);
2836
+ if (groupSpeaker === null)
2837
+ return;
2838
+ const person = { userId: user.id.toString(), username: user.username, name: (0, inbound_1.getDisplayName)(user) };
2839
+ seenGroupSenders.noteSender(person);
2840
+ state.updateTalkerIdentity(person);
2841
+ if (groupSpeaker.role === 'admin')
2842
+ return;
2843
+ const grants = await state.resolveTopicInvites(person);
2844
+ for (const grant of grants) {
2845
+ const topicKey = (0, sessionKey_1.tryKeyFromString)(grant.threadKey);
2846
+ if (topicKey === null)
2847
+ continue;
2848
+ await replyToThread(topicKey, withThreadLocale(topicKey, () => (0, i18n_1.t)('access.inviteResolvedNotice', { person: (0, personLabel_1.formatPersonLabel)(person) })));
2849
+ }
2850
+ // 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
2851
+ // another topic does not.
2852
+ const isTalkerNow = state.getEffectiveTalkerIds(groupSpeaker.key, getGroupGeneralKey(groupSpeaker.key)).has(person.userId);
2853
+ if (groupSpeaker.role === 'none' && !isTalkerNow)
2854
+ recentTopicWriters.noteIgnoredWriter((0, sessionKey_1.keyToString)(groupSpeaker.key), person);
2679
2855
  }
2680
2856
  // ═══════════════════════════════════════════════════════════════════════════════
2681
2857
  // Send helpers — replyToThread + auto-track + error routing
@@ -5052,6 +5228,7 @@ function getPromptWithThreadContext(key, text) {
5052
5228
  key,
5053
5229
  subdir,
5054
5230
  timezone: getCurrentTimezone(),
5231
+ hasTalkers: (0, sessionKeyCodec_1.checkIsTelegramKey)(key) && getMessageAccess(key).talkerIds.size > 0,
5055
5232
  });
5056
5233
  const kStr = (0, sessionKey_1.keyToString)(key);
5057
5234
  if (!(0, threadContextPreamble_1.checkShouldInjectPreamble)(preamble, threadContextMarkers.get(kStr))) {
@@ -5072,7 +5249,19 @@ function getPromptWithThreadContext(key, text) {
5072
5249
  * is looked up among the files this thread took in.
5073
5250
  */
5074
5251
  function getMessageContext(key, message) {
5075
- return (0, inbound_1.getTelegramMessageContext)(message, { userId: bot.botInfo?.id }, (meta) => findThreadSavedFile(key, meta));
5252
+ return (0, inbound_1.getTelegramMessageContext)(message, { userId: bot.botInfo?.id }, getMessageAccess(key), (meta) => findThreadSavedFile(key, meta));
5253
+ }
5254
+ /**
5255
+ * @description Who is the operator and who may talk in the conversation `key`: the two sets the agent-facing marks tell the
5256
+ * operator's words from anyone else's by (a talker's message, a reply to a stranger's). Read synchronously off the admin cache
5257
+ * 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
5258
+ * none can forget to ask. The DM surface is the owner's private chat: the owner is the operator and nobody else writes there.
5259
+ * In a group the talkers are the topic's own list plus General's, which is group-wide.
5260
+ */
5261
+ function getMessageAccess(key) {
5262
+ if (checkIsDmKey(key))
5263
+ return { adminIds: new Set([getOwnerUserId().toString()]), talkerIds: new Set() };
5264
+ return { adminIds: adminCache.getCachedAdminIds(), talkerIds: state.getEffectiveTalkerIds(key, getGroupGeneralKey(key)) };
5076
5265
  }
5077
5266
  /**
5078
5267
  * @description The bot's saved copy of a file sent to this thread earlier
@@ -5161,8 +5350,8 @@ void telegramInbound.start(async (event) => {
5161
5350
  * command handlers stop reading the telegraf context and move into
5162
5351
  * `connectors/telegram/` — the follow-up decomposition, not a typing change.
5163
5352
  */
5164
- function command(name, handler) {
5165
- commandRouter.register(name, (event, parsed) => handler(event.raw, event.key, parsed));
5353
+ function command(name, handler, options) {
5354
+ commandRouter.register(name, (event, parsed) => handler(event.raw, event.key, parsed), options);
5166
5355
  }
5167
5356
  /**
5168
5357
  * The ports the Telegram command modules (`connectors/telegram/commands/`) take from this file. `state` is
@@ -5179,6 +5368,7 @@ const botCore = {
5179
5368
  deleteThreadMessage,
5180
5369
  deleteThreadMessageDetailed,
5181
5370
  authoriseContext,
5371
+ authoriseSpeaker: authoriseTopicSpeaker,
5182
5372
  withThreadLocale,
5183
5373
  checkIsGeneral,
5184
5374
  updatePinnedStatus,
@@ -5199,7 +5389,8 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
5199
5389
  resumeSleepingSessionForCompaction: async (key) => (await ensureAgentSession(key, { isResumeOnly: true })).ok && (0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key),
5200
5390
  getThreadAdapter: createAdapter_1.getThreadAdapter,
5201
5391
  // An answer to the agent's own question is never a request (S7), even delivered as a prompt.
5202
- deliverLabel: (key, label) => withThreadLocale(key, () => deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), label, null)),
5392
+ // 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.
5393
+ deliverLabel: (key, label, messageContext) => withThreadLocale(key, () => deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), label, null, undefined, messageContext)),
5203
5394
  resumeSleepingSessionForPrompt: (key) => resumeSleepingSessionForPrompt(key),
5204
5395
  checkIsStarting: (key) => startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key)),
5205
5396
  closeOrphanQuestionMessage,
@@ -5217,6 +5408,13 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
5217
5408
  function checkIsRoutedCommand(name) {
5218
5409
  return commandRouter.checkIsRegistered(name);
5219
5410
  }
5411
+ /**
5412
+ * The names a talker may run, sorted. Exported so a test pins the exact set against the REAL registration table: a new command
5413
+ * is admin-only unless somebody flags it on purpose, and the flag cannot be added unnoticed.
5414
+ */
5415
+ function getTalkerAllowedCommandNames() {
5416
+ return commandRouter.listTalkerAllowedNames();
5417
+ }
5220
5418
  /** `/esc` and its other names: the interrupt, which also cancels a pending sign-in or `/topic` prompt first. */
5221
5419
  const escapeCommandNames = ['esc', 'escape', 'interrupt'];
5222
5420
  /** @description Whether `messageText` is one of the {@link escapeCommandNames} (`@botmention` tolerated). */
@@ -5275,10 +5473,20 @@ async function handleRoutedCommandMessage(ctx, next, deps) {
5275
5473
  const parsed = deps.getCommand(ctx.message);
5276
5474
  if (!parsed || !deps.checkIsRegistered(parsed.name))
5277
5475
  return next();
5278
- const key = await deps.authorise(ctx);
5279
- if (!key)
5476
+ const speaker = await deps.authorise(ctx);
5477
+ if (!speaker)
5280
5478
  return;
5281
- await deps.exitPendingInputModes(key, ctx.message.text);
5479
+ const { key } = speaker;
5480
+ if (speaker.role === 'talker') {
5481
+ if (!deps.checkIsTalkerAllowed(parsed.name)) {
5482
+ await deps.refuseTalkerCommand(key);
5483
+ return;
5484
+ }
5485
+ // A talker's command never ends an input step an admin armed: it is not the admin's own next word.
5486
+ }
5487
+ else {
5488
+ await deps.exitPendingInputModes(key, ctx.message.text);
5489
+ }
5282
5490
  deps.noteActivity(key);
5283
5491
  await deps.deliverInbound(ctx, key);
5284
5492
  }
@@ -5305,7 +5513,11 @@ function deliverRoutedCommand(ctx, key) {
5305
5513
  exports.routedCommandTriggerDeps = {
5306
5514
  getCommand: (message) => (0, inbound_1.getTelegramCommand)(message, { username: bot.botInfo?.username }),
5307
5515
  checkIsRegistered: checkIsRoutedCommand,
5308
- authorise: authoriseContext,
5516
+ authorise: authoriseTopicSpeaker,
5517
+ checkIsTalkerAllowed: (name) => commandRouter.checkIsTalkerAllowed(name),
5518
+ refuseTalkerCommand: async (key) => {
5519
+ await replyToThread(key, (0, i18n_1.t)('access.adminOnlyCommandRefusal'));
5520
+ },
5309
5521
  exitPendingInputModes,
5310
5522
  noteActivity: noteThreadActivity,
5311
5523
  deliverInbound: deliverRoutedCommand,
@@ -5410,7 +5622,7 @@ command('status', async (_ctx, key) => {
5410
5622
  timezone,
5411
5623
  timezoneNow: (0, timezone_1.formatZoneNow)(timezone, nowMs),
5412
5624
  }));
5413
- });
5625
+ }, { isTalkerAllowed: true });
5414
5626
  /** The `/language` argument: the first token, lower-cased (locale codes are case-insensitive). */
5415
5627
  function getLanguageCommandArg(parsed) {
5416
5628
  return (parsed.args[0] ?? '').toLowerCase();
@@ -6062,24 +6274,28 @@ command('version', async (_ctx, key) => {
6062
6274
  command('whoami', async (ctx, key) => {
6063
6275
  const userId = ctx.from?.id ?? 0;
6064
6276
  // Per-chat authority is the single source of truth now (owner for a DM chat,
6065
- // the served group's admins for the group chat); `checkIsAllowedUser` already
6066
- // encodes the surface gate, so no extra group-id clause is needed.
6067
- const allowed = await checkIsAllowedUser(ctx);
6277
+ // the served group's admins for the group chat); the speaker gate already
6278
+ // encodes the surface gate, so no extra group-id clause is needed. A talker is
6279
+ // told what they are here: allowed to talk in THIS topic, nothing more.
6280
+ const speaker = await authoriseTopicSpeaker(ctx);
6281
+ const allowed = speaker?.role === 'talker' ? (0, i18n_1.t)('access.whoamiTalkerRole') : speaker ? 'yes' : 'no';
6068
6282
  const binding = state.getBinding(key);
6069
6283
  await replyToThread(key, (0, i18n_1.t)('whoami.report', {
6070
6284
  userId,
6071
6285
  chatId: (0, sessionKeyCodec_1.getTelegramChatId)(key),
6072
6286
  threadId: (0, sessionKeyCodec_1.getTelegramThreadId)(key),
6073
- allowed: allowed ? 'yes' : 'no',
6287
+ allowed,
6074
6288
  binding: binding ? `\`${binding.subdir}\`` : (0, i18n_1.t)('whoami.binding_unbound'),
6075
6289
  }), { parse_mode: 'Markdown' });
6076
- });
6290
+ }, { isTalkerAllowed: true });
6077
6291
  /**
6078
6292
  * @description Re-point the bot to the forum supergroup this command was
6079
6293
  * sent in. Registered raw (not via the group-gated `command()` wrapper) so
6080
6294
  * it can switch the bot from one group to another. Refused when the id is
6081
- * locked by `ALLOWED_GROUP_ID` env. Only a creator/administrator of the target
6082
- * group may pair, so a random group can't hijack the binding.
6295
+ * locked by `ALLOWED_GROUP_ID` env. Who may pair is `getPairingRefusal`'s rule:
6296
+ * with an owner set, only the owner; without one, once a group is served,
6297
+ * only that group's creator — never merely an administrator of the new group,
6298
+ * which whoever made it is.
6083
6299
  */
6084
6300
  bot.command('pair', async (ctx, next) => {
6085
6301
  // A forwarded `/pair` is somebody else's words: it re-points the bot to no group, and it is not swallowed either —
@@ -6111,18 +6327,26 @@ bot.command('pair', async (ctx, next) => {
6111
6327
  await replyToThread(replyKey, (0, i18n_1.t)('pair.only_forum')).catch(() => { });
6112
6328
  return;
6113
6329
  }
6114
- if (!(await checkIsForumAdmin(routeChat.id, userId))) {
6115
- await replyToThread(replyKey, (0, i18n_1.t)('pair.not_admin')).catch(() => { });
6330
+ const refusal = await getPairingRefusalFor(userId, routeChat.id);
6331
+ if (refusal !== null) {
6332
+ console.warn(`[pair] refused /pair from chat ${routeChat.id} user ${userId} (${refusal})`);
6333
+ await replyToThread(replyKey, (0, i18n_1.t)(pairingRefusalTextKeys[refusal])).catch(() => { });
6116
6334
  return;
6117
6335
  }
6118
6336
  effectiveGroupId = routeChat.id;
6119
6337
  await state.setPairedGroupId(routeChat.id);
6338
+ await state.dropTopicTalkersOfOtherChats(routeChat.id);
6120
6339
  adminCache.invalidate();
6121
6340
  console.log(`[pair] re-paired to forum supergroup ${routeChat.id} via /pair`);
6122
6341
  const key = getThreadKey(ctx) ?? (0, sessionKeyCodec_1.makeTelegramKey)(routeChat.id, threadRouting_1.GENERAL_THREAD_ID);
6123
6342
  await replyToThread(key, (0, i18n_1.t)('pair.success', { groupId: routeChat.id }));
6124
6343
  });
6125
- command('help', async (_ctx, key) => {
6344
+ command('help', async (ctx, key) => {
6345
+ // A talker is shown what they may do — talk to the agent and four commands — never the admin command list.
6346
+ if ((await authoriseTopicSpeaker(ctx))?.role === 'talker') {
6347
+ await replyToThread(key, (0, i18n_1.t)('access.helpTalker'));
6348
+ return;
6349
+ }
6126
6350
  if (checkIsGeneral(key)) {
6127
6351
  await replyToThread(key, (0, i18n_1.t)('help.general'), { parse_mode: 'Markdown' });
6128
6352
  return;
@@ -6138,7 +6362,7 @@ command('help', async (_ctx, key) => {
6138
6362
  return;
6139
6363
  }
6140
6364
  await replyToThread(key, (0, i18n_1.t)('help.thread_bound', { subdir: binding.subdir }), { parse_mode: 'Markdown' });
6141
- });
6365
+ }, { isTalkerAllowed: true });
6142
6366
  function formatBytes(n) {
6143
6367
  if (n < 1024)
6144
6368
  return `${n} B`;
@@ -6146,6 +6370,8 @@ function formatBytes(n) {
6146
6370
  return `${(n / 1024).toFixed(1)} KB`;
6147
6371
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
6148
6372
  }
6373
+ /** How long one git read of the bind's welcome may take: a slow repository only loses its row. */
6374
+ const bindingGitTimeoutMs = 1500;
6149
6375
  /**
6150
6376
  * @description Collect a short factual summary of a bound project folder for
6151
6377
  * the welcome message — what onboarding context Claude would actually pick
@@ -6184,22 +6410,11 @@ async function getBindingStats(workDir) {
6184
6410
  catch {
6185
6411
  return out;
6186
6412
  }
6187
- try {
6188
- const { stdout } = await execFileAsync('git', ['symbolic-ref', '--short', 'HEAD'], {
6189
- cwd: workDir, timeout: 1500,
6190
- });
6191
- out.gitBranch = stdout.trim() || 'HEAD';
6192
- }
6193
- catch {
6194
- out.gitBranch = 'HEAD';
6195
- }
6196
- try {
6197
- const { stdout } = await execFileAsync('git', ['status', '--porcelain'], {
6198
- cwd: workDir, timeout: 1500,
6199
- });
6200
- out.gitClean = stdout.trim().length === 0;
6201
- }
6202
- catch { /* keep null = unknown */ }
6413
+ // The folder's git configuration is the agent's to write: `runGitInAgentFolder` runs git without the bot's secrets.
6414
+ out.gitBranch = (await (0, folderGit_1.runGitInAgentFolder)(workDir, ['symbolic-ref', '--short', 'HEAD'], bindingGitTimeoutMs)) || 'HEAD';
6415
+ const status = await (0, folderGit_1.runGitInAgentFolder)(workDir, ['status', '--porcelain'], bindingGitTimeoutMs);
6416
+ if (status !== null)
6417
+ out.gitClean = status.length === 0;
6203
6418
  return out;
6204
6419
  }
6205
6420
  /**
@@ -6265,6 +6480,11 @@ async function sendBindingWelcome(key, subdir, notes = {}) {
6265
6480
  const moreLabel = sharedMore > 0 ? (0, i18n_1.t)('binding.welcome.sharedMore', { count: sharedMore }) : null;
6266
6481
  lines.push((0, i18n_1.t)('binding.welcome.shared', { threads: (0, bindingWelcome_1.formatSharedTopicList)(notes.sharedWith ?? [], moreLabel) }));
6267
6482
  }
6483
+ // 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
6484
+ // 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.
6485
+ const reachCount = state.getTopicReachCount(key, getGroupGeneralKey(key));
6486
+ if (reachCount > 0)
6487
+ lines.push((0, i18n_1.t)('access.bindNote', { count: reachCount, subdir }));
6268
6488
  lines.push('');
6269
6489
  lines.push((0, i18n_1.t)('binding.welcome.start_prompt'));
6270
6490
  const welcomeMessageId = await replyToThread(key, lines.join('\n'), {
@@ -6687,6 +6907,19 @@ const { registerBotSkillsCommands, registerBotSkillsCallbacks } = (0, botSkills_
6687
6907
  checkIsOpenCodeTopic: (key) => ((0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name) === adapterNames_1.openCodeAdapterName,
6688
6908
  });
6689
6909
  registerBotSkillsCommands();
6910
+ // ── Who may talk to the agent in a topic (`/access`): `connectors/telegram/commands/topicAccess.ts`, `topicTalkers.ts` ──
6911
+ const { registerTopicAccessCommands, registerTopicAccessCallbacks } = (0, topicAccess_1.createTopicAccess)({
6912
+ ...botCore,
6913
+ getAdminIds: () => adminCache.getAdminIds(),
6914
+ getAdminUsernames: () => adminCache.getAdminHandles(),
6915
+ getBotUserId: () => bot.botInfo?.id,
6916
+ getBotUsername: () => bot.botInfo?.username,
6917
+ getGroupGeneralKey,
6918
+ checkIsDmKey,
6919
+ recentWriters: recentTopicWriters,
6920
+ seenSenders: seenGroupSenders,
6921
+ });
6922
+ registerTopicAccessCommands();
6690
6923
  // ── The cap on tracker task agents (`/task_agents`): `connectors/telegram/commands/taskAgents.ts`, `trackers/` ──
6691
6924
  const { registerTaskAgentsCommands, registerTaskAgentsCallbacks } = (0, taskAgents_1.createTaskAgents)({
6692
6925
  ...botCore,
@@ -6745,10 +6978,7 @@ function resolveThreadClaudeConfigDir(key) {
6745
6978
  * the probe fails.
6746
6979
  */
6747
6980
  async function readClaudeAuthStatusUnder(configDir) {
6748
- const env = { ...process.env };
6749
- delete env.ANTHROPIC_API_KEY;
6750
- if (configDir !== null)
6751
- env[claudeProfiles_1.claudeConfigDirVariableName] = configDir;
6981
+ const env = (0, claudeProfiles_1.getClaudeAuthCommandEnvironment)(configDir);
6752
6982
  try {
6753
6983
  const args = [...(0, claudeApiKeyHelper_1.buildClaudeAuthProbeSettingsArgs)(configDir), 'auth', 'status', '--json'];
6754
6984
  const { stdout } = await execFileAsync((0, resolveBinary_1.resolveClaudeBinary)(), args, { timeout: claudeAuthStatusProbeTimeoutMs, env });
@@ -7485,7 +7715,7 @@ async function checkIsPickBeyondLimit(from, to) {
7485
7715
  if (from?.backend !== 'claude' || to.backend !== 'claude' || to.model === null || from.profile !== to.profile)
7486
7716
  return false;
7487
7717
  await (0, usageRefreshBudget_1.refreshUsageWithinBudget)((options) => claudeUsageRefresher.refreshAll(options));
7488
- return (0, claudeUsage_1.checkIsClaudeModelClearOfLimit)(state.getClaudeProfileInfo(to.profile)?.usage, from.model, to.model);
7718
+ return (0, claudeUsage_1.checkIsClaudeModelClearOfLimit)(state.getClaudeProfileInfo(to.profile)?.usage, from.model, to.model, Date.now());
7489
7719
  }
7490
7720
  /** The rung as a manual switch's target: a picked Claude account (+ model alias), or an OpenCode model, both named in the question. */
7491
7721
  function buildBackendSwitchTargetOfRung(to) {
@@ -8000,20 +8230,24 @@ command('tab', async (_ctx, key) => {
8000
8230
  else
8001
8231
  await replyToThread(key, `Not supported for ${adapter.label}`);
8002
8232
  });
8003
- command(escapeCommandNames, async (_ctx, key) => {
8004
- // A pending ÂĢAdd accountÂģ name prompt, a pending sign-in (`/login`, `/connect` OAuth) and a `/topic` wizard take
8005
- // priority: the first /esc only cancels it, so the topic stops waiting for typed input.
8006
- if (cancelProfileNameCapture(key)) {
8007
- await replyToThread(key, (0, i18n_1.t)('account.askNameCancelled'));
8008
- return;
8009
- }
8010
- if (cancelPendingLogin(key)) {
8011
- await replyToThread(key, (0, i18n_1.t)('login.cancelled'));
8012
- return;
8233
+ command(escapeCommandNames, async (ctx, key) => {
8234
+ // 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
8235
+ // topic), and ending one is the admin's own word.
8236
+ if ((await authoriseTopicSpeaker(ctx))?.role !== 'talker') {
8237
+ // A pending ÂĢAdd accountÂģ name prompt, a pending sign-in (`/login`, `/connect` OAuth) and a `/topic` wizard take
8238
+ // priority: the first /esc only cancels it, so the topic stops waiting for typed input.
8239
+ if (cancelProfileNameCapture(key)) {
8240
+ await replyToThread(key, (0, i18n_1.t)('account.askNameCancelled'));
8241
+ return;
8242
+ }
8243
+ if (cancelPendingLogin(key)) {
8244
+ await replyToThread(key, (0, i18n_1.t)('login.cancelled'));
8245
+ return;
8246
+ }
8247
+ // A `/topic` wizard is ended at whatever step it waits (it says so itself).
8248
+ if (await cancelTopicWizard(key))
8249
+ return;
8013
8250
  }
8014
- // A `/topic` wizard is ended at whatever step it waits (it says so itself).
8015
- if (await cancelTopicWizard(key))
8016
- return;
8017
8251
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8018
8252
  if (adapter.sendEscape) {
8019
8253
  // The operator interrupted the turn: its open request closes silently.
@@ -8030,7 +8264,7 @@ command(escapeCommandNames, async (_ctx, key) => {
8030
8264
  else {
8031
8265
  await replyToThread(key, `Not supported for ${adapter.label}`);
8032
8266
  }
8033
- });
8267
+ }, { isTalkerAllowed: true });
8034
8268
  command('output', async (_ctx, key) => {
8035
8269
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8036
8270
  if (!adapter.getFullOutput) {
@@ -8301,7 +8535,7 @@ const botCommands = new Set([
8301
8535
  'disconnect', 'stop', 'stopall', 'stop-all', 'quit-all', 'status', 'c', 'y', 'n', 'enter', 'up', 'down', 'tab', 'esc', 'escape', 'interrupt', 'output', 'clear_messages',
8302
8536
  'bind', 'topic', 'unbind', 'where', 'ls', 'list', 'new', 'whoami', 'version', 'help', 'language', 'lang',
8303
8537
  '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',
8304
- 'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update',
8538
+ 'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update', 'access',
8305
8539
  ]);
8306
8540
  /**
8307
8541
  * @description The bare `/clear` is no longer bot-owned (it was renamed to
@@ -8313,10 +8547,79 @@ const forwardedClearCommand = '/clear';
8313
8547
  // ═══════════════════════════════════════════════════════════════════════════════
8314
8548
  // Text message handler — main conversational entrypoint
8315
8549
  // ═══════════════════════════════════════════════════════════════════════════════
8550
+ /**
8551
+ * @description A talker's text — the one early branch, so no armed step, command, start phrase or guide of the admin path
8552
+ * can be reached by checks spread through the handler. What it does: it is refused if it is a slash text (agent slash
8553
+ * commands control the conversation, and the commands the bot owns were decided before the message got here); a pasted
8554
+ * OAuth callback URL is deleted as a secret, whoever sent it; a raw-shell topic is refused; otherwise it is a prompt like any
8555
+ * other — buffered behind a session start, delivered to a live agent, or waking a sleeping conversation — and with no agent
8556
+ * at all the talker is told so (never offered the folder picker, never starting one). It never feeds an input step an admin
8557
+ * 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
8558
+ * is open the message is refused, since a prompt would end that sign-in. A message refused anywhere above changes nothing.
8559
+ */
8560
+ async function handleTalkerText(ctx, key) {
8561
+ const text = (0, utils_1.stripCommandBotMention)(ctx.message.text.trim());
8562
+ // A FORWARDED message is content: its `/â€Ļ` is words like any other. A slash the talker typed is refused.
8563
+ if (!(0, inbound_1.checkIsTelegramForward)(ctx.message) && text.startsWith('/')) {
8564
+ await replyToThread(key, (0, i18n_1.t)('access.adminOnlyCommandRefusal'));
8565
+ return;
8566
+ }
8567
+ await state.pushMessageId(key, ctx.message.message_id);
8568
+ // The safety net for a pasted OAuth callback URL holds for everybody: it is a secret, never a prompt.
8569
+ if ((0, openCodeAuthLogin_1.parseOAuthCallbackFromReply)(text)) {
8570
+ await deleteThreadMessage(key, ctx.message.message_id);
8571
+ await replyToThread(key, (0, i18n_1.t)('connect.oauth_callback_no_flow'));
8572
+ return;
8573
+ }
8574
+ if (await refuseTalkerInTerminalTopic(key))
8575
+ return;
8576
+ const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8577
+ // 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
8578
+ // (the admin's own text is typed into the box instead — that route is not a talker's).
8579
+ if (adapter.isLoginPastePending?.(key)) {
8580
+ await replyToThread(key, (0, i18n_1.t)('access.loginPendingForTalkerNotice'));
8581
+ return;
8582
+ }
8583
+ // The talker took over before a pending API-error retry fired, as any sender does — only now: a message that was refused above
8584
+ // changed nothing, so a usage-limit wait armed for the topic is still armed (it would otherwise end without its resume).
8585
+ cancelApiRetry(key);
8586
+ const messageContext = getMessageContext(key, ctx.message);
8587
+ const intake = { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) };
8588
+ const sentAtMs = ctx.message.date * 1000;
8589
+ if (startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key))) {
8590
+ await bufferPromptDuringStartup(key, text, intake, messageContext);
8591
+ return;
8592
+ }
8593
+ if (adapter.checkIsActive(key)) {
8594
+ await deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext);
8595
+ return;
8596
+ }
8597
+ // A sleeping conversation is resumed by the message itself, as for anybody (L-D4).
8598
+ if (await resumeSleepingSessionForPrompt(key)) {
8599
+ await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, intake, sentAtMs, messageContext);
8600
+ return;
8601
+ }
8602
+ await replyToThread(key, (0, i18n_1.t)('access.noAgentForTalkerNotice'));
8603
+ }
8604
+ /**
8605
+ * @description A raw-shell topic takes no talker: what is typed into a shell reaches it with no label, so none of the marks
8606
+ * and guards that tell the agent whose words these are can apply. Posts the refusal and answers `true` for such a topic.
8607
+ */
8608
+ async function refuseTalkerInTerminalTopic(key, sendRefusal = (text) => replyToThread(key, text)) {
8609
+ if ((0, createAdapter_1.getThreadAdapter)(key).name !== 'terminal')
8610
+ return false;
8611
+ await sendRefusal((0, i18n_1.t)('access.terminalTopicRefusal'));
8612
+ return true;
8613
+ }
8316
8614
  bot.on((0, filters_1.message)('text'), async (ctx) => {
8317
- const key = await authoriseContext(ctx);
8318
- if (!key)
8615
+ const speaker = await authoriseTopicSpeaker(ctx);
8616
+ if (!speaker)
8617
+ return;
8618
+ const { key } = speaker;
8619
+ if (speaker.role === 'talker') {
8620
+ await handleTalkerText(ctx, key);
8319
8621
  return;
8622
+ }
8320
8623
  // User took over before a pending API-error retry fired → cancel it silently
8321
8624
  // (no give-up notice). Fires for EVERY authorised inbound text — a plain
8322
8625
  // prompt AND an owned slash-command — before the bot-command early-return.
@@ -8663,8 +8966,12 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
8663
8966
  // Voice message handler
8664
8967
  // ═══════════════════════════════════════════════════════════════════════════════
8665
8968
  bot.on((0, filters_1.message)('voice'), async (ctx) => {
8666
- const key = await authoriseContext(ctx);
8667
- if (!key)
8969
+ const speaker = await authoriseTopicSpeaker(ctx);
8970
+ if (!speaker)
8971
+ return;
8972
+ const { key } = speaker;
8973
+ // A talker's voice note goes to the agent like their text does — marked as theirs — but never into a raw shell.
8974
+ if (speaker.role === 'talker' && await refuseTalkerInTerminalTopic(key))
8668
8975
  return;
8669
8976
  // User took over (voice note) before a pending API-error retry fired → cancel
8670
8977
  // it silently, like the text handler.
@@ -8771,7 +9078,8 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
8771
9078
  // transcript is routed here — right after the 🎤 echo and BEFORE the
8772
9079
  // startup-buffer / natural-language-start / binding gates, which would
8773
9080
  // otherwise treat it as a prompt. Same single creation path as the text side.
8774
- const reminderVoiceRoute = claimReminderTextCapture(key);
9081
+ // 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.
9082
+ const reminderVoiceRoute = (0, messageContext_1.checkIsForeignWords)(messageContext) ? null : claimReminderTextCapture(key);
8775
9083
  if (reminderVoiceRoute === 'capture') {
8776
9084
  await finishReminderWizard(key, transcript);
8777
9085
  return;
@@ -8783,8 +9091,8 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
8783
9091
  await bufferPromptDuringStartup(key, transcript, { source: 'voice', requesterId }, messageContext);
8784
9092
  return;
8785
9093
  }
8786
- // A FORWARDED voice note saying ÂĢClaudeÂģ is somebody else's words, not the operator's order to start an agent.
8787
- if (messageContext?.isForwarded !== true && !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)) {
9094
+ // 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.
9095
+ if (!(0, messageContext_1.checkIsForeignWords)(messageContext) && !(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key)) {
8788
9096
  const startMatch = (0, agentTrigger_1.parseAgentTrigger)(transcript);
8789
9097
  if (startMatch.isMatch && startMatch.adapterName) {
8790
9098
  if (checkIsGeneral(key)) {
@@ -8815,18 +9123,7 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
8815
9123
  }
8816
9124
  // A voice prompt wakes a sleeping conversation like a text one does (L-D4).
8817
9125
  if (!(0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) && !(await resumeSleepingSessionForPrompt(key))) {
8818
- if (checkIsGeneral(key)) {
8819
- await replyToThread(key, (0, i18n_1.t)('thread.general_no_agent'));
8820
- return;
8821
- }
8822
- const binding = state.getBinding(key);
8823
- if (!binding) {
8824
- const subdirs = listAvailableSubdirs(ENV.workRoot);
8825
- const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
8826
- await replyToThread(key, (0, i18n_1.t)('thread.no_binding'), extra);
8827
- return;
8828
- }
8829
- await replyToThread(key, (0, i18n_1.t)('thread.no_agent_with_binding', { subdir: binding.subdir }));
9126
+ await sendNoAgentGuidance(key, messageContext?.nonOperatorSender !== undefined, (text, extra) => replyToThread(key, text, extra));
8830
9127
  return;
8831
9128
  }
8832
9129
  // Same choke point as text: a voice transcript while a question is pending
@@ -8868,6 +9165,29 @@ function checkIsFileTooBigApiError(err) {
8868
9165
  * an agent is active (or mid-startup) — an idle/unbound thread gets the hint
8869
9166
  * and nothing hits disk, per the locked decision.
8870
9167
  */
9168
+ /**
9169
+ * @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
9170
+ * offered the folder picker, a bound one the hint to start an agent. A TALKER gets one line — an admin starts the agent —
9171
+ * and never the picker: they bind and start nothing. `sendHint` is how the line is sent (an album sends it once).
9172
+ */
9173
+ async function sendNoAgentGuidance(key, isFromTalker, sendHint) {
9174
+ if (isFromTalker) {
9175
+ await sendHint((0, i18n_1.t)('access.noAgentForTalkerNotice'));
9176
+ return;
9177
+ }
9178
+ if (checkIsGeneral(key)) {
9179
+ await sendHint((0, i18n_1.t)('thread.general_no_agent'));
9180
+ return;
9181
+ }
9182
+ const binding = state.getBinding(key);
9183
+ if (!binding) {
9184
+ const subdirs = listAvailableSubdirs(ENV.workRoot);
9185
+ const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
9186
+ await sendHint((0, i18n_1.t)('thread.no_binding'), extra);
9187
+ return;
9188
+ }
9189
+ await sendHint((0, i18n_1.t)('thread.no_agent_with_binding', { subdir: binding.subdir }));
9190
+ }
8871
9191
  /**
8872
9192
  * @description Evaluate the file-intake gate for a thread: an idle thread (no
8873
9193
  * active agent and not mid-startup) gets the same friendly guidance as the text
@@ -8877,25 +9197,14 @@ function checkIsFileTooBigApiError(err) {
8877
9197
  * album path can dedupe it to once-per-album; the single-file path passes
8878
9198
  * `replyToThread` verbatim.
8879
9199
  */
8880
- async function checkFileIntakeGatePassed(key, isStarting, sendHint) {
9200
+ async function checkFileIntakeGatePassed(key, isStarting, sendHint, isFromTalker) {
8881
9201
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
8882
9202
  if (isStarting || adapter.checkIsActive(key))
8883
9203
  return true;
8884
9204
  // A file sent to a sleeping conversation wakes it (L-D4) and is taken in by the resumed session.
8885
9205
  if (await resumeSleepingSessionForPrompt(key, sendHint))
8886
9206
  return true;
8887
- if (checkIsGeneral(key)) {
8888
- await sendHint((0, i18n_1.t)('thread.general_no_agent'));
8889
- return false;
8890
- }
8891
- const binding = state.getBinding(key);
8892
- if (!binding) {
8893
- const subdirs = listAvailableSubdirs(ENV.workRoot);
8894
- const extra = (0, bindPicker_1.buildBindKeyboard)(subdirs, 0, bindPicker_1.BIND_PAGE_SIZE, !!state.getBinding(key));
8895
- await sendHint((0, i18n_1.t)('thread.no_binding'), extra);
8896
- return false;
8897
- }
8898
- await sendHint((0, i18n_1.t)('thread.no_agent_with_binding', { subdir: binding.subdir }));
9207
+ await sendNoAgentGuidance(key, isFromTalker, sendHint);
8899
9208
  return false;
8900
9209
  }
8901
9210
  /**
@@ -9026,7 +9335,7 @@ function parseAlbumGroupKey(groupKey) {
9026
9335
  * {@link albumCollector}). A successful download is buffered into the collector;
9027
9336
  * a failed one still lets the album flush announce the rest.
9028
9337
  */
9029
- async function handleAlbumFile(ctx, key, meta, mediaGroupId) {
9338
+ async function handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker) {
9030
9339
  const groupKey = buildAlbumGroupKey(key, mediaGroupId);
9031
9340
  const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
9032
9341
  // Gate per item, but reply at most once per album. The guard is claimed
@@ -9035,7 +9344,7 @@ async function handleAlbumFile(ctx, key, meta, mediaGroupId) {
9035
9344
  if (albumCollector.checkShouldAnnounceOnce(groupKey)) {
9036
9345
  await replyToThread(key, text, extra);
9037
9346
  }
9038
- });
9347
+ }, isFromTalker);
9039
9348
  if (!gatePassed)
9040
9349
  return;
9041
9350
  const savedPath = await downloadIncomingFile(ctx, key, meta, async (text) => {
@@ -9053,7 +9362,7 @@ async function handleAlbumFile(ctx, key, meta, mediaGroupId) {
9053
9362
  requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from),
9054
9363
  });
9055
9364
  }
9056
- async function handleIncomingFile(ctx, key) {
9365
+ async function handleIncomingFile(ctx, key, isFromTalker) {
9057
9366
  const meta = (0, fileIntake_1.getTelegramFileMeta)(ctx.message);
9058
9367
  if (!meta)
9059
9368
  return; // Not one of the six kinds (e.g. sticker) — ignore.
@@ -9063,11 +9372,11 @@ async function handleIncomingFile(ctx, key) {
9063
9372
  // combined prompt instead of N prompts that abort each other.
9064
9373
  const mediaGroupId = (0, fileIntake_1.getMediaGroupId)(ctx.message);
9065
9374
  if (mediaGroupId) {
9066
- await handleAlbumFile(ctx, key, meta, mediaGroupId);
9375
+ await handleAlbumFile(ctx, key, meta, mediaGroupId, isFromTalker);
9067
9376
  return;
9068
9377
  }
9069
9378
  const isStarting = startupPromptBuffer.checkIsStarting((0, sessionKey_1.keyToString)(key));
9070
- const gatePassed = await checkFileIntakeGatePassed(key, isStarting, (text, extra) => replyToThread(key, text, extra));
9379
+ const gatePassed = await checkFileIntakeGatePassed(key, isStarting, (text, extra) => replyToThread(key, text, extra), isFromTalker);
9071
9380
  if (!gatePassed)
9072
9381
  return;
9073
9382
  const savedPath = await downloadIncomingFile(ctx, key, meta, (text) => replyToThread(key, text));
@@ -9091,11 +9400,21 @@ bot.on(
9091
9400
  // be an AND over the fields and never match a real media message (see
9092
9401
  // incomingFileMessageFilter).
9093
9402
  fileIntake_1.incomingFileMessageFilter, async (ctx) => {
9094
- const key = await authoriseContext(ctx);
9095
- if (!key)
9403
+ const speaker = await authoriseTopicSpeaker(ctx);
9404
+ if (!speaker)
9405
+ return;
9406
+ const { key } = speaker;
9407
+ const isFromTalker = speaker.role === 'talker';
9408
+ // 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,
9409
+ // not once per item.
9410
+ const mediaGroupId = (0, fileIntake_1.getMediaGroupId)(ctx.message);
9411
+ if (isFromTalker && await refuseTalkerInTerminalTopic(key, async (text) => {
9412
+ if (!mediaGroupId || albumCollector.checkShouldAnnounceOnce(buildAlbumGroupKey(key, mediaGroupId)))
9413
+ await replyToThread(key, text);
9414
+ }))
9096
9415
  return;
9097
9416
  try {
9098
- await handleIncomingFile(ctx, key);
9417
+ await handleIncomingFile(ctx, key, isFromTalker);
9099
9418
  }
9100
9419
  catch (err) {
9101
9420
  console.error('[Bot] File handling error:', err);
@@ -9106,9 +9425,10 @@ fileIntake_1.incomingFileMessageFilter, async (ctx) => {
9106
9425
  // Edited message — explicit UX hint instead of silent ignore
9107
9426
  // ═══════════════════════════════════════════════════════════════════════════════
9108
9427
  bot.on('edited_message', async (ctx) => {
9109
- const key = await authoriseContext(ctx);
9110
- if (!key)
9428
+ const speaker = await authoriseTopicSpeaker(ctx);
9429
+ if (!speaker)
9111
9430
  return;
9431
+ const { key } = speaker;
9112
9432
  // Reply once per edit so the user isn't left wondering. The bot does NOT
9113
9433
  // treat the edit as a re-prompt to the agent (plan §16.3, E6).
9114
9434
  await replyToThread(key, (0, i18n_1.t)('edited.hint'));
@@ -9158,10 +9478,16 @@ bot.on('my_chat_member', async (ctx) => {
9158
9478
  * (`checkShouldInvalidateAdminCache`). Requires `chat_member` in
9159
9479
  * `allowed_updates` (NOT in Telegram's default set — see `botAllowedUpdates`).
9160
9480
  */
9161
- bot.on('chat_member', (ctx) => {
9481
+ bot.on('chat_member', async (ctx) => {
9162
9482
  if (ctx.chat?.id !== getAllowedGroupId())
9163
9483
  return;
9164
9484
  const { old_chat_member, new_chat_member } = ctx.update.chat_member;
9485
+ // A person who left, was removed or banned loses every talker entry and waiting invitation: coming back needs a new grant.
9486
+ if ((0, inbound_1.checkHasLeftGroup)(new_chat_member)) {
9487
+ const { user } = new_chat_member;
9488
+ await state.removeUserFromAllTopics({ userId: user.id.toString(), username: user.username, name: (0, inbound_1.getDisplayName)(user) })
9489
+ .catch((e) => console.warn('[access] dropping the talker entries of a member who left failed:', e instanceof Error ? e.message : e));
9490
+ }
9165
9491
  if (!(0, inbound_1.checkShouldInvalidateAdminCache)(old_chat_member.status, new_chat_member.status))
9166
9492
  return;
9167
9493
  adminCache.invalidate();
@@ -9582,6 +9908,7 @@ registerModelCallbacks();
9582
9908
  registerCompactionCallbacks();
9583
9909
  registerAutoContinueLimitsCallbacks();
9584
9910
  registerBotSkillsCallbacks();
9911
+ registerTopicAccessCallbacks();
9585
9912
  registerTaskAgentsCallbacks();
9586
9913
  registerRunnersCallbacks();
9587
9914
  registerBackendSwitchCallbacks();
@@ -9701,6 +10028,9 @@ bot.action(/^resume_(\d+)$/, async (ctx) => {
9701
10028
  if (result !== null)
9702
10029
  await replyToThread(key, result);
9703
10030
  });
10031
+ // The agent's own question buttons (`qa_`, and `reask_` in the compaction module) are the taps a talker may make: they answer the
10032
+ // agent, so they ask the speaker gate; every other button — `opt_`, which types a digit into whatever a Claude TUI shows, included —
10033
+ // keeps asking the admin gate.
9704
10034
  bot.action(/^opt_(\d+)$/, async (ctx) => {
9705
10035
  const key = await authoriseContext(ctx);
9706
10036
  if (!key) {
@@ -9719,11 +10049,12 @@ bot.action(/^opt_(\d+)$/, async (ctx) => {
9719
10049
  }
9720
10050
  });
9721
10051
  bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
9722
- const key = await authoriseContext(ctx);
9723
- if (!key) {
10052
+ const speaker = await authoriseTopicSpeaker(ctx);
10053
+ if (!speaker) {
9724
10054
  await ctx.answerCbQuery((0, i18n_1.t)('cb.access_denied'));
9725
10055
  return;
9726
10056
  }
10057
+ const { key } = speaker;
9727
10058
  const qIdx = parseInt(ctx.match[1], 10);
9728
10059
  const optIdx = parseInt(ctx.match[2], 10);
9729
10060
  const kStr = (0, sessionKey_1.keyToString)(key);
@@ -9745,7 +10076,9 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
9745
10076
  return;
9746
10077
  }
9747
10078
  const selectedLabel = question.options[optIdx].label;
9748
- const isAnswerShown = await applyQuestionAnswer(key, [selectedLabel]);
10079
+ // The agent's question is its way to ask the OPERATOR: an answer a topic member chose says so, in the answer itself.
10080
+ const answeredBy = speaker.role === 'talker' && ctx.from ? (0, inbound_1.getTelegramTalkerContext)(ctx.from).nonOperatorSender : undefined;
10081
+ const isAnswerShown = await applyQuestionAnswer(key, [selectedLabel], answeredBy);
9749
10082
  if (isAnswerShown) {
9750
10083
  // The question message was just edited to carry the whole answer under the question: the toast only
9751
10084
  // confirms the tap, so a label too long for it is cut there and not posted a second time.
@@ -9767,8 +10100,10 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
9767
10100
  */
9768
10101
  async function bufferPromptDuringStartup(key, text, intake, messageContext) {
9769
10102
  // The same for a bare option number typed in that window: it answers the question asked again. A FORWARDED "1" is somebody
9770
- // else's words, not the operator's pick: it is delivered, marked, like any other message.
9771
- if (messageContext?.isForwarded !== true && await answerReAskedQuestionByNumber(key, text))
10103
+ // else's words, not the operator's pick: it is delivered, marked, like any other message. A topic member's number DOES
10104
+ // answer — the one thing foreign words may do here: members answer the agent's questions, and only that (every other
10105
+ // control guard asks `checkIsForeignWords`).
10106
+ if (messageContext?.isForwarded !== true && await answerReAskedQuestionByNumber(key, text, messageContext))
9772
10107
  return;
9773
10108
  // A person wrote, in a window where the session is starting or being stopped: it counts like a message that reaches
9774
10109
  // `deliverActivePrompt` — the idle latch clears, and a question the idle compaction re-asked is closed (the idle fire
@@ -9798,9 +10133,12 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
9798
10133
  */
9799
10134
  async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext) {
9800
10135
  // A FORWARDED message is content, never control input: it answers no question and purges no context, whatever its words are.
10136
+ // A topic member's words are not the operator's either — but a bare option number of theirs DOES answer the agent's question
10137
+ // (members may answer questions, the one thing foreign words may do here), so the two answer routes below ask `isForwarded`
10138
+ // alone, while the context wipe asks `checkIsForeignWords`.
9801
10139
  const isForwarded = messageContext?.isForwarded === true;
9802
10140
  // A bare option number answers the question the idle compaction asked again (a tap's own label comes in with no intake).
9803
- if (intake !== null && !isForwarded && await answerReAskedQuestionByNumber(key, text))
10141
+ if (intake !== null && !isForwarded && await answerReAskedQuestionByNumber(key, text, messageContext))
9804
10142
  return null;
9805
10143
  // A genuine USER message (text or voice) — clear the compact-on-idle latch so
9806
10144
  // the next idle period can compact again (D2), whether it answers a pending
@@ -9815,7 +10153,7 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
9815
10153
  // the quote — the reply context is deliberately dropped here. Not a request
9816
10154
  // either: the turn it unblocks continues under the open one. A forwarded digit
9817
10155
  // is not a pick: it falls to the free-form route below and reaches the agent marked.
9818
- await applyQuestionAnswer(key, route.labels);
10156
+ await applyQuestionAnswer(key, route.labels, messageContext?.nonOperatorSender);
9819
10157
  return null;
9820
10158
  }
9821
10159
  // Free-form text cancels the question and is a fresh prompt — a request (S7).
@@ -9829,7 +10167,7 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
9829
10167
  // before forwarding — the slash text itself never gets a preamble. The agent's
9830
10168
  // context is gone, so any intake files it might reference are now useless —
9831
10169
  // purge the thread's files dir in the same breath.
9832
- if (text === forwardedClearCommand && !isForwarded) {
10170
+ if (text === forwardedClearCommand && !(0, messageContext_1.checkIsForeignWords)(messageContext)) {
9833
10171
  clearThreadContextMarker(key);
9834
10172
  await (0, botFileStorage_1.purgeThreadFiles)(getDataDir(), key).catch((e) => console.warn(`[file] purge on /clear failed for ${(0, sessionKey_1.keyToString)(key)}:`, e));
9835
10173
  }
@@ -9935,21 +10273,25 @@ async function cancelPendingQuestionAndForward(key, adapter, text, sentAtMs, mes
9935
10273
  * inline-button (`qa_`) and custom-text answer paths so both collect answers
9936
10274
  * locally instead of closing the request on the first answer with empties.
9937
10275
  */
9938
- async function applyQuestionAnswer(key, answerForCurrent) {
10276
+ async function applyQuestionAnswer(key, answerForCurrent, answeredBy) {
9939
10277
  // Serialized: an in-flight re-post (delete+re-send) must fully finish before
9940
10278
  // the answer reads `messageId` for its ✅-edit — otherwise the edit targets
9941
10279
  // a message the re-post just deleted (live 2026-06-10: "message to edit not
9942
10280
  // found" + the next question never reached the topic).
9943
- return runQuestionLifecycleOp(key, () => applyQuestionAnswerInner(key, answerForCurrent));
10281
+ return runQuestionLifecycleOp(key, () => applyQuestionAnswerInner(key, answerForCurrent, answeredBy));
9944
10282
  }
9945
- /** Resolves to whether the topic now shows the whole answer: the answered question's message was edited to carry it. */
9946
- async function applyQuestionAnswerInner(key, answerForCurrent) {
10283
+ /**
10284
+ * Resolves to whether the topic now shows the whole answer: the answered question's message was edited to carry it.
10285
+ * `answeredBy` (the description of a person who is not the operator) rides in the answer the agent reads — each part of a
10286
+ * question of several parts says who chose it — and never in the note the topic shows, which stays the chosen label.
10287
+ */
10288
+ async function applyQuestionAnswerInner(key, answerForCurrent, answeredBy) {
9947
10289
  const kStr = (0, sessionKey_1.keyToString)(key);
9948
10290
  const pending = pendingQuestions.get(kStr);
9949
10291
  if (!pending)
9950
10292
  return false;
9951
10293
  const answeredQuestion = pending.data.questions[pending.currentIndex];
9952
- const { nextState, action } = (0, openCodeQuestionFlow_1.recordAnswerAndAdvance)(pending, answerForCurrent);
10294
+ const { nextState, action } = (0, openCodeQuestionFlow_1.recordAnswerAndAdvance)(pending, answeredBy === undefined ? answerForCurrent : (0, authorMark_1.getAnswerWithAttribution)(answerForCurrent, answeredBy));
9953
10295
  // Mark the answered question's message as done: the question stays as asked, the chosen answer takes the place of
9954
10296
  // its buttons.
9955
10297
  const isAnswerShown = pending.messageId !== null && answeredQuestion !== undefined && await editQuestionMessageToClosed(key, pending.messageId, answeredQuestion, (0, i18n_1.t)('agent.question_answered_note', { answer: answerForCurrent.join(', ') }));
@@ -11431,6 +11773,7 @@ exports.COMMANDS_MENU = [
11431
11773
  { command: 'timestamps', description: '🕒 Prepend send time to forwarded prompts' },
11432
11774
  { command: 'language', description: '🌐 Bot language for this chat/group' },
11433
11775
  { command: 'timezone', description: '🌍 Timezone for schedules and time context' },
11776
+ { command: 'access', description: '🔑 Who may talk to the agent in this topic (without being an admin)' },
11434
11777
  { command: 'whoami', description: 'đŸĒĒ Show debug ids' },
11435
11778
  { command: 'pair', description: '🔗 Bind this group to the bot' },
11436
11779
  { command: 'version', description: 'â„šī¸ Versions of bot + CLI tools' },
@@ -11681,9 +12024,11 @@ async function reattachExistingSessions(opts = { quietReattach: false }) {
11681
12024
  // reopen the FIFO writer and resume the stdout tail from the persisted
11682
12025
  // line-boundary offset, so everything produced during the downtime
11683
12026
  // replays through the normal pipeline (which is why an adopt posts NO
11684
- // recap — the replay IS the delivery). A session whose thread released
11685
- // its persisted id (`/quit`, `/new`) or isn't a json-stream thread is an
11686
- // orphan and is killed, never adopted (locked decision). A bound
12027
+ // recap — the replay IS the delivery) — read only from the boot's
12028
+ // `releaseAdoptedSessions` step on, once the restored state is back. A
12029
+ // session whose thread released its persisted id (`/quit`, `/new`) or
12030
+ // isn't a json-stream thread is an orphan and is killed, never adopted
12031
+ // (locked decision). A bound
11687
12032
  // json-stream thread with a persisted id but no live process SLEEPS
11688
12033
  // (lifecycle plan L4): it is NOT re-spawned — its next trigger resumes it
11689
12034
  // — and it gets the downtime recap read from the transcript alone. An
@@ -12047,7 +12392,8 @@ function readParkedErrorWrittenAtMs(key, claudeSessionId, errorText) {
12047
12392
  }
12048
12393
  /**
12049
12394
  * @description The threads whose limit episode the boot recovery armed and whose adopt is still replaying the downtime tail
12050
- * ({@link handleApiError} leaves the replay's copy of that error alone). An entry lives until the replay is over.
12395
+ * ({@link handleApiError} leaves the replay's copy of that error alone). An entry lives until the replay is over. The replay
12396
+ * cannot come first: an adopted session's output is read only after the boot's restore step (`releaseAdoptedSessions`).
12051
12397
  */
12052
12398
  const limitEpisodesOwnedByRecovery = new Set();
12053
12399
  /**
@@ -12133,8 +12479,8 @@ function recoverLimitEpisodesFromDisk() {
12133
12479
  void state
12134
12480
  .setLimitEpisodeRecovered(key, log)
12135
12481
  .catch(e => console.error('[limitRecovery] marker persist failed:', e));
12136
- // This episode is the recovery's alone: the adopt replays the same error a moment later (the tail was read from the
12137
- // saved offset), and `handleApiError` leaves that copy out until the replay is over.
12482
+ // This episode is the recovery's alone: the adopt replays the same error once the boot releases its output (after this
12483
+ // step), and `handleApiError` leaves that copy out until the replay is over.
12138
12484
  limitEpisodesOwnedByRecovery.add(keyStr);
12139
12485
  void ((0, createAdapter_1.getAdapter)(agent.name).whenAdoptReplayed?.(key) ?? Promise.resolve()).then(() => limitEpisodesOwnedByRecovery.delete(keyStr));
12140
12486
  void withThreadLocale(key, () => handleApiError(key, decision.cls, { isRecoveredEpisode: true }));
@@ -12148,7 +12494,7 @@ function recoverLimitEpisodesFromDisk() {
12148
12494
  * side — the mirror of OpenCode's `reconcileSchedulerMcpForActiveSessions`. A
12149
12495
  * json-stream session survives every bot restart, but its MCP client never
12150
12496
  * retries a server it once failed to reach, so a session that was alive across
12151
- * the restart can hold a permanently-`failed` `telegramBot` entry and lose
12497
+ * the restart can hold a permanently-`failed` `charness` entry and lose
12152
12498
  * `schedule_*` / `compact_conversation` / `send_file_to_user` /
12153
12499
  * `send_messages_to_user` for the rest of its life. Ask every live session whose
12154
12500
  * backend exposes `healMcpServer` and reconnect the ones that report `failed`.
@@ -12172,10 +12518,14 @@ function healSchedulerMcpForActiveSessions() {
12172
12518
  if (!adapter.healMcpServer || !adapter.checkIsActive(key))
12173
12519
  continue;
12174
12520
  const keyStr = (0, sessionKey_1.keyToString)(key);
12175
- void adapter.healMcpServer(key, injection_1.schedulerMcpServerName).then((outcome) => {
12521
+ void adapter.healMcpServer(key, injection_1.schedulerMcpServerName, legacyNames_1.legacySchedulerMcpServerName).then((outcome) => {
12176
12522
  if (outcome === 'healed') {
12177
12523
  console.log(`[scheduler] MCP heal: reconnected ${injection_1.schedulerMcpServerName} in ${keyStr}`);
12178
12524
  }
12525
+ else if (outcome === 'healedLegacy') {
12526
+ console.log(`[scheduler] MCP heal: reconnected ${legacyNames_1.legacySchedulerMcpServerName} in ${keyStr} — the agent started before the rename to ` +
12527
+ `${injection_1.schedulerMcpServerName} and keeps the old tool names until it restarts`);
12528
+ }
12179
12529
  else if (outcome === 'unavailable') {
12180
12530
  console.warn(`[scheduler] MCP heal: ${keyStr} left unhealed — its status ask went unanswered, or the reconnect was refused`);
12181
12531
  }
@@ -12523,7 +12873,8 @@ function wireScheduler(wiring) {
12523
12873
  const decision = (0, validation_1.resolveBoundWorkDir)(ENV.workRoot, state.getBinding((0, sessionKey_1.keyFromString)(threadKeyStr)));
12524
12874
  if (decision.kind !== 'proceed')
12525
12875
  return null;
12526
- return (0, checkRun_1.runCheckCommand)({ command, cwd: decision.workDir, timeoutMs, env: (0, checkRun_1.buildCheckEnv)(process.env) });
12876
+ // A check runs what an agent wrote, and its output is posted into the topic: never with the bot's own secrets.
12877
+ return (0, checkRun_1.runCheckCommand)({ command, cwd: decision.workDir, timeoutMs, env: (0, agentEnvironment_1.getChildProcessEnvironment)() });
12527
12878
  },
12528
12879
  setCheckFailing: async (jobId, isFailing) => {
12529
12880
  const record = state.getSchedules()[jobId];
@@ -12621,7 +12972,7 @@ function wireScheduler(wiring) {
12621
12972
  whenSessionsRestored: wiring.whenSessionsRestored,
12622
12973
  getSecret: () => state.getSchedulerMcpSecret(),
12623
12974
  // Reuse the port persisted from a prior boot (env override wins) so the
12624
- // `telegramBot` registrations injected into agent sessions keep pointing at
12975
+ // `charness` registrations injected into agent sessions keep pointing at
12625
12976
  // a live port across restarts instead of orphaning on a fresh ephemeral one.
12626
12977
  port: (0, mcpSurface_1.resolveSchedulerMcpPort)((0, mcpSurface_1.getSchedulerMcpPort)(), state.getPersistedSchedulerMcpPort()),
12627
12978
  });
@@ -13242,6 +13593,15 @@ async function startBot() {
13242
13593
  // the live persisted set during reattach).
13243
13594
  void reconcileTransientFrames(orphanedTransientFrames).catch((error) => console.error('[reattach] transient frame cleanup failed:', error));
13244
13595
  },
13596
+ // Only now is an adopted json-stream session's output read: its downtime replay is handled against the state restored
13597
+ // above — the limit episode the recovery took over stays the recovery's, an armed retry is not armed twice.
13598
+ releaseAdoptedSessions: () => {
13599
+ for (const name of [adapterNames_1.claudeJsonStreamAdapterName, adapterNames_1.claudePerTurnAdapterName]) {
13600
+ const adapter = (0, createAdapter_1.getAdapter)(name);
13601
+ if (adapter instanceof claudeJsonStreamAdapter_1.ClaudeJsonStreamAdapter)
13602
+ adapter.releaseAdoptedTails(ENV.testTimings.adoptedTailFirstReadMs);
13603
+ }
13604
+ },
13245
13605
  // The bot MCP tools that read session state (compact_conversation) wait
13246
13606
  // for this: until now a surviving session would read as not running.
13247
13607
  onSessionsRestored: () => {
@@ -13253,22 +13613,22 @@ async function startBot() {
13253
13613
  },
13254
13614
  healActiveSessions: () => {
13255
13615
  // When this boot ADOPTED an already-running opencode, that server may
13256
- // still hold a `telegramBot` registration from the previous bot
13616
+ // still hold a `charness` registration from the previous bot
13257
13617
  // generation pointing at a now-dead port. Reconcile against the live MCP
13258
13618
  // status and force-refresh any directory that is not `connected`.
13259
13619
  // Fire-and-forget: boot must not block on opencode HTTP round-trips
13260
- // before `bot.launch()`. The skills step (a server started without the
13261
- // bot's skills folder is replaced) and the compaction-plugin step go FIRST:
13620
+ // before `bot.launch()`. The launch step (a server started without the
13621
+ // bot's skills folder or without a password is replaced) and the compaction-plugin step go FIRST:
13262
13622
  // a replaced server or a recreated directory instance drops the MCP
13263
13623
  // registration, which this same reconcile then restores.
13264
13624
  const openCodeAdapter = (0, createAdapter_1.getAdapter)('opencode');
13265
13625
  void (async () => {
13266
- await openCodeAdapter.activateAgentSkillsForServer?.();
13626
+ await openCodeAdapter.replaceMislaunchedServer?.();
13267
13627
  await openCodeAdapter.activateCompactionPluginForActiveSessions?.();
13268
13628
  await openCodeAdapter.reconcileSchedulerMcpForActiveSessions?.();
13269
13629
  })().catch((e) => console.warn('[scheduler] MCP reconcile failed:', e instanceof Error ? e.message : e));
13270
13630
  // Same class of self-heal on the Claude side: a json-stream session that
13271
- // SURVIVED this restart can hold a `telegramBot` entry latched `failed`,
13631
+ // SURVIVED this restart can hold a `charness` entry latched `failed`,
13272
13632
  // and the CLI never retries a failed MCP server. Fire-and-forget.
13273
13633
  healSchedulerMcpForActiveSessions();
13274
13634
  },