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,40 @@
1
+ /**
2
+ * Claude Code's own slash commands and their aliases, as the installed CLI
3
+ * has them (2.1.326), for telling one from a typo of a bot command.
4
+ *
5
+ * The probe in available-commands.ts reads the list a headless `claude -p`
6
+ * reports, which holds only what works headless: interactive-only commands
7
+ * (`/export`, `/hooks`, `/theme`, `/cd`…) and every alias (`/rc`, `/peers`)
8
+ * are missing from it, and the typo fallback took them for a misspelt bot
9
+ * command (`/export` → "did you mean /effort"). This list fills that gap. A
10
+ * name it lacks still reaches Claude Code, through the fallback's "as typed"
11
+ * button, so a stale list costs a tap, not the command.
12
+ *
13
+ * Refresh it from the binary (`readlink -f "$(command -v claude)"`): the name
14
+ * and aliases of every command object in it, `{type:"local"|"local-jsx"|
15
+ * "prompt", name:"…", description:"…"}`, in either key order.
16
+ */
17
+ export const CLAUDE_CODE_COMMAND_NAMES = new Set([
18
+ 'add-dir', 'advisor', 'agents', 'allowed-tools', 'android', 'app',
19
+ 'artifacts', 'auto-mode-setup', 'autocompact', 'autofix-pr', 'background',
20
+ 'bashes', 'bg', 'branch', 'break-reminder', 'breaks', 'brief', 'btw', 'bug',
21
+ 'cd', 'checkpoint', 'clear', 'cloud-plugins', 'color', 'compact', 'config',
22
+ 'context', 'continue', 'copy', 'cost', 'daemon', 'design-consent',
23
+ 'design-login', 'design-revoke', 'desktop', 'doctor', 'downtime', 'effort',
24
+ 'exit', 'export', 'extra-usage', 'feedback', 'focus', 'fork', 'goal',
25
+ 'heapdump', 'help', 'hooks', 'ide', 'import', 'insights', 'install',
26
+ 'install-github-app', 'install-slack-app', 'ios', 'keybindings',
27
+ 'list-agents', 'login', 'logout', 'loop', 'loops', 'marketplace', 'mcp',
28
+ 'memory', 'mobile', 'model', 'name', 'new', 'output-style', 'peers',
29
+ 'permissions', 'plan', 'plugin', 'plugins', 'powerup', 'privacy-settings',
30
+ 'pro-trial-expired', 'proactive', 'project', 'quit', 'radio',
31
+ 'rate-limit-options', 'rc', 'recap', 'release-notes', 'reload-plugins',
32
+ 'reload-skills', 'remote', 'remote-control', 'remote-env', 'rename', 'reset',
33
+ 'resume', 'review', 'rewind', 'scroll-speed', 'session', 'settings',
34
+ 'setup-bedrock', 'setup-vertex', 'share', 'skill-doctor', 'skills', 'stats',
35
+ 'status', 'statusline', 'stickers', 'stop', 'subtask', 'tasks',
36
+ 'team-onboarding', 'teleport', 'terminal-setup', 'theme', 'tp', 'tui',
37
+ 'undo', 'upgrade', 'usage', 'usage-credits', 'use-case', 'version', 'voice',
38
+ 'web-setup', 'wellbeing', 'workflow-launch-exec', 'workflows',
39
+ ]);
40
+ //# sourceMappingURL=native-commands.js.map
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Pending-branch storage. When a user branches a conversation from Bot A to Bot B,
3
+ * Bot A writes the truncated transcript here keyed by Bot B's id. Bot B picks
4
+ * it up on the next user message and offers accept/decline.
5
+ *
6
+ * File: ~/.telecoder/pending-branches-<targetBotId>.json
7
+ * Structure: { users: { [userId]: PendingBranch } } — keyed by the Telegram
8
+ * user id, not the chatId, because each bot has its own private DM with the
9
+ * user (different chatId per bot). Routing by user id lets a branch from a
10
+ * DM with Bot A land in the DM with Bot B without either side knowing the
11
+ * other's chatId. The target bot's chat resolves when the user actually
12
+ * messages it — wherever they message from, that's where the offer shows up.
13
+ *
14
+ * Cross-bot handoff is via the shared `~/.telecoder/` dir on disk — every
15
+ * worker on this machine can read/write any bot's file. The target worker
16
+ * doesn't get a live notification; it polls on each incoming user message.
17
+ */
18
+ import * as path from 'path';
19
+ import { z } from 'zod';
20
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
21
+ const HISTORY_DIR = getStateDir();
22
+ const pendingBranchSchema = z.object({
23
+ fromBotName: z.string(),
24
+ fromBotId: z.string(),
25
+ /** Source chat the branch was created in — informational, not used for routing. */
26
+ fromChatId: z.number().optional(),
27
+ projectPath: z.string(),
28
+ // The truncated JSONL content, inline. JSONL is small (<1 MB even for very
29
+ // long conversations) so inlining is cheaper than a separate file with its
30
+ // own lifecycle.
31
+ jsonl: z.string(),
32
+ topic: z.string().optional(),
33
+ assistantPreview: z.string().optional(),
34
+ createdAt: z.string(),
35
+ /** Set to true once the target bot has proactively notified the user. The
36
+ * lazy in-message path still works regardless; this flag just prevents
37
+ * the proactive watcher from spamming on every file change / restart. */
38
+ offered: z.boolean().optional(),
39
+ });
40
+ const fileSchema = z.object({
41
+ users: z.record(z.string(), pendingBranchSchema),
42
+ });
43
+ function pathFor(botId) {
44
+ return path.join(HISTORY_DIR, `pending-branches-${botId}.json`);
45
+ }
46
+ function loadFile(botId) {
47
+ return readJsonFile(pathFor(botId), fileSchema, 'PendingBranches') ?? { users: {} };
48
+ }
49
+ // rethrow: callers confirm "Branched." to the user immediately after writing, so
50
+ // a swallowed failure would report a handoff that never landed on disk.
51
+ function saveFile(botId, data) {
52
+ ensureStateDir(HISTORY_DIR, 'PendingBranches');
53
+ writeJsonFile(pathFor(botId), data, 'PendingBranches', { rethrow: true });
54
+ }
55
+ /** Write a pending branch to the target bot's file, replacing any existing one for this user. */
56
+ export function putPendingBranch(targetBotId, userId, branch) {
57
+ const data = loadFile(targetBotId);
58
+ data.users[String(userId)] = branch;
59
+ saveFile(targetBotId, data);
60
+ }
61
+ /** Read the pending branch for this (target bot, user), if any. */
62
+ export function getPendingBranch(targetBotId, userId) {
63
+ const data = loadFile(targetBotId);
64
+ return data.users[String(userId)];
65
+ }
66
+ /** Remove the pending branch for this (target bot, user). No-op if missing. */
67
+ export function removePendingBranch(targetBotId, userId) {
68
+ const data = loadFile(targetBotId);
69
+ if (!(String(userId) in data.users))
70
+ return;
71
+ delete data.users[String(userId)];
72
+ saveFile(targetBotId, data);
73
+ }
74
+ /** Flag a branch as already-offered so the proactive watcher won't re-send it. */
75
+ export function markBranchOffered(targetBotId, userId) {
76
+ const data = loadFile(targetBotId);
77
+ const entry = data.users[String(userId)];
78
+ if (!entry)
79
+ return;
80
+ if (entry.offered)
81
+ return;
82
+ data.users[String(userId)] = { ...entry, offered: true };
83
+ saveFile(targetBotId, data);
84
+ }
85
+ /** Return all pending branches for a bot, keyed by userId (string). */
86
+ export function listPendingBranches(targetBotId) {
87
+ return loadFile(targetBotId).users;
88
+ }
89
+ /** Path that contains pending branches for this bot — useful for file watching. */
90
+ export function pendingBranchesPathFor(targetBotId) {
91
+ return pathFor(targetBotId);
92
+ }
93
+ //# sourceMappingURL=pending-branches.js.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * In-memory store for prompt suggestions awaiting a button tap.
3
+ *
4
+ * When Claude Code surfaces a speculative next-prompt at end-of-turn, the
5
+ * UI layer offers it with a callback like `sgt:<id>` — on a button under the
6
+ * response when it is short, on a card of its own when it is not. Either way
7
+ * the suggestion text itself may exceed Telegram's 64-byte callback_data, so
8
+ * we keep the text here and map it to a short id.
9
+ *
10
+ * Entries expire after TTL_MS so stale buttons from yesterday's conversation
11
+ * can't accidentally resurrect old prompts long after the context has moved
12
+ * on. The store is single-use: a successful consume removes the entry.
13
+ */
14
+ import { randomBytes } from 'crypto';
15
+ const store = new Map();
16
+ const TTL_MS = 30 * 60 * 1000;
17
+ const MAX_ENTRIES = 256;
18
+ function pruneExpired() {
19
+ const cutoff = Date.now() - TTL_MS;
20
+ for (const [id, entry] of store) {
21
+ if (entry.createdAt < cutoff)
22
+ store.delete(id);
23
+ }
24
+ // Hard cap as a safety net — high-traffic chats could otherwise grow the
25
+ // map without bound between TTL sweeps. Drop the oldest first.
26
+ if (store.size > MAX_ENTRIES) {
27
+ const sorted = [...store.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
28
+ const drop = sorted.slice(0, store.size - MAX_ENTRIES);
29
+ for (const [id] of drop)
30
+ store.delete(id);
31
+ }
32
+ }
33
+ export function storeSuggestion(sessionKey, text, presentation = 'button') {
34
+ pruneExpired();
35
+ const id = randomBytes(6).toString('base64url');
36
+ store.set(id, { text, sessionKey, presentation, createdAt: Date.now() });
37
+ return id;
38
+ }
39
+ export function consumeSuggestion(id) {
40
+ const entry = store.get(id);
41
+ if (!entry)
42
+ return null;
43
+ if (Date.now() - entry.createdAt > TTL_MS) {
44
+ store.delete(id);
45
+ return null;
46
+ }
47
+ store.delete(id);
48
+ return { text: entry.text, sessionKey: entry.sessionKey, presentation: entry.presentation };
49
+ }
50
+ //# sourceMappingURL=pending-suggestions.js.map
@@ -0,0 +1,338 @@
1
+ import { config } from '../config.js';
2
+ import { closeExpiredQuestion, createPendingQuestion } from './ask-user.js';
3
+ import { parseSessionKey } from '../utils/session-key.js';
4
+ import { legacyEnv } from '../utils/legacy-env.js';
5
+ import { getPromptResponderIds, hasGuestUsers } from '../utils/admins.js';
6
+ import { checkToolScope, isScopeGuardEnabled } from './scope-guard.js';
7
+ import { sessionManager } from './session-manager.js';
8
+ import { EntityText, clip } from '../telegram/entities.js';
9
+ import { resolveApproversInChat, appendApproverLine } from '../telegram/admin-mention.js';
10
+ import { consumeAutoApproval, formatRemaining } from './auto-approve.js';
11
+ import { sanitizeError } from '../utils/sanitize.js';
12
+ /**
13
+ * Pattern-based permission gate for PreToolUse. When enabled, certain tool calls
14
+ * (destructive bash patterns, force-pushes, DROP TABLE, etc.) trigger a Telegram
15
+ * approval prompt before executing. On approve, the hook returns the allow
16
+ * marker and claude proceeds; on deny or timeout, claude sees a tool-blocked
17
+ * error. The markers are consumed by the shell wrapper in
18
+ * pty-spawn-config.ts, which blocks on anything else too. The hook's handler
19
+ * goes through gateToolCall.
20
+ *
21
+ * A message that starts with `!` is a command too, but not a tool call: Claude
22
+ * Code runs it in shell mode and raises no hook for it. Those come here before
23
+ * they are typed into the pty (shell-mode-gate.ts).
24
+ *
25
+ * Soft by design: hooks can't override --disallowedTools deny rules, and the
26
+ * patterns list is intentionally conservative — false positives are worse here
27
+ * than false negatives because every prompt costs someone a button tap.
28
+ *
29
+ * On a shared bot the prompt is the supervision mechanism, so two things about
30
+ * it matter beyond the patterns. It goes to the admins, plus any approver who
31
+ * is not the person who raised it — a confirmation a *guest* can tap
32
+ * themselves confirms nothing, while an admin approving their own `sudo` is
33
+ * the owner of the machine agreeing with themselves, which is what a solo bot
34
+ * has always done. And it mentions them by id, because the group it lands in
35
+ * is muted and an unnoticed prompt is a denied prompt ten minutes later.
36
+ */
37
+ export const DENY_MARKER_START = '__TELECODER_DENY__';
38
+ export const DENY_MARKER_END = '__END__';
39
+ /**
40
+ * The whole reply body that lets a tool run. The hook fails closed: anything
41
+ * but exactly this — an empty reply while the bot restarts, a 500, a curl
42
+ * timeout — blocks the tool, so every path that means "allowed" says so.
43
+ */
44
+ export const ALLOW_MARKER = '__TELECODER_ALLOW__';
45
+ export function promptTimeoutMs() {
46
+ const minutes = config.PERMISSION_PROMPT_TIMEOUT_MINUTES;
47
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : 10) * 60 * 1000;
48
+ }
49
+ /**
50
+ * How long the PreToolUse hook's curl waits for the bot, in seconds: the
51
+ * prompt timeout plus room to post the prompt and close it. Under that, curl
52
+ * gives up on a prompt still open and the tool is blocked before anyone could
53
+ * answer it.
54
+ */
55
+ export function hookCurlTimeoutSeconds() {
56
+ return Math.ceil(promptTimeoutMs() / 1000) + 120;
57
+ }
58
+ /**
59
+ * The `timeout` the PreToolUse hook is registered with, in seconds. Past
60
+ * curl's own, so claude never kills the hook while curl still waits on the
61
+ * bot: claude's default (600s) is exactly the default prompt timeout, and a
62
+ * hook killed by claude is a race the user doesn't see.
63
+ */
64
+ export function hookTimeoutSeconds() {
65
+ return hookCurlTimeoutSeconds() + 30;
66
+ }
67
+ /** Longest command text we paste into the prompt before clipping. */
68
+ const MAX_COMMAND_CHARS = 400;
69
+ // Patterns that always prompt regardless of tool. Conservative — only the
70
+ // obviously destructive cases. Bash with sudo is included because it's almost
71
+ // always interactive on a desktop and shouldn't silently run on a server.
72
+ const DANGEROUS_BASH_PATTERNS = [
73
+ { re: /\brm\s+(-[a-z]*r[a-z]*f|-[a-z]*f[a-z]*r)\b/i, reason: 'rm -rf' },
74
+ { re: /\bsudo\b/i, reason: 'sudo' },
75
+ { re: /\bgit\s+push\s+(--force\b|-f\b)/i, reason: 'git push --force' },
76
+ { re: /\bgit\s+reset\s+--hard\b/i, reason: 'git reset --hard' },
77
+ { re: /\bgit\s+clean\s+-[a-z]*f/i, reason: 'git clean -f' },
78
+ { re: /\bgit\s+branch\s+-D\b/i, reason: 'git branch -D (force delete)' },
79
+ { re: /\bDROP\s+TABLE\b/i, reason: 'DROP TABLE' },
80
+ { re: /\bDROP\s+DATABASE\b/i, reason: 'DROP DATABASE' },
81
+ { re: /\bTRUNCATE\s+TABLE\b/i, reason: 'TRUNCATE TABLE' },
82
+ { re: /\bterraform\s+destroy\b/i, reason: 'terraform destroy' },
83
+ { re: /\bmkfs\b|\bdd\s+.*\bof=\/dev\//i, reason: 'destructive disk op' },
84
+ ];
85
+ /**
86
+ * On when TELECODER_PERMISSION_PROMPTS is "1", off when it is "0", and — with
87
+ * the var unset — on exactly when the bot has non-admin users.
88
+ *
89
+ * Sharing a bot with someone you intend to supervise and getting no prompts
90
+ * because a separate variable was never set is the wrong failure. Set it to "0"
91
+ * to share a bot without the gate; a solo bot has no guests, so its default is
92
+ * unchanged.
93
+ */
94
+ export function isPermissionGateEnabled() {
95
+ const explicit = legacyEnv('PERMISSION_PROMPTS');
96
+ if (explicit !== undefined && explicit !== '')
97
+ return explicit === '1';
98
+ return hasGuestUsers();
99
+ }
100
+ /** True when the gate is on because of guests rather than an explicit opt-in. */
101
+ export function isPermissionGateImplicit() {
102
+ const explicit = legacyEnv('PERMISSION_PROMPTS');
103
+ return (explicit === undefined || explicit === '') && hasGuestUsers();
104
+ }
105
+ /**
106
+ * Inspect a tool call and decide whether it needs approval. If yes, prompts via
107
+ * Telegram and waits for an admin's button tap, up to
108
+ * PERMISSION_PROMPT_TIMEOUT_MINUTES. Returns the final decision.
109
+ *
110
+ * Tools that don't match any pattern auto-allow immediately — most of claude's
111
+ * activity should pass through without anyone noticing.
112
+ */
113
+ export async function evaluateToolCall(req) {
114
+ if (!isPermissionGateEnabled()) {
115
+ return { block: false, reason: '' };
116
+ }
117
+ const pattern = matchDangerousPattern(req.toolName, req.toolInput) ?? matchOutOfScope(req);
118
+ if (!pattern)
119
+ return { block: false, reason: '' };
120
+ const ctx = req.telegramCtx;
121
+ if (!ctx?.chat?.id) {
122
+ // No ctx available — fail safe by blocking (so the gate's existence
123
+ // actually means something when it's enabled).
124
+ return {
125
+ block: true,
126
+ reason: `TeleCoder permission gate active but no Telegram context available to prompt user. Denied: ${pattern.reason}`,
127
+ };
128
+ }
129
+ const { chatId, threadId } = parseSessionKey(req.sessionKey);
130
+ // An open auto-approve window answers the prompt instead of posting it. The
131
+ // line it posts in its place is the point: the window buys back the button
132
+ // tap, not the record of what was allowed.
133
+ const window = consumeAutoApproval(chatId, pattern.reason);
134
+ if (window) {
135
+ await announceAutoApproval(ctx, chatId, threadId, pattern.reason, req.toolInput, window);
136
+ return { block: false, reason: '' };
137
+ }
138
+ // Admins, plus any approver who is not the person whose turn raised this.
139
+ // Restrict the buttons to the *configured* roster, not the subset that
140
+ // resolved to a display name. A prompt nobody can answer is safer than one
141
+ // the requester can answer, and the timeout still ends it either way.
142
+ const responderIds = getPromptResponderIds(ctx.from?.id);
143
+ const responders = await resolveApproversInChat(ctx.api, chatId, responderIds);
144
+ const optionLabels = ['✅ Allow once', '❌ Deny'];
145
+ const timeoutMs = promptTimeoutMs();
146
+ const { id, promise } = createPendingQuestion(optionLabels, timeoutMs, req.sessionKey, responderIds);
147
+ const keyboard = optionLabels.map((label, idx) => [{
148
+ text: label,
149
+ callback_data: `q:${id}:${idx}`,
150
+ }]);
151
+ const { text, entities } = buildPromptMessage({
152
+ reason: pattern.reason,
153
+ toolName: req.toolLabel ?? req.toolName,
154
+ toolInput: req.toolInput,
155
+ requester: describeRequester(ctx),
156
+ responders,
157
+ timeoutMinutes: Math.round(timeoutMs / 60000),
158
+ });
159
+ const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
160
+ // Kept for closing the prompt if nobody answers it, with whichever entities
161
+ // it actually went out with.
162
+ let sent;
163
+ let sentEntities = entities;
164
+ try {
165
+ sent = await ctx.api.sendMessage(chatId, text, {
166
+ entities,
167
+ reply_markup: { inline_keyboard: keyboard },
168
+ ...threadOpts,
169
+ });
170
+ }
171
+ catch (err) {
172
+ // The text itself can't be malformed — it is sent verbatim with no parse
173
+ // mode. What can fail is a text_mention for someone Telegram won't let us
174
+ // name here, so retry once with the formatting dropped rather than losing
175
+ // the prompt entirely.
176
+ console.error('[PermissionGate] entity send failed, retrying plain:', err instanceof Error ? err.message : err);
177
+ try {
178
+ sent = await ctx.api.sendMessage(chatId, text, {
179
+ reply_markup: { inline_keyboard: keyboard },
180
+ ...threadOpts,
181
+ });
182
+ sentEntities = undefined;
183
+ }
184
+ catch (err2) {
185
+ console.error('[PermissionGate] failed to send prompt:', err2 instanceof Error ? err2.message : err2);
186
+ return { block: true, reason: `Failed to send approval prompt to user. Denied: ${pattern.reason}` };
187
+ }
188
+ }
189
+ const answer = await promise;
190
+ if (answer === null) {
191
+ await closeExpiredQuestion(ctx.api, sent, text, `No answer within ${Math.round(timeoutMs / 60000)} min, so it was denied.`, sentEntities);
192
+ }
193
+ if (!answer || answer.index === 1) {
194
+ return {
195
+ block: true,
196
+ reason: answer === null
197
+ ? `Nobody approved within ${Math.round(timeoutMs / 60000)} minutes. Denied: ${pattern.reason}`
198
+ : `An approver denied: ${pattern.reason}`,
199
+ };
200
+ }
201
+ return { block: false, reason: '', approvedByPerson: true };
202
+ }
203
+ /**
204
+ * The gate as the PreToolUse hook's IPC handler calls it.
205
+ *
206
+ * Fails closed. A gate that let a call through because it broke while judging
207
+ * it would be no gate on exactly the calls it exists for.
208
+ */
209
+ export async function gateToolCall(req) {
210
+ try {
211
+ if (!isPermissionGateEnabled())
212
+ return { block: false, reason: '' };
213
+ return await evaluateToolCall(req);
214
+ }
215
+ catch (err) {
216
+ console.error('[PermissionGate] evaluation failed, denying:', sanitizeError(err));
217
+ return {
218
+ block: true,
219
+ reason: 'TeleCoder permission gate could not evaluate this call, so it was denied.',
220
+ };
221
+ }
222
+ }
223
+ /**
224
+ * How long a hook should give the gate before giving up on it: the prompt's
225
+ * own timeout plus slack, so the gate's denial is what ends an unanswered
226
+ * prompt rather than the hook runner — which would let the call through.
227
+ */
228
+ export function gateHookTimeoutSeconds() {
229
+ return Math.ceil(promptTimeoutMs() / 1000) + 120;
230
+ }
231
+ /**
232
+ * Post the line that stands in for the prompt a window just answered.
233
+ *
234
+ * Best-effort: an auto-approval that could not be announced is still an
235
+ * auto-approval, and failing the tool call because Telegram was unreachable
236
+ * would be a worse outcome than a gap in the chat log. The console keeps it
237
+ * either way.
238
+ */
239
+ async function announceAutoApproval(ctx, chatId, threadId, reason, toolInput, window) {
240
+ console.log(`[PermissionGate] auto-approved chat:${chatId} reason:${reason} `
241
+ + `(#${window.approved} of window opened by ${window.openedBy})`);
242
+ const b = new EntityText();
243
+ b.add('\u26a1 ').bold('Auto-approved').add(` \u2014 ${reason}`).newline();
244
+ const command = commandOf(toolInput);
245
+ if (command !== undefined) {
246
+ b.pre(clip(command, MAX_COMMAND_CHARS), 'bash');
247
+ }
248
+ else {
249
+ b.pre(clip(JSON.stringify(toolInput), MAX_COMMAND_CHARS), 'json');
250
+ }
251
+ b.italic(`#${window.approved} in ${window.openedByName}'s window \u2014 ${formatRemaining(window)} left. `
252
+ + '/autoapprove off ends it.');
253
+ const { text, entities } = b.build();
254
+ const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
255
+ try {
256
+ await ctx.api.sendMessage(chatId, text, { entities, ...threadOpts });
257
+ }
258
+ catch (err) {
259
+ console.error('[PermissionGate] auto-approval notice failed:', err instanceof Error ? err.message : err);
260
+ }
261
+ }
262
+ /** How the prompt refers to whoever's turn triggered it. */
263
+ function describeRequester(ctx) {
264
+ const from = ctx.from;
265
+ if (!from)
266
+ return undefined;
267
+ const name = [from.first_name, from.last_name].filter(Boolean).join(' ') || from.username;
268
+ return name || undefined;
269
+ }
270
+ /**
271
+ * Lay out the approval prompt. Exported for tests — the wording and the
272
+ * offsets are the whole product here, and both are worth pinning down.
273
+ */
274
+ export function buildPromptMessage(parts) {
275
+ const b = new EntityText();
276
+ b.add('🔐 ').bold('Permission requested').add(` — ${parts.reason}`).newline();
277
+ if (parts.requester) {
278
+ b.add('Asked by ').bold(parts.requester).newline();
279
+ }
280
+ b.add('Tool: ').code(parts.toolName).newline(2);
281
+ const command = commandOf(parts.toolInput);
282
+ if (command !== undefined) {
283
+ const description = typeof parts.toolInput.description === 'string' ? parts.toolInput.description.trim() : '';
284
+ if (description)
285
+ b.italic(clip(description, 200)).newline();
286
+ b.pre(clip(command, MAX_COMMAND_CHARS), 'bash');
287
+ }
288
+ else {
289
+ b.pre(clip(JSON.stringify(parts.toolInput), MAX_COMMAND_CHARS), 'json');
290
+ }
291
+ b.newline();
292
+ appendApproverLine(b, parts.responders);
293
+ b.newline().italic(`Times out in ${parts.timeoutMinutes} min → denied.`);
294
+ return b.build();
295
+ }
296
+ /** The command string for tools that run one, or undefined for everything else. */
297
+ function commandOf(toolInput) {
298
+ const command = toolInput.command;
299
+ return typeof command === 'string' ? command : undefined;
300
+ }
301
+ /**
302
+ * Second class of guarded call: one that reaches outside the shared projects.
303
+ *
304
+ * Runs after the destructive-pattern check so a `sudo` inside the workspace
305
+ * still reports as `sudo` rather than as a scope excursion — the more specific
306
+ * reason is the more useful one to show.
307
+ */
308
+ function matchOutOfScope(req) {
309
+ // The gate is already known to be on — evaluateToolCall returns before this
310
+ // when it isn't — so 'auto' resolves to on unless SCOPE_GUARD says otherwise.
311
+ if (!isScopeGuardEnabled(true))
312
+ return null;
313
+ const cwd = sessionManager.getSession(req.sessionKey)?.workingDirectory;
314
+ if (!cwd)
315
+ return null;
316
+ const verdict = checkToolScope(req.toolName, req.toolInput, cwd);
317
+ if (!verdict.outOfScope)
318
+ return null;
319
+ return { reason: `${verdict.reason} — ${verdict.offender}` };
320
+ }
321
+ function matchDangerousPattern(toolName, toolInput) {
322
+ if (toolName === 'Bash') {
323
+ const cmd = String(toolInput.command ?? '');
324
+ for (const p of DANGEROUS_BASH_PATTERNS) {
325
+ if (p.re.test(cmd))
326
+ return { reason: p.reason };
327
+ }
328
+ }
329
+ return null;
330
+ }
331
+ /** List the dangerous patterns surfaced via /gate. */
332
+ export function listDangerousPatterns() {
333
+ return DANGEROUS_BASH_PATTERNS.map((p) => ({
334
+ reason: p.reason,
335
+ example: p.re.toString(),
336
+ }));
337
+ }
338
+ //# sourceMappingURL=permission-gate.js.map
@@ -0,0 +1,152 @@
1
+ /**
2
+ * The permission mode a chat runs claude in.
3
+ *
4
+ * Claude Code's modes differ in how much it asks before acting, and this bot
5
+ * used to have no say in it: the pty spawned with
6
+ * `--dangerously-skip-permissions`, so every chat on every project ran in
7
+ * bypass.
8
+ *
9
+ * The five modes below are claude's own, described in its own words from the
10
+ * shift+tab lesson text. Only the first four are offered as choices a person
11
+ * cycles through; bypass is here because it is what the pty has always
12
+ * launched in, and a chat that leaves it needs a way back.
13
+ *
14
+ * `cli` is the word `--permission-mode` takes for a mode. Anything handed to
15
+ * the pty goes through it, never through the id.
16
+ */
17
+ import { tailLines } from './tui-state.js';
18
+ export const PERMISSION_MODES = [
19
+ {
20
+ id: 'manual',
21
+ label: 'Manual',
22
+ description: 'ask before every edit',
23
+ tuiPhrase: 'manual mode',
24
+ },
25
+ {
26
+ id: 'acceptEdits',
27
+ label: 'Accept edits',
28
+ description: 'edit freely, ask for commands',
29
+ tuiPhrase: 'accept edits',
30
+ },
31
+ {
32
+ id: 'plan',
33
+ label: 'Plan',
34
+ description: 'research and propose, never touch files',
35
+ tuiPhrase: 'plan mode',
36
+ },
37
+ {
38
+ id: 'auto',
39
+ label: 'Auto',
40
+ description: 'Claude decides what is safe',
41
+ tuiPhrase: 'auto mode',
42
+ },
43
+ {
44
+ id: 'bypassPermissions',
45
+ label: 'Bypass',
46
+ description: 'never ask — what the pty ran in before auto',
47
+ tuiPhrase: 'bypass permissions',
48
+ },
49
+ ];
50
+ export function permissionModeInfo(id) {
51
+ const info = PERMISSION_MODES.find((m) => m.id === id);
52
+ if (!info)
53
+ throw new Error(`unknown permission mode: ${id}`);
54
+ return info;
55
+ }
56
+ export function isPermissionModeId(value) {
57
+ return PERMISSION_MODES.some((m) => m.id === value);
58
+ }
59
+ /**
60
+ * The mode a chat runs in until it picks one with /mode: `auto`, which is also
61
+ * what claude itself launches in when nobody passes a flag. The pty ran
62
+ * bypassed for as long as it had no way to answer a permission prompt; now
63
+ * that dialogs reach the chat mid-turn, the mode that never asks is a choice
64
+ * rather than the only thing that worked. `/mode bypass` is one tap away for a
65
+ * chat that wants it back. /mode prints this through permissionModeInfo, so
66
+ * the menu cannot describe a mode a turn would not run in.
67
+ */
68
+ export function defaultPermissionMode() {
69
+ return 'auto';
70
+ }
71
+ /**
72
+ * Resolve what someone typed into a mode id, so `/mode plan` works alongside
73
+ * the buttons. Accepts the id and the label. `manual` and `default` both land
74
+ * on manual: the TUI calls the mode manual, and Claude Code's settings and
75
+ * flags have called it default.
76
+ */
77
+ export function parsePermissionModeArg(arg) {
78
+ const norm = arg.trim().toLowerCase().replace(/[\s_-]+/g, '');
79
+ if (norm === 'default')
80
+ return 'manual';
81
+ if (norm === 'bypass' || norm === 'yolo')
82
+ return 'bypassPermissions';
83
+ const hit = PERMISSION_MODES.find((m) => norm === m.id.toLowerCase()
84
+ || norm === m.label.toLowerCase().replace(/[\s_-]+/g, ''));
85
+ return hit?.id ?? null;
86
+ }
87
+ /** Rows from the bottom holding the mode indicator, which sits under the input box. */
88
+ const INDICATOR_ROWS = 6;
89
+ /**
90
+ * Which mode the TUI says it is in, or null when the screen doesn't say.
91
+ *
92
+ * Null is a real answer and the caller must respect it. The indicator is
93
+ * absent while a dialog covers the input box and while the screen is still
94
+ * being painted, and pressing shift+tab at a screen we cannot read is how a
95
+ * blind cycle walks the session into a mode nobody asked for.
96
+ */
97
+ export function parsePermissionMode(screenText) {
98
+ const tail = tailLines(screenText, INDICATOR_ROWS).join('\n').toLowerCase();
99
+ for (const mode of PERMISSION_MODES) {
100
+ // `<phrase> on` — the suffix differs per mode (`(shift+tab to cycle)` for
101
+ // most, `· ? for shortcuts` for manual), so only the phrase is matched.
102
+ if (tail.includes(`${mode.tuiPhrase} on`))
103
+ return mode.id;
104
+ }
105
+ return null;
106
+ }
107
+ /** Shift+Tab, as xterm encodes it: CSI Z, "back tab". */
108
+ const SHIFT_TAB = '\x1b[Z';
109
+ /** Settle time after a press, before re-reading the indicator. */
110
+ const PRESS_SETTLE_MS = 400;
111
+ /**
112
+ * How many presses to spend looking for the target.
113
+ *
114
+ * The cycle is not a fixed list: a pty launched with
115
+ * `--dangerously-skip-permissions` has five stops (bypass, auto, manual,
116
+ * accept edits, plan) and one launched without it has four, so the distance
117
+ * to any mode depends on how the session started. Measured against a live
118
+ * pty, four presses reach every mode from every starting point; the spare
119
+ * covers a release that adds one.
120
+ */
121
+ const MAX_PRESSES = 6;
122
+ function delay(ms) {
123
+ return new Promise((resolve) => setTimeout(resolve, ms));
124
+ }
125
+ /**
126
+ * Put the session in `target`, by pressing shift+tab until it says so.
127
+ *
128
+ * Reading the indicator after every press is what makes this safe to do on a
129
+ * live session. The cycle's order and length both depend on how the pty was
130
+ * launched, so counting presses would land somewhere plausible and wrong —
131
+ * and "wrong" here means claude acting with more freedom than the chat asked
132
+ * for. Every outcome other than `already` and `switched` means the mode was
133
+ * not established, and the caller is expected to refuse the turn rather than
134
+ * run it in whatever mode the session happens to be in.
135
+ */
136
+ export async function ensurePermissionMode(pty, target, settleMs = PRESS_SETTLE_MS) {
137
+ const from = parsePermissionMode(pty.screen());
138
+ if (from === null)
139
+ return { kind: 'unreadable' };
140
+ if (from === target)
141
+ return { kind: 'already', mode: from };
142
+ let last = from;
143
+ for (let i = 0; i < MAX_PRESSES; i++) {
144
+ pty.write(SHIFT_TAB);
145
+ await delay(settleMs);
146
+ last = parsePermissionMode(pty.screen());
147
+ if (last === target)
148
+ return { kind: 'switched', from, to: target };
149
+ }
150
+ return { kind: 'stuck', from, last };
151
+ }
152
+ //# sourceMappingURL=permission-mode.js.map