switchroom 0.18.7 → 0.18.9

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 (85) hide show
  1. package/README.md +2 -2
  2. package/dist/cli/switchroom.js +905 -758
  3. package/dist/host-control/main.js +1 -1
  4. package/package.json +1 -1
  5. package/profiles/_base/start.sh.hbs +111 -34
  6. package/skills/switchroom-runtime/SKILL.md +2 -0
  7. package/telegram-plugin/dist/gateway/gateway.js +46273 -44324
  8. package/telegram-plugin/flood-circuit-breaker.ts +123 -0
  9. package/telegram-plugin/gateway/activity-card-store.ts +63 -18
  10. package/telegram-plugin/gateway/approval-card-stores.ts +99 -0
  11. package/telegram-plugin/gateway/boot-card.ts +27 -0
  12. package/telegram-plugin/gateway/bot-commands-ops-info.ts +194 -0
  13. package/telegram-plugin/gateway/busy-ack.ts +106 -0
  14. package/telegram-plugin/gateway/callback-query-handlers.ts +2660 -0
  15. package/telegram-plugin/gateway/gateway.ts +1169 -3043
  16. package/telegram-plugin/gateway/inbound-delivery-machine-dispatch.ts +181 -23
  17. package/telegram-plugin/gateway/inbound-delivery-machine.ts +8 -0
  18. package/telegram-plugin/gateway/mental-model-propose-diff.ts +61 -5
  19. package/telegram-plugin/gateway/model-command.ts +23 -11
  20. package/telegram-plugin/gateway/outbound-send-path.ts +375 -0
  21. package/telegram-plugin/gateway/pending-state-stores.ts +106 -0
  22. package/telegram-plugin/gateway/register-bot-commands.ts +30 -0
  23. package/telegram-plugin/gateway/session-model-file.ts +198 -0
  24. package/telegram-plugin/gateway/status-pin-store.ts +82 -22
  25. package/telegram-plugin/gateway/worker-pin-reaper.ts +114 -0
  26. package/telegram-plugin/hooks/hooks.json +10 -10
  27. package/telegram-plugin/hooks/run-hook.sh +84 -0
  28. package/telegram-plugin/model-unavailable.ts +26 -0
  29. package/telegram-plugin/pty-partial-handler.ts +39 -0
  30. package/telegram-plugin/render/rich-render.ts +79 -1
  31. package/telegram-plugin/retry-api-call.ts +62 -0
  32. package/telegram-plugin/shared/bot-runtime.ts +8 -1
  33. package/telegram-plugin/silence-poke.ts +14 -0
  34. package/telegram-plugin/stream-controller.ts +156 -38
  35. package/telegram-plugin/tests/activity-card-store.test.ts +47 -2
  36. package/telegram-plugin/tests/approval-card-restart-outcome.test.ts +218 -0
  37. package/telegram-plugin/tests/approval-card-stores.test.ts +124 -0
  38. package/telegram-plugin/tests/boot-card-flood-suppress.test.ts +111 -0
  39. package/telegram-plugin/tests/busy-ack-wiring.test.ts +118 -0
  40. package/telegram-plugin/tests/busy-ack.test.ts +121 -0
  41. package/telegram-plugin/tests/callback-query-handlers.test.ts +701 -0
  42. package/telegram-plugin/tests/emission-determinism-wiring.test.ts +11 -4
  43. package/telegram-plugin/tests/fixtures/cutover-killswitch-probe.ts +75 -0
  44. package/telegram-plugin/tests/flood-circuit-breaker.test.ts +74 -0
  45. package/telegram-plugin/tests/gateway-outbound-redact.test.ts +5 -1
  46. package/telegram-plugin/tests/gateway-session-model-relaunch.test.ts +177 -25
  47. package/telegram-plugin/tests/inbound-delivery-cutover-flip.test.ts +418 -0
  48. package/telegram-plugin/tests/inbound-delivery-dispatch-equivalence.test.ts +348 -0
  49. package/telegram-plugin/tests/inbound-delivery-machine-dispatch.test.ts +141 -52
  50. package/telegram-plugin/tests/mental-model-name-entity-corruption.test.ts +119 -0
  51. package/telegram-plugin/tests/mental-model-propose-callback-gate.test.ts +8 -1
  52. package/telegram-plugin/tests/model-command.test.ts +2 -2
  53. package/telegram-plugin/tests/model-unavailable.test.ts +41 -0
  54. package/telegram-plugin/tests/outbound-send-chunks.test.ts +304 -0
  55. package/telegram-plugin/tests/outbound-send-path.test.ts +222 -0
  56. package/telegram-plugin/tests/pending-card-durability-wiring.test.ts +34 -15
  57. package/telegram-plugin/tests/pending-state-stores.test.ts +235 -0
  58. package/telegram-plugin/tests/pty-partial-handler.test.ts +56 -0
  59. package/telegram-plugin/tests/render/render-outbound-chunks.test.ts +98 -0
  60. package/telegram-plugin/tests/retry-api-call.test.ts +59 -0
  61. package/telegram-plugin/tests/run-hook-wrapper.test.ts +132 -0
  62. package/telegram-plugin/tests/session-model-file.test.ts +132 -0
  63. package/telegram-plugin/tests/slot-banner-boot-recovery.test.ts +3 -3
  64. package/telegram-plugin/tests/status-pin-boot-recovery.test.ts +3 -3
  65. package/telegram-plugin/tests/status-pin-store.test.ts +62 -6
  66. package/telegram-plugin/tests/stream-controller-chunk-cap.test.ts +122 -0
  67. package/telegram-plugin/tests/turn-flush-safety.test.ts +18 -4
  68. package/telegram-plugin/tests/vault-approval-posture.test.ts +15 -7
  69. package/telegram-plugin/tests/vault-grant-auto-resume.test.ts +8 -4
  70. package/telegram-plugin/tests/vault-grant-union.test.ts +8 -4
  71. package/telegram-plugin/tests/vault-grant-wizard.test.ts +8 -1
  72. package/telegram-plugin/tests/vault-grants-revoke.test.ts +8 -1
  73. package/telegram-plugin/tests/vault-key-regex-allows-slash.test.ts +8 -4
  74. package/telegram-plugin/tests/vault-request-access-tool.test.ts +8 -4
  75. package/telegram-plugin/tests/vault-request-access-unlock-resume.test.ts +8 -4
  76. package/telegram-plugin/tests/voice-send.test.ts +308 -0
  77. package/telegram-plugin/tests/worker-pin-reaper.test.ts +132 -0
  78. package/telegram-plugin/uat/scenarios/jtbd-deliberate-restart-resumes-dm.test.ts +118 -0
  79. package/telegram-plugin/uat/scenarios/jtbd-midflight-busy-ack-dm.test.ts +201 -0
  80. package/telegram-plugin/uat/scenarios/jtbd-worker-pin-lifecycle-dm.test.ts +208 -0
  81. package/telegram-plugin/uat/scenarios/vault-card-survives-gateway-restart-dm.test.ts +140 -0
  82. package/telegram-plugin/uat/scenarios/vault-deny-resumes-turn-dm.test.ts +84 -0
  83. package/telegram-plugin/uat/scenarios/vault-timeout-wakes-agent-dm.test.ts +91 -0
  84. package/telegram-plugin/voice-ondemand.ts +25 -1
  85. package/telegram-plugin/voice-send.ts +154 -0
