charness 4.1.1 → 4.2.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 (206) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/DEVELOPMENT.md +10 -4
  3. package/{COMMERCIAL-LICENSE.md → LICENSE-COMMERCIAL.md} +1 -1
  4. package/MIGRATION_3_TO_4.md +1 -1
  5. package/README.md +4 -1
  6. package/SETUP.md +3 -1
  7. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +1 -0
  8. package/agent-plugin/skills/charness-orchestration/SKILL.md +1 -0
  9. package/dist/adapters/adapterNames.d.ts +2 -0
  10. package/dist/adapters/adapterNames.d.ts.map +1 -1
  11. package/dist/adapters/adapterNames.js +3 -1
  12. package/dist/adapters/adapterNames.js.map +1 -1
  13. package/dist/adapters/claudeJsonStreamAdapter.d.ts +14 -0
  14. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  15. package/dist/adapters/claudeJsonStreamAdapter.js +36 -6
  16. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  17. package/dist/adapters/openCodeAdapter.d.ts +31 -2
  18. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  19. package/dist/adapters/openCodeAdapter.js +84 -8
  20. package/dist/adapters/openCodeAdapter.js.map +1 -1
  21. package/dist/adapters/terminalAdapter.d.ts.map +1 -1
  22. package/dist/adapters/terminalAdapter.js +2 -1
  23. package/dist/adapters/terminalAdapter.js.map +1 -1
  24. package/dist/bot.d.ts.map +1 -1
  25. package/dist/bot.js +605 -87
  26. package/dist/bot.js.map +1 -1
  27. package/dist/cli/claudeProfiles.d.ts +3 -0
  28. package/dist/cli/claudeProfiles.d.ts.map +1 -1
  29. package/dist/cli/claudeProfiles.js +8 -0
  30. package/dist/cli/claudeProfiles.js.map +1 -1
  31. package/dist/connectors/telegram/commands/botCore.d.ts +5 -2
  32. package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -1
  33. package/dist/connectors/telegram/commands/claudeAccounts.d.ts +5 -0
  34. package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
  35. package/dist/connectors/telegram/commands/claudeAccounts.js +15 -39
  36. package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
  37. package/dist/connectors/telegram/commands/compaction.d.ts +6 -0
  38. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  39. package/dist/connectors/telegram/commands/compaction.js +8 -1
  40. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  41. package/dist/connectors/telegram/commands/questionSetAside.d.ts +111 -0
  42. package/dist/connectors/telegram/commands/questionSetAside.d.ts.map +1 -0
  43. package/dist/connectors/telegram/commands/questionSetAside.js +637 -0
  44. package/dist/connectors/telegram/commands/questionSetAside.js.map +1 -0
  45. package/dist/connectors/telegram/commands/questionWait.d.ts +21 -0
  46. package/dist/connectors/telegram/commands/questionWait.d.ts.map +1 -0
  47. package/dist/connectors/telegram/commands/questionWait.js +109 -0
  48. package/dist/connectors/telegram/commands/questionWait.js.map +1 -0
  49. package/dist/connectors/telegram/commands/topicAccess.js +1 -1
  50. package/dist/connectors/telegram/commands/topicAccess.js.map +1 -1
  51. package/dist/connectors/telegram/commands/topicCommand.d.ts +0 -2
  52. package/dist/connectors/telegram/commands/topicCommand.d.ts.map +1 -1
  53. package/dist/connectors/telegram/commands/topicCommand.js +4 -5
  54. package/dist/connectors/telegram/commands/topicCommand.js.map +1 -1
  55. package/dist/connectors/telegram/commands/topicStatus.d.ts +24 -0
  56. package/dist/connectors/telegram/commands/topicStatus.d.ts.map +1 -0
  57. package/dist/connectors/telegram/commands/topicStatus.js +148 -0
  58. package/dist/connectors/telegram/commands/topicStatus.js.map +1 -0
  59. package/dist/connectors/telegram/firstUpdateBatchNote.d.ts +30 -0
  60. package/dist/connectors/telegram/firstUpdateBatchNote.d.ts.map +1 -0
  61. package/dist/connectors/telegram/firstUpdateBatchNote.js +39 -0
  62. package/dist/connectors/telegram/firstUpdateBatchNote.js.map +1 -0
  63. package/dist/connectors/telegram/inbound.d.ts +12 -0
  64. package/dist/connectors/telegram/inbound.d.ts.map +1 -1
  65. package/dist/connectors/telegram/inbound.js +31 -3
  66. package/dist/connectors/telegram/inbound.js.map +1 -1
  67. package/dist/connectors/telegram/topicIndicator.d.ts +86 -0
  68. package/dist/connectors/telegram/topicIndicator.d.ts.map +1 -0
  69. package/dist/connectors/telegram/topicIndicator.js +490 -0
  70. package/dist/connectors/telegram/topicIndicator.js.map +1 -0
  71. package/dist/connectors/telegram/waitingTopicRenames.d.ts +39 -0
  72. package/dist/connectors/telegram/waitingTopicRenames.d.ts.map +1 -0
  73. package/dist/connectors/telegram/waitingTopicRenames.js +48 -0
  74. package/dist/connectors/telegram/waitingTopicRenames.js.map +1 -0
  75. package/dist/i18n/de.d.ts.map +1 -1
  76. package/dist/i18n/de.js +47 -0
  77. package/dist/i18n/de.js.map +1 -1
  78. package/dist/i18n/en.d.ts.map +1 -1
  79. package/dist/i18n/en.js +47 -0
  80. package/dist/i18n/en.js.map +1 -1
  81. package/dist/i18n/es.d.ts.map +1 -1
  82. package/dist/i18n/es.js +47 -0
  83. package/dist/i18n/es.js.map +1 -1
  84. package/dist/i18n/fr.d.ts.map +1 -1
  85. package/dist/i18n/fr.js +47 -0
  86. package/dist/i18n/fr.js.map +1 -1
  87. package/dist/i18n/hi.d.ts.map +1 -1
  88. package/dist/i18n/hi.js +47 -0
  89. package/dist/i18n/hi.js.map +1 -1
  90. package/dist/i18n/ja.d.ts.map +1 -1
  91. package/dist/i18n/ja.js +47 -0
  92. package/dist/i18n/ja.js.map +1 -1
  93. package/dist/i18n/ka.d.ts.map +1 -1
  94. package/dist/i18n/ka.js +47 -0
  95. package/dist/i18n/ka.js.map +1 -1
  96. package/dist/i18n/pt.d.ts.map +1 -1
  97. package/dist/i18n/pt.js +47 -0
  98. package/dist/i18n/pt.js.map +1 -1
  99. package/dist/i18n/ru.d.ts.map +1 -1
  100. package/dist/i18n/ru.js +47 -0
  101. package/dist/i18n/ru.js.map +1 -1
  102. package/dist/i18n/uk.d.ts.map +1 -1
  103. package/dist/i18n/uk.js +47 -0
  104. package/dist/i18n/uk.js.map +1 -1
  105. package/dist/i18n/uz.d.ts.map +1 -1
  106. package/dist/i18n/uz.js +47 -0
  107. package/dist/i18n/uz.js.map +1 -1
  108. package/dist/i18n/zh.d.ts.map +1 -1
  109. package/dist/i18n/zh.js +47 -0
  110. package/dist/i18n/zh.js.map +1 -1
  111. package/dist/instanceSettings.d.ts +19 -1
  112. package/dist/instanceSettings.d.ts.map +1 -1
  113. package/dist/instanceSettings.js +35 -2
  114. package/dist/instanceSettings.js.map +1 -1
  115. package/dist/openCodeOpenQuestion.d.ts +12 -4
  116. package/dist/openCodeOpenQuestion.d.ts.map +1 -1
  117. package/dist/openCodeOpenQuestion.js +16 -7
  118. package/dist/openCodeOpenQuestion.js.map +1 -1
  119. package/dist/openCodeQuestionFlow.d.ts +10 -2
  120. package/dist/openCodeQuestionFlow.d.ts.map +1 -1
  121. package/dist/openCodeQuestionFlow.js +27 -5
  122. package/dist/openCodeQuestionFlow.js.map +1 -1
  123. package/dist/postToSession.d.ts +9 -0
  124. package/dist/postToSession.d.ts.map +1 -1
  125. package/dist/postToSession.js +15 -2
  126. package/dist/postToSession.js.map +1 -1
  127. package/dist/state.d.ts +98 -6
  128. package/dist/state.d.ts.map +1 -1
  129. package/dist/state.js +149 -7
  130. package/dist/state.js.map +1 -1
  131. package/dist/testTimings.d.ts +10 -2
  132. package/dist/testTimings.d.ts.map +1 -1
  133. package/dist/testTimings.js +20 -1
  134. package/dist/testTimings.js.map +1 -1
  135. package/dist/todos/registry.d.ts +2 -0
  136. package/dist/todos/registry.d.ts.map +1 -1
  137. package/dist/todos/registry.js +3 -1
  138. package/dist/todos/registry.js.map +1 -1
  139. package/dist/types.d.ts +88 -0
  140. package/dist/types.d.ts.map +1 -1
  141. package/dist/utils/claudeCompactHook.d.ts +3 -1
  142. package/dist/utils/claudeCompactHook.d.ts.map +1 -1
  143. package/dist/utils/claudeCompactHook.js +3 -1
  144. package/dist/utils/claudeCompactHook.js.map +1 -1
  145. package/dist/utils/claudeLimitSwitch.d.ts +1 -1
  146. package/dist/utils/claudeLimitSwitch.d.ts.map +1 -1
  147. package/dist/utils/claudeLimitSwitch.js +1 -1
  148. package/dist/utils/claudeLimitSwitch.js.map +1 -1
  149. package/dist/utils/claudeProfileSync.d.ts +88 -0
  150. package/dist/utils/claudeProfileSync.d.ts.map +1 -0
  151. package/dist/utils/claudeProfileSync.js +198 -0
  152. package/dist/utils/claudeProfileSync.js.map +1 -0
  153. package/dist/utils/claudeProfiles.d.ts +101 -6
  154. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  155. package/dist/utils/claudeProfiles.js +288 -23
  156. package/dist/utils/claudeProfiles.js.map +1 -1
  157. package/dist/utils/claudeUsageRefresher.d.ts +8 -1
  158. package/dist/utils/claudeUsageRefresher.d.ts.map +1 -1
  159. package/dist/utils/claudeUsageRefresher.js +11 -1
  160. package/dist/utils/claudeUsageRefresher.js.map +1 -1
  161. package/dist/utils/cutButtonLabel.d.ts +7 -0
  162. package/dist/utils/cutButtonLabel.d.ts.map +1 -0
  163. package/dist/utils/cutButtonLabel.js +17 -0
  164. package/dist/utils/cutButtonLabel.js.map +1 -0
  165. package/dist/utils/limitSwitchPlan.d.ts +44 -0
  166. package/dist/utils/limitSwitchPlan.d.ts.map +1 -0
  167. package/dist/utils/limitSwitchPlan.js +54 -0
  168. package/dist/utils/limitSwitchPlan.js.map +1 -0
  169. package/dist/utils/questionWaitChoices.d.ts +20 -0
  170. package/dist/utils/questionWaitChoices.d.ts.map +1 -0
  171. package/dist/utils/questionWaitChoices.js +31 -0
  172. package/dist/utils/questionWaitChoices.js.map +1 -0
  173. package/dist/utils/questionWaitPlan.d.ts +166 -0
  174. package/dist/utils/questionWaitPlan.d.ts.map +1 -0
  175. package/dist/utils/questionWaitPlan.js +237 -0
  176. package/dist/utils/questionWaitPlan.js.map +1 -0
  177. package/dist/utils/replyQuote.d.ts +10 -0
  178. package/dist/utils/replyQuote.d.ts.map +1 -1
  179. package/dist/utils/replyQuote.js +18 -7
  180. package/dist/utils/replyQuote.js.map +1 -1
  181. package/dist/utils/talkerAccess.d.ts +2 -2
  182. package/dist/utils/talkerAccess.d.ts.map +1 -1
  183. package/dist/utils/talkerAccess.js +5 -4
  184. package/dist/utils/talkerAccess.js.map +1 -1
  185. package/dist/utils/telegramError.d.ts +6 -0
  186. package/dist/utils/telegramError.d.ts.map +1 -1
  187. package/dist/utils/telegramError.js +12 -0
  188. package/dist/utils/telegramError.js.map +1 -1
  189. package/dist/utils/topicAccessScreenPlan.d.ts +1 -1
  190. package/dist/utils/topicAccessScreenPlan.d.ts.map +1 -1
  191. package/dist/utils/topicAccessScreenPlan.js +3 -7
  192. package/dist/utils/topicAccessScreenPlan.js.map +1 -1
  193. package/dist/utils/topicIndicatorPlan.d.ts +143 -0
  194. package/dist/utils/topicIndicatorPlan.d.ts.map +1 -0
  195. package/dist/utils/topicIndicatorPlan.js +202 -0
  196. package/dist/utils/topicIndicatorPlan.js.map +1 -0
  197. package/dist/utils/topicIndicatorSources.d.ts +40 -0
  198. package/dist/utils/topicIndicatorSources.d.ts.map +1 -0
  199. package/dist/utils/topicIndicatorSources.js +31 -0
  200. package/dist/utils/topicIndicatorSources.js.map +1 -0
  201. package/dist/utils/topicStatusPlan.d.ts +90 -0
  202. package/dist/utils/topicStatusPlan.d.ts.map +1 -0
  203. package/dist/utils/topicStatusPlan.js +160 -0
  204. package/dist/utils/topicStatusPlan.js.map +1 -0
  205. package/npm-shrinkwrap.json +2 -2
  206. package/package.json +2 -2
package/dist/bot.js CHANGED
@@ -69,6 +69,13 @@ const openCodeAdapter_1 = require("./adapters/openCodeAdapter");
69
69
  const terminalAdapter_1 = require("./adapters/terminalAdapter");
70
70
  const openCodeQuestionFlow_1 = require("./openCodeQuestionFlow");
71
71
  const pendingQuestionRepost_1 = require("./pendingQuestionRepost");
