telecoder 0.0.0-stage → 1.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 (223) hide show
  1. package/.env.example +363 -0
  2. package/CHANGELOG.md +1186 -0
  3. package/LICENSE +22 -0
  4. package/README.md +126 -2
  5. package/dist/audio/transcribe.js +50 -0
  6. package/dist/bin/mcp-server.js +378 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +592 -0
  10. package/dist/bot/file-access.js +141 -0
  11. package/dist/bot/handlers/command/access.js +407 -0
  12. package/dist/bot/handlers/command/admin.js +827 -0
  13. package/dist/bot/handlers/command/auto-approve.js +138 -0
  14. package/dist/bot/handlers/command/btw.js +224 -0
  15. package/dist/bot/handlers/command/cost.js +409 -0
  16. package/dist/bot/handlers/command/media.js +197 -0
  17. package/dist/bot/handlers/command/model.js +305 -0
  18. package/dist/bot/handlers/command/prefs-scope.js +197 -0
  19. package/dist/bot/handlers/command/project.js +536 -0
  20. package/dist/bot/handlers/command/resume.js +321 -0
  21. package/dist/bot/handlers/command/session.js +438 -0
  22. package/dist/bot/handlers/command/settings.js +1012 -0
  23. package/dist/bot/handlers/command/shared.js +210 -0
  24. package/dist/bot/handlers/command/streaming-mode.js +16 -0
  25. package/dist/bot/handlers/command/tasks.js +513 -0
  26. package/dist/bot/handlers/command/topic-store.js +113 -0
  27. package/dist/bot/handlers/command/topic.js +80 -0
  28. package/dist/bot/handlers/command.handler.js +772 -0
  29. package/dist/bot/handlers/fork.handler.js +1109 -0
  30. package/dist/bot/handlers/media-fallback.js +121 -0
  31. package/dist/bot/handlers/message/replies.js +133 -0
  32. package/dist/bot/handlers/message/shared.js +117 -0
  33. package/dist/bot/handlers/message/throttle.js +49 -0
  34. package/dist/bot/handlers/message/turn-notify.js +169 -0
  35. package/dist/bot/handlers/message/turn-runner.js +141 -0
  36. package/dist/bot/handlers/message.handler.js +107 -0
  37. package/dist/bot/handlers/newbot.handler.js +221 -0
  38. package/dist/bot/handlers/photo.handler.js +327 -0
  39. package/dist/bot/handlers/prompts.handler.js +343 -0
  40. package/dist/bot/handlers/running-note.js +44 -0
  41. package/dist/bot/handlers/schedule.handler.js +303 -0
  42. package/dist/bot/handlers/session-guard.js +78 -0
  43. package/dist/bot/handlers/suggestion.handler.js +84 -0
  44. package/dist/bot/handlers/tree.handler.js +480 -0
  45. package/dist/bot/handlers/view.js +41 -0
  46. package/dist/bot/handlers/voice.handler.js +209 -0
  47. package/dist/bot/middleware/admin-only.js +49 -0
  48. package/dist/bot/middleware/auth.middleware.js +122 -0
  49. package/dist/bot/middleware/group-mention.middleware.js +139 -0
  50. package/dist/bot/middleware/group-role.middleware.js +75 -0
  51. package/dist/bot/middleware/message-batcher.js +87 -0
  52. package/dist/bot/middleware/queued-messages.js +971 -0
  53. package/dist/bot/middleware/stale-filter.js +31 -0
  54. package/dist/build-info.json +8 -0
  55. package/dist/claude/agent-watchdog.js +162 -0
  56. package/dist/claude/agent.js +1458 -0
  57. package/dist/claude/ask-user.js +295 -0
  58. package/dist/claude/auto-approve.js +225 -0
  59. package/dist/claude/auto-topic-haiku.js +126 -0
  60. package/dist/claude/available-commands.js +153 -0
  61. package/dist/claude/carry-over.js +27 -0
  62. package/dist/claude/ccr-shim.js +46 -0
  63. package/dist/claude/charter-judge.js +214 -0
  64. package/dist/claude/claude-auth.js +121 -0
  65. package/dist/claude/command-parser.js +200 -0
  66. package/dist/claude/cost-overlay-scraper.js +129 -0
  67. package/dist/claude/enabled-plugins.js +56 -0
  68. package/dist/claude/fork-tree.js +393 -0
  69. package/dist/claude/held-query.js +190 -0
  70. package/dist/claude/in-flight-tracker.js +61 -0
  71. package/dist/claude/ipc-server.js +192 -0
  72. package/dist/claude/mcp-bridge.js +453 -0
  73. package/dist/claude/mcp-tools.js +354 -0
  74. package/dist/claude/message-offsets.js +88 -0
  75. package/dist/claude/modal-relay.js +450 -0
  76. package/dist/claude/model-catalog.js +85 -0
  77. package/dist/claude/monitor-relay.js +597 -0
  78. package/dist/claude/pending-forks.js +93 -0
  79. package/dist/claude/pending-suggestions.js +50 -0
  80. package/dist/claude/permission-gate.js +337 -0
  81. package/dist/claude/permission-mode.js +178 -0
  82. package/dist/claude/poll-user.js +51 -0
  83. package/dist/claude/project-commands.js +69 -0
  84. package/dist/claude/prompt-hold.js +124 -0
  85. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  86. package/dist/claude/pty-provider.js +2214 -0
  87. package/dist/claude/pty-spawn-config.js +296 -0
  88. package/dist/claude/pty-stream.js +363 -0
  89. package/dist/claude/request-queue.js +135 -0
  90. package/dist/claude/scheduled-runner.js +91 -0
  91. package/dist/claude/scheduler.js +237 -0
  92. package/dist/claude/scope-guard.js +274 -0
  93. package/dist/claude/sdk-permission-gate.js +77 -0
  94. package/dist/claude/secret-request.js +576 -0
  95. package/dist/claude/session-cost.js +41 -0
  96. package/dist/claude/session-history.js +286 -0
  97. package/dist/claude/session-jsonl.js +920 -0
  98. package/dist/claude/session-manager.js +195 -0
  99. package/dist/claude/session-scan.js +270 -0
  100. package/dist/claude/setup-token.js +285 -0
  101. package/dist/claude/side-call-options.js +45 -0
  102. package/dist/claude/side-question.js +249 -0
  103. package/dist/claude/stage-images.js +62 -0
  104. package/dist/claude/subagent-tools.js +12 -0
  105. package/dist/claude/synthetic-ctx.js +51 -0
  106. package/dist/claude/system-prompt.js +162 -0
  107. package/dist/claude/tasks-overlay-scraper.js +94 -0
  108. package/dist/claude/tip-scraper.js +78 -0
  109. package/dist/claude/tui-modal.js +501 -0
  110. package/dist/claude/tui-state.js +384 -0
  111. package/dist/claude/turn-end.js +91 -0
  112. package/dist/claude/turn-prose.js +64 -0
  113. package/dist/claude/update-banner-relay.js +70 -0
  114. package/dist/cli/commands/doctor.js +305 -0
  115. package/dist/cli/commands/help.js +25 -0
  116. package/dist/cli/commands/init.js +123 -0
  117. package/dist/cli/commands/service.js +678 -0
  118. package/dist/cli/commands/start.js +53 -0
  119. package/dist/cli/commands/version.js +11 -0
  120. package/dist/cli/dispatch.js +79 -0
  121. package/dist/cli/init/env-file.js +99 -0
  122. package/dist/cli/init/flow.js +638 -0
  123. package/dist/cli/init/prompter.js +116 -0
  124. package/dist/cli/init/telegram.js +94 -0
  125. package/dist/cli/service/render.js +212 -0
  126. package/dist/cli.js +18 -0
  127. package/dist/config-report.js +107 -0
  128. package/dist/config.js +500 -0
  129. package/dist/index.js +367 -0
  130. package/dist/launcher.js +933 -0
  131. package/dist/node-version-check.js +27 -0
  132. package/dist/providers/ccr-health.js +119 -0
  133. package/dist/providers/ccr-introspect.js +149 -0
  134. package/dist/providers/ccr-provider.js +60 -0
  135. package/dist/providers/claude-provider.js +63 -0
  136. package/dist/providers/prefs-sync.js +164 -0
  137. package/dist/providers/project-favorites.js +74 -0
  138. package/dist/providers/provider-router.js +127 -0
  139. package/dist/providers/provider-switch.js +91 -0
  140. package/dist/providers/sdk-provider.js +37 -0
  141. package/dist/providers/types.js +8 -0
  142. package/dist/providers/user-preferences.js +214 -0
  143. package/dist/restart-when-idle.js +153 -0
  144. package/dist/startup/auto-continue.js +67 -0
  145. package/dist/startup/auto-resume.js +173 -0
  146. package/dist/startup/notices.js +120 -0
  147. package/dist/startup/shared.js +44 -0
  148. package/dist/startup/verify-token.js +31 -0
  149. package/dist/telegram/access-request.js +153 -0
  150. package/dist/telegram/action-logger.js +684 -0
  151. package/dist/telegram/admin-mention.js +107 -0
  152. package/dist/telegram/background-activity-card.js +502 -0
  153. package/dist/telegram/botname-settings.js +336 -0
  154. package/dist/telegram/button-text.js +26 -0
  155. package/dist/telegram/client-options.js +27 -0
  156. package/dist/telegram/deduplication.js +33 -0
  157. package/dist/telegram/entities.js +295 -0
  158. package/dist/telegram/force-reply-tracker.js +57 -0
  159. package/dist/telegram/lettered-options.js +87 -0
  160. package/dist/telegram/markdown.js +362 -0
  161. package/dist/telegram/message-sender.js +1287 -0
  162. package/dist/telegram/prompt-label.js +142 -0
  163. package/dist/telegram/prompt-suggestion.js +54 -0
  164. package/dist/telegram/send.js +123 -0
  165. package/dist/telegram/streaming-turn.js +105 -0
  166. package/dist/telegram/suggestions-settings.js +30 -0
  167. package/dist/telegram/task-list.js +367 -0
  168. package/dist/telegram/task-tracker.js +209 -0
  169. package/dist/telegram/telegraph-settings.js +31 -0
  170. package/dist/telegram/telegraph.js +453 -0
  171. package/dist/telegram/terminal-renderer.js +671 -0
  172. package/dist/telegram/terminal-settings.js +25 -0
  173. package/dist/telegram/thread-titles.js +190 -0
  174. package/dist/telegram/threads-setup.js +117 -0
  175. package/dist/tts/tts-settings.js +62 -0
  176. package/dist/tts/tts.js +245 -0
  177. package/dist/tts/voice-reply.js +78 -0
  178. package/dist/utils/admins.js +143 -0
  179. package/dist/utils/agent-timer.js +55 -0
  180. package/dist/utils/atomic-write.js +24 -0
  181. package/dist/utils/bot-token.js +74 -0
  182. package/dist/utils/bounded-map.js +55 -0
  183. package/dist/utils/build-info.js +57 -0
  184. package/dist/utils/caffeinate.js +50 -0
  185. package/dist/utils/claude-env.js +54 -0
  186. package/dist/utils/claude-version.js +48 -0
  187. package/dist/utils/config-home.js +62 -0
  188. package/dist/utils/debug-agent.js +117 -0
  189. package/dist/utils/debug-watchdog.js +121 -0
  190. package/dist/utils/download.js +111 -0
  191. package/dist/utils/exit-codes.js +48 -0
  192. package/dist/utils/file-type.js +149 -0
  193. package/dist/utils/format.js +81 -0
  194. package/dist/utils/home-project.js +30 -0
  195. package/dist/utils/host-stall.js +51 -0
  196. package/dist/utils/id-list.js +44 -0
  197. package/dist/utils/idle-restart.js +92 -0
  198. package/dist/utils/install-mode.js +63 -0
  199. package/dist/utils/instance-config.js +148 -0
  200. package/dist/utils/instances.js +95 -0
  201. package/dist/utils/json-store.js +140 -0
  202. package/dist/utils/keyed-settings.js +62 -0
  203. package/dist/utils/legacy-env.js +35 -0
  204. package/dist/utils/npm-version.js +134 -0
  205. package/dist/utils/prefs-relay.js +107 -0
  206. package/dist/utils/proc-children.js +102 -0
  207. package/dist/utils/project-data-dir.js +33 -0
  208. package/dist/utils/reasoning-summary.js +12 -0
  209. package/dist/utils/resolve-bin.js +86 -0
  210. package/dist/utils/resolve-claude-bin.js +63 -0
  211. package/dist/utils/respawn-backoff.js +19 -0
  212. package/dist/utils/sanitize.js +91 -0
  213. package/dist/utils/session-key.js +37 -0
  214. package/dist/utils/stale-launcher.js +109 -0
  215. package/dist/utils/state-dir-migration.js +92 -0
  216. package/dist/utils/systemd.js +126 -0
  217. package/dist/utils/user-roster.js +275 -0
  218. package/dist/utils/verbosity.js +118 -0
  219. package/dist/utils/version-check.js +166 -0
  220. package/dist/utils/workspace-guard.js +44 -0
  221. package/dist/worker-restart.js +141 -0
  222. package/instances.json.example +41 -0
  223. package/package.json +76 -4
