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.
- package/.env.example +375 -0
- package/CHANGELOG.md +1867 -0
- package/LICENSE +22 -0
- package/README.md +130 -2
- package/dist/audio/transcribe.js +41 -0
- package/dist/bin/mcp-server.js +363 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +573 -0
- package/dist/bot/command-catalog.js +263 -0
- package/dist/bot/deleted-threads.js +103 -0
- package/dist/bot/file-access.js +150 -0
- package/dist/bot/handlers/album.handler.js +128 -0
- package/dist/bot/handlers/branch.handler.js +1096 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +803 -0
- package/dist/bot/handlers/command/all-view.js +33 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/background.js +37 -0
- package/dist/bot/handlers/command/botname.js +76 -0
- package/dist/bot/handlers/command/btw.js +175 -0
- package/dist/bot/handlers/command/cleanup.js +329 -0
- package/dist/bot/handlers/command/model.js +226 -0
- package/dist/bot/handlers/command/prefs-scope.js +362 -0
- package/dist/bot/handlers/command/project.js +458 -0
- package/dist/bot/handlers/command/resume.js +325 -0
- package/dist/bot/handlers/command/session.js +299 -0
- package/dist/bot/handlers/command/settings.js +657 -0
- package/dist/bot/handlers/command/shared.js +207 -0
- package/dist/bot/handlers/command/tasks.js +681 -0
- package/dist/bot/handlers/command/thread.js +128 -0
- package/dist/bot/handlers/command/topic-store.js +74 -0
- package/dist/bot/handlers/command/topic.js +27 -0
- package/dist/bot/handlers/command/usage.js +382 -0
- package/dist/bot/handlers/command-fallback.js +179 -0
- package/dist/bot/handlers/command.handler.js +446 -0
- package/dist/bot/handlers/loop.handler.js +389 -0
- package/dist/bot/handlers/media-fallback.js +126 -0
- package/dist/bot/handlers/message/replies.js +56 -0
- package/dist/bot/handlers/message/shared.js +95 -0
- package/dist/bot/handlers/message/turn-notify.js +135 -0
- package/dist/bot/handlers/message/turn-runner.js +56 -0
- package/dist/bot/handlers/message.handler.js +114 -0
- package/dist/bot/handlers/newbot.handler.js +230 -0
- package/dist/bot/handlers/photo.handler.js +286 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/session-guard.js +78 -0
- package/dist/bot/handlers/suggestion.handler.js +84 -0
- package/dist/bot/handlers/tree.handler.js +480 -0
- package/dist/bot/handlers/view.js +41 -0
- package/dist/bot/handlers/voice.handler.js +147 -0
- package/dist/bot/kept-threads.js +51 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/album-collector.js +69 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +145 -0
- package/dist/bot/middleware/group-role.middleware.js +75 -0
- package/dist/bot/middleware/message-batcher.js +87 -0
- package/dist/bot/middleware/queued-messages.js +1082 -0
- package/dist/bot/middleware/stale-filter.js +9 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/ask-user-form.js +517 -0
- package/dist/claude/ask-user.js +363 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +143 -0
- package/dist/claude/available-commands.js +156 -0
- package/dist/claude/background-hint.js +91 -0
- package/dist/claude/branch-tree.js +393 -0
- package/dist/claude/carry-over.js +25 -0
- package/dist/claude/ccr-shim.js +48 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +117 -0
- package/dist/claude/command-parser.js +206 -0
- package/dist/claude/cost-overlay-scraper.js +134 -0
- package/dist/claude/effort-level.js +5 -0
- package/dist/claude/enabled-plugins.js +52 -0
- package/dist/claude/in-flight-tracker.js +82 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +481 -0
- package/dist/claude/memory-guard.js +400 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +817 -0
- package/dist/claude/model-catalog.js +102 -0
- package/dist/claude/monitor-relay.js +712 -0
- package/dist/claude/native-commands.js +40 -0
- package/dist/claude/pending-branches.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +338 -0
- package/dist/claude/permission-mode.js +152 -0
- package/dist/claude/poll-user.js +51 -0
- package/dist/claude/prewarm.js +70 -0
- package/dist/claude/project-commands.js +69 -0
- package/dist/claude/prompt-hold.js +124 -0
- package/dist/claude/prompt-suggestion-scraper.js +89 -0
- package/dist/claude/pty-idle-reaper.js +96 -0
- package/dist/claude/pty-provider.js +2499 -0
- package/dist/claude/pty-spawn-config.js +343 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/pty-watch.js +201 -0
- package/dist/claude/request-queue.js +107 -0
- package/dist/claude/rewind.js +111 -0
- package/dist/claude/scheduled-runner.js +89 -0
- package/dist/claude/scheduler.js +241 -0
- package/dist/claude/scope-guard.js +279 -0
- package/dist/claude/screen-marks.js +83 -0
- package/dist/claude/screen-render.js +96 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-history.js +288 -0
- package/dist/claude/session-jsonl.js +1067 -0
- package/dist/claude/session-manager.js +216 -0
- package/dist/claude/session-move.js +70 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/shell-mode-gate.js +60 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +252 -0
- package/dist/claude/stage-images.js +62 -0
- package/dist/claude/subagent-tools.js +12 -0
- package/dist/claude/synthetic-ctx.js +51 -0
- package/dist/claude/tasks-overlay-scraper.js +217 -0
- package/dist/claude/thread-judge-haiku.js +88 -0
- package/dist/claude/tip-scraper.js +77 -0
- package/dist/claude/tui-modal.js +746 -0
- package/dist/claude/tui-state.js +456 -0
- package/dist/claude/turn-end.js +105 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/typed-answer.js +104 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +338 -0
- package/dist/cli/commands/help.js +34 -0
- package/dist/cli/commands/init.js +126 -0
- package/dist/cli/commands/service.js +710 -0
- package/dist/cli/commands/start.js +63 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/commands/watch.js +322 -0
- package/dist/cli/dispatch.js +84 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +705 -0
- package/dist/cli/init/prompter.js +124 -0
- package/dist/cli/init/telegram.js +120 -0
- package/dist/cli/service/render.js +212 -0
- package/dist/cli.js +18 -0
- package/dist/config-report.js +107 -0
- package/dist/config.js +525 -0
- package/dist/index.js +443 -0
- package/dist/launcher.js +960 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +142 -0
- package/dist/providers/ccr-provider.js +59 -0
- package/dist/providers/claude-provider.js +10 -0
- package/dist/providers/prefs-sync.js +121 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +128 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/spawn-settings.js +45 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +322 -0
- package/dist/restart-when-idle.js +173 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +161 -0
- package/dist/startup/notices.js +120 -0
- package/dist/startup/shared.js +44 -0
- package/dist/startup/verify-token.js +31 -0
- package/dist/telegram/access-request.js +153 -0
- package/dist/telegram/action-logger.js +522 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +282 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +26 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +96 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1019 -0
- package/dist/telegram/prompt-label.js +148 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +103 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/table-lists.js +56 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +128 -0
- package/dist/telegram/terminal-renderer.js +667 -0
- package/dist/telegram/thread-titles.js +262 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/utils/admins.js +143 -0
- package/dist/utils/agent-timer.js +55 -0
- package/dist/utils/atomic-write.js +24 -0
- package/dist/utils/bot-icon.js +248 -0
- package/dist/utils/bot-token.js +77 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +53 -0
- package/dist/utils/claude-env.js +53 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/download.js +137 -0
- package/dist/utils/exit-codes.js +59 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +78 -0
- package/dist/utils/home-project.js +30 -0
- package/dist/utils/host-stall.js +51 -0
- package/dist/utils/id-list.js +44 -0
- package/dist/utils/idle-restart.js +92 -0
- package/dist/utils/install-mode.js +63 -0
- package/dist/utils/instance-config.js +148 -0
- package/dist/utils/instances.js +95 -0
- package/dist/utils/json-store.js +140 -0
- package/dist/utils/keyed-settings.js +62 -0
- package/dist/utils/legacy-env.js +35 -0
- package/dist/utils/memory-pressure.js +60 -0
- package/dist/utils/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +52 -0
- package/dist/utils/respawn-backoff.js +28 -0
- package/dist/utils/sanitize.js +91 -0
- package/dist/utils/session-key.js +37 -0
- package/dist/utils/stale-launcher.js +109 -0
- package/dist/utils/state-dir-migration.js +92 -0
- package/dist/utils/systemd.js +126 -0
- package/dist/utils/telegram-proxy.js +72 -0
- package/dist/utils/uploads-dir.js +27 -0
- package/dist/utils/user-roster.js +275 -0
- package/dist/utils/verbosity.js +118 -0
- package/dist/utils/version-check.js +166 -0
- package/dist/utils/workspace-guard.js +44 -0
- package/dist/worker-restart.js +141 -0
- package/instances.json.example +41 -0
- package/package.json +75 -4
|
@@ -0,0 +1,389 @@
|
|
|
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, editCallbackMessage } 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
|
+
'/loop 5m check the dev server',
|
|
15
|
+
'/loop summarize the git log every 1h',
|
|
16
|
+
'/loop daily 9am give me my morning standup',
|
|
17
|
+
'/loop weekdays 14:00 ping team about standups',
|
|
18
|
+
'/loop mon,wed,fri 10:30 review open PRs',
|
|
19
|
+
];
|
|
20
|
+
const USAGE = (() => {
|
|
21
|
+
const b = new EntityText().bold('Usage:').add(' ').code('/loop <interval> <prompt>').newline(2);
|
|
22
|
+
b.bold('Examples:').newline();
|
|
23
|
+
for (const example of EXAMPLES)
|
|
24
|
+
b.code(example).newline();
|
|
25
|
+
b.code('/loop 0 9 * * * morning summary').add(' (raw cron)').newline(2);
|
|
26
|
+
b.add('An interval runs the prompt once now, then every interval; a time of day waits for it.').newline(2);
|
|
27
|
+
b.bold('Options').add(' (append at the end):').newline();
|
|
28
|
+
b.code('--max-runs N').add(' cap total runs (default 50, max 500)').newline();
|
|
29
|
+
b.code('--label "..."').add(' short title shown in the run header').newline(2);
|
|
30
|
+
b.add(`Hard limits: max ${HARD_LIMITS.MAX_PER_SESSION} active loops per chat, `
|
|
31
|
+
+ `${HARD_LIMITS.MIN_INTERVAL_MS / 1000}s minimum interval, `
|
|
32
|
+
+ `${HARD_LIMITS.DEFAULT_MAX_RUNS} runs by default.`);
|
|
33
|
+
return b.build();
|
|
34
|
+
})();
|
|
35
|
+
/** What /loop without an interval says: Claude Code's self-paced mode, which the chat can't have yet. */
|
|
36
|
+
const NO_INTERVAL = withCode('ℹ️ Without an interval, Claude Code\'s /loop lets Claude pick when to run again, which can\'t reach the chat yet. '
|
|
37
|
+
+ 'Give one: `/loop 10m <prompt>` or `/loop <prompt> every 10m`.');
|
|
38
|
+
const INTERVAL_UNITS = {
|
|
39
|
+
s: 1000,
|
|
40
|
+
sec: 1000,
|
|
41
|
+
m: 60_000,
|
|
42
|
+
min: 60_000,
|
|
43
|
+
h: 3_600_000,
|
|
44
|
+
hr: 3_600_000,
|
|
45
|
+
d: 86_400_000,
|
|
46
|
+
};
|
|
47
|
+
const DAY_OF_WEEK = {
|
|
48
|
+
sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6,
|
|
49
|
+
};
|
|
50
|
+
function parseTimeOfDay(raw) {
|
|
51
|
+
// `9am`, `9:30am`, `14:00`, `9pm`, `12:30`
|
|
52
|
+
const ampmMatch = raw.match(/^(\d{1,2})(?::(\d{2}))?(am|pm)$/i);
|
|
53
|
+
if (ampmMatch) {
|
|
54
|
+
let hour = parseInt(ampmMatch[1], 10);
|
|
55
|
+
const minute = ampmMatch[2] ? parseInt(ampmMatch[2], 10) : 0;
|
|
56
|
+
const ampm = ampmMatch[3].toLowerCase();
|
|
57
|
+
if (hour < 1 || hour > 12 || minute < 0 || minute > 59)
|
|
58
|
+
return null;
|
|
59
|
+
if (ampm === 'pm' && hour !== 12)
|
|
60
|
+
hour += 12;
|
|
61
|
+
if (ampm === 'am' && hour === 12)
|
|
62
|
+
hour = 0;
|
|
63
|
+
return { hour, minute };
|
|
64
|
+
}
|
|
65
|
+
const hhmmMatch = raw.match(/^(\d{1,2}):(\d{2})$/);
|
|
66
|
+
if (hhmmMatch) {
|
|
67
|
+
const hour = parseInt(hhmmMatch[1], 10);
|
|
68
|
+
const minute = parseInt(hhmmMatch[2], 10);
|
|
69
|
+
if (hour < 0 || hour > 23 || minute < 0 || minute > 59)
|
|
70
|
+
return null;
|
|
71
|
+
return { hour, minute };
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Pull `--max-runs N` and `--label "..."` out of the prompt. Mutates the
|
|
77
|
+
* returned `prompt` to drop the consumed flag pairs. Quoting on `--label`
|
|
78
|
+
* is required when the value spans multiple words.
|
|
79
|
+
*/
|
|
80
|
+
function extractOptions(prompt) {
|
|
81
|
+
let working = prompt;
|
|
82
|
+
let maxRuns;
|
|
83
|
+
let label;
|
|
84
|
+
const maxRunsMatch = working.match(/(?:^|\s)--max-runs\s+(\d+)\b/);
|
|
85
|
+
if (maxRunsMatch) {
|
|
86
|
+
maxRuns = parseInt(maxRunsMatch[1], 10);
|
|
87
|
+
working = (working.slice(0, maxRunsMatch.index ?? 0) + working.slice((maxRunsMatch.index ?? 0) + maxRunsMatch[0].length)).trim();
|
|
88
|
+
}
|
|
89
|
+
const labelMatch = working.match(/(?:^|\s)--label\s+(?:"([^"]+)"|(\S+))/);
|
|
90
|
+
if (labelMatch) {
|
|
91
|
+
label = labelMatch[1] ?? labelMatch[2];
|
|
92
|
+
working = (working.slice(0, labelMatch.index ?? 0) + working.slice((labelMatch.index ?? 0) + labelMatch[0].length)).trim();
|
|
93
|
+
}
|
|
94
|
+
return { prompt: working, maxRuns, label };
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Parse a schedule at the start of /loop's input. Tries
|
|
98
|
+
* (in order): raw 5-field cron, `every <N><unit>`, day-keyword + time-of-day,
|
|
99
|
+
* a bare `<N><unit>`.
|
|
100
|
+
* Returns the consumed token count so the caller can slice the prompt off.
|
|
101
|
+
*/
|
|
102
|
+
function parseWhen(tokens) {
|
|
103
|
+
if (tokens.length === 0)
|
|
104
|
+
return { error: 'Missing schedule specification.' };
|
|
105
|
+
// Raw 5-field cron: m h dom mon dow
|
|
106
|
+
if (tokens.length >= 5) {
|
|
107
|
+
const candidate = tokens.slice(0, 5).join(' ');
|
|
108
|
+
const looksLikeCron = /^[\d\*\-,\/\?]+(\s+[\d\*\-,\/\?A-Za-z]+){4}$/.test(candidate);
|
|
109
|
+
if (looksLikeCron) {
|
|
110
|
+
try {
|
|
111
|
+
const job = new Cron(candidate);
|
|
112
|
+
const next = job.nextRun();
|
|
113
|
+
job.stop();
|
|
114
|
+
if (next) {
|
|
115
|
+
return {
|
|
116
|
+
parsed: { kind: 'cron', cronExpr: candidate, humanDescription: candidate },
|
|
117
|
+
consumed: 5,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch { /* fall through to NL parsing */ }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const first = tokens[0].toLowerCase();
|
|
125
|
+
const second = tokens[1]?.toLowerCase();
|
|
126
|
+
if (first === 'every') {
|
|
127
|
+
if (!second)
|
|
128
|
+
return { error: 'Missing interval after `every`.' };
|
|
129
|
+
const intervalMatch = second.match(/^(\d+)([a-z]+)$/);
|
|
130
|
+
if (!intervalMatch)
|
|
131
|
+
return { error: `Unrecognized interval \`${second}\`. Try \`every 5m\`, \`every 1h\`.` };
|
|
132
|
+
const amount = parseInt(intervalMatch[1], 10);
|
|
133
|
+
const unitKey = intervalMatch[2];
|
|
134
|
+
const unitMs = INTERVAL_UNITS[unitKey];
|
|
135
|
+
if (!unitMs)
|
|
136
|
+
return { error: `Unknown unit \`${unitKey}\`. Use s/m/h/d.` };
|
|
137
|
+
const intervalMs = amount * unitMs;
|
|
138
|
+
if (intervalMs < HARD_LIMITS.MIN_INTERVAL_MS) {
|
|
139
|
+
return { error: `Interval must be at least ${HARD_LIMITS.MIN_INTERVAL_MS / 1000}s.` };
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
parsed: { kind: 'interval', intervalMs, humanDescription: `every ${amount}${unitKey}` },
|
|
143
|
+
consumed: 2,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
// Day-of-week keywords / lists → cron with time-of-day
|
|
147
|
+
let dowField = null;
|
|
148
|
+
let dowLabel = first;
|
|
149
|
+
if (first === 'daily')
|
|
150
|
+
dowField = '*';
|
|
151
|
+
else if (first === 'weekdays') {
|
|
152
|
+
dowField = '1-5';
|
|
153
|
+
dowLabel = 'weekdays';
|
|
154
|
+
}
|
|
155
|
+
else if (first === 'weekends') {
|
|
156
|
+
dowField = '0,6';
|
|
157
|
+
dowLabel = 'weekends';
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
// Comma-separated list of day names like `mon,wed,fri`
|
|
161
|
+
const parts = first.split(',').map((p) => p.trim());
|
|
162
|
+
if (parts.length > 0 && parts.every((p) => p in DAY_OF_WEEK)) {
|
|
163
|
+
dowField = parts.map((p) => String(DAY_OF_WEEK[p])).join(',');
|
|
164
|
+
dowLabel = parts.join(',');
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (dowField !== null) {
|
|
168
|
+
if (!second)
|
|
169
|
+
return { error: 'Missing time of day. Try `daily 9am`, `weekdays 14:00`.' };
|
|
170
|
+
const time = parseTimeOfDay(second);
|
|
171
|
+
if (!time)
|
|
172
|
+
return { error: `Unrecognized time \`${second}\`. Try \`9am\`, \`14:00\`, \`9:30pm\`.` };
|
|
173
|
+
const cronExpr = `${time.minute} ${time.hour} * * ${dowField}`;
|
|
174
|
+
return {
|
|
175
|
+
parsed: {
|
|
176
|
+
kind: 'cron',
|
|
177
|
+
cronExpr,
|
|
178
|
+
humanDescription: `${dowLabel} at ${String(time.hour).padStart(2, '0')}:${String(time.minute).padStart(2, '0')}`,
|
|
179
|
+
},
|
|
180
|
+
consumed: 2,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
// Claude Code's own leading interval: `/loop 5m <prompt>`.
|
|
184
|
+
const bare = parseInterval(first);
|
|
185
|
+
if (bare) {
|
|
186
|
+
if ('error' in bare)
|
|
187
|
+
return bare;
|
|
188
|
+
return { parsed: bare.parsed, consumed: 1 };
|
|
189
|
+
}
|
|
190
|
+
return { error: `Couldn't parse schedule. Type \`/loop\` with no args to see examples.` };
|
|
191
|
+
}
|
|
192
|
+
/** `5m`, `2h`, `30s`, `1d` as an interval, or null when the token isn't one. */
|
|
193
|
+
function parseInterval(token) {
|
|
194
|
+
const match = token.toLowerCase().match(/^(\d+)([smhd])$/);
|
|
195
|
+
if (!match)
|
|
196
|
+
return null;
|
|
197
|
+
return intervalOf(parseInt(match[1], 10), match[2]);
|
|
198
|
+
}
|
|
199
|
+
function intervalOf(amount, unitKey) {
|
|
200
|
+
const unitMs = INTERVAL_UNITS[unitKey];
|
|
201
|
+
if (!unitMs)
|
|
202
|
+
return { error: `Unknown unit \`${unitKey}\`. Use s/m/h/d.` };
|
|
203
|
+
const intervalMs = amount * unitMs;
|
|
204
|
+
if (intervalMs < HARD_LIMITS.MIN_INTERVAL_MS) {
|
|
205
|
+
return { error: `Interval must be at least ${HARD_LIMITS.MIN_INTERVAL_MS / 1000}s.` };
|
|
206
|
+
}
|
|
207
|
+
return { parsed: { kind: 'interval', intervalMs, humanDescription: `every ${amount}${unitKey}` } };
|
|
208
|
+
}
|
|
209
|
+
/** Unit words a trailing every clause may spell out, as Claude Code's /loop reads them. */
|
|
210
|
+
const UNIT_WORDS = {
|
|
211
|
+
s: 's', sec: 's', secs: 's', second: 's', seconds: 's',
|
|
212
|
+
m: 'm', min: 'm', mins: 'm', minute: 'm', minutes: 'm',
|
|
213
|
+
h: 'h', hr: 'h', hrs: 'h', hour: 'h', hours: 'h',
|
|
214
|
+
d: 'd', day: 'd', days: 'd',
|
|
215
|
+
};
|
|
216
|
+
/**
|
|
217
|
+
* Claude Code's rule 2: a prompt ending in `every 20m` or `every 5 minutes`.
|
|
218
|
+
* Only a time follows the every; "check every PR" is a prompt with no interval.
|
|
219
|
+
*/
|
|
220
|
+
export function parseTrailingEvery(input) {
|
|
221
|
+
const match = input.match(/^(.*?)\s*\bevery\s+(\d+)\s*([a-z]+)\s*$/i);
|
|
222
|
+
if (!match)
|
|
223
|
+
return null;
|
|
224
|
+
const unit = UNIT_WORDS[match[3].toLowerCase()];
|
|
225
|
+
if (!unit)
|
|
226
|
+
return null;
|
|
227
|
+
const interval = intervalOf(parseInt(match[2], 10), unit);
|
|
228
|
+
if ('error' in interval)
|
|
229
|
+
return interval;
|
|
230
|
+
return { parsed: interval.parsed, prompt: match[1].trim() };
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* What /loop's input asks for: when, the prompt, and whether it runs at once,
|
|
234
|
+
* which an interval does (as in Claude Code) and a time of day doesn't.
|
|
235
|
+
*/
|
|
236
|
+
export function parseLoop(input) {
|
|
237
|
+
// Split off `--` first if present: everything before it is the schedule.
|
|
238
|
+
const sepIdx = input.indexOf(' -- ');
|
|
239
|
+
const tokens = (sepIdx >= 0 ? input.slice(0, sepIdx) : input).split(/\s+/).filter(Boolean);
|
|
240
|
+
const leading = parseWhen(tokens);
|
|
241
|
+
if (!('error' in leading)) {
|
|
242
|
+
const prompt = sepIdx >= 0 ? input.slice(sepIdx + 4).trim() : tokens.slice(leading.consumed).join(' ').trim();
|
|
243
|
+
if (!prompt)
|
|
244
|
+
return { error: 'Missing prompt. After the interval, add the prompt to run each time.' };
|
|
245
|
+
return { parsed: leading.parsed, prompt, runNow: leading.parsed.kind === 'interval' };
|
|
246
|
+
}
|
|
247
|
+
// A leading spec that is one but is wrong (`every 10x`, `daily 25:00`, `20s`) says so.
|
|
248
|
+
if (sepIdx >= 0 || looksLikeSpec(tokens[0] ?? ''))
|
|
249
|
+
return leading;
|
|
250
|
+
const trailing = parseTrailingEvery(input);
|
|
251
|
+
if (trailing) {
|
|
252
|
+
if ('error' in trailing)
|
|
253
|
+
return trailing;
|
|
254
|
+
if (!trailing.prompt)
|
|
255
|
+
return { error: 'Missing prompt. Before the every, add the prompt to run each time.' };
|
|
256
|
+
return { parsed: trailing.parsed, prompt: trailing.prompt, runNow: true };
|
|
257
|
+
}
|
|
258
|
+
return { noInterval: true };
|
|
259
|
+
}
|
|
260
|
+
/** Whether a first word starts a schedule, so an error in it is about the schedule. */
|
|
261
|
+
function looksLikeSpec(first) {
|
|
262
|
+
const word = first.toLowerCase();
|
|
263
|
+
return word === 'every' || word === 'daily' || word === 'weekdays' || word === 'weekends'
|
|
264
|
+
|| /^\d+[smhd]?$/.test(word) || word.split(',').every((p) => p in DAY_OF_WEEK);
|
|
265
|
+
}
|
|
266
|
+
function formatSchedule(s) {
|
|
267
|
+
const status = s.disabled ? ' (disabled)' : '';
|
|
268
|
+
const when = s.kind === 'interval'
|
|
269
|
+
? `every ${Math.round((s.intervalMs ?? 0) / 1000)}s`
|
|
270
|
+
: (s.cronExpr ?? '?');
|
|
271
|
+
const next = scheduler.nextFireAt(s.id);
|
|
272
|
+
const nextLine = next ? `\nnext: ${new Date(next).toLocaleString()}` : '';
|
|
273
|
+
const labelLine = s.label ? `\nlabel: ${s.label}` : '';
|
|
274
|
+
const promptPreview = s.prompt.length > 80 ? s.prompt.slice(0, 77) + '...' : s.prompt;
|
|
275
|
+
return new EntityText()
|
|
276
|
+
.code(s.id)
|
|
277
|
+
.add(`${status}\n${when}${labelLine}\nruns: ${s.runs}/${s.maxRuns}${nextLine}\nprompt: ${promptPreview}`)
|
|
278
|
+
.build();
|
|
279
|
+
}
|
|
280
|
+
export async function handleLoop(ctx) {
|
|
281
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
282
|
+
if (!keyInfo)
|
|
283
|
+
return;
|
|
284
|
+
const { sessionKey } = keyInfo;
|
|
285
|
+
const text = (ctx.message?.text ?? '').trim();
|
|
286
|
+
const stripped = text.replace(/^\/\w+(?:@\w+)?\s*/, '');
|
|
287
|
+
if (!stripped) {
|
|
288
|
+
await replyFormatted(ctx, USAGE);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
// Session required so the loop can resume into a real project later.
|
|
292
|
+
const session = sessionManager.getSession(sessionKey)
|
|
293
|
+
?? sessionManager.getOrRestoreSession(sessionKey).session;
|
|
294
|
+
if (!session) {
|
|
295
|
+
await replyFormatted(ctx, withCode('⚠️ No project set. Use `/dir` or `/resume` first, then start the loop.'));
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
// Split off options first so they don't get eaten by the parser.
|
|
299
|
+
const { prompt: input, maxRuns, label } = extractOptions(stripped);
|
|
300
|
+
const result = parseLoop(input);
|
|
301
|
+
if ('noInterval' in result) {
|
|
302
|
+
await replyFormatted(ctx, NO_INTERVAL);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if ('error' in result) {
|
|
306
|
+
await replyFormatted(ctx, joinMessages([withCode(`❌ ${result.error}`), USAGE]));
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const { parsed, prompt, runNow } = result;
|
|
310
|
+
const spec = {
|
|
311
|
+
sessionKey,
|
|
312
|
+
cwd: session.workingDirectory,
|
|
313
|
+
claudeSessionId: session.claudeSessionId,
|
|
314
|
+
prompt,
|
|
315
|
+
label,
|
|
316
|
+
maxRuns,
|
|
317
|
+
...(parsed.kind === 'interval'
|
|
318
|
+
? { kind: 'interval', intervalMs: parsed.intervalMs }
|
|
319
|
+
: { kind: 'cron', cronExpr: parsed.cronExpr }),
|
|
320
|
+
};
|
|
321
|
+
let created;
|
|
322
|
+
try {
|
|
323
|
+
created = scheduler.createSchedule(spec);
|
|
324
|
+
}
|
|
325
|
+
catch (err) {
|
|
326
|
+
await replyFormatted(ctx, `❌ ${err instanceof Error ? err.message : String(err)}`);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
const b = new EntityText()
|
|
330
|
+
.add('✅ ').bold('Loop started').newline()
|
|
331
|
+
.add(`when: ${parsed.humanDescription}\n`)
|
|
332
|
+
.add(`max runs: ${created.maxRuns}`);
|
|
333
|
+
const next = scheduler.nextFireAt(created.id);
|
|
334
|
+
if (runNow)
|
|
335
|
+
b.add('\nFirst run: now');
|
|
336
|
+
else if (next)
|
|
337
|
+
b.add('\nFirst run: ').code(new Date(next).toLocaleString());
|
|
338
|
+
b.newline(2).code('/loops').add(' lists your loops and stops one.');
|
|
339
|
+
await replyFormatted(ctx, b.build());
|
|
340
|
+
// Not awaited: the run queues behind this chat's turn like any message, and
|
|
341
|
+
// this command must not hold the chat while it does.
|
|
342
|
+
if (runNow)
|
|
343
|
+
void scheduler.fireNow(created.id);
|
|
344
|
+
}
|
|
345
|
+
const DELETE_PREFIX = 'loops:del:';
|
|
346
|
+
/** The /loops message: each loop, and a button per loop that stops it. */
|
|
347
|
+
function loopsMessage(sessionKey) {
|
|
348
|
+
const list = scheduler.listSchedules(sessionKey);
|
|
349
|
+
if (list.length === 0)
|
|
350
|
+
return null;
|
|
351
|
+
const heading = new EntityText().add('📋 ').bold('Loops').add(` (${list.length})`).build();
|
|
352
|
+
const keyboard = list.map((s) => {
|
|
353
|
+
const name = s.label ?? s.prompt;
|
|
354
|
+
const short = name.length > 40 ? name.slice(0, 39) + '…' : name;
|
|
355
|
+
return [{ text: `🗑 ${short}`, callback_data: `${DELETE_PREFIX}${s.id}` }];
|
|
356
|
+
});
|
|
357
|
+
return { text: joinMessages([heading, ...list.map(formatSchedule)]), keyboard };
|
|
358
|
+
}
|
|
359
|
+
const NO_LOOPS = withCode('No loops running. Start one with `/loop <interval> <prompt>`.');
|
|
360
|
+
export async function handleLoops(ctx) {
|
|
361
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
362
|
+
if (!keyInfo)
|
|
363
|
+
return;
|
|
364
|
+
const message = loopsMessage(keyInfo.sessionKey);
|
|
365
|
+
if (!message) {
|
|
366
|
+
await replyFormatted(ctx, NO_LOOPS);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
await replyFormatted(ctx, message.text, { reply_markup: { inline_keyboard: message.keyboard } });
|
|
370
|
+
}
|
|
371
|
+
/** A 🗑 under /loops: stop that loop, and show the list without it. */
|
|
372
|
+
export async function handleLoopsCallback(ctx) {
|
|
373
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
374
|
+
const data = ctx.callbackQuery?.data ?? '';
|
|
375
|
+
if (!keyInfo || !data.startsWith(DELETE_PREFIX))
|
|
376
|
+
return;
|
|
377
|
+
const id = data.slice(DELETE_PREFIX.length);
|
|
378
|
+
const target = scheduler.getSchedule(id);
|
|
379
|
+
if (!target || target.sessionKey !== keyInfo.sessionKey) {
|
|
380
|
+
await ctx.answerCallbackQuery({ text: 'That loop is already gone.' }).catch(() => { });
|
|
381
|
+
}
|
|
382
|
+
else {
|
|
383
|
+
scheduler.deleteSchedule(id);
|
|
384
|
+
await ctx.answerCallbackQuery({ text: 'Loop stopped.' }).catch(() => { });
|
|
385
|
+
}
|
|
386
|
+
const message = loopsMessage(keyInfo.sessionKey);
|
|
387
|
+
await editCallbackMessage(ctx, message?.text ?? NO_LOOPS, message ? { reply_markup: { inline_keyboard: message.keyboard } } : undefined).catch(() => { });
|
|
388
|
+
}
|
|
389
|
+
//# sourceMappingURL=loop.handler.js.map
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { EntityText } from '../../telegram/entities.js';
|
|
2
|
+
import { replyFormatted } from '../../telegram/send.js';
|
|
3
|
+
import { isDuplicate, markProcessed } from '../../telegram/deduplication.js';
|
|
4
|
+
import { isStaleMessage } from '../middleware/stale-filter.js';
|
|
5
|
+
/**
|
|
6
|
+
* Telegram caps what a bot may *download* at 20MB. `getFile` itself fails with
|
|
7
|
+
* "file is too big" past that, so no bot-side setting can raise it — the guard
|
|
8
|
+
* exists to turn an opaque Telegram 400 into an explanation.
|
|
9
|
+
*
|
|
10
|
+
* Not to be confused with the 50MB *send* limit in mcp-bridge.ts: outbound and
|
|
11
|
+
* inbound are separate budgets, and inbound is the tighter one. Only a
|
|
12
|
+
* self-hosted Bot API server in --local mode lifts this.
|
|
13
|
+
*/
|
|
14
|
+
export const TELEGRAM_DOWNLOAD_LIMIT_MB = 20;
|
|
15
|
+
export function exceedsDownloadLimit(fileSizeBytes) {
|
|
16
|
+
return (fileSizeBytes ?? 0) / (1024 * 1024) > TELEGRAM_DOWNLOAD_LIMIT_MB;
|
|
17
|
+
}
|
|
18
|
+
/** ` (172.0MB)` — or empty when Telegram omitted the size. */
|
|
19
|
+
function sizeSuffix(fileSizeBytes) {
|
|
20
|
+
const mb = (fileSizeBytes ?? 0) / (1024 * 1024);
|
|
21
|
+
return mb > 0 ? ` (${mb.toFixed(1)}MB)` : '';
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Explain that a file is past Telegram's download ceiling. Every inbound media
|
|
25
|
+
* path should call this instead of letting `getFile` throw, so the user learns
|
|
26
|
+
* the limit is Telegram's rather than a bug here.
|
|
27
|
+
*/
|
|
28
|
+
export async function replyTooLargeToFetch(ctx, kindTitle, fileSizeBytes) {
|
|
29
|
+
// Log the answer, not just the drops. The original bug was invisible in the
|
|
30
|
+
// logs precisely because nothing recorded a decision, and "user reports
|
|
31
|
+
// nothing arrived" is unfalsifiable without a line to point at.
|
|
32
|
+
console.log(`[Media] ${kindTitle} over the ${TELEGRAM_DOWNLOAD_LIMIT_MB}MB fetch limit `
|
|
33
|
+
+ `(${((fileSizeBytes ?? 0) / (1024 * 1024)).toFixed(1)}MB) — explained to user`);
|
|
34
|
+
await replyFormatted(ctx, new EntityText()
|
|
35
|
+
.add('❌ ').bold(`${kindTitle} too large`).add(sizeSuffix(fileSizeBytes)).add('\n\n')
|
|
36
|
+
.add(`Telegram caps bot downloads at ${TELEGRAM_DOWNLOAD_LIMIT_MB}MB, so I can't fetch this one `
|
|
37
|
+
+ 'no matter how the bot is configured.\n\n'
|
|
38
|
+
+ 'Re-encode it smaller, or — if the file is already on this machine — send me its path instead.')
|
|
39
|
+
.build());
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* An audio file. Only voice notes become prompts, so rather than dropping the
|
|
43
|
+
* file we say so; silence here read as "the bot is broken".
|
|
44
|
+
*/
|
|
45
|
+
export async function replyBareAudio(ctx, fileSizeBytes) {
|
|
46
|
+
if (exceedsDownloadLimit(fileSizeBytes)) {
|
|
47
|
+
await replyTooLargeToFetch(ctx, 'Audio file', fileSizeBytes);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
console.log('[Media] Audio upload — unsupported, told user');
|
|
51
|
+
await replyFormatted(ctx, new EntityText()
|
|
52
|
+
.add('🎵 ').bold('Audio received').add(sizeSuffix(fileSizeBytes)).add('\n\n')
|
|
53
|
+
.add("I can't read audio files. To talk to Claude, record a voice note instead, "
|
|
54
|
+
+ "or point me at the file's path if it's already on this machine.")
|
|
55
|
+
.build());
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Video, video notes and GIFs have no ingestion path at all. Previously these
|
|
59
|
+
* updates matched no handler whatsoever and vanished without a trace.
|
|
60
|
+
*/
|
|
61
|
+
export async function replyUnsupportedVideo(ctx, fileSizeBytes) {
|
|
62
|
+
if (exceedsDownloadLimit(fileSizeBytes)) {
|
|
63
|
+
await replyTooLargeToFetch(ctx, 'Video', fileSizeBytes);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
console.log('[Media] Video upload — unsupported, told user');
|
|
67
|
+
await replyFormatted(ctx, new EntityText()
|
|
68
|
+
.add('🎬 ').bold("Video isn't supported").add(sizeSuffix(fileSizeBytes)).add('\n\n')
|
|
69
|
+
.add("I can't read video files. Point me at the file's path if it's already on this machine.")
|
|
70
|
+
.build());
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Stale/duplicate gate, shared by every path that now *answers* instead of
|
|
74
|
+
* returning silently. Skipping it would mean a restart replying to each video
|
|
75
|
+
* and mp3 sent while the bot was down — noisier than the bug being fixed.
|
|
76
|
+
*
|
|
77
|
+
* Claims the message id on success, so callers must not delegate to another
|
|
78
|
+
* handler that runs its own dedup afterwards.
|
|
79
|
+
*/
|
|
80
|
+
function claimsMediaMessage(ctx, label) {
|
|
81
|
+
const messageId = ctx.message?.message_id;
|
|
82
|
+
const messageDate = ctx.message?.date;
|
|
83
|
+
if (!messageId || !messageDate)
|
|
84
|
+
return false;
|
|
85
|
+
if (isStaleMessage(messageDate)) {
|
|
86
|
+
console.log(`[Media] Ignoring stale ${label} ${messageId}`);
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
if (isDuplicate(messageId)) {
|
|
90
|
+
console.log(`[Media] Ignoring duplicate ${label} ${messageId}`);
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
markProcessed(messageId);
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Entry point for `message:video` / `message:video_note` / `message:animation`,
|
|
98
|
+
* none of which had a handler before.
|
|
99
|
+
*/
|
|
100
|
+
export async function handleUnsupportedVideo(ctx) {
|
|
101
|
+
if (!claimsMediaMessage(ctx, 'video'))
|
|
102
|
+
return;
|
|
103
|
+
const media = ctx.message?.video ?? ctx.message?.video_note ?? ctx.message?.animation;
|
|
104
|
+
await replyUnsupportedVideo(ctx, media?.file_size);
|
|
105
|
+
}
|
|
106
|
+
/** Entry point for `message:audio`: music and recordings, not voice notes. */
|
|
107
|
+
export async function handleUnsupportedAudio(ctx) {
|
|
108
|
+
if (!claimsMediaMessage(ctx, 'audio'))
|
|
109
|
+
return;
|
|
110
|
+
await replyBareAudio(ctx, ctx.message?.audio?.file_size);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Entry point for audio/video sent as a *document* — the path a 172MB mp3 takes
|
|
114
|
+
* when Telegram declines to treat it as playable audio.
|
|
115
|
+
*/
|
|
116
|
+
export async function handleUnsupportedMediaDocument(ctx) {
|
|
117
|
+
const doc = ctx.message?.document;
|
|
118
|
+
if (!doc || !claimsMediaMessage(ctx, 'media document'))
|
|
119
|
+
return;
|
|
120
|
+
if (doc.mime_type?.startsWith('video/')) {
|
|
121
|
+
await replyUnsupportedVideo(ctx, doc.file_size);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
await replyBareAudio(ctx, doc.file_size);
|
|
125
|
+
}
|
|
126
|
+
//# sourceMappingURL=media-fallback.js.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Handlers for replies to the bot's ForceReply prompts — the flows where a
|
|
3
|
+
* command posts a question and the user's *next* message is the answer
|
|
4
|
+
* (the /dir path).
|
|
5
|
+
*
|
|
6
|
+
* `handleMessage` routes here by the flow the prompt it is replying to opened
|
|
7
|
+
* (see force-reply-tracker.ts).
|
|
8
|
+
*/
|
|
9
|
+
import * as fs from 'fs';
|
|
10
|
+
import * as path from 'path';
|
|
11
|
+
import { clearConversation } from '../../../providers/provider-router.js';
|
|
12
|
+
import { prewarmClaude } from '../../../claude/prewarm.js';
|
|
13
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
14
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
15
|
+
import { replyFormatted } from '../../../telegram/send.js';
|
|
16
|
+
import { projectStatusSuffix, resumeCommandMessage, clearTopic, } from '../command.handler.js';
|
|
17
|
+
// Handle reply to project ForceReply prompt
|
|
18
|
+
export async function handleDirReply(ctx, sessionKey, projectPath) {
|
|
19
|
+
let resolvedPath = projectPath.trim();
|
|
20
|
+
// Handle ~ expansion
|
|
21
|
+
if (resolvedPath.startsWith('~')) {
|
|
22
|
+
resolvedPath = path.join(process.env.HOME || '', resolvedPath.slice(1));
|
|
23
|
+
}
|
|
24
|
+
// Resolve to absolute path. Manual path entry is treated as an explicit
|
|
25
|
+
// user choice and may point anywhere on disk (mirrors typing `/dir <abs>`).
|
|
26
|
+
resolvedPath = path.resolve(resolvedPath);
|
|
27
|
+
// Check if exists
|
|
28
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
29
|
+
await replyFormatted(ctx, new EntityText()
|
|
30
|
+
.add('❌ Path not found: ').code(resolvedPath).add('\n\nPlease check the path and try again.')
|
|
31
|
+
.build());
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
// Check if directory
|
|
35
|
+
if (!fs.statSync(resolvedPath).isDirectory()) {
|
|
36
|
+
await replyFormatted(ctx, new EntityText().add('❌ Not a directory: ').code(resolvedPath).build());
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
// Set the project
|
|
40
|
+
sessionManager.setWorkingDirectory(sessionKey, resolvedPath);
|
|
41
|
+
clearConversation(sessionKey);
|
|
42
|
+
clearTopic(sessionKey);
|
|
43
|
+
const projectName = path.basename(resolvedPath);
|
|
44
|
+
await replyFormatted(ctx, new EntityText()
|
|
45
|
+
.add('✅ Project set: ').bold(projectName).newline(2)
|
|
46
|
+
.code(resolvedPath).newline(2)
|
|
47
|
+
.add('You can now chat with Claude about this project!')
|
|
48
|
+
.append(projectStatusSuffix(sessionKey))
|
|
49
|
+
.build());
|
|
50
|
+
const s = sessionManager.getSession(sessionKey);
|
|
51
|
+
if (s?.claudeSessionId) {
|
|
52
|
+
await replyFormatted(ctx, resumeCommandMessage(s.claudeSessionId));
|
|
53
|
+
}
|
|
54
|
+
void prewarmClaude(ctx, sessionKey);
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=replies.js.map
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helpers shared by every message-handling entry point.
|
|
3
|
+
*
|
|
4
|
+
* These sit below the domain modules rather than inside any one of them:
|
|
5
|
+
* `handleMessage`, the ForceReply handlers and the turn runner all need
|
|
6
|
+
* them, so putting them in a domain module would make the other two import
|
|
7
|
+
* across domains for a two-line helper.
|
|
8
|
+
*/
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { config } from '../../../config.js';
|
|
11
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
12
|
+
import { queueRequest } from '../../../claude/request-queue.js';
|
|
13
|
+
import { summarizeTopicWithHaiku } from '../../../claude/auto-topic-haiku.js';
|
|
14
|
+
import { readLastAiTitle } from '../../../claude/session-jsonl.js';
|
|
15
|
+
import { namesThread } from '../../../telegram/thread-titles.js';
|
|
16
|
+
import { userPreferences } from '../../../providers/user-preferences.js';
|
|
17
|
+
import { parseSessionKey } from '../../../utils/session-key.js';
|
|
18
|
+
import { getSessionTopic, setSessionTopic } from '../command.handler.js';
|
|
19
|
+
import { getMsSinceTopicSet } from '../command/topic-store.js';
|
|
20
|
+
import { turnErrorReply } from '../../../claude/claude-auth.js';
|
|
21
|
+
export { requireSession } from '../session-guard.js';
|
|
22
|
+
export async function replyFeatureDisabled(ctx, feature) {
|
|
23
|
+
await ctx.reply(`⚠️ ${feature} feature is disabled in configuration.`);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Fire-and-forget topic update via a parallel Haiku call. Runs alongside
|
|
27
|
+
* the main agent turn so the status line and the thread name reflect the new
|
|
28
|
+
* topic almost immediately, without depending on the main agent calling
|
|
29
|
+
* telecoder_set_topic.
|
|
30
|
+
*/
|
|
31
|
+
export function fireAutoTopic(ctx, sessionKey, userMessage) {
|
|
32
|
+
if (!config.AUTO_TOPIC_HAIKU)
|
|
33
|
+
return;
|
|
34
|
+
// Fire if the topic will be visible somewhere — the status line or the
|
|
35
|
+
// thread's name. Skipping when nothing displays it avoids wasted Haiku calls.
|
|
36
|
+
const { chatId } = parseSessionKey(sessionKey);
|
|
37
|
+
const wantsTopic = userPreferences.getShowTopicInStatusLine(chatId)
|
|
38
|
+
|| namesThread(sessionKey);
|
|
39
|
+
if (!wantsTopic)
|
|
40
|
+
return;
|
|
41
|
+
void (async () => {
|
|
42
|
+
try {
|
|
43
|
+
const previousTopic = getSessionTopic(sessionKey);
|
|
44
|
+
const startedAt = Date.now();
|
|
45
|
+
const workingDirectory = sessionManager.getSession(sessionKey)?.workingDirectory;
|
|
46
|
+
let topic = await summarizeTopicWithHaiku(userMessage, previousTopic, workingDirectory ? path.basename(workingDirectory) : undefined);
|
|
47
|
+
// The agent (or the user's /topic) set one while Haiku was thinking:
|
|
48
|
+
// that topic is newer and deliberate, and Haiku's guess, made from the
|
|
49
|
+
// topic before it, would otherwise land a few seconds later on top.
|
|
50
|
+
const setSince = getMsSinceTopicSet(sessionKey);
|
|
51
|
+
if (setSince !== undefined && setSince < Date.now() - startedAt)
|
|
52
|
+
return;
|
|
53
|
+
// If Haiku failed AND we have no prior topic at all, seed from Claude
|
|
54
|
+
// Code's aiTitle so the status line shows *something* instead of staying
|
|
55
|
+
// blank until the next turn succeeds. With a prior topic we keep it.
|
|
56
|
+
if (!topic && !previousTopic) {
|
|
57
|
+
const session = sessionManager.getSession(sessionKey);
|
|
58
|
+
if (session?.claudeSessionId) {
|
|
59
|
+
topic = readLastAiTitle(session.workingDirectory, session.claudeSessionId);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (!topic)
|
|
63
|
+
return;
|
|
64
|
+
// Topic lives in the status line and the thread name, not the Telegram
|
|
65
|
+
// bot name, so no setMyName call.
|
|
66
|
+
setSessionTopic(sessionKey, topic);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
console.debug('[AutoTopic] Side-call update failed:', err instanceof Error ? err.message : err);
|
|
70
|
+
}
|
|
71
|
+
})();
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Queue a turn and turn any failure into a user-facing error.
|
|
75
|
+
*
|
|
76
|
+
* "Queue cleared" is the normal signal that a newer message superseded this
|
|
77
|
+
* one, so it exits quietly. Anything else is logged as well as reported —
|
|
78
|
+
* three of the four call sites this replaces only replied to the chat, which
|
|
79
|
+
* left failures in the suggestion-tap and throttle-retry paths
|
|
80
|
+
* invisible from the server side.
|
|
81
|
+
*/
|
|
82
|
+
export async function runQueuedTurn(ctx, sessionKey, message, label, run) {
|
|
83
|
+
try {
|
|
84
|
+
await queueRequest(sessionKey, message, run);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error.message === 'Queue cleared')
|
|
88
|
+
return;
|
|
89
|
+
console.error(`[${label}] Turn failed:`, error);
|
|
90
|
+
// An auth failure gets a reply saying how to sign in rather than the
|
|
91
|
+
// CLI's own "Please run /login", which nobody can do from a phone.
|
|
92
|
+
await ctx.reply(turnErrorReply(error));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=shared.js.map
|