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,117 @@
1
+ /**
2
+ * Recognising "Claude Code isn't logged in", and saying so in the chat.
3
+ *
4
+ * On a machine where nobody has signed in, the CLI answers every prompt with
5
+ * `Not logged in · Please run /login`, which relayed as it is tells the person
6
+ * on their phone to run a command they can't. A fresh install doesn't even
7
+ * get that far: the interactive CLI opens its first-run onboarding (theme
8
+ * picker, then "Select login method"), which is no place to relay to a chat —
9
+ * signing in wants a browser on, or a terminal at, the bot's machine.
10
+ *
11
+ * Kept free of config imports so tests can call it directly.
12
+ */
13
+ import * as fs from 'fs';
14
+ import * as os from 'os';
15
+ import * as path from 'path';
16
+ export const CLAUDE_NOT_LOGGED_IN_REPLY = "Claude Code on the bot's machine isn't logged in. On that machine run `claude` and /login " +
17
+ '(or `claude setup-token` for a long-lived token), then try again.';
18
+ /**
19
+ * Error text that means the CLI has no usable credentials. Matched only
20
+ * against errors, never against a reply — a reply that discusses API keys is
21
+ * not a failed login.
22
+ */
23
+ const AUTH_ERROR_PATTERNS = [
24
+ /\bNot logged in\b/i,
25
+ /Please run \/login/i,
26
+ /Invalid API key/i,
27
+ /invalid x-api-key/i,
28
+ /authentication_error/i,
29
+ /authentication_failed/i,
30
+ /OAuth token (?:has expired|has been revoked|is invalid)/i,
31
+ /Invalid bearer token/i,
32
+ /API Error:\s*401\b/i,
33
+ ];
34
+ export function isClaudeAuthError(text) {
35
+ if (!text)
36
+ return false;
37
+ if (text.includes(CLAUDE_NOT_LOGGED_IN_REPLY))
38
+ return true;
39
+ return AUTH_ERROR_PATTERNS.some((re) => re.test(text));
40
+ }
41
+ export const CLAUDE_ONBOARDING_REPLY = "Claude Code on the bot's machine hasn't been set up yet: it is waiting at its first-run screens. " +
42
+ 'On that machine run `claude` once, finish the setup (and /login if it asks), then try again.';
43
+ /**
44
+ * What the interactive CLI is showing, when it is something only a person at
45
+ * the bot's machine can get past: the login-method menu, the sign-in link and
46
+ * the in-session "Not logged in" notice are 'login'; the first-run theme
47
+ * picker is 'onboarding' — it comes before the login question, and may also
48
+ * show for a token-only setup that has never run `claude` interactively.
49
+ * Measured on 2.1.280 with an empty HOME.
50
+ */
51
+ export function claudeSetupScreen(screenText) {
52
+ if (/Select login method/i.test(screenText)
53
+ || /Paste code here if prompted/i.test(screenText)
54
+ || /Not logged in · Please run \/login/i.test(screenText)) {
55
+ return 'login';
56
+ }
57
+ if (/Choose the text style that looks best with your terminal/i.test(screenText))
58
+ return 'onboarding';
59
+ return undefined;
60
+ }
61
+ /** Thrown when a turn can't run because the CLI isn't signed in or set up. */
62
+ export class ClaudeNotLoggedInError extends Error {
63
+ constructor(kind = 'login') {
64
+ super(kind === 'login' ? CLAUDE_NOT_LOGGED_IN_REPLY : CLAUDE_ONBOARDING_REPLY);
65
+ this.name = 'ClaudeNotLoggedInError';
66
+ }
67
+ }
68
+ /**
69
+ * The chat reply for a turn that failed with `error`: the login message for
70
+ * any auth failure, otherwise the usual `❌ Error: …`.
71
+ */
72
+ export function turnErrorReply(error) {
73
+ const message = error instanceof Error ? error.message : 'Unknown error';
74
+ if (error instanceof ClaudeNotLoggedInError)
75
+ return `🔑 ${message}`;
76
+ if (isClaudeAuthError(message))
77
+ return `🔑 ${CLAUDE_NOT_LOGGED_IN_REPLY}`;
78
+ return `❌ Error: ${message}`;
79
+ }
80
+ /**
81
+ * Whether Claude Code looks signed in, judged without starting it or spending
82
+ * a token. 'unknown' where the answer can't be read from the filesystem: macOS
83
+ * keeps the login in the keychain, not in a file.
84
+ *
85
+ * Only ever a warning. A false "no" here costs a log line; refusing to start
86
+ * on it would lock out a setup this can't see (a keychain, a helper script).
87
+ */
88
+ export function claudeCredentialsLookPresent(probe) {
89
+ const { env } = probe;
90
+ const set = (key) => !!env[key]?.trim();
91
+ if (set('ANTHROPIC_API_KEY') || set('CLAUDE_CODE_OAUTH_TOKEN') || set('ANTHROPIC_AUTH_TOKEN')
92
+ || set('CLAUDE_CODE_USE_BEDROCK') || set('CLAUDE_CODE_USE_VERTEX') || set('CLAUDE_CODE_USE_FOUNDRY')) {
93
+ return 'yes';
94
+ }
95
+ const configDir = env.CLAUDE_CONFIG_DIR?.trim() || path.join(probe.home, '.claude');
96
+ if (probe.exists(path.join(configDir, '.credentials.json')))
97
+ return 'yes';
98
+ if (probe.platform === 'darwin')
99
+ return 'unknown';
100
+ return 'no';
101
+ }
102
+ /** Log a warning at startup if Claude Code doesn't look signed in. */
103
+ export function warnIfClaudeNotLoggedIn() {
104
+ const verdict = claudeCredentialsLookPresent({
105
+ env: process.env,
106
+ home: os.homedir(),
107
+ platform: process.platform,
108
+ exists: (file) => fs.existsSync(file),
109
+ });
110
+ if (verdict !== 'no')
111
+ return;
112
+ console.warn('⚠️ Claude Code doesn\'t look logged in on this machine: there is no ~/.claude/.credentials.json, ' +
113
+ 'and none of ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN is set. Until it is, every message will ' +
114
+ 'fail. Run `claude` and /login (or `claude setup-token` and put the token in CLAUDE_CODE_OAUTH_TOKEN). ' +
115
+ 'Starting anyway, in case the login lives somewhere this check can\'t see.');
116
+ }
117
+ //# sourceMappingURL=claude-auth.js.map
@@ -0,0 +1,206 @@
1
+ import { config } from '../config.js';
2
+ import { hasGuestUsers } from '../utils/admins.js';
3
+ import { isCheckout } from '../utils/install-mode.js';
4
+ import { EntityText } from '../telegram/entities.js';
5
+ const CLAUDE_COMMANDS = ['model', 'commands', 'resume'];
6
+ export function parseClaudeCommand(message) {
7
+ const trimmed = message.trim();
8
+ // Check if message starts with a slash command
9
+ if (!trimmed.startsWith('/')) {
10
+ return { command: null, args: trimmed, model: null };
11
+ }
12
+ const firstSpace = trimmed.indexOf(' ');
13
+ const commandPart = firstSpace === -1 ? trimmed.slice(1) : trimmed.slice(1, firstSpace);
14
+ const args = firstSpace === -1 ? '' : trimmed.slice(firstSpace + 1).trim();
15
+ // Check if it's a Claude command
16
+ if (CLAUDE_COMMANDS.includes(commandPart)) {
17
+ return { command: commandPart, args, model: null };
18
+ }
19
+ // Not a recognized Claude command - return as regular message
20
+ return { command: null, args: trimmed, model: null };
21
+ }
22
+ export function isClaudeCommand(message) {
23
+ const trimmed = message.trim();
24
+ if (!trimmed.startsWith('/'))
25
+ return false;
26
+ const firstSpace = trimmed.indexOf(' ');
27
+ const commandPart = firstSpace === -1 ? trimmed.slice(1) : trimmed.slice(1, firstSpace);
28
+ return CLAUDE_COMMANDS.includes(commandPart);
29
+ }
30
+ /**
31
+ * Telegram appends `@BotName` to slash commands sent in group chats
32
+ * (`/compact@MyBot`, `/compact@MyBot keep the plan`). Strip the mention off the
33
+ * leading command token so downstream command detection — and the PTY TUI,
34
+ * which would otherwise type `/compact@MyBot` verbatim — see a clean `/compact`.
35
+ * Only touches a genuine `/word@word` command token; leaves ordinary messages
36
+ * (and slash-prefixed paths like `/some/path@host`) untouched.
37
+ */
38
+ export function stripCommandBotMention(text) {
39
+ const m = text.match(/^\/(\w+)@\w+(\s[\s\S]*)?$/);
40
+ return m ? '/' + m[1] + (m[2] ?? '') : text;
41
+ }
42
+ /**
43
+ * True if `text` is the native Claude Code `/compact` slash command (optionally
44
+ * with a `@BotName` mention or trailing custom-instructions argument).
45
+ */
46
+ export function isNativeCompactCommand(text) {
47
+ return /^\/compact(?:@\w+)?(?:\s|$)/.test(text.trim());
48
+ }
49
+ /**
50
+ * The /commands list. Each line is written with `backticks` around what shows
51
+ * as code; section titles go out bold.
52
+ */
53
+ export function getAvailableCommands() {
54
+ // Only worth saying on a bot that actually has guests — on a solo bot every
55
+ // user is an admin, so the tag would mark every line without narrowing
56
+ // anything.
57
+ const adminTag = hasGuestUsers() ? ' (admin)' : '';
58
+ // Opening an auto-approve window sits with the people who answer prompts,
59
+ // which is a wider set than the people who own the bot.
60
+ const approverTag = hasGuestUsers() ? ' (admin / approver)' : '';
61
+ const sections = [
62
+ {
63
+ title: 'Claude Commands',
64
+ commands: [
65
+ '• `/model [name]` - Show or set AI model',
66
+ "• `/later [text]` - Set an idea aside, and be asked about it after Claude's turn",
67
+ '• `/steer <text>` - Stop the running turn and send this in its place',
68
+ '• `/ctrlb` - Move the shell command or subagent Claude is waiting on to the background, as Ctrl+B does in Claude Code',
69
+ ...(config.CCR_ENABLED ? [`• \`/ccr\` - Switch between Claude and CCR${adminTag}`] : []),
70
+ '• `/commands` - Show this list',
71
+ ],
72
+ },
73
+ {
74
+ title: 'Session Commands',
75
+ commands: [
76
+ '• `/dir <path>` - Set working directory',
77
+ '• `/newbot [project]` - Create a bot for a project, named after it and starting in it',
78
+ '• `/resume` - Pick from recent sessions to resume',
79
+ '• `/terminal` - Continue this session in a terminal, as a branch',
80
+ '• `/clear` - Clear session and start fresh',
81
+ '• `/info` - Show current session info',
82
+ '• `/branch` - Branch this conversation into a new thread or another bot',
83
+ '• `/spinoff <task>` - Split a task off into a new thread, compacted around it (as a reply: from that message)',
84
+ '• `/threaddelete` - Delete this thread and its messages, and end its session',
85
+ '• `/tree` - Show where this conversation branched, and jump between branches',
86
+ '• `/branchaccept` - Accept a pending branch from another bot',
87
+ '• `/branchdecline` - Discard a pending branch',
88
+ ],
89
+ },
90
+ {
91
+ title: 'File Commands',
92
+ commands: [
93
+ '• `/file <path>` - Download a file from project',
94
+ ],
95
+ },
96
+ ];
97
+ sections.push({
98
+ title: 'Bot Commands',
99
+ commands: [
100
+ '• `/context` - What fills the context window, as Claude Code reports it',
101
+ '• `/usage` - Show usage limits and cost from Claude Code (alias: `/cost`)',
102
+ '• `/compact` - Compact the context window (reports the token reduction)',
103
+ '• `/rewind` - Go back to an earlier prompt: restore the conversation, the code, or both',
104
+ '• `/cc <command>` - Run Claude Code\'s own command of that name, where the bot has one too (`/cc model`)',
105
+ '• `/botstatus` - Show bot process status; answers mid-turn too',
106
+ '• `/botversion` - Show the running version and whether it\'s the latest',
107
+ `• \`/botrestart\` - Restart the bot process${adminTag}`,
108
+ ...(isCheckout()
109
+ ? [`• \`/botrebuild\` - Rebuild and restart with auto-resume; \`/botrebuild idle\` waits for each bot to finish first${adminTag}`]
110
+ : []),
111
+ '• `/cancel` - Stop the current request and drop anything queued',
112
+ '• `/mode` - How much Claude asks before acting',
113
+ `• \`/autoapprove [30m|off|status]\` - Let the gate approve instead of asking, for a while${approverTag}`,
114
+ '• `/verbosity` - Pick verbosity tier (quiet / normal / verbose / debug)',
115
+ '• `/botname <name>` - Rename the bot (admins)',
116
+ '• `/topic <text>` - Set current work topic in bot name',
117
+ ],
118
+ });
119
+ sections.push({
120
+ title: 'Claude Code Commands',
121
+ commands: [
122
+ 'Claude Code\'s own slash commands pass straight through — `/code-review`,',
123
+ '`/security-review`, `/simplify`, `/init`, `/run` and any `.claude/commands/`',
124
+ 'command all work by typing them here.',
125
+ '',
126
+ '⚠️ Where a bot command shares the name, the bot answers in its own way —',
127
+ '`/model` and `/usage` are TeleCoder\'s pickers and summaries, not Claude',
128
+ 'Code\'s dialogs. `/cc` reaches the one underneath: `/cc model`, `/cc usage`.',
129
+ 'The overlap shifts with each Claude Code release, so `/projectcommands`',
130
+ 'reports the current one.',
131
+ '',
132
+ '• `/projectcommands` - List everything this project offers, shadowing included',
133
+ ],
134
+ });
135
+ sections.push({
136
+ title: 'Group Access',
137
+ commands: [
138
+ '• `/members` - Show who may prompt the agent in this group',
139
+ '• `/allow` - Let someone prompt the agent here (reply to them, or pass @handle / id)',
140
+ '• `/deny` - Make someone a spectator here (admin only)',
141
+ ],
142
+ });
143
+ const b = new EntityText();
144
+ sections.forEach((section, i) => {
145
+ if (i > 0)
146
+ b.newline(2);
147
+ b.bold(`${section.title}:`).newline(2);
148
+ section.commands.forEach((line, j) => {
149
+ if (j > 0)
150
+ b.newline();
151
+ // Odd segments between backticks are code.
152
+ line.split('`').forEach((segment, k) => (k % 2 === 1 ? b.code(segment) : b.add(segment)));
153
+ });
154
+ });
155
+ return b.build();
156
+ }
157
+ /**
158
+ * Command names TeleCoder registers with grammY that do NOT reach Claude Code,
159
+ * recorded as they register (see the `cmd()` wrapper in `bot.ts`).
160
+ *
161
+ * A bot command wins over the native Claude Code command of the same name:
162
+ * grammY matches it first and the text never reaches the agent. The bot takes
163
+ * a Claude Code name only for a command that does the same thing its own way:
164
+ * `/model` answers about the bot's state rather than the CLI's, and `/usage`
165
+ * is a summary rather than the dialog. Keeping the list live rather than hand-maintained means
166
+ * `/projectcommands` names the shadowed commands accurately — the overlap
167
+ * shifts with every Claude Code release.
168
+ *
169
+ * `forwardsToAgent` marks the exception: a name registered only so grammY
170
+ * routes it (and its group-chat `@BotName` form) into the normal message
171
+ * pipeline, which hands it to Claude Code unchanged. `/compact` is one. Those
172
+ * are not shadowed and must not be reported as such.
173
+ */
174
+ const registeredBotCommands = new Set();
175
+ const forwardedBotCommands = new Set();
176
+ export function registerBotCommandName(name, forwardsToAgent = false) {
177
+ if (forwardsToAgent) {
178
+ registeredBotCommands.delete(name);
179
+ forwardedBotCommands.add(name);
180
+ return;
181
+ }
182
+ registeredBotCommands.add(name);
183
+ }
184
+ /**
185
+ * What `/cc <command>` types at Claude Code: `/cc model` is `/model`, and
186
+ * `/cc usage` is `/usage`, arguments and all. Null when no command was named.
187
+ *
188
+ * It is the way to a Claude Code command that a bot command of the same name
189
+ * stands in front of. grammY matches the bot's `/model` before the text can
190
+ * reach the agent, so the name alone can never get there; under `/cc` it is
191
+ * an argument, and goes through as typed. The slash is optional, since
192
+ * `/cc /model` is what half of people will write.
193
+ */
194
+ export function nativeCommandIn(text) {
195
+ const match = /^\/cc(?:@\w+)?\s+\/?([\w:-]+)(\s[\s\S]*)?$/.exec(text.trim());
196
+ return match ? `/${match[1]}${match[2] ?? ''}`.trimEnd() : null;
197
+ }
198
+ /** Names registered only to route into the agent, `/compact` among them. */
199
+ export function getForwardedCommandNames() {
200
+ return forwardedBotCommands;
201
+ }
202
+ /** Names that shadow a same-named Claude Code command. */
203
+ export function getBotCommandNames() {
204
+ return registeredBotCommands;
205
+ }
206
+ //# sourceMappingURL=command-parser.js.map
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Scrape the Session totals out of Claude Code's `/cost` overlay.
3
+ *
4
+ * `/cost` in the TUI is not a transcript message — it opens the settings panel
5
+ * on its Usage tab, behind the same full-width `▔` rule the `/tasks` overlay
6
+ * uses:
7
+ *
8
+ * ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
9
+ * Settings Status Config Usage Stats
10
+ *
11
+ * Session
12
+ *
13
+ * Total cost: $0.0246
14
+ * Total duration (API): 3s
15
+ * Total duration (wall): 8s
16
+ * Total code changes: 0 lines added, 0 lines removed
17
+ * Usage by model:
18
+ * claude-haiku-4-5: 1.8k input, 63 output, 26.3k cache read …
19
+ * Prompt cache (main): 1 request · 73% of input tokens from cache …
20
+ *
21
+ * Current session
22
+ * █████████ 18% used
23
+ * …
24
+ *
25
+ * Only the Session block is taken. Everything below it is the account-wide
26
+ * limits view, which `claude -p /cost` prints too — more compactly, and from
27
+ * any mode — so /cost reads that from the probe and comes here only for the
28
+ * part a probe can never have: the totals belong to the process that spent
29
+ * them, and a freshly spawned one has spent nothing.
30
+ *
31
+ * The panel scrolls, so only its first screenful is rendered. That is where
32
+ * the Session block lives, which is why this scrapes it and leaves the rest.
33
+ */
34
+ /**
35
+ * The overlay's top rule. Full-width in practice; 10 is a safe floor. `▔` up
36
+ * to claude 2.1.226; from 2.1.311 the same `─` as the input box, which is
37
+ * why the `Session` heading has to follow within HEADING_SEARCH_LINES — the
38
+ * lowest rule on a screen with no panel open is the input box's lower edge.
39
+ */
40
+ const OVERLAY_RULE_RE = /^(?:▔{10,}|─{10,})$/;
41
+ /** The block's heading, on its own line. */
42
+ const SESSION_HEADING_RE = /^Session$/;
43
+ /**
44
+ * `Total cost: $0.0246`, and the per-model rows, which have the same shape.
45
+ * The label is deliberately narrow — letters, digits and the few punctuation
46
+ * marks real labels use — so that a wrapped continuation line ("35m, next turn
47
+ * re-caches ~426.3k tokens") can't be mistaken for the start of a new field.
48
+ */
49
+ const FIELD_RE = /^([A-Za-z][\w .()/-]*?):\s*(.*)$/;
50
+ /**
51
+ * Where the Session block ends and the account-wide limits view begins. The
52
+ * panel always renders one of these next, so this doubles as the block's
53
+ * terminator when the screen is tall enough to show more.
54
+ */
55
+ const BLOCK_END_RE = /^(?:Current session|Current week|What's contributing)/i;
56
+ /**
57
+ * How far below the rule the `Session` heading may sit. The real layout puts
58
+ * it on the fourth line (rule, tab bar, blank, heading); the allowance is for
59
+ * a release that adds a line, not for finding the word somewhere in
60
+ * scrollback. Without a ceiling, a stale overlay left in the buffer could pass
61
+ * off last hour's numbers as this moment's.
62
+ */
63
+ const HEADING_SEARCH_LINES = 8;
64
+ /** Leading spaces on a line; 0 for a blank one. */
65
+ function indentOf(line) {
66
+ return line.trim() === '' ? 0 : line.length - line.trimStart().length;
67
+ }
68
+ /**
69
+ * The Session block of the `/cost` overlay, or null when the screen doesn't
70
+ * hold one — no overlay, a different tab, or a layout we no longer recognise.
71
+ * Callers show the limits view alone rather than guessing at the numbers.
72
+ */
73
+ export function scrapeCostSession(screenText) {
74
+ const lines = screenText.split('\n');
75
+ // Bottom-up: the panel is pinned to the bottom of the screen, and an earlier
76
+ // rule can survive in scrollback from a previous overlay.
77
+ let ruleIndex = -1;
78
+ for (let i = lines.length - 1; i >= 0; i--) {
79
+ if (OVERLAY_RULE_RE.test(lines[i].trim())) {
80
+ ruleIndex = i;
81
+ break;
82
+ }
83
+ }
84
+ if (ruleIndex === -1)
85
+ return null;
86
+ const limit = Math.min(lines.length, ruleIndex + 1 + HEADING_SEARCH_LINES);
87
+ let headingIndex = -1;
88
+ for (let i = ruleIndex + 1; i < limit; i++) {
89
+ if (SESSION_HEADING_RE.test(lines[i].trim())) {
90
+ headingIndex = i;
91
+ break;
92
+ }
93
+ }
94
+ if (headingIndex === -1)
95
+ return null;
96
+ const body = [];
97
+ for (let i = headingIndex + 1; i < lines.length; i++) {
98
+ if (BLOCK_END_RE.test(lines[i].trim()))
99
+ break;
100
+ body.push(lines[i]);
101
+ }
102
+ // The heading sets the block's baseline indent; the per-model rows sit four
103
+ // columns further in. Two is the smallest gap that can't be indent jitter.
104
+ const baseline = indentOf(lines[headingIndex]);
105
+ const nestedFrom = baseline + 2;
106
+ const rows = [];
107
+ for (const line of body) {
108
+ const text = line.trim();
109
+ if (!text)
110
+ continue;
111
+ const field = text.match(FIELD_RE);
112
+ if (field) {
113
+ rows.push({
114
+ label: field[1],
115
+ value: field[2].trim(),
116
+ nested: indentOf(line) >= nestedFrom,
117
+ });
118
+ continue;
119
+ }
120
+ // No label, so this is the tail of a value the panel wrapped. Rejoin it —
121
+ // the prompt-cache line is long enough to wrap on most terminals, and
122
+ // dropping the remainder would truncate it mid-sentence.
123
+ const previous = rows[rows.length - 1];
124
+ if (previous)
125
+ previous.value = `${previous.value} ${text}`.trim();
126
+ }
127
+ // A panel showing no dollar or duration total isn't the Usage tab, whatever
128
+ // else matched. Better to fall back to the limits view than to relay rows
129
+ // scraped out of something else.
130
+ if (!rows.some((row) => /^Total /.test(row.label)))
131
+ return null;
132
+ return { rows };
133
+ }
134
+ //# sourceMappingURL=cost-overlay-scraper.js.map
@@ -0,0 +1,5 @@
1
+ const VALID_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
2
+ export function isValidEffortLevel(level) {
3
+ return VALID_EFFORT_LEVELS.includes(level);
4
+ }
5
+ //# sourceMappingURL=effort-level.js.map
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Which marketplace plugins the bot enables on top of the settings claude reads.
3
+ *
4
+ * Claude Code keeps plugin enablement in settings.json under `enabledPlugins`.
5
+ * A plugin enabled in the terminal sits in the user's copy of that file, which
6
+ * the pty reads along with the rest of the user setup — unless that setup
7
+ * stays out, as it does on a bot with guests (loadsUserSetup in
8
+ * pty-spawn-config.ts). Then a plugin enabled in the terminal is simply absent
9
+ * in Telegram, and absent silently: a missing skill looks like a model that
10
+ * ignored it.
11
+ *
12
+ * CLAUDE_PLUGINS names the ones to bring across in that case, or to enable for
13
+ * the bot alone. It goes in at the *flag* tier, `--settings`, which sits above
14
+ * the other tiers in Claude Code's precedence order and merges with them
15
+ * key-by-key, so a project that enables its own plugins keeps them and picks
16
+ * these up as well.
17
+ */
18
+ import { config } from '../config.js';
19
+ /**
20
+ * `plugin@marketplace`, the id `claude plugin list` prints. The bare plugin
21
+ * name is the natural guess and never matches anything — Claude Code looks the
22
+ * entry up by the full id and finds nothing, which is indistinguishable from
23
+ * the plugin not being installed. Rejecting it here at least says so.
24
+ */
25
+ const PLUGIN_ID = /^[^@\s]+@[^@\s]+$/;
26
+ /** Bad ids already reported, so a respawn loop doesn't repeat itself. */
27
+ const warned = new Set();
28
+ /**
29
+ * The `enabledPlugins` settings fragment for this install, or undefined when
30
+ * nothing is configured — callers spread it conditionally so the key stays out
31
+ * of the settings payload entirely rather than appearing as `{}`.
32
+ */
33
+ export function enabledPluginsSetting() {
34
+ const enabled = {};
35
+ for (const id of config.CLAUDE_PLUGINS) {
36
+ if (!PLUGIN_ID.test(id)) {
37
+ if (!warned.has(id)) {
38
+ warned.add(id);
39
+ console.warn(`[plugins] ignoring CLAUDE_PLUGINS entry "${id}": expected plugin@marketplace, ` +
40
+ 'e.g. frontend-design@claude-plugins-official. Run `claude plugin list` for the ids.');
41
+ }
42
+ continue;
43
+ }
44
+ enabled[id] = true;
45
+ }
46
+ return Object.keys(enabled).length > 0 ? enabled : undefined;
47
+ }
48
+ /** Reset the warn-once state. Test seam — production never needs this. */
49
+ export function resetPluginWarnings() {
50
+ warned.clear();
51
+ }
52
+ //# sourceMappingURL=enabled-plugins.js.map
@@ -0,0 +1,82 @@
1
+ import * as path from 'path';
2
+ import { z } from 'zod';
3
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
4
+ import { BOT_ID } from '../config.js';
5
+ /**
6
+ * Tracks Claude tasks that are currently running per-session, persisted to disk.
7
+ * On a clean finish the marker is cleared. If the bot exits unexpectedly while
8
+ * a task is in flight, the marker survives and startup can notify the chat
9
+ * that the task was interrupted.
10
+ */
11
+ const inFlightEntrySchema = z.object({
12
+ sessionKey: z.string(),
13
+ messagePreview: z.string(),
14
+ startedAt: z.string(),
15
+ });
16
+ const inFlightFileSchema = z.object({
17
+ entries: z.array(inFlightEntrySchema),
18
+ });
19
+ const HISTORY_DIR = getStateDir();
20
+ function getFile() {
21
+ return path.join(HISTORY_DIR, `in-flight-${BOT_ID}.json`);
22
+ }
23
+ function readAll() {
24
+ return readJsonFile(getFile(), inFlightFileSchema, 'InFlight')?.entries ?? [];
25
+ }
26
+ function writeAll(entries) {
27
+ ensureStateDir(HISTORY_DIR, 'InFlight');
28
+ writeJsonFile(getFile(), { entries }, 'InFlight');
29
+ }
30
+ // Cap stored prompt at 50KB so a long interrupted prompt survives the restart
31
+ // notification flow intact. The restore renderer chunks if it exceeds the
32
+ // 4096-char per-Telegram-message limit.
33
+ const MAX_PROMPT_CHARS = 50_000;
34
+ export function markInFlight(sessionKey, messagePreview) {
35
+ const others = readAll().filter((e) => e.sessionKey !== sessionKey);
36
+ others.push({
37
+ sessionKey,
38
+ messagePreview: messagePreview.slice(0, MAX_PROMPT_CHARS),
39
+ startedAt: new Date().toISOString(),
40
+ });
41
+ writeAll(others);
42
+ }
43
+ /** Whether a turn is running for this session right now. */
44
+ export function isInFlight(sessionKey) {
45
+ return readAll().some((e) => e.sessionKey === sessionKey);
46
+ }
47
+ export function clearInFlight(sessionKey) {
48
+ const all = readAll();
49
+ const filtered = all.filter((e) => e.sessionKey !== sessionKey);
50
+ if (filtered.length !== all.length)
51
+ writeAll(filtered);
52
+ const after = afterTurn.get(sessionKey);
53
+ if (after) {
54
+ afterTurn.delete(sessionKey);
55
+ try {
56
+ after();
57
+ }
58
+ catch (err) {
59
+ console.warn(`[InFlight] After-turn action for ${sessionKey} failed:`, err instanceof Error ? err.message : err);
60
+ }
61
+ }
62
+ }
63
+ /** One action per session, run when its running turn ends. In memory only. */
64
+ const afterTurn = new Map();
65
+ /**
66
+ * Run `action` once the turn now running in this session ends, before the
67
+ * next queued message starts: for a setting change that needs a fresh claude
68
+ * but shouldn't cut a turn short. A later call for the same session replaces
69
+ * the earlier one, which only ever restarts the same pty.
70
+ */
71
+ export function runAfterTurn(sessionKey, action) {
72
+ afterTurn.set(sessionKey, action);
73
+ }
74
+ /** Read all entries and clear the file. Used at startup to surface tasks that
75
+ * were interrupted by an unexpected exit. */
76
+ export function consumeAllInFlight() {
77
+ const all = readAll();
78
+ if (all.length > 0)
79
+ writeAll([]);
80
+ return all;
81
+ }
82
+ //# sourceMappingURL=in-flight-tracker.js.map