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,409 @@
1
+ /**
2
+ * `/cost` — Claude Code's own cost report, delivered to the chat.
3
+ *
4
+ * What `/cost` reports depends on how the account pays, and the difference
5
+ * decides how much of it TeleCoder can honour:
6
+ *
7
+ * - subscription: the limits view — how much of the session and weekly
8
+ * windows is spent, and when each resets. Account-wide, and the same text
9
+ * `/usage` prints. Asking it in a process that has just spent $0.10
10
+ * returns exactly that view with no session figure in it.
11
+ * - API billing: the session's own totals — dollars, durations, per-model
12
+ * token counts.
13
+ *
14
+ * That second shape is session-scoped, and no probe recovers it. The cost
15
+ * counter lives in the CLI process that spent it: resume the session in a
16
+ * fresh process and it reads zero, because the session log carries no cost
17
+ * field to rebuild it from. So the totals a spawned probe reports are its own,
18
+ * not the conversation's, and `parseCostOutput` says so rather than letting a
19
+ * $0.00 read as this chat having been free.
20
+ *
21
+ * Since the probe is a fresh process either way, it needs no session and no
22
+ * `--resume` — nothing here can append a stray turn to a live conversation,
23
+ * and the command answers before a project is even open.
24
+ *
25
+ * What the probe can't have, the chat's own claude still holds. In PTY mode
26
+ * there is a live TUI a `/cost` away from drawing exactly those totals, so we
27
+ * ask it too and scrape the Session block off the overlay — the same trick
28
+ * /tasks uses. That is where "Total cost", the durations, the per-model
29
+ * breakdown and the prompt-cache line come from, and it is why the report is
30
+ * fuller in PTY mode than in SDK mode, where the totals stay unanswerable and
31
+ * TeleCoder's own per-turn tally stands in.
32
+ *
33
+ * Two sources, one report, no overlap: the panel's own limits view is left
34
+ * unscraped (it scrolls off the first screenful anyway) and read from the
35
+ * probe, which prints the same numbers in any mode.
36
+ */
37
+ import { spawn } from 'child_process';
38
+ import * as fs from 'fs';
39
+ import { sessionManager } from '../../../claude/session-manager.js';
40
+ import { config } from '../../../config.js';
41
+ import { getSessionCost } from '../../../claude/session-cost.js';
42
+ import { scrapeCostSession } from '../../../claude/cost-overlay-scraper.js';
43
+ import { getActiveMethod, getPtyProvider } from '../../../providers/claude-provider.js';
44
+ import { messageSender } from '../../../telegram/message-sender.js';
45
+ import { getProgressBar } from '../../../utils/format.js';
46
+ import { resolveActiveClaudeExecutable } from '../../../utils/resolve-claude-bin.js';
47
+ import { sanitizeError } from '../../../utils/sanitize.js';
48
+ import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
49
+ import { getWorkspaceRoot } from '../../../utils/workspace-guard.js';
50
+ /** The probe answers in ~2s; the ceiling matches `/context`'s. */
51
+ const COST_TIMEOUT_MS = 20_000;
52
+ /** Output cap, standing in for `execFile`'s `maxBuffer`. */
53
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
54
+ /** `Current session: 39% used · resets Aug 31, 5:09pm (UTC)` */
55
+ const LIMIT_RE = /^(.+?):\s*(\d+(?:\.\d+)?)%\s+used\b(?:\s*[·•-]\s*resets\s+(.+?))?$/i;
56
+ /** `Total cost: $0.1234` — the API-billing shape's label/value rows. */
57
+ const TOTALS_RE = /^(Total\s+[^:]+):\s*(.+)$/i;
58
+ /** `Last 24h · 1608 requests · 89 sessions` */
59
+ const PERIOD_RE = /^(Last\s+\S+)(\s*[·•].*)$/i;
60
+ /**
61
+ * Turn the Session block scraped off the live TUI into report lines.
62
+ *
63
+ * Kept close to the panel's own layout — same labels, same order, the
64
+ * per-model rows still nested under `Usage by model` — because this is the
65
+ * half of the report people already know from typing `/cost` in a terminal.
66
+ */
67
+ function renderSessionBlock(session) {
68
+ const lines = ['**This session**'];
69
+ for (const row of session.rows) {
70
+ if (row.nested) {
71
+ // A model's own line. Two spaces is the least indentation Telegram will
72
+ // render as a nested bullet rather than flatten into its parent.
73
+ lines.push(` - \`${row.label}\`: ${row.value}`);
74
+ }
75
+ else if (row.value) {
76
+ lines.push(`- **${row.label}:** ${row.value}`);
77
+ }
78
+ else {
79
+ // `Usage by model:` and friends — a label whose value is the rows below.
80
+ lines.push(`- **${row.label}:**`);
81
+ }
82
+ }
83
+ return lines;
84
+ }
85
+ /**
86
+ * Render `claude -p /cost` output as Telegram markdown.
87
+ *
88
+ * `chatCost` is TeleCoder's own running tally for this conversation, used in
89
+ * SDK mode where nothing else can answer what the chat has spent.
90
+ *
91
+ * `session` is the Session block off the live TUI's `/cost` panel — the real
92
+ * totals for this conversation, present only in PTY mode. When we have it, the
93
+ * probe's own `Total ...` rows are dropped rather than printed alongside: they
94
+ * belong to the process that ran the lookup, and two contradicting sets of
95
+ * totals in one message is worse than the one true set.
96
+ */
97
+ export function parseCostOutput(raw, chatCost, session) {
98
+ const trimmed = raw.trim();
99
+ if (!trimmed) {
100
+ // The probe failing doesn't make the live totals worthless — they are the
101
+ // part people came for, so show them alone rather than only an error.
102
+ if (session)
103
+ return ['## 💰 Cost & Usage', '', ...renderSessionBlock(session)].join('\n');
104
+ return '⚠️ No cost output received.';
105
+ }
106
+ const body = [];
107
+ let recognised = 0;
108
+ let sawTotals = false;
109
+ /**
110
+ * Inside the probe's own `Usage by model:` section, which the live block
111
+ * supersedes. Its rows are indented, and so are the per-period detail rows
112
+ * further down that we do want, so dropping them takes knowing which
113
+ * heading we are under.
114
+ */
115
+ let underSupersededModels = false;
116
+ /** Collapse runs of blank lines, and never open a section with one. */
117
+ const pushBlank = () => {
118
+ if (body.length > 0 && body[body.length - 1] !== '')
119
+ body.push('');
120
+ };
121
+ for (const rawLine of trimmed.split('\n')) {
122
+ const line = rawLine.trim();
123
+ // Any unindented line — or a blank one — closes whatever section we were in.
124
+ if (!line || !/^\s/.test(rawLine))
125
+ underSupersededModels = false;
126
+ if (!line) {
127
+ pushBlank();
128
+ continue;
129
+ }
130
+ const limit = line.match(LIMIT_RE);
131
+ if (limit) {
132
+ const pct = Math.round(Number(limit[2]));
133
+ // "Current session" reads better as "session" once the bar carries the number.
134
+ const label = limit[1].replace(/^current\s+/i, '');
135
+ const resets = limit[3] ? ` — resets ${limit[3]}` : '';
136
+ body.push(`${getProgressBar(pct)} **${pct}%** ${label}${resets}`);
137
+ recognised++;
138
+ continue;
139
+ }
140
+ const totals = line.match(TOTALS_RE);
141
+ if (totals) {
142
+ // Recognised either way — the line is understood, it is just superseded.
143
+ if (!session) {
144
+ body.push(`- **${totals[1]}:** ${totals[2].trim()}`);
145
+ sawTotals = true;
146
+ }
147
+ recognised++;
148
+ continue;
149
+ }
150
+ const period = line.match(PERIOD_RE);
151
+ if (period) {
152
+ pushBlank();
153
+ body.push(`**${period[1]}**${period[2]}`);
154
+ recognised++;
155
+ continue;
156
+ }
157
+ if (/^usage by model:?$/i.test(line)) {
158
+ if (session) {
159
+ underSupersededModels = true;
160
+ }
161
+ else {
162
+ pushBlank();
163
+ body.push('**Usage by model**');
164
+ }
165
+ recognised++;
166
+ continue;
167
+ }
168
+ if (/^what's contributing/i.test(line)) {
169
+ pushBlank();
170
+ body.push(`**${line}**`);
171
+ recognised++;
172
+ continue;
173
+ }
174
+ // The CLI indents the detail rows under each heading — as bullets they
175
+ // survive Telegram's whitespace collapsing, which would otherwise flatten
176
+ // them into the heading above.
177
+ if (/^\s+\S/.test(rawLine)) {
178
+ if (!underSupersededModels)
179
+ body.push(`- ${line}`);
180
+ continue;
181
+ }
182
+ // Framing prose ("You are currently using your subscription…", the
183
+ // "Approximate, based on local sessions…" caveat) — kept, because the
184
+ // caveat is the part that says these numbers miss your other machines.
185
+ body.push(`_${line}_`);
186
+ }
187
+ const lines = ['## 💰 Cost & Usage', ''];
188
+ if (session) {
189
+ lines.push(...renderSessionBlock(session), '');
190
+ }
191
+ if (recognised === 0) {
192
+ // A CLI whose wording we don't know. Show what came back rather than
193
+ // dressing up output we failed to understand — as a sentence when that is
194
+ // all it is (older builds answer `/cost` with a single line), as a block
195
+ // when there is a shape worth preserving.
196
+ lines.push(trimmed.includes('\n') ? `\`\`\`\n${trimmed}\n\`\`\`` : `_${trimmed}_`);
197
+ }
198
+ else {
199
+ lines.push(...body);
200
+ }
201
+ if (sawTotals) {
202
+ // These totals belong to the process that just answered, which has done
203
+ // nothing but answer. Left unqualified, an API-billed account reads its
204
+ // $0.00 as a conversation that cost nothing.
205
+ if (lines[lines.length - 1] !== '')
206
+ lines.push('');
207
+ lines.push('_Totals cover this lookup only — Claude Code keeps no per-conversation cost once a turn ends._');
208
+ }
209
+ if (chatCost && chatCost.turns > 0) {
210
+ if (lines[lines.length - 1] !== '')
211
+ lines.push('');
212
+ const turns = chatCost.turns === 1 ? '1 turn' : `${chatCost.turns} turns`;
213
+ lines.push(`**This chat:** $${chatCost.usd.toFixed(4)} across ${turns} — TeleCoder's own tally, since the CLI keeps none.`);
214
+ }
215
+ return lines.join('\n').trimEnd();
216
+ }
217
+ /**
218
+ * Which CLI to ask, best first.
219
+ *
220
+ * Every candidate is spawned as a fresh process with nothing spent in it, so
221
+ * the substance of the answer does not depend on which one asks. What does
222
+ * depend on it is how much gets printed: the copy bundled with the SDK trails
223
+ * the user's own install by many releases, and older builds reply with a
224
+ * single sentence where current ones break every limit down with its reset
225
+ * time. So ask the install the user maintains — the same `claude` they would
226
+ * type `/cost` into — and keep the bundled binary as the fallback for setups
227
+ * with no CLI on PATH at all.
228
+ */
229
+ function costExecutables() {
230
+ const preferred = process.env.CLAUDE_BIN || config.CLAUDE_EXECUTABLE_PATH;
231
+ const bundled = resolveActiveClaudeExecutable();
232
+ return preferred === bundled ? [preferred] : [preferred, bundled];
233
+ }
234
+ /** A CLI that never started, as opposed to one that ran and failed. */
235
+ function isSpawnFailure(error) {
236
+ const code = error?.code;
237
+ return code === 'ENOENT' || code === 'EACCES';
238
+ }
239
+ async function runClaudeCost(executables, cwd) {
240
+ let lastError;
241
+ for (const executable of executables) {
242
+ try {
243
+ return await runOne(executable, cwd);
244
+ }
245
+ catch (error) {
246
+ // Only a CLI that could not be started is worth retrying elsewhere. One
247
+ // that ran and failed has given its answer, and trying an older copy
248
+ // would just bury the reason.
249
+ if (!isSpawnFailure(error))
250
+ throw error;
251
+ lastError = error;
252
+ }
253
+ }
254
+ throw lastError ?? new Error('No Claude Code CLI found');
255
+ }
256
+ function runOne(executable, cwd) {
257
+ return new Promise((resolve, reject) => {
258
+ // stdin is 'ignore' rather than the pipe `execFile` would hand it: an idle
259
+ // stdin pipe makes the CLI wait three seconds for input that will never
260
+ // arrive, then warn about it on stderr. Closing it up front takes the
261
+ // round trip from ~5.4s to ~2.5s and keeps the warning out of the output.
262
+ const child = spawn(executable, ['-p', '/cost'], {
263
+ cwd,
264
+ stdio: ['ignore', 'pipe', 'pipe'],
265
+ env: process.env,
266
+ });
267
+ let stdout = '';
268
+ let stderr = '';
269
+ let settled = false;
270
+ const finish = (error) => {
271
+ if (settled)
272
+ return;
273
+ settled = true;
274
+ clearTimeout(timer);
275
+ try {
276
+ child.kill('SIGTERM');
277
+ }
278
+ catch { /* already gone */ }
279
+ if (error)
280
+ reject(error);
281
+ else
282
+ resolve((stdout || stderr).trim());
283
+ };
284
+ const timer = setTimeout(() => finish(new Error(`Timed out after ${COST_TIMEOUT_MS / 1000}s`)), COST_TIMEOUT_MS);
285
+ const collect = (into) => (chunk) => {
286
+ const text = chunk.toString('utf-8');
287
+ if (into === 'out')
288
+ stdout += text;
289
+ else
290
+ stderr += text;
291
+ // Standing in for execFile's maxBuffer: take what we have rather than
292
+ // growing without bound if some future build streams into `-p`.
293
+ if (stdout.length + stderr.length > MAX_OUTPUT_BYTES)
294
+ finish(null);
295
+ };
296
+ child.stdout.on('data', collect('out'));
297
+ child.stderr.on('data', collect('err'));
298
+ child.on('error', (error) => finish(error));
299
+ child.on('close', (code) => {
300
+ // A non-zero exit that still printed the report is worth showing; only
301
+ // an exit with nothing to show is an error.
302
+ if (code === 0 || stdout.trim())
303
+ finish(null);
304
+ else
305
+ finish(new Error(stderr.trim() || `claude exited with code ${code}`));
306
+ });
307
+ });
308
+ }
309
+ /**
310
+ * A directory the CLI can actually start in.
311
+ *
312
+ * A spawn whose `cwd` does not exist fails as `ENOENT <executable>` — an error
313
+ * that sends you looking for a binary that was never the problem. Falling back
314
+ * costs nothing here: `/cost` reports account-wide numbers, so the working
315
+ * directory only has to be somewhere the process can stand.
316
+ */
317
+ function resolveSpawnCwd(sessionCwd) {
318
+ for (const candidate of [sessionCwd, getWorkspaceRoot()]) {
319
+ if (candidate && fs.existsSync(candidate))
320
+ return candidate;
321
+ }
322
+ return process.cwd();
323
+ }
324
+ /**
325
+ * Why the live totals aren't in this report, in the chat's own terms.
326
+ *
327
+ * Every one of these means the report still goes out, carrying the limits view
328
+ * it has always carried. But saying nothing was worse than the missing
329
+ * numbers: a blank where a Session block should be looks like the feature is
330
+ * broken, when three of the four causes clear by themselves.
331
+ *
332
+ * `no-session` under SDK mode is the exception, and the only silent one — that
333
+ * transport has no TUI to read and never will, so there is no news in saying
334
+ * so on every `/cost`.
335
+ */
336
+ export function explainMissingTotals(reason, method) {
337
+ switch (reason) {
338
+ case 'turn-active':
339
+ return "This session's totals need the TUI, which is mid-turn — ask again when it finishes.";
340
+ case 'not-ready':
341
+ return "This session's totals need the TUI, which isn't at its prompt — a dialog may be waiting. Ask again in a moment.";
342
+ case 'no-session':
343
+ return method === 'pty'
344
+ ? "This chat has no live session yet, so there are no totals to read — send a message first."
345
+ : null;
346
+ case 'unreadable':
347
+ // The panel is a Claude Code implementation detail and can move between
348
+ // releases. Say that plainly rather than leave a silent gap.
349
+ return "Couldn't read this session's totals — Claude Code may have changed its `/cost` panel.";
350
+ }
351
+ }
352
+ /**
353
+ * The chat's own totals, read off the live TUI's `/cost` panel.
354
+ *
355
+ * PTY-only, and best-effort in every failure it can meet: no live session, a
356
+ * turn holding the keyboard, a panel whose layout has moved on. None is worth
357
+ * failing the command over — but each is worth naming, in the log for us and
358
+ * in the report for whoever is looking at the gap.
359
+ */
360
+ async function readLiveSessionTotals(sessionKey, method) {
361
+ const miss = (reason) => {
362
+ console.warn(`[Cost] no live session totals for ${sessionKey}: ${reason} (method=${method})`);
363
+ return { session: null, note: explainMissingTotals(reason, method) };
364
+ };
365
+ try {
366
+ const result = await getPtyProvider().runOverlayCommand(sessionKey, '/cost');
367
+ if (!result.ok)
368
+ return miss(result.reason);
369
+ const session = scrapeCostSession(result.screen);
370
+ return session ? { session, note: null } : miss('unreadable');
371
+ }
372
+ catch (error) {
373
+ console.warn('[Cost] Could not read the live /cost panel:', sanitizeError(error));
374
+ return { session: null, note: explainMissingTotals('unreadable', method) };
375
+ }
376
+ }
377
+ export async function handleCost(ctx) {
378
+ const keyInfo = getSessionKeyFromCtx(ctx);
379
+ if (!keyInfo)
380
+ return;
381
+ const { chatId, sessionKey } = keyInfo;
382
+ // Deliberately no session guard: limits are account-wide, so the answer is
383
+ // the same — and just as useful — in a chat that has never opened a project.
384
+ const session = sessionManager.getSession(sessionKey);
385
+ const cwd = resolveSpawnCwd(session?.workingDirectory);
386
+ const typing = ctx.replyWithChatAction?.('typing');
387
+ try {
388
+ // Concurrently: the probe is a process launch, the panel is a keystroke
389
+ // into a process already running, and neither waits on the other.
390
+ const [raw, live] = await Promise.all([
391
+ runClaudeCost(costExecutables(), cwd),
392
+ readLiveSessionTotals(sessionKey, getActiveMethod(sessionKey)),
393
+ ]);
394
+ await typing?.catch(() => { });
395
+ let report = parseCostOutput(raw, getSessionCost(sessionKey), live.session);
396
+ if (live.note)
397
+ report += `\n\n_${live.note}_`;
398
+ await messageSender.sendMessage(ctx, report);
399
+ }
400
+ catch (error) {
401
+ console.error('[Cost] Failed to run /cost:', sanitizeError(error));
402
+ const message = error instanceof Error ? error.message : 'Unknown error';
403
+ const hint = /unknown|unrecognized|command/i.test(message)
404
+ ? '\n\nThis Claude Code build may not support `/cost` yet.'
405
+ : '';
406
+ await messageSender.sendMessage(ctx, `❌ Failed to fetch cost: ${message}${hint}`);
407
+ }
408
+ }
409
+ //# sourceMappingURL=cost.js.map
@@ -0,0 +1,197 @@
1
+ /**
2
+ * /transcribe — turning an uploaded voice note or audio file into text, behind
3
+ * the same download-limit and staleness guards as the other upload handlers.
4
+ */
5
+ import { InputFile } from 'grammy';
6
+ import * as fs from 'fs';
7
+ import * as os from 'os';
8
+ import * as path from 'path';
9
+ import { config } from '../../../config.js';
10
+ import { messageSender } from '../../../telegram/message-sender.js';
11
+ import { EntityText } from '../../../telegram/entities.js';
12
+ import { replyFormatted } from '../../../telegram/send.js';
13
+ import { isDuplicate, markProcessed } from '../../../telegram/deduplication.js';
14
+ import { isStaleMessage } from '../../middleware/stale-filter.js';
15
+ import { replyBareAudio, exceedsDownloadLimit, replyTooLargeToFetch } from '../media-fallback.js';
16
+ import { transcribeFile, downloadTelegramAudio } from '../../../audio/transcribe.js';
17
+ import { sanitizeError, sanitizePath } from '../../../utils/sanitize.js';
18
+ import { replyFeatureDisabled } from './shared.js';
19
+ // ── /transcribe command ────────────────────────────────────────────
20
+ /**
21
+ * Send a transcript as text (short) or .txt document (long).
22
+ * Exported so voice.handler.ts can reuse it for the ForceReply path.
23
+ */
24
+ export async function sendTranscriptResult(ctx, transcript) {
25
+ if (transcript.length <= config.TRANSCRIBE_FILE_THRESHOLD_CHARS) {
26
+ await messageSender.sendMessage(ctx, transcript);
27
+ }
28
+ else {
29
+ const tmpPath = path.join(os.tmpdir(), `telecoder_transcript_${Date.now()}.txt`);
30
+ try {
31
+ fs.writeFileSync(tmpPath, transcript, { encoding: 'utf-8', mode: 0o600 });
32
+ const inputFile = new InputFile(fs.readFileSync(tmpPath), 'transcript.txt');
33
+ await ctx.replyWithDocument(inputFile, {
34
+ caption: `🎤 Transcript (${transcript.length} chars)`,
35
+ });
36
+ }
37
+ finally {
38
+ try {
39
+ if (fs.existsSync(tmpPath))
40
+ fs.unlinkSync(tmpPath);
41
+ }
42
+ catch (e) {
43
+ console.warn(`[transcribe] Cleanup failed for ${sanitizePath(tmpPath)}:`, sanitizeError(e));
44
+ }
45
+ }
46
+ }
47
+ }
48
+ /**
49
+ * Download a Telegram file by file_id → transcribe → send result.
50
+ * Shared helper for reply-to and ForceReply paths.
51
+ */
52
+ async function transcribeAndSend(ctx, fileId, mimeHint, fileSizeBytes) {
53
+ if (!config.TRANSCRIBE_ENABLED) {
54
+ await replyFeatureDisabled(ctx, 'Transcribe');
55
+ return;
56
+ }
57
+ const chatId = ctx.chat?.id;
58
+ if (!chatId)
59
+ return;
60
+ // Check before the ack, not after: getFile rejects anything over Telegram's
61
+ // download ceiling, and the bare 400 that comes back reads like a bot fault.
62
+ if (exceedsDownloadLimit(fileSizeBytes)) {
63
+ await replyTooLargeToFetch(ctx, 'Audio file', fileSizeBytes);
64
+ return;
65
+ }
66
+ const ackMsg = await ctx.reply('🎤 Transcribing...');
67
+ let tempFilePath = null;
68
+ try {
69
+ const file = await ctx.api.getFile(fileId);
70
+ if (!file.file_path)
71
+ throw new Error('Telegram did not return file_path.');
72
+ const ext = mimeHint?.includes('ogg') ? '.ogg'
73
+ : mimeHint?.includes('mp3') ? '.mp3'
74
+ : mimeHint?.includes('wav') ? '.wav'
75
+ : mimeHint?.includes('mp4') ? '.m4a'
76
+ : '.oga';
77
+ tempFilePath = path.join(os.tmpdir(), `telecoder_transcribe_${Date.now()}${ext}`);
78
+ await downloadTelegramAudio(config.TELEGRAM_BOT_TOKEN, file.file_path, tempFilePath);
79
+ const buf = fs.readFileSync(tempFilePath);
80
+ if (!buf.length)
81
+ throw new Error('Downloaded empty audio file.');
82
+ const transcript = await transcribeFile(tempFilePath);
83
+ // Remove ack
84
+ try {
85
+ await ctx.api.deleteMessage(chatId, ackMsg.message_id);
86
+ }
87
+ catch (e) {
88
+ console.debug('[Transcribe] Failed to delete ack message:', e instanceof Error ? e.message : e);
89
+ }
90
+ await sendTranscriptResult(ctx, transcript);
91
+ }
92
+ catch (error) {
93
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
94
+ console.error('[Transcribe] Error:', sanitizeError(error));
95
+ try {
96
+ await ctx.api.editMessageText(chatId, ackMsg.message_id, `❌ ${errorMessage}`);
97
+ }
98
+ catch {
99
+ await ctx.reply(`❌ Transcription error: ${errorMessage}`);
100
+ }
101
+ }
102
+ finally {
103
+ if (tempFilePath && fs.existsSync(tempFilePath)) {
104
+ try {
105
+ fs.unlinkSync(tempFilePath);
106
+ }
107
+ catch (e) {
108
+ console.warn(`[Transcribe] Cleanup failed for ${sanitizePath(tempFilePath)}:`, sanitizeError(e));
109
+ }
110
+ }
111
+ }
112
+ }
113
+ export async function handleTranscribe(ctx) {
114
+ if (!config.TRANSCRIBE_ENABLED) {
115
+ await replyFeatureDisabled(ctx, 'Transcribe');
116
+ return;
117
+ }
118
+ // Path A: reply to a voice/audio/audio-document message
119
+ const reply = ctx.message?.reply_to_message;
120
+ if (reply) {
121
+ const voice = reply.voice;
122
+ const audio = reply.audio;
123
+ const doc = reply.document;
124
+ const fileId = voice?.file_id
125
+ || audio?.file_id
126
+ || (doc?.mime_type?.startsWith('audio/') ? doc.file_id : null);
127
+ const mime = voice?.mime_type || audio?.mime_type || doc?.mime_type;
128
+ if (fileId) {
129
+ await transcribeAndSend(ctx, fileId, mime);
130
+ return;
131
+ }
132
+ }
133
+ // Path B: no audio attached — send ForceReply prompt
134
+ await replyFormatted(ctx, new EntityText().add('🎤 ').bold('Transcribe Audio').add('\n\n').italic('Send a voice note or audio file:').build(), {
135
+ reply_markup: {
136
+ force_reply: true,
137
+ input_field_placeholder: 'Send a voice note or audio file',
138
+ selective: true,
139
+ },
140
+ });
141
+ }
142
+ /**
143
+ * Handle audio messages (message:audio) sent as reply to the Transcribe ForceReply.
144
+ */
145
+ export async function handleTranscribeAudio(ctx) {
146
+ const audio = ctx.message?.audio;
147
+ const messageId = ctx.message?.message_id;
148
+ const messageDate = ctx.message?.date;
149
+ if (!audio || !messageId || !messageDate)
150
+ return;
151
+ // Guard before replying to anything. This handler used to return silently on
152
+ // every path, so it never needed these; now that it answers, a restart would
153
+ // otherwise respond to every audio file sent while the bot was down.
154
+ if (isStaleMessage(messageDate)) {
155
+ console.log(`[Transcribe] Ignoring stale audio ${messageId}`);
156
+ return;
157
+ }
158
+ if (isDuplicate(messageId)) {
159
+ console.log(`[Transcribe] Ignoring duplicate audio ${messageId}`);
160
+ return;
161
+ }
162
+ markProcessed(messageId);
163
+ if (!config.TRANSCRIBE_ENABLED) {
164
+ await replyFeatureDisabled(ctx, 'Transcribe');
165
+ return;
166
+ }
167
+ // Transcription is opt-in: the file has to be a reply to the /transcribe
168
+ // ForceReply prompt. A bare audio upload isn't a transcribe request, but it
169
+ // isn't nothing either — tell the user how to ask for one.
170
+ const replyTo = ctx.message?.reply_to_message;
171
+ const replyText = replyTo?.from?.is_bot ? (replyTo.text || '') : '';
172
+ if (!replyText.includes('Transcribe Audio')) {
173
+ await replyBareAudio(ctx, audio.file_size);
174
+ return;
175
+ }
176
+ await transcribeAndSend(ctx, audio.file_id, audio.mime_type, audio.file_size);
177
+ }
178
+ /**
179
+ * Handle document messages with audio MIME sent as reply to the Transcribe ForceReply.
180
+ */
181
+ export async function handleTranscribeDocument(ctx) {
182
+ if (!config.TRANSCRIBE_ENABLED) {
183
+ await replyFeatureDisabled(ctx, 'Transcribe');
184
+ return;
185
+ }
186
+ const replyTo = ctx.message?.reply_to_message;
187
+ if (!replyTo || !replyTo.from?.is_bot)
188
+ return;
189
+ const replyText = replyTo.text || '';
190
+ if (!replyText.includes('Transcribe Audio'))
191
+ return;
192
+ const doc = ctx.message?.document;
193
+ if (!doc || !doc.mime_type?.startsWith('audio/'))
194
+ return;
195
+ await transcribeAndSend(ctx, doc.file_id, doc.mime_type, doc.file_size);
196
+ }
197
+ //# sourceMappingURL=media.js.map