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,44 @@
1
+ /**
2
+ * Keeps work still running in the background in sight after a command answers.
3
+ *
4
+ * A turn closes with the status line, which counts what runs. A command's
5
+ * answer doesn't, and lands below whatever said a task was running, so after
6
+ * a /btw or a /cost the chat reads as if nothing is going on. Under such an
7
+ * answer the background card comes down again (PTY); without one, in SDK
8
+ * mode, a line says how many tasks run.
9
+ */
10
+ import { isProcessing } from '../../claude/request-queue.js';
11
+ import { bringCardDown } from '../../telegram/background-activity-card.js';
12
+ import { taskTracker } from '../../telegram/task-tracker.js';
13
+ import { EntityText } from '../../telegram/entities.js';
14
+ import { replyFormatted } from '../../telegram/send.js';
15
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
16
+ export async function noteStillRunning(ctx) {
17
+ const keyInfo = getSessionKeyFromCtx(ctx);
18
+ if (!keyInfo)
19
+ return;
20
+ const { sessionKey } = keyInfo;
21
+ // A turn is under way: it closes with the status line, and the card under it.
22
+ if (isProcessing(sessionKey))
23
+ return;
24
+ if (bringCardDown(sessionKey))
25
+ return;
26
+ const running = taskTracker.getBackgroundedCount(sessionKey);
27
+ if (running === 0)
28
+ return;
29
+ const tasks = `${running} task${running === 1 ? '' : 's'}`;
30
+ try {
31
+ await replyFormatted(ctx, new EntityText().italic(`⏳ ${tasks} still running · `).add('/tasks').build(), { disable_notification: true });
32
+ }
33
+ catch (err) {
34
+ console.debug('[RunningNote] Failed to send:', err instanceof Error ? err.message : err);
35
+ }
36
+ }
37
+ /** A command handler that ends with {@link noteStillRunning}. */
38
+ export function withRunningNote(handler) {
39
+ return async (ctx) => {
40
+ await handler(ctx);
41
+ await noteStillRunning(ctx);
42
+ };
43
+ }
44
+ //# sourceMappingURL=running-note.js.map
@@ -0,0 +1,303 @@
1
+ import { Cron } from 'croner';
2
+ import { sessionManager } from '../../claude/session-manager.js';
3
+ import { scheduler, HARD_LIMITS } from '../../claude/scheduler.js';
4
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
5
+ import { EntityText, joinMessages } from '../../telegram/entities.js';
6
+ import { replyFormatted } from '../../telegram/send.js';
7
+ /** Text with `inline code` spans and nothing else — the parser errors below are written that way. */
8
+ function withCode(text) {
9
+ const b = new EntityText();
10
+ text.split(/(`[^`]+`)/).forEach((part, i) => (i % 2 === 1 ? b.code(part.slice(1, -1)) : b.add(part)));
11
+ return b.build();
12
+ }
13
+ const EXAMPLES = [
14
+ '/schedule every 5m check the dev server',
15
+ '/schedule every 1h summarize git log since last hour',
16
+ '/schedule daily 9am give me my morning standup',
17
+ '/schedule weekdays 14:00 ping team about standups',
18
+ '/schedule mon,wed,fri 10:30 review open PRs',
19
+ ];
20
+ const USAGE = (() => {
21
+ const b = new EntityText().bold('Usage:').add(' ').code('/schedule <when> <prompt>').newline(2);
22
+ b.bold('Examples:').newline();
23
+ for (const example of EXAMPLES)
24
+ b.code(example).newline();
25
+ b.code('/schedule 0 9 * * * morning summary').add(' (raw cron)').newline(2);
26
+ b.bold('Options').add(' (append at the end):').newline();
27
+ b.code('--max-runs N').add(' cap total fires (default 50, max 500)').newline();
28
+ b.code('--label "..."').add(' short title shown in the fire header').newline(2);
29
+ b.add(`Hard limits: max ${HARD_LIMITS.MAX_PER_SESSION} active schedules per chat, `
30
+ + `${HARD_LIMITS.MIN_INTERVAL_MS / 1000}s minimum interval, `
31
+ + `${HARD_LIMITS.DEFAULT_MAX_RUNS} fires by default.`);
32
+ return b.build();
33
+ })();
34
+ const INTERVAL_UNITS = {
35
+ s: 1000,
36
+ sec: 1000,
37
+ m: 60_000,
38
+ min: 60_000,
39
+ h: 3_600_000,
40
+ hr: 3_600_000,
41
+ d: 86_400_000,
42
+ };
43
+ const DAY_OF_WEEK = {
44
+ sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6,
45
+ };
46
+ function parseTimeOfDay(raw) {
47
+ // `9am`, `9:30am`, `14:00`, `9pm`, `12:30`
48
+ const ampmMatch = raw.match(/^(\d{1,2})(?::(\d{2}))?(am|pm)$/i);
49
+ if (ampmMatch) {
50
+ let hour = parseInt(ampmMatch[1], 10);
51
+ const minute = ampmMatch[2] ? parseInt(ampmMatch[2], 10) : 0;
52
+ const ampm = ampmMatch[3].toLowerCase();
53
+ if (hour < 1 || hour > 12 || minute < 0 || minute > 59)
54
+ return null;
55
+ if (ampm === 'pm' && hour !== 12)
56
+ hour += 12;
57
+ if (ampm === 'am' && hour === 12)
58
+ hour = 0;
59
+ return { hour, minute };
60
+ }
61
+ const hhmmMatch = raw.match(/^(\d{1,2}):(\d{2})$/);
62
+ if (hhmmMatch) {
63
+ const hour = parseInt(hhmmMatch[1], 10);
64
+ const minute = parseInt(hhmmMatch[2], 10);
65
+ if (hour < 0 || hour > 23 || minute < 0 || minute > 59)
66
+ return null;
67
+ return { hour, minute };
68
+ }
69
+ return null;
70
+ }
71
+ /**
72
+ * Pull `--max-runs N` and `--label "..."` out of the prompt. Mutates the
73
+ * returned `prompt` to drop the consumed flag pairs. Quoting on `--label`
74
+ * is required when the value spans multiple words.
75
+ */
76
+ function extractOptions(prompt) {
77
+ let working = prompt;
78
+ let maxRuns;
79
+ let label;
80
+ const maxRunsMatch = working.match(/(?:^|\s)--max-runs\s+(\d+)\b/);
81
+ if (maxRunsMatch) {
82
+ maxRuns = parseInt(maxRunsMatch[1], 10);
83
+ working = (working.slice(0, maxRunsMatch.index ?? 0) + working.slice((maxRunsMatch.index ?? 0) + maxRunsMatch[0].length)).trim();
84
+ }
85
+ const labelMatch = working.match(/(?:^|\s)--label\s+(?:"([^"]+)"|(\S+))/);
86
+ if (labelMatch) {
87
+ label = labelMatch[1] ?? labelMatch[2];
88
+ working = (working.slice(0, labelMatch.index ?? 0) + working.slice((labelMatch.index ?? 0) + labelMatch[0].length)).trim();
89
+ }
90
+ return { prompt: working, maxRuns, label };
91
+ }
92
+ /**
93
+ * Parse the part of the command between `/schedule` and the prompt. Tries
94
+ * (in order): raw 5-field cron, `every <N><unit>`, day-keyword + time-of-day.
95
+ * Returns the consumed token count so the caller can slice the prompt off.
96
+ */
97
+ function parseWhen(tokens) {
98
+ if (tokens.length === 0)
99
+ return { error: 'Missing schedule specification.' };
100
+ // Raw 5-field cron: m h dom mon dow
101
+ if (tokens.length >= 5) {
102
+ const candidate = tokens.slice(0, 5).join(' ');
103
+ const looksLikeCron = /^[\d\*\-,\/\?]+(\s+[\d\*\-,\/\?A-Za-z]+){4}$/.test(candidate);
104
+ if (looksLikeCron) {
105
+ try {
106
+ const job = new Cron(candidate);
107
+ const next = job.nextRun();
108
+ job.stop();
109
+ if (next) {
110
+ return {
111
+ parsed: { kind: 'cron', cronExpr: candidate, humanDescription: candidate },
112
+ consumed: 5,
113
+ };
114
+ }
115
+ }
116
+ catch { /* fall through to NL parsing */ }
117
+ }
118
+ }
119
+ const first = tokens[0].toLowerCase();
120
+ const second = tokens[1]?.toLowerCase();
121
+ if (first === 'every') {
122
+ if (!second)
123
+ return { error: 'Missing interval after `every`.' };
124
+ const intervalMatch = second.match(/^(\d+)([a-z]+)$/);
125
+ if (!intervalMatch)
126
+ return { error: `Unrecognized interval \`${second}\`. Try \`every 5m\`, \`every 1h\`.` };
127
+ const amount = parseInt(intervalMatch[1], 10);
128
+ const unitKey = intervalMatch[2];
129
+ const unitMs = INTERVAL_UNITS[unitKey];
130
+ if (!unitMs)
131
+ return { error: `Unknown unit \`${unitKey}\`. Use s/m/h/d.` };
132
+ const intervalMs = amount * unitMs;
133
+ if (intervalMs < HARD_LIMITS.MIN_INTERVAL_MS) {
134
+ return { error: `Interval must be at least ${HARD_LIMITS.MIN_INTERVAL_MS / 1000}s.` };
135
+ }
136
+ return {
137
+ parsed: { kind: 'interval', intervalMs, humanDescription: `every ${amount}${unitKey}` },
138
+ consumed: 2,
139
+ };
140
+ }
141
+ // Day-of-week keywords / lists → cron with time-of-day
142
+ let dowField = null;
143
+ let dowLabel = first;
144
+ if (first === 'daily')
145
+ dowField = '*';
146
+ else if (first === 'weekdays') {
147
+ dowField = '1-5';
148
+ dowLabel = 'weekdays';
149
+ }
150
+ else if (first === 'weekends') {
151
+ dowField = '0,6';
152
+ dowLabel = 'weekends';
153
+ }
154
+ else {
155
+ // Comma-separated list of day names like `mon,wed,fri`
156
+ const parts = first.split(',').map((p) => p.trim());
157
+ if (parts.length > 0 && parts.every((p) => p in DAY_OF_WEEK)) {
158
+ dowField = parts.map((p) => String(DAY_OF_WEEK[p])).join(',');
159
+ dowLabel = parts.join(',');
160
+ }
161
+ }
162
+ if (dowField !== null) {
163
+ if (!second)
164
+ return { error: 'Missing time of day. Try `daily 9am`, `weekdays 14:00`.' };
165
+ const time = parseTimeOfDay(second);
166
+ if (!time)
167
+ return { error: `Unrecognized time \`${second}\`. Try \`9am\`, \`14:00\`, \`9:30pm\`.` };
168
+ const cronExpr = `${time.minute} ${time.hour} * * ${dowField}`;
169
+ return {
170
+ parsed: {
171
+ kind: 'cron',
172
+ cronExpr,
173
+ humanDescription: `${dowLabel} at ${String(time.hour).padStart(2, '0')}:${String(time.minute).padStart(2, '0')}`,
174
+ },
175
+ consumed: 2,
176
+ };
177
+ }
178
+ return { error: `Couldn't parse schedule. Type \`/schedule\` with no args to see examples.` };
179
+ }
180
+ function formatSchedule(s) {
181
+ const status = s.disabled ? ' (disabled)' : '';
182
+ const when = s.kind === 'interval'
183
+ ? `every ${Math.round((s.intervalMs ?? 0) / 1000)}s`
184
+ : (s.cronExpr ?? '?');
185
+ const next = scheduler.nextFireAt(s.id);
186
+ const nextLine = next ? `\nnext: ${new Date(next).toLocaleString()}` : '';
187
+ const labelLine = s.label ? `\nlabel: ${s.label}` : '';
188
+ const promptPreview = s.prompt.length > 80 ? s.prompt.slice(0, 77) + '...' : s.prompt;
189
+ return new EntityText()
190
+ .code(s.id)
191
+ .add(`${status}\n${when}${labelLine}\nruns: ${s.runs}/${s.maxRuns}${nextLine}\nprompt: ${promptPreview}`)
192
+ .build();
193
+ }
194
+ export async function handleSchedule(ctx) {
195
+ const keyInfo = getSessionKeyFromCtx(ctx);
196
+ if (!keyInfo)
197
+ return;
198
+ const { sessionKey } = keyInfo;
199
+ const text = (ctx.message?.text ?? '').trim();
200
+ const stripped = text.replace(/^\/schedule(?:@\w+)?\s*/i, '');
201
+ if (!stripped) {
202
+ await replyFormatted(ctx, USAGE);
203
+ return;
204
+ }
205
+ // Session required so the schedule can resume into a real project later.
206
+ const session = sessionManager.getSession(sessionKey)
207
+ ?? sessionManager.getOrRestoreSession(sessionKey).session;
208
+ if (!session) {
209
+ await replyFormatted(ctx, withCode('⚠️ No project set. Use `/project` or `/continue` first, then create the schedule.'));
210
+ return;
211
+ }
212
+ // Split off options first so they don't get eaten by the `when` parser.
213
+ const { prompt: promptWithoutOpts, maxRuns, label } = extractOptions(stripped);
214
+ // Honor `--` separator if present.
215
+ const sepIdx = promptWithoutOpts.indexOf(' -- ');
216
+ let whenPart;
217
+ let promptPart;
218
+ if (sepIdx >= 0) {
219
+ whenPart = promptWithoutOpts.slice(0, sepIdx).trim();
220
+ promptPart = promptWithoutOpts.slice(sepIdx + 4).trim();
221
+ }
222
+ else {
223
+ whenPart = promptWithoutOpts;
224
+ promptPart = '';
225
+ }
226
+ const whenTokens = whenPart.split(/\s+/).filter(Boolean);
227
+ const parseResult = parseWhen(whenTokens);
228
+ if ('error' in parseResult) {
229
+ await replyFormatted(ctx, joinMessages([withCode(`❌ ${parseResult.error}`), USAGE]));
230
+ return;
231
+ }
232
+ const { parsed, consumed } = parseResult;
233
+ if (sepIdx < 0) {
234
+ // No explicit `--` — take the remaining tokens as the prompt.
235
+ promptPart = whenTokens.slice(consumed).join(' ').trim();
236
+ }
237
+ if (!promptPart) {
238
+ await replyFormatted(ctx, '❌ Missing prompt. After the schedule spec, add the prompt to run on each fire.');
239
+ return;
240
+ }
241
+ const spec = {
242
+ sessionKey,
243
+ cwd: session.workingDirectory,
244
+ claudeSessionId: session.claudeSessionId,
245
+ prompt: promptPart,
246
+ label,
247
+ maxRuns,
248
+ ...(parsed.kind === 'interval'
249
+ ? { kind: 'interval', intervalMs: parsed.intervalMs }
250
+ : { kind: 'cron', cronExpr: parsed.cronExpr }),
251
+ };
252
+ let created;
253
+ try {
254
+ created = scheduler.createSchedule(spec);
255
+ }
256
+ catch (err) {
257
+ await replyFormatted(ctx, `❌ ${err instanceof Error ? err.message : String(err)}`);
258
+ return;
259
+ }
260
+ const next = scheduler.nextFireAt(created.id);
261
+ const b = new EntityText()
262
+ .add('✅ ').bold('Schedule created').newline()
263
+ .add('id: ').code(created.id).newline()
264
+ .add(`when: ${parsed.humanDescription}\n`)
265
+ .add(`max runs: ${created.maxRuns}`);
266
+ if (next)
267
+ b.add('\nNext fire: ').code(new Date(next).toLocaleString());
268
+ b.newline(2).add('Use ').code('/schedules').add(' to list, ').code(`/unschedule ${created.id}`).add(' to remove.');
269
+ await replyFormatted(ctx, b.build());
270
+ }
271
+ export async function handleSchedules(ctx) {
272
+ const keyInfo = getSessionKeyFromCtx(ctx);
273
+ if (!keyInfo)
274
+ return;
275
+ const { sessionKey } = keyInfo;
276
+ const list = scheduler.listSchedules(sessionKey);
277
+ if (list.length === 0) {
278
+ await replyFormatted(ctx, withCode('No active schedules. Create one with `/schedule <when> <prompt>`.'));
279
+ return;
280
+ }
281
+ const heading = new EntityText().add('📋 ').bold('Schedules').add(` (${list.length})`).build();
282
+ await replyFormatted(ctx, joinMessages([heading, ...list.map(formatSchedule)]));
283
+ }
284
+ export async function handleUnschedule(ctx) {
285
+ const keyInfo = getSessionKeyFromCtx(ctx);
286
+ if (!keyInfo)
287
+ return;
288
+ const { sessionKey } = keyInfo;
289
+ const text = (ctx.message?.text ?? '').trim();
290
+ const id = text.replace(/^\/unschedule(?:@\w+)?\s*/i, '').trim();
291
+ if (!id) {
292
+ await replyFormatted(ctx, withCode('Usage: `/unschedule <id>`. Use `/schedules` to see ids.'));
293
+ return;
294
+ }
295
+ const target = scheduler.getSchedule(id);
296
+ if (!target || target.sessionKey !== sessionKey) {
297
+ await replyFormatted(ctx, new EntityText().add('❌ No schedule ').code(id).add(' in this chat.').build());
298
+ return;
299
+ }
300
+ scheduler.deleteSchedule(id);
301
+ await replyFormatted(ctx, new EntityText().add('✅ Removed schedule ').code(id).add('.').build());
302
+ }
303
+ //# sourceMappingURL=schedule.handler.js.map
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The "is there a project to work in?" preamble every handler needs.
3
+ *
4
+ * This existed in eleven hand-written copies — three in the photo handler, one
5
+ * in voice, six across the command handlers and one in the message domain —
6
+ * with the message text drifting between two wordings along the way. Handlers
7
+ * import it from here so a change to the wording, or to what counts as a
8
+ * usable session, lands everywhere at once.
9
+ */
10
+ import * as path from 'path';
11
+ import { sessionManager } from '../../claude/session-manager.js';
12
+ import { sessionHistory } from '../../claude/session-history.js';
13
+ import { EntityText } from '../../telegram/entities.js';
14
+ import { replyFormatted } from '../../telegram/send.js';
15
+ import { taskListDisplay } from '../../telegram/task-list.js';
16
+ import { homeProject } from '../../utils/home-project.js';
17
+ /** Shown when a handler needs a working directory and no session supplies one. */
18
+ export const NO_PROJECT_MESSAGE = new EntityText()
19
+ .add('⚠️ No project set.\n\nIf the bot restarted, use ').code('/continue').add(' or ').code('/resume')
20
+ .add(' to restore your last session.\nOr use ').code('/project').add(' to open a project first.')
21
+ .build();
22
+ /**
23
+ * Where the chat is: the conversation it's on — or, when a restart dropped
24
+ * that and nothing has brought it back, the one it left off in (`live` false).
25
+ *
26
+ * Only ever read. Drawing /tree or listing /prompts mustn't load a
27
+ * conversation behind the chat's back: the next message would land in
28
+ * whatever it loaded.
29
+ */
30
+ export function whereChatIs(sessionKey) {
31
+ const session = sessionManager.getSession(sessionKey);
32
+ if (session)
33
+ return { projectPath: session.workingDirectory, sessionId: session.claudeSessionId, live: true };
34
+ const last = sessionHistory.getLastSession(sessionKey);
35
+ return last ? { projectPath: last.projectPath, sessionId: last.claudeSessionId, live: false } : undefined;
36
+ }
37
+ /**
38
+ * Require a session that is already live in memory.
39
+ *
40
+ * For commands that inspect or act on the current session but shouldn't
41
+ * silently revive a dead one — if the bot restarted, the user is told to
42
+ * /continue rather than having a session rehydrated underneath them.
43
+ * Returns null after replying, so callers just early-return.
44
+ */
45
+ export async function requireActiveSession(ctx, sessionKey) {
46
+ const session = sessionManager.getSession(sessionKey);
47
+ if (!session) {
48
+ await replyFormatted(ctx, NO_PROJECT_MESSAGE);
49
+ return null;
50
+ }
51
+ return session;
52
+ }
53
+ /**
54
+ * Require a session, restoring from disk if the bot restarted since the last
55
+ * message.
56
+ *
57
+ * For the paths where the user is mid-conversation — a typed message, a photo,
58
+ * a voice note — and a restart shouldn't be their problem. Announces the
59
+ * restore so the recovered context isn't invisible. With nothing to restore, a
60
+ * bot with a home project starts a fresh conversation there. Returns null
61
+ * after replying, so callers just early-return.
62
+ */
63
+ export async function requireSession(ctx, sessionKey) {
64
+ const { session: restoredSession, restored } = sessionManager.getOrRestoreSession(sessionKey);
65
+ // A bot made for one project starts there instead of asking for /project.
66
+ const home = restoredSession ? undefined : homeProject();
67
+ const session = restoredSession ?? (home ? sessionManager.createSession(sessionKey, home) : undefined);
68
+ if (!session) {
69
+ await replyFormatted(ctx, NO_PROJECT_MESSAGE);
70
+ return null;
71
+ }
72
+ if (restored) {
73
+ await replyFormatted(ctx, new EntityText().add('↩️ Resumed previous session: ').bold(path.basename(session.workingDirectory)).build());
74
+ await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
75
+ }
76
+ return session;
77
+ }
78
+ //# sourceMappingURL=session-guard.js.map
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Suggestion-tap callback handler.
3
+ *
4
+ * When a user taps a "💡 …" inline button — under an assistant response, or on
5
+ * a suggestion card of its own — we look up the stored suggestion text
6
+ * (callback_data only carries a short id) and dispatch it through the same
7
+ * path as a user-typed message:
8
+ * - show what was effectively sent, so the conversation log reads like a
9
+ * real exchange: an echo line under a button, or the card rewritten in
10
+ * place when it is already spelling the prompt out
11
+ * - remove the buttons so the same suggestion can't be replayed accidentally
12
+ * - push the prompt through the normal request queue and streaming path
13
+ */
14
+ import { consumeSuggestion } from '../../claude/pending-suggestions.js';
15
+ import { getSessionKeyFromCtx } from '../../utils/session-key.js';
16
+ import { sessionManager } from '../../claude/session-manager.js';
17
+ import { EntityText } from '../../telegram/entities.js';
18
+ import { editCallbackMessage, replyFormatted } from '../../telegram/send.js';
19
+ import { buildSuggestionCardText } from '../../telegram/prompt-suggestion.js';
20
+ export async function handleSuggestionTapCallback(ctx) {
21
+ const data = ctx.callbackQuery?.data;
22
+ if (!data?.startsWith('sgt:'))
23
+ return;
24
+ const id = data.slice('sgt:'.length);
25
+ const keyInfo = getSessionKeyFromCtx(ctx);
26
+ if (!keyInfo) {
27
+ await ctx.answerCallbackQuery({ text: 'Session not found' });
28
+ return;
29
+ }
30
+ const { sessionKey, chatId } = keyInfo;
31
+ const entry = consumeSuggestion(id);
32
+ if (!entry) {
33
+ await ctx.answerCallbackQuery({ text: 'Suggestion expired or already used' });
34
+ try {
35
+ await ctx.editMessageReplyMarkup({ reply_markup: undefined });
36
+ }
37
+ catch { /* ignore */ }
38
+ return;
39
+ }
40
+ // A button tap can sometimes outlive the session it came from (bot
41
+ // restarted between the response posting and the tap). Bail with a clear
42
+ // message rather than dispatching a prompt against no session.
43
+ const session = sessionManager.getSession(sessionKey);
44
+ if (!session) {
45
+ await ctx.answerCallbackQuery({ text: 'No active session' });
46
+ return;
47
+ }
48
+ await ctx.answerCallbackQuery({ text: 'Sending…' });
49
+ if (entry.presentation === 'card') {
50
+ // The card is the only place this prompt is written out, so it stays —
51
+ // rewritten to say it was sent, which drops the keyboard in the same
52
+ // edit. Echoing underneath would just repeat the line above it.
53
+ try {
54
+ await editCallbackMessage(ctx, buildSuggestionCardText(entry.text, { sent: true }));
55
+ }
56
+ catch (err) {
57
+ console.debug('[Suggestion] card edit failed:', err instanceof Error ? err.message : err);
58
+ // Fall back to at least taking the button away, so the card can't be
59
+ // tapped again into an "expired" answer.
60
+ try {
61
+ await ctx.editMessageReplyMarkup({ reply_markup: undefined });
62
+ }
63
+ catch { /* ignore */ }
64
+ }
65
+ }
66
+ else {
67
+ try {
68
+ await ctx.editMessageReplyMarkup({ reply_markup: undefined });
69
+ }
70
+ catch { /* ignore */ }
71
+ // Echo what we're sending so the chat scroll reads like a real conversation.
72
+ try {
73
+ await replyFormatted(ctx, new EntityText().add('💡 ').italic(entry.text).build());
74
+ }
75
+ catch (err) {
76
+ console.debug('[Suggestion] echo failed:', err instanceof Error ? err.message : err);
77
+ }
78
+ }
79
+ // Dispatch through the normal pipeline. Lazy import avoids a circular
80
+ // import between this file and message.handler.ts.
81
+ const { dispatchPromptFromCallback, runQueuedTurn } = await import('./message.handler.js');
82
+ await runQueuedTurn(ctx, sessionKey, entry.text, 'Suggestion', () => dispatchPromptFromCallback(ctx, sessionKey, chatId, entry.text));
83
+ }
84
+ //# sourceMappingURL=suggestion.handler.js.map