72
+ const questionSetAside_1 = require("./connectors/telegram/commands/questionSetAside");
73
+ const questionWaitPlan_1 = require("./utils/questionWaitPlan");
74
+ const topicIndicatorPlan_1 = require("./utils/topicIndicatorPlan");
75
+ const topicIndicator_1 = require("./connectors/telegram/topicIndicator");
76
+ const firstUpdateBatchNote_1 = require("./connectors/telegram/firstUpdateBatchNote");
77
+ const waitingTopicRenames_1 = require("./connectors/telegram/waitingTopicRenames");
78
+ const topicIndicatorSources_1 = require("./utils/topicIndicatorSources");
72
79
  const rateLimiter_1 = require("./rateLimiter");
73
80
  const testTimings_1 = require("./testTimings");
74
81
  const installManager_1 = require("./installManager");
@@ -258,6 +265,8 @@ const callbackToast_2 = require("./connectors/telegram/commands/callbackToast");
258
265
  const compaction_1 = require("./connectors/telegram/commands/compaction");
259
266
  const autoContinueLimits_1 = require("./connectors/telegram/commands/autoContinueLimits");
260
267
  const botSkills_2 = require("./connectors/telegram/commands/botSkills");
268
+ const questionWait_1 = require("./connectors/telegram/commands/questionWait");
269
+ const topicStatus_1 = require("./connectors/telegram/commands/topicStatus");
261
270
  const topicAccess_1 = require("./connectors/telegram/commands/topicAccess");
262
271
  const taskAgents_1 = require("./connectors/telegram/commands/taskAgents");
263
272
  const runners_1 = require("./connectors/telegram/commands/runners");