@@ -0,0 +1,375 @@
1
+ // Outbound send-path — deterministic text pipeline + chunking core (#2996).
2
+ //
3
+ // Phase 2 of the gateway.ts decomposition (issue #2996, plan §3B). This
4
+ // module owns the pure, side-effect-free heart of the reply/stream/turn-flush
5
+ // outbound pipeline: the normalize → redact → punctuation/bold → voice-scrub
6
+ // text transform, the effective-text spacing decision, the length-limit
7
+ // chunking, and the oversize-chunk re-split. These are exactly the transforms
8
+ // where the recent oversize / redaction / voice-scrub regressions landed, and
9
+ // extracting them here makes them unit-testable in isolation (see
10
+ // outbound-send-path.test.ts golden snapshots).
11
+ //
12
+ // Deliberately NOT moved here (they stay in gateway.ts, delegating to this
13
+ // module): the side-effecting send orchestration — currentTurn pinning,
14
+ // emission-authority / over-ping decisions, activity-card finalize, voice
15
+ // synthesis + sends, typing loops, history recording, the shared
16
+ // `outboundDedup` singleton check/record, and the raw bot.api send loop with
17
+ // its partial-failure contract. Those read gateway module state and are not
18
+ // byte-identically relocatable without an invocable-executeReply harness that
19
+ // this pure-core extraction is itself the prerequisite for.
20
+ //
21
+ // currentTurn coupling (#1067/#1664): this module NEVER reads the currentTurn
22
+ // global. Every function here is pure over its arguments — turn identity is
23
+ // pinned by the caller and never observed here.
24
+
25
+ import {
26
+ repairEscapedWhitespace,
27
+ normalizeParagraphBreaks,
28
+ normalizePunctuation,
29
+ stripExcessBold,
30
+ addParagraphSpacers,
31
+ splitMarkdownChunks,
32
+ hardSliceToCap,
33
+ RICH_MESSAGE_MAX_CHARS,
34
+ } from '../format.js'
35
+ import { scrubVoice } from '../text-voice-scrub.js'
36
+ import { isMessageTooLongError, isHtmlParseRejectError } from '../retry-api-call.js'
37
+
38
+ /** The redactor the caller injects. In gateway this is `redactOutboundText`,
39
+ * which wraps `redact()` and logs (never the secret value) when a mask fires.
40
+ * Injected rather than imported so the redaction structural-wiring test
41
+ * (`gateway-outbound-redact.test.ts`) keeps pinning the helper in gateway.ts,
42
+ * and so this module stays free of the stderr side effect. */
43
+ export type RedactFn = (text: string, site: string) => string
44
+
45
+ export interface NormalizeOutboundResult {
46
+ /** The fully-normalized text. This is the value used downstream as the
47
+ * dedup key, the Telegraph threshold input, and (after effective-text
48
+ * spacing) the chunk source. Callers apply it exactly as the pre-#2996
49
+ * inline pipeline did. */
50
+ text: string
51
+ /** Number of voice-scrub replacements applied (dashes → commas/periods,
52
+ * opener strips). >0 means the voice scrub mutated the text; the caller
53
+ * emits the `voice_scrub_applied` runtime metric on that condition. */
54
+ voiceReplaced: number
55
+ }
56
+
57
+ /**
58
+ * Stage 1 — the deterministic outbound text transform, byte-identical to the
59
+ * inline pipeline at the entry of executeReply (and mirrored on the
60
+ * answer-stream + turn-flush paths):
61
+ *
62
+ * 1. repairEscapedWhitespace — undo LLM JSON-escape bungles
63
+ * 2. normalizeParagraphBreaks — promote lone prose breaks to GFM hard breaks
64
+ * 3. redact (injected) — outbound secret scrub (#2044), BEFORE the
65
+ * punctuation/bold normalizers so a secret with
66
+ * an em-dash or `**` is matched literally
67
+ * 4. stripExcessBold∘normalizePunctuation — fleet-consistent formatting
68
+ * 5. scrubVoice — em/en dash → comma/period (#1683)
69
+ *
70
+ * The order is load-bearing and MUST NOT change (each step's comment in the
71
+ * former inline site documents why). Pure over its arguments.
72
+ */
73
+ export function normalizeOutboundBody(
74
+ rawText: string,
75
+ site: string,
76
+ redact: RedactFn,
77
+ ): NormalizeOutboundResult {
78
+ let text = normalizeParagraphBreaks(repairEscapedWhitespace(rawText))
79
+ text = redact(text, site)
80
+ text = stripExcessBold(normalizePunctuation(text))
81
+ let voiceReplaced = 0
82
+ const scrub = scrubVoice(text)
83
+ if (scrub.replaced > 0) {
84
+ text = scrub.scrubbed
85
+ voiceReplaced = scrub.replaced
86
+ }
87
+ return { text, voiceReplaced }
88
+ }
89
+
90
+ /**
91
+ * Effective-text spacing (#2669 rich-message regression fix). The rich GFM
92
+ * renderer collapses `\n\n` gaps tight, so prose paragraphs render jammed.
93
+ * Inject a visible blank-line spacer on the rich path only; the literal
94
+ * (`format:'text'`) path stays byte-exact. Pure.
95
+ */
96
+ export function computeEffectiveText(text: string, literalText: boolean): string {
97
+ return literalText ? text : addParagraphSpacers(text)
98
+ }
99
+
100
+ /**
101
+ * Length-limit chunking. The literal path uses the newline/length `chunk()`
102
+ * splitter; the rich path uses `splitMarkdownChunks` (markdown-boundary-aware).
103
+ * Pure. `chunk` is passed in so the splitter (moved here as `chunkText`) and
104
+ * this decision stay colocated without a circular gateway import.
105
+ */
106
+ export function computeReplyChunks(args: {
107
+ effectiveText: string
108
+ literalText: boolean
109
+ limit: number
110
+ chunkMode: 'length' | 'newline'
111
+ }): string[] {
112
+ const { effectiveText, literalText, limit, chunkMode } = args
113
+ return literalText
114
+ ? chunkText(effectiveText, limit, chunkMode)
115
+ : splitMarkdownChunks(effectiveText, limit)
116
+ }
117
+
118
+ /**
119
+ * Oversize-chunk re-split (length-error recovery). A single pre-computed chunk
120
+ * can still exceed the wire cap when `splitMarkdownChunks` hit an indivisible
121
+ * region and emitted it whole (a giant fenced block, a no-boundary blob).
122
+ * Re-split at the hard `RICH_MESSAGE_MAX_CHARS` cap; for a truly indivisible
123
+ * block, fall back to a hard character cut so each delivered piece stays under
124
+ * the wire cap. Byte-identical to the inline `sendChunkResplit` piece
125
+ * computation. Pure.
126
+ */
127
+ export function resplitOversizeChunk(piece: string): string[] {
128
+ const subPieces = splitMarkdownChunks(piece, RICH_MESSAGE_MAX_CHARS)
129
+ return subPieces.length > 1 ? subPieces : hardSliceToCap(piece, RICH_MESSAGE_MAX_CHARS)
130
+ }
131
+
132
+ /**
133
+ * Length/newline text splitter (relocated verbatim from gateway.ts). Splits
134
+ * `text` into <= `limit`-char pieces. In `newline` mode it prefers a paragraph
135
+ * break, then a line break, then a space past the halfway point; `length` mode
136
+ * cuts hard at the limit. Pure.
137
+ */
138
+ export function chunkText(text: string, limit: number, mode: 'length' | 'newline'): string[] {
139
+ if (text.length <= limit) return [text]
140
+ const out: string[] = []
141
+ let rest = text
142
+ while (rest.length > limit) {
143
+ let cut = limit
144
+ if (mode === 'newline') {
145
+ const para = rest.lastIndexOf('\n\n', limit)
146
+ const line = rest.lastIndexOf('\n', limit)
147
+ const space = rest.lastIndexOf(' ', limit)
148
+ cut = para > limit / 2 ? para : line > limit / 2 ? line : space > 0 ? space : limit
149
+ }
150
+ out.push(rest.slice(0, cut))
151
+ rest = rest.slice(cut).replace(/^\n+/, '')
152
+ }
153
+ if (rest) out.push(rest)
154
+ return out
155
+ }
156
+
157
+ // ─── Send orchestration (#2996 step 1) ────────────────────────────────────
158
+ //
159
+ // The reply chunk-send loop, relocated VERBATIM from executeReply so it can be
160
+ // driven from a unit test against a fake bot API (see
161
+ // outbound-send-path.test.ts). This is the highest-bug-density mechanic of the
162
+ // send path — the recent oversize / wire-cap / parse-reject / THREAD_NOT_FOUND
163
+ // fallback fixes all landed HERE — and it was previously reachable only through
164
+ // the non-importable gateway monolith (gateway.ts runs boot logic + Bun.listen
165
+ // at import, so `executeReply` cannot be invoked from vitest/bun in-place).
166
+ //
167
+ // The module stays bot-agnostic: every Telegram send is an INJECTED function
168
+ // dep, so the raw `bot.api.*` calls (and their retry wrapping + allow-raw-bot-api
169
+ // markers) remain in gateway.ts, and a test passes fakes. The caller keeps
170
+ // building the per-chunk send/edit option objects (so the option shape stays
171
+ // byte-identical to the inline site and the deps surface stays small — 8), pins
172
+ // the turn, owns dedup/voice/history, and threads the shared `sentIds` array by
173
+ // reference. currentTurn is NEVER read here (#1067/#1664).
174
+
175
+ /** Injected Telegram send surface + logging for {@link sendReplyChunks}. In
176
+ * gateway these are thin adapters over `lockedBot.api.*` (retry-wrapped where
177
+ * the inline site wrapped them); in tests they are fakes recording call shape. */
178
+ export interface ReplyChunkSendDeps {
179
+ /** robustApiCall-wrapped rich send. Adapter: `sendRichMessage(richMessage(s))`.
180
+ * `threadId` (the live value) is passed into the robustApiCall meta so a
181
+ * thread-not-found 400 is converted to THREAD_NOT_FOUND, exactly as inline. */
182
+ sendRich: (opts: Record<string, unknown>, richBody: unknown, threadId: number | undefined) => Promise<{ message_id: number }>
183
+ /** robustApiCall-wrapped literal send. Adapter: `sendMessage(chunk)`. */
184
+ sendLiteral: (opts: Record<string, unknown>, text: string, threadId: number | undefined) => Promise<{ message_id: number }>
185
+ /** UNwrapped literal send (last-resort fallbacks that must NOT re-enter the
186
+ * retry policy that just rejected the payload). Adapter: raw `sendMessage`. */
187
+ sendLiteralRaw: (opts: Record<string, unknown>, text: string) => Promise<{ message_id: number }>
188
+ /** UNwrapped rich send (length-error re-split last resort). Adapter: raw
189
+ * `sendRichMessage(richMessage(piece))`. */
190
+ sendRichRaw: (opts: Record<string, unknown>, richBody: unknown) => Promise<{ message_id: number }>
191
+ /** robustApiCall-wrapped preview edit-in-place. */
192
+ editPreview: (messageId: number, body: unknown, opts: Record<string, unknown>, threadId: number | undefined) => Promise<unknown>
193
+ /** rich-markdown wrapper (`richMessage`). Applied to a chunk/piece string. */
194
+ richMessage: (s: string) => unknown
195
+ /** outbound logger (`logOutbound`). */
196
+ logOutbound: (path: 'reply', chatId: string, messageId: number, chars: number, extra?: string) => void
197
+ /** delete a stale preview message (`deleteStalePreview`). */
198
+ deleteStalePreview: (id: number) => Promise<void>
199
+ /** stderr sink (`process.stderr.write`). */
200
+ stderr: (s: string) => void
201
+ }
202
+
203
+ /** Mutable send state + per-chunk option builders for {@link sendReplyChunks}.
204
+ * The caller owns option shape (byte-identical to the inline site). */
205
+ export interface ReplyChunkSendState {
206
+ chatId: string
207
+ chunks: string[]
208
+ literalText: boolean
209
+ /** voice-only mode with a full synthesis skips the text body entirely. */
210
+ suppressText: boolean
211
+ /** current thread id; re-split/fallbacks may drop it (THREAD_NOT_FOUND). */
212
+ threadId: number | undefined
213
+ /** a stale draft-stream preview to edit-in-place on the first chunk, or null. */
214
+ previewMessageId: number | null
215
+ /** shared results array — appended in place (voice/file sends push too). */
216
+ sentIds: number[]
217
+ /** build the send-options object for chunk `i` (last-chunk flag + live thread). */
218
+ buildSendOpts: (i: number, isLastChunk: boolean, threadId: number | undefined) => Record<string, unknown>
219
+ /** build the preview edit-in-place options for the first chunk. */
220
+ buildPreviewEditOpts: (isLastChunk: boolean) => Record<string, unknown>
221
+ }
222
+
223
+ export interface ReplyChunkSendResult {
224
+ /** thread id after any THREAD_NOT_FOUND fallback (used by later file sends). */
225
+ threadId: number | undefined
226
+ /** preview id after consumption (null once edited/deleted). */
227
+ previewMessageId: number | null
228
+ }
229
+
230
+ /**
231
+ * Send the pre-computed reply chunks. Relocated verbatim from executeReply's
232
+ * chunk loop. Appends message ids to `state.sentIds` in order. On an
233
+ * unrecoverable send error it throws the raw error — the caller wraps it into
234
+ * the `reply failed after N of M chunk(s) sent` partial-failure contract and
235
+ * runs the typing-loop `finally`, exactly as before.
236
+ */
237
+ export async function sendReplyChunks(
238
+ deps: ReplyChunkSendDeps,
239
+ state: ReplyChunkSendState,
240
+ ): Promise<ReplyChunkSendResult> {
241
+ const { chatId, chunks, literalText, suppressText, sentIds } = state
242
+ let threadId = state.threadId
243
+ let previewMessageId = state.previewMessageId
244
+
245
+ for (let i = 0; i < chunks.length; i++) {
246
+ // PR-C2: voice-only mode with a successful synthesis suppresses the
247
+ // text body — the spoken voice note IS the reply. Bail before the
248
+ // first chunk send (sentIds stays empty for text); the voice send
249
+ // below lands the answer. Any other mode (voice+text, or voice-only
250
+ // that fell back) sends the text chunks as normal.
251
+ if (suppressText) break
252
+ const isLastChunk = i === chunks.length - 1
253
+ const sendOpts = state.buildSendOpts(i, isLastChunk, threadId)
254
+
255
+ if (i === 0 && previewMessageId != null) {
256
+ const editOpts = state.buildPreviewEditOpts(isLastChunk)
257
+ try {
258
+ await deps.editPreview(previewMessageId!, literalText ? chunks[i] : deps.richMessage(chunks[i]), editOpts, threadId)
259
+ sentIds.push(previewMessageId!)
260
+ previewMessageId = null
261
+ continue
262
+ } catch (err) {
263
+ const msg = err instanceof Error ? err.message : String(err)
264
+ if (/not modified/i.test(msg)) {
265
+ sentIds.push(previewMessageId!)
266
+ previewMessageId = null
267
+ continue
268
+ }
269
+ deps.stderr(`telegram gateway: preview edit-in-place failed (${msg}), sending fresh\n`)
270
+ await deps.deleteStalePreview(previewMessageId!)
271
+ previewMessageId = null
272
+ }
273
+ }
274
+
275
+ // Last-resort: resend this chunk as plain text (no rich wrapper, so
276
+ // the markdown parser never runs). Keeps thread / reply / markup
277
+ // params; only the formatting is sacrificed. Used when Telegram
278
+ // rejects our markdown — better an unformatted answer than a
279
+ // vanished one. The raw markdown source is itself readable prose, so
280
+ // we send it verbatim rather than strip anything.
281
+ const sendChunkPlainText = async (opts: Record<string, unknown>): Promise<void> => {
282
+ const plain =
283
+ chunks[i].length > 0
284
+ ? chunks[i]
285
+ : '⚠️ (a fragment could not be rendered for Telegram)'
286
+ const sent = await deps.sendLiteralRaw(opts, plain)
287
+ sentIds.push(sent.message_id)
288
+ deps.logOutbound('reply', chatId, sent.message_id, plain.length, `chunk=${i + 1}/${chunks.length} plaintext-fallback`)
289
+ deps.stderr(
290
+ `telegram gateway: markdown parse-reject — resent chunk ${i + 1}/${chunks.length} as plain text\n`,
291
+ )
292
+ }
293
+
294
+ // Literal `format:'text'` sends bypass the rich parser entirely
295
+ // (plain sendMessage, no markdown). The default path ships rich
296
+ // markdown via sendRichMessage. Both resolve to a Message with a
297
+ // message_id, which is all the caller reads.
298
+ //
299
+ // `wrapped` selects the retry-wrapped adapter (first attempt) vs the
300
+ // UNwrapped adapter (THREAD_NOT_FOUND retry). The inline site wrapped only
301
+ // the first attempt in robustApiCall; the retry called the raw send
302
+ // deliberately, so re-attempting after a dropped thread never re-enters the
303
+ // retry policy. Preserving that split keeps behavior byte-identical.
304
+ const sendChunk = (opts: Record<string, unknown>, wrapped: boolean): Promise<{ message_id: number }> => {
305
+ if (literalText) {
306
+ return wrapped ? deps.sendLiteral(opts, chunks[i], threadId) : deps.sendLiteralRaw(opts, chunks[i])
307
+ }
308
+ // sendRichMessage does NOT accept link_preview_options (rich messages
309
+ // control previews via entity detection) — drop it for the rich path.
310
+ const richOpts = { ...opts }
311
+ delete (richOpts as { link_preview_options?: unknown }).link_preview_options
312
+ const richBody = deps.richMessage(chunks[i])
313
+ return wrapped ? deps.sendRich(richOpts, richBody, threadId) : deps.sendRichRaw(richOpts, richBody)
314
+ }
315
+
316
+ // Length-error recovery: a single pre-computed chunk can still exceed the
317
+ // wire cap when splitMarkdownChunks hit an indivisible region and emitted
318
+ // it whole (a giant fenced block, a no-boundary blob). Telegram answers
319
+ // with RICH_MESSAGE_TEXT_TOO_LONG / MESSAGE_TOO_LONG. Re-split this chunk
320
+ // at a harder boundary and send each piece, rather than misclassifying it
321
+ // as a parse-reject (which would resend the same oversized payload as
322
+ // plain text) or surfacing the raw 400.
323
+ const sendChunkResplit = async (opts: Record<string, unknown>): Promise<void> => {
324
+ // Re-split at the same cap; for a truly indivisible block this still
325
+ // yields one oversized piece, but a hard character-cut on the rendered
326
+ // markdown at least keeps each delivered piece under the wire cap.
327
+ const pieces = resplitOversizeChunk(chunks[i])
328
+ for (let p = 0; p < pieces.length; p++) {
329
+ let sent: { message_id: number }
330
+ if (literalText) {
331
+ sent = await deps.sendLiteralRaw(opts, pieces[p])
332
+ } else {
333
+ const ro = { ...opts }
334
+ delete (ro as { link_preview_options?: unknown }).link_preview_options
335
+ sent = await deps.sendRichRaw(ro, deps.richMessage(pieces[p]))
336
+ }
337
+ sentIds.push(sent.message_id)
338
+ deps.logOutbound('reply', chatId, sent.message_id, pieces[p].length, `chunk=${i + 1}/${chunks.length} resplit=${p + 1}/${pieces.length}`)
339
+ }
340
+ deps.stderr(
341
+ `telegram gateway: rich body too long — re-split chunk ${i + 1}/${chunks.length} into ${pieces.length} piece(s)\n`,
342
+ )
343
+ }
344
+
345
+ try {
346
+ const sent = await sendChunk(sendOpts, true)
347
+ sentIds.push(sent.message_id)
348
+ deps.logOutbound('reply', chatId, sent.message_id, chunks[i].length, `chunk=${i + 1}/${chunks.length}`)
349
+ } catch (err) {
350
+ if (err instanceof Error && err.message === 'THREAD_NOT_FOUND') {
351
+ threadId = undefined
352
+ const retryOpts = { ...sendOpts }
353
+ delete (retryOpts as Record<string, unknown>).message_thread_id
354
+ try {
355
+ const sent = await sendChunk(retryOpts, false)
356
+ sentIds.push(sent.message_id)
357
+ } catch (retryErr) {
358
+ // Thread dropped, AND another failure: length → re-split,
359
+ // parse-reject → plain text, else propagate.
360
+ if (isMessageTooLongError(retryErr)) await sendChunkResplit(retryOpts)
361
+ else if (isHtmlParseRejectError(retryErr)) await sendChunkPlainText(retryOpts)
362
+ else throw retryErr
363
+ }
364
+ } else if (isMessageTooLongError(err)) {
365
+ await sendChunkResplit(sendOpts)
366
+ } else if (isHtmlParseRejectError(err)) {
367
+ await sendChunkPlainText(sendOpts)
368
+ } else {
369
+ throw err
370
+ }
371
+ }
372
+ }
373
+
374
+ return { threadId, previewMessageId }
375
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * In-memory storage for the LONG-TAIL of gateway.ts pending-state Maps —
3
+ * the auth/vault-wizard, config-edit correlation, and transient capture Maps
4
+ * that PR #3008 deferred when it moved the four agent-initiated approval-card
5
+ * families behind `approval-card-stores.ts`. Phase 3 step 2 of the gateway
6
+ * decomposition (see #2996): STORAGE ONLY.
7
+ *
8
+ * Two shapes, mirroring the two shapes the long-tail Maps actually have:
9
+ *
10
+ * - `createSweepableStore<T>(isExpired)` — a Map-compatible store whose
11
+ * `sweep(now)` deletes every entry the caller's `isExpired(value, now)`
12
+ * predicate reports as past its TTL. The predicate is supplied by the
13
+ * gateway and CLOSES OVER the family's TTL constant, so the TTL and its
14
+ * comparison DIRECTION stay verbatim in gateway.ts — different families use
15
+ * `now - staged_at > TTL`, `now - startedAt > TTL`, `now - createdAt > TTL`,
16
+ * or an absolute `now > expiresAt`, and each is preserved byte-identically.
17
+ * `sweep` is a plain delete-past-TTL loop (no wake / side effects); it
18
+ * replaces the identical open-coded reaper / standalone-sweep loops. The
19
+ * delete-during-iteration is safe (JS Map iterators tolerate deleting the
20
+ * current key) — exactly as the original loops relied on.
21
+ *
22
+ * - `createPlainStore<T>()` — a Map-compatible store with NO sweep, for the
23
+ * long-tail Maps whose lifetime is bounded by per-entry timers or an
24
+ * LRU cap rather than a TTL sweep (`pendingAskUser`, `agentButtonMeta`).
25
+ *
26
+ * Why a Map-compatible surface (get/set/delete/has/size/keys/values/entries/
27
+ * forEach/iteration) rather than a bespoke API: every existing gateway call
28
+ * site used the raw Map directly. Preserving the exact Map method surface —
29
+ * and keeping the variable name unchanged — keeps those call sites
30
+ * BYTE-IDENTICAL. The store moves WHERE the Map is constructed and (for the
31
+ * sweepable shape) WHERE its sweep lives, nothing about how the gateway reads
32
+ * or writes it.
33
+ *
34
+ * The backing Map is the sole storage and backs every iterator, so mutation-
35
+ * during-iteration order/semantics are identical to the raw Map the gateway
36
+ * used before.
37
+ */
38
+
39
+ export interface PlainStore<T> {
40
+ get(key: string): T | undefined
41
+ set(key: string, value: T): void
42
+ delete(key: string): boolean
43
+ has(key: string): boolean
44
+ clear(): void
45
+ readonly size: number
46
+ keys(): IterableIterator<string>
47
+ values(): IterableIterator<T>
48
+ entries(): IterableIterator<[string, T]>
49
+ forEach(cb: (value: T, key: string, map: Map<string, T>) => void): void
50
+ [Symbol.iterator](): IterableIterator<[string, T]>
51
+ }
52
+
53
+ export interface SweepableStore<T> extends PlainStore<T> {
54
+ /**
55
+ * Delete every entry past its TTL per the injected `isExpired` predicate.
56
+ * Plain delete-past-TTL, no wake — byte-identical to the open-coded reaper /
57
+ * standalone sweep loop it replaces.
58
+ */
59
+ sweep(now: number): void
60
+ }
61
+
62
+ // Build the shared Map surface onto `target` (a getter for `size`, so the
63
+ // live Map size is read on every access — an object spread would freeze it).
64
+ function attachMapSurface<T, S extends object>(target: S, map: Map<string, T>): S & PlainStore<T> {
65
+ return Object.defineProperties(target, {
66
+ get: { value: (key: string) => map.get(key), enumerable: true },
67
+ set: { value: (key: string, value: T) => void map.set(key, value), enumerable: true },
68
+ delete: { value: (key: string) => map.delete(key), enumerable: true },
69
+ has: { value: (key: string) => map.has(key), enumerable: true },
70
+ clear: { value: () => map.clear(), enumerable: true },
71
+ size: { get: () => map.size, enumerable: true },
72
+ keys: { value: () => map.keys(), enumerable: true },
73
+ values: { value: () => map.values(), enumerable: true },
74
+ entries: { value: () => map.entries(), enumerable: true },
75
+ forEach: {
76
+ value: (cb: (value: T, key: string, m: Map<string, T>) => void) => map.forEach(cb),
77
+ enumerable: true,
78
+ },
79
+ [Symbol.iterator]: { value: () => map[Symbol.iterator](), enumerable: true },
80
+ }) as S & PlainStore<T>
81
+ }
82
+
83
+ /**
84
+ * Create a Map-backed store with no automatic expiry. For long-tail Maps
85
+ * whose entries are removed by per-entry timers or an LRU cap, not a TTL sweep.
86
+ */
87
+ export function createPlainStore<T>(): PlainStore<T> {
88
+ return attachMapSurface({}, new Map<string, T>())
89
+ }
90
+
91
+ /**
92
+ * Create a Map-backed, self-sweeping store for one long-tail pending-state
93
+ * family. `isExpired` closes over the family's TTL constant and encodes its
94
+ * exact comparison direction; `sweep(now)` deletes every entry it flags.
95
+ */
96
+ export function createSweepableStore<T>(
97
+ isExpired: (value: T, now: number) => boolean,
98
+ ): SweepableStore<T> {
99
+ const map = new Map<string, T>()
100
+ const sweep = (now: number): void => {
101
+ for (const [k, v] of map) {
102
+ if (isExpired(v, now)) map.delete(k)
103
+ }
104
+ }
105
+ return attachMapSurface({ sweep }, map)
106
+ }
@@ -0,0 +1,30 @@
1
+ import type { Bot } from 'grammy'
2
+ import {
3
+ TELEGRAM_BASE_COMMANDS,
4
+ TELEGRAM_SWITCHROOM_COMMANDS,
5
+ } from '../welcome-text.js'
6
+
7
+ /**
8
+ * Register the bot's slash-command menu with Telegram (`setMyCommands`).
9
+ *
10
+ * Extracted verbatim from gateway.ts (#2996 Phase 5 leaf move). The `bot`
11
+ * singleton is injected rather than imported so this stays a pure leaf with
12
+ * no back-reference into the gateway module.
13
+ *
14
+ * Slash-menu is deliberately trimmed from the full command catalogue.
15
+ * See telegram-plugin/welcome-text.ts TELEGRAM_MENU_COMMANDS for the
16
+ * rationale (mobile UX focus; ops primitives stay typable but out of
17
+ * the autocomplete clutter). /commands surfaces the full list.
18
+ */
19
+ export async function registerSwitchroomBotCommands(bot: Bot): Promise<void> {
20
+ await bot.api.setMyCommands(
21
+ [...TELEGRAM_BASE_COMMANDS, ...TELEGRAM_SWITCHROOM_COMMANDS],
22
+ { scope: { type: 'all_private_chats' } },
23
+ )
24
+ // Group chats don't support /start pairing, so only the switchroom
25
+ // commands are registered there.
26
+ await bot.api.setMyCommands(
27
+ TELEGRAM_SWITCHROOM_COMMANDS,
28
+ { scope: { type: 'all_group_chats' } },
29
+ )
30
+ }