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,142 @@
1
+ /**
2
+ * A prompt as TeleCoder shows it back: in /prompts, /recap and /handoff, on
3
+ * the branches /tree draws, in the status line under an answer, and at the
4
+ * bottom of the live action log.
5
+ *
6
+ * What the session log records as a prompt is often not what was typed: an
7
+ * upload arrives wrapped in a note saying where the file landed, a paste in
8
+ * the tags Claude Code puts around it, a reply under the quote it answers.
9
+ * These undo that, so a prompt reads the way it was sent.
10
+ *
11
+ * Lives here rather than with the /prompts command it started in because the
12
+ * action log needs it too, and that command's module imports the message
13
+ * sender, which imports the action log.
14
+ */
15
+ import { userTextKind } from '../claude/session-jsonl.js';
16
+ // An upload never reaches claude as the caption you typed. photo.handler wraps
17
+ // it in a note saying where the file landed and what to do with it, and that
18
+ // whole scaffold is what the transcript records — so replaying it verbatim
19
+ // buries the one line you actually wrote under six you didn't. Claude then
20
+ // makes it worse on the way in: it lifts every file path out of the note into
21
+ // an `[Image #N]` chip, leaving `Saved at:` and ` 1.` pointing at nothing.
22
+ //
23
+ // Collapse those notes back to what the upload was: kind, name, caption.
24
+ const UPLOAD_CHIPS = /^(?:\[(?:Image|Pasted text) #\d+(?: \+\d+ lines)?\]\s*)+/;
25
+ const IMAGE_NOTE = 'User uploaded an image to the project.';
26
+ const FILE_NOTE = /^User uploaded a file: (.+)$/;
27
+ // The line each handler puts directly after the caption — the caption itself
28
+ // is a user-supplied string that may run over several lines.
29
+ const AFTER_CAPTION = /^(?:The image is attached as a vision input|Use the Read tool to read its contents)/;
30
+ function uploadCaption(lines) {
31
+ const start = lines.findIndex((l) => l.startsWith('Caption: '));
32
+ if (start === -1)
33
+ return undefined;
34
+ let end = lines.length;
35
+ for (let i = start + 1; i < lines.length; i++) {
36
+ if (AFTER_CAPTION.test(lines[i])) {
37
+ end = i;
38
+ break;
39
+ }
40
+ }
41
+ const raw = lines.slice(start, end).join('\n').slice('Caption: '.length).trim();
42
+ if (raw === '(none)')
43
+ return undefined;
44
+ return raw.replace(/^"/, '').replace(/"$/, '').trim() || undefined;
45
+ }
46
+ /**
47
+ * Render an upload note as the upload it stands for, or return `text` unchanged
48
+ * when it isn't one. Matching is anchored on the note's own first line, so a
49
+ * prompt that merely quotes one is left alone.
50
+ */
51
+ export function summarizeUserPrompt(text) {
52
+ const lines = text.replace(UPLOAD_CHIPS, '').split('\n');
53
+ const first = lines[0]?.trim() ?? '';
54
+ let label;
55
+ if (first === IMAGE_NOTE) {
56
+ label = '📷 Image';
57
+ }
58
+ else {
59
+ const named = FILE_NOTE.exec(first);
60
+ if (named)
61
+ label = `📎 ${named[1].trim()}`;
62
+ }
63
+ if (!label)
64
+ return text;
65
+ const caption = uploadCaption(lines);
66
+ return caption ? `${label} — ${caption}` : label;
67
+ }
68
+ /**
69
+ * A prompt as a label: what the user asked, cleaned of what got wrapped
70
+ * around it — or undefined when it wasn't a turn of the conversation at all,
71
+ * but a command.
72
+ *
73
+ * /tree names a branch after the first prompt past a split, and the status
74
+ * line lists the last few; on the evidence of real transcripts either is often
75
+ * a paste, a reply quoted back, or a /compact. A paste keeps its text and
76
+ * loses its tags; a quote gives way to the words the user wrote under it,
77
+ * which say what the prompt asks rather than what it answers.
78
+ */
79
+ export function promptLabel(raw) {
80
+ const text = raw.trim();
81
+ if (userTextKind(text) !== 'prompt')
82
+ return undefined;
83
+ const unwrapped = summarizeUserPrompt(unwrapPaste(text));
84
+ const lines = unwrapped.split('\n');
85
+ const own = lines.filter((line) => !/^\s*>/.test(line)).join(' ');
86
+ const quoted = lines.map((line) => line.replace(/^\s*>\s?/, '')).join(' ');
87
+ const label = (own.trim() ? own : quoted)
88
+ .replace(/\s+/g, ' ')
89
+ .trim()
90
+ // A prompt written as a list starts with its marker, which says nothing.
91
+ .replace(/^(?:[-*•]|\d+[.)])\s+/, '');
92
+ return label || undefined;
93
+ }
94
+ /**
95
+ * `text` without the tags Claude Code wraps a long or multi-line paste in,
96
+ * along with the line break it puts inside each, so a paste in the middle of a
97
+ * turn keeps the blank line around it and gains no extra one.
98
+ */
99
+ export function unwrapPaste(text) {
100
+ return text.replace(/<pasted_content[^>]*>\n?|\n?<\/pasted_content[^>]*>/g, '').trim();
101
+ }
102
+ // What stands in for the middle of a prompt too long to show whole.
103
+ const ELISION = ' … ';
104
+ // How far a cut moves to fall between words rather than inside one: about the
105
+ // longest word. A path or a URL runs longer, and is cut where the cut falls.
106
+ const WORD_SLACK = 15;
107
+ /**
108
+ * `label` in at most `max` characters: whole when it fits, otherwise its start
109
+ * and its end with an ellipsis where the middle was. A long prompt usually
110
+ * closes on what it asks — "what do you think?" — so a cut that kept only the
111
+ * start dropped the question. The start gets two thirds, being what says what
112
+ * the prompt is about.
113
+ *
114
+ * Cut by code point, so an emoji at a cut isn't split in half, and between
115
+ * words when there's a space near, so neither side ends or starts mid-word.
116
+ */
117
+ export function cutLabel(label, max) {
118
+ const chars = Array.from(label);
119
+ if (chars.length <= max)
120
+ return label;
121
+ const room = max - ELISION.length;
122
+ const start = chars.slice(0, startEndsAt(chars, Math.ceil((room * 2) / 3))).join('');
123
+ const end = chars.slice(endStartsAt(chars, chars.length - Math.floor(room / 3))).join('');
124
+ return start.trimEnd() + ELISION + end.trimStart();
125
+ }
126
+ /** Where the start ends: at `cut`, or back at the space before the word `cut` falls in. */
127
+ function startEndsAt(chars, cut) {
128
+ for (let i = cut; i > 0 && cut - i <= WORD_SLACK; i--) {
129
+ if (/\s/.test(chars[i]))
130
+ return i;
131
+ }
132
+ return cut;
133
+ }
134
+ /** Where the end starts: at `cut`, or on past the word `cut` falls in. */
135
+ function endStartsAt(chars, cut) {
136
+ for (let i = cut - 1; i < chars.length && i - cut < WORD_SLACK; i++) {
137
+ if (/\s/.test(chars[i]))
138
+ return i + 1;
139
+ }
140
+ return cut;
141
+ }
142
+ //# sourceMappingURL=prompt-label.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * How Claude Code's predicted next prompt is rendered in the chat.
3
+ *
4
+ * The suggestion is scraped from one row of a 120-column terminal, so it can
5
+ * arrive nearly 120 characters wide — several times what an inline button
6
+ * shows before Telegram ellipsises it, with no way for the reader to expand
7
+ * it. Offering it as a button alone therefore delivered a half-sentence and
8
+ * dropped the rest: the user could still tap it, but could not read what they
9
+ * were about to send.
10
+ *
11
+ * So the same rule `telecoder_ask_user` follows applies here. Text rides on
12
+ * its own button while it fits, which keeps the common short suggestion a
13
+ * single tap under the response and adds nothing to the chat. Anything wider
14
+ * goes into its own message — a card — where the full prompt is in the body
15
+ * and the button beneath it is a fixed short label that cannot be clipped.
16
+ */
17
+ import { EntityText } from './entities.js';
18
+ import { fitsOnButton } from './button-text.js';
19
+ const BULB = '💡';
20
+ /** Fixed label for the card's button; the prompt itself is in the body above. */
21
+ export const SUGGESTION_CARD_BUTTON = `${BULB} Send this prompt`;
22
+ /**
23
+ * Collapse scraped ghost text to a single clean line. The flattened form is
24
+ * what gets stored, shown and ultimately sent, so what the user reads is
25
+ * exactly what Claude receives.
26
+ */
27
+ export function flattenSuggestion(text) {
28
+ return text.replace(/\s+/gu, ' ').trim();
29
+ }
30
+ /** Button label for a suggestion short enough to carry its own text. */
31
+ export function formatSuggestionLabel(text) {
32
+ return `${BULB} ${flattenSuggestion(text)}`;
33
+ }
34
+ /**
35
+ * True when the whole suggestion — bulb and all — survives on a button. False
36
+ * means it needs a card; nothing is ever truncated on the way to the user.
37
+ */
38
+ export function suggestionFitsOnButton(text) {
39
+ return fitsOnButton(formatSuggestionLabel(text));
40
+ }
41
+ /**
42
+ * The card body: a plain header over the prompt in italics.
43
+ *
44
+ * `sent: true` is the same message rewritten once the button has been tapped.
45
+ * The card is the only place the prompt is written out, so it has to keep
46
+ * showing it — but it must stop reading as an offer, the way an answered
47
+ * question grows a "✅ Answered" footer instead of silently losing its
48
+ * keyboard.
49
+ */
50
+ export function buildSuggestionCardText(text, opts = {}) {
51
+ const header = opts.sent ? '✅ Sent:' : `${BULB} Suggested next prompt:`;
52
+ return new EntityText().add(header).newline().italic(flattenSuggestion(text)).build();
53
+ }
54
+ //# sourceMappingURL=prompt-suggestion.js.map
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Sending formatted text to Telegram: every message goes out as plain text
3
+ * plus entities (see ./entities.ts), never with a parse mode.
4
+ *
5
+ * These wrap the three things a handler does with text — reply, send to a
6
+ * chat, edit — so a call site hands over an {@link EntityMessage} (or
7
+ * markdown) and the splitting, trimming and the plain-text fallback happen in
8
+ * one place.
9
+ */
10
+ import { GrammyError } from 'grammy';
11
+ import { trimMessage, plain } from './entities.js';
12
+ import { formatMarkdown, splitEntityMessage, MAX_ENTITIES, MAX_MESSAGE_LENGTH } from './markdown.js';
13
+ function asMessage(text) {
14
+ return trimMessage(typeof text === 'string' ? plain(text) : text);
15
+ }
16
+ /**
17
+ * Telegram turned the formatting down rather than the message. It only does
18
+ * that for an entity it won't accept — a link it can't open, an offset off
19
+ * the end — and the same text without them will go through.
20
+ */
21
+ export function isEntityError(error) {
22
+ if (!(error instanceof GrammyError) || error.error_code !== 400)
23
+ return false;
24
+ return /entit|can't parse|wrong (?:http )?url|url host is empty|unsupported url protocol/i.test(error.description);
25
+ }
26
+ /** `other` with the message's entities on it, and no parse mode. */
27
+ function withEntities(other, entities) {
28
+ const { parse_mode: _ignored, ...rest } = (other ?? {});
29
+ return { ...rest, entities };
30
+ }
31
+ /** Post one message through `post`, unformatted again if Telegram refuses the formatting. */
32
+ async function postOne(post, text, other) {
33
+ const message = fitOne(asMessage(text));
34
+ try {
35
+ return await post(message.text || '…', withEntities(other, message.entities));
36
+ }
37
+ catch (error) {
38
+ if (!isEntityError(error) || message.entities.length === 0)
39
+ throw error;
40
+ console.error('[Send] Telegram refused the formatting, sending plain text:', error.description);
41
+ return post(message.text, withEntities(other, []));
42
+ }
43
+ }
44
+ function apiPoster(api, chatId) {
45
+ return (text, other) => api.sendMessage(chatId, text, other);
46
+ }
47
+ /** `ctx.reply`, which keeps a reply in the forum topic it answers. */
48
+ function replyPoster(ctx) {
49
+ return (text, other) => ctx.reply(text, other);
50
+ }
51
+ /**
52
+ * Send one message — it must fit in one; see {@link sendParts} for anything
53
+ * longer. Retries once unformatted if Telegram refuses the formatting.
54
+ */
55
+ export async function sendFormatted(api, chatId, text, other) {
56
+ return postOne(apiPoster(api, chatId), text, other);
57
+ }
58
+ /** {@link sendFormatted} as a reply in the chat (and topic) `ctx` came from. */
59
+ export async function replyFormatted(ctx, text, other) {
60
+ return postOne(replyPoster(ctx), text, other);
61
+ }
62
+ /**
63
+ * Edit a message's text. A message that has grown past Telegram's limit is
64
+ * clipped: an edit can't split, so whoever needs the rest must send it.
65
+ * Retries unformatted if Telegram refuses the formatting.
66
+ */
67
+ export async function editFormatted(api, chatId, messageId, text, other) {
68
+ const message = fitOne(asMessage(text));
69
+ try {
70
+ await api.editMessageText(chatId, messageId, message.text || '…', withEntities(other, message.entities));
71
+ }
72
+ catch (error) {
73
+ if (!isEntityError(error) || message.entities.length === 0)
74
+ throw error;
75
+ console.error('[Send] Telegram refused the formatting, editing to plain text:', error.description);
76
+ await api.editMessageText(chatId, messageId, message.text, withEntities(other, []));
77
+ }
78
+ }
79
+ /** {@link editFormatted} on the message a callback query's button sits on. */
80
+ export async function editCallbackMessage(ctx, text, other) {
81
+ const message = ctx.callbackQuery?.message;
82
+ const chatId = message?.chat.id ?? ctx.chat?.id;
83
+ if (!message || chatId === undefined)
84
+ throw new Error('editCallbackMessage: no message on this update');
85
+ await editFormatted(ctx.api, chatId, message.message_id, text, other);
86
+ }
87
+ /**
88
+ * Send a message of any length as however many parts it needs. `other` goes on
89
+ * every part except `reply_markup`, which goes on the last, under the end of
90
+ * the text. Returns the parts as sent.
91
+ */
92
+ export async function sendParts(api, chatId, text, other) {
93
+ return postSplit(apiPoster(api, chatId), splitEntityMessage(asMessage(text)), other);
94
+ }
95
+ /** {@link sendParts} from markdown: the way the model's own text is sent. */
96
+ export async function sendMarkdown(api, chatId, markdown, other) {
97
+ return postSplit(apiPoster(api, chatId), formatMarkdown(markdown), other);
98
+ }
99
+ /** {@link sendParts} as replies in the chat (and topic) `ctx` came from. */
100
+ export async function replyParts(ctx, text, other) {
101
+ return postSplit(replyPoster(ctx), splitEntityMessage(asMessage(text)), other);
102
+ }
103
+ /** {@link sendMarkdown} as replies in the chat (and topic) `ctx` came from. */
104
+ export async function replyMarkdown(ctx, markdown, other) {
105
+ return postSplit(replyPoster(ctx), formatMarkdown(markdown), other);
106
+ }
107
+ async function postSplit(post, parts, other) {
108
+ const { reply_markup, ...rest } = other ?? {};
109
+ const sent = [];
110
+ for (let i = 0; i < parts.length; i++) {
111
+ const last = i === parts.length - 1;
112
+ sent.push(await postOne(post, parts[i], last && reply_markup ? { ...rest, reply_markup } : rest));
113
+ }
114
+ return sent;
115
+ }
116
+ /** A message cut down to one Telegram message, ending in an ellipsis. */
117
+ function fitOne(message) {
118
+ if (message.text.length <= MAX_MESSAGE_LENGTH && message.entities.length <= MAX_ENTITIES)
119
+ return message;
120
+ const [first] = splitEntityMessage(message, MAX_MESSAGE_LENGTH - 1, { markers: false });
121
+ return { text: first.text + '…', entities: first.entities };
122
+ }
123
+ //# sourceMappingURL=send.js.map
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The parts of running a streamed agent turn that don't depend on *why* the
3
+ * turn is running.
4
+ *
5
+ * Lives under `telegram/` rather than with the message handlers because the
6
+ * scheduler drives turns too, and `claude/scheduled-runner.ts` cannot import
7
+ * the handler layer without closing a cycle. Everything here depends only on
8
+ * the message sender, the request queue and the verbosity settings — all of
9
+ * which sit below both callers.
10
+ */
11
+ import { setAbortController } from '../claude/request-queue.js';
12
+ import { resolveVerbosityFlags } from '../utils/verbosity.js';
13
+ import { messageSender } from './message-sender.js';
14
+ /**
15
+ * Build the `onToolResult` callback passed to the provider runner. Resolves
16
+ * verbosity flags lazily on each event so a /verbosity change mid-turn takes
17
+ * effect immediately, and short-circuits when the chat opts out of tool
18
+ * previews entirely.
19
+ */
20
+ export function makeToolResultHandler(ctx) {
21
+ return (event) => {
22
+ const cid = ctx.chat?.id;
23
+ if (cid === undefined)
24
+ return;
25
+ const flags = resolveVerbosityFlags(cid);
26
+ if (!flags.showToolResults)
27
+ return;
28
+ return messageSender.postToolResult(ctx, event, flags.toolResultMaxLines, flags.toolResultMaxChars);
29
+ };
30
+ }
31
+ /** Companion to `makeToolResultHandler` for Edit/Write diff previews. */
32
+ export function makeEditDiffHandler(ctx) {
33
+ return (event) => {
34
+ const cid = ctx.chat?.id;
35
+ if (cid === undefined)
36
+ return;
37
+ const flags = resolveVerbosityFlags(cid);
38
+ if (!flags.showDiffs)
39
+ return;
40
+ return messageSender.postEditDiff(ctx, event, flags.diffMaxLines);
41
+ };
42
+ }
43
+ /**
44
+ * Callbacks that render a turn's progress into the streaming message. Shared
45
+ * by every streaming entry point, including /loop — which takes only these,
46
+ * since `sendLoopToAgent` reports iteration progress rather than individual
47
+ * tool calls.
48
+ */
49
+ export function progressCallbacks(ctx) {
50
+ return {
51
+ onProgress: (progressText) => {
52
+ messageSender.updateStream(ctx, progressText);
53
+ },
54
+ onTip: (tip) => {
55
+ messageSender.updateTip(ctx, tip);
56
+ },
57
+ onToolResult: makeToolResultHandler(ctx),
58
+ onEditDiff: makeEditDiffHandler(ctx),
59
+ };
60
+ }
61
+ /**
62
+ * Per-tool telemetry on top of `progressCallbacks`, for the `sendToAgent`
63
+ * paths that surface the running tool in the stream header and relay
64
+ * sub-agent output.
65
+ */
66
+ export function toolCallbacks(ctx, sessionKey) {
67
+ return {
68
+ onToolStart: (toolName, input) => {
69
+ messageSender.updateToolOperation(sessionKey, toolName, input, ctx);
70
+ },
71
+ onToolEnd: () => {
72
+ messageSender.clearToolOperation(sessionKey);
73
+ },
74
+ onTaskEvent: (event) => messageSender.notifyTaskEvent(ctx, sessionKey, event),
75
+ onSubTurnResponse: (text) => messageSender.postSubTurnResponse(ctx, text),
76
+ };
77
+ }
78
+ /**
79
+ * Open a streaming message for a turn sent `prompt`, run `body` against a
80
+ * fresh abort controller, and guarantee the stream is torn down if anything
81
+ * throws. The prompt is shown again at the bottom of the action log, which
82
+ * pushes the message it came in off screen.
83
+ *
84
+ * Every caller previously repeated this preamble by hand. Two invariants are
85
+ * easy to lose that way and are now structural: the session's abort controller
86
+ * is always registered before the provider is called (so /cancel can reach the
87
+ * turn), and a failure always replaces the spinner with the error rather than
88
+ * leaving it animating forever.
89
+ *
90
+ * The error is re-thrown after teardown so the caller's own queue handling —
91
+ * "Queue cleared" suppression, error replies — still sees it.
92
+ */
93
+ export async function withStreamingTurn(ctx, sessionKey, prompt, body) {
94
+ await messageSender.startStreaming(ctx, prompt);
95
+ const abortController = new AbortController();
96
+ setAbortController(sessionKey, abortController);
97
+ try {
98
+ await body(abortController);
99
+ }
100
+ catch (error) {
101
+ await messageSender.cancelStreaming(ctx, error);
102
+ throw error;
103
+ }
104
+ }
105
+ //# sourceMappingURL=streaming-turn.js.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Per-chat prompt-suggestion settings — controls whether TeleCoder enables
3
+ * Claude Code's `prompt_suggestion` feature for this session and scrapes the
4
+ * resulting ghost text. Persisted to ~/.telecoder/suggestions-settings.json.
5
+ *
6
+ * Takes effect on next PTY spawn (the env var is set at spawn time). A
7
+ * mid-session toggle is recorded but won't activate until the user starts a
8
+ * new session or the PTY is restarted for any other reason.
9
+ */
10
+ import { z } from 'zod';
11
+ import { config } from '../config.js';
12
+ import { createKeyedSettings } from '../utils/keyed-settings.js';
13
+ const store = createKeyedSettings({
14
+ file: 'suggestions-settings.json',
15
+ label: 'Suggestions',
16
+ entrySchema: z.object({ enabled: z.boolean().optional() }),
17
+ normalize: (stored) => ({
18
+ enabled: typeof stored?.enabled === 'boolean' ? stored.enabled : config.PROMPT_SUGGESTIONS_DEFAULT,
19
+ }),
20
+ });
21
+ export function getSuggestionsSettings(sessionKey) {
22
+ return store.get(sessionKey);
23
+ }
24
+ export function setSuggestionsEnabled(sessionKey, enabled) {
25
+ store.update(sessionKey, { enabled });
26
+ }
27
+ export function isSuggestionsEnabled(sessionKey) {
28
+ return store.get(sessionKey).enabled;
29
+ }
30
+ //# sourceMappingURL=suggestions-settings.js.map