telecoder 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/.env.example +375 -0
  2. package/CHANGELOG.md +1867 -0
  3. package/LICENSE +22 -0
  4. package/README.md +130 -2
  5. package/dist/audio/transcribe.js +41 -0
  6. package/dist/bin/mcp-server.js +363 -0
  7. package/dist/bin/tool-result.js +22 -0
  8. package/dist/bot/access/group-access.js +147 -0
  9. package/dist/bot/bot.js +573 -0
  10. package/dist/bot/command-catalog.js +263 -0
  11. package/dist/bot/deleted-threads.js +103 -0
  12. package/dist/bot/file-access.js +150 -0
  13. package/dist/bot/handlers/album.handler.js +128 -0
  14. package/dist/bot/handlers/branch.handler.js +1096 -0
  15. package/dist/bot/handlers/command/access.js +407 -0
  16. package/dist/bot/handlers/command/admin.js +803 -0
  17. package/dist/bot/handlers/command/all-view.js +33 -0
  18. package/dist/bot/handlers/command/auto-approve.js +138 -0
  19. package/dist/bot/handlers/command/background.js +37 -0
  20. package/dist/bot/handlers/command/botname.js +76 -0
  21. package/dist/bot/handlers/command/btw.js +175 -0
  22. package/dist/bot/handlers/command/cleanup.js +329 -0
  23. package/dist/bot/handlers/command/model.js +226 -0
  24. package/dist/bot/handlers/command/prefs-scope.js +362 -0
  25. package/dist/bot/handlers/command/project.js +458 -0
  26. package/dist/bot/handlers/command/resume.js +325 -0
  27. package/dist/bot/handlers/command/session.js +299 -0
  28. package/dist/bot/handlers/command/settings.js +657 -0
  29. package/dist/bot/handlers/command/shared.js +207 -0
  30. package/dist/bot/handlers/command/tasks.js +681 -0
  31. package/dist/bot/handlers/command/thread.js +128 -0
  32. package/dist/bot/handlers/command/topic-store.js +74 -0
  33. package/dist/bot/handlers/command/topic.js +27 -0
  34. package/dist/bot/handlers/command/usage.js +382 -0
  35. package/dist/bot/handlers/command-fallback.js +179 -0
  36. package/dist/bot/handlers/command.handler.js +446 -0
  37. package/dist/bot/handlers/loop.handler.js +389 -0
  38. package/dist/bot/handlers/media-fallback.js +126 -0
  39. package/dist/bot/handlers/message/replies.js +56 -0
  40. package/dist/bot/handlers/message/shared.js +95 -0
  41. package/dist/bot/handlers/message/turn-notify.js +135 -0
  42. package/dist/bot/handlers/message/turn-runner.js +56 -0
  43. package/dist/bot/handlers/message.handler.js +114 -0
  44. package/dist/bot/handlers/newbot.handler.js +230 -0
  45. package/dist/bot/handlers/photo.handler.js +286 -0
  46. package/dist/bot/handlers/prompts.handler.js +343 -0
  47. package/dist/bot/handlers/running-note.js +44 -0
  48. package/dist/bot/handlers/session-guard.js +78 -0
  49. package/dist/bot/handlers/suggestion.handler.js +84 -0
  50. package/dist/bot/handlers/tree.handler.js +480 -0
  51. package/dist/bot/handlers/view.js +41 -0
  52. package/dist/bot/handlers/voice.handler.js +147 -0
  53. package/dist/bot/kept-threads.js +51 -0
  54. package/dist/bot/middleware/admin-only.js +49 -0
  55. package/dist/bot/middleware/album-collector.js +69 -0
  56. package/dist/bot/middleware/auth.middleware.js +122 -0
  57. package/dist/bot/middleware/group-mention.middleware.js +145 -0
  58. package/dist/bot/middleware/group-role.middleware.js +75 -0
  59. package/dist/bot/middleware/message-batcher.js +87 -0
  60. package/dist/bot/middleware/queued-messages.js +1082 -0
  61. package/dist/bot/middleware/stale-filter.js +9 -0
  62. package/dist/build-info.json +8 -0
  63. package/dist/claude/ask-user-form.js +517 -0
  64. package/dist/claude/ask-user.js +363 -0
  65. package/dist/claude/auto-approve.js +225 -0
  66. package/dist/claude/auto-topic-haiku.js +143 -0
  67. package/dist/claude/available-commands.js +156 -0
  68. package/dist/claude/background-hint.js +91 -0
  69. package/dist/claude/branch-tree.js +393 -0
  70. package/dist/claude/carry-over.js +25 -0
  71. package/dist/claude/ccr-shim.js +48 -0
  72. package/dist/claude/charter-judge.js +214 -0
  73. package/dist/claude/claude-auth.js +117 -0
  74. package/dist/claude/command-parser.js +206 -0
  75. package/dist/claude/cost-overlay-scraper.js +134 -0
  76. package/dist/claude/effort-level.js +5 -0
  77. package/dist/claude/enabled-plugins.js +52 -0
  78. package/dist/claude/in-flight-tracker.js +82 -0
  79. package/dist/claude/ipc-server.js +192 -0
  80. package/dist/claude/mcp-bridge.js +481 -0
  81. package/dist/claude/memory-guard.js +400 -0
  82. package/dist/claude/message-offsets.js +88 -0
  83. package/dist/claude/modal-relay.js +817 -0
  84. package/dist/claude/model-catalog.js +102 -0
  85. package/dist/claude/monitor-relay.js +712 -0
  86. package/dist/claude/native-commands.js +40 -0
  87. package/dist/claude/pending-branches.js +93 -0
  88. package/dist/claude/pending-suggestions.js +50 -0
  89. package/dist/claude/permission-gate.js +338 -0
  90. package/dist/claude/permission-mode.js +152 -0
  91. package/dist/claude/poll-user.js +51 -0
  92. package/dist/claude/prewarm.js +70 -0
  93. package/dist/claude/project-commands.js +69 -0
  94. package/dist/claude/prompt-hold.js +124 -0
  95. package/dist/claude/prompt-suggestion-scraper.js +89 -0
  96. package/dist/claude/pty-idle-reaper.js +96 -0
  97. package/dist/claude/pty-provider.js +2499 -0
  98. package/dist/claude/pty-spawn-config.js +343 -0
  99. package/dist/claude/pty-stream.js +363 -0
  100. package/dist/claude/pty-watch.js +201 -0
  101. package/dist/claude/request-queue.js +107 -0
  102. package/dist/claude/rewind.js +111 -0
  103. package/dist/claude/scheduled-runner.js +89 -0
  104. package/dist/claude/scheduler.js +241 -0
  105. package/dist/claude/scope-guard.js +279 -0
  106. package/dist/claude/screen-marks.js +83 -0
  107. package/dist/claude/screen-render.js +96 -0
  108. package/dist/claude/secret-request.js +576 -0
  109. package/dist/claude/session-history.js +288 -0
  110. package/dist/claude/session-jsonl.js +1067 -0
  111. package/dist/claude/session-manager.js +216 -0
  112. package/dist/claude/session-move.js +70 -0
  113. package/dist/claude/session-scan.js +270 -0
  114. package/dist/claude/setup-token.js +285 -0
  115. package/dist/claude/shell-mode-gate.js +60 -0
  116. package/dist/claude/side-call-options.js +45 -0
  117. package/dist/claude/side-question.js +252 -0
  118. package/dist/claude/stage-images.js +62 -0
  119. package/dist/claude/subagent-tools.js +12 -0
  120. package/dist/claude/synthetic-ctx.js +51 -0
  121. package/dist/claude/tasks-overlay-scraper.js +217 -0
  122. package/dist/claude/thread-judge-haiku.js +88 -0
  123. package/dist/claude/tip-scraper.js +77 -0
  124. package/dist/claude/tui-modal.js +746 -0
  125. package/dist/claude/tui-state.js +456 -0
  126. package/dist/claude/turn-end.js +105 -0
  127. package/dist/claude/turn-prose.js +64 -0
  128. package/dist/claude/typed-answer.js +104 -0
  129. package/dist/claude/update-banner-relay.js +70 -0
  130. package/dist/cli/commands/doctor.js +338 -0
  131. package/dist/cli/commands/help.js +34 -0
  132. package/dist/cli/commands/init.js +126 -0
  133. package/dist/cli/commands/service.js +710 -0
  134. package/dist/cli/commands/start.js +63 -0
  135. package/dist/cli/commands/version.js +11 -0
  136. package/dist/cli/commands/watch.js +322 -0
  137. package/dist/cli/dispatch.js +84 -0
  138. package/dist/cli/init/env-file.js +99 -0
  139. package/dist/cli/init/flow.js +705 -0
  140. package/dist/cli/init/prompter.js +124 -0
  141. package/dist/cli/init/telegram.js +120 -0
  142. package/dist/cli/service/render.js +212 -0
  143. package/dist/cli.js +18 -0
  144. package/dist/config-report.js +107 -0
  145. package/dist/config.js +525 -0
  146. package/dist/index.js +443 -0
  147. package/dist/launcher.js +960 -0
  148. package/dist/node-version-check.js +27 -0
  149. package/dist/providers/ccr-health.js +119 -0
  150. package/dist/providers/ccr-introspect.js +142 -0
  151. package/dist/providers/ccr-provider.js +59 -0
  152. package/dist/providers/claude-provider.js +10 -0
  153. package/dist/providers/prefs-sync.js +121 -0
  154. package/dist/providers/project-favorites.js +74 -0
  155. package/dist/providers/provider-router.js +128 -0
  156. package/dist/providers/provider-switch.js +91 -0
  157. package/dist/providers/spawn-settings.js +45 -0
  158. package/dist/providers/types.js +8 -0
  159. package/dist/providers/user-preferences.js +322 -0
  160. package/dist/restart-when-idle.js +173 -0
  161. package/dist/startup/auto-continue.js +67 -0
  162. package/dist/startup/auto-resume.js +161 -0
  163. package/dist/startup/notices.js +120 -0
  164. package/dist/startup/shared.js +44 -0
  165. package/dist/startup/verify-token.js +31 -0
  166. package/dist/telegram/access-request.js +153 -0
  167. package/dist/telegram/action-logger.js +522 -0
  168. package/dist/telegram/admin-mention.js +107 -0
  169. package/dist/telegram/background-activity-card.js +502 -0
  170. package/dist/telegram/botname-settings.js +282 -0
  171. package/dist/telegram/button-text.js +26 -0
  172. package/dist/telegram/client-options.js +26 -0
  173. package/dist/telegram/deduplication.js +33 -0
  174. package/dist/telegram/entities.js +295 -0
  175. package/dist/telegram/force-reply-tracker.js +96 -0
  176. package/dist/telegram/lettered-options.js +87 -0
  177. package/dist/telegram/markdown.js +362 -0
  178. package/dist/telegram/message-sender.js +1019 -0
  179. package/dist/telegram/prompt-label.js +148 -0
  180. package/dist/telegram/prompt-suggestion.js +54 -0
  181. package/dist/telegram/send.js +123 -0
  182. package/dist/telegram/streaming-turn.js +103 -0
  183. package/dist/telegram/suggestions-settings.js +30 -0
  184. package/dist/telegram/table-lists.js +56 -0
  185. package/dist/telegram/task-list.js +367 -0
  186. package/dist/telegram/task-tracker.js +128 -0
  187. package/dist/telegram/terminal-renderer.js +667 -0
  188. package/dist/telegram/thread-titles.js +262 -0
  189. package/dist/telegram/threads-setup.js +117 -0
  190. package/dist/utils/admins.js +143 -0
  191. package/dist/utils/agent-timer.js +55 -0
  192. package/dist/utils/atomic-write.js +24 -0
  193. package/dist/utils/bot-icon.js +248 -0
  194. package/dist/utils/bot-token.js +77 -0
  195. package/dist/utils/bounded-map.js +55 -0
  196. package/dist/utils/build-info.js +57 -0
  197. package/dist/utils/caffeinate.js +53 -0
  198. package/dist/utils/claude-env.js +53 -0
  199. package/dist/utils/claude-version.js +48 -0
  200. package/dist/utils/config-home.js +62 -0
  201. package/dist/utils/download.js +137 -0
  202. package/dist/utils/exit-codes.js +59 -0
  203. package/dist/utils/file-type.js +149 -0
  204. package/dist/utils/format.js +78 -0
  205. package/dist/utils/home-project.js +30 -0
  206. package/dist/utils/host-stall.js +51 -0
  207. package/dist/utils/id-list.js +44 -0
  208. package/dist/utils/idle-restart.js +92 -0
  209. package/dist/utils/install-mode.js +63 -0
  210. package/dist/utils/instance-config.js +148 -0
  211. package/dist/utils/instances.js +95 -0
  212. package/dist/utils/json-store.js +140 -0
  213. package/dist/utils/keyed-settings.js +62 -0
  214. package/dist/utils/legacy-env.js +35 -0
  215. package/dist/utils/memory-pressure.js +60 -0
  216. package/dist/utils/npm-version.js +134 -0
  217. package/dist/utils/prefs-relay.js +107 -0
  218. package/dist/utils/proc-children.js +102 -0
  219. package/dist/utils/resolve-bin.js +86 -0
  220. package/dist/utils/resolve-claude-bin.js +52 -0
  221. package/dist/utils/respawn-backoff.js +28 -0
  222. package/dist/utils/sanitize.js +91 -0
  223. package/dist/utils/session-key.js +37 -0
  224. package/dist/utils/stale-launcher.js +109 -0
  225. package/dist/utils/state-dir-migration.js +92 -0
  226. package/dist/utils/systemd.js +126 -0
  227. package/dist/utils/telegram-proxy.js +72 -0
  228. package/dist/utils/uploads-dir.js +27 -0
  229. package/dist/utils/user-roster.js +275 -0
  230. package/dist/utils/verbosity.js +118 -0
  231. package/dist/utils/version-check.js +166 -0
  232. package/dist/utils/workspace-guard.js +44 -0
  233. package/dist/worker-restart.js +141 -0
  234. package/instances.json.example +41 -0
  235. package/package.json +75 -4