@@ -0,0 +1,971 @@
1
+ /**
2
+ * Messages waiting their turn, and taking one back.
3
+ *
4
+ * A message sent while the bot is busy doesn't reach Claude until the bot is
5
+ * free, so until then it can still be recalled. Deleting it in Telegram can't
6
+ * do that: the Bot API has no event for a delete outside business accounts, and
7
+ * in a bot chat a delete only ever removes the sender's copy, so the bot's stays
8
+ * as it was. The only signal that can reach us is one we offer, hence a button.
9
+ *
10
+ * The wait has to be announced from out here because the handlers can't see it.
11
+ * Every handler awaits its whole turn and sequentialize holds the next update
12
+ * until that returns, so by the time a handler runs there is no turn left to
13
+ * report. A message behind a turn used to wait in silence, which looks exactly
14
+ * like a bot that has gone idle. /cancel couldn't reach it either: the message
15
+ * wasn't in the request queue, so stopping the turn released it.
16
+ *
17
+ * Hence a middleware either side of sequentialize:
18
+ *
19
+ * - `trackQueuedMessage`, ahead of it, notes the message the moment it arrives
20
+ * and schedules the ack. It must not await anything on the way to `next`:
21
+ * updates reach sequentialize in the order they leave here, so waiting on the
22
+ * ack would let a later message overtake an earlier one.
23
+ * - `holdQueuedMessage`, behind it, is where the wait ends. It drops a message
24
+ * that was taken back and otherwise takes the ack down and lets it through.
25
+ *
26
+ * It also holds a message bound for Claude while Claude is busy with something
27
+ * sequentialize knows nothing about: a /schedule fire, or a turn Claude started
28
+ * itself when a background task reported back. Holding here rather than in the
29
+ * pty provider's readiness wait means taking the message back leaves that turn
30
+ * alone, no "thinking" bubble goes up for a prompt that hasn't been delivered,
31
+ * and the relay still gets to post that turn's reply. The provider's wait stays
32
+ * as the backstop for a turn that starts in the moment after this lets go.
33
+ *
34
+ * Bot commands get the ack and the button while sequentialize holds them, and
35
+ * nothing more. They don't need Claude, so they don't wait for it.
36
+ *
37
+ * Whether a message is still worth sending can depend on the answer it's waiting
38
+ * behind, so one bound for Claude can also be set aside, to decide on once that
39
+ * answer has been read. "Parked" in here, because "hold" already means the wait
40
+ * above. It leaves the line the way a taken-back message does, since waiting in
41
+ * there for a decision would hold up everything behind it, and it's kept on disk,
42
+ * since the decision can outlast any number of restarts. The question goes up once
43
+ * nothing is running or waiting in the session. Send feeds the update back through
44
+ * the whole middleware chain as if it had just arrived, which is what gets a voice
45
+ * note transcribed and puts the message back in line if a turn has started since.
46
+ *
47
+ * A message can also go in place of the turn. "Interrupt & send" stops the turn
48
+ * the way /cancel does, minus this message, which goes to Claude once the turn
49
+ * has stopped. `/steer <text>` does the same for a message typed knowing that:
50
+ * it takes the command off and sends what's left through the chain again, after
51
+ * the stop, so it waits for the turn's end like any other message. Either way
52
+ * Claude still has the stopped prompt and whatever it did before the stop, so
53
+ * the new message reads as a correction to it.
54
+ *
55
+ * `/later <text>` sets an idea aside without typing it at Claude first. It's the
56
+ * only way in while nothing is running, when any message would start a turn, and
57
+ * it saves racing the ack's button against the end of a turn. It goes into the
58
+ * same store and through the same question, with the command taken off what goes
59
+ * out. Sent while Claude is idle, it waits for the next turn to come and go before
60
+ * asking, or the question would go up at once. `/later` alone lists what's set
61
+ * aside in the chat.
62
+ *
63
+ * A question left unanswered while the conversation moves on would scroll out of
64
+ * sight, so once another turn has run it's taken down and asked again below the
65
+ * new reply, without a buzz the second time.
66
+ *
67
+ * A message doesn't have to wait for the turn at all. "Ask as /btw" answers it
68
+ * on the side straight away, and "Ask in a fork" sends it to a new thread whose
69
+ * conversation is this one as it stood before the running turn, so the two carry
70
+ * on side by side. Either way it leaves the line, as a taken-back message does.
71
+ * What does the asking lives with the handlers, which hand it in through
72
+ * `setQueuedDiverters`, so this file doesn't pull in the agent.
73
+ */
74
+ import * as path from 'path';
75
+ import { GrammyError } from 'grammy';
76
+ import { z } from 'zod';
77
+ import { BOT_ID, config } from '../../config.js';
78
+ import { getBotCommandNames } from '../../claude/command-parser.js';
79
+ import { hasSelfStartedTurn, whenRepliesSent } from '../../claude/monitor-relay.js';
80
+ import { cancelRequest, clearQueue, isProcessing } from '../../claude/request-queue.js';
81
+ import { cancelSecretRequest } from '../../claude/secret-request.js';
82
+ import { getPtyProvider } from '../../providers/claude-provider.js';
83
+ import { isAdmin } from '../../utils/admins.js';
84
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../../utils/json-store.js';
85
+ import { sanitizeError } from '../../utils/sanitize.js';
86
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
87
+ import { markAlreadyAddressed, stripBotMention } from './group-mention.middleware.js';
88
+ import { wasBatched } from './message-batcher.js';
89
+ import { isStaleMessage } from './stale-filter.js';
90
+ /**
91
+ * How long a message must have been waiting before it says so. Long enough that
92
+ * one arriving as a turn winds up, or behind a command that answers at once,
93
+ * doesn't flash a notice that's gone a moment later; short enough to read as an
94
+ * immediate answer.
95
+ */
96
+ const ACK_DELAY_MS = 500;
97
+ /** How often a held message looks again at what it is waiting for. */
98
+ const HOLD_POLL_MS = 500;
99
+ /**
100
+ * How long a message waits on a turn Claude started itself before it moves on
101
+ * to the pty provider's readiness wait, which reports a turn that never ends
102
+ * instead of sitting on it. Matches that wait's own patience. A turn TeleCoder
103
+ * started has no ceiling here, because the agent watchdog already looks after it.
104
+ */
105
+ const OWN_TURN_CEILING_MS = 30 * 60_000;
106
+ /** How often a message set aside looks again at whether it can be asked about. */
107
+ const REMIND_POLL_MS = 1_000;
108
+ const CALLBACK_PREFIX = 'queued:';
109
+ /** A bare message id is Take back, which is what acks already in chats carry. */
110
+ const CALLBACK_PATTERN = /^queued:(?:(park|send|drop|btw|fork|steer):)?(\d+)$/;
111
+ const BEHIND_TURN = '⏳ Queued behind the running turn.';
112
+ const BEHIND_OWN_TURN = '⏳ Queued behind a turn Claude started itself.';
113
+ const STEERING = '⚡ Stopping the turn, then sending this.';
114
+ const TAKEN_BACK = '🗑 Taken back before it reached Claude.';
115
+ const CANCELLED = '🛑 Cancelled before it reached Claude.';
116
+ const NO_LONGER_WAITING = '⌛ No longer waiting. If Claude never answered it, send it again.';
117
+ const PARKED = "🔔 Set aside. I'll ask when Claude is done.";
118
+ const PARKED_AFTER_NEXT_TURN = "🔔 Set aside. I'll ask after Claude's next turn.";
119
+ const REMINDER = '🔔 You set this aside. Still want to send it?\n✏️ Edit your message above to change what goes out.';
120
+ const NOTHING_SET_ASIDE = 'Nothing is set aside in this chat.\n\n'
121
+ + "/later <text> keeps an idea for after Claude's turn, without it reaching Claude now. "
122
+ + 'Or tap 🔔 Ask me after on a message waiting behind a turn.';
123
+ const LIST_HEADING = '🔔 Set aside in this chat:';
124
+ const LIST_FOOTER = 'Each gets a question below the reply, with Send and Drop. Edit a message to change what goes out.';
125
+ /** The command and the whitespace after it, on a message that starts with it. */
126
+ const LATER_COMMAND = /^\/later(?:@\w+)?(?:\s+|$)/i;
127
+ const STEER_COMMAND = /^\/steer(?:@\w+)?(?:\s+|$)/i;
128
+ const STEER_USAGE = '⚡ /steer <text> stops the running turn and sends <text> in its place. '
129
+ + 'Claude keeps what it had done, so <text> can be a correction to it.';
130
+ const SENT = '📤 Sent.';
131
+ const DROPPED = '🗑 Dropped before it reached Claude.';
132
+ const NOT_YOURS = 'Only the person who sent this, or an admin, can do that.';
133
+ const ASKED_AS_BTW = '💬 Asked as /btw instead. The answer is below.';
134
+ const ASKED_IN_FORK = '🍴 Asked in a fork instead:';
135
+ /** From arrival until the message is let through or dropped, keyed by entryKey. */
136
+ const queued = new Map();
137
+ /** Sent with /steer and on their way back through the chain, keyed by entryKey. */
138
+ const steered = new Set();
139
+ const isRecord = (value) => typeof value === 'object' && value !== null;
140
+ const parkedMessageSchema = z.object({
141
+ chatId: z.number(),
142
+ threadId: z.number().optional(),
143
+ sessionKey: z.string(),
144
+ messageId: z.number(),
145
+ senderId: z.number().optional(),
146
+ /** Kept whole, because any handler may read any of it. */
147
+ update: z.custom((value) => isRecord(value) && isRecord(value.message)),
148
+ /** The ack, now saying the message is set aside. Taken down when the question goes up. */
149
+ noticeId: z.number().optional(),
150
+ /** The question, once it's gone up. */
151
+ reminderId: z.number().optional(),
152
+ /** Set aside with /later: the command is taken off the text, on arrival and after an edit. */
153
+ command: z.boolean().optional(),
154
+ /** Set aside while nothing was running, so the next turn is what it waits for. */
155
+ awaitsTurn: z.boolean().optional(),
156
+ /** A turn has run since the question went up, so it's to be asked again below the new reply. */
157
+ repost: z.boolean().optional(),
158
+ });
159
+ /** From the tap until it's sent or dropped, keyed by entryKey. Mirrored on disk. */
160
+ const parked = new Map();
161
+ /**
162
+ * Messages from arrival until their handler returns, per session. isProcessing
163
+ * can't stand in for this, because a message let through a moment ago, or a voice
164
+ * note still being transcribed, isn't a turn yet.
165
+ */
166
+ const inFlight = new Map();
167
+ /** Replays a message on Send, and posts the questions. */
168
+ let botRef;
169
+ let diverters;
170
+ /** Called once at startup by whatever wires the handlers. */
171
+ export function setQueuedDiverters(d) {
172
+ diverters = d;
173
+ }
174
+ let reminderTimer = null;
175
+ let reminding = false;
176
+ /** Messages whose chat refused the question. Tried again after a restart. */
177
+ const unreachable = new Set();
178
+ function entryKey(chatId, messageId) {
179
+ return `${chatId}:${messageId}`;
180
+ }
181
+ /**
182
+ * Whether a message would go to Claude, or null for one with nothing to take
183
+ * back: a video gets told it isn't supported, a sticker gets nothing. A slash
184
+ * command the bot doesn't handle is typed at Claude, so it counts as a message.
185
+ */
186
+ function boundForClaude(msg) {
187
+ if (msg.text !== undefined) {
188
+ const command = msg.text.match(/^\/(\w+)/)?.[1];
189
+ return command === undefined || !getBotCommandNames().has(command);
190
+ }
191
+ return msg.voice || msg.photo || msg.document ? true : null;
192
+ }
193
+ function ackText(entry) {
194
+ if (entry.steering)
195
+ return STEERING;
196
+ return !isProcessing(entry.sessionKey) && getPtyProvider().isSessionGenerating(entry.sessionKey)
197
+ ? BEHIND_OWN_TURN
198
+ : BEHIND_TURN;
199
+ }
200
+ function takeBackButton(messageId) {
201
+ return { text: '🗑 Take back', callback_data: `${CALLBACK_PREFIX}${messageId}` };
202
+ }
203
+ function ackKeyboard(entry) {
204
+ const first = [takeBackButton(entry.messageId)];
205
+ // The turn is already being stopped for it, so there's nothing else to wait out.
206
+ if (entry.steering)
207
+ return { inline_keyboard: [first] };
208
+ // A bot command has no answer to read first, so there's nothing to decide after.
209
+ if (entry.forClaude) {
210
+ first.push({ text: '🔔 Ask me after', callback_data: `${CALLBACK_PREFIX}park:${entry.messageId}` });
211
+ }
212
+ // Four don't fit across a phone, so the ways around the wait get a row of their own.
213
+ const second = [];
214
+ if (entry.canBtw && diverters) {
215
+ second.push({ text: '💬 Ask as /btw', callback_data: `${CALLBACK_PREFIX}btw:${entry.messageId}` });
216
+ }
217
+ if (entry.canFork && diverters) {
218
+ second.push({ text: '🍴 Ask in a fork', callback_data: `${CALLBACK_PREFIX}fork:${entry.messageId}` });
219
+ }
220
+ // Last, as the one that stops something.
221
+ const steer = [{ text: '⚡ Interrupt & send', callback_data: `${CALLBACK_PREFIX}steer:${entry.messageId}` }];
222
+ return { inline_keyboard: second.length > 0 ? [first, second, steer] : [first, steer] };
223
+ }
224
+ async function postAck(api, entry) {
225
+ try {
226
+ const sent = await api.sendMessage(entry.chatId, ackText(entry), {
227
+ // It's answering the message it hangs off, and the person who sent that
228
+ // is looking at the chat, so a buzz would say nothing. Sent regardless of
229
+ // whether that message still exists: deleting it doesn't recall it.
230
+ reply_parameters: { message_id: entry.messageId, allow_sending_without_reply: true },
231
+ reply_markup: ackKeyboard(entry),
232
+ disable_notification: true,
233
+ ...(entry.threadId !== undefined ? { message_thread_id: entry.threadId } : {}),
234
+ });
235
+ return sent.message_id;
236
+ }
237
+ catch (err) {
238
+ console.warn('[Queued] Could not post the ack:', sanitizeError(err));
239
+ return undefined;
240
+ }
241
+ }
242
+ function stopAckTimer(entry) {
243
+ if (!entry.ackTimer)
244
+ return;
245
+ clearTimeout(entry.ackTimer);
246
+ entry.ackTimer = null;
247
+ }
248
+ /** Note a message that has just arrived. Null when it isn't one we track. */
249
+ function noteArrival(ctx) {
250
+ const msg = ctx.message;
251
+ const keyInfo = getSessionKeyFromCtx(ctx);
252
+ if (!msg || !keyInfo || isStaleMessage(msg.date))
253
+ return null;
254
+ const forClaude = boundForClaude(msg);
255
+ if (forClaude === null)
256
+ return null;
257
+ // Telegram redelivering one that's already waiting. Its copy passes through
258
+ // to the handlers, which have their own duplicate check.
259
+ const key = entryKey(keyInfo.chatId, msg.message_id);
260
+ if (queued.has(key))
261
+ return null;
262
+ const steering = steered.delete(key);
263
+ if (forClaude && config.CANCEL_ON_NEW_MESSAGE && isProcessing(keyInfo.sessionKey)) {
264
+ takeBackAllQueued(ctx.api, keyInfo.sessionKey);
265
+ clearQueue(keyInfo.sessionKey);
266
+ void cancelRequest(keyInfo.sessionKey);
267
+ }
268
+ const { api } = ctx;
269
+ // A slash command typed at Claude means something to the conversation it's
270
+ // in, so it neither goes on the side nor somewhere new.
271
+ const typed = msg.text ?? msg.caption ?? '';
272
+ const command = typed.trimStart().startsWith('/');
273
+ const entry = {
274
+ chatId: keyInfo.chatId,
275
+ threadId: keyInfo.threadId,
276
+ sessionKey: keyInfo.sessionKey,
277
+ messageId: msg.message_id,
278
+ senderId: ctx.from?.id,
279
+ update: ctx.update,
280
+ forClaude,
281
+ takenBack: false,
282
+ parked: false,
283
+ canBtw: forClaude && msg.text !== undefined && msg.text.trim() !== '' && !command,
284
+ canFork: forClaude && !command && ctx.chat?.type === 'private' && ctx.me?.has_topics_enabled === true,
285
+ diverting: false,
286
+ steering,
287
+ ackTimer: null,
288
+ ack: null,
289
+ };
290
+ entry.ackTimer = setTimeout(() => {
291
+ entry.ackTimer = null;
292
+ entry.ack = postAck(api, entry);
293
+ }, ACK_DELAY_MS);
294
+ queued.set(key, entry);
295
+ inFlight.set(entry.sessionKey, (inFlight.get(entry.sessionKey) ?? 0) + 1);
296
+ return entry;
297
+ }
298
+ function noteHandled(sessionKey) {
299
+ const remaining = (inFlight.get(sessionKey) ?? 0) - 1;
300
+ if (remaining > 0)
301
+ inFlight.set(sessionKey, remaining);
302
+ else
303
+ inFlight.delete(sessionKey);
304
+ }
305
+ /** The wait is over and the message is going through, so the ack has served. */
306
+ function release(api, entry) {
307
+ const key = entryKey(entry.chatId, entry.messageId);
308
+ if (queued.get(key) !== entry)
309
+ return;
310
+ queued.delete(key);
311
+ stopAckTimer(entry);
312
+ void entry.ack
313
+ ?.then((ackId) => (ackId === undefined ? undefined : api.deleteMessage(entry.chatId, ackId)))
314
+ .catch((err) => console.warn('[Queued] Could not remove the ack:', sanitizeError(err)));
315
+ }
316
+ /**
317
+ * Mark a message so `holdQueuedMessage` drops it, and say so on its ack. It stays
318
+ * registered until it gets there, so the update can still be told apart from one
319
+ * that was never tracked.
320
+ */
321
+ function takeBack(api, entry, notice) {
322
+ entry.takenBack = true;
323
+ stopAckTimer(entry);
324
+ void entry.ack
325
+ ?.then((ackId) => (ackId === undefined
326
+ ? undefined
327
+ : api.editMessageText(entry.chatId, ackId, notice, { reply_markup: { inline_keyboard: [] } })))
328
+ .catch((err) => console.warn('[Queued] Could not update the ack:', sanitizeError(err)));
329
+ }
330
+ /**
331
+ * Drop every message waiting in a session. Call this before stopping the running
332
+ * turn, because the end of that turn is what lets the next message through. One
333
+ * set aside isn't going anywhere by itself, so it stays set aside.
334
+ */
335
+ export function takeBackAllQueued(api, sessionKey, keep) {
336
+ let count = 0;
337
+ for (const entry of queued.values()) {
338
+ if (entry === keep || entry.sessionKey !== sessionKey || entry.takenBack || entry.parked)
339
+ continue;
340
+ takeBack(api, entry, CANCELLED);
341
+ count++;
342
+ }
343
+ return count;
344
+ }
345
+ /**
346
+ * What /cancel does to a session: drop what's waiting, withdraw a request for a
347
+ * secret, and stop the turn, whoever started it. `keep` stays in line, to go once
348
+ * the turn has stopped. Whether anything was stopped, and how many were dropped.
349
+ */
350
+ export async function stopTurn(api, sessionKey, keep) {
351
+ // First, because the turn ending is what would let them through.
352
+ const takenBack = takeBackAllQueued(api, sessionKey, keep);
353
+ // Before the turn, too: until the request is withdrawn, the next message
354
+ // would still be taken for the secret it asked for.
355
+ const secretCancelled = cancelSecretRequest(sessionKey);
356
+ // A turn claude started itself has no handle for cancelRequest to find.
357
+ const stopped = await cancelRequest(sessionKey) || getPtyProvider().interruptOwnTurn(sessionKey) || secretCancelled;
358
+ return { stopped, dropped: takenBack + clearQueue(sessionKey) };
359
+ }
360
+ function parkedFile() {
361
+ return path.join(getStateDir(), `parked-messages-${BOT_ID}.json`);
362
+ }
363
+ function saveParked() {
364
+ ensureStateDir(getStateDir(), 'Queued');
365
+ writeJsonFile(parkedFile(), { messages: [...parked.values()] }, 'Queued');
366
+ }
367
+ /** Called once, before updates flow, so a tap on an old question finds its message. */
368
+ export function initParkedMessages(bot) {
369
+ botRef = bot;
370
+ const schema = z.object({ messages: z.array(parkedMessageSchema) });
371
+ for (const message of readJsonFile(parkedFile(), schema, 'Queued')?.messages ?? []) {
372
+ parked.set(entryKey(message.chatId, message.messageId), message);
373
+ }
374
+ }
375
+ /** Forget what's in memory, leaving the file. Test seam, standing in for a restart. */
376
+ export function forgetParkedMessages() {
377
+ parked.clear();
378
+ unreachable.clear();
379
+ if (reminderTimer)
380
+ clearInterval(reminderTimer);
381
+ reminderTimer = null;
382
+ reminding = false;
383
+ }
384
+ /** Whether Claude is on a turn in the session, whoever started it. */
385
+ function turnRunning(sessionKey) {
386
+ return isProcessing(sessionKey)
387
+ || getPtyProvider().isSessionGenerating(sessionKey)
388
+ || hasSelfStartedTurn(sessionKey);
389
+ }
390
+ /**
391
+ * Whether the session has nothing left that would change the answer the question
392
+ * is about. Background tasks don't count: they can run for hours with the session
393
+ * free, and if one reports back, a question already asked still stands.
394
+ */
395
+ function sessionIsIdle(sessionKey) {
396
+ return !inFlight.has(sessionKey) && !turnRunning(sessionKey);
397
+ }
398
+ /** Post the question, or post it again below a newer reply. */
399
+ async function postReminder(api, key, message) {
400
+ const again = message.reminderId !== undefined;
401
+ try {
402
+ const sent = await api.sendMessage(message.chatId, REMINDER, {
403
+ // Unlike the ack this does buzz: its whole job is to reach someone who has
404
+ // looked away. Asked again it doesn't, since that only keeps it in view.
405
+ // The message it hangs off is what shows what's being asked about, and
406
+ // stays right if that message is edited.
407
+ reply_parameters: { message_id: message.messageId, allow_sending_without_reply: true },
408
+ reply_markup: {
409
+ inline_keyboard: [[
410
+ { text: '📤 Send', callback_data: `${CALLBACK_PREFIX}send:${message.messageId}` },
411
+ { text: '🗑 Drop', callback_data: `${CALLBACK_PREFIX}drop:${message.messageId}` },
412
+ ]],
413
+ },
414
+ ...(again ? { disable_notification: true } : {}),
415
+ ...(message.threadId !== undefined ? { message_thread_id: message.threadId } : {}),
416
+ });
417
+ // The notice, or the question this one replaces, would only sit above the
418
+ // reply saying what this now says below it.
419
+ const superseded = again ? message.reminderId : message.noticeId;
420
+ message.reminderId = sent.message_id;
421
+ delete message.noticeId;
422
+ delete message.repost;
423
+ saveParked();
424
+ if (superseded !== undefined) {
425
+ void api.deleteMessage(message.chatId, superseded)
426
+ .catch((err) => console.warn('[Queued] Could not take down what the question replaces:', sanitizeError(err)));
427
+ }
428
+ }
429
+ catch (err) {
430
+ console.warn(`[Queued] Could not ask about message ${message.messageId}:`, sanitizeError(err));
431
+ // Telegram said no, so asking again every poll won't help. Anything else has
432
+ // been through auto-retry already, and the next poll is one more try.
433
+ if (err instanceof GrammyError)
434
+ unreachable.add(key);
435
+ }
436
+ }
437
+ async function remindWhereIdle() {
438
+ if (reminding)
439
+ return;
440
+ reminding = true;
441
+ try {
442
+ const watched = [...parked].filter(([key]) => !unreachable.has(key));
443
+ if (watched.length === 0 && reminderTimer) {
444
+ clearInterval(reminderTimer);
445
+ reminderTimer = null;
446
+ }
447
+ for (const [key, message] of watched) {
448
+ if (!botRef)
449
+ break;
450
+ const running = turnRunning(message.sessionKey);
451
+ // Set aside while nothing was running: the next turn is what it's waiting for.
452
+ if (message.awaitsTurn) {
453
+ if (running) {
454
+ delete message.awaitsTurn;
455
+ saveParked();
456
+ }
457
+ continue;
458
+ }
459
+ // Asked already. A turn running now leaves the question above its reply,
460
+ // so once that's over it's asked again below.
461
+ if (message.reminderId !== undefined) {
462
+ if (running && !message.repost) {
463
+ message.repost = true;
464
+ saveParked();
465
+ }
466
+ if (!message.repost)
467
+ continue;
468
+ }
469
+ if (!sessionIsIdle(message.sessionKey))
470
+ continue;
471
+ // A turn Claude started itself is only over once its reply is in the chat,
472
+ // and the question belongs below that.
473
+ await whenRepliesSent(message.sessionKey);
474
+ if (parked.get(key) === message)
475
+ await postReminder(botRef.api, key, message);
476
+ }
477
+ }
478
+ finally {
479
+ reminding = false;
480
+ }
481
+ }
482
+ /**
483
+ * Start looking for the moment to ask, for as long as anything is set aside. It
484
+ * polls because the turn ending is only one of the things it's waiting for, and
485
+ * the poll only runs while something is set aside.
486
+ */
487
+ export function armReminders() {
488
+ if (reminderTimer)
489
+ return;
490
+ reminderTimer = setInterval(() => void remindWhereIdle(), REMIND_POLL_MS);
491
+ reminderTimer.unref();
492
+ }
493
+ /**
494
+ * Take the command off, leaving the idea as the message Claude will get. The
495
+ * command entity would then point at nothing, and nothing downstream reads
496
+ * entities, which is also what lets the mention gate rewrite text in place.
497
+ */
498
+ function stripCommand(msg, command) {
499
+ if (typeof msg.text !== 'string')
500
+ return;
501
+ msg.text = msg.text.replace(command, '');
502
+ delete msg.entities;
503
+ }
504
+ async function postNotice(api, message, text) {
505
+ try {
506
+ const sent = await api.sendMessage(message.chatId, text, {
507
+ // Answering the person who just typed it, who is looking at the chat.
508
+ reply_parameters: { message_id: message.messageId, allow_sending_without_reply: true },
509
+ reply_markup: { inline_keyboard: [[takeBackButton(message.messageId)]] },
510
+ disable_notification: true,
511
+ ...(message.threadId !== undefined ? { message_thread_id: message.threadId } : {}),
512
+ });
513
+ return sent.message_id;
514
+ }
515
+ catch (err) {
516
+ console.warn('[Queued] Could not post the notice:', sanitizeError(err));
517
+ return undefined;
518
+ }
519
+ }
520
+ function firstLine(text) {
521
+ const line = text.trim().split('\n')[0] ?? '';
522
+ return line.length > 80 ? `${line.slice(0, 79)}…` : line;
523
+ }
524
+ /** One line of the list: what the message says, and what it's waiting for. */
525
+ function describeSetAside(message) {
526
+ const msg = message.update.message;
527
+ const words = msg.text ?? msg.caption;
528
+ const what = words !== undefined && words.trim()
529
+ ? firstLine(words)
530
+ : msg.voice ? '🎤 voice note' : msg.photo ? '🖼 photo' : msg.document ? '📎 file' : 'message';
531
+ const state = message.reminderId !== undefined ? 'asked, see below the reply'
532
+ : message.awaitsTurn ? "after Claude's next turn"
533
+ : 'when Claude is done';
534
+ return `${what} · ${state}`;
535
+ }
536
+ async function listSetAside(ctx, sessionKey) {
537
+ const mine = [...parked.values()]
538
+ .filter((message) => message.sessionKey === sessionKey)
539
+ .sort((a, b) => a.messageId - b.messageId);
540
+ if (mine.length === 0) {
541
+ await ctx.reply(NOTHING_SET_ASIDE);
542
+ return;
543
+ }
544
+ const lines = mine.map((message, i) => `${i + 1}. ${describeSetAside(message)}`);
545
+ await ctx.reply([LIST_HEADING, ...lines, '', LIST_FOOTER].join('\n'));
546
+ }
547
+ /**
548
+ * `/later <text>`: set an idea aside without it reaching Claude. Asked about once
549
+ * Claude is done, or after the next turn if nothing is running, since asking at
550
+ * once would be no help. On its own, lists what's set aside in the chat. Registered
551
+ * ahead of sequentialize, or it would wait behind the very turn it's meant to
552
+ * outlast.
553
+ */
554
+ export async function handleLater(ctx) {
555
+ const msg = ctx.message;
556
+ const keyInfo = getSessionKeyFromCtx(ctx);
557
+ if (!msg || typeof msg.text !== 'string' || !keyInfo)
558
+ return;
559
+ if (!msg.text.replace(LATER_COMMAND, '').trim())
560
+ return listSetAside(ctx, keyInfo.sessionKey);
561
+ const key = entryKey(keyInfo.chatId, msg.message_id);
562
+ // Telegram delivering it twice.
563
+ if (parked.has(key))
564
+ return;
565
+ const update = ctx.update;
566
+ stripCommand(update.message, LATER_COMMAND);
567
+ const awaitsTurn = !turnRunning(keyInfo.sessionKey);
568
+ const message = {
569
+ chatId: keyInfo.chatId,
570
+ threadId: keyInfo.threadId,
571
+ sessionKey: keyInfo.sessionKey,
572
+ messageId: msg.message_id,
573
+ senderId: ctx.from?.id,
574
+ update,
575
+ command: true,
576
+ ...(awaitsTurn ? { awaitsTurn: true } : {}),
577
+ };
578
+ parked.set(key, message);
579
+ saveParked();
580
+ armReminders();
581
+ console.log(`[Queued] Set message ${msg.message_id} in ${keyInfo.sessionKey} aside with /later`);
582
+ const noticeId = await postNotice(ctx.api, message, awaitsTurn ? PARKED_AFTER_NEXT_TURN : PARKED);
583
+ if (noticeId === undefined)
584
+ return;
585
+ if (parked.get(key) === message && message.reminderId === undefined) {
586
+ message.noticeId = noticeId;
587
+ saveParked();
588
+ }
589
+ else {
590
+ // Dealt with, or asked about, while the notice was on its way.
591
+ void ctx.api.deleteMessage(keyInfo.chatId, noticeId)
592
+ .catch((err) => console.warn('[Queued] Could not remove the notice:', sanitizeError(err)));
593
+ }
594
+ }
595
+ /**
596
+ * `/steer <text>`: stop the running turn and send `<text>` in its place. The stop
597
+ * comes first, so the message isn't dropped along with what was waiting, and it
598
+ * then waits for the turn to end like any other. With nothing running it's just
599
+ * a message: stopping nothing would still end background work a turn left going.
600
+ * Registered ahead of sequentialize, or it would wait behind the turn it stops.
601
+ */
602
+ export async function handleSteer(ctx) {
603
+ const msg = ctx.message;
604
+ const keyInfo = getSessionKeyFromCtx(ctx);
605
+ if (!msg || typeof msg.text !== 'string' || !keyInfo || !botRef)
606
+ return;
607
+ if (!msg.text.replace(STEER_COMMAND, '').trim()) {
608
+ await ctx.reply(STEER_USAGE);
609
+ return;
610
+ }
611
+ const update = ctx.update;
612
+ stripCommand(update.message, STEER_COMMAND);
613
+ if (turnRunning(keyInfo.sessionKey)) {
614
+ await stopTurn(ctx.api, keyInfo.sessionKey);
615
+ steered.add(entryKey(keyInfo.chatId, msg.message_id));
616
+ console.log(`[Queued] Stopped the turn in ${keyInfo.sessionKey} for message ${msg.message_id}, sent with /steer`);
617
+ }
618
+ markAlreadyAddressed(update);
619
+ void botRef.handleUpdate(update).catch((err) => {
620
+ console.error(`[Queued] Sending message ${msg.message_id} with /steer failed:`, sanitizeError(err));
621
+ });
622
+ }
623
+ /** Back through the whole chain, as if it had just arrived. */
624
+ function sendParked(message) {
625
+ const { update } = message;
626
+ // Handlers ignore a message from before the bot started, which this is after
627
+ // any restart since it arrived.
628
+ update.message.date = Math.floor(Date.now() / 1000);
629
+ markAlreadyAddressed(update);
630
+ void botRef?.handleUpdate(update).catch((err) => {
631
+ console.error(`[Queued] Sending set-aside message ${message.messageId} failed:`, sanitizeError(err));
632
+ });
633
+ }
634
+ /** Until nothing stands between this message and Claude, or it left the line. */
635
+ async function waitForClaude(entry) {
636
+ let ownTurnSince = null;
637
+ while (!entry.takenBack && !entry.parked) {
638
+ if (entry.diverting || isProcessing(entry.sessionKey)) {
639
+ ownTurnSince = null;
640
+ }
641
+ else if (!getPtyProvider().isSessionGenerating(entry.sessionKey)) {
642
+ return;
643
+ }
644
+ else {
645
+ ownTurnSince ??= Date.now();
646
+ if (Date.now() - ownTurnSince >= OWN_TURN_CEILING_MS)
647
+ return;
648
+ }
649
+ await new Promise((resolve) => setTimeout(resolve, HOLD_POLL_MS));
650
+ }
651
+ }
652
+ /** Registered just ahead of sequentialize. */
653
+ export const trackQueuedMessage = async (ctx, next) => {
654
+ const entry = noteArrival(ctx);
655
+ if (!entry)
656
+ return next();
657
+ try {
658
+ await next();
659
+ }
660
+ finally {
661
+ // Long gone on the normal path. This is for a chain that threw before it
662
+ // reached holdQueuedMessage, which would otherwise leave the entry behind.
663
+ release(ctx.api, entry);
664
+ noteHandled(entry.sessionKey);
665
+ }
666
+ };
667
+ /** Registered just behind sequentialize. */
668
+ export const holdQueuedMessage = async (ctx, next) => {
669
+ const msg = ctx.message;
670
+ const chatId = ctx.chat?.id;
671
+ const found = msg && chatId !== undefined ? queued.get(entryKey(chatId, msg.message_id)) : undefined;
672
+ // A message asked in a fork arrives again under its own id, in the fork's
673
+ // thread, while the original is still being dropped here.
674
+ const entry = found?.sessionKey === getSessionKeyFromCtx(ctx)?.sessionKey ? found : undefined;
675
+ if (!entry)
676
+ return next();
677
+ if (entry.forClaude)
678
+ await waitForClaude(entry);
679
+ if (entry.takenBack || entry.parked) {
680
+ queued.delete(entryKey(entry.chatId, entry.messageId));
681
+ const why = entry.takenBack ? 'taken back before it reached Claude' : 'set aside until its sender decides';
682
+ console.log(`[Queued] Dropped message ${entry.messageId} in ${entry.sessionKey}: ${why}`);
683
+ return;
684
+ }
685
+ release(ctx.api, entry);
686
+ return next();
687
+ };
688
+ /**
689
+ * An edit to a message that hasn't gone out yet is what should go out. Telegram
690
+ * sends the whole message again, and the handlers read the update only when the
691
+ * wait is over, so swapping it in is all there is to it.
692
+ */
693
+ export async function handleEditedMessage(ctx) {
694
+ const edited = ctx.editedMessage;
695
+ if (!edited)
696
+ return;
697
+ const key = entryKey(edited.chat.id, edited.message_id);
698
+ const setAside = parked.get(key);
699
+ const waiting = queued.get(key) ?? setAside;
700
+ if (!waiting)
701
+ return;
702
+ if (wasBatched(waiting.update.message)) {
703
+ console.log(`[Queued] Ignored an edit to message ${edited.message_id}: merged with the messages after it`);
704
+ return;
705
+ }
706
+ // The gate did this for the message as it arrived, and passes edits untouched.
707
+ if (config.GROUP_REQUIRE_MENTION)
708
+ stripBotMention(edited, ctx.me);
709
+ // As did /later's handler, which an edit doesn't reach either.
710
+ if (setAside?.command)
711
+ stripCommand(edited, LATER_COMMAND);
712
+ waiting.update.message = edited;
713
+ if (setAside)
714
+ saveParked();
715
+ }
716
+ function maySettle(ctx, senderId) {
717
+ return ctx.from?.id === senderId || isAdmin(ctx.from?.id);
718
+ }
719
+ async function answerNoLongerWaiting(ctx) {
720
+ await ctx.answerCallbackQuery({ text: 'This message is no longer waiting.' });
721
+ // A restart forgets what was waiting and leaves its ack standing, promising
722
+ // a delivery that won't come.
723
+ try {
724
+ await ctx.editMessageText(NO_LONGER_WAITING, { reply_markup: { inline_keyboard: [] } });
725
+ }
726
+ catch {
727
+ // Its turn has started, and the ack is already gone or about to be.
728
+ }
729
+ }
730
+ async function handleTakeBackTap(ctx, key) {
731
+ const entry = queued.get(key);
732
+ // Set aside, perhaps with its place in line long gone.
733
+ const setAside = parked.get(key);
734
+ const sender = entry ?? setAside;
735
+ if (!sender)
736
+ return answerNoLongerWaiting(ctx);
737
+ if (entry?.takenBack) {
738
+ await ctx.answerCallbackQuery({ text: 'Already taken back.' });
739
+ return;
740
+ }
741
+ if (!maySettle(ctx, sender.senderId)) {
742
+ await ctx.answerCallbackQuery({ text: NOT_YOURS, show_alert: true });
743
+ return;
744
+ }
745
+ if (setAside) {
746
+ parked.delete(key);
747
+ saveParked();
748
+ }
749
+ if (entry) {
750
+ takeBack(ctx.api, entry, TAKEN_BACK);
751
+ }
752
+ else {
753
+ try {
754
+ await ctx.editMessageText(TAKEN_BACK, { reply_markup: { inline_keyboard: [] } });
755
+ }
756
+ catch (err) {
757
+ console.warn('[Queued] Could not update the notice:', sanitizeError(err));
758
+ }
759
+ }
760
+ await ctx.answerCallbackQuery({ text: 'Taken back.' });
761
+ }
762
+ async function handleParkTap(ctx, key) {
763
+ const entry = queued.get(key);
764
+ if (!entry)
765
+ return answerNoLongerWaiting(ctx);
766
+ if (entry.takenBack || entry.parked) {
767
+ await ctx.answerCallbackQuery({ text: entry.takenBack ? 'Already taken back.' : 'Already set aside.' });
768
+ return;
769
+ }
770
+ if (!maySettle(ctx, entry.senderId)) {
771
+ await ctx.answerCallbackQuery({ text: NOT_YOURS, show_alert: true });
772
+ return;
773
+ }
774
+ // Before anything that awaits, or the turn could end and let the message through.
775
+ entry.parked = true;
776
+ parked.set(key, {
777
+ chatId: entry.chatId,
778
+ threadId: entry.threadId,
779
+ sessionKey: entry.sessionKey,
780
+ messageId: entry.messageId,
781
+ senderId: entry.senderId,
782
+ update: entry.update,
783
+ noticeId: ctx.callbackQuery?.message?.message_id,
784
+ });
785
+ saveParked();
786
+ armReminders();
787
+ await ctx.answerCallbackQuery({ text: 'Set aside.' });
788
+ try {
789
+ await ctx.editMessageText(PARKED, { reply_markup: { inline_keyboard: [[takeBackButton(entry.messageId)]] } });
790
+ }
791
+ catch (err) {
792
+ console.warn('[Queued] Could not update the ack:', sanitizeError(err));
793
+ }
794
+ }
795
+ /** The checks every button on the ack makes first. The entry when the tap can go ahead. */
796
+ async function claimWaiting(ctx, key) {
797
+ const entry = queued.get(key);
798
+ if (!entry) {
799
+ await answerNoLongerWaiting(ctx);
800
+ return undefined;
801
+ }
802
+ if (entry.takenBack || entry.parked || entry.diverting || entry.steering) {
803
+ await ctx.answerCallbackQuery({
804
+ text: entry.takenBack ? 'Already taken back.'
805
+ : entry.parked ? 'Already set aside.'
806
+ : entry.diverting ? 'Already opening a fork.'
807
+ : 'Already stopping the turn for it.',
808
+ });
809
+ return undefined;
810
+ }
811
+ if (!maySettle(ctx, entry.senderId)) {
812
+ await ctx.answerCallbackQuery({ text: NOT_YOURS, show_alert: true });
813
+ return undefined;
814
+ }
815
+ return entry;
816
+ }
817
+ async function handleBtwTap(ctx, key) {
818
+ const entry = await claimWaiting(ctx, key);
819
+ const question = entry?.update.message.text?.trim();
820
+ if (!entry || !question || !diverters)
821
+ return;
822
+ // Before anything that awaits, or the turn could end and let it through as well.
823
+ takeBack(ctx.api, entry, ASKED_AS_BTW);
824
+ console.log(`[Queued] Asked message ${entry.messageId} in ${entry.sessionKey} as /btw`);
825
+ await ctx.answerCallbackQuery({ text: 'Asking on the side.' });
826
+ // Not awaited: the answer can take minutes, and the tap is done with.
827
+ const { btw } = diverters;
828
+ void btw(ctx, entry.sessionKey, question).catch((err) => {
829
+ console.error(`[Queued] /btw for message ${entry.messageId} failed:`, sanitizeError(err));
830
+ });
831
+ }
832
+ async function handleSteerTap(ctx, key) {
833
+ const entry = await claimWaiting(ctx, key);
834
+ if (!entry)
835
+ return;
836
+ // Set at once, so a second tap can't stop a turn that has already moved on to this one.
837
+ entry.steering = true;
838
+ // Started before anything else awaits, so what's waiting is dropped before the turn can end.
839
+ const stopping = stopTurn(ctx.api, entry.sessionKey, entry);
840
+ console.log(`[Queued] Stopping the turn in ${entry.sessionKey} for message ${entry.messageId}`);
841
+ await ctx.answerCallbackQuery({ text: 'Stopping the turn.' });
842
+ try {
843
+ await ctx.editMessageText(STEERING, { reply_markup: { inline_keyboard: [[takeBackButton(entry.messageId)]] } });
844
+ }
845
+ catch (err) {
846
+ console.warn('[Queued] Could not update the ack:', sanitizeError(err));
847
+ }
848
+ await stopping;
849
+ }
850
+ /**
851
+ * The message as if it had been sent in the new thread: the same update, with
852
+ * the thread's id on it, through the whole chain the way Send replays one.
853
+ */
854
+ function sendIntoThread(update, threadId) {
855
+ void replayIntoThread(update, threadId).catch((err) => {
856
+ console.error(`[Queued] Sending message ${update.message.message_id} into the fork failed:`, sanitizeError(err));
857
+ });
858
+ }
859
+ /**
860
+ * sendIntoThread's replay, for a caller that sends something of its own into a
861
+ * thread: `changes` go over the message first (its text, entities, id), and the
862
+ * promise settles once the whole chain has handled it, which for a prompt is
863
+ * once its turn is over. A different id is how two replays of one update stay
864
+ * apart: the message handler drops an id it has already seen as a retry.
865
+ */
866
+ export async function replayIntoThread(update, threadId, changes = {}) {
867
+ if (!update.message || !botRef)
868
+ return;
869
+ const copy = structuredClone(update);
870
+ Object.assign(copy.message, changes);
871
+ copy.message.message_thread_id = threadId;
872
+ copy.message.is_topic_message = true;
873
+ delete copy.message.reply_to_message;
874
+ copy.message.date = Math.floor(Date.now() / 1000);
875
+ markAlreadyAddressed(copy);
876
+ await botRef.handleUpdate(copy);
877
+ }
878
+ async function handleForkTap(ctx, key) {
879
+ const entry = await claimWaiting(ctx, key);
880
+ if (!entry || !diverters)
881
+ return;
882
+ // Holds its place while the thread is opened, so it can go back in line if
883
+ // that fails, and doesn't slip through to the running conversation meanwhile.
884
+ entry.diverting = true;
885
+ await ctx.answerCallbackQuery({ text: 'Opening a fork…' });
886
+ let opened;
887
+ try {
888
+ opened = await diverters.fork(ctx, entry.sessionKey, entry.update.message);
889
+ }
890
+ catch (err) {
891
+ console.error(`[Queued] Fork for message ${entry.messageId} failed:`, sanitizeError(err));
892
+ opened = { error: 'Could not open a fork.' };
893
+ }
894
+ if ('error' in opened) {
895
+ entry.diverting = false;
896
+ // Cancelled meanwhile, so there's no place in line to give back.
897
+ if (entry.takenBack)
898
+ return;
899
+ try {
900
+ await ctx.editMessageText(`${ackText(entry)}\n🍴 ${opened.error}`, { reply_markup: ackKeyboard(entry) });
901
+ }
902
+ catch (err) {
903
+ console.warn('[Queued] Could not update the ack:', sanitizeError(err));
904
+ }
905
+ return;
906
+ }
907
+ entry.diverting = false;
908
+ entry.takenBack = true;
909
+ stopAckTimer(entry);
910
+ console.log(`[Queued] Asked message ${entry.messageId} in ${entry.sessionKey} in a fork, thread ${opened.threadId}`);
911
+ sendIntoThread(entry.update, opened.threadId);
912
+ try {
913
+ await ctx.editMessageText(`${ASKED_IN_FORK} ${opened.name}`, {
914
+ reply_markup: {
915
+ inline_keyboard: opened.link ? [[{ text: `Open ${opened.name}`, url: opened.link }]] : [],
916
+ },
917
+ });
918
+ }
919
+ catch (err) {
920
+ console.warn('[Queued] Could not update the ack:', sanitizeError(err));
921
+ }
922
+ }
923
+ async function handleReminderTap(ctx, key, action) {
924
+ const message = parked.get(key);
925
+ if (!message) {
926
+ await ctx.answerCallbackQuery({ text: 'Already dealt with.' });
927
+ try {
928
+ await ctx.editMessageReplyMarkup();
929
+ }
930
+ catch {
931
+ // The tap that dealt with it took the buttons off already.
932
+ }
933
+ return;
934
+ }
935
+ if (!maySettle(ctx, message.senderId)) {
936
+ await ctx.answerCallbackQuery({ text: NOT_YOURS, show_alert: true });
937
+ return;
938
+ }
939
+ parked.delete(key);
940
+ saveParked();
941
+ if (action === 'send')
942
+ sendParked(message);
943
+ await ctx.answerCallbackQuery({ text: action === 'send' ? 'Sent.' : 'Dropped.' });
944
+ try {
945
+ await ctx.editMessageText(action === 'send' ? SENT : DROPPED, { reply_markup: { inline_keyboard: [] } });
946
+ }
947
+ catch (err) {
948
+ console.warn('[Queued] Could not update the question:', sanitizeError(err));
949
+ }
950
+ }
951
+ /** The buttons in this file. Registered ahead of sequentialize, or they'd wait in line too. */
952
+ export async function handleQueuedCallback(ctx) {
953
+ const match = ctx.callbackQuery?.data?.match(CALLBACK_PATTERN);
954
+ const chatId = ctx.chat?.id;
955
+ if (!match || chatId === undefined)
956
+ return;
957
+ const action = match[1];
958
+ const key = entryKey(chatId, Number(match[2]));
959
+ if (action === 'park')
960
+ return handleParkTap(ctx, key);
961
+ if (action === 'send' || action === 'drop')
962
+ return handleReminderTap(ctx, key, action);
963
+ if (action === 'btw')
964
+ return handleBtwTap(ctx, key);
965
+ if (action === 'fork')
966
+ return handleForkTap(ctx, key);
967
+ if (action === 'steer')
968
+ return handleSteerTap(ctx, key);
969
+ return handleTakeBackTap(ctx, key);
970
+ }
971
+ //# sourceMappingURL=queued-messages.js.map