telecoder 1.2.0 → 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 (197) hide show
  1. package/.env.example +142 -130
  2. package/CHANGELOG.md +683 -2
  3. package/README.md +36 -32
  4. package/dist/audio/transcribe.js +0 -9
  5. package/dist/bin/mcp-server.js +46 -61
  6. package/dist/bot/bot.js +162 -181
  7. package/dist/bot/command-catalog.js +263 -0
  8. package/dist/bot/deleted-threads.js +103 -0
  9. package/dist/bot/file-access.js +35 -26
  10. package/dist/bot/handlers/album.handler.js +128 -0
  11. package/dist/bot/handlers/{fork.handler.js → branch.handler.js} +267 -280
  12. package/dist/bot/handlers/command/access.js +1 -1
  13. package/dist/bot/handlers/command/admin.js +86 -110
  14. package/dist/bot/handlers/command/all-view.js +33 -0
  15. package/dist/bot/handlers/command/auto-approve.js +3 -3
  16. package/dist/bot/handlers/command/background.js +37 -0
  17. package/dist/bot/handlers/command/botname.js +76 -0
  18. package/dist/bot/handlers/command/btw.js +20 -69
  19. package/dist/bot/handlers/command/cleanup.js +329 -0
  20. package/dist/bot/handlers/command/model.js +40 -119
  21. package/dist/bot/handlers/command/prefs-scope.js +255 -90
  22. package/dist/bot/handlers/command/project.js +31 -109
  23. package/dist/bot/handlers/command/resume.js +8 -4
  24. package/dist/bot/handlers/command/session.js +74 -213
  25. package/dist/bot/handlers/command/settings.js +92 -447
  26. package/dist/bot/handlers/command/shared.js +32 -35
  27. package/dist/bot/handlers/command/tasks.js +263 -95
  28. package/dist/bot/handlers/command/thread.js +128 -0
  29. package/dist/bot/handlers/command/topic-store.js +14 -53
  30. package/dist/bot/handlers/command/topic.js +8 -61
  31. package/dist/bot/handlers/command/{cost.js → usage.js} +32 -59
  32. package/dist/bot/handlers/command-fallback.js +179 -0
  33. package/dist/bot/handlers/command.handler.js +96 -422
  34. package/dist/bot/handlers/{schedule.handler.js → loop.handler.js} +159 -73
  35. package/dist/bot/handlers/media-fallback.js +12 -7
  36. package/dist/bot/handlers/message/replies.js +10 -87
  37. package/dist/bot/handlers/message/shared.js +9 -31
  38. package/dist/bot/handlers/message/turn-notify.js +15 -49
  39. package/dist/bot/handlers/message/turn-runner.js +18 -103
  40. package/dist/bot/handlers/message.handler.js +59 -52
  41. package/dist/bot/handlers/newbot.handler.js +13 -4
  42. package/dist/bot/handlers/photo.handler.js +88 -129
  43. package/dist/bot/handlers/prompts.handler.js +11 -11
  44. package/dist/bot/handlers/running-note.js +2 -2
  45. package/dist/bot/handlers/session-guard.js +4 -4
  46. package/dist/bot/handlers/suggestion.handler.js +2 -2
  47. package/dist/bot/handlers/tree.handler.js +20 -20
  48. package/dist/bot/handlers/voice.handler.js +23 -85
  49. package/dist/bot/kept-threads.js +51 -0
  50. package/dist/bot/middleware/album-collector.js +69 -0
  51. package/dist/bot/middleware/auth.middleware.js +1 -1
  52. package/dist/bot/middleware/group-mention.middleware.js +11 -5
  53. package/dist/bot/middleware/queued-messages.js +143 -32
  54. package/dist/bot/middleware/stale-filter.js +0 -22
  55. package/dist/build-info.json +5 -5
  56. package/dist/claude/ask-user-form.js +517 -0
  57. package/dist/claude/ask-user.js +94 -26
  58. package/dist/claude/auto-topic-haiku.js +17 -0
  59. package/dist/claude/available-commands.js +22 -19
  60. package/dist/claude/background-hint.js +91 -0
  61. package/dist/claude/{fork-tree.js → branch-tree.js} +9 -9
  62. package/dist/claude/carry-over.js +0 -2
  63. package/dist/claude/ccr-shim.js +12 -10
  64. package/dist/claude/claude-auth.js +6 -10
  65. package/dist/claude/command-parser.js +49 -43
  66. package/dist/claude/cost-overlay-scraper.js +7 -2
  67. package/dist/claude/effort-level.js +5 -0
  68. package/dist/claude/enabled-plugins.js +12 -16
  69. package/dist/claude/in-flight-tracker.js +21 -0
  70. package/dist/claude/mcp-bridge.js +86 -58
  71. package/dist/claude/memory-guard.js +400 -0
  72. package/dist/claude/message-offsets.js +5 -5
  73. package/dist/claude/modal-relay.js +401 -34
  74. package/dist/claude/model-catalog.js +20 -3
  75. package/dist/claude/monitor-relay.js +130 -15
  76. package/dist/claude/native-commands.js +40 -0
  77. package/dist/claude/{pending-forks.js → pending-branches.js} +26 -26
  78. package/dist/claude/permission-gate.js +11 -10
  79. package/dist/claude/permission-mode.js +19 -45
  80. package/dist/claude/prewarm.js +70 -0
  81. package/dist/claude/pty-idle-reaper.js +96 -0
  82. package/dist/claude/pty-provider.js +473 -188
  83. package/dist/claude/pty-spawn-config.js +79 -32
  84. package/dist/claude/pty-watch.js +201 -0
  85. package/dist/claude/request-queue.js +7 -35
  86. package/dist/claude/rewind.js +111 -0
  87. package/dist/claude/scheduled-runner.js +1 -3
  88. package/dist/claude/scheduler.js +6 -2
  89. package/dist/claude/scope-guard.js +8 -3
  90. package/dist/claude/screen-marks.js +83 -0
  91. package/dist/claude/screen-render.js +96 -0
  92. package/dist/claude/session-history.js +4 -2
  93. package/dist/claude/session-jsonl.js +162 -15
  94. package/dist/claude/session-manager.js +29 -8
  95. package/dist/claude/session-move.js +70 -0
  96. package/dist/claude/shell-mode-gate.js +60 -0
  97. package/dist/claude/side-question.js +20 -17
  98. package/dist/claude/stage-images.js +5 -5
  99. package/dist/claude/tasks-overlay-scraper.js +143 -20
  100. package/dist/claude/thread-judge-haiku.js +88 -0
  101. package/dist/claude/tip-scraper.js +3 -4
  102. package/dist/claude/tui-modal.js +272 -27
  103. package/dist/claude/tui-state.js +74 -2
  104. package/dist/claude/turn-end.js +15 -1
  105. package/dist/claude/turn-prose.js +1 -1
  106. package/dist/claude/typed-answer.js +104 -0
  107. package/dist/claude/update-banner-relay.js +1 -1
  108. package/dist/cli/commands/doctor.js +48 -15
  109. package/dist/cli/commands/help.js +11 -2
  110. package/dist/cli/commands/init.js +16 -13
  111. package/dist/cli/commands/service.js +40 -8
  112. package/dist/cli/commands/start.js +10 -0
  113. package/dist/cli/commands/watch.js +322 -0
  114. package/dist/cli/dispatch.js +5 -0
  115. package/dist/cli/init/env-file.js +1 -1
  116. package/dist/cli/init/flow.js +114 -47
  117. package/dist/cli/init/prompter.js +8 -0
  118. package/dist/cli/init/telegram.js +35 -9
  119. package/dist/cli/service/render.js +3 -3
  120. package/dist/config.js +156 -131
  121. package/dist/index.js +107 -31
  122. package/dist/launcher.js +34 -7
  123. package/dist/providers/ccr-introspect.js +1 -8
  124. package/dist/providers/ccr-provider.js +19 -20
  125. package/dist/providers/claude-provider.js +4 -57
  126. package/dist/providers/prefs-sync.js +16 -59
  127. package/dist/providers/provider-router.js +24 -23
  128. package/dist/providers/spawn-settings.js +45 -0
  129. package/dist/providers/user-preferences.js +127 -19
  130. package/dist/restart-when-idle.js +27 -7
  131. package/dist/startup/auto-continue.js +2 -2
  132. package/dist/startup/auto-resume.js +3 -15
  133. package/dist/startup/notices.js +1 -1
  134. package/dist/startup/verify-token.js +4 -4
  135. package/dist/telegram/action-logger.js +3 -165
  136. package/dist/telegram/background-activity-card.js +1 -1
  137. package/dist/telegram/botname-settings.js +71 -125
  138. package/dist/telegram/client-options.js +6 -7
  139. package/dist/telegram/force-reply-tracker.js +55 -16
  140. package/dist/telegram/message-sender.js +92 -360
  141. package/dist/telegram/prompt-label.js +11 -5
  142. package/dist/telegram/streaming-turn.js +5 -7
  143. package/dist/telegram/table-lists.js +56 -0
  144. package/dist/telegram/task-list.js +4 -4
  145. package/dist/telegram/task-tracker.js +45 -126
  146. package/dist/telegram/terminal-renderer.js +1 -5
  147. package/dist/telegram/thread-titles.js +74 -2
  148. package/dist/telegram/threads-setup.js +1 -1
  149. package/dist/utils/admins.js +2 -2
  150. package/dist/utils/bot-icon.js +248 -0
  151. package/dist/utils/bot-token.js +8 -5
  152. package/dist/utils/build-info.js +3 -3
  153. package/dist/utils/caffeinate.js +6 -3
  154. package/dist/utils/claude-env.js +0 -1
  155. package/dist/utils/claude-version.js +2 -2
  156. package/dist/utils/config-home.js +3 -3
  157. package/dist/utils/download.js +41 -15
  158. package/dist/utils/exit-codes.js +11 -0
  159. package/dist/utils/format.js +3 -6
  160. package/dist/utils/home-project.js +1 -1
  161. package/dist/utils/idle-restart.js +1 -1
  162. package/dist/utils/install-mode.js +1 -1
  163. package/dist/utils/instance-config.js +1 -1
  164. package/dist/utils/instances.js +1 -1
  165. package/dist/utils/keyed-settings.js +2 -2
  166. package/dist/utils/memory-pressure.js +60 -0
  167. package/dist/utils/npm-version.js +2 -2
  168. package/dist/utils/resolve-claude-bin.js +13 -24
  169. package/dist/utils/respawn-backoff.js +9 -0
  170. package/dist/utils/stale-launcher.js +1 -1
  171. package/dist/utils/systemd.js +8 -8
  172. package/dist/utils/telegram-proxy.js +72 -0
  173. package/dist/utils/uploads-dir.js +27 -0
  174. package/dist/utils/verbosity.js +8 -8
  175. package/dist/utils/version-check.js +5 -5
  176. package/package.json +3 -4
  177. package/dist/bot/handlers/command/media.js +0 -197
  178. package/dist/bot/handlers/command/streaming-mode.js +0 -16
  179. package/dist/bot/handlers/message/throttle.js +0 -49
  180. package/dist/claude/agent-watchdog.js +0 -162
  181. package/dist/claude/agent.js +0 -1458
  182. package/dist/claude/held-query.js +0 -190
  183. package/dist/claude/mcp-tools.js +0 -354
  184. package/dist/claude/sdk-permission-gate.js +0 -77
  185. package/dist/claude/session-cost.js +0 -41
  186. package/dist/claude/system-prompt.js +0 -162
  187. package/dist/providers/sdk-provider.js +0 -37
  188. package/dist/telegram/telegraph-settings.js +0 -31
  189. package/dist/telegram/telegraph.js +0 -453
  190. package/dist/telegram/terminal-settings.js +0 -25
  191. package/dist/tts/tts-settings.js +0 -62
  192. package/dist/tts/tts.js +0 -245
  193. package/dist/tts/voice-reply.js +0 -78
  194. package/dist/utils/debug-agent.js +0 -117
  195. package/dist/utils/debug-watchdog.js +0 -121
  196. package/dist/utils/project-data-dir.js +0 -33
  197. package/dist/utils/reasoning-summary.js +0 -12
