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,111 @@
1
+ /**
2
+ * Claude Code's `/rewind`, once its dialog has been answered from the chat.
3
+ *
4
+ * `/rewind` is Claude Code's own: it goes to the pty like any prompt, and its
5
+ * two screens come to the chat through the dialog relay (modal-relay.ts) — the
6
+ * list of prompts to go back to, then what to restore. Two things are left
7
+ * over when it closes that only matter outside a terminal, and both are here.
8
+ *
9
+ * It says nothing. In a terminal the transcript redraws shorter and that is
10
+ * the confirmation; the log gets no record at all, so a chat would see "Done"
11
+ * for a conversation that just lost its last ten turns. {@link rewindReport}
12
+ * is what the chat is told instead, from the answers the relay pressed.
13
+ *
14
+ * And it hands the prompt back. A restored conversation leaves the prompt it
15
+ * went back to in the input box, for the person at the keyboard to edit and
16
+ * send again. Nobody is at this keyboard: whatever is typed next would be
17
+ * joined onto it. {@link restoredPromptNeedle} is how the caller finds it
18
+ * there to clear it.
19
+ *
20
+ * Measured against Claude Code 2.1.326.
21
+ */
22
+ /** The heading both of `/rewind`'s screens carry. */
23
+ const REWIND_TITLE = 'Rewind';
24
+ /**
25
+ * The rows of the second screen, by how they open. A row reads longer with
26
+ * the cursor on it (`Summarize from here: add context (optional)`), and the
27
+ * order matters: `Restore code` also opens `Restore code and conversation`.
28
+ */
29
+ const CHOICES = [
30
+ [/^Restore code and conversation\b/, 'code-and-conversation'],
31
+ [/^Restore conversation\b/, 'conversation'],
32
+ [/^Restore code\b/, 'code'],
33
+ [/^Summarize from here\b/, 'summarize-from'],
34
+ [/^Summarize up to here\b/, 'summarize-up-to'],
35
+ ];
36
+ /**
37
+ * The rewind a dialog's answers carried out, or null when they weren't one:
38
+ * another dialog, a rewind backed out of with `Never mind`, or one that closed
39
+ * on `(current)`, which goes nowhere.
40
+ *
41
+ * The screens are told apart by their rows. The prompts are not numbered and
42
+ * the choices are, which is also how the parser tells them apart.
43
+ */
44
+ export function rewindIn(steps) {
45
+ const ours = steps.filter((step) => step.dialog.title === REWIND_TITLE && step.option);
46
+ const latest = [...ours].reverse();
47
+ const chosen = latest.find((step) => step.option.number !== undefined);
48
+ const picked = latest.find((step) => step.option.number === undefined);
49
+ if (!chosen || !picked)
50
+ return null;
51
+ const choice = CHOICES.find(([opens]) => opens.test(chosen.option.text))?.[1];
52
+ return choice ? { prompt: picked.option.text, choice } : null;
53
+ }
54
+ /** Whether this rewind takes the conversation back, which is what puts the prompt in the input box. */
55
+ export function restoresConversation(rewind) {
56
+ return rewind.choice !== 'code';
57
+ }
58
+ /**
59
+ * Enough of the prompt to find it in the input box. The list cuts a long
60
+ * prompt with an ellipsis the box doesn't have, and shows only its first line.
61
+ */
62
+ export function restoredPromptNeedle(rewind) {
63
+ return rewind.prompt.replace(/…$/u, '').trim().slice(0, 24);
64
+ }
65
+ /**
66
+ * A line Claude Code prints when a rewind didn't go through, read off the
67
+ * screen it left: `Failed to restore the code: …`, `Couldn't summarize: …`,
68
+ * `Restored the code, but skipped …`. Only the last rows are looked at, since
69
+ * an older one may have scrolled up from a rewind before this.
70
+ */
71
+ export function rewindFailure(screenText) {
72
+ const tail = screenText.split('\n').map((line) => line.trim()).filter(Boolean).slice(-12);
73
+ return tail.find((line) => /Failed to restore|Couldn't summarize|Restored the code, but skipped/.test(line));
74
+ }
75
+ /**
76
+ * What the chat is told. `promptCleared` says the prompt was found in the
77
+ * input box and taken out again, which is the proof that the conversation
78
+ * went back; without it the report claims no more than what was pressed.
79
+ */
80
+ export function rewindReport(rewind, seen) {
81
+ const prompt = `“${rewind.prompt}”`;
82
+ if (seen.failure) {
83
+ return `⚠️ Claude Code couldn't finish the rewind to before ${prompt}:\n${seen.failure}`;
84
+ }
85
+ const lines = [];
86
+ switch (rewind.choice) {
87
+ case 'code-and-conversation':
88
+ lines.push(`⏪ Rewound to before ${prompt}: the conversation, and the files Claude edited since.`);
89
+ break;
90
+ case 'conversation':
91
+ lines.push(`⏪ The conversation is back to before ${prompt}. The files are as they were.`);
92
+ break;
93
+ case 'code':
94
+ lines.push(`⏪ The files Claude edited are back to how they were before ${prompt}. The conversation is unchanged.`);
95
+ break;
96
+ case 'summarize-from':
97
+ lines.push(`⏪ Summarized the conversation from ${prompt} on.`);
98
+ break;
99
+ case 'summarize-up-to':
100
+ lines.push(`⏪ Summarized the conversation up to ${prompt}.`);
101
+ break;
102
+ }
103
+ if (rewind.choice === 'code-and-conversation' || rewind.choice === 'code') {
104
+ lines.push('Changes made by shell commands are not undone.');
105
+ }
106
+ if (seen.promptCleared) {
107
+ lines.push('That prompt was not sent again. Send it, changed or not, to carry on from there.');
108
+ }
109
+ return lines.join('\n');
110
+ }
111
+ //# sourceMappingURL=rewind.js.map
@@ -0,0 +1,89 @@
1
+ import { sendToAgent } from '../providers/provider-router.js';
2
+ import { sessionManager } from './session-manager.js';
3
+ import { sessionHistory } from './session-history.js';
4
+ import { queueRequest } from './request-queue.js';
5
+ import { messageSender } from '../telegram/message-sender.js';
6
+ import { progressCallbacks, toolCallbacks, withStreamingTurn } from '../telegram/streaming-turn.js';
7
+ import { closeTurn, relayCatchUpIfMissed } from '../bot/handlers/message.handler.js';
8
+ import { parseSessionKey } from '../utils/session-key.js';
9
+ import { buildSyntheticCtx } from './synthetic-ctx.js';
10
+ import { scheduler } from './scheduler.js';
11
+ /**
12
+ * Wires the scheduler to the rest of the bot. On boot, registers a fire
13
+ * handler that resolves the session, posts a "🔔 Scheduled" header, then
14
+ * enqueues the schedule's prompt through the normal turn pipeline so the
15
+ * response renders identically to a user-typed message.
16
+ *
17
+ * Failures don't auto-disable on a single miss — the scheduler tracks
18
+ * consecutive failures and disables only after MAX_CONSECUTIVE_FAILURES so
19
+ * transient errors don't silently kill an otherwise healthy schedule.
20
+ */
21
+ export function startScheduledRunner(bot) {
22
+ scheduler.loadAll((schedule) => fireSchedule(bot, schedule));
23
+ }
24
+ async function fireSchedule(bot, schedule) {
25
+ const { sessionKey, prompt, label } = schedule;
26
+ const { chatId, threadId } = parseSessionKey(sessionKey);
27
+ const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
28
+ // Resolve the session — restore from disk if the PTY isn't live anymore.
29
+ // The scheduler doesn't capture a long-lived ctx, so cold-restore is
30
+ // expected after a bot restart.
31
+ let { session } = sessionManager.getOrRestoreSession(sessionKey);
32
+ if (!session) {
33
+ // Fall back to the most recent persisted entry regardless of age — a
34
+ // user who explicitly scheduled a task wants it to fire even if the
35
+ // session has been idle for weeks.
36
+ if (sessionHistory.getLastSession(sessionKey)) {
37
+ session = sessionManager.resumeLastSession(sessionKey) ?? undefined;
38
+ }
39
+ }
40
+ if (!session) {
41
+ // Can't fire — let the user know but keep the schedule armed; they may
42
+ // restore the project shortly.
43
+ try {
44
+ await bot.api.sendMessage(chatId, '⚠️ Scheduled fire skipped — no project bound to this chat. Use /dir to bind one, then the next fire will run.', threadOpts);
45
+ }
46
+ catch (err) {
47
+ console.error('[ScheduledRunner] failed to notify missing session:', err);
48
+ }
49
+ throw new Error('no session');
50
+ }
51
+ const ctx = buildSyntheticCtx({ api: bot.api, sessionKey, syntheticText: prompt });
52
+ const labelText = label ?? prompt.slice(0, 60);
53
+ await messageSender.postScheduledFire(ctx, labelText, prompt);
54
+ // Enqueue through the same FIFO the user's own messages flow through.
55
+ // If a user turn is already running, the scheduled fire waits behind it
56
+ // instead of racing — same ordering guarantees `/btw`-bypassing commands
57
+ // get when they bypass the queue.
58
+ try {
59
+ await queueRequest(sessionKey, `[scheduled] ${prompt}`, async () => {
60
+ await runScheduledTurn(ctx, sessionKey, prompt);
61
+ });
62
+ }
63
+ catch (err) {
64
+ const msg = err instanceof Error ? err.message : String(err);
65
+ try {
66
+ await bot.api.sendMessage(chatId, `⚠️ Scheduled fire failed: ${msg}`, threadOpts);
67
+ }
68
+ catch { /* ignore */ }
69
+ throw err instanceof Error ? err : new Error(msg);
70
+ }
71
+ }
72
+ async function runScheduledTurn(ctx, sessionKey, prompt) {
73
+ const startTime = Date.now();
74
+ await withStreamingTurn(ctx, sessionKey, prompt, async (abortController) => {
75
+ const response = await sendToAgent(sessionKey, prompt, {
76
+ ...progressCallbacks(ctx),
77
+ ...toolCallbacks(ctx, sessionKey),
78
+ abortController,
79
+ telegramCtx: ctx,
80
+ });
81
+ await messageSender.finishStreaming(ctx, response.text);
82
+ await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
83
+ await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
84
+ // The short form: a schedule can fire every minute, and the whole block
85
+ // under each fire would outweigh the result it closes.
86
+ await closeTurn(ctx, sessionKey, response, prompt, { brief: true });
87
+ });
88
+ }
89
+ //# sourceMappingURL=scheduled-runner.js.map
@@ -0,0 +1,241 @@
1
+ import * as path from 'path';
2
+ import { z } from 'zod';
3
+ import { Cron } from 'croner';
4
+ import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
5
+ import { BOT_ID } from '../config.js';
6
+ /**
7
+ * Persistent scheduler for /loop and the agent's telecoder_loop/telecoder_schedule tools. Schedules survive
8
+ * bot restarts via ~/.telecoder/schedules-<BOT_ID>.json; in-memory timers
9
+ * are re-armed on loadAll(). Hard caps enforced at create time so a user
10
+ * can't accidentally cron themselves into a runaway billing crater.
11
+ */
12
+ export const HARD_LIMITS = {
13
+ MAX_PER_SESSION: 10,
14
+ MIN_INTERVAL_MS: 60_000,
15
+ DEFAULT_MAX_RUNS: 50,
16
+ MAX_MAX_RUNS: 500,
17
+ MAX_CONSECUTIVE_FAILURES: 3,
18
+ };
19
+ const scheduleSchema = z.object({
20
+ id: z.string(),
21
+ sessionKey: z.string(),
22
+ cwd: z.string(),
23
+ claudeSessionId: z.string().optional(),
24
+ prompt: z.string(),
25
+ label: z.string().optional(),
26
+ kind: z.enum(['interval', 'cron']),
27
+ intervalMs: z.number().optional(),
28
+ cronExpr: z.string().optional(),
29
+ maxRuns: z.number(),
30
+ runs: z.number(),
31
+ consecutiveFailures: z.number(),
32
+ disabled: z.boolean(),
33
+ createdAt: z.string(),
34
+ lastFiredAt: z.string().optional(),
35
+ });
36
+ const scheduleFileSchema = z.object({
37
+ schedules: z.array(scheduleSchema),
38
+ });
39
+ const HISTORY_DIR = getStateDir();
40
+ function getFile() {
41
+ return path.join(HISTORY_DIR, `schedules-${BOT_ID}.json`);
42
+ }
43
+ function genId() {
44
+ return `sch_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
45
+ }
46
+ class Scheduler {
47
+ schedules = new Map();
48
+ intervalTimers = new Map();
49
+ cronJobs = new Map();
50
+ fireHandler = null;
51
+ loaded = false;
52
+ /** Re-arm all persisted schedules. Idempotent. Pass the handler that runs
53
+ * when a schedule fires — defining it outside this module avoids the
54
+ * scheduler→runner→provider dependency cycle. */
55
+ loadAll(handler) {
56
+ this.fireHandler = handler;
57
+ if (this.loaded) {
58
+ this.armAll();
59
+ return;
60
+ }
61
+ this.loaded = true;
62
+ const loaded = readJsonFile(getFile(), scheduleFileSchema, 'Scheduler');
63
+ if (!loaded)
64
+ return;
65
+ for (const s of loaded.schedules) {
66
+ this.schedules.set(s.id, s);
67
+ }
68
+ this.armAll();
69
+ console.log(`[Scheduler] loaded ${this.schedules.size} schedule(s)`);
70
+ }
71
+ createSchedule(spec) {
72
+ const existing = this.listSchedules(spec.sessionKey).filter((s) => !s.disabled);
73
+ if (existing.length >= HARD_LIMITS.MAX_PER_SESSION) {
74
+ throw new Error(`Schedule cap reached for this chat (${HARD_LIMITS.MAX_PER_SESSION} active). ` +
75
+ `Stop one in /loops before adding another.`);
76
+ }
77
+ if (spec.kind === 'interval') {
78
+ if (!spec.intervalMs || spec.intervalMs < HARD_LIMITS.MIN_INTERVAL_MS) {
79
+ throw new Error(`Interval must be at least ${HARD_LIMITS.MIN_INTERVAL_MS / 1000}s.`);
80
+ }
81
+ }
82
+ else {
83
+ if (!spec.cronExpr) {
84
+ throw new Error('Cron expression is required for cron schedules.');
85
+ }
86
+ try {
87
+ new Cron(spec.cronExpr);
88
+ }
89
+ catch (err) {
90
+ throw new Error(`Invalid cron expression: ${err instanceof Error ? err.message : err}`);
91
+ }
92
+ }
93
+ const maxRunsRequested = spec.maxRuns ?? HARD_LIMITS.DEFAULT_MAX_RUNS;
94
+ const maxRuns = Math.max(1, Math.min(HARD_LIMITS.MAX_MAX_RUNS, maxRunsRequested));
95
+ const schedule = {
96
+ id: genId(),
97
+ sessionKey: spec.sessionKey,
98
+ cwd: spec.cwd,
99
+ claudeSessionId: spec.claudeSessionId,
100
+ prompt: spec.prompt,
101
+ label: spec.label,
102
+ kind: spec.kind,
103
+ intervalMs: spec.intervalMs,
104
+ cronExpr: spec.cronExpr,
105
+ maxRuns,
106
+ runs: 0,
107
+ consecutiveFailures: 0,
108
+ disabled: false,
109
+ createdAt: new Date().toISOString(),
110
+ };
111
+ this.schedules.set(schedule.id, schedule);
112
+ this.persist();
113
+ this.arm(schedule);
114
+ return schedule;
115
+ }
116
+ listSchedules(sessionKey) {
117
+ return Array.from(this.schedules.values()).filter((s) => s.sessionKey === sessionKey);
118
+ }
119
+ getSchedule(id) {
120
+ return this.schedules.get(id);
121
+ }
122
+ deleteSchedule(id) {
123
+ const existed = this.schedules.delete(id);
124
+ this.disarm(id);
125
+ if (existed)
126
+ this.persist();
127
+ return existed;
128
+ }
129
+ /** Next fire instant as an ISO string, for display. Undefined when the
130
+ * schedule is disabled or its timer hasn't been armed (boot race). */
131
+ nextFireAt(id) {
132
+ const schedule = this.schedules.get(id);
133
+ if (!schedule || schedule.disabled)
134
+ return undefined;
135
+ if (schedule.kind === 'cron') {
136
+ const job = this.cronJobs.get(id);
137
+ const next = job?.nextRun();
138
+ return next ? next.toISOString() : undefined;
139
+ }
140
+ if (schedule.lastFiredAt && schedule.intervalMs) {
141
+ return new Date(new Date(schedule.lastFiredAt).getTime() + schedule.intervalMs).toISOString();
142
+ }
143
+ return undefined;
144
+ }
145
+ armAll() {
146
+ for (const id of this.intervalTimers.keys())
147
+ this.disarm(id);
148
+ for (const id of this.cronJobs.keys())
149
+ this.disarm(id);
150
+ for (const schedule of this.schedules.values())
151
+ this.arm(schedule);
152
+ }
153
+ arm(schedule) {
154
+ if (schedule.disabled)
155
+ return;
156
+ if (schedule.runs >= schedule.maxRuns)
157
+ return;
158
+ if (schedule.kind === 'interval' && schedule.intervalMs) {
159
+ const timer = setInterval(() => this.fire(schedule.id), schedule.intervalMs);
160
+ timer.unref();
161
+ this.intervalTimers.set(schedule.id, timer);
162
+ }
163
+ else if (schedule.kind === 'cron' && schedule.cronExpr) {
164
+ try {
165
+ const job = new Cron(schedule.cronExpr, () => this.fire(schedule.id));
166
+ this.cronJobs.set(schedule.id, job);
167
+ }
168
+ catch (err) {
169
+ console.error(`[Scheduler] failed to arm cron ${schedule.id}:`, err);
170
+ }
171
+ }
172
+ }
173
+ disarm(id) {
174
+ const timer = this.intervalTimers.get(id);
175
+ if (timer) {
176
+ clearInterval(timer);
177
+ this.intervalTimers.delete(id);
178
+ }
179
+ const job = this.cronJobs.get(id);
180
+ if (job) {
181
+ try {
182
+ job.stop();
183
+ }
184
+ catch { /* ignore */ }
185
+ this.cronJobs.delete(id);
186
+ }
187
+ }
188
+ /** Internal: invoked by the timer/cron when a schedule should fire.
189
+ * Delegates execution to the registered handler, then records the outcome. */
190
+ async fire(id) {
191
+ const schedule = this.schedules.get(id);
192
+ if (!schedule || schedule.disabled)
193
+ return;
194
+ if (!this.fireHandler) {
195
+ console.warn(`[Scheduler] no fire handler registered, dropping fire for ${id}`);
196
+ return;
197
+ }
198
+ if (schedule.runs >= schedule.maxRuns) {
199
+ this.disarm(id);
200
+ return;
201
+ }
202
+ let success = false;
203
+ try {
204
+ await this.fireHandler(schedule);
205
+ success = true;
206
+ }
207
+ catch (err) {
208
+ console.error(`[Scheduler] fire handler threw for ${id}:`, err);
209
+ }
210
+ this.recordFire(id, success);
211
+ }
212
+ /** Run a schedule once now, outside its timer: /loop's first run. It counts as a run. */
213
+ fireNow(id) {
214
+ return this.fire(id);
215
+ }
216
+ /** Public so the runner can mark a fire complete after async work even if
217
+ * it bypassed the internal `fire()` (e.g. coalesced/manual triggers). */
218
+ recordFire(id, success) {
219
+ const schedule = this.schedules.get(id);
220
+ if (!schedule)
221
+ return;
222
+ schedule.runs += 1;
223
+ schedule.lastFiredAt = new Date().toISOString();
224
+ schedule.consecutiveFailures = success ? 0 : schedule.consecutiveFailures + 1;
225
+ if (schedule.runs >= schedule.maxRuns) {
226
+ schedule.disabled = true;
227
+ this.disarm(id);
228
+ }
229
+ else if (schedule.consecutiveFailures >= HARD_LIMITS.MAX_CONSECUTIVE_FAILURES) {
230
+ schedule.disabled = true;
231
+ this.disarm(id);
232
+ }
233
+ this.persist();
234
+ }
235
+ persist() {
236
+ ensureStateDir(HISTORY_DIR, 'Scheduler');
237
+ writeJsonFile(getFile(), { schedules: Array.from(this.schedules.values()) }, 'Scheduler');
238
+ }
239
+ }
240
+ export const scheduler = new Scheduler();
241
+ //# sourceMappingURL=scheduler.js.map