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,817 @@
1
+ /**
2
+ * Putting a Claude Code dialog in the chat, and its answer back in the pty.
3
+ *
4
+ * The pty has no keyboard, so a dialog claude opens blocks forever unless
5
+ * someone answers it. Guessing the answer is not an option — the readiness
6
+ * check used to guess by accident, and pressing Enter at a dialog it had
7
+ * mistaken for the input box is enough to change a setting. So the dialog goes
8
+ * to the person the session belongs to, as buttons, and their tap becomes the
9
+ * keystrokes.
10
+ *
11
+ * Three rules the flow is built around:
12
+ *
13
+ * - Only offer what the dialog offers. Buttons come from its numbered rows
14
+ * and from the keys its own footer names; nothing is inferred. A dialog we
15
+ * cannot parse gets relayed as text with no buttons at all.
16
+ * - Confirm the cursor before committing. Arrow keys are written first and
17
+ * the screen re-read; Enter follows only once the glyph is on the intended
18
+ * row. A dialog that redrew under us, or moved in a way we did not model,
19
+ * stops here instead of committing the wrong row.
20
+ * - Silence presses nothing. On timeout the dialog is left exactly as it
21
+ * was. An unanswered dialog is a prompt that fails; a guessed one is a
22
+ * setting that changed, and only the second is unrecoverable.
23
+ *
24
+ * A dialog can also take more than one answer. `/mcp` is a menu several
25
+ * screens deep — its servers, then one server's actions, then that server's
26
+ * tools — and a tap that opens the next screen hasn't finished with the
27
+ * dialog, it has moved it on. So the relay follows it ({@link relayDialog})
28
+ * until claude is back at its input box, offering each screen as it offered
29
+ * the first.
30
+ *
31
+ * And some of it is answered in words. A dialog with a text field (`/add-dir`,
32
+ * `/export`'s file name, `/config`'s search) takes a message typed into it,
33
+ * and a permission prompt takes one as the note that goes with No. Both are
34
+ * ordinary messages sent while the dialog is open, as a typed answer to
35
+ * telecoder_ask_user is (typed-answer.ts). See {@link typedInput}.
36
+ *
37
+ * A dialog with tabs is several dialogs behind one heading. `/permissions`
38
+ * keeps its allow, ask and deny rules on a tab each, and `/status` is the
39
+ * first tab of the dialog `/config` and `/usage` open further along. Each tab
40
+ * gets a button, and the relay does the walking there ({@link switchTab}).
41
+ */
42
+ import * as path from 'path';
43
+ import { closeAnsweredQuestion, closeExpiredQuestion, createPendingQuestion, questionTimeoutMinutes, resolvePendingQuestionWithText, } from './ask-user.js';
44
+ import { arrowsTo, keystrokeFor, parseModal, tabsOn, } from './tui-modal.js';
45
+ import { hasInputBox, screenSignature } from './tui-state.js';
46
+ import { acceptTypedAnswers, acknowledgeTypedAnswer, shownTypedAnswer } from './typed-answer.js';
47
+ import { clip, EntityText } from '../telegram/entities.js';
48
+ import { parseSessionKey } from '../utils/session-key.js';
49
+ import { sanitizeError } from '../utils/sanitize.js';
50
+ /** Settle time after writing a key, before re-reading the screen. */
51
+ const KEY_SETTLE_MS = 400;
52
+ /**
53
+ * Gap between the arrow keys of one walk, so each arrives as a keystroke of
54
+ * its own. Short, because a walk can be long: a list that scrolls is a page of
55
+ * eighteen rows, and a page scroll is that many arrows twice. Measured against
56
+ * a live 2.1.310 pty, eighteen arrows sent back to back, and ten in a single
57
+ * write, all landed. The screen is re-read for where the cursor ended up
58
+ * either way.
59
+ */
60
+ const ARROW_GAP_MS = 20;
61
+ /** How often to look at the screen while waiting to see what a press did. */
62
+ const PRESS_POLL_MS = 100;
63
+ /** How long one arrow of a scroll gets to show up on screen before the scroll gives up. */
64
+ const REDRAW_MS = 500;
65
+ /** How long a tab gets to open after the arrow that asks for it. */
66
+ const TAB_SWITCH_MS = 1_500;
67
+ /**
68
+ * Most presses of ↓ spent getting a resting list to take the cursor. `/config`
69
+ * needs two from its tabs: one to the search box, one more to the list.
70
+ */
71
+ const MAX_WAKE_STEPS = 3;
72
+ /** Tab buttons to a row. Their names are short, and a dialog can have six. */
73
+ const TABS_PER_ROW = 2;
74
+ /**
75
+ * Most rows offered as buttons: a whole screenful, which at 40 rows is about
76
+ * twenty. A list longer than that scrolls, and its scroll buttons reach the
77
+ * rest.
78
+ */
79
+ const MAX_ROW_BUTTONS = 20;
80
+ /** The dialog on screen, read with everything the pty can say about it. */
81
+ function read(pty, screen = pty.screen()) {
82
+ return parseModal(screen, pty.marks?.());
83
+ }
84
+ /**
85
+ * The buttons a dialog earns. Numbered rows first, in the dialog's own order,
86
+ * then the footer keys that are answers rather than navigation — `Esc to
87
+ * cancel` is worth a button, `↑/↓ to select` is not, because the relay does
88
+ * the navigating. Enter is dropped when there are rows to pick, since picking
89
+ * a row already presses it.
90
+ *
91
+ * Doing the navigating includes scrolling. A list that runs past the screen
92
+ * gets a scroll button at each end it continues beyond, placed at that end,
93
+ * and each row it draws gets a button of its own. The cap of seven this used
94
+ * to have left `/mcp`'s 111-tool list reachable as far as its seventh tool.
95
+ *
96
+ * Tabs come first, one button for each the dialog isn't on. A lone `↓` in
97
+ * the footer is the way from the tabs into the list, and gets a button only
98
+ * while the list has no cursor to offer rows by. Once it has, a row's own
99
+ * button makes that step.
100
+ */
101
+ export function buildChoices(modal) {
102
+ const tabs = (modal.tabs?.names ?? []).flatMap((name, index) => (index === modal.tabs.active ? [] : [{ kind: 'tab', label: `Tab: ${name}`, index }]));
103
+ const rows = [];
104
+ if (modal.highlighted >= 0) {
105
+ for (const option of modal.options.slice(0, MAX_ROW_BUTTONS)) {
106
+ const prefix = option.number === undefined ? '' : `${option.number}. `;
107
+ rows.push({ kind: 'row', label: `${prefix}${option.label}`, index: option.index });
108
+ }
109
+ // A list that only marks its edge doesn't say how much lies past it.
110
+ const count = (n) => (modal.more.uncounted ? '' : ` (${n} more)`);
111
+ if (modal.more.above > 0) {
112
+ rows.unshift({ kind: 'page', label: `↑ Scroll up${count(modal.more.above)}`, direction: 'up' });
113
+ }
114
+ if (modal.more.below > 0) {
115
+ rows.push({ kind: 'page', label: `↓ Scroll down${count(modal.more.below)}`, direction: 'down' });
116
+ }
117
+ }
118
+ const keys = [];
119
+ for (const hint of modal.hints) {
120
+ if (rows.length > 0 && /^Enter/.test(hint.key))
121
+ continue;
122
+ if (hint.key === '↓' && rows.length > 0)
123
+ continue;
124
+ const key = keystrokeFor(hint.key);
125
+ if (key === null)
126
+ continue;
127
+ keys.push({ kind: 'key', label: `${hint.key} — ${hint.action}`, key });
128
+ }
129
+ return [...tabs, ...rows, ...keys];
130
+ }
131
+ /**
132
+ * The buttons as Telegram lays them out: one to a row, except tabs, which sit
133
+ * side by side as they do in the dialog. `data` gives each button's callback
134
+ * by its index in `labels`.
135
+ */
136
+ export function layOut(choices, labels, data) {
137
+ const rows = [];
138
+ let tabRow = null;
139
+ labels.forEach((text, index) => {
140
+ const button = { text, callback_data: data(index) };
141
+ if (choices[index]?.kind !== 'tab') {
142
+ tabRow = null;
143
+ rows.push([button]);
144
+ }
145
+ else if (tabRow && tabRow.length < TABS_PER_ROW) {
146
+ tabRow.push(button);
147
+ }
148
+ else {
149
+ tabRow = [button];
150
+ rows.push(tabRow);
151
+ }
152
+ });
153
+ return rows;
154
+ }
155
+ /**
156
+ * The message above the buttons: claude's dialog, laid out for a phone.
157
+ *
158
+ * The screen does not travel well as it is. Claude hard-wraps it at 120
159
+ * columns, which a phone then wraps again; the indentation and the gutter that
160
+ * set a command apart mean nothing in a proportional font; and the rows repeat
161
+ * the buttons with a cursor glyph nobody can move. So the body goes out as the
162
+ * parts {@link parseModal} read it into — title and question in bold, drawn
163
+ * content in a monospace block, each row once in full, since its button is
164
+ * clipped.
165
+ *
166
+ * Entities rather than a parse mode: the body is claude's own render, and the
167
+ * underscores and asterisks of whatever command it is asking about would be
168
+ * read as Markdown and 400 the send.
169
+ */
170
+ export function buildModalMessage(modal, cwd, stage) {
171
+ const b = new EntityText();
172
+ b.add('⌨️ ').bold('Claude Code needs an answer').newline();
173
+ b.add('Project: ').bold(path.basename(cwd) || cwd).newline(2);
174
+ appendDialog(b, modal);
175
+ return b.newline(2).italic(closingLine(modal, stage)).build();
176
+ }
177
+ function appendDialog(b, modal) {
178
+ const { parts } = modal;
179
+ // The line the rows answer — "Do you want to proceed?" — sits right above them.
180
+ const question = parts.findIndex((p) => p.kind === 'options') - 1;
181
+ parts.forEach((part, i) => {
182
+ if (i > 0)
183
+ b.newline(part.gapBefore ? 2 : 1);
184
+ if (part.kind === 'verbatim') {
185
+ b.pre(part.lines.join('\n'));
186
+ }
187
+ else if (part.kind === 'options') {
188
+ const { above, below, uncounted } = modal.more;
189
+ const count = (n) => (uncounted ? 'more' : `${n} more`);
190
+ [
191
+ ...(above > 0 ? [`↑ ${count(above)}`] : []),
192
+ ...modal.options.map((o) => {
193
+ const key = o.number === undefined ? '•' : `${o.number}.`;
194
+ return `${key} ${o.text}${o.detail ? ` — ${o.detail}` : ''}`;
195
+ }),
196
+ ...(below > 0 ? [`↓ ${count(below)}`] : []),
197
+ ].forEach((row, n) => b.newline(n > 0 ? 1 : 0).add(row));
198
+ }
199
+ else {
200
+ part.lines.forEach((line, n) => {
201
+ const heading = (i === 0 && n === 0)
202
+ || (i === question && n === part.lines.length - 1 && line.endsWith('?'));
203
+ b.newline(n > 0 ? 1 : 0);
204
+ if (heading)
205
+ b.bold(line);
206
+ else
207
+ b.add(line);
208
+ if (i === 0 && n === 0 && modal.tabs)
209
+ appendTabs(b.newline(), modal.tabs);
210
+ });
211
+ }
212
+ });
213
+ }
214
+ /** The dialog's tabs on one line, the open one in bold and brackets. */
215
+ function appendTabs(b, tabs) {
216
+ tabs.names.forEach((name, i) => {
217
+ if (i > 0)
218
+ b.add(' · ');
219
+ if (i === tabs.active)
220
+ b.bold(`[${name}]`);
221
+ else
222
+ b.add(name);
223
+ });
224
+ }
225
+ /**
226
+ * Why the turn stops at a dialog that is still open, for the chat.
227
+ *
228
+ * Where the turn stands decides what's true. Before a prompt, the user's
229
+ * message is what didn't happen: it was never typed in, and sending it again
230
+ * is the fix. Mid-turn it was delivered long before, and saying otherwise sent
231
+ * people off to resend a message claude already had. What stops there is the
232
+ * bot waiting on the turn, while claude stays paused on the dialog — and the
233
+ * next message meets it before anything else, with its buttons.
234
+ */
235
+ export function openDialogError(dialog, stage) {
236
+ if (stage === 'before-prompt') {
237
+ switch (dialog.kind) {
238
+ case 'still-open':
239
+ return `I pressed "${dialog.label}", but Claude Code hasn't returned to its input box, `
240
+ + "so your message wasn't delivered. Send it again in a moment.";
241
+ case 'timeout':
242
+ return "Nobody answered Claude Code's dialog, so I left it alone and your message wasn't "
243
+ + "delivered. Send it again to get the dialog's buttons back.";
244
+ default:
245
+ return `Your message wasn't delivered — ${dialog.why}. Claude Code is still waiting on that dialog.`;
246
+ }
247
+ }
248
+ switch (dialog.kind) {
249
+ case 'still-open':
250
+ return `I pressed "${dialog.label}", but Claude Code's dialog is still open, so I stopped `
251
+ + 'waiting on this turn. Your next message brings its buttons back.';
252
+ case 'timeout':
253
+ return "Nobody answered Claude Code's dialog, so I left it alone and stopped waiting on "
254
+ + 'this turn. Claude Code is paused on it until your next message, which brings its buttons back.';
255
+ default:
256
+ return `I stopped waiting on this turn — ${dialog.why}. Claude Code is still paused on that dialog.`;
257
+ }
258
+ }
259
+ /**
260
+ * What a message typed while `modal` is open does there, or null when the
261
+ * dialog has no place for words.
262
+ *
263
+ * Keys typed at a dialog with no such place are keystrokes: at a permission
264
+ * prompt a digit picks a row. So a message is only ever typed where the
265
+ * dialog shows it takes text, and there are two such places.
266
+ *
267
+ * `field`: the dialog draws a text field. The message replaces what the field
268
+ * holds, and the dialog is relayed again as it then stands, with the path's
269
+ * completions or the settings the search left, for a tap to commit. Nothing is
270
+ * committed by typing.
271
+ *
272
+ * `note`: a permission prompt whose footer says `Tab to amend`. Tab turns the
273
+ * row under the cursor into `…, and tell Claude what to do next`, on Yes as
274
+ * much as on No. A message goes to No, never to the row the cursor starts on,
275
+ * which is Yes: someone who writes "don't, use the staging database" at a
276
+ * prompt has not approved the command it asks about. Yes with a note stays a
277
+ * tap on Yes and a message after it.
278
+ */
279
+ export function typedInput(modal) {
280
+ if (modal.field)
281
+ return 'field';
282
+ const amends = modal.hints.some((hint) => hint.key === 'Tab' && /^amend\b/.test(hint.action));
283
+ return amends && refusalRow(modal) ? 'note' : null;
284
+ }
285
+ /** The row that says No and nothing else. */
286
+ function refusalRow(modal) {
287
+ return modal.options.find((option) => option.text === 'No');
288
+ }
289
+ /** What a tap does, what a message does, and what happens once either has. */
290
+ function closingLine(modal, stage) {
291
+ const typing = typedInput(modal);
292
+ const typed = typing === 'field'
293
+ ? "✏️ Send a message and I'll type it into the field, then show you the dialog again."
294
+ : typing === 'note'
295
+ ? '✏️ Or send a message saying what Claude should do instead. That answers No, with your note.'
296
+ : null;
297
+ if (buildChoices(modal).length === 0) {
298
+ return typed ?? 'It offers no key I can press from here, so it needs someone at the terminal.';
299
+ }
300
+ const tap = stage === 'before-prompt'
301
+ ? "Tap your answer and I'll press it in Claude Code, then send your message."
302
+ : "Tap your answer and I'll press it in Claude Code so it can carry on.";
303
+ return typed ? `${tap}\n${typed}` : tap;
304
+ }
305
+ /**
306
+ * Relay the dialog on screen to the chat and press whatever comes back — one
307
+ * screen of it; {@link relayDialog} follows it through the rest.
308
+ *
309
+ * Returns without pressing anything when the dialog cannot be parsed, when it
310
+ * offers nothing pressable, or when nobody answers — the caller turns each of
311
+ * those into a message saying the prompt was not delivered, which is the
312
+ * honest outcome and leaves the dialog for a person to deal with.
313
+ */
314
+ export async function relayModal(pty, sessionKey, ctx, cwd, stage) {
315
+ const modal = read(pty);
316
+ if (!modal)
317
+ return { kind: 'declined', why: 'the screen could not be read as a dialog' };
318
+ const choices = buildChoices(modal);
319
+ const typing = typedInput(modal);
320
+ const labels = [...choices.map((c) => c.label), '✋ Leave it alone'];
321
+ const message = buildModalMessage(modal, cwd, stage);
322
+ if (choices.length === 0 && !typing) {
323
+ await send(ctx, sessionKey, message, undefined);
324
+ return { kind: 'declined', why: 'the dialog offers no keys this bot can press' };
325
+ }
326
+ // Waits QUESTION_TIMEOUT_MINUTES, like any other question the turn asks.
327
+ const { id, promise } = createPendingQuestion(labels, undefined, sessionKey);
328
+ const keyboard = layOut(choices, labels, (idx) => `q:${id}:${idx}`);
329
+ const { sent, entities } = await send(ctx, sessionKey, message, keyboard);
330
+ // A message sent now is for the dialog, when it has a place for one.
331
+ const stopTyped = typing
332
+ ? acceptTypedAnswers({
333
+ sessionKey,
334
+ chatId: parseSessionKey(sessionKey).chatId,
335
+ messageId: sent.message_id,
336
+ take: async (msgCtx, text) => {
337
+ if (resolvePendingQuestionWithText(id, text, msgCtx.from?.id) !== 'resolved')
338
+ return false;
339
+ await acknowledgeTypedAnswer(msgCtx);
340
+ return true;
341
+ },
342
+ })
343
+ : undefined;
344
+ const answer = await promise;
345
+ stopTyped?.();
346
+ if (!answer) {
347
+ await closeExpiredQuestion(ctx.api, sent, message.text, `No answer within ${questionTimeoutMinutes()} min, so I left the dialog alone.`, entities);
348
+ return { kind: 'timeout' };
349
+ }
350
+ // A tap closes its question in bot.ts; a typed answer has no tap to do it.
351
+ if (answer.typed) {
352
+ await closeAnsweredQuestion(ctx.api, sent, message.text, shownTypedAnswer(answer.label), entities);
353
+ }
354
+ const choice = answer.typed ? undefined : choices[answer.index];
355
+ if (!answer.typed && !choice)
356
+ return { kind: 'declined', why: 'you chose to leave it alone' };
357
+ // The tap can come minutes after the message went out. A key meant for this
358
+ // dialog means something else anywhere else — at the input box, `s` is a
359
+ // letter typed into the next message — so look again before pressing it.
360
+ const screen = pty.screen();
361
+ const current = hasInputBox(screen) ? null : read(pty, screen);
362
+ if (!current || !sameDialog(current, modal)) {
363
+ return { kind: 'failed', why: 'the dialog changed before your answer reached it' };
364
+ }
365
+ if (!choice) {
366
+ return typedInput(current) === 'field'
367
+ ? typeIntoField(pty, current, answer.label)
368
+ : refuseWithNote(pty, current, answer.label);
369
+ }
370
+ if (choice.kind === 'key') {
371
+ pty.write(choice.key);
372
+ return { kind: 'answered', label: choice.label, dialog: current };
373
+ }
374
+ if (choice.kind === 'tab')
375
+ return switchTab(pty, current, choice.index, choice.label);
376
+ if (choice.kind === 'page') {
377
+ const awake = await wake(pty, current);
378
+ if ('kind' in awake)
379
+ return awake;
380
+ return awake.more.uncounted
381
+ ? reveal(pty, awake, choice.direction, choice.label)
382
+ : scroll(pty, awake, choice.direction, choice.label);
383
+ }
384
+ return pressOption(pty, current, choice.index, choice.label);
385
+ }
386
+ /**
387
+ * True when two reads are of the same dialog, whatever has changed inside it.
388
+ * A row can be redrawn while the dialog waits for its answer without changing
389
+ * what that answer presses. A different heading, a different number of rows,
390
+ * different keys in the footer or another tab would.
391
+ */
392
+ function sameDialog(a, b) {
393
+ return a.title === b.title && a.options.length === b.options.length && sameHints(a, b)
394
+ && a.tabs?.active === b.tabs?.active;
395
+ }
396
+ /** True when two reads show the dialog exactly as it was: same rows, same cursor, same keys. */
397
+ function drawnAlike(a, b) {
398
+ return screenSignature(a.body) === screenSignature(b.body) && sameHints(a, b);
399
+ }
400
+ function sameHints(a, b) {
401
+ return a.hints.length === b.hints.length
402
+ && a.hints.every((hint, i) => hint.key === b.hints[i].key && hint.action === b.hints[i].action);
403
+ }
404
+ /**
405
+ * Walk the cursor to `index` and commit — but only after seeing it arrive.
406
+ *
407
+ * The re-read is the whole point. Arrow keys are a bet that the dialog moves
408
+ * its cursor the way every dialog we measured moves it, and a bet that is
409
+ * wrong must not end in Enter: a dialog whose cursor did not land where we
410
+ * asked is one where Enter commits an option nobody chose.
411
+ */
412
+ async function pressOption(pty, modal, index, label) {
413
+ const landed = await walkTo(pty, modal, index);
414
+ if ('kind' in landed)
415
+ return landed;
416
+ pty.write('\r');
417
+ return { kind: 'answered', label, dialog: landed, option: modal.options[index] };
418
+ }
419
+ /** Walk the cursor to `index` and read the dialog back with it there, or say why it isn't. */
420
+ async function walkTo(pty, modal, index) {
421
+ // A list that isn't taking keys has to be given them before a walk along it
422
+ // can be counted.
423
+ const from = await wake(pty, modal);
424
+ if ('kind' in from)
425
+ return from;
426
+ const arrows = arrowsTo(from, index);
427
+ if (arrows === null)
428
+ return { kind: 'failed', why: 'the dialog\'s cursor position could not be read' };
429
+ for (const arrow of arrows) {
430
+ pty.write(arrow);
431
+ await delay(ARROW_GAP_MS);
432
+ }
433
+ await delay(KEY_SETTLE_MS);
434
+ const landed = read(pty);
435
+ if (!landed)
436
+ return { kind: 'failed', why: 'the dialog changed shape while being answered' };
437
+ // Which row the cursor is on is read off what the row says. A list that
438
+ // scrolls moves its rows under the cursor: past its first screen, `/mcp`'s
439
+ // tool list keeps the cursor on its bottom row and shifts the rest, so the
440
+ // row asked for is on screen but never at the index it was asked for at. A
441
+ // list that didn't scroll has to match on the index too, which is what
442
+ // tells apart two rows that read the same.
443
+ const wanted = modal.options[index];
444
+ const reached = landed.options[landed.highlighted];
445
+ const scrolled = landed.more.above !== modal.more.above || landed.more.below !== modal.more.below;
446
+ if (!reached || landed.resting || !sameRow(reached, wanted) || (!scrolled && landed.highlighted !== index)) {
447
+ return {
448
+ kind: 'failed',
449
+ why: `the cursor stopped on "${reached?.label ?? 'no row'}", not "${wanted.label}"`,
450
+ };
451
+ }
452
+ return landed;
453
+ }
454
+ /**
455
+ * Give a resting list the keys: ↓ until its cursor is drawn live.
456
+ *
457
+ * `/config` opens with its keys going to the search box and its list's cursor
458
+ * drawn grey on the first row. The first ↓ there moves to the list and leaves
459
+ * the cursor where it is, so a walk of three arrows to the fourth row ended
460
+ * on the third, and the row tapped was refused. From the dialog's tabs it is
461
+ * two presses, the search box being on the way. How many is read off the
462
+ * screen, not counted: the glyph turns from grey to its colour when the list
463
+ * has the keys.
464
+ *
465
+ * Returns the dialog as it then stands, which is `modal` itself for a list
466
+ * that was listening all along.
467
+ */
468
+ async function wake(pty, modal) {
469
+ let now = modal;
470
+ for (let presses = 0; now.resting && presses < MAX_WAKE_STEPS; presses++) {
471
+ pty.write('\x1b[B');
472
+ await delay(KEY_SETTLE_MS);
473
+ const next = read(pty);
474
+ if (!next || next.highlighted < 0) {
475
+ return { kind: 'failed', why: 'the dialog changed shape while being answered' };
476
+ }
477
+ now = next;
478
+ }
479
+ return now.resting ? { kind: 'failed', why: 'the dialog\'s list didn\'t take the cursor' } : now;
480
+ }
481
+ /** True when ←/→ will move along the dialog's tabs as it stands. */
482
+ function tabsListening(modal) {
483
+ if (modal.hints.some((hint) => hint.key.startsWith('←/→') && /^switch\b/.test(hint.action)))
484
+ return true;
485
+ // A tab with nothing to pick (`/status`) names no arrows at all, and its
486
+ // tabs take them: there is nowhere else for them to go.
487
+ return modal.highlighted < 0 && !modal.hints.some((hint) => /[↑↓←→]/u.test(hint.key));
488
+ }
489
+ /**
490
+ * Open the tab at `index`: get the keys to the row of tabs, then step along
491
+ * it, watching each step land.
492
+ *
493
+ * Where ←/→ go depends on which part of the dialog has the keys. With them on
494
+ * a list or in a search box they do something else, or nothing, and the tabs
495
+ * are reached by going up: `/config` says `↑ to tabs` from its search box,
496
+ * which is itself one ↑ above the top of its list. So ↑ is pressed until the
497
+ * footer says the arrows switch tabs, for at most the rows above the cursor
498
+ * and the two steps past them. A list that wraps at its top never gets
499
+ * there, and the switch is given up with the cursor moved and nothing else.
500
+ *
501
+ * Then one arrow for each tab between here and there, never round the end,
502
+ * and each has to open the tab next to the last. A tab opens before its
503
+ * content has loaded, so the steps are checked on the row of tabs alone.
504
+ */
505
+ async function switchTab(pty, modal, index, label) {
506
+ const failed = (why) => ({ kind: 'failed', why });
507
+ if (!modal.tabs || index < 0 || index >= modal.tabs.names.length) {
508
+ return failed('the dialog has no such tab');
509
+ }
510
+ let now = modal;
511
+ const climb = (now.highlighted >= 0 ? now.highlighted + now.more.above : 0) + 2;
512
+ for (let presses = 0; !tabsListening(now) && presses < climb; presses++) {
513
+ pty.write('\x1b[A');
514
+ const next = await redrawn(pty, now);
515
+ if (!next?.tabs)
516
+ return failed('the dialog\'s tabs couldn\'t be reached');
517
+ now = next;
518
+ }
519
+ if (!tabsListening(now) || !now.tabs)
520
+ return failed('the dialog\'s tabs couldn\'t be reached');
521
+ let at = now.tabs.active;
522
+ const arrow = index > at ? '\x1b[C' : '\x1b[D';
523
+ while (at !== index) {
524
+ const want = at + (index > at ? 1 : -1);
525
+ pty.write(arrow);
526
+ const opened = await tabOpened(pty, at);
527
+ if (opened !== want) {
528
+ return failed(`the dialog didn't open "${modal.tabs.names[want]}" when asked`);
529
+ }
530
+ at = want;
531
+ }
532
+ return { kind: 'answered', label, dialog: modal };
533
+ }
534
+ /** The tab that opened in place of `was`, or null if none did in time. */
535
+ async function tabOpened(pty, was) {
536
+ const deadline = Date.now() + TAB_SWITCH_MS;
537
+ while (Date.now() < deadline) {
538
+ await delay(ARROW_GAP_MS);
539
+ const tabs = tabsOn(pty.screen(), pty.marks?.());
540
+ if (tabs && tabs.active !== was)
541
+ return tabs.active;
542
+ }
543
+ return null;
544
+ }
545
+ /**
546
+ * True when two reads are of the same row. A numbered row can say more with
547
+ * the cursor on it than without: `/rewind` draws `4. Summarize from here`, and
548
+ * `4. Summarize from here: add context (optional)` once the cursor arrives. It
549
+ * is still row 4, so a row with a number matches when one text opens the other.
550
+ */
551
+ function sameRow(a, b) {
552
+ if (a.number !== b.number)
553
+ return false;
554
+ if (a.text === b.text)
555
+ return true;
556
+ return a.number !== undefined && (a.text.startsWith(b.text) || b.text.startsWith(a.text));
557
+ }
558
+ /** What a message comes to as keys: one line, with nothing in it a terminal would act on. */
559
+ function keyable(text) {
560
+ return text.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
561
+ }
562
+ /** The footer's `/ to search`: the list has the keys, and `/` hands them to the search box. */
563
+ function searchKey(hint) {
564
+ return hint.key === '/' && /^search\b/.test(hint.action);
565
+ }
566
+ /** How much of a typed message has to show up on screen to count as typed. */
567
+ const TYPED_NEEDLE = 16;
568
+ /**
569
+ * Type a message into the dialog's text field, in place of what it holds.
570
+ *
571
+ * Ctrl+U first: `/export` opens with a file name already in its field, and a
572
+ * name typed after it would be appended to it. On an empty field the press
573
+ * does nothing. Then the field is read back, because text that didn't arrive
574
+ * is a dialog about to be confirmed with something else in it. A field
575
+ * narrower than the text shows the end of it, so either end counts.
576
+ *
577
+ * Before any of it, the keys have to be going to the field. `/config` keeps
578
+ * them on its list once a row has been picked, and says `/ to search`.
579
+ */
580
+ async function typeIntoField(pty, modal, text) {
581
+ const line = keyable(text);
582
+ if (!line)
583
+ return { kind: 'failed', why: 'the message had no text to type' };
584
+ // With the keys on a list, text is keys pressed at it, and `/config` reads
585
+ // Space as "change this setting". Where the footer names the key that moves
586
+ // to the search box, that comes first, and has to have worked.
587
+ if (modal.hints.some(searchKey)) {
588
+ pty.write('/');
589
+ await delay(KEY_SETTLE_MS);
590
+ const focused = read(pty);
591
+ if (!focused?.field || focused.hints.some(searchKey)) {
592
+ return { kind: 'failed', why: 'the dialog\'s search box didn\'t take the keys' };
593
+ }
594
+ }
595
+ pty.write('\x15');
596
+ await delay(KEY_SETTLE_MS);
597
+ pty.write(line);
598
+ await delay(KEY_SETTLE_MS);
599
+ const shown = read(pty)?.field?.value.replace(/\s+/g, ' ');
600
+ if (!shown || !(shown.includes(line.slice(0, TYPED_NEEDLE)) || shown.includes(line.slice(-TYPED_NEEDLE)))) {
601
+ return { kind: 'failed', why: 'the dialog\'s field didn\'t take the text' };
602
+ }
603
+ return { kind: 'answered', label: `typed “${clip(line, 40)}”`, dialog: modal };
604
+ }
605
+ /**
606
+ * Answer a permission prompt No, with a note: walk to No, Tab, type, Enter.
607
+ *
608
+ * Each step is read back before the next. Tab has to have turned the row into
609
+ * `No, and tell Claude what to do differently`, or the note would be typed at
610
+ * a list, where its letters and digits are keys. And the note has to be in the
611
+ * row before Enter, or Enter sends a bare No and the note is lost.
612
+ */
613
+ async function refuseWithNote(pty, modal, text) {
614
+ const line = keyable(text);
615
+ const no = refusalRow(modal);
616
+ if (!line || !no)
617
+ return { kind: 'failed', why: 'this dialog has no place for a note' };
618
+ const landed = await walkTo(pty, modal, no.index);
619
+ if ('kind' in landed)
620
+ return landed;
621
+ pty.write('\t');
622
+ await delay(KEY_SETTLE_MS);
623
+ const amended = read(pty);
624
+ const field = amended?.options[amended.highlighted];
625
+ if (!amended || !field || field.number !== no.number || field.text === no.text || !/^No\b/.test(field.text)) {
626
+ return { kind: 'failed', why: 'the dialog didn\'t open a note on its No row' };
627
+ }
628
+ pty.write(line);
629
+ await delay(KEY_SETTLE_MS);
630
+ const typed = read(pty);
631
+ const row = typed?.options[typed.highlighted];
632
+ if (!typed || !row || row.number !== no.number || !row.text.includes(line.slice(0, TYPED_NEEDLE))) {
633
+ return { kind: 'failed', why: 'the dialog didn\'t take the note' };
634
+ }
635
+ pty.write('\r');
636
+ return { kind: 'answered', label: `No — ${clip(line, 40)}`, dialog: typed, option: no };
637
+ }
638
+ /**
639
+ * Bring one more row of a windowed list into view.
640
+ *
641
+ * A list that marks its edge with a bare arrow says only that it goes on, so
642
+ * there is no count to scroll by ({@link scroll}). Its window moves when the
643
+ * cursor steps past the edge row, one row a step. So: walk to the edge row,
644
+ * step once more, which the marker says is there to step to, and check the
645
+ * cursor is still on the edge with a new row under it. Then one step back.
646
+ * The cursor hides the marker of the row it is on, so with it left on the edge
647
+ * the next screen could not say whether the list goes on further.
648
+ */
649
+ async function reveal(pty, modal, direction, label) {
650
+ const [on, back] = direction === 'down' ? ['\x1b[B', '\x1b[A'] : ['\x1b[A', '\x1b[B'];
651
+ const edgeOf = (m) => (direction === 'down' ? m.options.length - 1 : 0);
652
+ const atEdge = await walkTo(pty, modal, edgeOf(modal));
653
+ if ('kind' in atEdge)
654
+ return atEdge;
655
+ pty.write(on);
656
+ const shifted = await redrawn(pty, atEdge);
657
+ const was = atEdge.options[atEdge.highlighted];
658
+ const now = shifted?.options[shifted.highlighted];
659
+ if (!shifted || !now || !was || shifted.highlighted !== edgeOf(shifted) || sameRow(now, was)) {
660
+ return { kind: 'failed', why: 'the list didn\'t move on the way it said it would' };
661
+ }
662
+ pty.write(back);
663
+ await redrawn(pty, shifted);
664
+ return { kind: 'answered', label, dialog: modal };
665
+ }
666
+ /**
667
+ * Scroll a long list on by a screenful less one row. The one row is what
668
+ * keeps the screens joined: a list that has scrolled draws a marker at the
669
+ * end it came from, in a row's place, and a whole screenful would carry the
670
+ * row beside the old screen past without ever drawing it.
671
+ *
672
+ * One arrow at a time, with the list read after each, until its `↓ 92 more`
673
+ * has come down by that much. Counting the presses ahead of time would mean
674
+ * knowing how the list scrolls, and lists don't agree: some move the cursor
675
+ * to their edge before the rows move at all, while `/mcp`'s tool list, once
676
+ * past its first screen, moves every row on every press. Nothing is committed
677
+ * either way, so nothing needs confirming. Wherever the list ends up is the
678
+ * next screen, and it is relayed like any other.
679
+ */
680
+ async function scroll(pty, modal, direction, label) {
681
+ const hidden = (m) => (direction === 'down' ? m.more.below : m.more.above);
682
+ if (modal.highlighted < 0 || hidden(modal) === 0) {
683
+ return { kind: 'failed', why: 'the list had nothing further to scroll to' };
684
+ }
685
+ const arrow = direction === 'down' ? '\x1b[B' : '\x1b[A';
686
+ const goal = Math.max(0, hidden(modal) - Math.max(1, modal.options.length - 1));
687
+ // A walk to the edge and a page past it is the most this takes. A list
688
+ // still short of the goal after that isn't scrolling the way it says.
689
+ const most = 2 * modal.options.length + hidden(modal);
690
+ let now = modal;
691
+ for (let presses = 0; hidden(now) > goal && presses < most; presses++) {
692
+ pty.write(arrow);
693
+ const next = await redrawn(pty, now);
694
+ if (!next)
695
+ return { kind: 'failed', why: 'the list stopped moving while being scrolled' };
696
+ now = next;
697
+ }
698
+ return { kind: 'answered', label, dialog: modal };
699
+ }
700
+ /** The dialog once the screen has redrawn after a key, or null if it doesn't redraw in time. */
701
+ async function redrawn(pty, before) {
702
+ const deadline = Date.now() + REDRAW_MS;
703
+ while (Date.now() < deadline) {
704
+ await delay(ARROW_GAP_MS);
705
+ const screen = pty.screen();
706
+ const next = hasInputBox(screen) ? null : read(pty, screen);
707
+ if (next && !drawnAlike(next, before))
708
+ return next;
709
+ }
710
+ return null;
711
+ }
712
+ /**
713
+ * The dialog standing between claude and the end of a turn, or null.
714
+ *
715
+ * Both halves matter. Claude draws its input box for the whole of a working
716
+ * turn, so the box being *gone* is what separates a dialog from ordinary
717
+ * progress; and an ordinary footer (`⏵⏵ bypass permissions on · ← for agents`)
718
+ * parses as no dialog, so a half-drawn frame can't be mistaken for one.
719
+ *
720
+ * Split out from the caller because this is the judgement that decides whether
721
+ * a turn gets interrupted, and it is worth being able to point real screens at.
722
+ */
723
+ export function blockingModal(screenText, marks) {
724
+ if (hasInputBox(screenText))
725
+ return null;
726
+ return parseModal(screenText, marks);
727
+ }
728
+ /**
729
+ * Relay a dialog, and keep relaying it for as long as answering it leads on
730
+ * to more of it.
731
+ *
732
+ * Every press used to be expected to close the dialog. In `/mcp` that holds
733
+ * only for the last one: picking a server opens that server's screen, `View
734
+ * tools` opens its tool list, and Esc there steps back up a level rather than
735
+ * out. The first tap left the menu on whatever screen it opened and ended the
736
+ * turn calling the dialog still open — so a menu could be opened from the
737
+ * chat, and never used. What a press leads to is looked at instead: claude
738
+ * back at its input box ends the relay, a screen that differs from the one
739
+ * answered is relayed in its turn, and only a press that changes nothing
740
+ * leaves the dialog counted as still open.
741
+ *
742
+ * No count caps the screens. Each one waits on a tap, and each offers "Leave
743
+ * it alone", so the person answering decides when it ends.
744
+ */
745
+ export async function relayDialog(pty, sessionKey, ctx, cwd, stage, timing) {
746
+ const steps = [];
747
+ for (;;) {
748
+ const outcome = await relayModal(pty, sessionKey, ctx, cwd, stage);
749
+ if (outcome.kind !== 'answered')
750
+ return outcome;
751
+ steps.push({ dialog: outcome.dialog, label: outcome.label, ...(outcome.option ? { option: outcome.option } : {}) });
752
+ const next = await afterPress(pty, outcome.dialog, timing);
753
+ if (next === 'closed')
754
+ return { kind: 'closed', label: outcome.label, steps };
755
+ if (next === 'unchanged')
756
+ return { kind: 'still-open', label: outcome.label };
757
+ }
758
+ }
759
+ /**
760
+ * Where a press left the dialog: closed, moved on to a screen of its own, or
761
+ * still showing exactly what was answered when the deadline came.
762
+ *
763
+ * Closed counts the moment the input box is back, as it always has. A new
764
+ * screen has to stand still first, as a screen must before the readiness wait
765
+ * will read it: a read taken while claude is still drawing can catch a frame
766
+ * halfway, and buttons built from it would be for a dialog that was never on
767
+ * screen. Only a press that changed nothing at all waits out the deadline.
768
+ */
769
+ export async function afterPress(pty, pressed, timing) {
770
+ const deadline = Date.now() + timing.clearMs;
771
+ let seen = null;
772
+ let stillSince = Date.now();
773
+ while (Date.now() < deadline) {
774
+ const screen = pty.screen();
775
+ if (hasInputBox(screen))
776
+ return 'closed';
777
+ const signature = screenSignature(screen);
778
+ if (signature !== seen) {
779
+ seen = signature;
780
+ stillSince = Date.now();
781
+ }
782
+ else if (Date.now() - stillSince >= timing.settleMs) {
783
+ const modal = read(pty, screen);
784
+ if (modal && !drawnAlike(modal, pressed))
785
+ return 'moved';
786
+ }
787
+ await delay(PRESS_POLL_MS);
788
+ }
789
+ return 'unchanged';
790
+ }
791
+ function delay(ms) {
792
+ return new Promise((r) => setTimeout(r, ms));
793
+ }
794
+ /**
795
+ * Send the dialog, and say which entities it went out with — closing it later
796
+ * has to repeat them, or the edit strips the formatting.
797
+ */
798
+ async function send(ctx, sessionKey, message, keyboard) {
799
+ const { chatId, threadId } = parseSessionKey(sessionKey);
800
+ const extra = {
801
+ ...(keyboard ? { reply_markup: { inline_keyboard: keyboard } } : {}),
802
+ ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
803
+ };
804
+ try {
805
+ const sent = await ctx.api.sendMessage(chatId, message.text, { ...extra, entities: message.entities });
806
+ return { sent, entities: message.entities };
807
+ }
808
+ catch (err) {
809
+ // Nothing in the text is parsed, so if Telegram refused it, an entity is
810
+ // what it refused — and that shouldn't cost the dialog its buttons, the
811
+ // only way to answer it from the chat. Anything else, like a network
812
+ // failure, fails the plain send too and surfaces as it always did.
813
+ console.warn('[ModalRelay] formatted dialog refused, sending it plain:', sanitizeError(err));
814
+ return { sent: await ctx.api.sendMessage(chatId, message.text, extra) };
815
+ }
816
+ }
817
+ //# sourceMappingURL=modal-relay.js.map