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,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,337 @@
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 PTY transport's hook returns the markers (consumed by the shell
18
+ * wrapper in pty-spawn-config.ts, which blocks on anything else too); the SDK
19
+ * transport's (sdk-permission-gate.ts) a deny decision. Both go through
20
+ * gateToolCall.
21
+ *
22
+ * Soft by design: hooks can't override --disallowedTools deny rules, and the
23
+ * patterns list is intentionally conservative — false positives are worse here
24
+ * than false negatives because every prompt costs someone a button tap.
25
+ *
26
+ * On a shared bot the prompt is the supervision mechanism, so two things about
27
+ * it matter beyond the patterns. It goes to the admins, plus any approver who
28
+ * is not the person who raised it — a confirmation a *guest* can tap
29
+ * themselves confirms nothing, while an admin approving their own `sudo` is
30
+ * the owner of the machine agreeing with themselves, which is what a solo bot
31
+ * has always done. And it mentions them by id, because the group it lands in
32
+ * is muted and an unnoticed prompt is a denied prompt ten minutes later.
33
+ */
34
+ export const DENY_MARKER_START = '__TELECODER_DENY__';
35
+ export const DENY_MARKER_END = '__END__';
36
+ /**
37
+ * The whole reply body that lets a tool run. The hook fails closed: anything
38
+ * but exactly this — an empty reply while the bot restarts, a 500, a curl
39
+ * timeout — blocks the tool, so every path that means "allowed" says so.
40
+ */
41
+ export const ALLOW_MARKER = '__TELECODER_ALLOW__';
42
+ export function promptTimeoutMs() {
43
+ const minutes = config.PERMISSION_PROMPT_TIMEOUT_MINUTES;
44
+ return (Number.isFinite(minutes) && minutes > 0 ? minutes : 10) * 60 * 1000;
45
+ }
46
+ /**
47
+ * How long the PreToolUse hook's curl waits for the bot, in seconds: the
48
+ * prompt timeout plus room to post the prompt and close it. Under that, curl
49
+ * gives up on a prompt still open and the tool is blocked before anyone could
50
+ * answer it.
51
+ */
52
+ export function hookCurlTimeoutSeconds() {
53
+ return Math.ceil(promptTimeoutMs() / 1000) + 120;
54
+ }
55
+ /**
56
+ * The `timeout` the PreToolUse hook is registered with, in seconds. Past
57
+ * curl's own, so claude never kills the hook while curl still waits on the
58
+ * bot: claude's default (600s) is exactly the default prompt timeout, and a
59
+ * hook killed by claude is a race the user doesn't see.
60
+ */
61
+ export function hookTimeoutSeconds() {
62
+ return hookCurlTimeoutSeconds() + 30;
63
+ }
64
+ /** Longest command text we paste into the prompt before clipping. */
65
+ const MAX_COMMAND_CHARS = 400;
66
+ // Patterns that always prompt regardless of tool. Conservative — only the
67
+ // obviously destructive cases. Bash with sudo is included because it's almost
68
+ // always interactive on a desktop and shouldn't silently run on a server.
69
+ const DANGEROUS_BASH_PATTERNS = [
70
+ { re: /\brm\s+(-[a-z]*r[a-z]*f|-[a-z]*f[a-z]*r)\b/i, reason: 'rm -rf' },
71
+ { re: /\bsudo\b/i, reason: 'sudo' },
72
+ { re: /\bgit\s+push\s+(--force\b|-f\b)/i, reason: 'git push --force' },
73
+ { re: /\bgit\s+reset\s+--hard\b/i, reason: 'git reset --hard' },
74
+ { re: /\bgit\s+clean\s+-[a-z]*f/i, reason: 'git clean -f' },
75
+ { re: /\bgit\s+branch\s+-D\b/i, reason: 'git branch -D (force delete)' },
76
+ { re: /\bDROP\s+TABLE\b/i, reason: 'DROP TABLE' },
77
+ { re: /\bDROP\s+DATABASE\b/i, reason: 'DROP DATABASE' },
78
+ { re: /\bTRUNCATE\s+TABLE\b/i, reason: 'TRUNCATE TABLE' },
79
+ { re: /\bterraform\s+destroy\b/i, reason: 'terraform destroy' },
80
+ { re: /\bmkfs\b|\bdd\s+.*\bof=\/dev\//i, reason: 'destructive disk op' },
81
+ ];
82
+ /**
83
+ * On when TELECODER_PERMISSION_PROMPTS is "1", off when it is "0", and — with
84
+ * the var unset — on exactly when the bot has non-admin users.
85
+ *
86
+ * Sharing a bot with someone you intend to supervise and getting no prompts
87
+ * because a separate variable was never set is the wrong failure. Set it to "0"
88
+ * to share a bot without the gate; a solo bot has no guests, so its default is
89
+ * unchanged.
90
+ */
91
+ export function isPermissionGateEnabled() {
92
+ const explicit = legacyEnv('PERMISSION_PROMPTS');
93
+ if (explicit !== undefined && explicit !== '')
94
+ return explicit === '1';
95
+ return hasGuestUsers();
96
+ }
97
+ /** True when the gate is on because of guests rather than an explicit opt-in. */
98
+ export function isPermissionGateImplicit() {
99
+ const explicit = legacyEnv('PERMISSION_PROMPTS');
100
+ return (explicit === undefined || explicit === '') && hasGuestUsers();
101
+ }
102
+ /**
103
+ * Inspect a tool call and decide whether it needs approval. If yes, prompts via
104
+ * Telegram and waits for an admin's button tap, up to
105
+ * PERMISSION_PROMPT_TIMEOUT_MINUTES. Returns the final decision.
106
+ *
107
+ * Tools that don't match any pattern auto-allow immediately — most of claude's
108
+ * activity should pass through without anyone noticing.
109
+ */
110
+ export async function evaluateToolCall(req) {
111
+ if (!isPermissionGateEnabled()) {
112
+ return { block: false, reason: '' };
113
+ }
114
+ const pattern = matchDangerousPattern(req.toolName, req.toolInput) ?? matchOutOfScope(req);
115
+ if (!pattern)
116
+ return { block: false, reason: '' };
117
+ const ctx = req.telegramCtx;
118
+ if (!ctx?.chat?.id) {
119
+ // No ctx available — fail safe by blocking (so the gate's existence
120
+ // actually means something when it's enabled).
121
+ return {
122
+ block: true,
123
+ reason: `TeleCoder permission gate active but no Telegram context available to prompt user. Denied: ${pattern.reason}`,
124
+ };
125
+ }
126
+ const { chatId, threadId } = parseSessionKey(req.sessionKey);
127
+ // An open auto-approve window answers the prompt instead of posting it. The
128
+ // line it posts in its place is the point: the window buys back the button
129
+ // tap, not the record of what was allowed.
130
+ const window = consumeAutoApproval(chatId, pattern.reason);
131
+ if (window) {
132
+ await announceAutoApproval(ctx, chatId, threadId, pattern.reason, req.toolInput, window);
133
+ return { block: false, reason: '' };
134
+ }
135
+ // Admins, plus any approver who is not the person whose turn raised this.
136
+ // Restrict the buttons to the *configured* roster, not the subset that
137
+ // resolved to a display name. A prompt nobody can answer is safer than one
138
+ // the requester can answer, and the timeout still ends it either way.
139
+ const responderIds = getPromptResponderIds(ctx.from?.id);
140
+ const responders = await resolveApproversInChat(ctx.api, chatId, responderIds);
141
+ const optionLabels = ['✅ Allow once', '❌ Deny'];
142
+ const timeoutMs = promptTimeoutMs();
143
+ const { id, promise } = createPendingQuestion(optionLabels, timeoutMs, req.sessionKey, responderIds);
144
+ const keyboard = optionLabels.map((label, idx) => [{
145
+ text: label,
146
+ callback_data: `q:${id}:${idx}`,
147
+ }]);
148
+ const { text, entities } = buildPromptMessage({
149
+ reason: pattern.reason,
150
+ toolName: req.toolName,
151
+ toolInput: req.toolInput,
152
+ requester: describeRequester(ctx),
153
+ responders,
154
+ timeoutMinutes: Math.round(timeoutMs / 60000),
155
+ });
156
+ const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
157
+ // Kept for closing the prompt if nobody answers it, with whichever entities
158
+ // it actually went out with.
159
+ let sent;
160
+ let sentEntities = entities;
161
+ try {
162
+ sent = await ctx.api.sendMessage(chatId, text, {
163
+ entities,
164
+ reply_markup: { inline_keyboard: keyboard },
165
+ ...threadOpts,
166
+ });
167
+ }
168
+ catch (err) {
169
+ // The text itself can't be malformed — it is sent verbatim with no parse
170
+ // mode. What can fail is a text_mention for someone Telegram won't let us
171
+ // name here, so retry once with the formatting dropped rather than losing
172
+ // the prompt entirely.
173
+ console.error('[PermissionGate] entity send failed, retrying plain:', err instanceof Error ? err.message : err);
174
+ try {
175
+ sent = await ctx.api.sendMessage(chatId, text, {
176
+ reply_markup: { inline_keyboard: keyboard },
177
+ ...threadOpts,
178
+ });
179
+ sentEntities = undefined;
180
+ }
181
+ catch (err2) {
182
+ console.error('[PermissionGate] failed to send prompt:', err2 instanceof Error ? err2.message : err2);
183
+ return { block: true, reason: `Failed to send approval prompt to user. Denied: ${pattern.reason}` };
184
+ }
185
+ }
186
+ const answer = await promise;
187
+ if (answer === null) {
188
+ await closeExpiredQuestion(ctx.api, sent, text, `No answer within ${Math.round(timeoutMs / 60000)} min, so it was denied.`, sentEntities);
189
+ }
190
+ if (!answer || answer.index === 1) {
191
+ return {
192
+ block: true,
193
+ reason: answer === null
194
+ ? `Nobody approved within ${Math.round(timeoutMs / 60000)} minutes. Denied: ${pattern.reason}`
195
+ : `An approver denied: ${pattern.reason}`,
196
+ };
197
+ }
198
+ return { block: false, reason: '' };
199
+ }
200
+ /**
201
+ * The gate as a transport's PreToolUse hook calls it: the PTY's IPC handler
202
+ * and the SDK's in-process hook both go through here, so the two can't drift
203
+ * apart in what they check or how they fail.
204
+ *
205
+ * Fails closed. A gate that let a call through because it broke while judging
206
+ * it would be no gate on exactly the calls it exists for.
207
+ */
208
+ export async function gateToolCall(req) {
209
+ try {
210
+ if (!isPermissionGateEnabled())
211
+ return { block: false, reason: '' };
212
+ return await evaluateToolCall(req);
213
+ }
214
+ catch (err) {
215
+ console.error('[PermissionGate] evaluation failed, denying:', sanitizeError(err));
216
+ return {
217
+ block: true,
218
+ reason: 'TeleCoder permission gate could not evaluate this call, so it was denied.',
219
+ };
220
+ }
221
+ }
222
+ /**
223
+ * How long a hook should give the gate before giving up on it: the prompt's
224
+ * own timeout plus slack, so the gate's denial is what ends an unanswered
225
+ * prompt rather than the hook runner — which would let the call through.
226
+ */
227
+ export function gateHookTimeoutSeconds() {
228
+ return Math.ceil(promptTimeoutMs() / 1000) + 120;
229
+ }
230
+ /**
231
+ * Post the line that stands in for the prompt a window just answered.
232
+ *
233
+ * Best-effort: an auto-approval that could not be announced is still an
234
+ * auto-approval, and failing the tool call because Telegram was unreachable
235
+ * would be a worse outcome than a gap in the chat log. The console keeps it
236
+ * either way.
237
+ */
238
+ async function announceAutoApproval(ctx, chatId, threadId, reason, toolInput, window) {
239
+ console.log(`[PermissionGate] auto-approved chat:${chatId} reason:${reason} `
240
+ + `(#${window.approved} of window opened by ${window.openedBy})`);
241
+ const b = new EntityText();
242
+ b.add('\u26a1 ').bold('Auto-approved').add(` \u2014 ${reason}`).newline();
243
+ const command = commandOf(toolInput);
244
+ if (command !== undefined) {
245
+ b.pre(clip(command, MAX_COMMAND_CHARS), 'bash');
246
+ }
247
+ else {
248
+ b.pre(clip(JSON.stringify(toolInput), MAX_COMMAND_CHARS), 'json');
249
+ }
250
+ b.italic(`#${window.approved} in ${window.openedByName}'s window \u2014 ${formatRemaining(window)} left. `
251
+ + '/autoapprove off ends it.');
252
+ const { text, entities } = b.build();
253
+ const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
254
+ try {
255
+ await ctx.api.sendMessage(chatId, text, { entities, ...threadOpts });
256
+ }
257
+ catch (err) {
258
+ console.error('[PermissionGate] auto-approval notice failed:', err instanceof Error ? err.message : err);
259
+ }
260
+ }
261
+ /** How the prompt refers to whoever's turn triggered it. */
262
+ function describeRequester(ctx) {
263
+ const from = ctx.from;
264
+ if (!from)
265
+ return undefined;
266
+ const name = [from.first_name, from.last_name].filter(Boolean).join(' ') || from.username;
267
+ return name || undefined;
268
+ }
269
+ /**
270
+ * Lay out the approval prompt. Exported for tests — the wording and the
271
+ * offsets are the whole product here, and both are worth pinning down.
272
+ */
273
+ export function buildPromptMessage(parts) {
274
+ const b = new EntityText();
275
+ b.add('🔐 ').bold('Permission requested').add(` — ${parts.reason}`).newline();
276
+ if (parts.requester) {
277
+ b.add('Asked by ').bold(parts.requester).newline();
278
+ }
279
+ b.add('Tool: ').code(parts.toolName).newline(2);
280
+ const command = commandOf(parts.toolInput);
281
+ if (command !== undefined) {
282
+ const description = typeof parts.toolInput.description === 'string' ? parts.toolInput.description.trim() : '';
283
+ if (description)
284
+ b.italic(clip(description, 200)).newline();
285
+ b.pre(clip(command, MAX_COMMAND_CHARS), 'bash');
286
+ }
287
+ else {
288
+ b.pre(clip(JSON.stringify(parts.toolInput), MAX_COMMAND_CHARS), 'json');
289
+ }
290
+ b.newline();
291
+ appendApproverLine(b, parts.responders);
292
+ b.newline().italic(`Times out in ${parts.timeoutMinutes} min → denied.`);
293
+ return b.build();
294
+ }
295
+ /** The command string for tools that run one, or undefined for everything else. */
296
+ function commandOf(toolInput) {
297
+ const command = toolInput.command;
298
+ return typeof command === 'string' ? command : undefined;
299
+ }
300
+ /**
301
+ * Second class of guarded call: one that reaches outside the shared projects.
302
+ *
303
+ * Runs after the destructive-pattern check so a `sudo` inside the workspace
304
+ * still reports as `sudo` rather than as a scope excursion — the more specific
305
+ * reason is the more useful one to show.
306
+ */
307
+ function matchOutOfScope(req) {
308
+ // The gate is already known to be on — evaluateToolCall returns before this
309
+ // when it isn't — so 'auto' resolves to on unless SCOPE_GUARD says otherwise.
310
+ if (!isScopeGuardEnabled(true))
311
+ return null;
312
+ const cwd = sessionManager.getSession(req.sessionKey)?.workingDirectory;
313
+ if (!cwd)
314
+ return null;
315
+ const verdict = checkToolScope(req.toolName, req.toolInput, cwd);
316
+ if (!verdict.outOfScope)
317
+ return null;
318
+ return { reason: `${verdict.reason} — ${verdict.offender}` };
319
+ }
320
+ function matchDangerousPattern(toolName, toolInput) {
321
+ if (toolName === 'Bash') {
322
+ const cmd = String(toolInput.command ?? '');
323
+ for (const p of DANGEROUS_BASH_PATTERNS) {
324
+ if (p.re.test(cmd))
325
+ return { reason: p.reason };
326
+ }
327
+ }
328
+ return null;
329
+ }
330
+ /** List the dangerous patterns surfaced via /permissions. */
331
+ export function listDangerousPatterns() {
332
+ return DANGEROUS_BASH_PATTERNS.map((p) => ({
333
+ reason: p.reason,
334
+ example: p.re.toString(),
335
+ }));
336
+ }
337
+ //# sourceMappingURL=permission-gate.js.map
@@ -0,0 +1,178 @@
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 until now
5
+ * this bot had no say in it: the SDK transport hard-coded `acceptEdits` and
6
+ * the pty spawned with `--dangerously-skip-permissions`, so every chat on
7
+ * every project ran at whatever those two happened to be. `/plan` was the one
8
+ * escape hatch, and only for a single turn.
9
+ *
10
+ * The five modes below are claude's own, described in its own words from the
11
+ * shift+tab lesson text. Only the first four are offered as choices a person
12
+ * cycles through; bypass is here because it is what the pty has always
13
+ * launched in, and a chat that leaves it needs a way back.
14
+ *
15
+ * Two names for one thing, which is the trap this table exists to close: the
16
+ * CLI flag spells the ask-every-time mode `manual` and the SDK spells it
17
+ * `default`, and each rejects the other's word. Anything crossing into either
18
+ * transport goes through `cli` or `sdk` here, never through the id.
19
+ */
20
+ import { tailLines } from './tui-state.js';
21
+ export const PERMISSION_MODES = [
22
+ {
23
+ id: 'manual',
24
+ label: 'Manual',
25
+ description: 'ask before every edit',
26
+ cli: 'manual',
27
+ sdk: 'default',
28
+ tuiPhrase: 'manual mode',
29
+ },
30
+ {
31
+ id: 'acceptEdits',
32
+ label: 'Accept edits',
33
+ description: 'edit freely, ask for commands',
34
+ cli: 'acceptEdits',
35
+ sdk: 'acceptEdits',
36
+ tuiPhrase: 'accept edits',
37
+ },
38
+ {
39
+ id: 'plan',
40
+ label: 'Plan',
41
+ description: 'research and propose, never touch files',
42
+ cli: 'plan',
43
+ sdk: 'plan',
44
+ tuiPhrase: 'plan mode',
45
+ },
46
+ {
47
+ id: 'auto',
48
+ label: 'Auto',
49
+ description: 'Claude decides what is safe',
50
+ cli: 'auto',
51
+ sdk: 'auto',
52
+ tuiPhrase: 'auto mode',
53
+ },
54
+ {
55
+ id: 'bypassPermissions',
56
+ label: 'Bypass',
57
+ description: 'never ask — what the pty ran in before auto',
58
+ cli: 'bypassPermissions',
59
+ sdk: 'bypassPermissions',
60
+ tuiPhrase: 'bypass permissions',
61
+ },
62
+ ];
63
+ export function permissionModeInfo(id) {
64
+ const info = PERMISSION_MODES.find((m) => m.id === id);
65
+ if (!info)
66
+ throw new Error(`unknown permission mode: ${id}`);
67
+ return info;
68
+ }
69
+ export function isPermissionModeId(value) {
70
+ return PERMISSION_MODES.some((m) => m.id === value);
71
+ }
72
+ /**
73
+ * The mode a chat runs in when it has chosen none.
74
+ *
75
+ * "Default" means "leave it to the transport", and the transports disagree, so
76
+ * this is where the disagreement is written down — beside the table, rather
77
+ * than in either transport, so the answer /mode prints and the answer a turn
78
+ * runs in cannot drift apart.
79
+ *
80
+ * The pty answers `auto`, which is also what claude itself launches in when
81
+ * nobody passes a flag. It ran bypassed for as long as it had no way to answer
82
+ * a permission prompt; now that dialogs reach the chat mid-turn, the mode that
83
+ * never asks is a choice rather than the only thing that worked. `/mode bypass`
84
+ * is still one tap away for a chat that wants it back.
85
+ *
86
+ * DANGEROUS_MODE has no say here, exactly as it never had one on the pty: it
87
+ * predates all of this, describes itself as an SDK-side auto-approve, and a
88
+ * config flag quietly re-loosening a default the transport just tightened is
89
+ * the kind of surprise this whole function exists to prevent.
90
+ */
91
+ export function transportDefaultMode(method, dangerousMode) {
92
+ if (method === 'pty')
93
+ return 'auto';
94
+ return dangerousMode ? 'bypassPermissions' : 'acceptEdits';
95
+ }
96
+ /**
97
+ * Resolve what someone typed into a mode id, so `/mode plan` works alongside
98
+ * the buttons. Accepts the id, the label, and the CLI spelling — `manual` and
99
+ * `default` both land on manual, since which word is right depends on which
100
+ * transport you last read about.
101
+ */
102
+ export function parsePermissionModeArg(arg) {
103
+ const norm = arg.trim().toLowerCase().replace(/[\s_-]+/g, '');
104
+ if (norm === 'default')
105
+ return 'manual';
106
+ if (norm === 'bypass' || norm === 'yolo')
107
+ return 'bypassPermissions';
108
+ const hit = PERMISSION_MODES.find((m) => norm === m.id.toLowerCase()
109
+ || norm === m.label.toLowerCase().replace(/[\s_-]+/g, '')
110
+ || norm === m.cli.toLowerCase());
111
+ return hit?.id ?? null;
112
+ }
113
+ /** Rows from the bottom holding the mode indicator, which sits under the input box. */
114
+ const INDICATOR_ROWS = 6;
115
+ /**
116
+ * Which mode the TUI says it is in, or null when the screen doesn't say.
117
+ *
118
+ * Null is a real answer and the caller must respect it. The indicator is
119
+ * absent while a dialog covers the input box and while the screen is still
120
+ * being painted, and pressing shift+tab at a screen we cannot read is how a
121
+ * blind cycle walks the session into a mode nobody asked for.
122
+ */
123
+ export function parsePermissionMode(screenText) {
124
+ const tail = tailLines(screenText, INDICATOR_ROWS).join('\n').toLowerCase();
125
+ for (const mode of PERMISSION_MODES) {
126
+ // `<phrase> on` — the suffix differs per mode (`(shift+tab to cycle)` for
127
+ // most, `· ? for shortcuts` for manual), so only the phrase is matched.
128
+ if (tail.includes(`${mode.tuiPhrase} on`))
129
+ return mode.id;
130
+ }
131
+ return null;
132
+ }
133
+ /** Shift+Tab, as xterm encodes it: CSI Z, "back tab". */
134
+ const SHIFT_TAB = '\x1b[Z';
135
+ /** Settle time after a press, before re-reading the indicator. */
136
+ const PRESS_SETTLE_MS = 400;
137
+ /**
138
+ * How many presses to spend looking for the target.
139
+ *
140
+ * The cycle is not a fixed list: a pty launched with
141
+ * `--dangerously-skip-permissions` has five stops (bypass, auto, manual,
142
+ * accept edits, plan) and one launched without it has four, so the distance
143
+ * to any mode depends on how the session started. Measured against a live
144
+ * pty, four presses reach every mode from every starting point; the spare
145
+ * covers a release that adds one.
146
+ */
147
+ const MAX_PRESSES = 6;
148
+ function delay(ms) {
149
+ return new Promise((resolve) => setTimeout(resolve, ms));
150
+ }
151
+ /**
152
+ * Put the session in `target`, by pressing shift+tab until it says so.
153
+ *
154
+ * Reading the indicator after every press is what makes this safe to do on a
155
+ * live session. The cycle's order and length both depend on how the pty was
156
+ * launched, so counting presses would land somewhere plausible and wrong —
157
+ * and "wrong" here means claude acting with more freedom than the chat asked
158
+ * for. Every outcome other than `already` and `switched` means the mode was
159
+ * not established, and the caller is expected to refuse the turn rather than
160
+ * run it in whatever mode the session happens to be in.
161
+ */
162
+ export async function ensurePermissionMode(pty, target, settleMs = PRESS_SETTLE_MS) {
163
+ const from = parsePermissionMode(pty.screen());
164
+ if (from === null)
165
+ return { kind: 'unreadable' };
166
+ if (from === target)
167
+ return { kind: 'already', mode: from };
168
+ let last = from;
169
+ for (let i = 0; i < MAX_PRESSES; i++) {
170
+ pty.write(SHIFT_TAB);
171
+ await delay(settleMs);
172
+ last = parsePermissionMode(pty.screen());
173
+ if (last === target)
174
+ return { kind: 'switched', from, to: target };
175
+ }
176
+ return { kind: 'stuck', from, last };
177
+ }
178
+ //# sourceMappingURL=permission-mode.js.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Pending-poll registry for telecoder_poll_user MCP tool.
3
+ *
4
+ * Mirrors ask-user.ts but uses Telegram polls instead of inline keyboards —
5
+ * better for group decisions, vote counts, or multi-select. Telegram polls
6
+ * MUST be non-anonymous for us to receive poll_answer events; anonymous
7
+ * polls only emit aggregate "poll" updates with no per-user trigger.
8
+ *
9
+ * Resolves on the first poll_answer (multi-select captures the snapshot at
10
+ * that moment). Users can change votes afterward but we've already returned.
11
+ */
12
+ import { questionTimeoutMs } from './ask-user.js';
13
+ const pending = new Map();
14
+ function clearPending(pollId) {
15
+ const entry = pending.get(pollId);
16
+ if (!entry)
17
+ return undefined;
18
+ pending.delete(pollId);
19
+ clearTimeout(entry.timer);
20
+ return entry;
21
+ }
22
+ /**
23
+ * Register a pending poll keyed by Telegram's poll_id (returned from
24
+ * bot.api.sendPoll). The poll_id is unique per poll instance and what
25
+ * arrives back on poll_answer updates.
26
+ */
27
+ export function createPendingPoll(pollId, optionLabels, allowsMultiple, sessionKey, timeoutMs = questionTimeoutMs()) {
28
+ return new Promise((resolve) => {
29
+ const timer = setTimeout(() => {
30
+ const entry = clearPending(pollId);
31
+ if (entry)
32
+ entry.resolve(null);
33
+ }, timeoutMs);
34
+ pending.set(pollId, { resolve, timer, optionLabels, allowsMultiple, sessionKey });
35
+ });
36
+ }
37
+ /**
38
+ * Resolve a pending poll with the user's selected option indices.
39
+ * Returns true if a pending entry existed for the poll_id.
40
+ */
41
+ export function resolvePendingPoll(pollId, optionIndices) {
42
+ const entry = clearPending(pollId);
43
+ if (!entry)
44
+ return false;
45
+ const labels = optionIndices
46
+ .map((i) => entry.optionLabels[i])
47
+ .filter((l) => l !== undefined);
48
+ entry.resolve({ labels, indices: optionIndices });
49
+ return true;
50
+ }
51
+ //# sourceMappingURL=poll-user.js.map
@@ -0,0 +1,69 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ const MAX_COMMANDS = 30; // keeps the listing inside one Telegram message
4
+ const DESC_MAX = 80;
5
+ export function getProjectCommands(workingDirectory) {
6
+ const dir = path.join(workingDirectory, '.claude', 'commands');
7
+ if (!fs.existsSync(dir))
8
+ return [];
9
+ let entries;
10
+ try {
11
+ entries = fs.readdirSync(dir);
12
+ }
13
+ catch {
14
+ return [];
15
+ }
16
+ const commands = [];
17
+ for (const entry of entries) {
18
+ if (!entry.endsWith('.md'))
19
+ continue;
20
+ const name = entry.slice(0, -3);
21
+ // Claude Code's own charset for a command name. Hyphens are fine here
22
+ // because this list is only ever rendered as text.
23
+ if (!/^[a-z0-9_-]+$/i.test(name))
24
+ continue;
25
+ let description = '';
26
+ try {
27
+ const content = fs.readFileSync(path.join(dir, entry), 'utf-8');
28
+ description = extractDescription(content);
29
+ }
30
+ catch {
31
+ // unreadable — skip rather than error
32
+ continue;
33
+ }
34
+ commands.push({ name: name.toLowerCase(), description });
35
+ }
36
+ commands.sort((a, b) => a.name.localeCompare(b.name));
37
+ return commands.slice(0, MAX_COMMANDS);
38
+ }
39
+ /**
40
+ * Pull a one-line description from a command markdown file. Prefers a
41
+ * `description:` frontmatter field; falls back to the first non-empty
42
+ * non-heading line of the body.
43
+ */
44
+ function extractDescription(content) {
45
+ // YAML frontmatter: ---\n...description: foo\n...---
46
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
47
+ if (frontmatterMatch) {
48
+ const fm = frontmatterMatch[1];
49
+ const descMatch = fm.match(/^description:\s*(.+)$/m);
50
+ if (descMatch) {
51
+ return truncate(descMatch[1].trim().replace(/^["']|["']$/g, ''));
52
+ }
53
+ }
54
+ // Fallback: first non-empty body line that isn't a heading
55
+ const body = frontmatterMatch ? content.slice(frontmatterMatch[0].length) : content;
56
+ for (const rawLine of body.split('\n')) {
57
+ const line = rawLine.trim();
58
+ if (!line)
59
+ continue;
60
+ if (line.startsWith('#'))
61
+ continue;
62
+ return truncate(line);
63
+ }
64
+ return '';
65
+ }
66
+ function truncate(s) {
67
+ return s.length > DESC_MAX ? s.slice(0, DESC_MAX - 1) + '…' : s;
68
+ }
69
+ //# sourceMappingURL=project-commands.js.map