@@ -1,190 +0,0 @@
1
- /**
2
- * An SDK query kept running after its reply, for the background work it
3
- * started — see userMessage in agent.ts for why the CLI needs its input held
4
- * open for that.
5
- *
6
- * The reply is delivered when the turn ends; the query then belongs to no
7
- * turn. Its messages are still read, so a finished task's notification gets a
8
- * sub-turn whose reply is posted on its own. The chat's next message is pushed
9
- * into the same query's input rather than starting a second CLI on the same
10
- * session, which would be told the first one's tasks had ended and would
11
- * leave them to die with it.
12
- */
13
- /**
14
- * The prompt stream of a query: messages pushed in, in order, until `end`.
15
- * The CLI treats the stream's end as the end of its input.
16
- */
17
- export class PromptChannel {
18
- queue = [];
19
- wake;
20
- ended = false;
21
- constructor(first) {
22
- this.queue.push(first);
23
- }
24
- get isOpen() {
25
- return !this.ended;
26
- }
27
- /** False once the stream has ended: the message would never be read. */
28
- push(message) {
29
- if (this.ended)
30
- return false;
31
- this.queue.push(message);
32
- this.wake?.();
33
- return true;
34
- }
35
- end() {
36
- this.ended = true;
37
- this.wake?.();
38
- }
39
- async *[Symbol.asyncIterator]() {
40
- for (;;) {
41
- const next = this.queue.shift();
42
- if (next) {
43
- yield next;
44
- continue;
45
- }
46
- if (this.ended)
47
- return;
48
- await new Promise((resolve) => { this.wake = resolve; });
49
- this.wake = undefined;
50
- }
51
- }
52
- }
53
- /**
54
- * A query's messages, read once and passed to one reader at a time.
55
- *
56
- * A turn that joins a held query waits as the next reader; it takes over at
57
- * the first message `takesOver` accepts (its own prompt starting), and the
58
- * reader before it — still answering a task notification, say — stops there.
59
- */
60
- export class QueryFeed {
61
- source;
62
- closeSource;
63
- current;
64
- next;
65
- started = false;
66
- finished = false;
67
- resolveClosed;
68
- /** Settles once the query's stream has ended. */
69
- closed = new Promise((resolve) => { this.resolveClosed = resolve; });
70
- constructor(source, closeSource) {
71
- this.source = source;
72
- this.closeSource = closeSource;
73
- }
74
- attach(takesOver) {
75
- const sink = { buffer: [], wake: undefined, done: false, handedOver: false, error: undefined };
76
- if (this.finished) {
77
- sink.done = true;
78
- }
79
- else if (!this.current) {
80
- this.current = sink;
81
- }
82
- else {
83
- if (this.next)
84
- this.finish(this.next.sink);
85
- this.next = { sink, takesOver: takesOver ?? (() => true) };
86
- }
87
- if (!this.started) {
88
- this.started = true;
89
- void this.pump();
90
- }
91
- return {
92
- messages: { [Symbol.asyncIterator]: () => this.read(sink) },
93
- handedOver: () => sink.handedOver,
94
- };
95
- }
96
- async pump() {
97
- let error;
98
- try {
99
- for await (const message of this.source) {
100
- if (this.next && this.next.takesOver(message))
101
- this.handOver();
102
- if (this.current)
103
- this.deliver(this.current, message);
104
- }
105
- }
106
- catch (err) {
107
- error = err;
108
- }
109
- this.finished = true;
110
- if (this.current) {
111
- this.current.error = error;
112
- this.finish(this.current);
113
- }
114
- if (this.next)
115
- this.finish(this.next.sink);
116
- this.resolveClosed();
117
- }
118
- handOver() {
119
- if (this.current) {
120
- this.current.handedOver = true;
121
- this.finish(this.current);
122
- }
123
- this.current = this.next?.sink;
124
- this.next = undefined;
125
- }
126
- deliver(sink, message) {
127
- sink.buffer.push(message);
128
- sink.wake?.();
129
- }
130
- finish(sink) {
131
- sink.done = true;
132
- sink.wake?.();
133
- }
134
- async *read(sink) {
135
- try {
136
- for (;;) {
137
- const message = sink.buffer.shift();
138
- if (message) {
139
- yield message;
140
- continue;
141
- }
142
- if (sink.done) {
143
- if (sink.error)
144
- throw sink.error;
145
- return;
146
- }
147
- await new Promise((resolve) => { sink.wake = resolve; });
148
- sink.wake = undefined;
149
- }
150
- }
151
- finally {
152
- // A reader that stops early (an abort) leaves the query to the next
153
- // one if there is one, and otherwise closes it, as breaking out of the
154
- // SDK's own iterator does.
155
- if (!sink.done && this.current === sink) {
156
- if (this.next)
157
- this.handOver();
158
- else
159
- this.closeSource();
160
- }
161
- sink.done = true;
162
- }
163
- }
164
- }
165
- const heldQueries = new Map();
166
- export function holdQuery(sessionKey, held) {
167
- heldQueries.set(sessionKey, held);
168
- void held.feed.closed.then(() => {
169
- if (heldQueries.get(sessionKey) === held)
170
- heldQueries.delete(sessionKey);
171
- });
172
- }
173
- /** The held query, no longer held: the caller joins it or lets it go. */
174
- export function takeHeldQuery(sessionKey) {
175
- const held = heldQueries.get(sessionKey);
176
- heldQueries.delete(sessionKey);
177
- return held;
178
- }
179
- export function getHeldQuery(sessionKey) {
180
- return heldQueries.get(sessionKey);
181
- }
182
- /** Ends a held query's input; its tasks stop when the CLI exits. */
183
- export function releaseHeldQuery(sessionKey) {
184
- const held = heldQueries.get(sessionKey);
185
- if (!held || !held.input.isOpen)
186
- return false;
187
- held.input.end();
188
- return true;
189
- }
190
- //# sourceMappingURL=held-query.js.map
@@ -1,354 +0,0 @@
1
- /**
2
- * MCP Tools — In-process MCP server factory for TeleCoder.
3
- *
4
- * Wraps existing standalone functions (project management, files, questions,
5
- * telegraph) as MCP tools so Claude can invoke them automatically
6
- * based on conversation context instead of requiring explicit /commands.
7
- */
8
- import { z } from 'zod';
9
- import { sanitizeError } from '../utils/sanitize.js';
10
- import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
11
- import { InputFile } from 'grammy';
12
- import * as fs from 'fs';
13
- import * as path from 'path';
14
- import { config } from '../config.js';
15
- import { sessionManager } from './session-manager.js';
16
- import { getWorkspaceRoot, isPathWithinRoot } from '../utils/workspace-guard.js';
17
- import { setSessionTopic, clearTopicAndRefreshBotName } from '../bot/handlers/command/topic-store.js';
18
- import { messageSender } from '../telegram/message-sender.js';
19
- import { createPendingQuestion, buildAskUserMessageText, buildAskUserKeyboard, buildAskUserExpiredNote, closeExpiredQuestion, questionTimeoutMinutes, } from './ask-user.js';
20
- import { parseSessionKey } from '../utils/session-key.js';
21
- import { parseSecretRequest, requestSecret } from './secret-request.js';
22
- // Lazy imports to avoid circular deps and unnecessary module loading
23
- async function importTelegraph() {
24
- return import('../telegram/telegraph.js');
25
- }
26
- // ── Factory ──────────────────────────────────────────────────────────
27
- export function createTeleCoderMcpServer(toolsCtx) {
28
- const tools = buildToolList(toolsCtx);
29
- return createSdkMcpServer({
30
- name: 'telecoder-tools',
31
- version: '1.0.0',
32
- tools,
33
- });
34
- }
35
- function buildToolList(toolsCtx) {
36
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
37
- const tools = [
38
- listProjectsTool(toolsCtx),
39
- switchProjectTool(toolsCtx),
40
- createBotTool(toolsCtx),
41
- sendFileTool(toolsCtx),
42
- askUserTool(toolsCtx),
43
- requestSecretTool(toolsCtx),
44
- ];
45
- if (config.DYNAMIC_BOT_NAME) {
46
- tools.push(setTopicTool(toolsCtx));
47
- }
48
- if (config.TELEGRAPH_ENABLED) {
49
- tools.push(publishTelegraphTool(toolsCtx));
50
- }
51
- return tools;
52
- }
53
- // ── Tool Definitions ─────────────────────────────────────────────────
54
- function listProjectsTool(_toolsCtx) {
55
- return tool('telecoder_list_projects', 'List all available projects in the workspace directory. Use this to see what projects the user can switch to.', {}, async () => {
56
- try {
57
- const workspaceRoot = getWorkspaceRoot();
58
- const entries = fs.readdirSync(workspaceRoot, { withFileTypes: true });
59
- const projects = entries
60
- .filter(e => e.isDirectory() && !e.name.startsWith('.'))
61
- .map(e => e.name);
62
- return {
63
- content: [{
64
- type: 'text',
65
- text: `Projects in ${workspaceRoot}:\n${projects.join('\n')}`,
66
- }],
67
- };
68
- }
69
- catch (error) {
70
- return {
71
- content: [{ type: 'text', text: `Error listing projects: ${error instanceof Error ? error.message : String(error)}` }],
72
- isError: true,
73
- };
74
- }
75
- });
76
- }
77
- function switchProjectTool(toolsCtx) {
78
- return tool('telecoder_switch_project', 'Switch the working directory to a different project. The change takes effect on the next query. Use telecoder_list_projects first to see available projects.', { project_name: z.string().describe('Name of the project directory to switch to') }, async ({ project_name }) => {
79
- try {
80
- const workspaceRoot = getWorkspaceRoot();
81
- const targetPath = path.resolve(workspaceRoot, project_name);
82
- if (!isPathWithinRoot(workspaceRoot, targetPath)) {
83
- return {
84
- content: [{ type: 'text', text: `Error: Path must be within workspace root: ${workspaceRoot}` }],
85
- isError: true,
86
- };
87
- }
88
- if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isDirectory()) {
89
- return {
90
- content: [{ type: 'text', text: `Error: Project not found: ${project_name}` }],
91
- isError: true,
92
- };
93
- }
94
- sessionManager.setWorkingDirectory(toolsCtx.sessionKey, targetPath);
95
- await clearTopicAndRefreshBotName(toolsCtx.telegramCtx, toolsCtx.sessionKey);
96
- return {
97
- content: [{
98
- type: 'text',
99
- text: `Switched to project: ${project_name} (${targetPath}). The new working directory will take effect on the next query.`,
100
- }],
101
- };
102
- }
103
- catch (error) {
104
- return {
105
- content: [{ type: 'text', text: `Error switching project: ${error instanceof Error ? error.message : String(error)}` }],
106
- isError: true,
107
- };
108
- }
109
- });
110
- }
111
- function createBotTool(toolsCtx) {
112
- return tool('telecoder_create_bot', "Create a Telegram bot for one project: sends the user a button that opens Telegram's create-a-bot screen. Once they confirm, the new bot is added to the launcher and starts in that project. Use when the user asks for a bot for a project. Only from a private chat, and only for an admin.", { project_name: z.string().describe('Project directory name in the workspace, or an absolute path') }, async ({ project_name }) => {
113
- try {
114
- const { offerNewBotForSession } = await import('../bot/handlers/newbot.handler.js');
115
- const result = await offerNewBotForSession(toolsCtx.telegramCtx.api, toolsCtx.sessionKey, project_name);
116
- return { content: [{ type: 'text', text: result.message }], ...(result.ok ? {} : { isError: true }) };
117
- }
118
- catch (error) {
119
- return {
120
- content: [{ type: 'text', text: `Error creating bot: ${sanitizeError(error)}` }],
121
- isError: true,
122
- };
123
- }
124
- });
125
- }
126
- const TELEGRAM_MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
127
- function sendFileTool(toolsCtx) {
128
- return tool('telecoder_send_file', 'Send a file from the server to the user via Telegram. The file must be within the current working directory or /tmp. Use this after creating files (SVGs, images, reports, etc.) to deliver them directly to the user. Maximum file size: 50MB.', {
129
- file_path: z.string().describe('Absolute or relative path to the file to send. Relative paths are resolved from the current working directory.'),
130
- caption: z.string().optional().describe('Optional caption to display with the file in Telegram'),
131
- }, async ({ file_path, caption }) => {
132
- try {
133
- const ctx = toolsCtx.telegramCtx;
134
- const session = sessionManager.getSession(toolsCtx.sessionKey);
135
- if (!session) {
136
- return {
137
- content: [{ type: 'text', text: 'Error: No active session.' }],
138
- isError: true,
139
- };
140
- }
141
- // Resolve relative paths against the session working directory
142
- const resolvedPath = path.isAbsolute(file_path)
143
- ? file_path
144
- : path.resolve(session.workingDirectory, file_path);
145
- // Security: validate the path is within allowed directories
146
- const workspaceRoot = getWorkspaceRoot();
147
- const inWorkspace = isPathWithinRoot(workspaceRoot, resolvedPath);
148
- const inTmp = isPathWithinRoot('/tmp', resolvedPath);
149
- if (!inWorkspace && !inTmp) {
150
- return {
151
- content: [{ type: 'text', text: `Error: File path must be within the workspace (${workspaceRoot}) or /tmp. Access denied.` }],
152
- isError: true,
153
- };
154
- }
155
- if (!fs.existsSync(resolvedPath)) {
156
- return {
157
- content: [{ type: 'text', text: `Error: File not found: ${path.basename(resolvedPath)}` }],
158
- isError: true,
159
- };
160
- }
161
- const stat = fs.statSync(resolvedPath);
162
- if (stat.isDirectory()) {
163
- return {
164
- content: [{ type: 'text', text: `Error: Path is a directory, not a file: ${path.basename(resolvedPath)}` }],
165
- isError: true,
166
- };
167
- }
168
- if (stat.size > TELEGRAM_MAX_FILE_SIZE) {
169
- const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);
170
- return {
171
- content: [{ type: 'text', text: `Error: File too large (${sizeMB}MB). Telegram limit is 50MB.` }],
172
- isError: true,
173
- };
174
- }
175
- const fileName = path.basename(resolvedPath);
176
- const fileBuffer = fs.readFileSync(resolvedPath);
177
- const inputFile = new InputFile(fileBuffer, fileName);
178
- await ctx.replyWithDocument(inputFile, {
179
- caption: caption || undefined,
180
- });
181
- const sizeMB = (stat.size / (1024 * 1024)).toFixed(2);
182
- return {
183
- content: [{
184
- type: 'text',
185
- text: `File sent to user: ${fileName} (${sizeMB}MB)`,
186
- }],
187
- };
188
- }
189
- catch (error) {
190
- return {
191
- content: [{ type: 'text', text: `File send error: ${error instanceof Error ? error.message : String(error)}` }],
192
- isError: true,
193
- };
194
- }
195
- });
196
- }
197
- function setTopicTool(toolsCtx) {
198
- return tool('telecoder_set_topic', 'Update the conversation topic shown in the status line. Call this proactively when the work topic changes. Pass an empty string to clear. Keep topics very short (1-4 words).', {
199
- topic: z.string().describe('Short topic label (1-4 words, e.g. "auth refactor", "CI fix", "dark mode"). Empty string to clear.'),
200
- }, async ({ topic }) => {
201
- try {
202
- const { sessionKey } = toolsCtx;
203
- // The topic lives in the status line, not the Telegram bot display name
204
- // (which only carries BOT_NAME — project). So we update in-memory +
205
- // persistent topic state and DO NOT call setMyName. Telegram rate-limits
206
- // setMyName brutally — firing it on every proactive topic change is what
207
- // trips multi-hour 429 flood-waits. Mirrors the /topic command handler.
208
- const trimmedTopic = topic.trim();
209
- setSessionTopic(sessionKey, trimmedTopic);
210
- return {
211
- content: [{
212
- type: 'text',
213
- text: trimmedTopic
214
- ? `Topic set to "${trimmedTopic}".`
215
- : 'Topic cleared.',
216
- }],
217
- };
218
- }
219
- catch (error) {
220
- return {
221
- content: [{
222
- type: 'text',
223
- text: `Failed to set topic: ${error instanceof Error ? error.message : String(error)}`,
224
- }],
225
- isError: true,
226
- };
227
- }
228
- });
229
- }
230
- function publishTelegraphTool(_toolsCtx) {
231
- return tool('telecoder_publish_telegraph', 'Publish markdown content as a Telegraph (telegra.ph) Instant View page. Returns the URL. Useful for sharing long-form content as a readable link.', {
232
- title: z.string().describe('Page title'),
233
- markdown: z.string().describe('Markdown content for the page'),
234
- }, async ({ title, markdown }) => {
235
- try {
236
- const { createTelegraphPage } = await importTelegraph();
237
- const url = await createTelegraphPage(title, markdown);
238
- if (!url) {
239
- return {
240
- content: [{ type: 'text', text: 'Failed to create Telegraph page.' }],
241
- isError: true,
242
- };
243
- }
244
- return {
245
- content: [{ type: 'text', text: `Telegraph page created: ${url}` }],
246
- };
247
- }
248
- catch (error) {
249
- return {
250
- content: [{ type: 'text', text: `Telegraph error: ${error instanceof Error ? error.message : String(error)}` }],
251
- isError: true,
252
- };
253
- }
254
- });
255
- }
256
- function askUserTool(toolsCtx) {
257
- return tool('telecoder_ask_user', 'Ask the user a multiple-choice question via a Telegram inline keyboard. Use when you need a clear decision from the user (e.g. picking between approaches, confirming a destructive action, choosing among options) instead of free-text. Pauses the agent loop until the user taps a button or the question times out. Keep the question short and the options crisp — a label of ≤ 25 chars stays on its button; anything longer makes the whole keyboard fall back to lettered buttons (A/B/C) with the full labels listed in the message body. IMPORTANT: `context` is required and carries everything the user needs to decide (the comparison, trade-offs, findings, rationale) — it renders in the SAME message as the buttons. Do NOT write that explanation as prose before calling this tool: text you emit before an ask_user call is not delivered to the user until after they answer, so they would be choosing blind.', {
258
- question: z.string().describe('The question to display to the user. Keep concise (1-2 sentences).'),
259
- context: z
260
- .string()
261
- .min(1)
262
- .describe('Required. The multi-line explanation shown above the buttons in the same message (e.g. a comparison table, trade-offs, findings the user needs to make an informed choice). Put decision-relevant detail here, not in prose before the call — that prose is not shown until after the user answers. If the choice genuinely needs no explanation, restate what each option will do.'),
263
- options: z
264
- .array(z.object({
265
- label: z.string().describe('Button label. ≤ 25 chars keeps the label on its own button; longer labels are still shown in full in the message body, keyed A/B/C. Keep it to one line either way.'),
266
- description: z.string().optional().describe('Optional one-line context shown in the question body.'),
267
- }))
268
- .min(2)
269
- .max(8)
270
- .describe('Between 2 and 8 options for the user to choose from.'),
271
- }, async ({ question, context, options }) => {
272
- try {
273
- const ctx = toolsCtx.telegramCtx;
274
- if (!ctx?.chat?.id) {
275
- return {
276
- content: [{ type: 'text', text: 'Error: no Telegram context available to ask the user.' }],
277
- isError: true,
278
- };
279
- }
280
- const optionLabels = options.map((o) => o.label);
281
- const { id, promise } = createPendingQuestion(optionLabels, undefined, toolsCtx.sessionKey);
282
- const messageText = buildAskUserMessageText(question, options, context);
283
- const keyboard = buildAskUserKeyboard(id, options);
284
- // Plain text (no parse_mode): model-supplied question/context/label/
285
- // description text can contain stray underscores, asterisks, or
286
- // backticks (e.g. URL params like `f_WT=2`) that break legacy Markdown
287
- // parsing — Telegram returns 400 and the tool fails with no useful
288
- // signal to the model. The body lists every option in full, keyed by
289
- // the letter on its button.
290
- // From the session key, not `ctx.message` — a turn started by a tapped
291
- // button carries a callback-query context with no `message`, which
292
- // would silently drop the thread and post into General.
293
- const threadId = parseSessionKey(toolsCtx.sessionKey).threadId;
294
- const sent = await ctx.api.sendMessage(ctx.chat.id, messageText, {
295
- reply_markup: { inline_keyboard: keyboard },
296
- ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
297
- });
298
- await messageSender.noteQuestionPosted(ctx, toolsCtx.sessionKey);
299
- const answer = await promise;
300
- await messageSender.noteQuestionAnswered(ctx, toolsCtx.sessionKey);
301
- if (!answer) {
302
- await closeExpiredQuestion(ctx.api, sent, messageText, buildAskUserExpiredNote());
303
- return {
304
- content: [{ type: 'text', text: `User did not respond within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment or ask again.` }],
305
- isError: false,
306
- };
307
- }
308
- return {
309
- content: [{ type: 'text', text: `User selected: ${answer.label}` }],
310
- };
311
- }
312
- catch (error) {
313
- return {
314
- content: [{ type: 'text', text: `Ask-user error: ${error instanceof Error ? error.message : String(error)}` }],
315
- isError: true,
316
- };
317
- }
318
- });
319
- }
320
- /**
321
- * The SDK side of telecoder_request_secret; secret-request.ts has the flow.
322
- * The description and fields match src/bin/mcp-server.ts's, which PTY mode
323
- * registers.
324
- */
325
- function requestSecretTool(toolsCtx) {
326
- return tool('telecoder_request_secret', 'Get a secret from the user (an API key, token or password) without it entering this conversation. The user sends it in Telegram; TeleCoder deletes their message at once and runs `command` with the secret in $SECRET and on stdin. You get the exit code and the output with the secret blanked out, never the value. Use this whenever a task needs a credential from the user: never ask them to paste one into the chat, and don\'t send them to a terminal for it. They see the command before they send anything, so make it do exactly what it says. For a long-lived Claude token (CLAUDE_CODE_OAUTH_TOKEN), set source to "claude-setup-token": TeleCoder runs `claude setup-token` on this machine and walks them through signing in, and the token goes straight into your command without passing through Telegram. Works only in a private chat with an admin of the bot. Blocks until the command has run, the user cancels, or the request times out.', {
327
- name: z.string().min(1).max(100).describe('What the secret is, as the user knows it: an env var name like CLAUDE_CODE_OAUTH_TOKEN, or a label like "Stripe test key".'),
328
- purpose: z.string().min(1).describe('One or two sentences for the user: what it is for, and where to get it.'),
329
- command: z.string().min(1).describe('Bash that consumes the secret, from $SECRET or from stdin (the secret and a newline). It runs once, with no terminal, and has 2 minutes. Prefer stdin where the tool reads it: an argument shows in the process list while the command runs. Example: npx dotenvx set API_KEY "$SECRET" -f .env'),
330
- cwd: z.string().optional().describe('Directory to run the command in. Defaults to the session\'s working directory; ~ works.'),
331
- pattern: z.string().optional().describe('A regular expression the secret has to match, e.g. ^sk-ant-oat01-. A message that doesn\'t match is deleted unused and the user asked again, so a stray reply can\'t end up stored as the secret.'),
332
- source: z.enum(['paste', 'claude-setup-token']).optional().describe('"paste" (the default): the user sends the secret. "claude-setup-token": TeleCoder makes a long-lived Claude OAuth token by running `claude setup-token` here; the user signs in through a link and sends back the code the page shows. A token they already have is accepted too.'),
333
- }, async ({ name, purpose, command, cwd, pattern, source }, extra) => {
334
- try {
335
- const req = parseSecretRequest({ name, purpose, command, cwd, pattern, source });
336
- if (typeof req === 'string')
337
- return { content: [{ type: 'text', text: req }], isError: true };
338
- const signal = extra?.signal;
339
- const { sessionKey, telegramCtx: ctx } = toolsCtx;
340
- const result = await requestSecret(ctx, sessionKey, req, signal, {
341
- onPosted: () => messageSender.noteQuestionPosted(ctx, sessionKey),
342
- onSettled: () => messageSender.noteQuestionAnswered(ctx, sessionKey),
343
- });
344
- return { content: [{ type: 'text', text: result.message }], isError: !result.success };
345
- }
346
- catch (error) {
347
- return {
348
- content: [{ type: 'text', text: `Secret request error: ${error instanceof Error ? error.message : String(error)}` }],
349
- isError: true,
350
- };
351
- }
352
- });
353
- }
354
- //# sourceMappingURL=mcp-tools.js.map
@@ -1,77 +0,0 @@
1
- import { gateHookTimeoutSeconds, gateToolCall } from './permission-gate.js';
2
- /**
3
- * The permission gate on the SDK transport, and so on CCR, which always takes
4
- * the SDK path.
5
- *
6
- * The PTY transport runs the gate as a PreToolUse command hook that calls back
7
- * into the bot over IPC. Here the CLI is driven through the agent SDK, which
8
- * takes PreToolUse hooks as in-process callbacks, so the same decision is made
9
- * by the same function (gateToolCall) without the round trip. A PreToolUse
10
- * hook rather than canUseTool, for two reasons: canUseTool is only asked about
11
- * calls the permission rules leave open, and the curated `allowedTools` list
12
- * pre-approves Bash, Write and the rest; and a hook fires in every permission
13
- * mode, bypass included, which is what the PTY hook does too — so a chat's
14
- * /mode means the same thing on both transports.
15
- *
16
- * Hooks fire for a subagent's tool calls as well (their input carries an
17
- * `agent_id`), so a Task or a background agent is gated like the main thread.
18
- */
19
- /**
20
- * The Telegram update behind each session's latest turn. A query can outlive
21
- * the turn that started it — it is held open for background work, and the
22
- * chat's next message joins it — and the gate has to prompt about, and name,
23
- * whoever's turn it is now, as the PTY gate does through its registered turn.
24
- */
25
- const turnContexts = new Map();
26
- /**
27
- * Record `ctx` as the update behind `sessionKey`'s current turn. A turn with
28
- * none clears it, so the gate denies rather than prompting on behalf of an
29
- * earlier turn's sender — as a PTY turn without a context does.
30
- */
31
- export function noteTurnContext(sessionKey, ctx) {
32
- if (ctx)
33
- turnContexts.set(sessionKey, ctx);
34
- else
35
- turnContexts.delete(sessionKey);
36
- }
37
- /** Forget a session's turn context, for tests and a cleared conversation. */
38
- export function forgetTurnContext(sessionKey) {
39
- turnContexts.delete(sessionKey);
40
- }
41
- /**
42
- * The PreToolUse matcher that runs the gate for `sessionKey`'s query.
43
- *
44
- * Registered whether or not the gate is on: it is checked per call, so a bot
45
- * that gains a guest mid-query gets the gate on its next tool call, and the
46
- * hook set a held query is matched on stays the same either way.
47
- */
48
- export function permissionGateHook(sessionKey) {
49
- return {
50
- // Long enough for an unanswered prompt to time out into the gate's own
51
- // denial. A hook that times out is skipped, so the call would run.
52
- timeout: gateHookTimeoutSeconds(),
53
- hooks: [async (input) => {
54
- if (input.hook_event_name !== 'PreToolUse')
55
- return { continue: true };
56
- const toolInput = input.tool_input;
57
- const decision = await gateToolCall({
58
- sessionKey,
59
- toolName: String(input.tool_name ?? 'unknown'),
60
- toolInput: toolInput && typeof toolInput === 'object'
61
- ? toolInput
62
- : {},
63
- telegramCtx: turnContexts.get(sessionKey),
64
- });
65
- if (!decision.block)
66
- return { continue: true };
67
- return {
68
- hookSpecificOutput: {
69
- hookEventName: 'PreToolUse',
70
- permissionDecision: 'deny',
71
- permissionDecisionReason: decision.reason,
72
- },
73
- };
74
- }],
75
- };
76
- }
77
- //# sourceMappingURL=sdk-permission-gate.js.map
@@ -1,41 +0,0 @@
1
- /**
2
- * What a conversation has cost, accumulated turn by turn.
3
- *
4
- * Claude Code cannot answer this. Its own cost counter belongs to the CLI
5
- * process that spent the money: ask `/cost` in a live process and you get its
6
- * running total, resume that same session in a fresh one and you get zero,
7
- * because the session log records token counts but no pricing. So the total
8
- * for a conversation that spans many turns — many processes, in SDK mode —
9
- * only exists if something keeps it, and this is that something.
10
- *
11
- * Only SDK-mode turns feed it. They end in a result message carrying
12
- * `total_cost_usd` for the process that just answered, which is exactly one
13
- * turn's spend. PTY mode never sees a cost figure at all: its numbers come
14
- * from tailing the session JSONL, which has none to give. The turn count
15
- * travels with the total so the figure stays interpretable — a resumed
16
- * session starts from zero here, and "$0.42 across 7 turns" says that plainly
17
- * where a bare "$0.42" would imply the whole history.
18
- */
19
- import { BoundedMap } from '../utils/bounded-map.js';
20
- const sessionCosts = new BoundedMap(1000);
21
- /** Add one turn's cost to a session's running total, and return the total. */
22
- export function recordTurnCost(sessionKey, turnCostUsd) {
23
- const prior = sessionCosts.get(sessionKey);
24
- // A turn with no cost still counts as a turn — PTY-mode zeros never reach
25
- // here, so a zero from the SDK is a real turn that happened to be free.
26
- const next = {
27
- usd: (prior?.usd ?? 0) + (Number.isFinite(turnCostUsd) ? turnCostUsd : 0),
28
- turns: (prior?.turns ?? 0) + 1,
29
- };
30
- sessionCosts.set(sessionKey, next);
31
- return next;
32
- }
33
- /** The running total for a session, or zero when nothing has been recorded. */
34
- export function getSessionCost(sessionKey) {
35
- return sessionCosts.get(sessionKey) ?? { usd: 0, turns: 0 };
36
- }
37
- /** Forget a session's total — it starts again from zero on the next turn. */
38
- export function clearSessionCost(sessionKey) {
39
- sessionCosts.delete(sessionKey);
40
- }
41
- //# sourceMappingURL=session-cost.js.map