telecoder 0.0.0-stage → 1.3.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 (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -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 +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Pending-question registry for telecoder_ask_user MCP tool.
3
+ *
4
+ * When Claude calls telecoder_ask_user, the MCP tool body:
5
+ * 1. Calls createPendingQuestion() → gets { id, promise }
6
+ * 2. Sends a Telegram message with an inline keyboard whose buttons have
7
+ * callback_data = `q:<id>:<optionIndex>`
8
+ * 3. Awaits the promise
9
+ *
10
+ * When the user taps a button, the bot's callback dispatcher routes to
11
+ * resolvePendingQuestion(id, ...), which fulfils the awaited promise so the
12
+ * agent loop continues with the user's choice.
13
+ *
14
+ * A question nobody answers times out after QUESTION_TIMEOUT_MINUTES (10 by
15
+ * default): the agent receives a "user did not respond" result and moves on,
16
+ * and the caller closes the message (closeExpiredQuestion) so its keyboard
17
+ * doesn't outlive the wait.
18
+ *
19
+ * In-memory only — a restart forgets every open question without touching its
20
+ * message. The first tap on one of those gets the expired answer, and the tap
21
+ * handler takes the dead keyboard down then.
22
+ */
23
+ import * as crypto from 'crypto';
24
+ import { config } from '../config.js';
25
+ import { buildLetteredKeyboard, letteredOptionLines, } from '../telegram/lettered-options.js';
26
+ import { TYPED_ANSWER_HINT } from './typed-answer.js';
27
+ /**
28
+ * Max characters of `context` we render into the question message. Keeps the
29
+ * whole message comfortably under Telegram's 4096-char limit even alongside a
30
+ * long question and eight annotated options; overflow is clipped with an
31
+ * ellipsis rather than letting sendMessage 400 on us.
32
+ */
33
+ const MAX_CONTEXT_LEN = 3500;
34
+ /** Telegram's hard cap on a text message / message edit. */
35
+ const MAX_MESSAGE_LEN = 4096;
36
+ /**
37
+ * How long a question waits for a tap: QUESTION_TIMEOUT_MINUTES, 10 by
38
+ * default. One clock for everything a turn stops to ask — telecoder_ask_user,
39
+ * telecoder_poll_user, a relayed Claude Code dialog. Permission prompts and
40
+ * held messages keep their own, PERMISSION_PROMPT_TIMEOUT_MINUTES.
41
+ */
42
+ export function questionTimeoutMinutes() {
43
+ const minutes = config.QUESTION_TIMEOUT_MINUTES;
44
+ return Number.isFinite(minutes) && minutes > 0 ? minutes : 10;
45
+ }
46
+ export function questionTimeoutMs() {
47
+ return questionTimeoutMinutes() * 60 * 1000;
48
+ }
49
+ /**
50
+ * Build the plain-text body for an ask_user Telegram message, for the IPC
51
+ * handler in mcp-bridge.ts.
52
+ *
53
+ * Layout:
54
+ * ❓ <question>
55
+ *
56
+ * <context> ← only when provided; the model's decision rationale
57
+ *
58
+ * A. Label — description ← every option, keyed by its letter
59
+ *
60
+ * ✏️ Or reply with your own answer.
61
+ *
62
+ * The `context` block is the fix for the "user is asked to choose before the
63
+ * explanation is shown" bug: prose the model emits *before* calling ask_user
64
+ * isn't delivered until end-of-turn (after the tap), so decision-relevant
65
+ * information must ride inside the question message itself.
66
+ */
67
+ export function buildAskUserMessageText(question, options, context) {
68
+ const lines = [`❓ ${question}`];
69
+ const ctx = context?.trim();
70
+ if (ctx) {
71
+ const clipped = ctx.length > MAX_CONTEXT_LEN ? ctx.slice(0, MAX_CONTEXT_LEN - 1) + '…' : ctx;
72
+ lines.push('');
73
+ lines.push(clipped);
74
+ }
75
+ // Every option, always — not just the ones that came with a description.
76
+ // A button is not a reliable place to read a label from: Telegram clips a
77
+ // long one and offers no way to see the rest, so the body is where an
78
+ // option's full text lives and the letter is how its button points back at
79
+ // it.
80
+ lines.push('');
81
+ lines.push(...letteredOptionLines(options));
82
+ lines.push('');
83
+ lines.push(TYPED_ANSWER_HINT);
84
+ return lines.join('\n');
85
+ }
86
+ /**
87
+ * The inline keyboard for a question, for the IPC handler in mcp-bridge.ts —
88
+ * rendered like every other lettered picker, through {@link buildLetteredKeyboard}.
89
+ */
90
+ export function buildAskUserKeyboard(id, options) {
91
+ return buildLetteredKeyboard(options.map((o, idx) => ({ label: o.label, callbackData: `q:${id}:${idx}` })));
92
+ }
93
+ /**
94
+ * Rewrite an answered question's text so it no longer reads as unanswered once
95
+ * the keyboard is stripped. Returns `null` when the footer won't fit (or there
96
+ * is no original text to append to) — the caller should then drop the keyboard
97
+ * on its own and let the separate confirmation message carry the answer.
98
+ *
99
+ * The length check is not theoretical: `context` may be up to
100
+ * {@link MAX_CONTEXT_LEN} chars, so a long question plus annotated options can
101
+ * sit close enough to Telegram's 4096-char ceiling that appending a footer
102
+ * tips the edit into a 400 — which would leave a live-looking keyboard on a
103
+ * question that has already been resolved.
104
+ */
105
+ export function appendAnsweredFooter(original, label) {
106
+ return appendFooter(original, `✅ Answered: ${label}`);
107
+ }
108
+ /**
109
+ * The counterpart of {@link appendAnsweredFooter} for a question nobody
110
+ * answered: `note` says what happened instead. Same length rule, same `null`.
111
+ */
112
+ export function appendExpiredFooter(original, note) {
113
+ return appendFooter(original, `⏱️ ${note}`);
114
+ }
115
+ function appendFooter(original, footer) {
116
+ if (!original)
117
+ return null;
118
+ const appended = `${original}\n\n${footer}`;
119
+ return appended.length > MAX_MESSAGE_LEN ? null : appended;
120
+ }
121
+ /**
122
+ * The line an ask_user question ends on once it expires.
123
+ */
124
+ export function buildAskUserExpiredNote() {
125
+ return `No answer within ${questionTimeoutMinutes()} min, so Claude carried on without one.`;
126
+ }
127
+ /**
128
+ * Wait for a question's answer, or for the tool call that asked it to hang up:
129
+ * claude cancelled the call, as it does when its turn is stopped, or its pty
130
+ * went away. `'hung-up'` then, and the caller withdraws the question and
131
+ * closes its message, which would otherwise wait out the clock looking live
132
+ * and take the next message typed for its answer.
133
+ */
134
+ export function answerOrHangUp(answer, signal) {
135
+ if (!signal)
136
+ return answer;
137
+ if (signal.aborted)
138
+ return Promise.resolve('hung-up');
139
+ return new Promise((resolve) => {
140
+ const onAbort = () => resolve('hung-up');
141
+ signal.addEventListener('abort', onAbort, { once: true });
142
+ void answer.then((value) => {
143
+ signal.removeEventListener('abort', onAbort);
144
+ resolve(value);
145
+ });
146
+ });
147
+ }
148
+ /**
149
+ * Close a question nobody answered in time: take its keyboard down and say
150
+ * what happened where the answer would have gone.
151
+ *
152
+ * A tap is the only other thing that strips a keyboard, so without this a
153
+ * question that simply ran out of time kept buttons that looked as live as
154
+ * the moment they were posted — and tapping one got nothing but a toast. Each
155
+ * caller runs it once its wait comes back empty, with the text it sent and
156
+ * the entities too, when it sent some: an edit that leaves them out drops the
157
+ * formatting. They stay valid because the footer only appends.
158
+ *
159
+ * Best-effort, like the answered path in bot.ts. A footer that won't fit or an
160
+ * edit Telegram refuses still gets the keyboard taken down on its own.
161
+ */
162
+ export async function closeExpiredQuestion(api, message, text, note, entities) {
163
+ await closeQuestion(api, message, appendExpiredFooter(text, note), entities);
164
+ }
165
+ /**
166
+ * Close a question answered by something other than a tap, which bot.ts
167
+ * closes itself: a typed answer. Same fallbacks as {@link closeExpiredQuestion}.
168
+ */
169
+ export async function closeAnsweredQuestion(api, message, text, label, entities) {
170
+ await closeQuestion(api, message, appendAnsweredFooter(text, label), entities);
171
+ }
172
+ /** Close a question claude stopped waiting on (see {@link answerOrHangUp}). Same fallbacks. */
173
+ export async function closeWithdrawnQuestion(api, message, text) {
174
+ await closeQuestion(api, message, appendFooter(text, '🚫 Claude stopped waiting for an answer.'));
175
+ }
176
+ async function closeQuestion(api, message, closed, entities) {
177
+ const chatId = message.chat.id;
178
+ if (closed !== null) {
179
+ try {
180
+ await api.editMessageText(chatId, message.message_id, closed, entities ? { entities } : undefined);
181
+ return;
182
+ }
183
+ catch {
184
+ // Losing the note is cosmetic; a live keyboard on a closed question is
185
+ // not — fall through and take the keyboard down on its own.
186
+ }
187
+ }
188
+ try {
189
+ await api.editMessageReplyMarkup(chatId, message.message_id);
190
+ }
191
+ catch (err) {
192
+ // Nothing left to try here. A tap on it still gets the expired answer,
193
+ // and the tap handler strips the keyboard then.
194
+ console.warn('[AskUser] could not close a question:', err instanceof Error ? err.message : err);
195
+ }
196
+ }
197
+ /**
198
+ * The confirmation sent as its own message once a question is answered.
199
+ *
200
+ * Editing the question in place is silent and anonymous: Telegram raises no
201
+ * notification for an edit, and the footer says nothing about who tapped. In a
202
+ * group that means the rest of the chat never sees a decision was made. A
203
+ * standalone message replying to the question puts the answer in the
204
+ * conversation flow the way a typed reply would be, and names the person.
205
+ */
206
+ export function buildAnswerConfirmation(label, opts) {
207
+ const who = opts.isPrivate ? 'You' : opts.who?.trim() || 'Someone';
208
+ return `✅ ${who} picked: ${label}`;
209
+ }
210
+ const pending = new Map();
211
+ // Per-sessionKey pending counter: the status bubble reads it to say the turn
212
+ // is waiting on the user. A counter, not a boolean, for the rare overlapping
213
+ // asks in one session.
214
+ const pendingBySession = new Map();
215
+ function clearPending(id) {
216
+ const entry = pending.get(id);
217
+ if (!entry)
218
+ return undefined;
219
+ pending.delete(id);
220
+ clearTimeout(entry.timer);
221
+ if (entry.sessionKey) {
222
+ const next = (pendingBySession.get(entry.sessionKey) ?? 1) - 1;
223
+ if (next <= 0)
224
+ pendingBySession.delete(entry.sessionKey);
225
+ else
226
+ pendingBySession.set(entry.sessionKey, next);
227
+ }
228
+ return entry;
229
+ }
230
+ /**
231
+ * Register a new pending question. Returns a short id (hex) and a promise
232
+ * that resolves with the user's selected option, or `null` on timeout.
233
+ */
234
+ export function createPendingQuestion(optionLabels, timeoutMs = questionTimeoutMs(), sessionKey, allowedResponderIds, opts) {
235
+ const id = crypto.randomBytes(4).toString('hex');
236
+ let resolveFn;
237
+ const promise = new Promise((resolve) => {
238
+ resolveFn = resolve;
239
+ });
240
+ const timer = setTimeout(() => {
241
+ const entry = clearPending(id);
242
+ if (entry)
243
+ entry.resolve(null);
244
+ }, timeoutMs);
245
+ pending.set(id, {
246
+ resolve: resolveFn,
247
+ timer,
248
+ optionLabels,
249
+ sessionKey,
250
+ ...(allowedResponderIds && allowedResponderIds.length > 0 ? { allowedResponderIds } : {}),
251
+ ...(opts?.ownerCloses ? { ownerCloses: true } : {}),
252
+ });
253
+ if (sessionKey) {
254
+ pendingBySession.set(sessionKey, (pendingBySession.get(sessionKey) ?? 0) + 1);
255
+ }
256
+ return { id, promise };
257
+ }
258
+ /**
259
+ * Take a question back without answering it: its promise never settles, and a
260
+ * later tap gets the expired toast. For an asker that stopped needing the
261
+ * answer — the memory guard whose wait found room before anyone tapped, or
262
+ * an ask_user call claude cancelled.
263
+ */
264
+ export function withdrawPendingQuestion(id) {
265
+ clearPending(id);
266
+ }
267
+ /**
268
+ * Resolve a pending question with the user's selection. Called by the
269
+ * Telegram callback-query dispatcher on button tap.
270
+ *
271
+ * The responder check lives in here rather than at the call site on purpose:
272
+ * a restricted question must be impossible to resolve without passing the id
273
+ * of whoever tapped, so a future caller cannot forget the check and quietly
274
+ * reopen the question to everyone.
275
+ */
276
+ export function resolvePendingQuestion(id, optionIndex, responderId) {
277
+ const entry = claimPending(id, responderId);
278
+ if (typeof entry === 'string')
279
+ return entry;
280
+ const label = entry.optionLabels[optionIndex];
281
+ if (label === undefined) {
282
+ entry.resolve(null);
283
+ return 'resolved';
284
+ }
285
+ entry.resolve({ label, index: optionIndex });
286
+ return 'resolved';
287
+ }
288
+ /**
289
+ * Resolve a pending question with an answer the user typed instead of tapping
290
+ * (see typed-answer.ts). Same outcomes, and the same responder check, as
291
+ * {@link resolvePendingQuestion}.
292
+ */
293
+ export function resolvePendingQuestionWithText(id, text, responderId) {
294
+ const entry = claimPending(id, responderId);
295
+ if (typeof entry === 'string')
296
+ return entry;
297
+ entry.resolve({ label: text, index: -1, typed: true });
298
+ return 'resolved';
299
+ }
300
+ /** Take a question off the books for this responder to answer, or say why they can't. */
301
+ function claimPending(id, responderId) {
302
+ const entry = pending.get(id);
303
+ if (!entry)
304
+ return 'expired';
305
+ const allowed = entry.allowedResponderIds;
306
+ // Fails closed: no responder id on a restricted question is a refusal, not
307
+ // a pass. Unrestricted questions ignore the id entirely.
308
+ if (allowed && (responderId === undefined || !allowed.includes(responderId))) {
309
+ return 'forbidden';
310
+ }
311
+ clearPending(id);
312
+ return entry;
313
+ }
314
+ /** Whether the asker closes this question's message itself (see PendingEntry.ownerCloses). Read before resolving: resolving drops the entry. */
315
+ export function questionOwnerCloses(id) {
316
+ return pending.get(id)?.ownerCloses === true;
317
+ }
318
+ /**
319
+ * The full label of one option on a pending question — what the model wrote,
320
+ * not what its button shows. The two part company as soon as a keyboard goes
321
+ * compact and the button is a bare `A`, and it is the model's text that
322
+ * belongs in the answered footer and the confirmation message. Read it before
323
+ * resolving; resolving drops the entry.
324
+ */
325
+ export function getQuestionOptionLabel(id, index) {
326
+ return pending.get(id)?.optionLabels[index];
327
+ }
328
+ /**
329
+ * The ids allowed to answer this question, or undefined when it is open to
330
+ * everyone. Lets the callback handler tell the tapper who they are waiting on
331
+ * instead of a bare refusal.
332
+ */
333
+ export function getQuestionResponders(id) {
334
+ return pending.get(id)?.allowedResponderIds;
335
+ }
336
+ /**
337
+ * Count a wait on the user that isn't a button question, such as a secret
338
+ * request, as one: the status bubble says the turn is waiting on them.
339
+ * Returns the call that ends the wait, which is safe to make more than once.
340
+ */
341
+ export function noteAwaitingUser(sessionKey) {
342
+ pendingBySession.set(sessionKey, (pendingBySession.get(sessionKey) ?? 0) + 1);
343
+ let ended = false;
344
+ return () => {
345
+ if (ended)
346
+ return;
347
+ ended = true;
348
+ const next = (pendingBySession.get(sessionKey) ?? 1) - 1;
349
+ if (next <= 0)
350
+ pendingBySession.delete(sessionKey);
351
+ else
352
+ pendingBySession.set(sessionKey, next);
353
+ };
354
+ }
355
+ /**
356
+ * True when there's an outstanding ask-user question for this sessionKey.
357
+ * The status bubble uses this to say the turn is parked on the user, where
358
+ * it would otherwise go on animating "Thinking…".
359
+ */
360
+ export function hasPendingQuestionForSession(sessionKey) {
361
+ return (pendingBySession.get(sessionKey) ?? 0) > 0;
362
+ }
363
+ //# sourceMappingURL=ask-user.js.map
@@ -0,0 +1,225 @@
1
+ /**
2
+ * A time-boxed window in which the permission gate approves instead of asking.
3
+ *
4
+ * The gate costs one button tap per guarded tool call, which is right when the
5
+ * calls are rare and wrong when someone is doing a job made of them — a
6
+ * dependency bump that runs `rm -rf node_modules` four times, a rebase that
7
+ * force-pushes twice. The person supervising ends up tapping a prompt they had
8
+ * already decided about before the run started, and a guardrail people tap
9
+ * without reading is worse than one that isn't there.
10
+ *
11
+ * So the decision can be made once, in advance, for a stated length of time.
12
+ * What a window is *not* is a mode: it does not change what the gate matches,
13
+ * it does not reach the charter judge, and it cannot be opened by a guest. It
14
+ * only answers the prompts that would otherwise be posted, and says so in the
15
+ * chat each time, so the window trades a tap for a line in the log rather than
16
+ * for silence.
17
+ *
18
+ * Three properties make that trade safe, and all three are load-bearing:
19
+ *
20
+ * - It expires on its own, and the expiry is announced. A supervision hole
21
+ * nobody remembers opening is the failure mode to avoid.
22
+ * - It is per chat and lives only in memory, so a restart closes every
23
+ * window. The safe direction to fail is closed.
24
+ * - The irreversible patterns still prompt. Tedium is the problem being
25
+ * solved; `mkfs` and `DROP DATABASE` are not tedium.
26
+ */
27
+ /** Shortest window worth opening. Below this the tap would have been cheaper. */
28
+ export const MIN_WINDOW_MS = 60 * 1000;
29
+ /**
30
+ * Longest window. Four hours is about a working session; a window that can
31
+ * outlive the attention of the person who opened it is the thing this cap
32
+ * exists to prevent, and re-opening one is a single command.
33
+ */
34
+ export const MAX_WINDOW_MS = 4 * 60 * 60 * 1000;
35
+ /** What `/autoapprove` with no duration means. */
36
+ export const DEFAULT_WINDOW_MS = 30 * 60 * 1000;
37
+ /**
38
+ * Deliberately a plain Map and deliberately not persisted. A window is a
39
+ * statement about the next half hour by someone who is present; surviving a
40
+ * restart would make it a statement about a half hour nobody was watching.
41
+ */
42
+ const entries = new Map();
43
+ /**
44
+ * Gate reasons that a window never answers for.
45
+ *
46
+ * The line is not "dangerous" — everything the gate matches is dangerous, or
47
+ * it would not be matched. It is whether a wrong call can be walked back. A
48
+ * force-push can be undone from a reflog, a dropped *database* cannot, and
49
+ * neither can a filesystem written over. Those keep their prompt, so a window
50
+ * left open by accident still cannot cost you the machine.
51
+ */
52
+ const ALWAYS_PROMPT_REASONS = new Set([
53
+ 'destructive disk op',
54
+ 'DROP DATABASE',
55
+ 'terraform destroy',
56
+ ]);
57
+ /**
58
+ * The scope guard's credential verdict, which arrives as
59
+ * `"reads a credential or bot-state path — <path>"`. Reading `~/.ssh/id_rsa` is
60
+ * not tedium either, and a window is not consent to it.
61
+ */
62
+ const CREDENTIAL_REASON = 'reads a credential or bot-state path';
63
+ /** True when this gate reason must be asked about even inside a window. */
64
+ export function alwaysPrompts(reason) {
65
+ if (ALWAYS_PROMPT_REASONS.has(reason))
66
+ return true;
67
+ return reason.startsWith(CREDENTIAL_REASON);
68
+ }
69
+ /**
70
+ * What a window never covers, phrased for the person reading the chat rather
71
+ * than for the matcher. `alwaysPrompts()` above is the matcher; these are
72
+ * labels, and the two are meant to drift apart — "destructive disk op" is an
73
+ * accurate reason and a poor thing to read in a list of what is still guarded.
74
+ */
75
+ export function listAlwaysPrompted() {
76
+ return [
77
+ 'mkfs, or dd writing to a device',
78
+ 'DROP DATABASE',
79
+ 'terraform destroy',
80
+ 'reading a credential or bot-state path',
81
+ ];
82
+ }
83
+ /** Close an entry and tell whoever asked to be told. Idempotent. */
84
+ function finish(chatId, notify) {
85
+ const entry = entries.get(chatId);
86
+ if (!entry)
87
+ return null;
88
+ entries.delete(chatId);
89
+ if (entry.timer)
90
+ clearTimeout(entry.timer);
91
+ if (entry.finished)
92
+ return entry.window;
93
+ entry.finished = true;
94
+ if (notify && entry.onExpire) {
95
+ try {
96
+ entry.onExpire(entry.window);
97
+ }
98
+ catch {
99
+ // The announcement is best-effort: a chat that has gone away must not
100
+ // keep a window alive, and this runs on a bare timer with no catcher.
101
+ }
102
+ }
103
+ return entry.window;
104
+ }
105
+ /**
106
+ * The open window for this chat, or null.
107
+ *
108
+ * Expiry is decided here rather than trusted to the timer, so a timer that was
109
+ * never scheduled, or fired late, can only ever close a window early — never
110
+ * leave a lapsed one answering prompts.
111
+ */
112
+ export function getWindow(chatId) {
113
+ const entry = entries.get(chatId);
114
+ if (!entry)
115
+ return null;
116
+ if (Date.now() >= entry.window.expiresAt) {
117
+ finish(chatId, true);
118
+ return null;
119
+ }
120
+ return entry.window;
121
+ }
122
+ /**
123
+ * Open a window on this chat, replacing any window already open.
124
+ *
125
+ * Replacing rather than extending: someone re-running the command has a length
126
+ * in mind, and reading "50 min left" after asking for 30 is the kind of
127
+ * surprise a supervision feature cannot afford.
128
+ */
129
+ export function openWindow(chatId, opts) {
130
+ finish(chatId, false);
131
+ const now = Date.now();
132
+ const window = {
133
+ chatId,
134
+ openedBy: opts.openedBy,
135
+ openedByName: opts.openedByName,
136
+ openedAt: now,
137
+ expiresAt: now + opts.durationMs,
138
+ approved: 0,
139
+ };
140
+ const entry = { window, onExpire: opts.onExpire, finished: false };
141
+ // unref so a pending window never holds the process open through a shutdown.
142
+ entry.timer = setTimeout(() => finish(chatId, true), opts.durationMs);
143
+ entry.timer.unref?.();
144
+ entries.set(chatId, entry);
145
+ return window;
146
+ }
147
+ /**
148
+ * Close a window early. Returns what was closed, or null if nothing was open.
149
+ * The expiry announcement is suppressed — whoever ran the command is already
150
+ * being answered.
151
+ */
152
+ export function closeWindow(chatId) {
153
+ const entry = entries.get(chatId);
154
+ if (!entry)
155
+ return null;
156
+ return finish(chatId, false);
157
+ }
158
+ /**
159
+ * Decide whether an open window answers this prompt, and count it if so.
160
+ *
161
+ * Returns the window — with `approved` already incremented — when the call may
162
+ * proceed without asking, and null when the gate should post its prompt as
163
+ * usual. Null covers all three of: no window, a lapsed one, and a reason no
164
+ * window ever answers for.
165
+ */
166
+ export function consumeAutoApproval(chatId, reason) {
167
+ if (alwaysPrompts(reason))
168
+ return null;
169
+ const window = getWindow(chatId);
170
+ if (!window)
171
+ return null;
172
+ window.approved += 1;
173
+ return window;
174
+ }
175
+ /**
176
+ * Parse `30m`, `2h`, `90s`, or a bare number read as minutes.
177
+ *
178
+ * Bare numbers are minutes rather than milliseconds because this is typed into
179
+ * a chat by a person: `/autoapprove 30` means half an hour to everyone who
180
+ * would type it.
181
+ */
182
+ export function parseWindowDuration(raw) {
183
+ const text = raw.trim().toLowerCase();
184
+ if (!text)
185
+ return { ok: true, ms: DEFAULT_WINDOW_MS };
186
+ const match = /^(\d+(?:\.\d+)?)\s*(s|sec|secs|m|min|mins|h|hr|hrs)?$/.exec(text);
187
+ if (!match) {
188
+ return { ok: false, error: 'I could not read that as a length of time. Try 30m, 2h or 90s.' };
189
+ }
190
+ const value = Number(match[1]);
191
+ if (!Number.isFinite(value) || value <= 0) {
192
+ return { ok: false, error: 'That has to be a positive length of time.' };
193
+ }
194
+ const unit = match[2] ?? 'm';
195
+ const perUnit = unit.startsWith('s') ? 1000 : unit.startsWith('h') ? 3600_000 : 60_000;
196
+ const ms = Math.round(value * perUnit);
197
+ if (ms < MIN_WINDOW_MS) {
198
+ return { ok: false, error: `The shortest window is ${formatDuration(MIN_WINDOW_MS)} — below that, tapping the prompt is quicker.` };
199
+ }
200
+ if (ms > MAX_WINDOW_MS) {
201
+ return { ok: false, error: `The longest window is ${formatDuration(MAX_WINDOW_MS)}. Open another one when it lapses.` };
202
+ }
203
+ return { ok: true, ms };
204
+ }
205
+ /** "45 min", "2 h", "1 h 30 min" — for announcements and status lines. */
206
+ export function formatDuration(ms) {
207
+ const totalMinutes = Math.max(1, Math.round(ms / 60_000));
208
+ const hours = Math.floor(totalMinutes / 60);
209
+ const minutes = totalMinutes % 60;
210
+ if (hours === 0)
211
+ return `${minutes} min`;
212
+ if (minutes === 0)
213
+ return `${hours} h`;
214
+ return `${hours} h ${minutes} min`;
215
+ }
216
+ /** How long this window has left, already formatted. */
217
+ export function formatRemaining(window) {
218
+ return formatDuration(Math.max(0, window.expiresAt - Date.now()));
219
+ }
220
+ /** Test seam — production keeps windows for the life of the process. */
221
+ export function resetAutoApprove() {
222
+ for (const chatId of [...entries.keys()])
223
+ finish(chatId, false);
224
+ }
225
+ //# sourceMappingURL=auto-approve.js.map