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,456 @@
1
+ /**
2
+ * Reading Claude Code's state off the rendered TUI.
3
+ *
4
+ * Two guards in the pty provider need to know whether claude is mid-turn: the
5
+ * readiness wait that decides when a prompt can be submitted, and the idle
6
+ * fallback that decides a turn has ended. Both inferred it from the pty going
7
+ * quiet, and quiet doesn't carry that meaning in either direction. Measured
8
+ * against a live 120x40 pty: a running turn redraws several times a second —
9
+ * the longest silence inside a 27-second turn was 0.3s — so a readiness rule
10
+ * that waits for three seconds of quiet can only ever time out on a session
11
+ * that is working, however long it works. Once the turn ends that same screen
12
+ * sits silent for tens of seconds, which is the only reason silence looks
13
+ * like a signal at all. The input glyph separates nothing: claude draws `❯`
14
+ * throughout a turn, because you can type at it while the model works.
15
+ *
16
+ * What does track generation is the footer hint. The TUI offers `esc to
17
+ * interrupt` exactly while there is a generation to interrupt and drops it
18
+ * the moment the turn ends; the live spinner (`✶ Percolating… (29s)`) carries
19
+ * the same meaning while it's on screen. Both are read from the bottom of the
20
+ * buffer, where the TUI's own chrome lives — a scan of the whole screen would
21
+ * take an assistant message that merely quotes the phrase as proof that
22
+ * claude is still working.
23
+ *
24
+ * Above the input box is the transcript, where claude draws each reply from
25
+ * its Markdown rather than printing the Markdown itself. Measured on claude
26
+ * 2.1.280 at 120x40: a reply's first row starts with `● `, its later rows are
27
+ * indented by two, its lines wrap at the terminal's width, and a blank row
28
+ * comes between its blocks. Bold and italic markers go, and the cells carry
29
+ * those attributes instead. Headings lose their `#`s and show bold, `#` also
30
+ * italic and underlined. Inline code, and a code block without a language,
31
+ * get a colour of their own, a code block with one gets syntax colours, and
32
+ * neither shows its fences. A quote is a dim `▎` before italic text, and a
33
+ * link is `text (url)`. Lists, `---`, `~~strike~~` and HTML tags stay as
34
+ * written. A table is drawn in box drawing, with a rule between every two
35
+ * rows:
36
+ *
37
+ * ┌───────┬───────┐
38
+ * │ cell1 │ cell2 │
39
+ * ├───────┼───────┤
40
+ * │ cell3 │ cell4 │
41
+ * └───────┴───────┘
42
+ *
43
+ * A cell too long for its column goes on in the same cell on the next row,
44
+ * and when a table opens the reply, its top border is the `● ` row.
45
+ */
46
+ /** Rows from the bottom that hold the TUI's chrome rather than transcript. */
47
+ const FOOTER_ROWS = 5;
48
+ /** Rows to search for the spinner, which sits above the input box. */
49
+ const SPINNER_ROWS = 12;
50
+ /** The footer's interrupt hint, offered only while a generation is running. */
51
+ const INTERRUPT_HINT = /esc to interrupt/i;
52
+ /**
53
+ * The live spinner: a glyph, a gerund, and a running timer. Measured on
54
+ * claude 2.1.280, the glyph cycles through `✢ * ✶ ✻ ✽ ·` several times a
55
+ * second, and the timer opens the parentheses (`✶ Percolating… (29s · ↓ 1.2k
56
+ * tokens)`), counts minutes past the first one (`(1m 3s · …)`), and follows
57
+ * what claude waits on while a hook runs (`· Inferring… (running Stop hook ·
58
+ * 0s · ↓ 2 tokens)`). The completed turn's summary (`✻ Brewed for 3m 5s`) is
59
+ * deliberately not matched — it has no ellipsis and stays on screen long
60
+ * after the turn ends.
61
+ */
62
+ const LIVE_SPINNER = /^\s*[✶✳✻✽✢·*]\s+\S+…\s*\((?:[^()]*·\s*)?(?:\d+h\s*)?(?:\d+m\s*)?\d+s\b/u;
63
+ /** Claude's own output bullet, so a quoted hint isn't read as chrome. */
64
+ const ASSISTANT_BULLET = /^\s*●/u;
65
+ export function tailLines(screenText, rows) {
66
+ return screenText.split('\n').filter((line) => line.trim()).slice(-rows);
67
+ }
68
+ /**
69
+ * Is claude generating right now?
70
+ *
71
+ * True while a turn is in flight, false once it ends — including while a tool
72
+ * the model backgrounded keeps running, which the TUI accepts input during.
73
+ */
74
+ export function isGenerating(screenText) {
75
+ const footer = tailLines(screenText, FOOTER_ROWS)
76
+ .filter((line) => !ASSISTANT_BULLET.test(line));
77
+ if (footer.some((line) => INTERRUPT_HINT.test(line)))
78
+ return true;
79
+ return tailLines(screenText, SPINNER_ROWS).some((line) => LIVE_SPINNER.test(line));
80
+ }
81
+ /**
82
+ * A running subagent's row in the panel under the input box:
83
+ *
84
+ * ◯ fork Applying refinements to messages.test.ts 21m 57s · ↓ 486.9k tokens
85
+ *
86
+ * Its timer, token count and description all change while the main session
87
+ * sits idle at its prompt. It starts as a bare `0s`, with no token count yet.
88
+ */
89
+ const SUBAGENT_ROW = /^\s*◯\s.*\d+[smh](?:\s+·\s+[↑↓]\s*[\d.,]+[kKmM]?\s*tokens)?\s*$/u;
90
+ /**
91
+ * The screen reduced to what changing actually means something.
92
+ *
93
+ * A TUI still coming up rewrites whole rows; one sitting at the prompt rewrites
94
+ * nothing. Between those two are the rows that redraw on a clock: the spinner,
95
+ * and a running subagent's row. Comparing raw screens would read either as a
96
+ * session that never settles, which is the mistake byte-silence already makes.
97
+ * With a subagent running that refused every message for as long as it ran,
98
+ * though the input box was open and accepting them. Dropping those rows is
99
+ * enough.
100
+ */
101
+ export function screenSignature(screenText) {
102
+ return screenText
103
+ .split('\n')
104
+ .filter((line) => !LIVE_SPINNER.test(line) && !SUBAGENT_ROW.test(line))
105
+ .map((line) => line.trimEnd())
106
+ .join('\n');
107
+ }
108
+ /**
109
+ * A full-width horizontal rule: the input box's top and bottom border.
110
+ * Ten is well below the 120-column render but far above anything that shows
111
+ * up inside prose, so a model quoting `──` in a reply can't forge a border.
112
+ */
113
+ const RULE = /^\s*─{10,}\s*$/u;
114
+ /**
115
+ * The input box's own row. The glyph may sit inside side borders on terminals
116
+ * that draw them (`│ ❯ typed text │`), which is a shape only the input box
117
+ * has — no overlay draws vertical borders — so it stands on its own below.
118
+ */
119
+ const INPUT_ROW = /^\s*(?:│\s*)?❯/u;
120
+ const SIDE_BORDERED_INPUT = /│\s*❯/u;
121
+ /**
122
+ * The box's row in shell mode. A `!` typed or pasted first flips the editor:
123
+ * the `❯` gives way to the `!`, drawn apart from the command (`! echo hi` for a
124
+ * pasted `!echo hi`), and Enter runs the command itself. Only {@link
125
+ * inputBoxText} reads it. {@link hasInputBox} deliberately does not: a prompt
126
+ * pasted into a box in this state would run as a command.
127
+ *
128
+ * Anchored at the first column, where the box draws it. The footer under the
129
+ * box reads ` ! for shell mode` in this state, indented, and it sits right
130
+ * under a rule as well.
131
+ */
132
+ const SHELL_INPUT_ROW = /^!(?:\s|$)/u;
133
+ /** Rows from the bottom that can hold the input box and its footer. */
134
+ const INPUT_BOX_ROWS = 10;
135
+ /**
136
+ * Is claude's input box open, as opposed to an overlay covering it?
137
+ *
138
+ * The distinction a bare search for `❯` cannot draw, which is what this
139
+ * replaced. Claude's select lists mark the highlighted option with the same
140
+ * glyph the input box uses:
141
+ *
142
+ * Select model
143
+ * ❯ 1. Default (recommended) ✔ Opus 5 with 1M context
144
+ * 2. Opus (1M context) …
145
+ * Enter to set as default · s to use this session only · Esc to cancel
146
+ *
147
+ * so a bare `includes('❯')` reads a modal as a prompt. That screen is also
148
+ * perfectly still and draws no interrupt hint, which means every other
149
+ * readiness signal agrees — and the prompt then gets pasted into a list that
150
+ * ignores it, with the Enter after it landing on whichever option happens to
151
+ * be highlighted. Measured against a live pty, that is enough to change a
152
+ * setting: pasting into `/model` and pressing Enter answered the dialog.
153
+ *
154
+ * What separates them is structure, not the glyph. The input box is a `❯` row
155
+ * fenced by two rules; an overlay draws at most one rule, as the seam between
156
+ * the transcript above it and its own body. Both are read from the bottom of
157
+ * the buffer, where the box lives — an option list long enough to scroll would
158
+ * otherwise offer its own `❯` row somewhere in the middle of the screen.
159
+ */
160
+ export function hasInputBox(screenText) {
161
+ const lines = tailLines(screenText, INPUT_BOX_ROWS);
162
+ return lines.some((line, i) => SIDE_BORDERED_INPUT.test(line)
163
+ || (INPUT_ROW.test(line) && RULE.test(lines[i - 1] ?? '') && RULE.test(lines[i + 1] ?? '')));
164
+ }
165
+ /**
166
+ * A tool call's row in the transcript: `● Bash(npm test)`, cut off if it
167
+ * wraps, or the one row claude collapses calls into, `● Read 1 file (ctrl+o
168
+ * to expand)`, which reads `● Reading 1 file… (ctrl+o to expand)` while they
169
+ * run.
170
+ */
171
+ const TOOL_CALL_ROW = /^\s*●\s+(?:[A-Za-z][\w:-]*\((?:[^)]*|.*\))|.*\(ctrl\+o to expand\))\s*$/u;
172
+ /**
173
+ * The rows that still tell a call apart from text while its `●` is off. The
174
+ * bullet blinks while the call runs, and without it the call's rows read as
175
+ * more rows of the text above them. What claude draws under a call opens with
176
+ * `⎿` (` ⎿ Running…`), and a collapsed call's row ends in its hint.
177
+ */
178
+ const TOOL_RESULT_ROW = /^\s*⎿/u;
179
+ const COLLAPSED_CALL_ROW = /\(ctrl\+o to expand\)\s*$/u;
180
+ /** A background agent reporting in: `● Agent "Run the checks" finished · 4s`. */
181
+ const AGENT_NOTICE_ROW = /^\s*●\s+Agent\s+".*"\s+\w+\s+·/u;
182
+ /** A prompt already submitted, as the transcript shows it. */
183
+ const SUBMITTED_PROMPT_ROW = /^\s*❯\s+\S/u;
184
+ /**
185
+ * Does this row end the assistant's text: a timer, a tool call's row, an input
186
+ * box part or a rule?
187
+ *
188
+ * The timer is the completed turn's `✻` summary, or the live spinner in any of
189
+ * its frames, while the turn still runs. A call's rows end it when the call's
190
+ * `●` is off.
191
+ *
192
+ * A row opening with `│ ` is not one. An input box with side borders opens
193
+ * with a `╭` row, which ends the text before its first `│` row, and the rows
194
+ * of a table that claude draws in box drawing open with `│ ` too.
195
+ */
196
+ function endsReply(line) {
197
+ const trimmed = line.trim();
198
+ return trimmed.startsWith('✻')
199
+ || LIVE_SPINNER.test(trimmed)
200
+ || TOOL_RESULT_ROW.test(trimmed)
201
+ || COLLAPSED_CALL_ROW.test(trimmed)
202
+ || /^[╭╰╮╯]/u.test(trimmed)
203
+ || trimmed.includes('❯')
204
+ || /^[─━═]{3,}$/u.test(trimmed);
205
+ }
206
+ /** The screen's rows above the input box. Below it is only chrome. */
207
+ function rowsAboveInputBox(lines) {
208
+ for (let i = lines.length - 1; i >= 0; i--) {
209
+ if (SIDE_BORDERED_INPUT.test(lines[i]))
210
+ return lines.slice(0, i);
211
+ if (i > 0 && INPUT_ROW.test(lines[i]) && RULE.test(lines[i - 1]))
212
+ return lines.slice(0, i - 1);
213
+ }
214
+ return lines;
215
+ }
216
+ /**
217
+ * The turn's reply as the screen shows it, for when the session log has no
218
+ * record of the prompt.
219
+ *
220
+ * That's the last `●` above the input box, and only if it's text. Below the box
221
+ * the subagent panel draws its own `● main`, which once went out as the reply.
222
+ * A tool call, an agent's notice or a later prompt in that position means the
223
+ * turn has written no text, and anything further up belongs to an earlier turn.
224
+ */
225
+ export function replyFromScreen(screenText) {
226
+ const rows = rowsAboveInputBox(screenText.split('\n'));
227
+ const bullet = rows.reduce((last, line, i) => (ASSISTANT_BULLET.test(line) ? i : last), -1);
228
+ if (bullet === -1) {
229
+ const promptIndex = rows.findIndex((line) => line.includes('❯'));
230
+ return (promptIndex === -1 ? rows : rows.slice(0, promptIndex)).join('\n').trim();
231
+ }
232
+ const below = rows.slice(bullet + 1);
233
+ if (TOOL_CALL_ROW.test(rows[bullet]) || AGENT_NOTICE_ROW.test(rows[bullet])
234
+ || below.some((line) => SUBMITTED_PROMPT_ROW.test(line))) {
235
+ return '';
236
+ }
237
+ const end = below.findIndex(endsReply);
238
+ let text = end === -1 ? below : below.slice(0, end);
239
+ // A `⎿` row hangs under its call's own rows, which have no `●` while it is
240
+ // off: they go too, back to the blank row before them.
241
+ if (end !== -1 && TOOL_RESULT_ROW.test(below[end])) {
242
+ let blank = text.length - 1;
243
+ while (blank >= 0 && text[blank].trim())
244
+ blank--;
245
+ if (blank >= 0)
246
+ text = text.slice(0, blank);
247
+ }
248
+ return [rows[bullet], ...text]
249
+ .join('\n')
250
+ .replace(/^\s*●\s*/u, '')
251
+ .trim();
252
+ }
253
+ /**
254
+ * Claude Code's collapsed-paste placeholder.
255
+ *
256
+ * Its editor does not draw a pasted block that runs past 800 characters or two
257
+ * newlines. It mints an id for the block, keeps the text off-screen, and
258
+ * renders `[Pasted text #3 +10 lines]` in its place — `[Pasted text #3]` when
259
+ * the block has no newlines at all. The full text is restored on submit, so
260
+ * this costs delivery nothing, but it means anything checking the screen for a
261
+ * prompt's own words has to recognise the placeholder instead: every prompt we
262
+ * build from a template (an upload note, a staged image list) clears both
263
+ * thresholds and is therefore never on screen literally.
264
+ */
265
+ const PASTE_PLACEHOLDER = /\[Pasted text #(\d+)(?: \+(\d+) lines)?\]/g;
266
+ /**
267
+ * Every collapsed paste anywhere on the rendered screen, scrollback included.
268
+ *
269
+ * Submitting expands a placeholder back to the text it stood for, so a live
270
+ * one marks a paste still held in the editor. Stale ones linger all the same:
271
+ * the box redraws in place, and the frames it scrolls off the top keep
272
+ * whatever they were showing at the time. Ids are minted in increasing order
273
+ * within a session, which is what lets a caller tell a paste its own write
274
+ * just made from one an earlier turn left behind.
275
+ */
276
+ export function pastePlaceholders(screenText) {
277
+ return [...screenText.matchAll(PASTE_PLACEHOLDER)].map((match) => ({
278
+ id: Number(match[1]),
279
+ lines: Number(match[2] ?? 0),
280
+ }));
281
+ }
282
+ /**
283
+ * The ids of every paste placeholder already drawn — the "before" half of the
284
+ * only reliable proof that a write landed.
285
+ */
286
+ export function pastePlaceholderIds(screenText) {
287
+ return new Set(pastePlaceholders(screenText).map((p) => p.id));
288
+ }
289
+ /**
290
+ * The first placeholder on screen that `known` has not seen. Identity is the
291
+ * id and nothing else: claude rewrites a paste before drawing it — an image
292
+ * path becomes an `[Image #N]` chip and leaves the text shorter — so the
293
+ * `+N lines` it reports is not the line count of what we wrote and must never
294
+ * be matched against it.
295
+ */
296
+ export function newPastePlaceholder(known, screenText) {
297
+ return pastePlaceholders(screenText).find((p) => !known.has(p.id));
298
+ }
299
+ /**
300
+ * The live input box's text: everything from its `❯` row down.
301
+ *
302
+ * The only part of the screen where a prompt of ours can still be waiting, and
303
+ * so the only part worth searching for one. Everything above it is transcript,
304
+ * which holds our own prompts too — claude redraws a prompt into the transcript
305
+ * once it submits, and the frames the box scrolls off keep whatever they were
306
+ * showing at the time — so a whole-screen search answers a different question
307
+ * than the one the callers here are asking.
308
+ *
309
+ * Anchored on the box's own `❯` row rather than a count of rows from the
310
+ * bottom, and on the last such row rather than the first: claude draws a
311
+ * submitted prompt on a `❯` row too, so the transcript offers rows of the same
312
+ * shape above the real one. Everything from that row down is in scope, because
313
+ * an input long enough to wrap spills onto the rows beneath it.
314
+ *
315
+ * The glyph alone does not make a row the box's, for the reason hasInputBox
316
+ * gives above: a select list marks its highlighted option with the same `❯`,
317
+ * and reading one as an editor is how a prompt ends up pasted into `/model`
318
+ * with an Enter behind it. So the row has to carry the box's structure too —
319
+ * the top rule right above it, or the side borders terminals that draw them
320
+ * use. Only the opening rule is required, not the closing one, because a
321
+ * wrapped input pushes that several rows down.
322
+ *
323
+ * A box in shell mode counts, with its `!` row in the `❯` row's place. It holds
324
+ * a `!command` of ours between the paste and the Enter, and not reading it was
325
+ * how every such command longer than a word was reported as never having
326
+ * reached the editor, with the command sitting in the box on screen.
327
+ *
328
+ * One more row wears the glyph under a rule: the first of the menu claude
329
+ * draws beneath the box while a command is typed. Being last, it was taken
330
+ * for the box, and what it says is the command's own name. So `/config` was
331
+ * found in it and went through, while a command typed by its alias was not:
332
+ * under `/allowed-tools` the menu reads `❯ /permissions (allowed-tools)`,
333
+ * and the alias was reported as never having reached the editor.
334
+ *
335
+ * Undefined when no box is drawn at all — an overlay has replaced it, or the
336
+ * TUI is still starting. That is not the same answer as an empty box, and a
337
+ * caller about to send a keystroke needs to tell them apart.
338
+ */
339
+ export function inputBoxText(screenText) {
340
+ const lines = tailLines(screenText, INPUT_BOX_ROWS);
341
+ let inputRow = -1;
342
+ for (let i = 0; i < lines.length; i++) {
343
+ const line = lines[i];
344
+ // The command menu's marked row has the glyph and a rule right above it
345
+ // as well: the rule is the box's own closing one.
346
+ if (inputRow === i - 2 && inputRow >= 0 && COMMAND_MENU_ROW.test(line))
347
+ continue;
348
+ if (SIDE_BORDERED_INPUT.test(line)
349
+ || ((INPUT_ROW.test(line) || SHELL_INPUT_ROW.test(line)) && RULE.test(lines[i - 1] ?? '')))
350
+ inputRow = i;
351
+ }
352
+ if (inputRow === -1)
353
+ return boxAboveCommandMenu(screenText);
354
+ return lines.slice(inputRow).join('\n');
355
+ }
356
+ /**
357
+ * A row of the menu claude draws under the box while a slash command is being
358
+ * typed: the commands the text so far could mean, the likeliest marked.
359
+ *
360
+ * ❯ /config
361
+ * ────────────────────────────────────────
362
+ * ❯ /config Open settings
363
+ * /update-config Change settings: hooks, permissions, environment
364
+ * variables
365
+ *
366
+ * A command with other names lists them after its own:
367
+ * `❯ /permissions (allowed-tools) Manage allow and deny …`.
368
+ */
369
+ const COMMAND_MENU_ROW = /^\s{2}(?:❯ | {2})\/\S+(?: \([^)]*\))?(?:\s{2,}\S.*)?$/u;
370
+ /** The rest of a menu row's description, wrapped under it in the descriptions' column. */
371
+ const COMMAND_MENU_WRAP = /^\s{20,}\S/u;
372
+ /** Rows a command menu can run to. Measured: ten, for a `/config` that seven other commands also matched. */
373
+ const COMMAND_MENU_ROWS = 24;
374
+ /**
375
+ * The input box when a command menu has pushed it out of the bottom rows.
376
+ *
377
+ * The menu takes the footer's place and can be longer than {@link
378
+ * INPUT_BOX_ROWS}: `/config`, on a machine whose plugins add commands with
379
+ * "config" in their names, drew ten rows of it. The box was then above the
380
+ * rows read, so a command typed into it was reported as never having arrived,
381
+ * and `/config` could not be sent at all.
382
+ *
383
+ * Looking further up is only safe for this one shape, which is why it is
384
+ * spelled out: a `❯` row between two rules, and nothing under it but menu
385
+ * rows. A box from an earlier frame, still in the buffer above a dialog,
386
+ * has that dialog under it instead.
387
+ */
388
+ function boxAboveCommandMenu(screenText) {
389
+ const lines = tailLines(screenText, INPUT_BOX_ROWS + COMMAND_MENU_ROWS);
390
+ for (let i = lines.length - 3; i >= 1; i--) {
391
+ if (!INPUT_ROW.test(lines[i]) || !RULE.test(lines[i - 1]) || !RULE.test(lines[i + 1]))
392
+ continue;
393
+ const menu = lines.slice(i + 2);
394
+ const isMenu = COMMAND_MENU_ROW.test(menu[0])
395
+ && menu.every((line) => COMMAND_MENU_ROW.test(line) || COMMAND_MENU_WRAP.test(line));
396
+ return isMenu ? lines[i] : undefined;
397
+ }
398
+ return undefined;
399
+ }
400
+ /** What a row break can add between two characters of one line: spacing and side borders. */
401
+ const WRAP_FILLER = /[\s│]+/gu;
402
+ /**
403
+ * Does the input box hold `needle`, however claude wrapped it?
404
+ *
405
+ * Claude wraps the box at word boundaries. When the prompt's opening words are
406
+ * followed by a word too long for the rest of the row, such as a URL, the row
407
+ * breaks inside the slice we look for:
408
+ *
409
+ * ❯ I'm about to submit
410
+ * https://boards.corp.example.org/t/03-14-publish-the-next-release-…
411
+ *
412
+ * A plain substring search for `I'm about to submit http` cannot see that, so
413
+ * every attempt missed and the user was told nothing had been sent. Nothing a
414
+ * row break adds is part of the prompt, so both sides drop it before comparing.
415
+ */
416
+ export function inputBoxHolds(screenText, needle) {
417
+ const box = inputBoxText(screenText);
418
+ return box !== undefined && box.replace(WRAP_FILLER, '').includes(needle.replace(WRAP_FILLER, ''));
419
+ }
420
+ /** Most Ctrl+U presses one clear sends. A paste this long is always collapsed. */
421
+ const MAX_CLEAR_PRESSES = 64;
422
+ /**
423
+ * How many Ctrl+U presses empty the input box of `prompt`, in a box
424
+ * `boxCols` wide.
425
+ *
426
+ * One press deletes back to the start of the row the cursor is on. That is
427
+ * the row as wrapped on screen, not the line. A press at the start of a row
428
+ * deletes only the line break before it. So one press after a prompt that
429
+ * wrapped leaves its first row behind. Measured against a live 120x40 pty:
430
+ * the retry loop's single press left `I'm about to submit` in the box, the
431
+ * next attempt pasted the whole prompt after it, and three attempts left
432
+ * three copies there to ride along with the user's next message.
433
+ *
434
+ * The count is the most rows the prompt can fill, plus one press per line
435
+ * break. Claude wraps at word boundaries, which can leave a row half empty
436
+ * where long words meet, so each row is assumed to hold only half the box's
437
+ * width. A press with nothing left to delete does nothing, so sending too many
438
+ * costs only the time it takes.
439
+ */
440
+ export function clearPresses(prompt, boxCols) {
441
+ const lines = prompt.split(/\r\n|\r|\n/);
442
+ const perRow = Math.max(1, Math.floor(boxCols / 2));
443
+ const rows = lines.reduce((sum, line) => sum + Math.ceil(line.length / perRow) + 1, 0);
444
+ return Math.min(rows + lines.length, MAX_CLEAR_PRESSES);
445
+ }
446
+ /**
447
+ * Collapsed pastes sitting in the input box right now, as opposed to anywhere
448
+ * on the screen. This is the reader for "did Enter take?", where the whole-
449
+ * screen one gets the answer wrong: the box's earlier frames survive in the
450
+ * scrollback, so a prompt that submitted cleanly still has its old placeholder
451
+ * up there, and scanning for it never stops finding one.
452
+ */
453
+ export function inputBoxPastePlaceholders(screenText) {
454
+ return pastePlaceholders(inputBoxText(screenText) ?? '');
455
+ }
456
+ //# sourceMappingURL=tui-state.js.map
@@ -0,0 +1,105 @@
1
+ /**
2
+ * What keeps a pty turn from ending, and what is allowed to overrule it.
3
+ *
4
+ * The two answers here were each written after a live session hung on the
5
+ * other one's absence, and they fail in opposite directions: one ended a turn
6
+ * that was still running, the other refused to end one that had finished over
7
+ * an hour earlier. Both are decisions about trusting a signal that is not
8
+ * quite the thing it stands for, which is why they live together and in the
9
+ * open rather than inline in a timer callback.
10
+ *
11
+ * ---
12
+ *
13
+ * The gap between answering a dialog and claude picking the turn back up.
14
+ *
15
+ * The end-of-turn check has no direct signal for "claude is finished" — it
16
+ * infers it from a quiet pty, the input box being back, no spinner, and the
17
+ * session log having moved since the prompt went in. That inference holds for
18
+ * an ordinary turn. It does not hold in the moment after a dialog is answered,
19
+ * where every one of those is true and none of them mean what they usually do:
20
+ * the dialog is gone so the box is back, the spinner is not drawn yet because
21
+ * claude has not resumed, and the log moved long before the dialog opened.
22
+ *
23
+ * A turn resolved in that gap is not merely early, it is unrecoverable for the
24
+ * session. The bot hands back an answer and forgets the turn; claude carries on
25
+ * working with nobody listening. Its hooks arrive with no active turn and are
26
+ * dropped, so the in-flight tool count stops being maintained; its output goes
27
+ * nowhere; and because the screen does say "generating" once it resumes, every
28
+ * later message is held against it and rejected when the ceiling runs out.
29
+ * That is one live session spending 37 minutes unreachable, which is what this
30
+ * module exists to prevent.
31
+ *
32
+ * So the gap is waited out rather than reasoned about. Claude ends it by
33
+ * showing itself — a spinner on screen, or a tool announcing itself through the
34
+ * hooks — and a bound ends it if claude never does, because a dialog whose
35
+ * answer genuinely finished the turn has to resolve too.
36
+ */
37
+ /**
38
+ * Where a turn stands relative to a dialog it answered at `answeredAt`.
39
+ *
40
+ * `null` in, `null` out and `resuming: false` — no dialog was answered, so
41
+ * there is nothing to wait for and the caller's usual rules stand unchanged.
42
+ */
43
+ export function dialogResumeState(answeredAt, { generating, inflightTools, now, graceMs }) {
44
+ if (answeredAt === null)
45
+ return { answeredAt: null, resuming: false };
46
+ // Claude showed itself. The marker has done its job and must be cleared, not
47
+ // just ignored: leaving it set would hold the *real* end of this turn off for
48
+ // the rest of the grace window every time the check ran.
49
+ if (generating || inflightTools > 0)
50
+ return { answeredAt: null, resuming: false };
51
+ // Nothing from claude yet. Keep waiting, unless we have waited long enough
52
+ // that "the dialog ended the turn" is the better reading. Note this keeps the
53
+ // marker: the bound stops it blocking, and clearing it here would restart the
54
+ // window on a later check that happened to see the same silence.
55
+ return { answeredAt, resuming: now - answeredAt < graceMs };
56
+ }
57
+ /**
58
+ * Whether the turn may end, and what is holding it if not.
59
+ *
60
+ * Stop outranks the tool count, and that ordering is the whole point. Stop is
61
+ * emitted after every tool has completed, so once it has fired a non-zero
62
+ * count cannot be a live tool — it is a decrement that never arrived. The
63
+ * hooks are `curl` calls into a loopback server, fired and forgotten
64
+ * (`>/dev/null 2>&1; exit 0`), and a POST that fails takes its decrement with
65
+ * it. There is no retry, and nothing else ever brings the count back down.
66
+ *
67
+ * Checking the count first, as this did, let one lost hook outrank the only
68
+ * authoritative end-of-turn signal there is. A turn then hung until the
69
+ * two-hour ceiling with claude idle at its prompt and its finished answer
70
+ * sitting undelivered in the session log — which is exactly what happened to
71
+ * one chat, an hour and seven minutes after claude had said "Done".
72
+ *
73
+ * The count still guards the ordinary path, where it earns its keep: a tool
74
+ * like telecoder_ask_user long-polls for a button tap and the pty is silent
75
+ * by design for as long as it waits, which is otherwise indistinguishable
76
+ * from a finished turn.
77
+ *
78
+ * Nor is a screen that says finished proof of it. Claude can pause for a
79
+ * second or two in the middle of writing a reply with no spinner in the rows
80
+ * the check reads, and the reply reaches the log only once the whole message
81
+ * is in. A turn on claude 2.1.311 was ended that way 0.2s before claude wrote
82
+ * its reply and fired Stop: the log held the prompt and nothing after it, the
83
+ * chat got an empty "Done", and the answer was never sent. So without Stop,
84
+ * the log has to show the turn's end too, and only a long quiet — a Stop hook
85
+ * lost on its way — ends a turn that has neither.
86
+ */
87
+ export function turnHold(s) {
88
+ // Stop is authoritative. All it waits for is the screen to settle.
89
+ if (s.stopReceived)
90
+ return s.isIdle ? null : 'working';
91
+ if (s.inflightTools > 0)
92
+ return 'tools';
93
+ if (!(s.isIdle && s.hasInputBox && !s.stillGenerating && s.claudeProducedSomething)) {
94
+ return 'working';
95
+ }
96
+ // Everything says finished, which is also how the moment after a dialog is
97
+ // answered looks. That one is not finished.
98
+ if (s.resumingAfterDialog)
99
+ return 'resuming';
100
+ // And how a pause in the middle of a reply looks.
101
+ if (!s.stopWaitOver && !s.turnEndedInLog())
102
+ return 'stop';
103
+ return null;
104
+ }
105
+ //# sourceMappingURL=turn-end.js.map
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Tracks assistant prose already delivered to Telegram *during* a PTY turn.
3
+ *
4
+ * A pty has no streaming text channel. The turn's prose is scraped from
5
+ * Claude Code's JSONL log at end-of-turn (readLastAssistantTurnText) and posted
6
+ * as one message. That is fine right up until the model stops mid-turn to ask a
7
+ * question: everything it wrote to explain the choice is still sitting
8
+ * undelivered in the log, so the buttons arrive with no reasoning attached and
9
+ * the explanation only lands after the user has already picked.
10
+ *
11
+ * The ask_user bridge fixes that by flushing the prose written so far as its
12
+ * own message just above the question, and recording it here. At end-of-turn
13
+ * the provider strips what was already sent so the user doesn't read it twice.
14
+ *
15
+ * In-memory and per-turn: cleared when a turn starts and when it finishes, so
16
+ * a crash mid-turn can at worst cause one duplicated paragraph, never a
17
+ * swallowed reply.
18
+ */
19
+ /**
20
+ * How readLastAssistantTurnText joins consecutive assistant text records. The
21
+ * flushed text is always a prefix of the end-of-turn text under this same
22
+ * join, which is what makes the strip below a plain prefix match.
23
+ */
24
+ const RECORD_SEPARATOR = '\n\n';
25
+ const delivered = new Map();
26
+ /** Remember the full run of turn prose that has now been sent to the chat. */
27
+ export function recordDeliveredProse(sessionKey, text) {
28
+ if (!text)
29
+ return;
30
+ delivered.set(sessionKey, text);
31
+ }
32
+ /** What has been delivered so far this turn, if anything. */
33
+ export function getDeliveredProse(sessionKey) {
34
+ return delivered.get(sessionKey);
35
+ }
36
+ /** Drop the turn's record. Called at both ends of a PTY turn. */
37
+ export function clearDeliveredProse(sessionKey) {
38
+ delivered.delete(sessionKey);
39
+ }
40
+ /**
41
+ * Return the part of `full` that hasn't been delivered yet.
42
+ *
43
+ * Deliberately conservative: if `full` doesn't actually start with what we
44
+ * delivered — a screen-scrape fallback, a compaction rewriting the log, a
45
+ * session swapped underneath us — nothing is stripped. Showing a paragraph
46
+ * twice is a cosmetic annoyance; silently eating the model's answer is not.
47
+ */
48
+ export function stripDeliveredPrefix(full, alreadyDelivered) {
49
+ if (!alreadyDelivered || !full)
50
+ return full;
51
+ if (full === alreadyDelivered)
52
+ return '';
53
+ if (!full.startsWith(alreadyDelivered))
54
+ return full;
55
+ const rest = full.slice(alreadyDelivered.length);
56
+ // Only a record boundary counts as a real continuation. What we delivered is
57
+ // always a whole run of joined records, so anything else means the two
58
+ // strings merely happen to share a prefix — cutting there would behead the
59
+ // reply mid-sentence.
60
+ if (!rest.startsWith(RECORD_SEPARATOR))
61
+ return full;
62
+ return rest.slice(RECORD_SEPARATOR.length);
63
+ }
64
+ //# sourceMappingURL=turn-prose.js.map