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,192 @@
1
+ import * as http from 'http';
2
+ import { randomBytes, timingSafeEqual } from 'crypto';
3
+ import { legacyEnv } from '../utils/legacy-env.js';
4
+ const activeTurns = new Map();
5
+ export function registerActiveTurn(claudeSessionId, turn) {
6
+ activeTurns.set(claudeSessionId, turn);
7
+ }
8
+ export function unregisterActiveTurn(claudeSessionId) {
9
+ activeTurns.delete(claudeSessionId);
10
+ }
11
+ export function getActiveTurn(claudeSessionId) {
12
+ return activeTurns.get(claudeSessionId);
13
+ }
14
+ /**
15
+ * The chat each claude session belongs to, for the MCP tools it calls between
16
+ * TeleCoder's turns. Claude Code starts a turn of its own when a background
17
+ * task reports back, and a tool called in it — a question for the user, a
18
+ * file to send — has no turn of TeleCoder's to run in. Kept for as long as the
19
+ * session's claude runs.
20
+ */
21
+ const sessionChats = new Map();
22
+ /** Record `telegramCtx`'s chat as `sessionKey`'s, for its claude to reach between turns. */
23
+ export function registerSessionChat(claudeSessionId, sessionKey, telegramCtx) {
24
+ sessionChats.set(claudeSessionId, { sessionKey, options: { telegramCtx }, selfStarted: true });
25
+ }
26
+ export function unregisterSessionChat(claudeSessionId) {
27
+ sessionChats.delete(claudeSessionId);
28
+ }
29
+ /**
30
+ * What an MCP tool is told when there is no chat to run it in. The bare ack a
31
+ * hook gets has no message, and a tool result made of it was an empty text
32
+ * block, which the MCP SDK rejects with a schema dump naming nothing.
33
+ */
34
+ const NO_CHAT_MESSAGE = "TeleCoder didn't do this: it has no Telegram chat on record for this Claude Code session. "
35
+ + 'Put what you needed from the user in your reply instead.';
36
+ const handlers = new Map();
37
+ export function registerIpcHandler(path, fn, options = {}) {
38
+ if (handlers.has(path)) {
39
+ console.warn(`[IPC] Replacing existing handler for ${path}`);
40
+ }
41
+ handlers.set(path, { fn, ...options });
42
+ }
43
+ /** The env var a child reads the IPC token from. */
44
+ export const IPC_TOKEN_ENV = 'TELECODER_IPC_TOKEN';
45
+ /** The header every IPC request carries it in. */
46
+ export const IPC_TOKEN_HEADER = 'X-TeleCoder-Token';
47
+ /** Made once per bot process; a restarted bot respawns its ptys with the new one. */
48
+ const ipcToken = randomBytes(32).toString('hex');
49
+ /** The token to hand a child that calls this server, in its environment only. */
50
+ export function getIpcToken() {
51
+ return ipcToken;
52
+ }
53
+ /** Constant-time check of a request's token header. */
54
+ function hasValidToken(req) {
55
+ const presented = req.headers[IPC_TOKEN_HEADER.toLowerCase()];
56
+ if (typeof presented !== 'string')
57
+ return false;
58
+ const given = Buffer.from(presented);
59
+ const expected = Buffer.from(ipcToken);
60
+ return given.length === expected.length && timingSafeEqual(given, expected);
61
+ }
62
+ let ipcPort = null;
63
+ let ipcServerInstance = null;
64
+ export function getIpcPort() {
65
+ if (ipcPort === null) {
66
+ throw new Error('IPC server has not started yet — call startIpcServer() first');
67
+ }
68
+ return ipcPort;
69
+ }
70
+ export function getIpcUrl() {
71
+ return `http://127.0.0.1:${getIpcPort()}`;
72
+ }
73
+ function extractSessionId(body, req) {
74
+ // Claude's hook payloads use snake_case `session_id`. MCP bridge calls pass
75
+ // it explicitly in the same field for consistency.
76
+ const fromBody = typeof body.session_id === 'string' ? body.session_id : undefined;
77
+ if (fromBody)
78
+ return fromBody;
79
+ const fromHeader = req.headers['x-telecoder-session-id'];
80
+ if (typeof fromHeader === 'string')
81
+ return fromHeader;
82
+ return undefined;
83
+ }
84
+ export async function startIpcServer() {
85
+ if (ipcServerInstance)
86
+ return { port: getIpcPort() };
87
+ const server = http.createServer((req, res) => {
88
+ if (!hasValidToken(req)) {
89
+ // Not logged with the session id or path: neither came from anyone we
90
+ // trust, and a log line per probe is a log anyone local can fill.
91
+ req.resume();
92
+ res.writeHead(401, { 'Content-Type': 'application/json' });
93
+ res.end(JSON.stringify({ error: 'unauthorized' }));
94
+ return;
95
+ }
96
+ if (req.method !== 'POST') {
97
+ res.writeHead(405, { 'Content-Type': 'application/json' });
98
+ res.end(JSON.stringify({ error: 'method not allowed' }));
99
+ return;
100
+ }
101
+ let body = '';
102
+ req.on('data', chunk => { body += chunk.toString(); });
103
+ req.on('end', async () => {
104
+ const path = (req.url || '/').split('?')[0];
105
+ let payload;
106
+ try {
107
+ payload = body ? JSON.parse(body) : {};
108
+ }
109
+ catch {
110
+ res.writeHead(400, { 'Content-Type': 'application/json' });
111
+ res.end(JSON.stringify({ error: 'invalid JSON body' }));
112
+ return;
113
+ }
114
+ const registered = handlers.get(path);
115
+ if (!registered) {
116
+ // 404 is intentional — callers can probe for endpoint availability.
117
+ // Hooks ignore body so this won't block claude either way.
118
+ console.warn(`[IPC] No handler for ${path}`);
119
+ res.writeHead(404, { 'Content-Type': 'application/json' });
120
+ res.end(JSON.stringify({ error: 'no handler', path }));
121
+ return;
122
+ }
123
+ // An MCP tool called outside TeleCoder's turns runs in the session's
124
+ // chat, and so does a hook that asks to (the permission gate, which a
125
+ // background agent or a turn claude started itself must not skip).
126
+ // Other hooks drive a turn's own UI, and outside one they go on being
127
+ // acked and ignored.
128
+ const isTool = path.startsWith('/mcp/');
129
+ const betweenTurns = registered.betweenTurns ?? isTool;
130
+ const sessionId = extractSessionId(payload, req);
131
+ const turn = sessionId
132
+ ? activeTurns.get(sessionId) ?? (betweenTurns ? sessionChats.get(sessionId) : undefined)
133
+ : undefined;
134
+ if (!turn) {
135
+ // Don't fail a hook — hooks that fail noisily can block claude. Just
136
+ // log and ack, unless the route says what no turn means for it. A
137
+ // tool is told what didn't happen.
138
+ console.warn(`[IPC] ${path} received with no active turn (sessionId=${sessionId ?? 'missing'})`);
139
+ const reply = registered.noTurn
140
+ ? registered.noTurn(payload)
141
+ : isTool ? { success: false, message: NO_CHAT_MESSAGE } : { ok: true, ignored: true };
142
+ res.writeHead(200, { 'Content-Type': 'application/json' });
143
+ res.end(JSON.stringify(reply));
144
+ return;
145
+ }
146
+ const hangUp = new AbortController();
147
+ res.on('close', () => {
148
+ if (!res.writableFinished)
149
+ hangUp.abort();
150
+ });
151
+ try {
152
+ const result = await registered.fn(turn, payload, hangUp.signal);
153
+ res.writeHead(200, { 'Content-Type': 'application/json' });
154
+ res.end(JSON.stringify(result ?? { ok: true }));
155
+ }
156
+ catch (err) {
157
+ console.error(`[IPC] Handler ${path} threw:`, err);
158
+ res.writeHead(500, { 'Content-Type': 'application/json' });
159
+ res.end(JSON.stringify({
160
+ error: err instanceof Error ? err.message : String(err),
161
+ }));
162
+ }
163
+ });
164
+ });
165
+ // Long-poll friendly: telecoder_ask_user can hold a request open for as long
166
+ // as QUESTION_TIMEOUT_MINUTES waiting on a user button tap, and Node's
167
+ // default requestTimeout (5 min in Node 18+) would otherwise kill the
168
+ // connection mid-wait. This
169
+ // server is bound to 127.0.0.1 only, so disabling the cap doesn't expose
170
+ // anything to the network.
171
+ server.requestTimeout = 0;
172
+ server.headersTimeout = 0;
173
+ const pinnedPort = legacyEnv('IPC_PORT');
174
+ const envPort = pinnedPort ? parseInt(pinnedPort, 10) : 0;
175
+ await new Promise((resolve, reject) => {
176
+ server.once('error', reject);
177
+ server.listen(envPort, '127.0.0.1', () => {
178
+ const addr = server.address();
179
+ if (addr && typeof addr === 'object') {
180
+ ipcPort = addr.port;
181
+ console.log(`[IPC] Listening on http://127.0.0.1:${addr.port}`);
182
+ resolve();
183
+ }
184
+ else {
185
+ reject(new Error('Failed to determine IPC port from server.address()'));
186
+ }
187
+ });
188
+ });
189
+ ipcServerInstance = server;
190
+ return { port: getIpcPort() };
191
+ }
192
+ //# sourceMappingURL=ipc-server.js.map
@@ -0,0 +1,453 @@
1
+ /**
2
+ * IPC handlers that bridge the standalone MCP subprocess back into the main
3
+ * bot process. The MCP subprocess (src/bin/mcp-server.ts) handles tool
4
+ * registrations and JSON-RPC stdio with claude; the tool implementations that
5
+ * need bot-side context (Telegram API, session state, …) POST to the loopback
6
+ * IPC server, which dispatches to handlers registered here.
7
+ *
8
+ * All imports of bot/handlers/* are lazy to avoid circular dependencies:
9
+ * bot/handlers/command.handler → providers/provider-router → providers/claude-provider
10
+ * → claude/pty-provider → claude/mcp-bridge → (here)
11
+ * Eager imports of command.handler would close the loop and TypeScript would
12
+ * resolve some of the exports to `undefined` at module load.
13
+ *
14
+ * Side-effect module: importing it registers the handlers. PtyProvider does so
15
+ * at module load so the IPC server has them ready before any MCP request
16
+ * arrives.
17
+ */
18
+ import * as fs from 'fs';
19
+ import * as path from 'path';
20
+ import { InputFile } from 'grammy';
21
+ import { registerIpcHandler } from './ipc-server.js';
22
+ import { settleBeforePost } from './monitor-relay.js';
23
+ import { sessionManager } from './session-manager.js';
24
+ import { getWorkspaceRoot, isPathWithinRoot } from '../utils/workspace-guard.js';
25
+ import { createPendingQuestion, buildAskUserMessageText, buildAskUserKeyboard, buildAskUserExpiredNote, closeExpiredQuestion, questionTimeoutMinutes, } from './ask-user.js';
26
+ import { createPendingPoll } from './poll-user.js';
27
+ import { scheduler } from './scheduler.js';
28
+ import { readLastAssistantTurnText } from './session-jsonl.js';
29
+ import { getDeliveredProse, recordDeliveredProse, stripDeliveredPrefix } from './turn-prose.js';
30
+ import { parseSessionKey } from '../utils/session-key.js';
31
+ import { parseSecretRequest, requestSecret } from './secret-request.js';
32
+ const TELEGRAM_MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
33
+ function getTelegramCtx(options) {
34
+ if (!options || typeof options !== 'object')
35
+ return undefined;
36
+ const ctx = options.telegramCtx;
37
+ if (!ctx || typeof ctx !== 'object')
38
+ return undefined;
39
+ return ctx;
40
+ }
41
+ /**
42
+ * Ready the chat for something a tool is about to post. In a turn claude
43
+ * started itself, that means sending what the turn has written so far and
44
+ * sealing the background card, so what the turn writes around the post stays
45
+ * in order.
46
+ */
47
+ async function beforePosting(turn) {
48
+ if (turn.selfStarted)
49
+ await settleBeforePost(turn.sessionKey);
50
+ }
51
+ // ── /mcp/set_topic ───────────────────────────────────────────────────
52
+ registerIpcHandler('/mcp/set_topic', async (turn, body) => {
53
+ const topic = String(body.topic ?? '').trim();
54
+ // Topic now lives in the status line, not the Telegram bot name, so
55
+ // setSessionTopic is the only thing we do here — no setMyName call.
56
+ // (The persisted topic survives restarts and is what the status-line
57
+ // renderer reads.)
58
+ const { setSessionTopic } = await import('../bot/handlers/command.handler.js');
59
+ setSessionTopic(turn.sessionKey, topic);
60
+ return {
61
+ success: true,
62
+ message: topic ? `Topic set to "${topic}".` : 'Topic cleared.',
63
+ };
64
+ });
65
+ /**
66
+ * Post the assistant prose written so far in this PTY turn as its own message,
67
+ * so a question that follows it doesn't arrive ahead of its own reasoning.
68
+ *
69
+ * Reads the same JSONL the end-of-turn path reads, subtracts whatever an
70
+ * earlier flush in this turn already sent, and records the new high-water mark
71
+ * for {@link stripDeliveredPrefix} to remove at end-of-turn.
72
+ *
73
+ * Best-effort throughout: no claude session id yet, an unreadable log, or a
74
+ * failed send all just mean the prose stays where it was — the question still
75
+ * goes out, carrying its own `context` block.
76
+ */
77
+ async function flushTurnProse(sessionKey, ctx, messageSender) {
78
+ try {
79
+ const botSession = sessionManager.getSession(sessionKey);
80
+ if (!botSession?.claudeSessionId)
81
+ return;
82
+ const soFar = readLastAssistantTurnText(botSession.workingDirectory, botSession.claudeSessionId);
83
+ if (!soFar)
84
+ return;
85
+ const fresh = stripDeliveredPrefix(soFar, getDeliveredProse(sessionKey)).trim();
86
+ if (!fresh)
87
+ return;
88
+ await messageSender.sendMessage(ctx, fresh);
89
+ recordDeliveredProse(sessionKey, soFar);
90
+ }
91
+ catch (err) {
92
+ console.debug('[AskUser] Prose flush skipped:', err instanceof Error ? err.message : err);
93
+ }
94
+ }
95
+ // ── /mcp/ask_user ────────────────────────────────────────────────────
96
+ // Long-polling IPC handler: registers a pending question in the same shared
97
+ // ask-user registry SDK mode uses, sends a Telegram inline keyboard, and
98
+ // awaits the user's button tap. The existing callback-query dispatcher
99
+ // (handling `q:<id>:<idx>` callback_data) resolves the promise so we can
100
+ // return the chosen label to claude. Times out after QUESTION_TIMEOUT_MINUTES via
101
+ // createPendingQuestion's default.
102
+ registerIpcHandler('/mcp/ask_user', async (turn, body) => {
103
+ const question = String(body.question ?? '').trim();
104
+ const context = typeof body.context === 'string' ? body.context : undefined;
105
+ const rawOptions = Array.isArray(body.options) ? body.options : [];
106
+ const options = rawOptions
107
+ .map((o) => {
108
+ if (!o || typeof o !== 'object')
109
+ return null;
110
+ const oo = o;
111
+ if (typeof oo.label !== 'string' || !oo.label)
112
+ return null;
113
+ return {
114
+ label: oo.label,
115
+ description: typeof oo.description === 'string' ? oo.description : undefined,
116
+ };
117
+ })
118
+ .filter((o) => o !== null);
119
+ if (!question || options.length < 2) {
120
+ return { success: false, message: 'Error: ask_user requires a non-empty question and ≥ 2 options.' };
121
+ }
122
+ const ctx = getTelegramCtx(turn.options);
123
+ if (!ctx?.chat?.id) {
124
+ return { success: false, message: 'Error: no Telegram context available to ask the user.' };
125
+ }
126
+ const optionLabels = options.map((o) => o.label);
127
+ const { id, promise } = createPendingQuestion(optionLabels, undefined, turn.sessionKey);
128
+ // PTY mode holds the turn's prose in the JSONL log until end-of-turn, so
129
+ // anything the model wrote to set up this question is still undelivered.
130
+ // Flush it above the buttons; the provider strips it from the end-of-turn
131
+ // text so it isn't shown twice. Imported lazily to keep this module's eager
132
+ // graph minimal — it is loaded from pty-provider at module scope, so every
133
+ // eager edge here is a chance to close a cycle back through it.
134
+ //
135
+ // A turn claude started itself has its prose sent by the monitor relay
136
+ // instead, which beforePosting has it do now.
137
+ const { messageSender } = await import('../telegram/message-sender.js');
138
+ await beforePosting(turn);
139
+ if (!turn.selfStarted)
140
+ await flushTurnProse(turn.sessionKey, ctx, messageSender);
141
+ const messageText = buildAskUserMessageText(question, options, context);
142
+ const keyboard = buildAskUserKeyboard(id, options);
143
+ // Plain text (no parse_mode): model-supplied question/context/label/
144
+ // description text can contain stray underscores, asterisks, or backticks
145
+ // (e.g. URL params like `f_WT=2`) that break legacy Markdown parsing —
146
+ // Telegram returns 400, grammy throws, the IPC server returns 500, and the
147
+ // model just sees the tool fail. The bold on labels was a nice-to-have; the
148
+ // body lists every option in full, keyed by the letter on its button.
149
+ // From the session key, not `ctx.message` — a turn started by a tapped
150
+ // button carries a callback-query context with no `message`, which would
151
+ // silently drop the thread and post the question into General.
152
+ const threadId = parseSessionKey(turn.sessionKey).threadId;
153
+ const sent = await ctx.api.sendMessage(ctx.chat.id, messageText, {
154
+ reply_markup: { inline_keyboard: keyboard },
155
+ ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
156
+ });
157
+ // Tell the streaming UI a question is on screen, so the final answer is
158
+ // posted below it rather than edited into the bubble above it, and the
159
+ // status line says we're blocked on the user.
160
+ await messageSender.noteQuestionPosted(ctx, turn.sessionKey);
161
+ const answer = await promise;
162
+ await messageSender.noteQuestionAnswered(ctx, turn.sessionKey);
163
+ if (!answer) {
164
+ await closeExpiredQuestion(ctx.api, sent, messageText, buildAskUserExpiredNote());
165
+ return {
166
+ success: true,
167
+ message: `User did not respond within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment or ask again.`,
168
+ };
169
+ }
170
+ return { success: true, message: `User selected: ${answer.label}` };
171
+ });
172
+ // ── /mcp/request_secret ──────────────────────────────────────────────
173
+ // Long-polls like ask_user: the user's answer is a message that
174
+ // captureSecretMessages takes out of the chat, or a sign-in code for the
175
+ // claude setup-token run the request starts. Hanging up (claude cancelled the
176
+ // call, or its pty went away) withdraws the request, so the next message the
177
+ // user sends isn't taken for a secret nobody is waiting on.
178
+ registerIpcHandler('/mcp/request_secret', async (turn, body, signal) => {
179
+ const req = parseSecretRequest(body);
180
+ if (typeof req === 'string')
181
+ return { success: false, message: req };
182
+ const ctx = getTelegramCtx(turn.options);
183
+ if (!ctx?.chat?.id) {
184
+ return { success: false, message: 'Error: no Telegram context available to ask the user.' };
185
+ }
186
+ // Same reasons as ask_user: the prose that leads up to the request goes
187
+ // out above it, not after the user has answered.
188
+ const { messageSender } = await import('../telegram/message-sender.js');
189
+ await beforePosting(turn);
190
+ if (!turn.selfStarted)
191
+ await flushTurnProse(turn.sessionKey, ctx, messageSender);
192
+ return requestSecret(ctx, turn.sessionKey, req, signal, {
193
+ onPosted: () => messageSender.noteQuestionPosted(ctx, turn.sessionKey),
194
+ onSettled: () => messageSender.noteQuestionAnswered(ctx, turn.sessionKey),
195
+ });
196
+ });
197
+ // ── /mcp/switch_project ──────────────────────────────────────────────
198
+ // Updates the session's working directory. PtyProvider's _getOrCreateSession
199
+ // detects the cwd mismatch on the next turn and respawns the pty in the new
200
+ // dir — so the switch is logically "happens on next query," same as SDK mode.
201
+ registerIpcHandler('/mcp/switch_project', async (turn, body) => {
202
+ const projectName = String(body.project_name ?? '').trim();
203
+ if (!projectName) {
204
+ return { success: false, message: 'Error: project_name is required.' };
205
+ }
206
+ const workspaceRoot = getWorkspaceRoot();
207
+ const targetPath = path.resolve(workspaceRoot, projectName);
208
+ if (!isPathWithinRoot(workspaceRoot, targetPath)) {
209
+ return { success: false, message: `Error: Path must be within workspace root: ${workspaceRoot}` };
210
+ }
211
+ if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isDirectory()) {
212
+ return { success: false, message: `Error: Project not found: ${projectName}` };
213
+ }
214
+ sessionManager.setWorkingDirectory(turn.sessionKey, targetPath);
215
+ // Refresh the Telegram bot display name so it reflects the new project.
216
+ // Matches the behavior of /project and the SDK in-process switch_project tool.
217
+ const ctx = getTelegramCtx(turn.options);
218
+ if (ctx) {
219
+ const { clearTopicAndRefreshBotName } = await import('../bot/handlers/command.handler.js');
220
+ await clearTopicAndRefreshBotName(ctx, turn.sessionKey);
221
+ }
222
+ return {
223
+ success: true,
224
+ message: `Switched to project: ${projectName} (${targetPath}). The new working directory will take effect on the next query.`,
225
+ };
226
+ });
227
+ // ── /mcp/create_bot ──────────────────────────────────────────────────
228
+ // Offers the create-a-bot button in this turn's chat. The bot itself is
229
+ // adopted later, when Telegram reports it: see newbot.handler.ts.
230
+ registerIpcHandler('/mcp/create_bot', async (turn, body) => {
231
+ const projectName = String(body.project_name ?? '').trim();
232
+ if (!projectName)
233
+ return { success: false, message: 'Error: project_name is required.' };
234
+ const ctx = getTelegramCtx(turn.options);
235
+ if (!ctx)
236
+ return { success: false, message: 'Error: no Telegram chat for this turn.' };
237
+ const { offerNewBotForSession } = await import('../bot/handlers/newbot.handler.js');
238
+ const result = await offerNewBotForSession(ctx.api, turn.sessionKey, projectName);
239
+ return { success: result.ok, message: result.message };
240
+ });
241
+ // ── /mcp/send_file ───────────────────────────────────────────────────
242
+ // Sends a file from the bot's filesystem (workspace or /tmp) to the user via
243
+ // Telegram. Mirrors the SDK in-process MCP tool in src/claude/mcp-tools.ts but
244
+ // routed through IPC so the MCP subprocess can stay out of process.
245
+ registerIpcHandler('/mcp/send_file', async (turn, body) => {
246
+ const filePath = String(body.file_path ?? '');
247
+ const caption = typeof body.caption === 'string' && body.caption.length > 0 ? body.caption : undefined;
248
+ const session = sessionManager.getSession(turn.sessionKey);
249
+ if (!session) {
250
+ return { success: false, message: 'Error: No active session.' };
251
+ }
252
+ const ctx = getTelegramCtx(turn.options);
253
+ if (!ctx) {
254
+ return { success: false, message: 'Error: No Telegram context for this turn.' };
255
+ }
256
+ // Resolve relative paths against the session's workspace, same as SDK mode.
257
+ const resolvedPath = path.isAbsolute(filePath)
258
+ ? filePath
259
+ : path.resolve(session.workingDirectory, filePath);
260
+ // Path must be inside the workspace root or /tmp — anything outside is
261
+ // treated as an exfiltration attempt and rejected. Same guards as the
262
+ // in-process MCP version.
263
+ const workspaceRoot = getWorkspaceRoot();
264
+ if (!isPathWithinRoot(workspaceRoot, resolvedPath) && !isPathWithinRoot('/tmp', resolvedPath)) {
265
+ return { success: false, message: `Error: File path must be within the workspace (${workspaceRoot}) or /tmp. Access denied.` };
266
+ }
267
+ if (!fs.existsSync(resolvedPath)) {
268
+ return { success: false, message: `Error: File not found: ${path.basename(resolvedPath)}` };
269
+ }
270
+ const stat = fs.statSync(resolvedPath);
271
+ if (stat.isDirectory()) {
272
+ return { success: false, message: `Error: Path is a directory, not a file: ${path.basename(resolvedPath)}` };
273
+ }
274
+ if (stat.size > TELEGRAM_MAX_FILE_SIZE) {
275
+ const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);
276
+ return { success: false, message: `Error: File too large (${sizeMB}MB). Telegram limit is 50MB.` };
277
+ }
278
+ const fileName = path.basename(resolvedPath);
279
+ try {
280
+ const fileBuffer = fs.readFileSync(resolvedPath);
281
+ const inputFile = new InputFile(fileBuffer, fileName);
282
+ await beforePosting(turn);
283
+ await ctx.replyWithDocument(inputFile, caption ? { caption } : undefined);
284
+ }
285
+ catch (err) {
286
+ return {
287
+ success: false,
288
+ message: `Error sending file: ${err instanceof Error ? err.message : String(err)}`,
289
+ };
290
+ }
291
+ const sizeMB = (stat.size / (1024 * 1024)).toFixed(2);
292
+ return {
293
+ success: true,
294
+ message: `File sent to user: ${fileName} (${sizeMB}MB)`,
295
+ };
296
+ });
297
+ // ── /mcp/poll_user ───────────────────────────────────────────────────
298
+ // Telegram poll variant of ask_user. Non-anonymous (required for the bot
299
+ // to receive poll_answer events); resolves on the first vote so the agent
300
+ // loop doesn't hang. Multi-select snapshots whatever's selected when the
301
+ // first poll_answer arrives.
302
+ registerIpcHandler('/mcp/poll_user', async (turn, body) => {
303
+ const question = String(body.question ?? '').trim();
304
+ const rawOptions = Array.isArray(body.options) ? body.options : [];
305
+ const options = rawOptions.filter((o) => typeof o === 'string' && o.length > 0).slice(0, 10);
306
+ const allowsMultiple = !!body.allows_multiple_answers;
307
+ if (!question)
308
+ return { success: false, message: 'Error: question is required.' };
309
+ if (options.length < 2)
310
+ return { success: false, message: 'Error: at least 2 options required.' };
311
+ const ctx = getTelegramCtx(turn.options);
312
+ if (!ctx?.chat?.id) {
313
+ return { success: false, message: 'Error: no Telegram context available to ask the user.' };
314
+ }
315
+ // Session key, not `ctx.message` — see the note in the ask_user handler.
316
+ const threadId = parseSessionKey(turn.sessionKey).threadId;
317
+ await beforePosting(turn);
318
+ const sent = await ctx.api.sendPoll(ctx.chat.id, question, options.map((o) => ({ text: o })), {
319
+ is_anonymous: false,
320
+ allows_multiple_answers: allowsMultiple,
321
+ ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
322
+ });
323
+ const pollId = sent.poll.id;
324
+ const answer = await createPendingPoll(pollId, options, allowsMultiple, turn.sessionKey);
325
+ if (!answer) {
326
+ // Close the poll: nothing is counting votes any more, and an open one
327
+ // still invites them. A stopped poll shows its final results instead.
328
+ try {
329
+ await ctx.api.stopPoll(sent.chat.id, sent.message_id);
330
+ }
331
+ catch {
332
+ // Cosmetic — the agent gets its answer either way.
333
+ }
334
+ return {
335
+ success: true,
336
+ message: `No one voted within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment.`,
337
+ };
338
+ }
339
+ if (answer.labels.length === 0) {
340
+ return { success: true, message: 'Vote received but no options recorded.' };
341
+ }
342
+ if (answer.labels.length === 1) {
343
+ return { success: true, message: `User selected: ${answer.labels[0]}` };
344
+ }
345
+ return { success: true, message: `User selected: ${answer.labels.join(', ')}` };
346
+ });
347
+ // ── /mcp/schedule_loop ───────────────────────────────────────────────
348
+ // Claude-initiated interval scheduling. Same scheduler as the Telegram-side
349
+ // /schedule command — only the entrypoint differs, so caps and persistence
350
+ // are uniformly enforced regardless of who created the schedule.
351
+ registerIpcHandler('/mcp/schedule_loop', async (turn, body) => {
352
+ const prompt = String(body.prompt ?? '').trim();
353
+ const intervalSeconds = typeof body.interval_seconds === 'number' ? body.interval_seconds : 0;
354
+ const maxRuns = typeof body.max_runs === 'number' ? body.max_runs : undefined;
355
+ const label = typeof body.label === 'string' ? body.label : undefined;
356
+ if (!prompt)
357
+ return { success: false, message: 'Error: prompt is required.' };
358
+ if (intervalSeconds < 60)
359
+ return { success: false, message: 'Error: interval_seconds must be at least 60.' };
360
+ const session = sessionManager.getSession(turn.sessionKey);
361
+ if (!session) {
362
+ return { success: false, message: 'Error: no session bound to this chat — schedule cannot be created.' };
363
+ }
364
+ try {
365
+ const created = scheduler.createSchedule({
366
+ sessionKey: turn.sessionKey,
367
+ cwd: session.workingDirectory,
368
+ claudeSessionId: session.claudeSessionId,
369
+ prompt,
370
+ label,
371
+ maxRuns,
372
+ kind: 'interval',
373
+ intervalMs: intervalSeconds * 1000,
374
+ });
375
+ const nextFire = scheduler.nextFireAt(created.id);
376
+ const nextLine = nextFire ? ` Next fire: ${new Date(nextFire).toLocaleString()}.` : '';
377
+ return {
378
+ success: true,
379
+ message: `Schedule created (id=${created.id}). Will fire every ${intervalSeconds}s, up to ${created.maxRuns} times.${nextLine}`,
380
+ };
381
+ }
382
+ catch (err) {
383
+ return { success: false, message: `Error: ${err instanceof Error ? err.message : String(err)}` };
384
+ }
385
+ });
386
+ // ── /mcp/schedule_cron ───────────────────────────────────────────────
387
+ registerIpcHandler('/mcp/schedule_cron', async (turn, body) => {
388
+ const prompt = String(body.prompt ?? '').trim();
389
+ const cronExpression = String(body.cron_expression ?? '').trim();
390
+ const maxRuns = typeof body.max_runs === 'number' ? body.max_runs : undefined;
391
+ const label = typeof body.label === 'string' ? body.label : undefined;
392
+ if (!prompt)
393
+ return { success: false, message: 'Error: prompt is required.' };
394
+ if (!cronExpression)
395
+ return { success: false, message: 'Error: cron_expression is required.' };
396
+ const session = sessionManager.getSession(turn.sessionKey);
397
+ if (!session) {
398
+ return { success: false, message: 'Error: no session bound to this chat — schedule cannot be created.' };
399
+ }
400
+ try {
401
+ const created = scheduler.createSchedule({
402
+ sessionKey: turn.sessionKey,
403
+ cwd: session.workingDirectory,
404
+ claudeSessionId: session.claudeSessionId,
405
+ prompt,
406
+ label,
407
+ maxRuns,
408
+ kind: 'cron',
409
+ cronExpr: cronExpression,
410
+ });
411
+ const nextFire = scheduler.nextFireAt(created.id);
412
+ const nextLine = nextFire ? ` Next fire: ${new Date(nextFire).toLocaleString()}.` : '';
413
+ return {
414
+ success: true,
415
+ message: `Schedule created (id=${created.id}, cron=${cronExpression}, up to ${created.maxRuns} fires).${nextLine}`,
416
+ };
417
+ }
418
+ catch (err) {
419
+ return { success: false, message: `Error: ${err instanceof Error ? err.message : String(err)}` };
420
+ }
421
+ });
422
+ // ── /mcp/schedule_list ───────────────────────────────────────────────
423
+ registerIpcHandler('/mcp/schedule_list', async (turn) => {
424
+ const list = scheduler.listSchedules(turn.sessionKey);
425
+ if (list.length === 0) {
426
+ return { success: true, message: 'No active schedules for this chat.' };
427
+ }
428
+ const lines = list.map((s) => {
429
+ const status = s.disabled ? ' [DISABLED]' : '';
430
+ const cadence = s.kind === 'interval'
431
+ ? `every ${Math.round((s.intervalMs ?? 0) / 1000)}s`
432
+ : `cron ${s.cronExpr ?? '?'}`;
433
+ const next = scheduler.nextFireAt(s.id);
434
+ const nextLine = next ? `, next ${new Date(next).toLocaleString()}` : '';
435
+ const promptPreview = s.prompt.length > 60 ? s.prompt.slice(0, 57) + '...' : s.prompt;
436
+ const labelPart = s.label ? ` "${s.label}"` : '';
437
+ return `${s.id}${labelPart}: ${cadence}, ${s.runs}/${s.maxRuns} runs${nextLine}${status}\n prompt: ${promptPreview}`;
438
+ });
439
+ return { success: true, message: `Active schedules (${list.length}):\n\n${lines.join('\n\n')}` };
440
+ });
441
+ // ── /mcp/schedule_cancel ─────────────────────────────────────────────
442
+ registerIpcHandler('/mcp/schedule_cancel', async (turn, body) => {
443
+ const id = String(body.id ?? '').trim();
444
+ if (!id)
445
+ return { success: false, message: 'Error: id is required.' };
446
+ const target = scheduler.getSchedule(id);
447
+ if (!target || target.sessionKey !== turn.sessionKey) {
448
+ return { success: false, message: `No schedule "${id}" in this chat.` };
449
+ }
450
+ scheduler.deleteSchedule(id);
451
+ return { success: true, message: `Schedule ${id} cancelled.` };
452
+ });
453
+ //# sourceMappingURL=mcp-bridge.js.map