@@ -273,9 +282,11 @@ const claudeAccounts_1 = require("./connectors/telegram/commands/claudeAccounts"
273
282
  const claudeProfiles_1 = require("./utils/claudeProfiles");
274
283
  const claudeUsage_1 = require("./utils/claudeUsage");
275
284
  const claudeUsageRefresher_1 = require("./utils/claudeUsageRefresher");
285
+ const claudeProfileSync_1 = require("./utils/claudeProfileSync");
276
286
  const openCodeUsage_1 = require("./utils/openCodeUsage");
277
287
  const usageRefreshBudget_1 = require("./utils/usageRefreshBudget");
278
288
  const claudeLimitSwitch_1 = require("./utils/claudeLimitSwitch");
289
+ const limitSwitchPlan_1 = require("./utils/limitSwitchPlan");
279
290
  const anthropicApiKeyCheck_1 = require("./utils/anthropicApiKeyCheck");
280
291
  const claudeApiKeyHelper_1 = require("./utils/claudeApiKeyHelper");
281
292
  const fallbackSwitchNotice_1 = require("./utils/fallbackSwitchNotice");
@@ -420,6 +431,7 @@ if (ENV.testTimings.backgroundHoldMaxMs !== undefined)
420
431
  (0, createAdapter_1.registerPendingWorkHoldMs)(ENV.testTimings.backgroundHoldMaxMs);
421
432
  if (ENV.testTimings.scheduleMinFireIntervalMs !== undefined)
422
433
  (0, recurrence_1.registerMinFireIntervalMs)(ENV.testTimings.scheduleMinFireIntervalMs);
434
+ (0, postToSession_1.registerPostWaitWindows)({ busyPollMs: ENV.testTimings.postBusyPollMs, waitForIdleMs: ENV.testTimings.postWaitForIdleMs });
423
435
  /** The short retry that probes an unconfirmed usage limit (a test instance may shorten it). */
424
436
  const limitProbeDelayMs = ENV.testTimings.limitProbeDelayMs ?? apiErrorRetry_1.unconfirmedLimitProbeDelayMs;
425
437
  // The instance default effort (`/effort` in General) is `settings.json`'s `defaultEffort`, re-read when the file changes.
@@ -486,9 +498,12 @@ function checkIsDmKey(key) {
486
498
  * chat type and identifies the owner. False when the DM surface is inert.
487
499
  */
488
500
  function checkIsDmChat(ctx) {
501
+ return checkIsOwnerDm(ctx.chat);
502
+ }
503
+ /** @description Whether `chat` is the owner's private chat on a surface that serves it. */
504
+ function checkIsOwnerDm(chat) {
489
505
  if (!checkIsDmSurfaceActive())
490
506
  return false;
491
- const chat = ctx.chat;
492
507
  if (!chat || chat.type !== 'private')
493
508
  return false;
494
509
  return chat.id === getOwnerUserId();
@@ -549,6 +564,9 @@ process.on('exit', outputTrace_1.flushTraceBufferSyncOnExit);
549
564
  // connection the server had closed. AFTER the trace wrap, so the trace records both real HTTP attempts, and below the
550
565
  // send queue, pacer and 429 retry. Telegraf builds a NEW client per update: see the first `bot.use` below.
551
566
  (0, botApiConnection_1.wireBotApiClient)(bot.telegram, telegramApiAgent);
567
+ // The first answered long poll: the updates that waited while the bot was down are in its hands from then on — the boot wave of the topic
568
+ // status marks waits for it and for the dispatcher to be idle, so an owner's rename made during the downtime is learned before the wave writes.
569
+ const firstUpdateBatch = (0, firstUpdateBatchNote_1.installFirstUpdateBatchNote)(bot.telegram);
552
570
  // Default every text message/edit to NO link preview: a bare URL in agent
553
571
  // output otherwise expanded into a large preview card, one per message, in the
554
572
  // muted topic (operator complaint 2026-09-07). Installed OUTSIDE the trace wrap
@@ -657,10 +675,13 @@ const seenGroupSenders = (0, topicTalkerMemory_1.createSeenSenders)();
657
675
  * group with the owner id would lock out the group's real admins.
658
676
  */
659
677
  async function checkIsAllowedUser(ctx) {
660
- const userId = ctx.from?.id;
678
+ return checkIsAllowedSender(checkIsDmChat(ctx), ctx.from?.id);
679
+ }
680
+ /** @description {@link checkIsAllowedUser} for a sender read off a raw update (no `ctx`): `isDmChat` says which surface decides. */
681
+ async function checkIsAllowedSender(isDmChat, userId) {
661
682
  if (!userId)
662
683
  return false;
663
- if (checkIsDmChat(ctx)) {
684
+ if (isDmChat) {
664
685
  return userId === getOwnerUserId();
665
686
  }
666
687
  const adminIds = await adminCache.getAdminIds();
@@ -792,6 +813,17 @@ bot.use(async (ctx, next) => {
792
813
  }
793
814
  return next();
794
815
  });
816
+ // The name a topic was created with rides on the root message a client attaches to the owner's plain messages: kept as a candidate for
817
+ // the topic's name while the bot does not know it (it is offered to the owner, never applied by itself).
818
+ bot.use(async (ctx, next) => {
819
+ try {
820
+ await noteTopicNameCandidate(ctx);
821
+ }
822
+ catch (e) {
823
+ console.warn('[topic-name] noting the creation name of a topic failed:', e instanceof Error ? e.message : e);
824
+ }
825
+ return next();
826
+ });
795
827
  // Default-deny for talkers on buttons: a person an admin let talk to the agent here may tap only the agent's own question
796
828
  // buttons (`checkIsTalkerCallback`). Every other tap is refused with one toast, here, so no handler or module has to know a
797
829
  // talker exists — each of them keeps asking the admin gate.
@@ -1011,7 +1043,7 @@ function getDataDir() {
1011
1043
  /** The shared todo registry (`todos/`), built on first use: its store lives in `DATA_DIR`, known once the state is. */
1012
1044
  let todoRegistry = null;
1013
1045
  function getTodoRegistry() {
1014
- todoRegistry ??= (0, registry_1.createTodoRegistry)({ store: new store_1.TodoStore(getDataDir()), getNowMs: Date.now });
1046
+ todoRegistry ??= (0, registry_1.createTodoRegistry)({ store: new store_1.TodoStore(getDataDir()), getNowMs: Date.now, onItemsChanged: (key) => topicIndicator.requestRefresh(key) });
1015
1047
  return todoRegistry;
1016
1048
  }
1017
1049
  /**
@@ -1291,29 +1323,51 @@ const identicalOutputGuard = (0, identicalOutputGuard_1.createIdenticalOutputGua
1291
1323
  */
1292
1324
  function setPendingQuestion(key, value) {
1293
1325
  pendingQuestions.set((0, sessionKey_1.keyToString)(key), value);
1326
+ topicIndicator.requestRefresh(key);
1294
1327
  state.setPendingQuestion(key, value).catch(e => console.error('[pendingQuestion] persist failed:', e));
1295
1328
  }
1296
1329
  /**
1297
- * @description Drop a thread's pending interactive question from BOTH the
1298
- * in-memory map and the persisted store. Single choke point for every
1299
- * `pendingQuestions.delete(...)` so memory and disk stay in lockstep.
1330
+ * @description The ONE place a thread's pending interactive question is removed: from the in-memory map, the persisted store
1331
+ * and the re-post and set-aside-timer bookkeeping, so memory and disk stay in lockstep. Everything it does is STARTED in the
1332
+ * same tick, in order — the saved-state clear and the pin step queue behind whatever else touches them — so a question the
1333
+ * agent asks right after cannot be wiped by a removal that is still finishing: its own writes queue after this one's.
1334
+ *
1335
+ * `isPinKept`: the bot SET the question aside, so its pin stays — it belongs to the set-aside record now. The map entry that
1336
+ * tracks «the pinned question» is dropped WITHOUT unpinning, so the pin of the question the agent asks next neither retires it
1337
+ * nor counts as a re-pin (which is silent); taken under the pin lock, after any pin of this question still in flight. Otherwise
1338
+ * the pin is released. Resolves once the saved state and the pin step are done.
1300
1339
  */
1301
- function clearPendingQuestion(key) {
1340
+ function dropPendingQuestion(key, options) {
1302
1341
  const kStr = (0, sessionKey_1.keyToString)(key);
1303
- // Post-restart OpenCode: the in-memory pin map was lost on restart but the
1304
- // question message is still pinned on Telegram (its id lives on the persisted
1305
- // `pendingQuestions` entry). Seed the map from it so the unpin below finds the
1306
- // id — deterministic, with no reliance on sync execution order against the
1307
- // `delete` that follows. The live case is a no-op (the map already holds the
1308
- // id; `has` is true).
1309
- const pending = pendingQuestions.get(kStr);
1310
- if (pending?.messageId != null && !questionPinnedMessageId.has(kStr)) {
1311
- questionPinnedMessageId.set(kStr, pending.messageId);
1342
+ let pinStep;
1343
+ if (options.isPinKept) {
1344
+ pinStep = questionPinLock.withLock(kStr, async () => {
1345
+ questionPinnedMessageId.delete(kStr);
1346
+ });
1347
+ }
1348
+ else {
1349
+ // Post-restart OpenCode: the in-memory pin map was lost on restart but the
1350
+ // question message is still pinned on Telegram (its id lives on the persisted
1351
+ // `pendingQuestions` entry). Seed the map from it so the unpin below finds the
1352
+ // id — deterministic, with no reliance on sync execution order against the
1353
+ // `delete` that follows. The live case is a no-op (the map already holds the
1354
+ // id; `has` is true).
1355
+ const pending = pendingQuestions.get(kStr);
1356
+ if (pending?.messageId != null && !questionPinnedMessageId.has(kStr)) {
1357
+ questionPinnedMessageId.set(kStr, pending.messageId);
1358
+ }
1359
+ pinStep = unpinThreadQuestion(key);
1312
1360
  }
1313
- void unpinThreadQuestion(key);
1314
1361
  pendingQuestions.delete(kStr);
1315
- state.clearPendingQuestion(key).catch(e => console.error('[pendingQuestion] clear failed:', e));
1362
+ topicIndicator.requestRefresh(key);
1363
+ const savedStateStep = state.clearPendingQuestion(key).catch(e => console.error('[pendingQuestion] clear failed:', e));
1316
1364
  clearQuestionRepostState(key);
1365
+ clearQuestionSetAsideTimer(key);
1366
+ return Promise.all([pinStep, savedStateStep]).then(() => undefined);
1367
+ }
1368
+ /** @description Drop a thread's pending question and release its pin ({@link dropPendingQuestion}); not awaited. */
1369
+ function clearPendingQuestion(key) {
1370
+ void dropPendingQuestion(key, { isPinKept: false });
1317
1371
  }
1318
1372
  const questionRepostStates = new Map();
1319
1373
  /**
@@ -1455,33 +1509,39 @@ const questionClosingNoteKeys = {
1455
1509
  askedAgain: 'agent.question_asked_again_note',
1456
1510
  };
1457
1511
  /**
1458
- * @description End a question's message in the topic WITHOUT deleting it: the buttons are replaced by `note`, and the
1459
- * header, the question and its options stay, so what the agent asked and how it ended can still be read. Resolves
1460
- * whether the text edit landed. Every way a question ends goes through this — a delete would take the record away.
1512
+ * @description Put a note under a question's message in the topic WITHOUT deleting it or re-posting it: the header, the question
1513
+ * and its options stay, so what the agent asked can still be read, and `note` says what became of it. Without `keyboard` the
1514
+ * buttons are taken off (a question that ended — every way one ends goes through this, a delete would take the record away);
1515
+ * with `keyboard` they are replaced by it (a question the bot set aside keeps option buttons, which now name its record).
1516
+ * Resolves whether the text edit landed.
1461
1517
  *
1462
1518
  * Telegram that cannot parse the Markdown render gets the plain one (no escape marks shown), and a question too long for
1463
- * the note gets a shortened plain one. An edit that still fails (the message gone, say) leaves the old text, and the
1464
- * buttons would stay on it dead — so they are taken off by themselves.
1519
+ * the note gets a shortened plain one. An edit that fails (the message gone, say) leaves the old text — and with it the buttons
1520
+ * of a question that is NO LONGER the one waiting here, which would answer whatever the agent asks next: they are replaced by
1521
+ * `keyboard`, or taken off when there is none or that edit fails too.
1465
1522
  */
1466
- async function editQuestionMessageToClosed(key, messageId, question, note) {
1523
+ async function editQuestionMessageWithNote(key, messageId, question, note, keyboard) {
1467
1524
  const markdownText = (0, openCodeQuestionFlow_1.buildClosedQuestionText)(question, note, escapeMarkdown);
1468
1525
  const plainText = (0, openCodeQuestionFlow_1.buildClosedQuestionPlainText)(question, note, messageSplit_1.MAX_MESSAGE_LEN);
1469
1526
  // A question that filled a message when it was asked has no room for the note under it, and Telegram refuses the text:
1470
1527
  // the note is the result, so the body gives way (descriptions first) and goes out as plain text, which cutting cannot break.
1471
1528
  const isEdited = markdownText.length <= messageSplit_1.MAX_MESSAGE_LEN
1472
- ? await editThreadMessage(key, messageId, markdownText, { parse_mode: 'Markdown' }, plainText)
1473
- : await editThreadMessage(key, messageId, plainText);
1474
- if (!isEdited)
1475
- await editThreadKeyboard(key, messageId, null, 'questionClose');
1476
- return isEdited;
1529
+ ? await editThreadMessage(key, messageId, markdownText, (0, questionKeyboards_1.buildKeyboardExtra)(keyboard, { parse_mode: 'Markdown' }), plainText)
1530
+ : await editThreadMessage(key, messageId, plainText, (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
1531
+ if (isEdited)
1532
+ return true;
1533
+ const isKeyboardReplaced = keyboard !== undefined && await editThreadKeyboard(key, messageId, keyboard, 'questionNote');
1534
+ if (!isKeyboardReplaced)
1535
+ await editThreadKeyboard(key, messageId, null, 'questionNote');
1536
+ return false;
1477
1537
  }
1478
1538
  /**
1479
- * {@link editQuestionMessageToClosed} for a question that ended some way ({@link QuestionEnd}). The note speaks the topic's
1539
+ * {@link editQuestionMessageWithNote} for a question that ended some way ({@link QuestionEnd}). The note speaks the topic's
1480
1540
  * language whatever called it — a boot or a session teardown runs in no request, so no locale is set by one.
1481
1541
  */
1482
1542
  async function closeQuestionMessage(key, messageId, question, ending) {
1483
1543
  const note = withThreadLocale(key, () => (typeof ending === 'string' ? (0, i18n_1.t)(questionClosingNoteKeys[ending]) : (0, i18n_1.t)('agent.question_answered_note', { answer: ending.answer })));
1484
- return editQuestionMessageToClosed(key, messageId, question, note);
1544
+ return editQuestionMessageWithNote(key, messageId, question, note);
1485
1545
  }
1486
1546
  /**
1487
1547
  * @description End a question message the bot holds no record of — a copy a restart left while its re-ask was being sent, an
@@ -1613,6 +1673,7 @@ function handleApiError(key, cls, options = {}) {
1613
1673
  if (cls.kind === 'usageLimit' && !state.checkIsAutoContinueOnLimitEnabled(key)) {
1614
1674
  const isFirstOffNotice = !autoContinueOffNoticedThreads.has(k);
1615
1675
  autoContinueOffNoticedThreads.add(k);
1676
+ topicIndicator.requestRefresh(key);
1616
1677
  // Each repeat is offered to the open request: the dedup is per request, so one
1617
1678
  // opened after the first notice still hears about the limit (and is stopped).
1618
1679
  const wait = { kind: 'autoResumeOff' };
@@ -1700,6 +1761,7 @@ function armApiRetryTimer(key, arming) {
1700
1761
  // S3: the notice landed below any pending question — bring it back to the
1701
1762
  // bottom (debounced; no-op when no question is pending).
1702
1763
  onThreadActivityWhileQuestionPending(key);
1764
+ topicIndicator.requestRefresh(key);
1703
1765
  void state
1704
1766
  .setApiRetry(key, { kind: arming.kind, attempt: arming.attempt, fireAt: arming.fireAt, ...(arming.isLimitProbe ? { isLimitProbe: true } : {}), ...(arming.resumeOn ? { resumeOn: arming.resumeOn } : {}) })
1705
1767
  .catch(e => console.error('[apiRetry] persist failed:', e));
@@ -1805,7 +1867,13 @@ function holdPromptForLimitResume(key, text, heldText) {
1805
1867
  * relentlessly.
1806
1868
  */
1807
1869
  async function fireApiRetry(key) {
1808
- return withThreadLocale(key, () => (0, apiRetryKick_1.runApiRetryKick)(apiRetryKickDeps, key));
1870
+ try {
1871
+ return await withThreadLocale(key, () => (0, apiRetryKick_1.runApiRetryKick)(apiRetryKickDeps, key));
1872
+ }
1873
+ finally {
1874
+ // The wait is no longer armed (the entry stays in memory, its timer is gone): the topic is no longer stuck on it.
1875
+ topicIndicator.requestRefresh(key);
1876
+ }
1809
1877
  }
1810
1878
  /**
1811
1879
  * The ports of the retry kick (`apiRetryKick.ts`): the bot's own retry map and
@@ -1843,7 +1911,7 @@ const apiRetryKickDeps = {
1843
1911
  const from = getTopicFallbackPosition(key);
1844
1912
  if (from !== null && (0, fallbackChain_1.checkIsSameFallbackAccount)(from, rung))
1845
1913
  return false; // already there
1846
- const outcome = await switchTopicToFallbackEntry(key, from, rung, { isAnnounced: true });
1914
+ const outcome = await switchTopicToFallbackEntry(key, from, rung, { isAnnounced: true, isAutomatic: true });
1847
1915
  return outcome.isSwitched;
1848
1916
  },
1849
1917
  clearSavedRetry: clearSavedApiRetry,
@@ -1891,7 +1959,7 @@ async function announceUsageLimitOrSwitch(key, cls, episodeId, initialWait, atte
1891
1959
  }
1892
1960
  if (plan.action === 'auto') {
1893
1961
  const to = plan.to;
1894
- const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true }).catch((e) => {
1962
+ const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true, isAutomatic: true }).catch((e) => {
1895
1963
  console.warn(`[fallback] ${(0, sessionKey_1.keyToString)(key)}: the auto-switch to ${formatFallbackEntry(to)} failed:`, e instanceof Error ? e.message : e);
1896
1964
  return { isSwitched: false };
1897
1965
  });
@@ -1955,6 +2023,7 @@ async function handleBalanceExhausted(key, cls) {
1955
2023
  return;
1956
2024
  }
1957
2025
  balanceExhaustedNoticedThreads.add(k);
2026
+ topicIndicator.requestRefresh(key);
1958
2027
  const episodeId = Date.now();
1959
2028
  let plan = { action: 'none', from: position, earliest: null };
1960
2029
  try {
@@ -1965,8 +2034,9 @@ async function handleBalanceExhausted(key, cls) {
1965
2034
  }
1966
2035
  if (plan.action === 'auto') {
1967
2036
  const to = plan.to;
1968
- await replyToThread(key, notice);
1969
- const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true }).catch((e) => {
2037
+ if ((0, sessionKeyCodec_1.checkIsTelegramKey)(key))
2038
+ await replyToThread(key, notice);
2039
+ const outcome = await switchTopicToFallbackEntry(key, plan.from, to, { isAnnounced: true, isAutomatic: true }).catch((e) => {
1970
2040
  console.warn(`[fallback] ${k}: the auto-switch to ${formatFallbackEntry(to)} failed:`, e instanceof Error ? e.message : e);
1971
2041
  return { isSwitched: false };
1972
2042
  });
@@ -2093,6 +2163,7 @@ function cancelApiRetry(key) {
2093
2163
  autoContinueOffNoticedThreads.delete(k);
2094
2164
  balanceExhaustedNoticedThreads.delete(k);
2095
2165
  fallbackSwitchOffers.delete(k);
2166
+ topicIndicator.requestRefresh(key);
2096
2167
  // NOTE: intentionally does NOT touch the logged-out notice. `cancelApiRetry`
2097
2168
  // fires on EVERY inbound message (user takeover); clearing the auth notice here
2098
2169
  // would drop the one-notice guard so the user's next prompt (into the STILL
@@ -2200,6 +2271,7 @@ async function handleNoResponseWithLocale(key) {
2200
2271
  async function surfaceLoggedOutNotice(key) {
2201
2272
  const messageKey = (0, createAdapter_1.getThreadAdapterNameRaw)(key) === adapterNames_1.openCodeAdapterName ? 'apiRetry.loggedOutOpenCode' : 'apiRetry.loggedOutClaude';
2202
2273
  await (0, pinnedNoticeSlot_1.surfacePinnedNotice)(authNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key), getPinnedNoticePorts(key, (0, i18n_1.t)(messageKey)));
2274
+ topicIndicator.requestRefresh(key);
2203
2275
  }
2204
2276
  /** @description The post and the notifying pin of a pinned notice of `key`'s topic ({@link surfacePinnedNotice}). */
2205
2277
  function getPinnedNoticePorts(key, text) {
@@ -2222,6 +2294,7 @@ function clearAuthNotice(key) {
2222
2294
  const pinnedId = (0, pinnedNoticeSlot_1.releasePinnedNoticeSlot)(authNoticePinnedMessageId, (0, sessionKey_1.keyToString)(key));
2223
2295
  if (pinnedId !== null)
2224
2296
  void unpinMessageQuiet(key, pinnedId);
2297
+ topicIndicator.requestRefresh(key);
2225
2298
  }
2226
2299
  /**
2227
2300
  * @description Announce that a usage/session-limit window reset and work is moving
@@ -2592,6 +2665,10 @@ function getThreadKey(ctx) {
2592
2665
  }
2593
2666
  : undefined,
2594
2667
  };
2668
+ return getThreadKeyForRoute(routeInput);
2669
+ }
2670
+ /** @description The thread key of a route, under the instance's surface settings — for a `ctx` and for a raw update alike. */
2671
+ function getThreadKeyForRoute(routeInput) {
2595
2672
  return (0, threadRouting_1.resolveThreadKeyForMode)(routeInput, {
2596
2673
  mode: getChatMode(),
2597
2674
  ownerUserId: getOwnerUserId(),
@@ -2838,6 +2915,26 @@ async function noteServedGroupSender(ctx) {
2838
2915
  if (groupSpeaker.role === 'none' && !isTalkerNow)
2839
2916
  recentTopicWriters.noteIgnoredWriter((0, sessionKey_1.keyToString)(groupSpeaker.key), person);
2840
2917
  }
2918
+ /**
2919
+ * @description Keep the name a bound topic was created with as the candidate for its name, when an admin writes in it and the bot
2920
+ * knows no name for it yet. The topic may have been renamed since: the candidate is only offered by `/topic_status`, never applied.
2921
+ */
2922
+ async function noteTopicNameCandidate(ctx) {
2923
+ if (!ctx.message)
2924
+ return;
2925
+ const creationName = (0, inbound_1.getTopicCreationName)(ctx.message);
2926
+ if (creationName === null)
2927
+ return;
2928
+ const key = getThreadKey(ctx);
2929
+ if (!key || checkIsGeneral(key))
2930
+ return;
2931
+ const binding = state.getBinding(key);
2932
+ if (!binding || binding.topicName !== undefined || binding.topicNameCandidate === creationName)
2933
+ return;
2934
+ if (!(await checkIsAllowedUser(ctx)))
2935
+ return;
2936
+ await state.setBindingTopicNaming(key, { topicNameCandidate: creationName });
2937
+ }
2841
2938
  // ═══════════════════════════════════════════════════════════════════════════════
2842
2939
  // Send helpers — replyToThread + auto-track + error routing
2843
2940
  // ═══════════════════════════════════════════════════════════════════════════════
@@ -3077,6 +3174,75 @@ function computePinnedStatusText(key) {
3077
3174
  }
3078
3175
  return (0, pinnedStatus_1.formatPinnedStatus)({ binding, agentLabel, model, effort: effortView?.level ?? null, effortNextStart: effortView?.nextStartLevel ?? null, isActive });
3079
3176
  }
3177
+ /**
3178
+ * Conversations whose agent went wrong on its own — a crash, an error after the start, a conversation that was lost — until their
3179
+ * next turn begins: the topic's status mark says «stuck» meanwhile. In memory: a restart starts the conversation clean.
3180
+ */
3181
+ const topicsStuckUntilNextTurn = new Set();
3182
+ /**
3183
+ * @description Whether the agent of `key`'s topic cannot go on by itself: logged out, a usage-limit wait ARMED (a fired one — its entry kept in memory — is the agent going on) or its notice waiting for
3184
+ * the owner (auto-continue off, an API account used up), or a crash / lost conversation not yet followed by a turn.
3185
+ */
3186
+ function checkIsTopicStuck(key) {
3187
+ const k = (0, sessionKey_1.keyToString)(key);
3188
+ return (authNoticePinnedMessageId.has(k) ||
3189
+ getArmedApiRetry(key)?.kind === 'usageLimit' ||
3190
+ autoContinueOffNoticedThreads.has(k) ||
3191
+ balanceExhaustedNoticedThreads.has(k) ||
3192
+ topicsStuckUntilNextTurn.has(k));
3193
+ }
3194
+ /** The workers the agent of `key`'s topic watches that still run (`checkIsWatchedWorkerRunning`). */
3195
+ function getWatchedWorkerCount(key) {
3196
+ return state.getThreadSchedules(key).filter(topicIndicatorSources_1.checkIsWatchedWorkerRunning).length;
3197
+ }
3198
+ /** The adapter names a topic held that no adapter answers to, told once each. */
3199
+ const unknownTopicAdapterNamesLogged = new Set();
3200
+ /**
3201
+ * @description Read the agent of `key`'s topic once: `null` for a topic with no agent states — a terminal topic, one that never started an
3202
+ * agent. A name no adapter answers to (a stale binding) is a topic with an agent that is not up, said once in the log.
3203
+ */
3204
+ function readTopicAgent(key) {
3205
+ const adapterName = (0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name;
3206
+ if (adapterName === undefined || adapterName === adapterNames_1.terminalAdapterName)
3207
+ return null;
3208
+ if (!(0, createAdapter_1.getKnownAdapterNames)().includes(adapterName)) {
3209
+ if (!unknownTopicAdapterNamesLogged.has(adapterName)) {
3210
+ unknownTopicAdapterNamesLogged.add(adapterName);
3211
+ console.warn(`[topic-indicator] ${(0, sessionKey_1.keyToString)(key)}: the topic holds the backend "${adapterName}", which no adapter answers to — no agent states for it`);
3212
+ }
3213
+ return { adapterName, isActive: false, isTurnRunning: false };
3214
+ }
3215
+ const adapter = (0, createAdapter_1.getAdapter)(adapterName);
3216
+ const isActive = adapter.checkIsActive(key);
3217
+ return { adapterName, isActive, isTurnRunning: isActive && (adapter.checkIsWorking ? adapter.checkIsWorking(key) : adapter.checkIsBusy?.(key) === true) };
3218
+ }
3219
+ /**
3220
+ * @description The facts the status mark of `key`'s topic name is chosen from (`utils/topicIndicatorPlan.ts`), read live: an open question
3221
+ * (waiting or set aside), a stuck agent, a turn or a watched worker at work, a process that is up and idle (finished) or stopped with the
3222
+ * conversation kept (asleep; for the per-turn backend, whose process stops after every turn, finished). The rules are `getTopicStatusInputs`.
3223
+ */
3224
+ function getTopicIndicatorInputs(key) {
3225
+ const k = (0, sessionKey_1.keyToString)(key);
3226
+ const agent = readTopicAgent(key);
3227
+ return (0, topicIndicatorSources_1.getTopicStatusInputs)({
3228
+ hasAgent: agent !== null,
3229
+ isActive: agent?.isActive ?? false,
3230
+ isTurnRunning: agent?.isTurnRunning ?? false,
3231
+ isPerTurnBackend: agent?.adapterName === adapterNames_1.claudePerTurnAdapterName,
3232
+ watchedWorkerCount: getWatchedWorkerCount(key),
3233
+ hasOpenQuestion: pendingQuestions.has(k) || (state.getSetAsideQuestions()[k]?.length ?? 0) > 0,
3234
+ isStuck: checkIsTopicStuck(key),
3235
+ hasResumableSession: getResumableSessionId(key) !== null,
3236
+ });
3237
+ }
3238
+ /** The agents at work in `key`'s topic: its own while it works, plus each worker it watches. */
3239
+ function getTopicIndicatorAgentsCount(key) {
3240
+ return (readTopicAgent(key)?.isTurnRunning ? 1 : 0) + getWatchedWorkerCount(key);
3241
+ }
3242
+ /** The tasks the topic's agent published as queued (`todo_update`); `inWork` ones are being done and show as working. */
3243
+ function getTopicIndicatorQueuedCount(key) {
3244
+ return getTodoRegistry().getTopic(key).items.filter((item) => item.status === 'queued').length;
3245
+ }
3080
3246
  /**
3081
3247
  * @description Send-or-edit the pinned status banner for a thread.
3082
3248
  *
@@ -3096,6 +3262,8 @@ async function updatePinnedStatus(key) {
3096
3262
  return;
3097
3263
  if (!shouldHavePinnedStatus(key))
3098
3264
  return;
3265
+ // The banner is refreshed at every start, stop, suspension and close of the topic's agent: the same moments its name's mark changes.
3266
+ topicIndicator.requestRefresh(key);
3099
3267
  // Audit S6 / #8: serialise all banner work for a key — without this,
3100
3268
  // two near-simultaneous adapter events could both observe a missing
3101
3269
  // `pinnedStatusMessageId` and stack duplicate pins. Errors from one
@@ -4377,6 +4545,16 @@ async function releaseThreadSession(key) {
4377
4545
  async function releaseConversationIds(key) {
4378
4546
  await state.clearAgentSessionIds(key);
4379
4547
  clearThreadCompaction(key);
4548
+ closeSetAsideQuestionsInBackground(key);
4549
+ }
4550
+ /**
4551
+ * @description The conversation ended or was replaced (released for good, another conversation or backend picked): every question
4552
+ * the bot had set aside for it ends as «not answered», its pin released — its buttons would send an answer into a conversation that
4553
+ * is not the one that asked. NOT the idle stop, the sleep or a crash: the conversation is still there, and a late answer wakes it.
4554
+ * Not awaited (the edits go through the send pacer); a failure is logged.
4555
+ */
4556
+ function closeSetAsideQuestionsInBackground(key) {
4557
+ closeSetAsideQuestions(key).catch((e) => console.error('[questionSetAside] closing the set-aside questions failed:', e));
4380
4558
  }
4381
4559
  /**
4382
4560
  * @description Switch a thread's adapter and clear the previous adapter's
@@ -4395,7 +4573,7 @@ async function releaseConversationIds(key) {
4395
4573
  * Resolves the work the stop cut off that the agent's next prompt is told about (`null`: none), so a caller's line to
4396
4574
  * the operator is derived from the very record the note lists.
4397
4575
  */
4398
- async function switchThreadAdapter(key, newName) {
4576
+ async function switchThreadAdapter(key, newName, options = {}) {
4399
4577
  const prevName = (0, createAdapter_1.getThreadAdapterNameRaw)(key);
4400
4578
  // Another agent or a shell takes the topic over: the open request belonged to
4401
4579
  // the old conversation, so it closes silently instead of a later wake-up
@@ -4404,6 +4582,10 @@ async function switchThreadAdapter(key, newName) {
4404
4582
  cancelConversationRequest(key);
4405
4583
  // Nor does the conversation left behind get its re-asked question answered: its buttons would send the label into the new one.
4406
4584
  closeReAskedQuestion(key);
4585
+ // The same for the questions it had set aside — unless the bot moved the conversation itself (an automatic usage-limit
4586
+ // fallback): it parks the conversation and bridges its context, so a late answer goes to the one now running.
4587
+ if (options.isConversationKept !== true)
4588
+ closeSetAsideQuestionsInBackground(key);
4407
4589
  }
4408
4590
  let switchCutOffWork = null;
4409
4591
  if (prevName && prevName !== newName) {
@@ -4932,6 +5114,7 @@ const autoStopUnsupportedLoggedKeys = new Set();
4932
5114
  */
4933
5115
  function handleAgentTurnEnded(key) {
4934
5116
  noteThreadActivity(key);
5117
+ topicIndicator.requestRefresh(key);
4935
5118
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
4936
5119
  if (adapter.name !== adapterNames_1.claudePerTurnAdapterName)
4937
5120
  return;
@@ -5013,6 +5196,9 @@ async function replayBufferedPrompts(key) {
5013
5196
  * for an adopt replay can come out as anything but `forwarded`; most callers have no use for the answer.
5014
5197
  */
5015
5198
  async function forwardPromptToAgent(key, adapter, text, sentAtMs, options = {}) {
5199
+ // The next turn begins: an agent that went wrong is no longer stuck (`checkIsTopicStuck`), and its name follows.
5200
+ if (topicsStuckUntilNextTurn.delete((0, sessionKey_1.keyToString)(key)))
5201
+ topicIndicator.requestRefresh(key);
5016
5202
  // An adopted session replays what its process wrote during the downtime first: a prompt written meanwhile would reset
5017
5203
  // the answer and error state those frames still use, and the replayed text would join the new reply's message (the
5018
5204
  // «new message» mark would go to the replayed text). Nothing is awaited when no replay is pending: the forward then runs
@@ -5388,6 +5574,8 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
5388
5574
  pendingQuestions,
5389
5575
  clearPendingQuestion,
5390
5576
  closeQuestionMessage,
5577
+ // The module that sets questions aside is built just below (it needs nothing from this one): the idle fire reaches it through this.
5578
+ setQuestionAsideAtIdle: (key) => setPendingQuestionAsideAtIdle(key),
5391
5579
  idleWindowMs: (0, compactOnIdle_1.getAgentIdleMs)(process.env.AGENT_IDLE_MINUTES),
5392
5580
  checkIsLimitWaitArmed: (key) => getArmedApiRetry(key)?.kind === 'usageLimit',
5393
5581
  suspendThreadSession,
@@ -5403,6 +5591,29 @@ const { checkIsThreadCompacting, noteThreadActivity, noteThreadUserActivity, mar
5403
5591
  notePersonActivity,
5404
5592
  compactSelfReviewFlagDirs: (0, compactSelfReviewFlags_1.getCompactSelfReviewFlagDirs)((0, state_1.resolveDataDir)(), (0, openCodeCompactPlugin_1.resolveOpenCodeGlobalPluginDir)(process.env)),
5405
5593
  });
5594
+ /** The instance's question wait, re-read from `settings.json` when the file changes (`null`: not set, the default applies). */
5595
+ const readInstanceQuestionWait = (0, instanceSettings_1.createQuestionWaitSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
5596
+ const { armQuestionSetAsideTimer, clearQuestionSetAsideTimer, setPendingQuestionAsideAtIdle, answerQuestionAskedAgain, checkIsSetAsideQuestionMessage, answerLiveTapOnSetAsideQuestion, registerQuestionSetAsideCallbacks, answerSetAsideQuestionByReply, closeSetAsideQuestions, } = (0, questionSetAside_1.createQuestionSetAside)({
5597
+ ...botCore,
5598
+ pendingQuestions,
5599
+ getThreadAdapter: createAdapter_1.getThreadAdapter,
5600
+ runQuestionLifecycleOp,
5601
+ setPendingQuestion,
5602
+ clearPendingQuestion,
5603
+ releasePendingQuestionToSetAside: (key) => dropPendingQuestion(key, { isPinKept: true }),
5604
+ editQuestionMessageWithNote,
5605
+ closeQuestionMessage,
5606
+ unpinMessage: unpinMessageQuiet,
5607
+ pinMessageSilently: (key, messageId) => pinMessageQuiet(key, messageId, { disableNotification: true }),
5608
+ sendQuestionMessage,
5609
+ deliverLateAnswer: (key, text) => withThreadLocale(key, () => deliverLateAnswerPrompt(key, text)),
5610
+ markNeedsNewMessage,
5611
+ // The topic's own choice (`/question_wait`), else the instance value `settings.json` holds (`questionWait`), else the default.
5612
+ getQuestionWaitChoice: (key) => (0, questionWaitPlan_1.resolveQuestionWait)(state.getQuestionWaitOverride(key), readInstanceQuestionWait() ?? undefined),
5613
+ shortenedWaitMs: ENV.testTimings.questionSetAsideWaitMs,
5614
+ retryDelayMs: ENV.testTimings.questionSetAsideRetryMs,
5615
+ postQuestionAnew: postAgentQuestion,
5616
+ });
5406
5617
  /**
5407
5618
  * @description True iff the neutral router owns `name`, i.e. a `/name` message
5408
5619
  * is claimed by the routed-command trigger instead of falling through.
@@ -6119,6 +6330,9 @@ async function unbindThread(key) {
6119
6330
  // the next /bind resumes them. `removeBinding` only touches bindings/agents/
6120
6331
  // messages — schedules are their own collection and survive (S8).
6121
6332
  await pauseThreadSchedulesOnUnbind(key).catch((e) => console.warn(`[scheduler] pause-on-unbind failed for ${kStr}:`, e));
6333
+ // The topic leaves the status marks: the owner's own name goes back while the binding still knows it.
6334
+ await topicIndicator.restoreBaseName(key);
6335
+ topicIndicator.forgetTopic(key);
6122
6336
  await state.removeBinding(key);
6123
6337
  clearInMemoryThreadState(key);
6124
6338
  await replyToThread(key, (0, i18n_1.t)('thread.unbound'));
@@ -6913,6 +7127,57 @@ const { registerBotSkillsCommands, registerBotSkillsCallbacks } = (0, botSkills_
6913
7127
  checkIsOpenCodeTopic: (key) => ((0, createAdapter_1.getThreadAdapterNameRaw)(key) ?? state.getAgent(key)?.name) === adapterNames_1.openCodeAdapterName,
6914
7128
  });
6915
7129
  registerBotSkillsCommands();
7130
+ // ── The question wait (`/question_wait`): `connectors/telegram/commands/questionWait.ts`, `utils/questionWaitPlan.ts` ──
7131
+ const { registerQuestionWaitCommands, registerQuestionWaitCallbacks } = (0, questionWait_1.createQuestionWait)({
7132
+ ...botCore,
7133
+ readInstanceQuestionWait,
7134
+ getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
7135
+ // A changed wait applies to the questions that wait now too: their timers are set again, counted from the moment each was asked.
7136
+ noteQuestionWaitChanged: (key) => rearmQuestionSetAsideTimers(key),
7137
+ });
7138
+ registerQuestionWaitCommands();
7139
+ // ── The status mark at the end of a topic's name: `connectors/telegram/topicIndicator.ts`, `utils/topicIndicatorPlan.ts` ──
7140
+ const readInstanceTopicStatus = (0, instanceSettings_1.createTopicStatusSettingsReader)(() => (0, instanceSettings_1.getInstanceSettingsPath)(), (line) => console.error(line));
7141
+ const topicIndicator = (0, topicIndicator_1.createTopicIndicator)({
7142
+ getState: () => state,
7143
+ checkIsMarkableTopic: (key) => (0, sessionKeyCodec_1.checkIsTelegramKey)(key) && !checkIsGeneral(key),
7144
+ checkIsUnbinding: (key) => unbindingKeys.has((0, sessionKey_1.keyToString)(key)),
7145
+ getPrefs: (key) => (0, topicIndicatorPlan_1.resolveTopicStatusPrefs)(readInstanceTopicStatus(), state.getTopicStatusOverride(key)),
7146
+ getStatusInputs: getTopicIndicatorInputs,
7147
+ getAgentsCount: getTopicIndicatorAgentsCount,
7148
+ getQueuedCount: getTopicIndicatorQueuedCount,
7149
+ // The NAME alone: the topic's icon is the owner's and never travels with a rename.
7150
+ sendTopicName: async (key, name) => {
7151
+ await (0, rateLimiter_1.enqueueSend)(key, () => bot.telegram.editForumTopic((0, sessionKeyCodec_1.getTelegramChatId)(key), (0, sessionKeyCodec_1.getTelegramThreadId)(key), { name }));
7152
+ },
7153
+ deleteMessage: async (key, messageId) => {
7154
+ await (0, rateLimiter_1.enqueueSend)(key, () => bot.telegram.deleteMessage((0, sessionKeyCodec_1.getTelegramChatId)(key), messageId));
7155
+ },
7156
+ checkIsBacklogHandled: () => firstUpdateBatch.checkIsBacklogHandled(updateDispatcher.size()),
7157
+ windows: {
7158
+ settleMs: ENV.testTimings.topicIndicatorSettleMs ?? topicIndicatorPlan_1.indicatorSettleMs,
7159
+ minGapMs: ENV.testTimings.topicIndicatorMinRenameGapMs ?? topicIndicatorPlan_1.indicatorMinRenameGapMs,
7160
+ sweepIntervalMs: ENV.testTimings.topicIndicatorSweepMs ?? topicIndicatorPlan_1.indicatorSweepIntervalMs,
7161
+ bootWaveDelayMs: ENV.testTimings.topicIndicatorBootWaveDelayMs ?? topicIndicatorPlan_1.indicatorBootWaveDelayMs,
7162
+ },
7163
+ getNowMs: Date.now,
7164
+ setTimer: (callback, delayMs) => {
7165
+ const timer = setTimeout(callback, delayMs);
7166
+ timer.unref();
7167
+ return { cancel: () => clearTimeout(timer) };
7168
+ },
7169
+ log: (line) => console.warn(line),
7170
+ });
7171
+ // ── `/topic_status`: `connectors/telegram/commands/topicStatus.ts`, `utils/topicStatusPlan.ts` — the switches of those marks ──
7172
+ const { registerTopicStatusCommands, registerTopicStatusCallbacks } = (0, topicStatus_1.createTopicStatus)({
7173
+ ...botCore,
7174
+ readInstanceTopicStatus,
7175
+ getSettingsPath: () => (0, instanceSettings_1.getInstanceSettingsPath)(),
7176
+ getHealth: (key) => topicIndicator.getHealth(key),
7177
+ // The change is the owner's own: it skips the settle time and the gap, like the edges of ❓.
7178
+ noteTopicStatusChanged: (key) => (key === null ? topicIndicator.refreshAll({ isOwnerChange: true }) : topicIndicator.requestRefresh(key, { isOwnerChange: true })),
7179
+ });
7180
+ registerTopicStatusCommands();
6916
7181
  // ── Who may talk to the agent in a topic (`/access`): `connectors/telegram/commands/topicAccess.ts`, `topicTalkers.ts` ──
6917
7182
  const { registerTopicAccessCommands, registerTopicAccessCallbacks } = (0, topicAccess_1.createTopicAccess)({
6918
7183
  ...botCore,
@@ -6965,9 +7230,20 @@ const { registerRunnersCommands, registerRunnersCallbacks, handleRunnersAddressT
6965
7230
  });
6966
7231
  registerRunnersCommands();
6967
7232
  // ── Claude account profiles (`/account`): `utils/claudeProfiles.ts`, `commands/claudeAccounts.ts` ──
7233
+ /**
7234
+ * @description Put a profile folder's layout right before a process starts under it (`repairClaudeProfileFolderForLaunch`): the entries
7235
+ * Claude Code loads as user-level configuration are links into `~/.claude` again, and whatever an agent on the account planted in their
7236
+ * place is moved aside. Every launch site calls it — the conversation spawns (`resolveThreadClaudeConfigDir`: json-stream, per-turn and
7237
+ * tmux, start, resume and account switch), the `claude auth` probes (`readClaudeAuthStatusUnder`), the sign-in (the layout call of
7238
+ * `/accounts`) and the account a worker is pointed at (`listClaudeProfilesForAgent`, `charness claude-profiles`). Never throws.
7239
+ */
7240
+ function repairClaudeProfileFolder(configDir) {
7241
+ (0, claudeProfiles_1.repairClaudeProfileFolderForLaunch)({ dataDir: (0, state_1.resolveDataDir)(), configDir });
7242
+ }
6968
7243
  /**
6969
7244
  * @description The Claude config directory a conversation's NEXT process starts with: its resolved account
6970
- * profile's directory, `null` for the default profile. Registered as the adapters' reader at boot. A profile
7245
+ * profile's directory, `null` for the default profile. Registered as the adapters' reader at boot, and read by
7246
+ * every spawn, so the folder is repaired here ({@link repairClaudeProfileFolder}). A profile
6971
7247
  * whose directory vanished (a hand-cleaned `DATA_DIR`) runs on the default rather than failing the spawn.
6972
7248
  */
6973
7249
  function resolveThreadClaudeConfigDir(key) {
@@ -6977,6 +7253,7 @@ function resolveThreadClaudeConfigDir(key) {
6977
7253
  console.warn(`[account] ${(0, sessionKey_1.keyToString)(key)}: the directory of profile ${name} is missing; its process runs on the default profile`);
6978
7254
  return null;
6979
7255
  }
7256
+ repairClaudeProfileFolder(dir);
6980
7257
  return dir;
6981
7258
  }
6982
7259
  /**
@@ -6985,6 +7262,8 @@ function resolveThreadClaudeConfigDir(key) {
6985
7262
  * the probe fails.
6986
7263
  */
6987
7264
  async function readClaudeAuthStatusUnder(configDir) {
7265
+ // The probe loads the folder's settings (an `apiKeyHelper` there is a command): the layout is put right first.
7266
+ repairClaudeProfileFolder(configDir);
6988
7267
  const env = (0, claudeProfiles_1.getClaudeAuthCommandEnvironment)(configDir);
6989
7268
  try {
6990
7269
  const args = [...(0, claudeApiKeyHelper_1.buildClaudeAuthProbeSettingsArgs)(configDir), 'auth', 'status', '--json'];
@@ -7050,12 +7329,31 @@ const openCodeUsagePoller = (0, openCodeUsage_1.createOpenCodeUsagePoller)({
7050
7329
  getRecord: (providerId) => state.getOpenCodeProviderUsage(providerId),
7051
7330
  saveRecord: (providerId, record) => state.setOpenCodeProviderUsage(providerId, record),
7052
7331
  });
7332
+ /**
7333
+ * The registry of Claude profiles kept in step with the disk and the CLI, with no Telegram in the way (`utils/claudeProfileSync.ts`):
7334
+ * a profile folder under `DATA_DIR/claude-profiles/` signed in by hand is adopted, every profile's sign-in status is probed when it
7335
+ * is due. The usage poll below runs it first, so an instance that serves only a tracker sees every account; `/accounts` forces it.
7336
+ * `state` is assigned at boot, so the store reads it at each call.
7337
+ */
7338
+ const claudeProfileSync = (0, claudeProfileSync_1.createClaudeProfileSync)({
7339
+ store: {
7340
+ getClaudeProfileRecords: () => state.getClaudeProfileRecords(),
7341
+ getClaudeProfileRecord: (name) => state.getClaudeProfileRecord(name),
7342
+ getClaudeProfileInfo: (name) => state.getClaudeProfileInfo(name),
7343
+ upsertClaudeProfileRecord: (name, patch) => state.upsertClaudeProfileRecord(name, patch),
7344
+ },
7345
+ getDataDir: () => (0, state_1.resolveDataDir)(),
7346
+ readStatus: readClaudeAuthStatusUnder,
7347
+ // A folder made by hand may lack the links into `~/.claude` (the transcripts above all): the one idempotent layout call adds them.
7348
+ ensureLayout: (name) => { (0, claudeProfiles_1.createClaudeProfileLayout)({ dataDir: (0, state_1.resolveDataDir)(), name }); },
7349
+ });
7053
7350
  /**
7054
7351
  * The per-profile usage cache (`utils/claudeUsageRefresher.ts`): every signed-in profile's windows off the
7055
7352
  * OAuth usage endpoint on a 10-minute timer, on `/account` open and on a `claude_profiles` call, plus the
7056
7353
  * `rate_limit_event` frames the json-stream sessions report. Snapshots live on the profile records.
7057
7354
  */
7058
7355
  const claudeUsageRefresher = (0, claudeUsageRefresher_1.createClaudeUsageRefresher)({
7356
+ syncProfiles: () => claudeProfileSync.sync(),
7059
7357
  listProfiles: () => [
7060
7358
  {
7061
7359
  name: claudeProfiles_1.defaultClaudeProfileName, configDir: null,
@@ -7335,12 +7633,18 @@ function notePersonActivity(key) {
7335
7633
  * blind delay; an OpenCode model: else the blind delay), the usage snapshots are brought up to date, and the
7336
7634
  * chain's AVAILABLE rungs are listed in priority order. Without a configured chain a Claude topic falls back to
7337
7635
  * the within-Claude ranking by the soonest weekly reset (`utils/claudeLimitSwitch.ts`) — the behaviour before the chain existed. An
7338
- * offer is remembered per thread under its episode so only ITS buttons can act on it. `none` for a non-Telegram
7339
- * conversation, a topic with no account to switch from, or when no rung can take over.
7636
+ * offer is remembered per thread under its episode so only ITS buttons can act on it. `none` for a topic with no account to
7637
+ * switch from, or when no rung can take over.
7638
+ *
7639
+ * A conversation of another platform (a Jira issue) takes the AUTOMATIC move only, and only between Claude accounts: the chain's
7640
+ * Claude rungs when it has any (else the ranking), never an OpenCode rung (a cross-backend hand-over has no surface there). The
7641
+ * offer's buttons and the wait aimed at the rung that resets first (the retry kick moves a topic there only for Telegram) are
7642
+ * Telegram's: with auto-switch OFF, with no account free, or on OpenCode such a conversation waits for the reset as it always did.
7340
7643
  */
7341
7644
  async function planFallbackSwitch(key, cls, episodeId) {
7342
7645
  const from = getTopicFallbackPosition(key);
7343
- if (!(0, sessionKeyCodec_1.checkIsTelegramKey)(key) || from === null)
7646
+ const isTelegram = (0, sessionKeyCodec_1.checkIsTelegramKey)(key);
7647
+ if (from === null || !(0, limitSwitchPlan_1.checkIsLimitSwitchPossible)(isTelegram, from))
7344
7648
  return { action: 'none', from, earliest: null };
7345
7649
  const k = (0, sessionKey_1.keyToString)(key);
7346
7650
  const nowMs = Date.now();
@@ -7369,29 +7673,23 @@ async function planFallbackSwitch(key, cls, episodeId) {
7369
7673
  // a stuck usage endpoint must never hold the switch or the wait notice of a topic that just hit its limit.
7370
7674
  await (0, usageRefreshBudget_1.refreshUsageWithinBudget)((options) => claudeUsageRefresher.refreshAll(options));
7371
7675
  const detection = await detectFallbackOptions();
7372
- let chain = state.getFallbackChain();
7373
- if (chain.length === 0 && from.backend === 'claude') {
7374
- chain = (0, claudeLimitSwitch_1.pickClaudeLimitSwitchCandidates)({ profiles: detection.claudeProfiles, currentName: from.profile, model: from.model, nowMs: Date.now() })
7375
- .map((profile) => ({ backend: 'claude', profile, model: null }));
7376
- }
7377
- const candidates = (0, fallbackChain_1.pickFallbackCandidates)({ chain, current: from, detection, nowMs: Date.now() });
7378
- const plan = (0, fallbackChain_1.decideFallbackSwitch)({ candidates, isAutoSwitchEnabled: state.checkIsClaudeAutoSwitchOnLimitEnabled(key) });
7676
+ const { plan, waitRungs } = (0, limitSwitchPlan_1.decideLimitSwitch)({
7677
+ isTelegram,
7678
+ from,
7679
+ chain: state.getFallbackChain(),
7680
+ detection,
7681
+ isAutoSwitchEnabled: state.checkIsClaudeAutoSwitchOnLimitEnabled(key),
7682
+ nowMs: Date.now(),
7683
+ });
7379
7684
  if (plan.action === 'offer')
7380
7685
  fallbackSwitchOffers.set(k, { episodeId, from, candidates: plan.candidates });
7381
7686
  else
7382
7687
  fallbackSwitchOffers.delete(k);
7383
7688
  const detail = plan.action === 'auto' ? ` → ${formatFallbackEntry(plan.to)}` : plan.action === 'offer' ? ` [${plan.candidates.map(formatFallbackEntry).join(', ')}]` : '';
7384
- // Nothing has room: the wait should end on the rung whose limit resets EARLIEST, not necessarily this one.
7689
+ // Nothing has room: the wait should end on the rung whose limit resets EARLIEST, not necessarily this one (a topic's wait only).
7385
7690
  let earliest = null;
7386
- if (plan.action === 'none') {
7387
- const explicit = state.getFallbackChain();
7388
- // Without a chain the implicit one is the signed-in SUBSCRIPTIONS: an account billed to API credits never ends a wait by itself.
7389
- const rungs = explicit.length > 0 ? explicit : from.backend === 'claude'
7390
- ? detection.claudeProfiles
7391
- .filter((profile) => profile.loggedIn !== false && profile.billing !== 'api')
7392
- .map((profile) => ({ backend: 'claude', profile: profile.name, model: null }))
7393
- : [];
7394
- const found = (0, fallbackChain_1.pickEarliestResetRung)({ chain: rungs, current: from, detection, nowMs: Date.now() });
7691
+ if (waitRungs.length > 0) {
7692
+ const found = (0, fallbackChain_1.pickEarliestResetRung)({ chain: waitRungs, current: from, detection, nowMs: Date.now() });
7395
7693
  if (found && !found.isCurrent)
7396
7694
  earliest = { entry: found.entry, untilMs: found.untilMs };
7397
7695
  }
@@ -7516,8 +7814,10 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
7516
7814
  // An OpenCode topic on the server's default model has no rung (`from` is null), yet it is on OpenCode all the same.
7517
7815
  const isSameFamily = (from?.backend ?? getTopicBackendFamily(key)) === to.backend;
7518
7816
  const runningModel = readRunningModelBeforeMove(key, from, to);
7817
+ // The notice is a topic message: a conversation of another platform (a Jira issue) hears nothing — the log line below says it — and
7818
+ // its work simply continues.
7519
7819
  const say = async (notice) => {
7520
- if (options.isAnnounced)
7820
+ if (options.isAnnounced && (0, sessionKeyCodec_1.checkIsTelegramKey)(key))
7521
7821
  await replyToThread(key, notice);
7522
7822
  };
7523
7823
  const fail = async (error) => {
@@ -7564,7 +7864,8 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
7564
7864
  reason: 'limit',
7565
7865
  resetsAtText: getFallbackResetTime(from),
7566
7866
  });
7567
- isStoppingBackground = await moveTopicToOtherBackend(key, to.backend, to.backend === 'claude' ? to.profile : null);
7867
+ // An automatic fallback keeps the conversation (parked, bridged): the questions it had set aside stay open for a late answer.
7868
+ isStoppingBackground = await moveTopicToOtherBackend(key, to.backend, to.backend === 'claude' ? to.profile : null, { isConversationKept: options.isAutomatic === true });
7568
7869
  if (to.backend === 'opencode') {
7569
7870
  const error = await (0, createAdapter_1.getThreadAdapter)(key).setModel?.(key, (0, fallbackChain_1.buildOpenCodeModelLabel)(to));
7570
7871
  if (error)
@@ -7606,10 +7907,10 @@ async function switchTopicToFallbackEntry(key, from, to, options) {
7606
7907
  * the adapter being left still runs. Resolves whether the stop took background work with it — the caller tells the
7607
7908
  * operator (the agent is told by the next prompt, `switchThreadAdapter`).
7608
7909
  */
7609
- async function moveTopicToOtherBackend(key, backend, account) {
7910
+ async function moveTopicToOtherBackend(key, backend, account, options = {}) {
7610
7911
  if (account !== null)
7611
7912
  await state.setClaudeProfileOverride(key, account);
7612
- return (0, lostWork_1.checkHasLostBackgroundWork)(await switchThreadAdapter(key, backend === 'claude' ? (0, createAdapter_1.resolveClaudeBackendName)(key) : adapterNames_1.openCodeAdapterName));
7913
+ return (0, lostWork_1.checkHasLostBackgroundWork)(await switchThreadAdapter(key, backend === 'claude' ? (0, createAdapter_1.resolveClaudeBackendName)(key) : adapterNames_1.openCodeAdapterName, options));
7613
7914
  }
7614
7915
  /**
7615
7916
  * @description The second half, after a move (across backends or between accounts): start or resume the topic's
@@ -7836,6 +8137,9 @@ async function takeFallbackSwitchOffer(key, episodeId, index) {
7836
8137
  * dropped by its own client after 300 s).
7837
8138
  */
7838
8139
  async function listClaudeProfilesForAgent(query) {
8140
+ // The agent launches its worker under whichever folder the answer names, so every folder is put right before it is named.
8141
+ for (const view of getClaudeProfileUsageViews())
8142
+ repairClaudeProfileFolder(view.configDir);
7839
8143
  const stoppedApiProfile = (0, claudeApiAgentStop_1.getApiProfileStoppedByAgent)(getClaudeProfileUsageViews(), query, Date.now());
7840
8144
  await Promise.all([
7841
8145
  (0, claudeUsageRefresher_1.refreshClaudeUsageForLaunch)(claudeUsageRefresher, { currentProfile: query.currentProfile, isStoppedByLimit: query.isStoppedByLimit, maxAgeMs: claudeUsageRefresher_1.claudeUsageOnDemandMaxAgeMs }),
@@ -7881,6 +8185,7 @@ const { registerClaudeAccountCommands, registerClaudeAccountCallbacks, checkIsAw
7881
8185
  getDataDir: state_1.resolveDataDir,
7882
8186
  getInstanceTimezone: getCurrentTimezone,
7883
8187
  refreshClaudeUsage: (options) => claudeUsageRefresher.refreshAll(options),
8188
+ syncClaudeProfiles: (options) => claudeProfileSync.sync(options),
7884
8189
  readClaudeAuthStatus: readClaudeAuthStatusUnder,
7885
8190
  startClaudeProfileLogin: (key, profile) => startClaudeAuthLogin(key, profile),
7886
8191
  applyClaudeProfile: applyClaudePickToThread,
@@ -8046,6 +8351,7 @@ async function resumeSessionByIndex(key, idx, onExpired) {
8046
8351
  // for the conversation it replaces would send its label into the picked one.
8047
8352
  cancelConversationRequest(key);
8048
8353
  closeReAskedQuestion(key);
8354
+ closeSetAsideQuestionsInBackground(key);
8049
8355
  // Persist the PICKED id — without this the next restart re-attaches to
8050
8356
  // whatever id the last fresh start wrote, silently dropping the user's
8051
8357
  // pick (live incident 2026-06-10).
@@ -8541,7 +8847,7 @@ const botCommands = new Set([
8541
8847
  'start', 'claude', 'opencode', 'oc', 'terminal', 'agent', 'sessions', 'resume', 'cancel', 'model', 'connect',
8542
8848
  'disconnect', 'stop', 'stopall', 'stop-all', 'quit-all', 'status', 'c', 'y', 'n', 'enter', 'up', 'down', 'tab', 'esc', 'escape', 'interrupt', 'output', 'clear_messages',
8543
8849
  'bind', 'topic', 'unbind', 'where', 'ls', 'list', 'new', 'whoami', 'version', 'help', 'language', 'lang',
8544
- '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',
8850
+ 'doctor', 'mcp', 'rename_session', 'compact', 'compact_on_idle', 'compact_summary', 'compact_self_review', 'bot_skills', 'question_wait', 'topic_status', 'task_agents', 'runners', 'auto_continue_limits', 'limits', 'limits_autoswitch', 'trace', 'timestamps', 'timezone', 'schedule', 'reminders', 'todo', 'thinking', 'tool_results',
8545
8851
  'subagent', 'claude_mode', 'effort', 'verbosity', 'quit', 'q', 'quitall', 'pair', 'account', 'accounts', 'fallback', 'stt', 'voice', 'speech', 'update', 'access',
8546
8852
  ]);
8547
8853
  /**
@@ -8598,12 +8904,12 @@ async function handleTalkerText(ctx, key) {
8598
8904
  return;
8599
8905
  }
8600
8906
  if (adapter.checkIsActive(key)) {
8601
- await deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext);
8907
+ await deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext, { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
8602
8908
  return;
8603
8909
  }
8604
8910
  // A sleeping conversation is resumed by the message itself, as for anybody (L-D4).
8605
8911
  if (await resumeSleepingSessionForPrompt(key)) {
8606
- await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, intake, sentAtMs, messageContext);
8912
+ await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, intake, sentAtMs, messageContext, { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
8607
8913
  return;
8608
8914
  }
8609
8915
  await replyToThread(key, (0, i18n_1.t)('access.noAgentForTalkerNotice'));
@@ -8623,6 +8929,10 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
8623
8929
  if (!speaker)
8624
8930
  return;
8625
8931
  const { key } = speaker;
8932
+ // A REPLY to a question the bot set aside is its late answer — from the operator and from a topic member alike. It is not a prompt:
8933
+ // it cancels no question that waits now, and reaches the agent as the late-answer message.
8934
+ if (await answerSetAsideQuestionByReply(ctx.from, key, { message_id: ctx.message.message_id, text: ctx.message.text, replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message), isForwarded: (0, inbound_1.checkIsTelegramForward)(ctx.message) }, speaker.role))
8935
+ return;
8626
8936
  if (speaker.role === 'talker') {
8627
8937
  await handleTalkerText(ctx, key);
8628
8938
  return;
@@ -8941,13 +9251,13 @@ bot.on((0, filters_1.message)('text'), async (ctx) => {
8941
9251
  // REPLY or FORWARD folds its context into the prompt (see `getMessageContext`).
8942
9252
  if (adapter.checkIsActive(key)) {
8943
9253
  const messageContext = getMessageContext(key, ctx.message);
8944
- await deliverActivePrompt(key, adapter, text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, messageContext);
9254
+ await deliverActivePrompt(key, adapter, text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, messageContext, { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
8945
9255
  return;
8946
9256
  }
8947
9257
  // A sleeping conversation (its process stopped, its session kept) is resumed by
8948
9258
  // the message itself (L-D4) — the prompt continues the same conversation.
8949
9259
  if (await resumeSleepingSessionForPrompt(key)) {
8950
- await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, getMessageContext(key, ctx.message));
9260
+ await deliverActivePrompt(key, (0, createAdapter_1.getThreadAdapter)(key), text, { source: 'text', requesterId: (0, topicRequest_1.getTopicRequesterId)(ctx.from) }, ctx.message.date * 1000, getMessageContext(key, ctx.message), { replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) });
8951
9261
  return;
8952
9262
  }
8953
9263
  // Idle thread — guide the user. Three sub-states:
@@ -9010,8 +9320,10 @@ bot.on((0, filters_1.message)('voice'), async (ctx) => {
9010
9320
  // clock runs from the voice's arrival, so a voice waiting in line behind an earlier one gets its note too; the job finishes it
9011
9321
  // the moment its text arrives, and the `finally` is the backstop for a job that never ran or ended some other way.
9012
9322
  const progressNote = startVoiceProgressNote(key);
9323
+ // What the job needs to treat the transcript as a LATE ANSWER when the voice note is a reply to a set-aside question's message.
9324
+ const reply = { from: ctx.from, role: speaker.role, messageId: ctx.message.message_id, replyToMessageId: (0, inbound_1.getTelegramReplyTargetId)(ctx.message) };
9013
9325
  void (0, voiceQueue_1.getVoiceTranscriptionQueue)(key)
9014
- .run(() => processVoiceJob(key, fileId, durationSeconds, (0, topicRequest_1.getTopicRequesterId)(ctx.from), warmedEndpoint, progressNote, sentAtMs, messageContext))
9326
+ .run(() => processVoiceJob(key, fileId, durationSeconds, (0, topicRequest_1.getTopicRequesterId)(ctx.from), warmedEndpoint, progressNote, reply, sentAtMs, messageContext))
9015
9327
  .catch((err) => {
9016
9328
  console.error('[Bot] Voice job error (already handled):', err);
9017
9329
  })
@@ -9033,9 +9345,10 @@ bot.on((0, filters_1.message)('voice'), async (ctx) => {
9033
9345
  * (the job reuses that one ask — see `warmUpFirstEngine`), and `progressNote`, the
9034
9346
  * «transcribing…» note armed on arrival, which the job finishes as soon as the
9035
9347
  * text is here or the voice failed — BEFORE the echo or the failure notice, never
9036
- * at the end of the job (delivering the prompt may take long).
9348
+ * at the end of the job (delivering the prompt may take long). `reply` says who sent the voice note and what it replies to: a voice reply
9349
+ * to a question the bot set aside is that question's late answer, its transcript the answer (like a typed reply).
9037
9350
  */
9038
- async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmedEndpoint, progressNote, sentAtMs, messageContext) {
9351
+ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmedEndpoint, progressNote, reply, sentAtMs, messageContext) {
9039
9352
  try {
9040
9353
  // Audit S14 / #33: `getFileLink` builds the bot-token URL in one
9041
9354
  // place inside Telegraf instead of us materialising the token in a
@@ -9081,6 +9394,11 @@ async function processVoiceJob(key, fileId, durationSeconds, requesterId, warmed
9081
9394
  // surfaces immediately instead of queuing behind the thread's streaming
9082
9395
  // agent output (which is what made it arrive minutes late under load).
9083
9396
  void replyToThread(key, (0, i18n_1.t)('voice.transcribed', { text: transcript }), {}, { unpaced: true }).catch(() => { });
9397
+ // A voice REPLY to a question the bot set aside is its late answer, as a typed reply is: the transcript is the answer (a topic member's
9398
+ // only when it names an option; a forwarded voice note never answers). Taken before any other route, like the typed one — answering the
9399
+ // agent's question is the one thing foreign words may do here.
9400
+ if (await answerSetAsideQuestionByReply(reply.from, key, { message_id: reply.messageId, text: transcript, replyToMessageId: reply.replyToMessageId, isForwarded: messageContext?.isForwarded === true }, reply.role))
9401
+ return;
9084
9402
  // `/reminders` step 4 accepts a voice note as well as typed text, so the
9085
9403
  // transcript is routed here — right after the 🎤 echo and BEFORE the
9086
9404
  // startup-buffer / natural-language-start / binding gates, which would
@@ -9572,7 +9890,9 @@ bot.on((0, filters_1.message)('forum_topic_created'), async (ctx) => {
9572
9890
  /**
9573
9891
  * @description A forum topic was renamed (or its icon changed). When the name
9574
9892
  * changed, persist it so the thread-context preamble can tell the agent its
9575
- * current topic name. Admin-gated like the created/closed/reopened trio: a
9893
+ * current topic name — the owner's OWN name: a trailing status mark of the bot's
9894
+ * is cut off it (`getOwnerRenameOutcome`), and the name saved is remembered as the
9895
+ * one the topic shows now. Admin-gated like the created/closed/reopened trio: a
9576
9896
  * non-authorised member's rename must not reshape what the bot remembers.
9577
9897
  *
9578
9898
  * This is also the ONLY way the bot learns the name of a pre-existing topic
@@ -9588,18 +9908,76 @@ bot.on((0, filters_1.message)('forum_topic_edited'), async (ctx) => {
9588
9908
  if (!newName)
9589
9909
  return;
9590
9910
  const userId = ctx.from?.id;
9911
+ // The bot's OWN rename (its status mark) comes back as this service message: never an owner's rename (stored as a name) nor a
9912
+ // stranger's (a `[security]` line) — only a line to delete, so the topic shows no trace of the change.
9913
+ if (userId !== undefined && userId === bot.botInfo?.id) {
9914
+ await topicIndicator.handleOwnRenameLine(key, ctx.message.message_id);
9915
+ return;
9916
+ }
9591
9917
  if (!userId || !(await checkIsAllowedUser(ctx))) {
9592
9918
  console.warn(`[security] forum_topic_edited in chat ${ctx.chat.id} by user ${userId ?? '?'} (not a group admin) — name not updated`);
9593
9919
  return;
9594
9920
  }
9595
- if (state.getBinding(key)) {
9596
- await state.setBindingTopicName(key, newName);
9921
+ await applyOwnerTopicRename(key, newName);
9922
+ });
9923
+ /**
9924
+ * @description An authorised sender renamed a topic: what the bot keeps of its name. Shared by the live `forum_topic_edited` update and
9925
+ * the renames read before a cold start drops the waiting updates (`applyRenamesThatWaitedForColdStart`).
9926
+ */
9927
+ async function applyOwnerTopicRename(key, newName) {
9928
+ const binding = state.getBinding(key);
9929
+ // The owner's own words are what is kept: a trailing mark of the bot's is not part of them (`getOwnerRenameOutcome`).
9930
+ const renamed = (0, topicIndicatorPlan_1.getOwnerRenameOutcome)(newName, binding?.indicatorAppliedName, binding?.topicName, topicIndicator.getRecentAppliedNames(key));
9931
+ if (binding) {
9932
+ // The name saved IS what the topic shows now; the candidate (a guess) is settled by it.
9933
+ await state.setBindingTopicNaming(key, {
9934
+ topicName: renamed.base,
9935
+ topicNameCandidate: null,
9936
+ indicatorAppliedName: newName,
9937
+ indicatorDroppedMark: renamed.droppedMark,
9938
+ });
9939
+ // What the topic shows now is the owner's name (with or without our mark): look at it again.
9940
+ topicIndicator.requestRefresh(key);
9597
9941
  }
9598
9942
  else {
9599
9943
  // No binding yet — keep the freshest name for a later fuzzy auto-bind.
9600
- pendingTopicNames.set((0, sessionKey_1.keyToString)(key), { name: newName, ts: Date.now(), isFromAdmin: true });
9944
+ pendingTopicNames.set((0, sessionKey_1.keyToString)(key), { name: renamed.base, ts: Date.now(), isFromAdmin: true });
9601
9945
  }
9602
- });
9946
+ }
9947
+ /**
9948
+ * @description A COLD start drops the updates that waited while the bot was down, and with them an owner's rename of a topic — the bot
9949
+ * would write the old name plus a mark over it. So they are read once first (`waitingTopicRenames.ts`) and only the renames of bound
9950
+ * topics, by an authorised sender, are applied through {@link applyOwnerTopicRename}; the bot's own «renamed» lines are deleted as a live
9951
+ * one is; everything else is dropped by the launch as before. Never throws: a read that fails is the old behaviour.
9952
+ */
9953
+ async function applyRenamesThatWaitedForColdStart() {
9954
+ const renames = await (0, waitingTopicRenames_1.readWaitingTopicRenames)((request) => bot.telegram.callApi('getUpdates', request), (error) => console.warn('[boot] reading the topic renames that waited failed — they are dropped with the other updates:', error instanceof Error ? error.message : error), botAllowedUpdates);
9955
+ const botUserId = bot.botInfo?.id ?? (await bot.telegram.getMe()).id;
9956
+ let appliedCount = 0;
9957
+ for (const renamed of renames) {
9958
+ const chat = renamed.chat;
9959
+ const key = getThreadKeyForRoute({
9960
+ chat: { id: chat.id, type: chat.type, is_forum: 'is_forum' in chat ? chat.is_forum : undefined },
9961
+ message: { message_thread_id: renamed.message_thread_id, is_topic_message: renamed.is_topic_message },
9962
+ });
9963
+ if (!key)
9964
+ continue;
9965
+ const senderId = renamed.from?.id;
9966
+ if (senderId !== undefined && senderId === botUserId) {
9967
+ await topicIndicator.handleOwnRenameLine(key, renamed.message_id);
9968
+ continue;
9969
+ }
9970
+ if (!state.getBinding(key))
9971
+ continue;
9972
+ if (!(await checkIsAllowedSender(checkIsOwnerDm(chat), senderId))) {
9973
+ console.warn(`[security] forum_topic_edited in chat ${chat.id} by user ${senderId ?? '?'} (not a group admin) — name not updated`);
9974
+ continue;
9975
+ }
9976
+ await applyOwnerTopicRename(key, renamed.forum_topic_edited.name);
9977
+ appliedCount += 1;
9978
+ }
9979
+ console.log(`Cold start: ${renames.length} topic rename(s) waited while the bot was down, ${appliedCount} applied; the other waiting updates are dropped`);
9980
+ }
9603
9981
  // Audit S2 / #5: closed/reopened events can come from a member who isn't an
9604
9982
  // authorised user. We deliberately diverge from "trust Telegram's state":
9605
9983
  // better to leave our `closed` flag stale than to let a non-authorised user
@@ -9914,8 +10292,12 @@ bot.action(timezonePicker_1.zonePickCallbackRe, async (ctx) => {
9914
10292
  });
9915
10293
  registerModelCallbacks();
9916
10294
  registerCompactionCallbacks();
10295
+ // The buttons of a set-aside question (`qs_<id>_<i>`): disjoint from the live (`qa_`) and the re-asked (`reask_`) ones.
10296
+ registerQuestionSetAsideCallbacks(bot);
9917
10297
  registerAutoContinueLimitsCallbacks();
9918
10298
  registerBotSkillsCallbacks();
10299
+ registerQuestionWaitCallbacks();
10300
+ registerTopicStatusCallbacks();
9919
10301
  registerTopicAccessCallbacks();
9920
10302
  registerTaskAgentsCallbacks();
9921
10303
  registerRunnersCallbacks();
@@ -10066,11 +10448,22 @@ bot.action(/^qa_(\d+)_(\d+)$/, async (ctx) => {
10066
10448
  const qIdx = parseInt(ctx.match[1], 10);
10067
10449
  const optIdx = parseInt(ctx.match[2], 10);
10068
10450
  const kStr = (0, sessionKey_1.keyToString)(key);
10451
+ // A button still showing on the message of a question the bot SET ASIDE meanwhile (the edit to the `qs_` buttons is paced by the send
10452
+ // gate, or was refused): that question is open and answerable, so the tap answers IT through the set-aside path.
10453
+ if (await answerLiveTapOnSetAsideQuestion(ctx, speaker, qIdx, optIdx))
10454
+ return;
10069
10455
  const pending = pendingQuestions.get(kStr);
10070
10456
  if (!pending) {
10071
10457
  await ctx.answerCbQuery((0, i18n_1.t)('cb.no_pending_question'));
10072
10458
  return;
10073
10459
  }
10460
+ // A button on a message of a set-aside question that is not the open one is stale: that question is no longer the one waiting, and
10461
+ // its `qa_<i>_<j>` would answer whatever the agent asks next.
10462
+ const tappedMessageId = (0, callbackMessage_1.getCallbackMessageId)(ctx);
10463
+ if (tappedMessageId !== null && checkIsSetAsideQuestionMessage(key, tappedMessageId)) {
10464
+ await ctx.answerCbQuery((0, i18n_1.t)('cb.no_pending_question'));
10465
+ return;
10466
+ }
10074
10467
  // A button must belong to the question currently on screen. With sequential
10075
10468
  // posting we only ever show `currentIndex`, so a click for any other index is
10076
10469
  // a stale button from a question that was already answered/advanced.
@@ -10139,7 +10532,9 @@ async function bufferPromptDuringStartup(key, text, intake, messageContext) {
10139
10532
  * `answerQuestion`). The tmux-scrape Claude and the terminal never reach it (no `pendingQuestions` entry): for them
10140
10533
  * `forwardPromptToAgent` interrupts the TUI selector itself.
10141
10534
  */
10142
- async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext) {
10535
+ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, messageContext,
10536
+ /** `replyToMessageId`: the message the text is genuinely a reply to (`getTelegramReplyTargetId`), `null` for none. */
10537
+ options = {}) {
10143
10538
  // A FORWARDED message is content, never control input: it answers no question and purges no context, whatever its words are.
10144
10539
  // A topic member's words are not the operator's either — but a bare option number of theirs DOES answer the agent's question
10145
10540
  // (members may answer questions, the one thing foreign words may do here), so the two answer routes below ask `isForwarded`
@@ -10154,9 +10549,14 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
10154
10549
  notePersonActivity(key);
10155
10550
  const pending = pendingQuestions.get((0, sessionKey_1.keyToString)(key));
10156
10551
  if (pending && adapter.answerQuestion) {
10552
+ // A REPLY to a message other than the question that waits NOW (one that was answered, closed or set aside, or any other message)
10553
+ // is not a response to this question: no number in it is a pick — «2» typed as a reply to an old question's message would answer
10554
+ // the one the owner never looked at. Its words still move the agent on like any text: below, they cancel the waiting question.
10555
+ const { replyToMessageId } = options;
10556
+ const isReplyToAnotherMessage = replyToMessageId != null && replyToMessageId !== pending.messageId && replyToMessageId !== pending.originalMessageId;
10157
10557
  const currentQuestion = pending.data.questions[pending.currentIndex];
10158
10558
  const route = (0, openCodeQuestionFlow_1.getQuestionReplyRoute)(text, currentQuestion);
10159
- if (route.kind === 'answer' && !isForwarded) {
10559
+ if (route.kind === 'answer' && !isForwarded && !isReplyToAnotherMessage) {
10160
10560
  // Answering a pending question (bare digit) is a pick, not a prompt about
10161
10561
  // the quote — the reply context is deliberately dropped here. Not a request
10162
10562
  // either: the turn it unblocks continues under the open one. A forwarded digit
@@ -10191,6 +10591,15 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
10191
10591
  adapter.sendSignal(key, 'SIGINT');
10192
10592
  await replyToThread(key, (0, i18n_1.t)('agent.question_cancelled_for_prompt'));
10193
10593
  }
10594
+ return deliverPromptByState(key, adapter, text, intake, sentAtMs, messageContext);
10595
+ }
10596
+ /**
10597
+ * @description The end of {@link deliverActivePrompt}, shared with the delivery of a late answer ({@link deliverLateAnswerPrompt}): open
10598
+ * the request the prompt belongs to (none for `intake` null — an answer to the agent's own question is never a request), deliver it by
10599
+ * the state of the session NOW — buffered behind a start, waking a sleeping conversation, or forwarded to the live one — and settle
10600
+ * the request. It touches no pending question and no wedged turn: that is the caller's.
10601
+ */
10602
+ async function deliverPromptByState(key, adapter, text, intake, sentAtMs, messageContext) {
10194
10603
  // The request (S7) is opened AFTER the user takeover cancelled an armed limit
10195
10604
  // wait (the handlers' `cancelApiRetry`) and before the forward, so its id is
10196
10605
  // durable by the time the agent reads it.
@@ -10214,6 +10623,22 @@ async function deliverActivePrompt(key, adapter, text, intake, sentAtMs, message
10214
10623
  await settleTopicRequestAfterDelivery(key, opening, outcome);
10215
10624
  return outcome;
10216
10625
  }
10626
+ /**
10627
+ * @description Deliver a LATE ANSWER to the agent — what the owner chose for a question the bot set aside, worded by
10628
+ * `buildLateAnswerPrompt` — as a message of the owner's: written to a live session behind whatever it is doing, buffered behind a
10629
+ * start, or waking a sleeping conversation. Unlike {@link deliverActivePrompt} it is NOT free text for the question the agent may be
10630
+ * waiting on NOW (that one is a different question, and the owner has not answered it): it never cancels it and never aborts a
10631
+ * wedged turn. It cancels an armed usage-limit wait first, as typed text does. It carries no message context: the text is the bot's
10632
+ * block, and a topic member's answer says who gave it inside the answer itself (an author mark ahead of it would end at the block's
10633
+ * own header).
10634
+ */
10635
+ async function deliverLateAnswerPrompt(key, text) {
10636
+ // The owner took over, like with any message they type: an armed usage-limit wait is over (the answer is not written INTO it, and its
10637
+ // own «continue» nudge would come on top of the answer later).
10638
+ cancelApiRetry(key);
10639
+ noteThreadUserActivity(key);
10640
+ return deliverPromptByState(key, (0, createAdapter_1.getThreadAdapter)(key), text, null);
10641
+ }
10217
10642
  /**
10218
10643
  * @description Close the on-screen state of a pending question that ends without an answer: clear the bot's
10219
10644
  * pending-question state (which unpins it) and edit the question's message so its buttons are gone and a note says that
@@ -10302,7 +10727,7 @@ async function applyQuestionAnswerInner(key, answerForCurrent, answeredBy) {
10302
10727
  const { nextState, action } = (0, openCodeQuestionFlow_1.recordAnswerAndAdvance)(pending, answeredBy === undefined ? answerForCurrent : (0, authorMark_1.getAnswerWithAttribution)(answerForCurrent, answeredBy));
10303
10728
  // Mark the answered question's message as done: the question stays as asked, the chosen answer takes the place of
10304
10729
  // its buttons.
10305
- const isAnswerShown = pending.messageId !== null && answeredQuestion !== undefined && await editQuestionMessageToClosed(key, pending.messageId, answeredQuestion, (0, i18n_1.t)('agent.question_answered_note', { answer: answerForCurrent.join(', ') }));
10730
+ const isAnswerShown = pending.messageId !== null && answeredQuestion !== undefined && await editQuestionMessageWithNote(key, pending.messageId, answeredQuestion, (0, i18n_1.t)('agent.question_answered_note', { answer: answerForCurrent.join(', ') }));
10306
10731
  if (action.kind === 'submit') {
10307
10732
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
10308
10733
  clearPendingQuestion(key);
@@ -11342,6 +11767,22 @@ function handleSubagentStatus(key, payload) {
11342
11767
  }
11343
11768
  })();
11344
11769
  }
11770
+ /**
11771
+ * @description The question wait changed (`/question_wait`): the questions that wait now are timed again from the moment each was
11772
+ * asked — one conversation's (`key`), or, when the instance value changed, every waiting one (those that follow it get a new moment,
11773
+ * the others keep theirs). A wait that is already over sets the question aside at once; «Wait for my answer» takes the timer off.
11774
+ */
11775
+ function rearmQuestionSetAsideTimers(key) {
11776
+ if (key !== null) {
11777
+ armQuestionSetAsideTimer(key);
11778
+ return;
11779
+ }
11780
+ for (const keyString of pendingQuestions.keys()) {
11781
+ const pendingKey = (0, sessionKey_1.tryKeyFromString)(keyString);
11782
+ if (pendingKey)
11783
+ armQuestionSetAsideTimer(pendingKey);
11784
+ }
11785
+ }
11345
11786
  function handleAgentQuestion(key, questionData) {
11346
11787
  console.log(`[Bot] question ${(0, sessionKey_1.keyToString)(key)} (${questionData.requestId}): ${questionData.questions.length}`);
11347
11788
  // Idempotent across restart: this handler ALSO fires from the adapter's
@@ -11357,6 +11798,16 @@ function handleAgentQuestion(key, questionData) {
11357
11798
  if (persistedQuestion && persistedQuestion.data.requestId === questionData.requestId) {
11358
11799
  return;
11359
11800
  }
11801
+ // A question whose set-aside copy is still open in the topic is not posted again: the agent is told it is the same one.
11802
+ if (answerQuestionAskedAgain(key, questionData))
11803
+ return;
11804
+ postAgentQuestion(key, questionData);
11805
+ }
11806
+ /**
11807
+ * @description Put a question the agent asked to the topic as the one that WAITS: the question UI takes over from the agent's
11808
+ * status, the message is posted (and pinned) in the lifecycle queue, and the question wait starts.
11809
+ */
11810
+ function postAgentQuestion(key, questionData) {
11360
11811
  // The agent asks anew: a question the idle compaction re-asked earlier is superseded, and its buttons would now answer
11361
11812
  // the wrong question — it is closed as unanswered.
11362
11813
  closeReAskedQuestion(key);
@@ -11398,12 +11849,29 @@ function handleAgentQuestion(key, questionData) {
11398
11849
  messageId: null,
11399
11850
  answers: new Array(questionData.questions.length).fill(null),
11400
11851
  currentIndex: 0,
11852
+ askedAt: Date.now(),
11401
11853
  });
11854
+ // The question waits for the owner only for the question wait: then the agent is told to go on without it.
11855
+ armQuestionSetAsideTimer(key);
11402
11856
  void runQuestionLifecycleOp(key, async () => {
11403
11857
  await streamedOutputLanding;
11404
11858
  await postPendingQuestionAt(key);
11405
11859
  });
11406
11860
  }
11861
+ /**
11862
+ * @description Post a question as a NEW message of the topic — its text (header, question, numbered options with their descriptions)
11863
+ * with `keyboard` as its buttons. Resolves the id of the message, `null` when no send landed.
11864
+ *
11865
+ * Markdown first, then plain when Telegram refuses it. Only a post that FAILED is retried: one whose outcome is unknown may already
11866
+ * be in the topic, and a second copy of the question would be posted under it (its id stays unknown; its buttons still answer it).
11867
+ */
11868
+ async function sendQuestionMessage(key, question, keyboard) {
11869
+ let outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLines)(question, escapeMarkdown).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard, { parse_mode: 'Markdown' }));
11870
+ if (outcome.kind === 'failed') {
11871
+ outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLinesPlain)(question).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
11872
+ }
11873
+ return outcome.kind === 'sent' ? outcome.messageId : null;
11874
+ }
11407
11875
  /**
11408
11876
  * @description Render + send ONE OpenCode question (the one at the pending
11409
11877
  * state's `currentIndex`) as the newest thread message, then patch the
@@ -11465,13 +11933,7 @@ async function postPendingQuestionAt(key) {
11465
11933
  ? (0, questionKeyboards_1.buildQuestionOptionsKeyboard)(question, (optionIndex) => `qa_${qIdx}_${optionIndex}`)
11466
11934
  : undefined;
11467
11935
  try {
11468
- let outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLines)(question, escapeMarkdown).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard, { parse_mode: 'Markdown' }));
11469
- // Markdown rejected — retry plain. Only a post that FAILED: one whose outcome is unknown may already be in the topic, and a
11470
- // second copy of the question would be posted under it (its id stays unknown; its buttons still answer it).
11471
- if (outcome.kind === 'failed') {
11472
- outcome = await replyToThreadDetailed(key, (0, openCodeQuestionFlow_1.buildQuestionBodyLinesPlain)(question).join('\n'), (0, questionKeyboards_1.buildKeyboardExtra)(keyboard));
11473
- }
11474
- const messageId = outcome.kind === 'sent' ? outcome.messageId : null;
11936
+ const messageId = await sendQuestionMessage(key, question, keyboard);
11475
11937
  if (messageId !== null) {
11476
11938
  // Patch the messageId on the existing entry (it may already have been
11477
11939
  // cleared/advanced by an answer callback firing in between). Route
@@ -11541,6 +12003,8 @@ function handleAgentClosed(key) {
11541
12003
  // A closed session has nothing to resume — drop any armed retry silently.
11542
12004
  cancelApiRetry(key);
11543
12005
  clearAuthNotice(key); // session closed → retire any pinned logged-out notice
12006
+ // The process died on its own: the topic's name says stuck until the next turn (the banner refresh below asks for the mark).
12007
+ topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
11544
12008
  // A closed session has nothing to compact — drop the idle watchdog + any arm.
11545
12009
  clearThreadCompaction(key);
11546
12010
  const adapter = (0, createAdapter_1.getThreadAdapter)(key);
@@ -11703,6 +12167,8 @@ function createBufferedOutcome() {
11703
12167
  }
11704
12168
  function handleAgentError(key, error) {
11705
12169
  console.error(`[Bot] adapter error ${(0, sessionKey_1.keyToString)(key)}:`, error.message);
12170
+ topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
12171
+ topicIndicator.requestRefresh(key);
11706
12172
  stopClaudeLiveness(key);
11707
12173
  supersedeStatusFrames(key);
11708
12174
  deleteStatusMessage(key).catch(() => { });
@@ -11791,6 +12257,8 @@ function handleAgentStopped(key) {
11791
12257
  * never told it.
11792
12258
  */
11793
12259
  function handleConversationLost(key) {
12260
+ topicsStuckUntilNextTurn.add((0, sessionKey_1.keyToString)(key));
12261
+ topicIndicator.requestRefresh(key);
11794
12262
  dropLostConversationWatermark(key);
11795
12263
  clearThreadContextMarker(key);
11796
12264
  replyToThread(key, (0, i18n_1.t)('agent.resume_failed_fresh')).catch(() => { });
@@ -11850,6 +12318,8 @@ exports.COMMANDS_MENU = [
11850
12318
  { command: 'compact_summary', description: '📄 Post the compaction summary (toggle)' },
11851
12319
  { command: 'compact_self_review', description: '💡 Agent self-review on compaction: its mistakes and what to change in its instructions' },
11852
12320
  { command: 'bot_skills', description: '🧰 The bot\'s own skills for agents (on/off)' },
12321
+ { command: 'question_wait', description: '⏳ How long the agent waits for your answer to its question' },
12322
+ { command: 'topic_status', description: '❓ Marks at the end of topic names: question, working, finished, asleep' },
11853
12323
  { command: 'task_agents', description: '🧵 How many tracker task agents work at once' },
11854
12324
  { command: 'runners', description: '🖥 Runners — machines for the agents\' tests and builds' },
11855
12325
  { command: 'accounts', description: '👤 Claude accounts and OpenCode providers (switch, add, re-login, remove, connect, disconnect)' },
@@ -12346,6 +12816,8 @@ function restorePendingQuestions() {
12346
12816
  // handlers. Migrate to the new shape and re-persist so disk catches up.
12347
12817
  const migrated = (0, openCodeQuestionFlow_1.migratePendingQuestionState)(value);
12348
12818
  setPendingQuestion(key, migrated);
12819
+ // The rest of its wait, counted from when it was asked — not a new one.
12820
+ armQuestionSetAsideTimer(key);
12349
12821
  restored += 1;
12350
12822
  }
12351
12823
  else {
@@ -12363,6 +12835,28 @@ function restorePendingQuestions() {
12363
12835
  }
12364
12836
  console.log(`[reattach] pending questions: restored ${restored}, dropped ${dropped}`);
12365
12837
  }
12838
+ /**
12839
+ * @description Boot: the questions the bot set aside keep their buttons while their conversation can still be resumed (a live
12840
+ * adopted process, or a sleeping conversation whose id is kept — a late answer wakes it); those of a conversation that was released
12841
+ * while the bot was down end as «not answered», their pins released. MUST run AFTER {@link reattachExistingSessions} so session
12842
+ * activity is known. A platform this instance does not serve is left alone, like {@link restorePendingQuestions}.
12843
+ */
12844
+ function restoreSetAsideQuestions() {
12845
+ for (const keyStr of Object.keys(state.getSetAsideQuestions())) {
12846
+ let key;
12847
+ try {
12848
+ key = (0, sessionKey_1.keyFromString)(keyStr);
12849
+ }
12850
+ catch {
12851
+ continue;
12852
+ }
12853
+ if (!(0, connectorSet_1.checkIsServedConversation)(key, ENV.servedPlatforms))
12854
+ continue;
12855
+ if ((0, createAdapter_1.getThreadAdapter)(key).checkIsActive(key) || getResumableSessionId(key) !== null)
12856
+ continue;
12857
+ closeSetAsideQuestionsInBackground(key);
12858
+ }
12859
+ }
12366
12860
  /**
12367
12861
  * @description Bring back the questions the idle compaction re-asked, at boot. One whose conversation can still be
12368
12862
  * resumed (a live adopted process, or a sleeping conversation whose id is kept) gets its buttons working again — a tap
@@ -13350,6 +13844,8 @@ async function startBot() {
13350
13844
  // docs/troubleshooting.md's two-instances section tells the operator to compare this
13351
13845
  // exact line across instances.
13352
13846
  state = await (0, state_1.getStateStore)({ saveDebounceMs: ENV.testTimings.stateSaveDebounceMs });
13847
+ // A watched worker created, ended or paused, a question set aside or closed: the topic's name follows.
13848
+ state.setStatusSourceChangeListener((key) => topicIndicator.requestRefresh(key));
13353
13849
  console.log(`[startup] DATA_DIR=${path.dirname(state.stateFilePath)}`);
13354
13850
  // R13: before anything reads, rewrites or acts on the state, it must hold only
13355
13851
  // conversations of the platforms this instance serves.
@@ -13533,6 +14029,9 @@ async function startBot() {
13533
14029
  // Output means a turn is under way — the wake-up engine's busy-onset signal, and the todo reminder's.
13534
14030
  requestWakeUpEngine?.noteAgentOutput(key);
13535
14031
  todoReminderEngine?.noteAgentOutput(key);
14032
+ // …and the topic's name shows it: an agent that went wrong is no longer stuck once a turn runs.
14033
+ topicsStuckUntilNextTurn.delete((0, sessionKey_1.keyToString)(key));
14034
+ topicIndicator.requestRefresh(key);
13536
14035
  };
13537
14036
  (0, createAdapter_1.registerAdapterEventHandlers)({
13538
14037
  onOutput: (key, output, meta) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'output', () => {
@@ -13550,7 +14049,11 @@ async function startBot() {
13550
14049
  markThreadTurnProducedOutput(key);
13551
14050
  noteThreadActivity(key);
13552
14051
  }),
13553
- onStatus: (key, status) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'status', () => withThreadLocale(key, () => handleAdapterStatus(key, status))),
14052
+ onStatus: (key, status) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'status', () => {
14053
+ // A status frame (a tool call, thinking) is the first sign of a turn that produces no text yet.
14054
+ topicIndicator.requestRefresh(key);
14055
+ return withThreadLocale(key, () => handleAdapterStatus(key, status));
14056
+ }),
13554
14057
  onQuestion: (key, question) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'question', () => withThreadLocale(key, () => handleAgentQuestion(key, question))),
13555
14058
  onThinking: (key, payload) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'thinking', () => withThreadLocale(key, () => handleAgentThinking(key, payload))),
13556
14059
  onToolResult: (key, payload) => (0, adapterEventRouting_1.dispatchAdapterEvent)(key, 'toolResult', () => withThreadLocale(key, () => handleAgentToolResult(key, payload))),
@@ -13706,6 +14209,8 @@ async function startBot() {
13706
14209
  // The questions the idle compaction re-asked: their buttons come back while the conversation can be resumed,
13707
14210
  // else the message is closed.
13708
14211
  restoreReAskedQuestions();
14212
+ // The questions the bot set aside: their buttons stay while the conversation can be resumed, else they are closed.
14213
+ restoreSetAsideQuestions();
13709
14214
  // Re-arm persisted API-error retries (S6) so a pending kick survives the
13710
14215
  // restart. AFTER restorePendingQuestions so the kick lands in a live
13711
14216
  // session; a past fireAt fires one delayed catch-up.
@@ -13966,6 +14471,7 @@ async function startBot() {
13966
14471
  schedulerEngine?.shutdown();
13967
14472
  requestWakeUpEngine?.stop();
13968
14473
  todoReminderEngine?.stop();
14474
+ topicIndicator.stop();
13969
14475
  jiraConnector?.stop();
13970
14476
  if (isSchedulerMcpStarted)
13971
14477
  void schedulerMcpHandle.stop().catch(() => { });
@@ -14057,6 +14563,18 @@ async function startBot() {
14057
14563
  // The local speech engine: clean up after an earlier run, re-attach to / start its install. Starts no process.
14058
14564
  void bootSttLocalEngine().catch((e) => console.warn('[STT] boot step failed:', e instanceof Error ? e.message : e));
14059
14565
  console.log(`Launching Telegraf bot (long polling, dropPendingUpdates=${bootMode.dropPendingUpdates})...`);
14566
+ // The marks of the topic names are written once the updates that waited are handled — an owner's rename made while the bot was down is
14567
+ // learned first (on a COLD start, which drops the waiting updates, it is read before the drop) — and looked at again every few minutes.
14568
+ // `launch` below returns only when the bot stops.
14569
+ if (bootMode.dropPendingUpdates) {
14570
+ try {
14571
+ await applyRenamesThatWaitedForColdStart();
14572
+ }
14573
+ catch (error) {
14574
+ console.warn('[boot] applying the topic renames that waited failed:', error instanceof Error ? error.message : error);
14575
+ }
14576
+ }
14577
+ topicIndicator.start();
14060
14578
  try {
14061
14579
  await bot.launch({
14062
14580
  dropPendingUpdates: bootMode.dropPendingUpdates,