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,9 @@
1
+ const BOT_START_TIME = Date.now();
2
+ const STALE_THRESHOLD = 30000; // 30 seconds
3
+ export function isStaleMessage(messageDate) {
4
+ // messageDate is Unix timestamp in seconds, convert to ms
5
+ const messageDateMs = messageDate * 1000;
6
+ // Ignore messages sent before bot started (minus threshold)
7
+ return messageDateMs < BOT_START_TIME - STALE_THRESHOLD;
8
+ }
9
+ //# sourceMappingURL=stale-filter.js.map
@@ -0,0 +1,8 @@
1
+ {
2
+ "version": "1.3.0",
3
+ "commit": "7a9fc17",
4
+ "subject": "release: 1.3.0",
5
+ "dirty": false,
6
+ "sourceHash": "f5119649be2ee357",
7
+ "builtAt": "2026-12-01T05:40:17.889Z"
8
+ }
@@ -0,0 +1,517 @@
1
+ /**
2
+ * Multi-question forms for telecoder_ask_user.
3
+ *
4
+ * One `telecoder_ask_user` call answers one question, and a tap on it is
5
+ * final: the answer goes to Claude at once, so there is nothing to go back to.
6
+ * Claude Code's own AskUserQuestion dialog is different — several questions
7
+ * sit side by side, you can move between them and change your mind, and
8
+ * nothing is sent until you submit. This module is that dialog in a Telegram
9
+ * message.
10
+ *
11
+ * The model passes `questions` (2–4, each with 2–8 options) and the user gets
12
+ * ONE message. Its body lists every question; the one being answered has its
13
+ * options written out and on the keyboard, an answered one shows its answer.
14
+ * A tap on an option records it and moves on to the next unanswered question;
15
+ * a row of numbered buttons jumps to any question, answered or not, so an
16
+ * earlier answer can be changed; and once every question has an answer a
17
+ * Submit button appears. Only Submit resolves the tool call. The agent loop
18
+ * waits throughout, like a single question.
19
+ *
20
+ * A message sent while the form is open answers the question on screen in the
21
+ * user's own words, as the "Type something" row does in Claude Code's dialog
22
+ * (see typed-answer.ts), and moves on the way a tap does.
23
+ *
24
+ * The form is in-memory, like single questions: a restart forgets it, and the
25
+ * first tap afterwards takes the dead keyboard down. One clock for all of it
26
+ * (QUESTION_TIMEOUT_MINUTES), from posting to Submit.
27
+ *
28
+ * Callback data (≤ 64 bytes, id is 8 hex chars):
29
+ * qf:<id>:o:<q>:<idx> pick option idx on question q
30
+ * qf:<id>:g:<q> go to question q
31
+ * qf:<id>:s submit
32
+ */
33
+ import * as crypto from 'crypto';
34
+ import { buildLetteredKeyboard, letteredOptionLines, optionLetter, } from '../telegram/lettered-options.js';
35
+ import { describeResponderRefusal } from '../telegram/admin-mention.js';
36
+ import { answerOrHangUp, buildAskUserExpiredNote, closeExpiredQuestion, closeWithdrawnQuestion, noteAwaitingUser, questionTimeoutMinutes, questionTimeoutMs, } from './ask-user.js';
37
+ import { TYPED_ANSWER_HINT, acceptTypedAnswers, acknowledgeTypedAnswer, shownTypedAnswer, } from './typed-answer.js';
38
+ /** As many questions as Claude Code's own dialog takes. */
39
+ export const MAX_FORM_QUESTIONS = 4;
40
+ export const MIN_FORM_OPTIONS = 2;
41
+ export const MAX_FORM_OPTIONS = 8;
42
+ /** Telegram's hard cap on a text message / message edit. */
43
+ const MAX_MESSAGE_LEN = 4096;
44
+ const pending = new Map();
45
+ // ── Parsing ──────────────────────────────────────────────────────────
46
+ /**
47
+ * Validate the `questions` argument as it arrives, straight off the IPC
48
+ * body. Returns the questions, or the error
49
+ * the model should read. A single question is not a form; the caller routes
50
+ * it through the ordinary one-question path.
51
+ */
52
+ export function parseFormQuestions(raw) {
53
+ if (!Array.isArray(raw))
54
+ return 'Error: `questions` must be an array.';
55
+ if (raw.length > MAX_FORM_QUESTIONS) {
56
+ return `Error: a form takes at most ${MAX_FORM_QUESTIONS} questions; split the rest into a second call.`;
57
+ }
58
+ const out = [];
59
+ for (const [i, q] of raw.entries()) {
60
+ if (!q || typeof q !== 'object')
61
+ return `Error: question ${i + 1} is not an object.`;
62
+ const qq = q;
63
+ const question = typeof qq.question === 'string' ? qq.question.trim() : '';
64
+ if (!question)
65
+ return `Error: question ${i + 1} has no text.`;
66
+ const options = parseOptions(qq.options);
67
+ if (options.length < MIN_FORM_OPTIONS || options.length > MAX_FORM_OPTIONS) {
68
+ return `Error: question ${i + 1} needs between ${MIN_FORM_OPTIONS} and ${MAX_FORM_OPTIONS} options.`;
69
+ }
70
+ out.push({ question, options });
71
+ }
72
+ return out;
73
+ }
74
+ /** The options of one question as they arrive, dropping anything malformed. */
75
+ export function parseOptions(raw) {
76
+ if (!Array.isArray(raw))
77
+ return [];
78
+ return raw
79
+ .map((o) => {
80
+ if (!o || typeof o !== 'object')
81
+ return null;
82
+ const oo = o;
83
+ if (typeof oo.label !== 'string' || !oo.label.trim())
84
+ return null;
85
+ return {
86
+ label: oo.label,
87
+ ...(typeof oo.description === 'string' ? { description: oo.description } : {}),
88
+ };
89
+ })
90
+ .filter((o) => o !== null);
91
+ }
92
+ /**
93
+ * Sort a call's arguments into a form or a single question. `questions` wins
94
+ * when given; a one-entry `questions` is just a single question. The string
95
+ * is the error the model reads.
96
+ */
97
+ export function resolveAskUserArgs(raw) {
98
+ if (Array.isArray(raw.questions) && raw.questions.length > 0) {
99
+ const parsed = parseFormQuestions(raw.questions);
100
+ if (typeof parsed === 'string')
101
+ return parsed;
102
+ if (parsed.length === 1)
103
+ return { question: parsed[0].question, options: parsed[0].options };
104
+ return { form: parsed };
105
+ }
106
+ const question = typeof raw.question === 'string' ? raw.question.trim() : '';
107
+ const options = parseOptions(raw.options);
108
+ if (!question || options.length < MIN_FORM_OPTIONS) {
109
+ return 'Error: ask_user requires a non-empty question and ≥ 2 options, or a `questions` array.';
110
+ }
111
+ return { question, options };
112
+ }
113
+ // ── Rendering ────────────────────────────────────────────────────────
114
+ function oneLine(text) {
115
+ return text.replace(/\s+/g, ' ').trim();
116
+ }
117
+ function answerLine(q, pick) {
118
+ if (typeof pick === 'string')
119
+ return ` ✅ ${shownTypedAnswer(pick)}`;
120
+ return ` ✅ ${optionLetter(pick)}. ${oneLine(q.options[pick].label)}`;
121
+ }
122
+ function allAnswered(view) {
123
+ return view.answers.every((a) => a !== undefined);
124
+ }
125
+ /**
126
+ * The message body for a form in a given state, and the keyboard under it.
127
+ *
128
+ * The body is the one place every option is guaranteed to reach the user in
129
+ * full (see lettered-options.ts), so the current question's options are
130
+ * written out there, lettered, and its buttons carry the same letters. The
131
+ * other questions take one line each — their answer if they have one — so the
132
+ * message stays a form and not a wall; jumping to one brings its options back.
133
+ *
134
+ * `context` is trimmed to whatever room the questions leave under Telegram's
135
+ * 4096 limit, so a form never fails to post for being wordy.
136
+ */
137
+ export function renderForm(view) {
138
+ const n = view.questions.length;
139
+ const done = allAnswered(view);
140
+ const header = done
141
+ ? `📋 ${n} questions · all answered — check them, then Submit`
142
+ : `📋 ${n} questions · answer each, then Submit. You can change an answer until then.`;
143
+ const body = [];
144
+ view.questions.forEach((q, i) => {
145
+ const answer = view.answers[i];
146
+ if (i === view.cur) {
147
+ body.push('');
148
+ body.push(`▶ ${i + 1}. ${oneLine(q.question)}`);
149
+ letteredOptionLines(q.options).forEach((line, idx) => {
150
+ body.push(idx === answer ? ` ✅ ${line}` : ` ${line}`);
151
+ });
152
+ body.push(typeof answer === 'string' ? answerLine(q, answer) : ` ${TYPED_ANSWER_HINT}`);
153
+ }
154
+ else {
155
+ body.push('');
156
+ body.push(`${i + 1}. ${oneLine(q.question)}`);
157
+ if (answer !== undefined)
158
+ body.push(answerLine(q, answer));
159
+ }
160
+ });
161
+ const text = fitWithContext(header, view.context, body.join('\n'));
162
+ return { text, keyboard: buildFormKeyboard(view) };
163
+ }
164
+ /** The body once submitted: every question with its answer, nothing to tap. */
165
+ export function renderSubmittedForm(view) {
166
+ const lines = [];
167
+ view.questions.forEach((q, i) => {
168
+ const answer = view.answers[i];
169
+ lines.push('');
170
+ lines.push(`${i + 1}. ${oneLine(q.question)}`);
171
+ if (answer !== undefined)
172
+ lines.push(answerLine(q, answer));
173
+ });
174
+ return fitWithContext(`📋 ${view.questions.length} questions · ✅ Submitted`, view.context, lines.join('\n'));
175
+ }
176
+ /**
177
+ * Header, context and body joined, with the context clipped to fit Telegram's
178
+ * limit — and, should the questions alone overflow it, the whole text clipped
179
+ * as a last resort rather than letting sendMessage 400.
180
+ */
181
+ function fitWithContext(header, context, body) {
182
+ const ctx = context?.trim() ?? '';
183
+ const join = (c) => (c ? `${header}\n\n${c}\n${body}` : `${header}\n${body}`);
184
+ let text = join(ctx);
185
+ if (text.length > MAX_MESSAGE_LEN && ctx) {
186
+ const room = ctx.length - (text.length - MAX_MESSAGE_LEN) - 1;
187
+ text = join(room > 0 ? ctx.slice(0, room) + '…' : '');
188
+ }
189
+ if (text.length > MAX_MESSAGE_LEN)
190
+ text = text.slice(0, MAX_MESSAGE_LEN - 1) + '…';
191
+ return text;
192
+ }
193
+ export function buildFormKeyboard(view) {
194
+ const rows = [];
195
+ const q = view.questions[view.cur];
196
+ if (q) {
197
+ rows.push(...buildLetteredKeyboard(q.options.map((o, idx) => ({ label: o.label, callbackData: `qf:${view.id}:o:${view.cur}:${idx}` }))));
198
+ }
199
+ rows.push(view.questions.map((_, i) => ({
200
+ text: i === view.cur ? `▶ ${i + 1}` : view.answers[i] !== undefined ? `${i + 1} ✓` : `${i + 1}`,
201
+ callback_data: `qf:${view.id}:g:${i}`,
202
+ })));
203
+ if (allAnswered(view))
204
+ rows.push([{ text: '✅ Submit', callback_data: `qf:${view.id}:s` }]);
205
+ return rows;
206
+ }
207
+ /** What the model reads back once the form is submitted. A typed answer goes as typed, line breaks and all. */
208
+ export function formatFormAnswers(answers) {
209
+ return [
210
+ 'User answered:',
211
+ ...answers.map((a, i) => {
212
+ const answer = a.typed ? `in their own words: ${a.label.trim().replace(/\n/g, '\n ')}` : oneLine(a.label);
213
+ return `${i + 1}. ${oneLine(a.question)} → ${answer}`;
214
+ }),
215
+ ].join('\n');
216
+ }
217
+ /**
218
+ * The confirmation posted as a reply once a form is submitted — the same
219
+ * reasons as buildAnswerConfirmation: an edit is silent and anonymous.
220
+ */
221
+ export function buildFormConfirmation(answers, opts) {
222
+ const who = opts.isPrivate ? 'You' : opts.who?.trim() || 'Someone';
223
+ const shown = (a) => (a.typed ? shownTypedAnswer(a.label) : oneLine(a.label));
224
+ return `✅ ${who} answered: ${answers.map((a, i) => `${i + 1}. ${shown(a)}`).join(' · ')}`;
225
+ }
226
+ // ── Registry ─────────────────────────────────────────────────────────
227
+ function clearPending(id) {
228
+ const entry = pending.get(id);
229
+ if (!entry)
230
+ return undefined;
231
+ pending.delete(id);
232
+ clearTimeout(entry.timer);
233
+ entry.endWait();
234
+ return entry;
235
+ }
236
+ /**
237
+ * Register a form. The promise resolves with every answer once the user taps
238
+ * Submit, or `null` when the clock runs out first. `form` is the live state
239
+ * the caller posts and, on expiry, closes; the registry drops it on resolve.
240
+ */
241
+ export function createPendingForm(questions, context, timeoutMs = questionTimeoutMs(), sessionKey, allowedResponderIds) {
242
+ const id = crypto.randomBytes(4).toString('hex');
243
+ let resolveFn;
244
+ const promise = new Promise((resolve) => {
245
+ resolveFn = resolve;
246
+ });
247
+ const timer = setTimeout(() => {
248
+ const entry = clearPending(id);
249
+ if (entry)
250
+ entry.resolve(null);
251
+ }, timeoutMs);
252
+ const state = {
253
+ id,
254
+ questions,
255
+ context,
256
+ answers: questions.map(() => undefined),
257
+ cur: 0,
258
+ resolve: resolveFn,
259
+ timer,
260
+ endWait: sessionKey ? noteAwaitingUser(sessionKey) : () => { },
261
+ lastText: '',
262
+ ...(allowedResponderIds && allowedResponderIds.length > 0 ? { allowedResponderIds } : {}),
263
+ };
264
+ state.lastText = renderForm(state).text;
265
+ pending.set(id, state);
266
+ return { id, promise, form: state };
267
+ }
268
+ export function hasPendingForm(id) {
269
+ return pending.has(id);
270
+ }
271
+ /** Decode a `qf:` callback, or undefined for one that is not well formed. */
272
+ export function parseFormCallback(data) {
273
+ const parts = data.split(':');
274
+ if (parts[0] !== 'qf' || !parts[1])
275
+ return undefined;
276
+ const id = parts[1];
277
+ const num = (s) => (s !== undefined && /^\d+$/.test(s) ? Number(s) : undefined);
278
+ switch (parts[2]) {
279
+ case 'o': {
280
+ const question = num(parts[3]);
281
+ const index = num(parts[4]);
282
+ if (question === undefined || index === undefined || parts.length !== 5)
283
+ return undefined;
284
+ return { id, tap: { kind: 'option', question, index } };
285
+ }
286
+ case 'g': {
287
+ const question = num(parts[3]);
288
+ if (question === undefined || parts.length !== 4)
289
+ return undefined;
290
+ return { id, tap: { kind: 'goto', question } };
291
+ }
292
+ case 's':
293
+ return parts.length === 3 ? { id, tap: { kind: 'submit' } } : undefined;
294
+ default:
295
+ return undefined;
296
+ }
297
+ }
298
+ /**
299
+ * Apply one tap to a form. The option tap names its question, not "the
300
+ * current one": two quick taps before Telegram redraws the keyboard must not
301
+ * land the second on the question the first moved to.
302
+ *
303
+ * The responder check lives here for the same reason as in ask-user.ts: a
304
+ * restricted form must be impossible to advance without saying who tapped.
305
+ */
306
+ export function tapForm(id, tap, responderId) {
307
+ const entry = openForm(id, responderId);
308
+ if (!('questions' in entry))
309
+ return entry;
310
+ let toast;
311
+ const n = entry.questions.length;
312
+ switch (tap.kind) {
313
+ case 'option': {
314
+ const q = entry.questions[tap.question];
315
+ if (q && tap.index >= 0 && tap.index < q.options.length) {
316
+ entry.answers[tap.question] = tap.index;
317
+ entry.cur = nextUnanswered(entry.answers, tap.question);
318
+ }
319
+ break;
320
+ }
321
+ case 'goto':
322
+ if (tap.question >= 0 && tap.question < n)
323
+ entry.cur = tap.question;
324
+ break;
325
+ case 'submit': {
326
+ if (allAnswered(entry)) {
327
+ clearPending(id);
328
+ const answers = entry.questions.map((q, i) => {
329
+ const pick = entry.answers[i];
330
+ return typeof pick === 'string'
331
+ ? { question: q.question, index: -1, label: pick, typed: true }
332
+ : { question: q.question, index: pick, label: q.options[pick].label };
333
+ });
334
+ entry.resolve(answers);
335
+ return { kind: 'submitted', text: renderSubmittedForm(entry), answers };
336
+ }
337
+ entry.cur = nextUnanswered(entry.answers, -1);
338
+ toast = `Answer question ${entry.cur + 1} first.`;
339
+ break;
340
+ }
341
+ }
342
+ const drawn = renderForm(entry);
343
+ entry.lastText = drawn.text;
344
+ return { kind: 'redraw', ...drawn, ...(toast ? { toast } : {}) };
345
+ }
346
+ /**
347
+ * Answer the question on screen with text the user sent instead of tapping
348
+ * (see typed-answer.ts), and move on as a tap does. `none-open` when every
349
+ * question is answered and none is on screen, so there is nothing for the
350
+ * text to answer.
351
+ */
352
+ export function typeFormAnswer(id, text, responderId) {
353
+ const entry = openForm(id, responderId);
354
+ if (!('questions' in entry))
355
+ return entry;
356
+ if (entry.cur === -1)
357
+ return { kind: 'none-open' };
358
+ entry.answers[entry.cur] = text;
359
+ entry.cur = nextUnanswered(entry.answers, entry.cur);
360
+ const drawn = renderForm(entry);
361
+ entry.lastText = drawn.text;
362
+ return { kind: 'redraw', ...drawn };
363
+ }
364
+ /** The open form this responder may answer, or the outcome that says why not. */
365
+ function openForm(id, responderId) {
366
+ const entry = pending.get(id);
367
+ if (!entry)
368
+ return { kind: 'expired' };
369
+ const allowed = entry.allowedResponderIds;
370
+ if (allowed && (responderId === undefined || !allowed.includes(responderId))) {
371
+ return { kind: 'forbidden', allowed };
372
+ }
373
+ return entry;
374
+ }
375
+ /** The first unanswered question after `from`, wrapping round; -1 when none. */
376
+ function nextUnanswered(answers, from) {
377
+ const n = answers.length;
378
+ for (let step = 1; step <= n; step++) {
379
+ const i = (from + step) % n;
380
+ if (answers[i] === undefined)
381
+ return i;
382
+ }
383
+ return -1;
384
+ }
385
+ // ── Posting and waiting ──────────────────────────────────────────────
386
+ /**
387
+ * Post a form and wait for Submit: the whole of what the IPC handler does
388
+ * once it has a chat to post into. Returns the text the model reads as its
389
+ * tool result, or null when `signal` hung up first and the form was withdrawn.
390
+ */
391
+ export async function runAskUserForm(opts) {
392
+ const { id, promise, form } = createPendingForm(opts.questions, opts.context, undefined, opts.sessionKey);
393
+ const { text, keyboard } = renderForm(form);
394
+ // Plain text, no parse_mode, for the reasons the single question gives: the
395
+ // text is the model's and a stray underscore would 400 the whole post.
396
+ const sent = await opts.api.sendMessage(opts.chatId, text, {
397
+ reply_markup: { inline_keyboard: keyboard },
398
+ ...(opts.threadId !== undefined ? { message_thread_id: opts.threadId } : {}),
399
+ });
400
+ await opts.onPosted?.();
401
+ const stopTypedAnswers = acceptTypedAnswers({
402
+ sessionKey: opts.sessionKey,
403
+ chatId: opts.chatId,
404
+ messageId: sent.message_id,
405
+ take: (ctx, typed) => takeTypedFormAnswer(opts.api, sent, id, ctx, typed),
406
+ });
407
+ const answers = await answerOrHangUp(promise, opts.signal);
408
+ stopTypedAnswers();
409
+ await opts.onSettled?.();
410
+ if (answers === 'hung-up') {
411
+ clearPending(id);
412
+ await closeWithdrawnQuestion(opts.api, sent, form.lastText);
413
+ return null;
414
+ }
415
+ if (!answers) {
416
+ await closeExpiredQuestion(opts.api, sent, form.lastText, buildAskUserExpiredNote());
417
+ return `User did not respond within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment or ask again.`;
418
+ }
419
+ return formatFormAnswers(answers);
420
+ }
421
+ /** A message sent while the form is open: the answer to the question on screen. */
422
+ async function takeTypedFormAnswer(api, sent, id, ctx, text) {
423
+ const outcome = typeFormAnswer(id, text, ctx.from?.id);
424
+ if (outcome.kind === 'expired' || outcome.kind === 'forbidden')
425
+ return false;
426
+ if (outcome.kind === 'none-open') {
427
+ // Kept out of the queue all the same: it would only wait there for a
428
+ // Submit that this message can't give.
429
+ await ctx.reply('Every question already has an answer. To change one, tap its number above and send the new answer, or tap Submit.', { reply_parameters: { message_id: ctx.message.message_id, allow_sending_without_reply: true } }).catch(() => { });
430
+ return true;
431
+ }
432
+ try {
433
+ await api.editMessageText(sent.chat.id, sent.message_id, outcome.text, {
434
+ reply_markup: { inline_keyboard: outcome.keyboard },
435
+ });
436
+ }
437
+ catch {
438
+ // As for a tap: the state moved on regardless, and the next redraw catches up.
439
+ }
440
+ await acknowledgeTypedAnswer(ctx);
441
+ return true;
442
+ }
443
+ // ── The tap handler ──────────────────────────────────────────────────
444
+ /**
445
+ * Telegram callback handler for `qf:` buttons. Registered in bot.ts outside
446
+ * the sequentialize middleware, like the single question's: the turn is
447
+ * blocked on this exact tap.
448
+ */
449
+ export async function handleAskUserFormCallback(ctx) {
450
+ const data = ctx.callbackQuery?.data;
451
+ if (!data)
452
+ return;
453
+ const parsed = parseFormCallback(data);
454
+ if (!parsed)
455
+ return;
456
+ const outcome = tapForm(parsed.id, parsed.tap, ctx.from?.id);
457
+ if (outcome.kind === 'expired') {
458
+ await ctx.answerCallbackQuery({ text: 'This form already closed.' });
459
+ // Closed by whoever was waiting on it, or forgotten by a restart: either
460
+ // way the keyboard must stop looking live.
461
+ try {
462
+ await ctx.editMessageReplyMarkup();
463
+ }
464
+ catch {
465
+ // Already gone, or not editable — nothing left to do.
466
+ }
467
+ return;
468
+ }
469
+ if (outcome.kind === 'forbidden') {
470
+ await ctx.answerCallbackQuery({
471
+ text: describeResponderRefusal(outcome.allowed, ctx.from?.id),
472
+ show_alert: true,
473
+ });
474
+ return;
475
+ }
476
+ await ctx.answerCallbackQuery(outcome.kind === 'redraw' && outcome.toast ? { text: outcome.toast } : undefined);
477
+ const message = ctx.callbackQuery?.message;
478
+ if (outcome.kind === 'redraw') {
479
+ try {
480
+ await ctx.editMessageText(outcome.text, { reply_markup: { inline_keyboard: outcome.keyboard } });
481
+ }
482
+ catch {
483
+ // A redraw to the same text ("message is not modified") or a message
484
+ // that cannot be edited: the state moved on regardless, and the next
485
+ // tap redraws again.
486
+ }
487
+ return;
488
+ }
489
+ try {
490
+ await ctx.editMessageText(outcome.text);
491
+ }
492
+ catch {
493
+ try {
494
+ await ctx.editMessageReplyMarkup();
495
+ }
496
+ catch {
497
+ // A second tap is answered "already closed" anyway.
498
+ }
499
+ }
500
+ try {
501
+ await ctx.reply(buildFormConfirmation(outcome.answers, {
502
+ isPrivate: ctx.chat?.type === 'private',
503
+ who: ctx.from?.first_name,
504
+ }), message?.message_id === undefined
505
+ ? undefined
506
+ : { reply_parameters: { message_id: message.message_id, allow_sending_without_reply: true } });
507
+ }
508
+ catch {
509
+ // Non-fatal — the submitted body above already records the answers.
510
+ }
511
+ }
512
+ /** For tests: forget every open form without resolving it. */
513
+ export function _resetFormsForTests() {
514
+ for (const id of [...pending.keys()])
515
+ clearPending(id);
516
+ }
517
+ //# sourceMappingURL=ask-user-form.js.map