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,295 @@
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
+ /**
27
+ * Max characters of `context` we render into the question message. Keeps the
28
+ * whole message comfortably under Telegram's 4096-char limit even alongside a
29
+ * long question and eight annotated options; overflow is clipped with an
30
+ * ellipsis rather than letting sendMessage 400 on us.
31
+ */
32
+ const MAX_CONTEXT_LEN = 3500;
33
+ /** Telegram's hard cap on a text message / message edit. */
34
+ const MAX_MESSAGE_LEN = 4096;
35
+ /**
36
+ * How long a question waits for a tap: QUESTION_TIMEOUT_MINUTES, 10 by
37
+ * default. One clock for everything a turn stops to ask — telecoder_ask_user,
38
+ * telecoder_poll_user, a relayed Claude Code dialog. Permission prompts and
39
+ * held messages keep their own, PERMISSION_PROMPT_TIMEOUT_MINUTES.
40
+ */
41
+ export function questionTimeoutMinutes() {
42
+ const minutes = config.QUESTION_TIMEOUT_MINUTES;
43
+ return Number.isFinite(minutes) && minutes > 0 ? minutes : 10;
44
+ }
45
+ export function questionTimeoutMs() {
46
+ return questionTimeoutMinutes() * 60 * 1000;
47
+ }
48
+ /**
49
+ * Build the plain-text body for an ask_user Telegram message, shared by SDK
50
+ * mode (mcp-tools.ts) and PTY/IPC mode (mcp-bridge.ts) so both render
51
+ * identically.
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
+ * The `context` block is the fix for the "user is asked to choose before the
61
+ * explanation is shown" bug: prose the model emits *before* calling ask_user
62
+ * isn't delivered until end-of-turn (after the tap), so decision-relevant
63
+ * information must ride inside the question message itself.
64
+ */
65
+ export function buildAskUserMessageText(question, options, context) {
66
+ const lines = [`❓ ${question}`];
67
+ const ctx = context?.trim();
68
+ if (ctx) {
69
+ const clipped = ctx.length > MAX_CONTEXT_LEN ? ctx.slice(0, MAX_CONTEXT_LEN - 1) + '…' : ctx;
70
+ lines.push('');
71
+ lines.push(clipped);
72
+ }
73
+ // Every option, always — not just the ones that came with a description.
74
+ // A button is not a reliable place to read a label from: Telegram clips a
75
+ // long one and offers no way to see the rest, so the body is where an
76
+ // option's full text lives and the letter is how its button points back at
77
+ // it.
78
+ lines.push('');
79
+ lines.push(...letteredOptionLines(options));
80
+ return lines.join('\n');
81
+ }
82
+ /**
83
+ * The inline keyboard for a question, shared by SDK mode (mcp-tools.ts) and
84
+ * PTY/IPC mode (mcp-bridge.ts) so both render identically — and with every
85
+ * other lettered picker, through {@link buildLetteredKeyboard}.
86
+ */
87
+ export function buildAskUserKeyboard(id, options) {
88
+ return buildLetteredKeyboard(options.map((o, idx) => ({ label: o.label, callbackData: `q:${id}:${idx}` })));
89
+ }
90
+ /**
91
+ * Rewrite an answered question's text so it no longer reads as unanswered once
92
+ * the keyboard is stripped. Returns `null` when the footer won't fit (or there
93
+ * is no original text to append to) — the caller should then drop the keyboard
94
+ * on its own and let the separate confirmation message carry the answer.
95
+ *
96
+ * The length check is not theoretical: `context` may be up to
97
+ * {@link MAX_CONTEXT_LEN} chars, so a long question plus annotated options can
98
+ * sit close enough to Telegram's 4096-char ceiling that appending a footer
99
+ * tips the edit into a 400 — which would leave a live-looking keyboard on a
100
+ * question that has already been resolved.
101
+ */
102
+ export function appendAnsweredFooter(original, label) {
103
+ return appendFooter(original, `✅ Answered: ${label}`);
104
+ }
105
+ /**
106
+ * The counterpart of {@link appendAnsweredFooter} for a question nobody
107
+ * answered: `note` says what happened instead. Same length rule, same `null`.
108
+ */
109
+ export function appendExpiredFooter(original, note) {
110
+ return appendFooter(original, `⏱️ ${note}`);
111
+ }
112
+ function appendFooter(original, footer) {
113
+ if (!original)
114
+ return null;
115
+ const appended = `${original}\n\n${footer}`;
116
+ return appended.length > MAX_MESSAGE_LEN ? null : appended;
117
+ }
118
+ /**
119
+ * The line an ask_user question ends on once it expires — shared by SDK mode
120
+ * and PTY/IPC mode, like the rest of the message.
121
+ */
122
+ export function buildAskUserExpiredNote() {
123
+ return `No answer within ${questionTimeoutMinutes()} min, so Claude carried on without one.`;
124
+ }
125
+ /**
126
+ * Close a question nobody answered in time: take its keyboard down and say
127
+ * what happened where the answer would have gone.
128
+ *
129
+ * A tap is the only other thing that strips a keyboard, so without this a
130
+ * question that simply ran out of time kept buttons that looked as live as
131
+ * the moment they were posted — and tapping one got nothing but a toast. Each
132
+ * caller runs it once its wait comes back empty, with the text it sent and
133
+ * the entities too, when it sent some: an edit that leaves them out drops the
134
+ * formatting. They stay valid because the footer only appends.
135
+ *
136
+ * Best-effort, like the answered path in bot.ts. A footer that won't fit or an
137
+ * edit Telegram refuses still gets the keyboard taken down on its own.
138
+ */
139
+ export async function closeExpiredQuestion(api, message, text, note, entities) {
140
+ const chatId = message.chat.id;
141
+ const closed = appendExpiredFooter(text, note);
142
+ if (closed !== null) {
143
+ try {
144
+ await api.editMessageText(chatId, message.message_id, closed, entities ? { entities } : undefined);
145
+ return;
146
+ }
147
+ catch {
148
+ // Losing the note is cosmetic; a live keyboard on a closed question is
149
+ // not — fall through and take the keyboard down on its own.
150
+ }
151
+ }
152
+ try {
153
+ await api.editMessageReplyMarkup(chatId, message.message_id);
154
+ }
155
+ catch (err) {
156
+ // Nothing left to try here. A tap on it still gets the expired answer,
157
+ // and the tap handler strips the keyboard then.
158
+ console.warn('[AskUser] could not close an expired question:', err instanceof Error ? err.message : err);
159
+ }
160
+ }
161
+ /**
162
+ * The confirmation sent as its own message once a question is answered.
163
+ *
164
+ * Editing the question in place is silent and anonymous: Telegram raises no
165
+ * notification for an edit, and the footer says nothing about who tapped. In a
166
+ * group that means the rest of the chat never sees a decision was made. A
167
+ * standalone message replying to the question puts the answer in the
168
+ * conversation flow the way a typed reply would be, and names the person.
169
+ */
170
+ export function buildAnswerConfirmation(label, opts) {
171
+ const who = opts.isPrivate ? 'You' : opts.who?.trim() || 'Someone';
172
+ return `✅ ${who} picked: ${label}`;
173
+ }
174
+ const pending = new Map();
175
+ // Per-sessionKey pending counter — read by the agent watchdog so it can
176
+ // pause its stale-tool/silence timeouts while we're legitimately waiting on
177
+ // the user. Counter (not boolean) supports rare overlapping asks per session.
178
+ const pendingBySession = new Map();
179
+ function clearPending(id) {
180
+ const entry = pending.get(id);
181
+ if (!entry)
182
+ return undefined;
183
+ pending.delete(id);
184
+ clearTimeout(entry.timer);
185
+ if (entry.sessionKey) {
186
+ const next = (pendingBySession.get(entry.sessionKey) ?? 1) - 1;
187
+ if (next <= 0)
188
+ pendingBySession.delete(entry.sessionKey);
189
+ else
190
+ pendingBySession.set(entry.sessionKey, next);
191
+ }
192
+ return entry;
193
+ }
194
+ /**
195
+ * Register a new pending question. Returns a short id (hex) and a promise
196
+ * that resolves with the user's selected option, or `null` on timeout.
197
+ */
198
+ export function createPendingQuestion(optionLabels, timeoutMs = questionTimeoutMs(), sessionKey, allowedResponderIds) {
199
+ const id = crypto.randomBytes(4).toString('hex');
200
+ let resolveFn;
201
+ const promise = new Promise((resolve) => {
202
+ resolveFn = resolve;
203
+ });
204
+ const timer = setTimeout(() => {
205
+ const entry = clearPending(id);
206
+ if (entry)
207
+ entry.resolve(null);
208
+ }, timeoutMs);
209
+ pending.set(id, {
210
+ resolve: resolveFn,
211
+ timer,
212
+ optionLabels,
213
+ sessionKey,
214
+ ...(allowedResponderIds && allowedResponderIds.length > 0 ? { allowedResponderIds } : {}),
215
+ });
216
+ if (sessionKey) {
217
+ pendingBySession.set(sessionKey, (pendingBySession.get(sessionKey) ?? 0) + 1);
218
+ }
219
+ return { id, promise };
220
+ }
221
+ /**
222
+ * Resolve a pending question with the user's selection. Called by the
223
+ * Telegram callback-query dispatcher on button tap.
224
+ *
225
+ * The responder check lives in here rather than at the call site on purpose:
226
+ * a restricted question must be impossible to resolve without passing the id
227
+ * of whoever tapped, so a future caller cannot forget the check and quietly
228
+ * reopen the question to everyone.
229
+ */
230
+ export function resolvePendingQuestion(id, optionIndex, responderId) {
231
+ const entry = pending.get(id);
232
+ if (!entry)
233
+ return 'expired';
234
+ const allowed = entry.allowedResponderIds;
235
+ // Fails closed: no responder id on a restricted question is a refusal, not
236
+ // a pass. Unrestricted questions ignore the id entirely.
237
+ if (allowed && (responderId === undefined || !allowed.includes(responderId))) {
238
+ return 'forbidden';
239
+ }
240
+ clearPending(id);
241
+ const label = entry.optionLabels[optionIndex];
242
+ if (label === undefined) {
243
+ entry.resolve(null);
244
+ return 'resolved';
245
+ }
246
+ entry.resolve({ label, index: optionIndex });
247
+ return 'resolved';
248
+ }
249
+ /**
250
+ * The full label of one option on a pending question — what the model wrote,
251
+ * not what its button shows. The two part company as soon as a keyboard goes
252
+ * compact and the button is a bare `A`, and it is the model's text that
253
+ * belongs in the answered footer and the confirmation message. Read it before
254
+ * resolving; resolving drops the entry.
255
+ */
256
+ export function getQuestionOptionLabel(id, index) {
257
+ return pending.get(id)?.optionLabels[index];
258
+ }
259
+ /**
260
+ * The ids allowed to answer this question, or undefined when it is open to
261
+ * everyone. Lets the callback handler tell the tapper who they are waiting on
262
+ * instead of a bare refusal.
263
+ */
264
+ export function getQuestionResponders(id) {
265
+ return pending.get(id)?.allowedResponderIds;
266
+ }
267
+ /**
268
+ * Count a wait on the user that isn't a button question, such as a secret
269
+ * request, as one: the watchdog pauses for it and the status bubble says
270
+ * the turn is waiting on them. Returns the call that ends the wait, which is
271
+ * safe to make more than once.
272
+ */
273
+ export function noteAwaitingUser(sessionKey) {
274
+ pendingBySession.set(sessionKey, (pendingBySession.get(sessionKey) ?? 0) + 1);
275
+ let ended = false;
276
+ return () => {
277
+ if (ended)
278
+ return;
279
+ ended = true;
280
+ const next = (pendingBySession.get(sessionKey) ?? 1) - 1;
281
+ if (next <= 0)
282
+ pendingBySession.delete(sessionKey);
283
+ else
284
+ pendingBySession.set(sessionKey, next);
285
+ };
286
+ }
287
+ /**
288
+ * True when there's an outstanding ask-user question for this sessionKey.
289
+ * The agent watchdog uses this to pause its timeouts so legitimate waits
290
+ * for a button tap don't get force-closed as a "stale tool".
291
+ */
292
+ export function hasPendingQuestionForSession(sessionKey) {
293
+ return (pendingBySession.get(sessionKey) ?? 0) > 0;
294
+ }
295
+ //# 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
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Out-of-band topic summarizer using Haiku.
3
+ *
4
+ * Fires alongside the main agent turn to derive a two-part topic phrase
5
+ * for the status line: a stable GENERAL part (the broader feature/area)
6
+ * and a CURRENT part (the specific task in this turn). The previous
7
+ * GENERAL is fed back into the prompt so Haiku can keep it sticky
8
+ * across consecutive messages and only change it when the user pivots.
9
+ *
10
+ * Runs isolated (see side-call-options.ts): no plugins, MCP servers, hooks,
11
+ * or the bot's own folder's memory and git status — making it immune to the SDK's
12
+ * tool-deferral mode that can degrade the existing model-driven
13
+ * auto-topic mechanism when many user-level tools are loaded.
14
+ *
15
+ * Auth piggybacks on the same Claude executable the main bot uses, so no
16
+ * extra API key, account, or subscription is required.
17
+ */
18
+ import { query } from '@anthropic-ai/claude-agent-sdk';
19
+ import { sideCallOptions } from './side-call-options.js';
20
+ const TOPIC_TIMEOUT_MS = 10_000;
21
+ const MAX_INPUT_CHARS = 1500;
22
+ // Display delimiter between GENERAL and CURRENT in the stored topic.
23
+ // The status line renders the topic as-is, so this also doubles as the
24
+ // rendered separator. Kept in sync with the prompt below.
25
+ export const TOPIC_PART_SEPARATOR = ' · ';
26
+ // Trivial replies that don't carry topical content. Skip the Haiku call so we
27
+ // don't overwrite a perfectly good prior topic with garbage like "ok".
28
+ const TRIVIAL_MESSAGE_RE = /^(ok|okay|yes|yeah|yep|yup|no|nope|nah|thanks|thx|ty|cool|sure|nice|great|sounds good|got it|alright|done|next|continue|go|stop|wait|hmm|huh|lol|haha|👍|👌|✅|🙏|❤️|🎉)[.!?]*$/i;
29
+ function buildInstructions(previousTopic, project) {
30
+ // The project is shown next to the topic (in a thread's name, the status
31
+ // line), so a GENERAL that only repeats it says nothing.
32
+ const projectLine = project
33
+ ? `The project is "${project}" and is already shown next to the topic. GENERAL must name the feature/area within it, never just the project name.\n\n`
34
+ : '';
35
+ const previousLine = previousTopic
36
+ ? `Previous topic was: "${previousTopic}"\n` +
37
+ '- Keep GENERAL the same unless the user has clearly pivoted to a different feature/area.\n' +
38
+ '- If the latest message is a meta-question, acknowledgment, or has no concrete task, keep the previous CURRENT too.\n\n'
39
+ : '';
40
+ return ('You are a topic summarizer. Output format is strict: "GENERAL | CURRENT".\n' +
41
+ '- GENERAL: the broader feature/area being worked on. Stable across messages. Concise.\n' +
42
+ '- CURRENT: the specific task in this latest message. Be as descriptive as needed.\n' +
43
+ 'Output ONLY the topic line. NO chat, NO acknowledgment, NO explanation, NO quotes, NO prefix.\n' +
44
+ 'The pipe character "|" MUST appear exactly once, separating the two parts.\n\n' +
45
+ 'Good output:\n' +
46
+ 'Dark mode | Fixing toggle animation glitch\n' +
47
+ 'Auth bug | Adding rate limit to login endpoint\n' +
48
+ 'PR review | Reading test coverage report\n\n' +
49
+ 'Bad output (do NOT do any of these):\n' +
50
+ '"Understood, I\'ll continue with..." (chat reply)\n' +
51
+ 'Dark mode (missing CURRENT)\n' +
52
+ 'Fixing the bug. (missing GENERAL and pipe)\n\n' +
53
+ projectLine +
54
+ previousLine +
55
+ 'User message:\n');
56
+ }
57
+ /**
58
+ * Summarize a user message into a two-part topic via Haiku.
59
+ * Returns the combined "general · current" string. Returns undefined if
60
+ * Haiku doesn't follow the format — caller keeps the prior topic in that
61
+ * case rather than overwriting it with garbage. Pass the full previous
62
+ * topic so Haiku can keep GENERAL stable and reuse CURRENT for
63
+ * meta/acknowledgment messages, and the project's folder name so GENERAL
64
+ * isn't just that.
65
+ */
66
+ export async function summarizeTopicWithHaiku(userMessage, previousTopic, project) {
67
+ const trimmed = userMessage.trim();
68
+ if (trimmed.length < 3)
69
+ return undefined;
70
+ if (TRIVIAL_MESSAGE_RE.test(trimmed))
71
+ return undefined;
72
+ const input = trimmed.length > MAX_INPUT_CHARS ? trimmed.slice(0, MAX_INPUT_CHARS) : trimmed;
73
+ const controller = new AbortController();
74
+ const timer = setTimeout(() => controller.abort(), TOPIC_TIMEOUT_MS);
75
+ try {
76
+ const response = query({
77
+ prompt: buildInstructions(previousTopic, project) + input,
78
+ options: sideCallOptions('You are a topic summarizer.', controller),
79
+ });
80
+ let collected = '';
81
+ for await (const message of response) {
82
+ if (message.type === 'assistant') {
83
+ for (const block of message.message.content) {
84
+ if (block.type === 'text')
85
+ collected += block.text;
86
+ }
87
+ }
88
+ if (message.type === 'result')
89
+ break;
90
+ }
91
+ return sanitizeTwoPartTopic(collected);
92
+ }
93
+ catch (err) {
94
+ if (controller.signal.aborted)
95
+ return undefined;
96
+ console.debug('[AutoTopic] Haiku side-call failed:', err instanceof Error ? err.message : err);
97
+ return undefined;
98
+ }
99
+ finally {
100
+ clearTimeout(timer);
101
+ }
102
+ }
103
+ function cleanPart(raw) {
104
+ const cleaned = raw
105
+ .trim()
106
+ .replace(/^["'`*_]+|["'`*_]+$/g, '')
107
+ .replace(/[.!?,:;]+$/g, '')
108
+ .trim();
109
+ return cleaned || undefined;
110
+ }
111
+ function sanitizeTwoPartTopic(raw) {
112
+ const firstLine = raw.trim().split(/\n/)[0]?.trim() ?? '';
113
+ if (!firstLine)
114
+ return undefined;
115
+ // Strict: require the pipe. If Haiku didn't follow the format we'd rather
116
+ // skip this turn (keeping the prior topic) than render conversational prose.
117
+ const pipeIdx = firstLine.indexOf('|');
118
+ if (pipeIdx < 0)
119
+ return undefined;
120
+ const general = cleanPart(firstLine.slice(0, pipeIdx));
121
+ const current = cleanPart(firstLine.slice(pipeIdx + 1));
122
+ if (!general || !current)
123
+ return undefined;
124
+ return `${general}${TOPIC_PART_SEPARATOR}${current}`;
125
+ }
126
+ //# sourceMappingURL=auto-topic-haiku.js.map