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,501 @@
1
+ /**
2
+ * Reading a blocking dialog off Claude Code's TUI.
3
+ *
4
+ * A pty has no one at the keyboard, so every dialog claude opens is a dead
5
+ * end: the input box is gone, the prompt we paste is swallowed by a list that
6
+ * ignores it, and whatever we press next lands on whichever option happens to
7
+ * be highlighted. The bot's answer is to put the dialog in the chat and let a
8
+ * person tap — which needs the dialog read off the screen first.
9
+ *
10
+ * What follows is a parser for the two shapes claude actually draws, measured
11
+ * against a live 120x40 pty:
12
+ *
13
+ * ❯ /model ← the command that opened it, scrolled up
14
+ * ────────────────────────────── ← the seam between transcript and body
15
+ * Select model ← title
16
+ * Switch between Claude models… ← blurb
17
+ * ❯ 1. Default (recommended) ✔ ← options, the glyph marking the cursor
18
+ * 2. Opus (1M context)
19
+ * Enter to set as default · s to use this session only · Esc to cancel
20
+ *
21
+ * the same list without the numbers, which is how the trust dialog draws its
22
+ * `No, exit` / `Yes, I trust this folder`, and dialogs with no list at all
23
+ * (`/tasks`, `/config`) where the footer's key hints are the only affordances
24
+ * there are. WebFetch's permission prompt is the odd one out the other way: a
25
+ * numbered list and no footer at all, so there the list has to mark where the
26
+ * dialog ends ({@link findListEnd}).
27
+ *
28
+ * The footer is parsed rather than assumed, because the keys do not mean the
29
+ * same thing twice. `/model` closes on Esc; `/tasks` closes on Esc; `/config`
30
+ * reads `Esc to clear`, where Esc empties the filter box and leaves the dialog
31
+ * open — pressing it there on the belief that Esc always cancels is how a
32
+ * probe session silently turned off auto-compact. Offer what the dialog says
33
+ * it offers, and nothing else.
34
+ */
35
+ /** The seam rule between the transcript and a dialog's body. */
36
+ const RULE = /^\s*─{10,}\s*$/u;
37
+ /**
38
+ * The dashed rules an edit prompt draws above and below its diff. What sits
39
+ * between a pair is file content, and is shown exactly as drawn.
40
+ */
41
+ const FENCE = /^\s*╌{10,}\s*$/u;
42
+ /** A row in claude's quote gutter — how a Bash prompt draws its command. */
43
+ const GUTTER = /^\s*│ ?(.*)$/u;
44
+ /**
45
+ * How far short of the terminal's edge claude's prose wraps. Dialogs are
46
+ * padded, so a row breaks a column or two early: `/model`'s blurb broke at a
47
+ * row its next word would only have taken to column 119 of 120.
48
+ */
49
+ const WRAP_SLACK = 4;
50
+ /**
51
+ * The cursor's row: indent, the glyph, a gap, then the label. The capture
52
+ * groups give the column its label starts at, which is what finds the rows
53
+ * beside it.
54
+ */
55
+ const CURSOR_ROW = /^(\s*)❯(\s+)(\S.*)$/u;
56
+ /** A leading `1. `, when the dialog numbers its rows. Many do not. */
57
+ const ROW_NUMBER = /^(\d{1,2})\.\s+(\S.*)$/u;
58
+ /**
59
+ * What a list too long for the screen draws past the rows it shows: `↑ 2 more`
60
+ * above them, `↓ 92 more` below. It sits in the rows' own column, so without
61
+ * this the walk out from the cursor took it for one more row.
62
+ */
63
+ const MORE_ROWS = /^\s*([↑↓])\s+(\d+)\s+more\s*$/u;
64
+ /**
65
+ * The group headings `/mcp` draws between its servers, in the rows' own
66
+ * column: `Built-in MCPs (always available)`, `User MCPs (~/.claude.json)`,
67
+ * `claude.ai` — the labels Claude Code 2.1.310's list gives its groups. Its
68
+ * cursor skips them. Read as rows, the server list's heading became a button
69
+ * that could only fail, and a second group's heading would put every row
70
+ * below it one arrow further off than it is.
71
+ */
72
+ const LIST_HEADING = /^\s*(?:[\w.-]+(?: [\w.-]+)* MCPs(?: \(.*\))?|claude\.ai)\s*$/u;
73
+ /**
74
+ * A footer hint. Claude writes these as `Enter to confirm`, `Esc to cancel`,
75
+ * `↑/↓ to select`, `s to use this session only` — a key, the word "to", and a
76
+ * verb phrase. Keys are matched narrowly so a sentence in the body that
77
+ * happens to contain " to " cannot pose as one.
78
+ */
79
+ const KEY_HINT = /^(Enter(?:\/[^\s]+)?|Esc|Tab|Space|[a-z]|↑\/↓|←\/→|\/)\s+to\s+(.+)$/u;
80
+ /** How far up from the footer a dialog's body can reach. */
81
+ const MAX_BODY_ROWS = 30;
82
+ /**
83
+ * How many lines of chrome may sit *below* the footer.
84
+ *
85
+ * The footer is not reliably the last thing on screen. Claude draws its status
86
+ * bar under a dialog — `⏵⏵ bypass permissions on (shift+tab to cycle)` — and
87
+ * adds notices there too, and every one of those pushed the hints off the last
88
+ * line and made this parser answer null. The caller reads null as "a screen we
89
+ * cannot drive", so a trust dialog with a status bar under it timed out after
90
+ * 180 seconds instead of being offered as two buttons.
91
+ *
92
+ * Bounded rather than open-ended: the footer has to still be near the bottom,
93
+ * or a hint line from the transcript scrolled above could pose as one.
94
+ */
95
+ const MAX_FOOTER_CHROME = 3;
96
+ /**
97
+ * Longest option label we keep. Telegram caps a button at 64 bytes and the
98
+ * ask-user contract at 60 chars; claude pads its rows out to the full 120
99
+ * columns with a trailing description, so most need clipping.
100
+ */
101
+ const MAX_LABEL = 48;
102
+ /**
103
+ * The screen's non-blank rows, the bottom {@link MAX_BODY_ROWS} of them, and
104
+ * for each whether a blank row sat above it. The parse reads only the rows;
105
+ * the gaps are for showing the result, since they are how claude splits a
106
+ * dialog into its title, command, reason and question.
107
+ */
108
+ function bodyLines(screenText) {
109
+ const lines = [];
110
+ const gaps = [];
111
+ let gap = false;
112
+ for (const raw of screenText.split('\n')) {
113
+ const line = raw.trimEnd();
114
+ if (!line.trim()) {
115
+ gap = true;
116
+ continue;
117
+ }
118
+ lines.push(line);
119
+ gaps.push(gap);
120
+ gap = false;
121
+ }
122
+ return { lines: lines.slice(-MAX_BODY_ROWS), gaps: gaps.slice(-MAX_BODY_ROWS) };
123
+ }
124
+ function collapse(text) {
125
+ return text.replace(/\s+/g, ' ').trim();
126
+ }
127
+ function clip(text, max) {
128
+ const collapsed = collapse(text);
129
+ // trimEnd after slicing: a cut that lands on a space would otherwise render
130
+ // the gap before the ellipsis, which reads as a missing word.
131
+ return collapsed.length > max ? `${collapsed.slice(0, max - 1).trimEnd()}…` : collapsed;
132
+ }
133
+ /**
134
+ * Find the footer: the lowest line that reads as key hints, allowing for the
135
+ * status chrome claude draws beneath a dialog. Returns null when the bottom of
136
+ * the screen holds no hints at all.
137
+ */
138
+ function findFooter(lines) {
139
+ const floor = Math.max(0, lines.length - 1 - MAX_FOOTER_CHROME);
140
+ for (let i = lines.length - 1; i >= floor; i--) {
141
+ const hints = parseKeyHints(lines[i]);
142
+ if (hints.length > 0)
143
+ return { index: i, hints };
144
+ }
145
+ return null;
146
+ }
147
+ /**
148
+ * Where a dialog with no footer ends, standing in for {@link findFooter}.
149
+ *
150
+ * WebFetch's permission prompt has none. It ends on its last row, and the one
151
+ * key it names is written into that row — `3. No, and tell Claude what to do
152
+ * differently (esc)` — so a parser that insisted on a footer never saw it,
153
+ * and a turn that asked to fetch a page sat on the dialog, unrelayed, until
154
+ * the hard ceiling. What marks the end instead is the list itself: numbered
155
+ * rows with the cursor on one, under the seam, reaching the bottom of the
156
+ * screen. The glyph's other haunts don't fit that shape — echoed prompts sit
157
+ * above the seam, and the input box has a rule of its own beneath it.
158
+ *
159
+ * Numbered rows only, because that is how claude draws a list meant for
160
+ * picking from, and it keeps this to the shape that was measured. The index is
161
+ * just past the list, where a footer would be; there are no hints to go with it.
162
+ */
163
+ function findListEnd(lines, width) {
164
+ const seam = lastRuleBefore(lines, lines.length);
165
+ if (seam < 0)
166
+ return null;
167
+ const { options, list } = extractOptions(lines.slice(seam + 1), width);
168
+ if (!list || options.length < 2 || options.some((o) => o.number === undefined))
169
+ return null;
170
+ const index = seam + 1 + list.end + 1;
171
+ return lines.length - index <= MAX_FOOTER_CHROME ? { index, hints: [] } : null;
172
+ }
173
+ /**
174
+ * Split the footer into its hints. Returns [] for a line that is prose rather
175
+ * than chrome, which is what keeps a dialog we cannot drive from being offered
176
+ * buttons that do nothing.
177
+ */
178
+ export function parseKeyHints(footer) {
179
+ const hints = [];
180
+ for (const part of footer.split('·')) {
181
+ const match = KEY_HINT.exec(part.trim());
182
+ if (match)
183
+ hints.push({ key: match[1], action: clip(match[2], 40) });
184
+ }
185
+ return hints;
186
+ }
187
+ /**
188
+ * Read the dialog covering the input box, or null when the screen holds none.
189
+ *
190
+ * The caller is expected to have established that the input box is absent
191
+ * ({@link hasInputBox}); this only answers what is there instead. A null here
192
+ * with no input box means a screen we cannot drive — mid-render, or a dialog
193
+ * shaped in a way this parser does not know — and the caller should relay it
194
+ * verbatim rather than press anything.
195
+ */
196
+ export function parseModal(screenText) {
197
+ const { lines, gaps } = bodyLines(screenText);
198
+ if (lines.length === 0)
199
+ return null;
200
+ // The terminal's width, near enough: the seam is drawn edge to edge.
201
+ const width = Math.max(...lines.map((l) => l.length));
202
+ const footer = findFooter(lines) ?? findListEnd(lines, width);
203
+ if (!footer)
204
+ return null;
205
+ const { hints, index: footerIndex } = footer;
206
+ // Body starts below the seam rule when there is one; a dialog that redrew
207
+ // the whole screen has no seam, and everything we kept is its body.
208
+ let seam = lastRuleBefore(lines, footerIndex);
209
+ let body = lines.slice(seam + 1, footerIndex);
210
+ // A rule can also sit *inside* a dialog. Auto mode draws one between its
211
+ // numbered choices and a trailing "Chat about this", which left a body of a
212
+ // single line with no cursor in it — five options parsed as none, and the
213
+ // only button on offer was a bare `Enter to select` committing the row
214
+ // nobody had been shown. Reach back past a rule like that.
215
+ //
216
+ // Only when what's left below it is numbered, though. The transcript above
217
+ // a dialog carries the echoed command wearing this same glyph (`❯ /tasks`),
218
+ // and reaching past the real seam would swallow it as an option. Claude
219
+ // numbers a list exactly when its rows are selectable, so that is the line
220
+ // between a continued list and a dialog that simply has no rows.
221
+ if (seam > 0 && body.length > 0
222
+ && !body.some((line) => CURSOR_ROW.test(line))
223
+ && body.every((line) => ROW_NUMBER.test(line.trimStart()))) {
224
+ const outer = lastRuleBefore(lines, seam);
225
+ const extended = lines.slice(outer + 1, footerIndex);
226
+ if (extended.some((line) => CURSOR_ROW.test(line))) {
227
+ seam = outer;
228
+ body = extended;
229
+ }
230
+ }
231
+ if (body.length === 0)
232
+ return null;
233
+ const { options, highlighted, more, rows, list } = extractOptions(body, width);
234
+ // A cursor we could not resolve into rows is the one state that must not
235
+ // produce buttons. The footer's `Enter to confirm` would then be the only
236
+ // thing on offer, and Enter commits whatever the cursor is on — which is
237
+ // exactly how the trust dialog, whose default row is `No, exit`, got
238
+ // answered with an exit. Better to relay the screen and press nothing.
239
+ if (options.length === 0 && body.some((l) => l.includes('❯')))
240
+ return null;
241
+ // The title is the first body row that isn't an option — dialogs lead with
242
+ // their heading, and one that opens straight onto its list has none.
243
+ const title = body.find((_, i) => !rows.has(i));
244
+ return {
245
+ title: title ? clip(title, 120) : clip(body[0], 120),
246
+ options,
247
+ highlighted,
248
+ more,
249
+ hints,
250
+ body: body.join('\n'),
251
+ parts: readParts(body, gaps.slice(seam + 1, footerIndex), list, width),
252
+ };
253
+ }
254
+ /** Index of the last rule strictly above `before`, or -1 when there is none. */
255
+ function lastRuleBefore(lines, before) {
256
+ for (let i = before - 1; i >= 0; i--) {
257
+ if (RULE.test(lines[i]))
258
+ return i;
259
+ }
260
+ return -1;
261
+ }
262
+ /**
263
+ * What `line` is, to a list whose rows begin at `col`.
264
+ *
265
+ * The three answers are the shape of every list claude draws. A row starts
266
+ * exactly at the column its siblings do. Anything starting *deeper* hangs off
267
+ * the row above — auto mode gives each choice a sentence of explanation
268
+ * underneath, and a walk that stopped at the first of those found one option
269
+ * where there were five. A rule can sit inside a list too, so it is stepped
270
+ * over rather than treated as the end. Anything starting *shallower* is the
271
+ * title, the blurb or prose, and that really is the end of the list. Two
272
+ * things are drawn in the rows' column without being rows, and are told
273
+ * apart by what they say: the `↓ 92 more` of a list that scrolls, and the
274
+ * headings of one in groups.
275
+ */
276
+ function rowRole(line, col) {
277
+ if (RULE.test(line))
278
+ return 'skip';
279
+ const at = line.search(/\S/);
280
+ if (at < 0)
281
+ return 'skip';
282
+ if (MORE_ROWS.test(line))
283
+ return 'more';
284
+ if (at === col)
285
+ return LIST_HEADING.test(line) ? 'skip' : 'row';
286
+ return at > col ? 'skip' : 'end';
287
+ }
288
+ /**
289
+ * The dialog's selectable rows, found from the cursor outwards.
290
+ *
291
+ * Claude does not number them consistently — `/model` draws `❯ 1. Default`,
292
+ * the trust dialog draws a bare `❯ No, exit` — so a pattern keyed on the
293
+ * number misses the dialogs that matter most. What every list does share is
294
+ * layout: the rows are the run of lines whose text starts in the same column
295
+ * as the cursor's own label, and nothing else on the screen lines up there.
296
+ * Walking out from the cursor until that alignment breaks picks up the rows
297
+ * and stops at the blurb above and the footer below.
298
+ */
299
+ function extractOptions(body, width) {
300
+ const more = { above: 0, below: 0 };
301
+ const none = { options: [], highlighted: -1, more, rows: new Set(), list: null };
302
+ const cursor = body.findIndex((l) => CURSOR_ROW.test(l));
303
+ if (cursor < 0)
304
+ return none;
305
+ const match = CURSOR_ROW.exec(body[cursor]);
306
+ const labelCol = match[1].length + 1 + match[2].length;
307
+ const indexes = [];
308
+ // The list's first line, which is its `↑ 2 more` when it has one.
309
+ let start = cursor;
310
+ for (let i = cursor - 1; i >= 0; i--) {
311
+ const role = rowRole(body[i], labelCol);
312
+ if (role === 'end')
313
+ break;
314
+ if (role === 'row')
315
+ indexes.unshift(i);
316
+ if (role === 'more')
317
+ more.above = Number(MORE_ROWS.exec(body[i])[2]);
318
+ if (role !== 'skip')
319
+ start = i;
320
+ }
321
+ // However many rows sit above it is where the cursor is — the arrow walk
322
+ // counts rows, not screen lines, and the two differ wherever a description
323
+ // or a rule sits between them.
324
+ const highlighted = indexes.length;
325
+ indexes.push(cursor);
326
+ // Where this walk stops is where the list ends: what hangs under its last
327
+ // row still belongs to that row.
328
+ let stop = cursor + 1;
329
+ for (; stop < body.length; stop++) {
330
+ const role = rowRole(body[stop], labelCol);
331
+ if (role === 'end')
332
+ break;
333
+ if (role === 'row')
334
+ indexes.push(stop);
335
+ if (role === 'more')
336
+ more.below = Number(MORE_ROWS.exec(body[stop])[2]);
337
+ }
338
+ const options = [];
339
+ const rows = new Set();
340
+ indexes.forEach((i, k) => {
341
+ rows.add(i);
342
+ const text = i === cursor ? match[3] : body[i].slice(labelCol);
343
+ const numbered = ROW_NUMBER.exec(text);
344
+ const own = numbered ? numbered[2] : text;
345
+ const under = body.slice(i + 1, indexes[k + 1] ?? stop)
346
+ .filter((l) => !RULE.test(l) && !MORE_ROWS.test(l) && !LIST_HEADING.test(l));
347
+ options.push({
348
+ ...(numbered ? { number: Number(numbered[1]) } : {}),
349
+ label: clip(own, MAX_LABEL),
350
+ ...readRow(body[i], own, under, width),
351
+ index: options.length,
352
+ });
353
+ });
354
+ return { options, highlighted, more, rows, list: { start, end: stop - 1 } };
355
+ }
356
+ /**
357
+ * A row's full text, and what the dialog says about it.
358
+ *
359
+ * `under` is whatever hangs beneath the row before the next one: the rest of
360
+ * a label claude wrapped at the edge, then any description — auto writes a
361
+ * sentence under each choice. `/model` puts its description beside the row
362
+ * instead, a wide gap away, which is what splitting on a run of spaces finds.
363
+ */
364
+ function readRow(row, own, under, width) {
365
+ let text = own;
366
+ let last = row;
367
+ let n = 0;
368
+ while (n < under.length && wrapsOnto(last, under[n], width)) {
369
+ text += ` ${under[n].trim()}`;
370
+ last = under[n++];
371
+ }
372
+ const [label, ...beside] = text.trim().split(/\s{2,}/);
373
+ const detail = collapse([...beside, ...under.slice(n)].join(' '));
374
+ return { text: collapse(label), ...(detail ? { detail } : {}) };
375
+ }
376
+ /**
377
+ * Read the body into what a chat can show, in the order claude drew it.
378
+ *
379
+ * Blank rows split it into parts, as they split the dialog on screen, and so
380
+ * does any change between prose and drawn content — a Bash prompt's command
381
+ * sits straight under its title, with nothing but its gutter to set it off.
382
+ */
383
+ function readParts(body, gaps, list, width) {
384
+ const parts = [];
385
+ let open = null;
386
+ let fenced = false;
387
+ for (let i = 0; i < body.length; i++) {
388
+ const line = body[i];
389
+ if (list && i >= list.start && i <= list.end) {
390
+ if (i === list.start)
391
+ parts.push({ kind: 'options', gapBefore: gaps[i] });
392
+ open = null;
393
+ continue;
394
+ }
395
+ if (FENCE.test(line)) {
396
+ fenced = !fenced;
397
+ open = null;
398
+ continue;
399
+ }
400
+ if (RULE.test(line)) {
401
+ open = null;
402
+ continue;
403
+ }
404
+ const gutter = fenced ? null : GUTTER.exec(line);
405
+ const kind = fenced || gutter ? 'verbatim' : 'text';
406
+ if (open?.kind === 'verbatim' && kind === 'verbatim' && gaps[i]) {
407
+ // A blank row inside drawn content is part of the content.
408
+ open.lines.push('');
409
+ }
410
+ else if (!open || open.kind !== kind || gaps[i]) {
411
+ open = { kind, lines: [], gapBefore: gaps[i] };
412
+ parts.push(open);
413
+ }
414
+ open.lines.push(gutter ? gutter[1] : line);
415
+ }
416
+ // The dialog's own prose sits at one indent; what it quotes — a one-line
417
+ // command, a URL — is indented under it. Only the prose gets rejoined: a
418
+ // command whose last row ends near the edge would otherwise swallow the
419
+ // description under it, and show the user a command they aren't approving.
420
+ const base = Math.min(...parts.flatMap((p) => (p.kind === 'text' ? p.lines.map(indentOf) : [])));
421
+ return parts.map((part) => {
422
+ if (part.kind === 'text')
423
+ return { ...part, lines: unwrap(part.lines, width, base) };
424
+ if (part.kind === 'verbatim')
425
+ return { ...part, lines: dedent(part.lines) };
426
+ return part;
427
+ });
428
+ }
429
+ /**
430
+ * Undo claude's wraps at the terminal edge. It breaks prose where the width
431
+ * runs out, and a phone then wraps both halves again, stranding the odd word
432
+ * on a line of its own. A row carries on into the next exactly when the next
433
+ * one's first word would not have fitted on it.
434
+ */
435
+ function unwrap(lines, width, indent) {
436
+ const out = [];
437
+ lines.forEach((line, i) => {
438
+ const prose = i > 0 && indentOf(lines[i - 1]) === indent && indentOf(line) === indent;
439
+ if (prose && wrapsOnto(lines[i - 1], line, width))
440
+ out[out.length - 1] += ` ${line.trim()}`;
441
+ else
442
+ out.push(line.trim());
443
+ });
444
+ return out;
445
+ }
446
+ function indentOf(line) {
447
+ return line.search(/\S/);
448
+ }
449
+ /** True when claude broke `row` at the edge and `next` is the rest of it. */
450
+ function wrapsOnto(row, next, width) {
451
+ const word = next.trim().split(/\s/, 1)[0];
452
+ return row.length + 1 + word.length > width - WRAP_SLACK;
453
+ }
454
+ /** Strip the indentation every line shares — the dialog's, not the content's. */
455
+ function dedent(lines) {
456
+ const depth = Math.min(...lines.filter((l) => l.trim()).map(indentOf));
457
+ return Number.isFinite(depth) ? lines.map((l) => l.slice(depth)) : lines;
458
+ }
459
+ /**
460
+ * The keystrokes that answer `modal` with the option at `index`.
461
+ *
462
+ * Arrow keys rather than the row's digit: not every dialog numbers its rows,
463
+ * and the ones that do don't all take the number as a hotkey, whereas ↑/↓ move
464
+ * the cursor in all of them. Moving is also checkable — the caller re-reads the
465
+ * screen and confirms the glyph landed on the intended row before committing —
466
+ * where a digit is a blind press.
467
+ *
468
+ * Returns null when the cursor's position is unknown, since every step from an
469
+ * unknown start is a guess.
470
+ */
471
+ export function arrowsTo(modal, index) {
472
+ if (modal.highlighted < 0)
473
+ return null;
474
+ if (index < 0 || index >= modal.options.length)
475
+ return null;
476
+ const distance = index - modal.highlighted;
477
+ return Array.from({ length: Math.abs(distance) }, () => (distance > 0 ? '\x1b[B' : '\x1b[A'));
478
+ }
479
+ /**
480
+ * The byte a footer hint's key sends. Null for keys that don't answer the
481
+ * dialog, which are no use as a button.
482
+ *
483
+ * Tab is one of those, though claude's footers name it. A permission prompt's
484
+ * `Tab to amend` turns the highlighted row into a text field — `Yes, and tell
485
+ * Claude what to do next` — and waits for a note there, which a button cannot
486
+ * type. Pressing it only ever changed the dialog without closing it, and the
487
+ * turn then failed on a dialog that was still open.
488
+ */
489
+ export function keystrokeFor(key) {
490
+ if (/^Enter/.test(key))
491
+ return '\r';
492
+ if (key === 'Esc')
493
+ return '\x1b';
494
+ if (key === 'Space')
495
+ return ' ';
496
+ if (/^[a-z]$/.test(key))
497
+ return key;
498
+ // ↑/↓, ←/→ and / are navigation or search affordances, not answers.
499
+ return null;
500
+ }
501
+ //# sourceMappingURL=tui-modal.js.map