charness 3.12.0 → 3.13.0

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