@@ -0,0 +1,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,481 @@
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 { resolveSendablePath, sendableRefusalMessage } from '../bot/file-access.js';
26
+ import { createPendingQuestion, buildAskUserMessageText, buildAskUserKeyboard, buildAskUserExpiredNote, answerOrHangUp, closeAnsweredQuestion, closeExpiredQuestion, closeWithdrawnQuestion, questionTimeoutMinutes, resolvePendingQuestionWithText, withdrawPendingQuestion, } from './ask-user.js';
27
+ import { resolveAskUserArgs, runAskUserForm } from './ask-user-form.js';
28
+ import { acceptTypedAnswers, acknowledgeTypedAnswer, shownTypedAnswer } from './typed-answer.js';
29
+ import { createPendingPoll } from './poll-user.js';
30
+ import { scheduler } from './scheduler.js';
31
+ import { readLastAssistantTurnText } from './session-jsonl.js';
32
+ import { getDeliveredProse, recordDeliveredProse, stripDeliveredPrefix } from './turn-prose.js';
33
+ import { parseSessionKey } from '../utils/session-key.js';
34
+ import { parseSecretRequest, requestSecret } from './secret-request.js';
35
+ const TELEGRAM_MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
36
+ function getTelegramCtx(options) {
37
+ if (!options || typeof options !== 'object')
38
+ return undefined;
39
+ const ctx = options.telegramCtx;
40
+ if (!ctx || typeof ctx !== 'object')
41
+ return undefined;
42
+ return ctx;
43
+ }
44
+ /**
45
+ * Ready the chat for something a tool is about to post. In a turn claude
46
+ * started itself, that means sending what the turn has written so far and
47
+ * sealing the background card, so what the turn writes around the post stays
48
+ * in order.
49
+ */
50
+ async function beforePosting(turn) {
51
+ if (turn.selfStarted)
52
+ await settleBeforePost(turn.sessionKey);
53
+ }
54
+ // ── /mcp/set_topic ───────────────────────────────────────────────────
55
+ registerIpcHandler('/mcp/set_topic', async (turn, body) => {
56
+ const topic = String(body.topic ?? '').trim();
57
+ // Topic now lives in the status line, not the Telegram bot name, so
58
+ // setSessionTopic is the only thing we do here — no setMyName call.
59
+ // (The persisted topic survives restarts and is what the status-line
60
+ // renderer reads.)
61
+ const { setSessionTopic } = await import('../bot/handlers/command.handler.js');
62
+ setSessionTopic(turn.sessionKey, topic);
63
+ return {
64
+ success: true,
65
+ message: topic ? `Topic set to "${topic}".` : 'Topic cleared.',
66
+ };
67
+ });
68
+ /**
69
+ * Post the assistant prose written so far in this PTY turn as its own message,
70
+ * so a question that follows it doesn't arrive ahead of its own reasoning.
71
+ *
72
+ * Reads the same JSONL the end-of-turn path reads, subtracts whatever an
73
+ * earlier flush in this turn already sent, and records the new high-water mark
74
+ * for {@link stripDeliveredPrefix} to remove at end-of-turn.
75
+ *
76
+ * Best-effort throughout: no claude session id yet, an unreadable log, or a
77
+ * failed send all just mean the prose stays where it was — the question still
78
+ * goes out, carrying its own `context` block.
79
+ */
80
+ async function flushTurnProse(sessionKey, ctx, messageSender) {
81
+ try {
82
+ const botSession = sessionManager.getSession(sessionKey);
83
+ if (!botSession?.claudeSessionId)
84
+ return;
85
+ const soFar = readLastAssistantTurnText(botSession.workingDirectory, botSession.claudeSessionId);
86
+ if (!soFar)
87
+ return;
88
+ const fresh = stripDeliveredPrefix(soFar, getDeliveredProse(sessionKey)).trim();
89
+ if (!fresh)
90
+ return;
91
+ await messageSender.sendMessage(ctx, fresh);
92
+ recordDeliveredProse(sessionKey, soFar);
93
+ }
94
+ catch (err) {
95
+ console.debug('[AskUser] Prose flush skipped:', err instanceof Error ? err.message : err);
96
+ }
97
+ }
98
+ // ── /mcp/ask_user ────────────────────────────────────────────────────
99
+ // Long-polling IPC handler: registers a pending question in the shared
100
+ // ask-user registry, sends a Telegram inline keyboard, and
101
+ // awaits the user's button tap. The existing callback-query dispatcher
102
+ // (handling `q:<id>:<idx>` callback_data) resolves the promise so we can
103
+ // return the chosen label to claude, and a message the user sends instead is
104
+ // their answer in their own words (typed-answer.ts). Times out after
105
+ // QUESTION_TIMEOUT_MINUTES via createPendingQuestion's default, and closes
106
+ // early when claude cancels the call.
107
+ registerIpcHandler('/mcp/ask_user', async (turn, body, signal) => {
108
+ const context = typeof body.context === 'string' ? body.context : undefined;
109
+ const asked = resolveAskUserArgs(body);
110
+ if (typeof asked === 'string')
111
+ return { success: false, message: asked };
112
+ const ctx = getTelegramCtx(turn.options);
113
+ if (!ctx?.chat?.id) {
114
+ return { success: false, message: 'Error: no Telegram context available to ask the user.' };
115
+ }
116
+ // From the session key, not `ctx.message` — a turn started by a tapped
117
+ // button carries a callback-query context with no `message`, which would
118
+ // silently drop the thread and post the question into General.
119
+ const threadId = parseSessionKey(turn.sessionKey).threadId;
120
+ if (asked.form) {
121
+ // Same prose flush as the single question below: what the model wrote
122
+ // to set up the form is still undelivered, and belongs above it.
123
+ const { messageSender } = await import('../telegram/message-sender.js');
124
+ await beforePosting(turn);
125
+ if (!turn.selfStarted)
126
+ await flushTurnProse(turn.sessionKey, ctx, messageSender);
127
+ const message = await runAskUserForm({
128
+ api: ctx.api,
129
+ chatId: ctx.chat.id,
130
+ threadId,
131
+ sessionKey: turn.sessionKey,
132
+ questions: asked.form,
133
+ context,
134
+ signal,
135
+ onPosted: () => messageSender.noteQuestionPosted(ctx, turn.sessionKey),
136
+ onSettled: () => messageSender.noteQuestionAnswered(ctx, turn.sessionKey),
137
+ });
138
+ return message === null ? withdrawnAnswer() : { success: true, message };
139
+ }
140
+ const { question, options } = asked;
141
+ const optionLabels = options.map((o) => o.label);
142
+ const { id, promise } = createPendingQuestion(optionLabels, undefined, turn.sessionKey);
143
+ // The turn's prose stays in the JSONL log until end-of-turn, so
144
+ // anything the model wrote to set up this question is still undelivered.
145
+ // Flush it above the buttons; the provider strips it from the end-of-turn
146
+ // text so it isn't shown twice. Imported lazily to keep this module's eager
147
+ // graph minimal — it is loaded from pty-provider at module scope, so every
148
+ // eager edge here is a chance to close a cycle back through it.
149
+ //
150
+ // A turn claude started itself has its prose sent by the monitor relay
151
+ // instead, which beforePosting has it do now.
152
+ const { messageSender } = await import('../telegram/message-sender.js');
153
+ await beforePosting(turn);
154
+ if (!turn.selfStarted)
155
+ await flushTurnProse(turn.sessionKey, ctx, messageSender);
156
+ const messageText = buildAskUserMessageText(question, options, context);
157
+ const keyboard = buildAskUserKeyboard(id, options);
158
+ // Plain text (no parse_mode): model-supplied question/context/label/
159
+ // description text can contain stray underscores, asterisks, or backticks
160
+ // (e.g. URL params like `f_WT=2`) that break legacy Markdown parsing —
161
+ // Telegram returns 400, grammy throws, the IPC server returns 500, and the
162
+ // model just sees the tool fail. The bold on labels was a nice-to-have; the
163
+ // body lists every option in full, keyed by the letter on its button.
164
+ const sent = await ctx.api.sendMessage(ctx.chat.id, messageText, {
165
+ reply_markup: { inline_keyboard: keyboard },
166
+ ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
167
+ });
168
+ // Tell the streaming UI a question is on screen, so the final answer is
169
+ // posted below it rather than edited into the bubble above it, and the
170
+ // status line says we're blocked on the user.
171
+ await messageSender.noteQuestionPosted(ctx, turn.sessionKey);
172
+ // A message sent now is an answer in the user's own words (typed-answer.ts).
173
+ const stopTypedAnswers = acceptTypedAnswers({
174
+ sessionKey: turn.sessionKey,
175
+ chatId: ctx.chat.id,
176
+ messageId: sent.message_id,
177
+ take: async (msgCtx, text) => {
178
+ if (resolvePendingQuestionWithText(id, text, msgCtx.from?.id) !== 'resolved')
179
+ return false;
180
+ await acknowledgeTypedAnswer(msgCtx);
181
+ return true;
182
+ },
183
+ });
184
+ const answer = await answerOrHangUp(promise, signal);
185
+ stopTypedAnswers();
186
+ await messageSender.noteQuestionAnswered(ctx, turn.sessionKey);
187
+ if (answer === 'hung-up') {
188
+ withdrawPendingQuestion(id);
189
+ await closeWithdrawnQuestion(ctx.api, sent, messageText);
190
+ return withdrawnAnswer();
191
+ }
192
+ if (!answer) {
193
+ await closeExpiredQuestion(ctx.api, sent, messageText, buildAskUserExpiredNote());
194
+ return {
195
+ success: true,
196
+ message: `User did not respond within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment or ask again.`,
197
+ };
198
+ }
199
+ if (answer.typed) {
200
+ // A tap closes its question in bot.ts; a typed answer has no tap to do it.
201
+ await closeAnsweredQuestion(ctx.api, sent, messageText, shownTypedAnswer(answer.label));
202
+ return { success: true, message: `User answered in their own words: ${answer.label}` };
203
+ }
204
+ return { success: true, message: `User selected: ${answer.label}` };
205
+ });
206
+ /** What claude reads for a question it stopped waiting on, should the reply still reach it. */
207
+ function withdrawnAnswer() {
208
+ return { success: false, message: 'The question was withdrawn before the user answered.' };
209
+ }
210
+ // ── /mcp/request_secret ──────────────────────────────────────────────
211
+ // Long-polls like ask_user: the user's answer is a message that
212
+ // captureSecretMessages takes out of the chat, or a sign-in code for the
213
+ // claude setup-token run the request starts. Hanging up (claude cancelled the
214
+ // call, or its pty went away) withdraws the request, so the next message the
215
+ // user sends isn't taken for a secret nobody is waiting on.
216
+ registerIpcHandler('/mcp/request_secret', async (turn, body, signal) => {
217
+ const req = parseSecretRequest(body);
218
+ if (typeof req === 'string')
219
+ return { success: false, message: req };
220
+ const ctx = getTelegramCtx(turn.options);
221
+ if (!ctx?.chat?.id) {
222
+ return { success: false, message: 'Error: no Telegram context available to ask the user.' };
223
+ }
224
+ // Same reasons as ask_user: the prose that leads up to the request goes
225
+ // out above it, not after the user has answered.
226
+ const { messageSender } = await import('../telegram/message-sender.js');
227
+ await beforePosting(turn);
228
+ if (!turn.selfStarted)
229
+ await flushTurnProse(turn.sessionKey, ctx, messageSender);
230
+ return requestSecret(ctx, turn.sessionKey, req, signal, {
231
+ onPosted: () => messageSender.noteQuestionPosted(ctx, turn.sessionKey),
232
+ onSettled: () => messageSender.noteQuestionAnswered(ctx, turn.sessionKey),
233
+ });
234
+ });
235
+ // ── /mcp/switch_project ──────────────────────────────────────────────
236
+ // Updates the session's working directory. PtyProvider's _getOrCreateSession
237
+ // detects the cwd mismatch on the next turn and respawns the pty in the new
238
+ // dir — so the switch is logically "happens on next query".
239
+ registerIpcHandler('/mcp/switch_project', async (turn, body) => {
240
+ const projectName = String(body.project_name ?? '').trim();
241
+ if (!projectName) {
242
+ return { success: false, message: 'Error: project_name is required.' };
243
+ }
244
+ const workspaceRoot = getWorkspaceRoot();
245
+ const targetPath = path.resolve(workspaceRoot, projectName);
246
+ if (!isPathWithinRoot(workspaceRoot, targetPath)) {
247
+ return { success: false, message: `Error: Path must be within workspace root: ${workspaceRoot}` };
248
+ }
249
+ if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isDirectory()) {
250
+ return { success: false, message: `Error: Project not found: ${projectName}` };
251
+ }
252
+ sessionManager.setWorkingDirectory(turn.sessionKey, targetPath);
253
+ // A new project is a new topic, as after /dir.
254
+ const { clearTopic } = await import('../bot/handlers/command.handler.js');
255
+ clearTopic(turn.sessionKey);
256
+ return {
257
+ success: true,
258
+ message: `Switched to project: ${projectName} (${targetPath}). The new working directory will take effect on the next query.`,
259
+ };
260
+ });
261
+ // ── /mcp/create_bot ──────────────────────────────────────────────────
262
+ // Offers the create-a-bot button in this turn's chat. The bot itself is
263
+ // adopted later, when Telegram reports it: see newbot.handler.ts.
264
+ registerIpcHandler('/mcp/create_bot', async (turn, body) => {
265
+ const projectName = String(body.project_name ?? '').trim();
266
+ if (!projectName)
267
+ return { success: false, message: 'Error: project_name is required.' };
268
+ const ctx = getTelegramCtx(turn.options);
269
+ if (!ctx)
270
+ return { success: false, message: 'Error: no Telegram chat for this turn.' };
271
+ const { offerNewBotForSession } = await import('../bot/handlers/newbot.handler.js');
272
+ const result = await offerNewBotForSession(ctx.api, turn.sessionKey, projectName);
273
+ return { success: result.ok, message: result.message };
274
+ });
275
+ // ── /mcp/send_file ───────────────────────────────────────────────────
276
+ // Sends a file from the bot's filesystem to the user via Telegram, under the
277
+ // same rules as /file (bot/file-access.ts) plus /tmp, routed through IPC so
278
+ // the MCP subprocess can stay out of process.
279
+ registerIpcHandler('/mcp/send_file', async (turn, body) => {
280
+ const filePath = String(body.file_path ?? '');
281
+ const caption = typeof body.caption === 'string' && body.caption.length > 0 ? body.caption : undefined;
282
+ const session = sessionManager.getSession(turn.sessionKey);
283
+ if (!session) {
284
+ return { success: false, message: 'Error: No active session.' };
285
+ }
286
+ const ctx = getTelegramCtx(turn.options);
287
+ if (!ctx) {
288
+ return { success: false, message: 'Error: No Telegram context for this turn.' };
289
+ }
290
+ // The credential denylist for everyone, the chat's project for a guest, the
291
+ // workspace for an admin — judged by who sent the message this turn answers
292
+ // — and /tmp for files claude made to send.
293
+ const resolved = resolveSendablePath(filePath, session.workingDirectory, ctx.from?.id);
294
+ if (!resolved.ok) {
295
+ if (resolved.reason === 'sensitive') {
296
+ console.log(`[MCP] send_file REFUSED credential path for user:${ctx.from?.id ?? 'unknown'}`);
297
+ }
298
+ return { success: false, message: sendableRefusalMessage(resolved.reason, filePath, resolved.root) };
299
+ }
300
+ const resolvedPath = resolved.path;
301
+ const stat = fs.statSync(resolvedPath);
302
+ if (stat.size > TELEGRAM_MAX_FILE_SIZE) {
303
+ const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);
304
+ return { success: false, message: `Error: File too large (${sizeMB}MB). Telegram limit is 50MB.` };
305
+ }
306
+ const fileName = path.basename(resolvedPath);
307
+ try {
308
+ const fileBuffer = fs.readFileSync(resolvedPath);
309
+ const inputFile = new InputFile(fileBuffer, fileName);
310
+ await beforePosting(turn);
311
+ await ctx.replyWithDocument(inputFile, caption ? { caption } : undefined);
312
+ }
313
+ catch (err) {
314
+ return {
315
+ success: false,
316
+ message: `Error sending file: ${err instanceof Error ? err.message : String(err)}`,
317
+ };
318
+ }
319
+ const sizeMB = (stat.size / (1024 * 1024)).toFixed(2);
320
+ return {
321
+ success: true,
322
+ message: `File sent to user: ${fileName} (${sizeMB}MB)`,
323
+ };
324
+ });
325
+ // ── /mcp/poll_user ───────────────────────────────────────────────────
326
+ // Telegram poll variant of ask_user. Non-anonymous (required for the bot
327
+ // to receive poll_answer events); resolves on the first vote so the agent
328
+ // loop doesn't hang. Multi-select snapshots whatever's selected when the
329
+ // first poll_answer arrives.
330
+ registerIpcHandler('/mcp/poll_user', async (turn, body) => {
331
+ const question = String(body.question ?? '').trim();
332
+ const rawOptions = Array.isArray(body.options) ? body.options : [];
333
+ const options = rawOptions.filter((o) => typeof o === 'string' && o.length > 0).slice(0, 10);
334
+ const allowsMultiple = !!body.allows_multiple_answers;
335
+ if (!question)
336
+ return { success: false, message: 'Error: question is required.' };
337
+ if (options.length < 2)
338
+ return { success: false, message: 'Error: at least 2 options required.' };
339
+ const ctx = getTelegramCtx(turn.options);
340
+ if (!ctx?.chat?.id) {
341
+ return { success: false, message: 'Error: no Telegram context available to ask the user.' };
342
+ }
343
+ // Session key, not `ctx.message` — see the note in the ask_user handler.
344
+ const threadId = parseSessionKey(turn.sessionKey).threadId;
345
+ await beforePosting(turn);
346
+ const sent = await ctx.api.sendPoll(ctx.chat.id, question, options.map((o) => ({ text: o })), {
347
+ is_anonymous: false,
348
+ allows_multiple_answers: allowsMultiple,
349
+ ...(threadId !== undefined ? { message_thread_id: threadId } : {}),
350
+ });
351
+ const pollId = sent.poll.id;
352
+ const answer = await createPendingPoll(pollId, options, allowsMultiple, turn.sessionKey);
353
+ if (!answer) {
354
+ // Close the poll: nothing is counting votes any more, and an open one
355
+ // still invites them. A stopped poll shows its final results instead.
356
+ try {
357
+ await ctx.api.stopPoll(sent.chat.id, sent.message_id);
358
+ }
359
+ catch {
360
+ // Cosmetic — the agent gets its answer either way.
361
+ }
362
+ return {
363
+ success: true,
364
+ message: `No one voted within ${questionTimeoutMinutes()} minutes. Proceed using your best judgment.`,
365
+ };
366
+ }
367
+ if (answer.labels.length === 0) {
368
+ return { success: true, message: 'Vote received but no options recorded.' };
369
+ }
370
+ if (answer.labels.length === 1) {
371
+ return { success: true, message: `User selected: ${answer.labels[0]}` };
372
+ }
373
+ return { success: true, message: `User selected: ${answer.labels.join(', ')}` };
374
+ });
375
+ // ── /mcp/schedule_loop ───────────────────────────────────────────────
376
+ // Claude-initiated interval scheduling. Same scheduler as the Telegram-side
377
+ // /loop command — only the entrypoint differs, so caps and persistence
378
+ // are uniformly enforced regardless of who created the schedule.
379
+ registerIpcHandler('/mcp/schedule_loop', async (turn, body) => {
380
+ const prompt = String(body.prompt ?? '').trim();
381
+ const intervalSeconds = typeof body.interval_seconds === 'number' ? body.interval_seconds : 0;
382
+ const maxRuns = typeof body.max_runs === 'number' ? body.max_runs : undefined;
383
+ const label = typeof body.label === 'string' ? body.label : undefined;
384
+ if (!prompt)
385
+ return { success: false, message: 'Error: prompt is required.' };
386
+ if (intervalSeconds < 60)
387
+ return { success: false, message: 'Error: interval_seconds must be at least 60.' };
388
+ const session = sessionManager.getSession(turn.sessionKey);
389
+ if (!session) {
390
+ return { success: false, message: 'Error: no session bound to this chat — schedule cannot be created.' };
391
+ }
392
+ try {
393
+ const created = scheduler.createSchedule({
394
+ sessionKey: turn.sessionKey,
395
+ cwd: session.workingDirectory,
396
+ claudeSessionId: session.claudeSessionId,
397
+ prompt,
398
+ label,
399
+ maxRuns,
400
+ kind: 'interval',
401
+ intervalMs: intervalSeconds * 1000,
402
+ });
403
+ const nextFire = scheduler.nextFireAt(created.id);
404
+ const nextLine = nextFire ? ` Next fire: ${new Date(nextFire).toLocaleString()}.` : '';
405
+ return {
406
+ success: true,
407
+ message: `Schedule created (id=${created.id}). Will fire every ${intervalSeconds}s, up to ${created.maxRuns} times.${nextLine}`,
408
+ };
409
+ }
410
+ catch (err) {
411
+ return { success: false, message: `Error: ${err instanceof Error ? err.message : String(err)}` };
412
+ }
413
+ });
414
+ // ── /mcp/schedule_cron ───────────────────────────────────────────────
415
+ registerIpcHandler('/mcp/schedule_cron', async (turn, body) => {
416
+ const prompt = String(body.prompt ?? '').trim();
417
+ const cronExpression = String(body.cron_expression ?? '').trim();
418
+ const maxRuns = typeof body.max_runs === 'number' ? body.max_runs : undefined;
419
+ const label = typeof body.label === 'string' ? body.label : undefined;
420
+ if (!prompt)
421
+ return { success: false, message: 'Error: prompt is required.' };
422
+ if (!cronExpression)
423
+ return { success: false, message: 'Error: cron_expression is required.' };
424
+ const session = sessionManager.getSession(turn.sessionKey);
425
+ if (!session) {
426
+ return { success: false, message: 'Error: no session bound to this chat — schedule cannot be created.' };
427
+ }
428
+ try {
429
+ const created = scheduler.createSchedule({
430
+ sessionKey: turn.sessionKey,
431
+ cwd: session.workingDirectory,
432
+ claudeSessionId: session.claudeSessionId,
433
+ prompt,
434
+ label,
435
+ maxRuns,
436
+ kind: 'cron',
437
+ cronExpr: cronExpression,
438
+ });
439
+ const nextFire = scheduler.nextFireAt(created.id);
440
+ const nextLine = nextFire ? ` Next fire: ${new Date(nextFire).toLocaleString()}.` : '';
441
+ return {
442
+ success: true,
443
+ message: `Schedule created (id=${created.id}, cron=${cronExpression}, up to ${created.maxRuns} fires).${nextLine}`,
444
+ };
445
+ }
446
+ catch (err) {
447
+ return { success: false, message: `Error: ${err instanceof Error ? err.message : String(err)}` };
448
+ }
449
+ });
450
+ // ── /mcp/schedule_list ───────────────────────────────────────────────
451
+ registerIpcHandler('/mcp/schedule_list', async (turn) => {
452
+ const list = scheduler.listSchedules(turn.sessionKey);
453
+ if (list.length === 0) {
454
+ return { success: true, message: 'No active schedules for this chat.' };
455
+ }
456
+ const lines = list.map((s) => {
457
+ const status = s.disabled ? ' [DISABLED]' : '';
458
+ const cadence = s.kind === 'interval'
459
+ ? `every ${Math.round((s.intervalMs ?? 0) / 1000)}s`
460
+ : `cron ${s.cronExpr ?? '?'}`;
461
+ const next = scheduler.nextFireAt(s.id);
462
+ const nextLine = next ? `, next ${new Date(next).toLocaleString()}` : '';
463
+ const promptPreview = s.prompt.length > 60 ? s.prompt.slice(0, 57) + '...' : s.prompt;
464
+ const labelPart = s.label ? ` "${s.label}"` : '';
465
+ return `${s.id}${labelPart}: ${cadence}, ${s.runs}/${s.maxRuns} runs${nextLine}${status}\n prompt: ${promptPreview}`;
466
+ });
467
+ return { success: true, message: `Active schedules (${list.length}):\n\n${lines.join('\n\n')}` };
468
+ });
469
+ // ── /mcp/schedule_cancel ─────────────────────────────────────────────
470
+ registerIpcHandler('/mcp/schedule_cancel', async (turn, body) => {
471
+ const id = String(body.id ?? '').trim();
472
+ if (!id)
473
+ return { success: false, message: 'Error: id is required.' };
474
+ const target = scheduler.getSchedule(id);
475
+ if (!target || target.sessionKey !== turn.sessionKey) {
476
+ return { success: false, message: `No schedule "${id}" in this chat.` };
477
+ }
478
+ scheduler.deleteSchedule(id);
479
+ return { success: true, message: `Schedule ${id} cancelled.` };
480
+ });
481
+ //# sourceMappingURL=mcp-bridge.js.map