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,135 @@
1
+ import { markInFlight, clearInFlight } from './in-flight-tracker.js';
2
+ import { releaseHeldQuery } from './held-query.js';
3
+ const activeAbortControllers = new Map();
4
+ const activeQueries = new Map();
5
+ const pendingQueues = new Map();
6
+ const processingFlags = new Map();
7
+ // Tracks chats where a cancel was initiated — checked by agent.ts to detect
8
+ // user-initiated cancellation without calling controller.abort() (which crashes the SDK).
9
+ const cancelledChats = new Set();
10
+ export function getAbortController(sessionKey) {
11
+ return activeAbortControllers.get(sessionKey);
12
+ }
13
+ export function setAbortController(sessionKey, controller) {
14
+ activeAbortControllers.set(sessionKey, controller);
15
+ }
16
+ export function clearAbortController(sessionKey) {
17
+ activeAbortControllers.delete(sessionKey);
18
+ }
19
+ export function setActiveQuery(sessionKey, q) {
20
+ activeQueries.set(sessionKey, q);
21
+ }
22
+ export function getActiveQuery(sessionKey) {
23
+ return activeQueries.get(sessionKey);
24
+ }
25
+ export function clearActiveQuery(sessionKey) {
26
+ activeQueries.delete(sessionKey);
27
+ }
28
+ export function isCancelled(sessionKey) {
29
+ return cancelledChats.has(sessionKey);
30
+ }
31
+ export function clearCancelled(sessionKey) {
32
+ cancelledChats.delete(sessionKey);
33
+ }
34
+ export function isProcessing(sessionKey) {
35
+ return processingFlags.get(sessionKey) === true;
36
+ }
37
+ /** Sessions with a turn running or waiting in line for one. */
38
+ export function busySessionCount() {
39
+ let busy = 0;
40
+ for (const key of new Set([...processingFlags.keys(), ...pendingQueues.keys()])) {
41
+ if (processingFlags.get(key) || (pendingQueues.get(key)?.length ?? 0) > 0)
42
+ busy++;
43
+ }
44
+ return busy;
45
+ }
46
+ export async function queueRequest(sessionKey, message, handler) {
47
+ return new Promise((resolve, reject) => {
48
+ const request = {
49
+ message,
50
+ handler,
51
+ resolve: resolve,
52
+ reject,
53
+ };
54
+ let queue = pendingQueues.get(sessionKey);
55
+ if (!queue) {
56
+ queue = [];
57
+ pendingQueues.set(sessionKey, queue);
58
+ }
59
+ queue.push(request);
60
+ processQueue(sessionKey);
61
+ });
62
+ }
63
+ async function processQueue(sessionKey) {
64
+ if (processingFlags.get(sessionKey)) {
65
+ return;
66
+ }
67
+ const queue = pendingQueues.get(sessionKey);
68
+ if (!queue || queue.length === 0) {
69
+ return;
70
+ }
71
+ processingFlags.set(sessionKey, true);
72
+ const request = queue.shift();
73
+ // Persist a marker so an unexpected exit during this turn can be surfaced
74
+ // to the user on next startup.
75
+ markInFlight(sessionKey, request.message);
76
+ try {
77
+ const result = await request.handler();
78
+ request.resolve(result);
79
+ }
80
+ catch (error) {
81
+ request.reject(error instanceof Error ? error : new Error(String(error)));
82
+ }
83
+ finally {
84
+ processingFlags.set(sessionKey, false);
85
+ clearAbortController(sessionKey);
86
+ clearActiveQuery(sessionKey);
87
+ clearCancelled(sessionKey);
88
+ clearInFlight(sessionKey);
89
+ if (queue.length > 0) {
90
+ processQueue(sessionKey);
91
+ }
92
+ }
93
+ }
94
+ /** Soft cancel: interrupt the running query but keep the session alive. */
95
+ export async function cancelRequest(sessionKey) {
96
+ const q = activeQueries.get(sessionKey);
97
+ if (q) {
98
+ // Set the cancelled flag BEFORE interrupt so agent.ts can detect it
99
+ // when the error_during_execution result arrives.
100
+ // Do NOT call controller.abort() — that crashes the SDK subprocess.
101
+ // The input stays open: background tasks the turn started outlive it.
102
+ cancelledChats.add(sessionKey);
103
+ try {
104
+ await q.interrupt();
105
+ }
106
+ catch (err) {
107
+ console.debug('[cancelRequest] interrupt() threw for chat', sessionKey, err);
108
+ }
109
+ clearActiveQuery(sessionKey);
110
+ return true;
111
+ }
112
+ // Fallback to AbortController if no query stored
113
+ const controller = activeAbortControllers.get(sessionKey);
114
+ if (controller) {
115
+ cancelledChats.add(sessionKey);
116
+ controller.abort();
117
+ clearAbortController(sessionKey);
118
+ return true;
119
+ }
120
+ // No turn running, but a query answered earlier is still open for its
121
+ // background work: stop that.
122
+ return releaseHeldQuery(sessionKey);
123
+ }
124
+ export function clearQueue(sessionKey) {
125
+ const queue = pendingQueues.get(sessionKey);
126
+ if (!queue)
127
+ return 0;
128
+ const count = queue.length;
129
+ for (const request of queue) {
130
+ request.reject(new Error('Queue cleared'));
131
+ }
132
+ queue.length = 0;
133
+ return count;
134
+ }
135
+ //# sourceMappingURL=request-queue.js.map
@@ -0,0 +1,91 @@
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 { maybeSendVoiceReply } from '../tts/voice-reply.js';
8
+ import { closeTurn, relayCatchUpIfMissed } from '../bot/handlers/message.handler.js';
9
+ import { parseSessionKey } from '../utils/session-key.js';
10
+ import { buildSyntheticCtx } from './synthetic-ctx.js';
11
+ import { scheduler } from './scheduler.js';
12
+ /**
13
+ * Wires the scheduler to the rest of the bot. On boot, registers a fire
14
+ * handler that resolves the session, posts a "🔔 Scheduled" header, then
15
+ * enqueues the schedule's prompt through the normal turn pipeline so the
16
+ * response renders identically to a user-typed message.
17
+ *
18
+ * Failures don't auto-disable on a single miss — the scheduler tracks
19
+ * consecutive failures and disables only after MAX_CONSECUTIVE_FAILURES so
20
+ * transient errors don't silently kill an otherwise healthy schedule.
21
+ */
22
+ export function startScheduledRunner(bot) {
23
+ scheduler.loadAll((schedule) => fireSchedule(bot, schedule));
24
+ }
25
+ async function fireSchedule(bot, schedule) {
26
+ const { sessionKey, prompt, label } = schedule;
27
+ const { chatId, threadId } = parseSessionKey(sessionKey);
28
+ const threadOpts = threadId !== undefined ? { message_thread_id: threadId } : {};
29
+ // Resolve the session — restore from disk if the PTY isn't live anymore.
30
+ // The scheduler doesn't capture a long-lived ctx, so cold-restore is
31
+ // expected after a bot restart.
32
+ let { session } = sessionManager.getOrRestoreSession(sessionKey);
33
+ if (!session) {
34
+ // Fall back to the most recent persisted entry regardless of age — a
35
+ // user who explicitly scheduled a task wants it to fire even if the
36
+ // session has been idle for weeks.
37
+ if (sessionHistory.getLastSession(sessionKey)) {
38
+ session = sessionManager.resumeLastSession(sessionKey) ?? undefined;
39
+ }
40
+ }
41
+ if (!session) {
42
+ // Can't fire — let the user know but keep the schedule armed; they may
43
+ // restore the project shortly.
44
+ try {
45
+ await bot.api.sendMessage(chatId, '⚠️ Scheduled fire skipped — no project bound to this chat. Use /project to bind one, then the next fire will run.', threadOpts);
46
+ }
47
+ catch (err) {
48
+ console.error('[ScheduledRunner] failed to notify missing session:', err);
49
+ }
50
+ throw new Error('no session');
51
+ }
52
+ const ctx = buildSyntheticCtx({ api: bot.api, sessionKey, syntheticText: prompt });
53
+ const labelText = label ?? prompt.slice(0, 60);
54
+ await messageSender.postScheduledFire(ctx, labelText, prompt);
55
+ // Enqueue through the same FIFO the user's own messages flow through.
56
+ // If a user turn is already running, the scheduled fire waits behind it
57
+ // instead of racing — same ordering guarantees `/btw`-bypassing commands
58
+ // get when they bypass the queue.
59
+ try {
60
+ await queueRequest(sessionKey, `[scheduled] ${prompt}`, async () => {
61
+ await runScheduledTurn(ctx, sessionKey, prompt);
62
+ });
63
+ }
64
+ catch (err) {
65
+ const msg = err instanceof Error ? err.message : String(err);
66
+ try {
67
+ await bot.api.sendMessage(chatId, `⚠️ Scheduled fire failed: ${msg}`, threadOpts);
68
+ }
69
+ catch { /* ignore */ }
70
+ throw err instanceof Error ? err : new Error(msg);
71
+ }
72
+ }
73
+ async function runScheduledTurn(ctx, sessionKey, prompt) {
74
+ const startTime = Date.now();
75
+ await withStreamingTurn(ctx, sessionKey, prompt, async (abortController) => {
76
+ const response = await sendToAgent(sessionKey, prompt, {
77
+ ...progressCallbacks(ctx),
78
+ ...toolCallbacks(ctx, sessionKey),
79
+ abortController,
80
+ telegramCtx: ctx,
81
+ });
82
+ await messageSender.finishStreaming(ctx, response.text);
83
+ await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
84
+ await maybeSendVoiceReply(ctx, response.text);
85
+ await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
86
+ // The short form: a schedule can fire every minute, and the whole block
87
+ // under each fire would outweigh the result it closes.
88
+ await closeTurn(ctx, sessionKey, response, prompt, { brief: true });
89
+ });
90
+ }
91
+ //# sourceMappingURL=scheduled-runner.js.map
@@ -0,0 +1,237 @@
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 /schedule Telegram commands. 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
+ `Delete one with /unschedule 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
+ /** Public so the runner can mark a fire complete after async work even if
213
+ * it bypassed the internal `fire()` (e.g. coalesced/manual triggers). */
214
+ recordFire(id, success) {
215
+ const schedule = this.schedules.get(id);
216
+ if (!schedule)
217
+ return;
218
+ schedule.runs += 1;
219
+ schedule.lastFiredAt = new Date().toISOString();
220
+ schedule.consecutiveFailures = success ? 0 : schedule.consecutiveFailures + 1;
221
+ if (schedule.runs >= schedule.maxRuns) {
222
+ schedule.disabled = true;
223
+ this.disarm(id);
224
+ }
225
+ else if (schedule.consecutiveFailures >= HARD_LIMITS.MAX_CONSECUTIVE_FAILURES) {
226
+ schedule.disabled = true;
227
+ this.disarm(id);
228
+ }
229
+ this.persist();
230
+ }
231
+ persist() {
232
+ ensureStateDir(HISTORY_DIR, 'Scheduler');
233
+ writeJsonFile(getFile(), { schedules: Array.from(this.schedules.values()) }, 'Scheduler');
234
+ }
235
+ }
236
+ export const scheduler = new Scheduler();
237
+ //# sourceMappingURL=scheduler.js.map