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.
- package/.env.example +363 -0
- package/CHANGELOG.md +1186 -0
- package/LICENSE +22 -0
- package/README.md +126 -2
- package/dist/audio/transcribe.js +50 -0
- package/dist/bin/mcp-server.js +378 -0
- package/dist/bin/tool-result.js +22 -0
- package/dist/bot/access/group-access.js +147 -0
- package/dist/bot/bot.js +592 -0
- package/dist/bot/file-access.js +141 -0
- package/dist/bot/handlers/command/access.js +407 -0
- package/dist/bot/handlers/command/admin.js +827 -0
- package/dist/bot/handlers/command/auto-approve.js +138 -0
- package/dist/bot/handlers/command/btw.js +224 -0
- package/dist/bot/handlers/command/cost.js +409 -0
- package/dist/bot/handlers/command/media.js +197 -0
- package/dist/bot/handlers/command/model.js +305 -0
- package/dist/bot/handlers/command/prefs-scope.js +197 -0
- package/dist/bot/handlers/command/project.js +536 -0
- package/dist/bot/handlers/command/resume.js +321 -0
- package/dist/bot/handlers/command/session.js +438 -0
- package/dist/bot/handlers/command/settings.js +1012 -0
- package/dist/bot/handlers/command/shared.js +210 -0
- package/dist/bot/handlers/command/streaming-mode.js +16 -0
- package/dist/bot/handlers/command/tasks.js +513 -0
- package/dist/bot/handlers/command/topic-store.js +113 -0
- package/dist/bot/handlers/command/topic.js +80 -0
- package/dist/bot/handlers/command.handler.js +772 -0
- package/dist/bot/handlers/fork.handler.js +1109 -0
- package/dist/bot/handlers/media-fallback.js +121 -0
- package/dist/bot/handlers/message/replies.js +133 -0
- package/dist/bot/handlers/message/shared.js +117 -0
- package/dist/bot/handlers/message/throttle.js +49 -0
- package/dist/bot/handlers/message/turn-notify.js +169 -0
- package/dist/bot/handlers/message/turn-runner.js +141 -0
- package/dist/bot/handlers/message.handler.js +107 -0
- package/dist/bot/handlers/newbot.handler.js +221 -0
- package/dist/bot/handlers/photo.handler.js +327 -0
- package/dist/bot/handlers/prompts.handler.js +343 -0
- package/dist/bot/handlers/running-note.js +44 -0
- package/dist/bot/handlers/schedule.handler.js +303 -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 +209 -0
- package/dist/bot/middleware/admin-only.js +49 -0
- package/dist/bot/middleware/auth.middleware.js +122 -0
- package/dist/bot/middleware/group-mention.middleware.js +139 -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 +971 -0
- package/dist/bot/middleware/stale-filter.js +31 -0
- package/dist/build-info.json +8 -0
- package/dist/claude/agent-watchdog.js +162 -0
- package/dist/claude/agent.js +1458 -0
- package/dist/claude/ask-user.js +295 -0
- package/dist/claude/auto-approve.js +225 -0
- package/dist/claude/auto-topic-haiku.js +126 -0
- package/dist/claude/available-commands.js +153 -0
- package/dist/claude/carry-over.js +27 -0
- package/dist/claude/ccr-shim.js +46 -0
- package/dist/claude/charter-judge.js +214 -0
- package/dist/claude/claude-auth.js +121 -0
- package/dist/claude/command-parser.js +200 -0
- package/dist/claude/cost-overlay-scraper.js +129 -0
- package/dist/claude/enabled-plugins.js +56 -0
- package/dist/claude/fork-tree.js +393 -0
- package/dist/claude/held-query.js +190 -0
- package/dist/claude/in-flight-tracker.js +61 -0
- package/dist/claude/ipc-server.js +192 -0
- package/dist/claude/mcp-bridge.js +453 -0
- package/dist/claude/mcp-tools.js +354 -0
- package/dist/claude/message-offsets.js +88 -0
- package/dist/claude/modal-relay.js +450 -0
- package/dist/claude/model-catalog.js +85 -0
- package/dist/claude/monitor-relay.js +597 -0
- package/dist/claude/pending-forks.js +93 -0
- package/dist/claude/pending-suggestions.js +50 -0
- package/dist/claude/permission-gate.js +337 -0
- package/dist/claude/permission-mode.js +178 -0
- package/dist/claude/poll-user.js +51 -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-provider.js +2214 -0
- package/dist/claude/pty-spawn-config.js +296 -0
- package/dist/claude/pty-stream.js +363 -0
- package/dist/claude/request-queue.js +135 -0
- package/dist/claude/scheduled-runner.js +91 -0
- package/dist/claude/scheduler.js +237 -0
- package/dist/claude/scope-guard.js +274 -0
- package/dist/claude/sdk-permission-gate.js +77 -0
- package/dist/claude/secret-request.js +576 -0
- package/dist/claude/session-cost.js +41 -0
- package/dist/claude/session-history.js +286 -0
- package/dist/claude/session-jsonl.js +920 -0
- package/dist/claude/session-manager.js +195 -0
- package/dist/claude/session-scan.js +270 -0
- package/dist/claude/setup-token.js +285 -0
- package/dist/claude/side-call-options.js +45 -0
- package/dist/claude/side-question.js +249 -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/system-prompt.js +162 -0
- package/dist/claude/tasks-overlay-scraper.js +94 -0
- package/dist/claude/tip-scraper.js +78 -0
- package/dist/claude/tui-modal.js +501 -0
- package/dist/claude/tui-state.js +384 -0
- package/dist/claude/turn-end.js +91 -0
- package/dist/claude/turn-prose.js +64 -0
- package/dist/claude/update-banner-relay.js +70 -0
- package/dist/cli/commands/doctor.js +305 -0
- package/dist/cli/commands/help.js +25 -0
- package/dist/cli/commands/init.js +123 -0
- package/dist/cli/commands/service.js +678 -0
- package/dist/cli/commands/start.js +53 -0
- package/dist/cli/commands/version.js +11 -0
- package/dist/cli/dispatch.js +79 -0
- package/dist/cli/init/env-file.js +99 -0
- package/dist/cli/init/flow.js +638 -0
- package/dist/cli/init/prompter.js +116 -0
- package/dist/cli/init/telegram.js +94 -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 +500 -0
- package/dist/index.js +367 -0
- package/dist/launcher.js +933 -0
- package/dist/node-version-check.js +27 -0
- package/dist/providers/ccr-health.js +119 -0
- package/dist/providers/ccr-introspect.js +149 -0
- package/dist/providers/ccr-provider.js +60 -0
- package/dist/providers/claude-provider.js +63 -0
- package/dist/providers/prefs-sync.js +164 -0
- package/dist/providers/project-favorites.js +74 -0
- package/dist/providers/provider-router.js +127 -0
- package/dist/providers/provider-switch.js +91 -0
- package/dist/providers/sdk-provider.js +37 -0
- package/dist/providers/types.js +8 -0
- package/dist/providers/user-preferences.js +214 -0
- package/dist/restart-when-idle.js +153 -0
- package/dist/startup/auto-continue.js +67 -0
- package/dist/startup/auto-resume.js +173 -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 +684 -0
- package/dist/telegram/admin-mention.js +107 -0
- package/dist/telegram/background-activity-card.js +502 -0
- package/dist/telegram/botname-settings.js +336 -0
- package/dist/telegram/button-text.js +26 -0
- package/dist/telegram/client-options.js +27 -0
- package/dist/telegram/deduplication.js +33 -0
- package/dist/telegram/entities.js +295 -0
- package/dist/telegram/force-reply-tracker.js +57 -0
- package/dist/telegram/lettered-options.js +87 -0
- package/dist/telegram/markdown.js +362 -0
- package/dist/telegram/message-sender.js +1287 -0
- package/dist/telegram/prompt-label.js +142 -0
- package/dist/telegram/prompt-suggestion.js +54 -0
- package/dist/telegram/send.js +123 -0
- package/dist/telegram/streaming-turn.js +105 -0
- package/dist/telegram/suggestions-settings.js +30 -0
- package/dist/telegram/task-list.js +367 -0
- package/dist/telegram/task-tracker.js +209 -0
- package/dist/telegram/telegraph-settings.js +31 -0
- package/dist/telegram/telegraph.js +453 -0
- package/dist/telegram/terminal-renderer.js +671 -0
- package/dist/telegram/terminal-settings.js +25 -0
- package/dist/telegram/thread-titles.js +190 -0
- package/dist/telegram/threads-setup.js +117 -0
- package/dist/tts/tts-settings.js +62 -0
- package/dist/tts/tts.js +245 -0
- package/dist/tts/voice-reply.js +78 -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-token.js +74 -0
- package/dist/utils/bounded-map.js +55 -0
- package/dist/utils/build-info.js +57 -0
- package/dist/utils/caffeinate.js +50 -0
- package/dist/utils/claude-env.js +54 -0
- package/dist/utils/claude-version.js +48 -0
- package/dist/utils/config-home.js +62 -0
- package/dist/utils/debug-agent.js +117 -0
- package/dist/utils/debug-watchdog.js +121 -0
- package/dist/utils/download.js +111 -0
- package/dist/utils/exit-codes.js +48 -0
- package/dist/utils/file-type.js +149 -0
- package/dist/utils/format.js +81 -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/npm-version.js +134 -0
- package/dist/utils/prefs-relay.js +107 -0
- package/dist/utils/proc-children.js +102 -0
- package/dist/utils/project-data-dir.js +33 -0
- package/dist/utils/reasoning-summary.js +12 -0
- package/dist/utils/resolve-bin.js +86 -0
- package/dist/utils/resolve-claude-bin.js +63 -0
- package/dist/utils/respawn-backoff.js +19 -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/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 +76 -4
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { config } from '../../config.js';
|
|
4
|
+
import { sendToAgent } from '../../providers/provider-router.js';
|
|
5
|
+
import { sessionManager } from '../../claude/session-manager.js';
|
|
6
|
+
import { messageSender } from '../../telegram/message-sender.js';
|
|
7
|
+
import { closeTurn, relayCatchUpIfMissed } from './message/turn-notify.js';
|
|
8
|
+
import { isDuplicate, markProcessed } from '../../telegram/deduplication.js';
|
|
9
|
+
import { isStaleMessage } from '../middleware/stale-filter.js';
|
|
10
|
+
import { queueRequest, setAbortController, } from '../../claude/request-queue.js';
|
|
11
|
+
import { getStreamingMode } from './command.handler.js';
|
|
12
|
+
import { downloadFileSecure, getTelegramFileUrl } from '../../utils/download.js';
|
|
13
|
+
import { sanitizeError } from '../../utils/sanitize.js';
|
|
14
|
+
import { isValidImageFile, getFileType } from '../../utils/file-type.js';
|
|
15
|
+
import { getSessionKeyFromCtx } from '../../utils/session-key.js';
|
|
16
|
+
import { requireSession } from './session-guard.js';
|
|
17
|
+
import { progressCallbacks, withStreamingTurn } from '../../telegram/streaming-turn.js';
|
|
18
|
+
import { ensureProjectDataDir } from '../../utils/project-data-dir.js';
|
|
19
|
+
function sanitizeFileName(name) {
|
|
20
|
+
return path.basename(name).replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
21
|
+
}
|
|
22
|
+
function ensureUploadsDir(projectDir) {
|
|
23
|
+
return ensureProjectDataDir(projectDir, 'uploads');
|
|
24
|
+
}
|
|
25
|
+
function pickLargestPhoto(photoSizes) {
|
|
26
|
+
return photoSizes.reduce((best, current) => {
|
|
27
|
+
const bestSize = best.file_size || 0;
|
|
28
|
+
const currentSize = current.file_size || 0;
|
|
29
|
+
return currentSize > bestSize ? current : best;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async function downloadTelegramFile(ctx, fileId, destPath) {
|
|
33
|
+
const file = await ctx.api.getFile(fileId);
|
|
34
|
+
if (!file.file_path) {
|
|
35
|
+
throw new Error('Telegram did not provide file_path for this image.');
|
|
36
|
+
}
|
|
37
|
+
const fileUrl = getTelegramFileUrl(config.TELEGRAM_BOT_TOKEN, file.file_path);
|
|
38
|
+
await downloadFileSecure(fileUrl, destPath);
|
|
39
|
+
return file.file_path;
|
|
40
|
+
}
|
|
41
|
+
function getMediaType(filePath) {
|
|
42
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
43
|
+
const mimeTypes = {
|
|
44
|
+
'.jpg': 'image/jpeg',
|
|
45
|
+
'.jpeg': 'image/jpeg',
|
|
46
|
+
'.png': 'image/png',
|
|
47
|
+
'.gif': 'image/gif',
|
|
48
|
+
'.webp': 'image/webp',
|
|
49
|
+
};
|
|
50
|
+
return mimeTypes[ext] || 'image/jpeg';
|
|
51
|
+
}
|
|
52
|
+
async function handleSavedImage(ctx, savedPath, caption) {
|
|
53
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
54
|
+
if (!keyInfo)
|
|
55
|
+
return;
|
|
56
|
+
const { sessionKey } = keyInfo;
|
|
57
|
+
const session = sessionManager.getSession(sessionKey);
|
|
58
|
+
if (!session)
|
|
59
|
+
return;
|
|
60
|
+
const relativePath = path.relative(session.workingDirectory, savedPath);
|
|
61
|
+
const captionText = caption?.trim();
|
|
62
|
+
const noteLines = [
|
|
63
|
+
'User uploaded an image to the project.',
|
|
64
|
+
`Saved at: ${savedPath}`,
|
|
65
|
+
`Relative path: ${relativePath}`,
|
|
66
|
+
captionText ? `Caption: "${captionText}"` : 'Caption: (none)',
|
|
67
|
+
'The image is attached as a vision input โ you can see it directly.',
|
|
68
|
+
'If the caption includes a question or request, answer it. Otherwise, describe what you see and ask if they want any analysis or edits.',
|
|
69
|
+
];
|
|
70
|
+
const agentPrompt = noteLines.join('\n');
|
|
71
|
+
// Read image as base64 for multimodal vision input
|
|
72
|
+
const imageBase64 = fs.readFileSync(savedPath).toString('base64');
|
|
73
|
+
const mediaType = getMediaType(savedPath);
|
|
74
|
+
// savedPath is what the note above names in "Saved at:", and naming it is
|
|
75
|
+
// what makes claude attach it in pty mode โ so hand the provider that same
|
|
76
|
+
// path rather than letting it stage a duplicate copy of the same picture.
|
|
77
|
+
const images = [{ data: imageBase64, mediaType, path: savedPath }];
|
|
78
|
+
await queueRequest(sessionKey, agentPrompt, async () => {
|
|
79
|
+
if (getStreamingMode() === 'streaming') {
|
|
80
|
+
const startTime = Date.now();
|
|
81
|
+
await withStreamingTurn(ctx, sessionKey, agentPrompt, async (abortController) => {
|
|
82
|
+
const response = await sendToAgent(sessionKey, agentPrompt, {
|
|
83
|
+
...progressCallbacks(ctx),
|
|
84
|
+
abortController,
|
|
85
|
+
images,
|
|
86
|
+
telegramCtx: ctx,
|
|
87
|
+
});
|
|
88
|
+
await messageSender.finishStreaming(ctx, response.text);
|
|
89
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
90
|
+
await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
|
|
91
|
+
await closeTurn(ctx, sessionKey, response, agentPrompt);
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
await ctx.replyWithChatAction('typing');
|
|
96
|
+
const abortController = new AbortController();
|
|
97
|
+
setAbortController(sessionKey, abortController);
|
|
98
|
+
const response = await sendToAgent(sessionKey, agentPrompt, {
|
|
99
|
+
abortController,
|
|
100
|
+
images,
|
|
101
|
+
telegramCtx: ctx,
|
|
102
|
+
});
|
|
103
|
+
await messageSender.sendMessage(ctx, response.text);
|
|
104
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
105
|
+
await closeTurn(ctx, sessionKey, response, agentPrompt);
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
export async function handlePhoto(ctx) {
|
|
110
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
111
|
+
const messageId = ctx.message?.message_id;
|
|
112
|
+
const messageDate = ctx.message?.date;
|
|
113
|
+
const photos = ctx.message?.photo;
|
|
114
|
+
if (!keyInfo || !messageId || !messageDate || !photos || photos.length === 0)
|
|
115
|
+
return;
|
|
116
|
+
const { sessionKey } = keyInfo;
|
|
117
|
+
if (isStaleMessage(messageDate)) {
|
|
118
|
+
console.log(`[Photo] Ignoring stale photo message ${messageId}`);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (isDuplicate(messageId)) {
|
|
122
|
+
console.log(`[Photo] Ignoring duplicate photo message ${messageId}`);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
markProcessed(messageId);
|
|
126
|
+
const session = await requireSession(ctx, sessionKey);
|
|
127
|
+
if (!session)
|
|
128
|
+
return;
|
|
129
|
+
const largest = pickLargestPhoto(photos);
|
|
130
|
+
const fileSizeBytes = largest.file_size || 0;
|
|
131
|
+
const fileSizeMB = fileSizeBytes / (1024 * 1024);
|
|
132
|
+
if (fileSizeMB > config.IMAGE_MAX_FILE_SIZE_MB) {
|
|
133
|
+
await ctx.reply(`โ Image too large (${fileSizeMB.toFixed(1)}MB).\n\nPlease send images under ${config.IMAGE_MAX_FILE_SIZE_MB}MB.`);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const uploadsDir = ensureUploadsDir(session.workingDirectory);
|
|
137
|
+
const timestamp = Date.now();
|
|
138
|
+
const safeUniqueId = sanitizeFileName(largest.file_unique_id);
|
|
139
|
+
const fallbackName = `photo_${timestamp}_${safeUniqueId}.jpg`;
|
|
140
|
+
const destPath = path.join(uploadsDir, fallbackName);
|
|
141
|
+
try {
|
|
142
|
+
const filePath = await downloadTelegramFile(ctx, largest.file_id, destPath);
|
|
143
|
+
// Validate file content via magic bytes (defense against spoofed MIME types)
|
|
144
|
+
let isValid = false;
|
|
145
|
+
try {
|
|
146
|
+
isValid = isValidImageFile(destPath);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// Validation threw โ treat as invalid
|
|
150
|
+
}
|
|
151
|
+
if (!isValid) {
|
|
152
|
+
if (fs.existsSync(destPath))
|
|
153
|
+
fs.unlinkSync(destPath);
|
|
154
|
+
throw new Error('Downloaded file is not a valid image.');
|
|
155
|
+
}
|
|
156
|
+
// Get actual file type from magic bytes instead of trusting extension
|
|
157
|
+
const actualType = getFileType(destPath);
|
|
158
|
+
const rawExt = actualType?.extension || path.extname(filePath) || '.jpg';
|
|
159
|
+
const ext = rawExt.startsWith('.') ? rawExt : `.${rawExt}`;
|
|
160
|
+
const finalPath = ext && ext !== '.jpg'
|
|
161
|
+
? destPath.replace(/\.jpg$/, ext)
|
|
162
|
+
: destPath;
|
|
163
|
+
if (finalPath !== destPath) {
|
|
164
|
+
fs.renameSync(destPath, finalPath);
|
|
165
|
+
}
|
|
166
|
+
const buffer = fs.readFileSync(finalPath);
|
|
167
|
+
if (!buffer.length) {
|
|
168
|
+
throw new Error('Downloaded image is empty.');
|
|
169
|
+
}
|
|
170
|
+
await handleSavedImage(ctx, finalPath, ctx.message?.caption);
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
const errorMessage = sanitizeError(error);
|
|
174
|
+
console.error('[Photo] Error:', errorMessage);
|
|
175
|
+
await ctx.reply(`โ Image error: ${errorMessage}`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Handle non-image, non-audio document uploads (PDFs, .txt, .csv, .md, code
|
|
180
|
+
* files, etc.). Saves to the project's uploads dir and prompts claude to
|
|
181
|
+
* Read the file. Image and audio MIME types are filtered out before this
|
|
182
|
+
* runs by the dispatcher in bot.ts.
|
|
183
|
+
*/
|
|
184
|
+
export async function handleTextDocument(ctx) {
|
|
185
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
186
|
+
const messageId = ctx.message?.message_id;
|
|
187
|
+
const messageDate = ctx.message?.date;
|
|
188
|
+
const document = ctx.message?.document;
|
|
189
|
+
if (!keyInfo || !messageId || !messageDate || !document)
|
|
190
|
+
return;
|
|
191
|
+
const { sessionKey } = keyInfo;
|
|
192
|
+
if (isStaleMessage(messageDate)) {
|
|
193
|
+
console.log(`[Doc] Ignoring stale document ${messageId}`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (isDuplicate(messageId)) {
|
|
197
|
+
console.log(`[Doc] Ignoring duplicate document ${messageId}`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
markProcessed(messageId);
|
|
201
|
+
const session = await requireSession(ctx, sessionKey);
|
|
202
|
+
if (!session)
|
|
203
|
+
return;
|
|
204
|
+
const fileSizeMB = (document.file_size || 0) / (1024 * 1024);
|
|
205
|
+
if (fileSizeMB > config.DOCUMENT_MAX_FILE_SIZE_MB) {
|
|
206
|
+
await ctx.reply(`โ Document too large (${fileSizeMB.toFixed(1)}MB). Limit: ${config.DOCUMENT_MAX_FILE_SIZE_MB}MB.`);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const uploadsDir = ensureUploadsDir(session.workingDirectory);
|
|
210
|
+
const timestamp = Date.now();
|
|
211
|
+
const originalName = document.file_name ? sanitizeFileName(document.file_name) : `file_${document.file_unique_id}`;
|
|
212
|
+
const destPath = path.join(uploadsDir, `${timestamp}_${originalName}`);
|
|
213
|
+
try {
|
|
214
|
+
await downloadTelegramFile(ctx, document.file_id, destPath);
|
|
215
|
+
if (!fs.existsSync(destPath) || fs.statSync(destPath).size === 0) {
|
|
216
|
+
throw new Error('Downloaded document is empty.');
|
|
217
|
+
}
|
|
218
|
+
const relativePath = path.relative(session.workingDirectory, destPath);
|
|
219
|
+
const caption = ctx.message?.caption?.trim();
|
|
220
|
+
const noteLines = [
|
|
221
|
+
`User uploaded a file: ${document.file_name ?? originalName}`,
|
|
222
|
+
`Saved at: ${destPath}`,
|
|
223
|
+
`Relative path: ${relativePath}`,
|
|
224
|
+
caption ? `Caption: "${caption}"` : 'Caption: (none)',
|
|
225
|
+
'Use the Read tool to read its contents. For PDFs use Read with `pages` for large files.',
|
|
226
|
+
'If the caption asks a question, answer it based on the file. Otherwise summarize the contents and ask if they want a specific analysis.',
|
|
227
|
+
];
|
|
228
|
+
const agentPrompt = noteLines.join('\n');
|
|
229
|
+
await queueRequest(sessionKey, agentPrompt, async () => {
|
|
230
|
+
if (getStreamingMode() === 'streaming') {
|
|
231
|
+
const startTime = Date.now();
|
|
232
|
+
await withStreamingTurn(ctx, sessionKey, agentPrompt, async (abortController) => {
|
|
233
|
+
const response = await sendToAgent(sessionKey, agentPrompt, {
|
|
234
|
+
...progressCallbacks(ctx),
|
|
235
|
+
abortController,
|
|
236
|
+
telegramCtx: ctx,
|
|
237
|
+
});
|
|
238
|
+
await messageSender.finishStreaming(ctx, response.text);
|
|
239
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
240
|
+
await messageSender.sendCompletionNotification(ctx, Date.now() - startTime);
|
|
241
|
+
await closeTurn(ctx, sessionKey, response, agentPrompt);
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
await ctx.replyWithChatAction('typing');
|
|
246
|
+
const abortController = new AbortController();
|
|
247
|
+
setAbortController(sessionKey, abortController);
|
|
248
|
+
const response = await sendToAgent(sessionKey, agentPrompt, {
|
|
249
|
+
abortController,
|
|
250
|
+
telegramCtx: ctx,
|
|
251
|
+
});
|
|
252
|
+
await messageSender.sendMessage(ctx, response.text);
|
|
253
|
+
await relayCatchUpIfMissed(ctx, sessionKey, response.text || '');
|
|
254
|
+
await closeTurn(ctx, sessionKey, response, agentPrompt);
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
const errorMessage = sanitizeError(error);
|
|
260
|
+
console.error('[Doc] Error:', errorMessage);
|
|
261
|
+
await ctx.reply(`โ Document error: ${errorMessage}`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
export async function handleImageDocument(ctx) {
|
|
265
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
266
|
+
const messageId = ctx.message?.message_id;
|
|
267
|
+
const messageDate = ctx.message?.date;
|
|
268
|
+
const document = ctx.message?.document;
|
|
269
|
+
if (!keyInfo || !messageId || !messageDate || !document)
|
|
270
|
+
return;
|
|
271
|
+
const { sessionKey } = keyInfo;
|
|
272
|
+
// Only handle image documents
|
|
273
|
+
if (!document.mime_type || !document.mime_type.startsWith('image/')) {
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (isStaleMessage(messageDate)) {
|
|
277
|
+
console.log(`[ImageDoc] Ignoring stale document ${messageId}`);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
if (isDuplicate(messageId)) {
|
|
281
|
+
console.log(`[ImageDoc] Ignoring duplicate document ${messageId}`);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
markProcessed(messageId);
|
|
285
|
+
const session = await requireSession(ctx, sessionKey);
|
|
286
|
+
if (!session)
|
|
287
|
+
return;
|
|
288
|
+
const fileSizeBytes = document.file_size || 0;
|
|
289
|
+
const fileSizeMB = fileSizeBytes / (1024 * 1024);
|
|
290
|
+
if (fileSizeMB > config.IMAGE_MAX_FILE_SIZE_MB) {
|
|
291
|
+
await ctx.reply(`โ Image too large (${fileSizeMB.toFixed(1)}MB).\n\nPlease send images under ${config.IMAGE_MAX_FILE_SIZE_MB}MB.`);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const uploadsDir = ensureUploadsDir(session.workingDirectory);
|
|
295
|
+
const timestamp = Date.now();
|
|
296
|
+
const originalName = document.file_name ? sanitizeFileName(document.file_name) : '';
|
|
297
|
+
const ext = originalName.includes('.') ? '' : '.jpg';
|
|
298
|
+
const baseName = originalName || `image_${timestamp}_${document.file_unique_id}${ext}`;
|
|
299
|
+
const destPath = path.join(uploadsDir, `${timestamp}_${baseName}`);
|
|
300
|
+
try {
|
|
301
|
+
await downloadTelegramFile(ctx, document.file_id, destPath);
|
|
302
|
+
// Validate file content via magic bytes (defense against spoofed MIME types)
|
|
303
|
+
let isValid = false;
|
|
304
|
+
try {
|
|
305
|
+
isValid = isValidImageFile(destPath);
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
// Validation threw โ treat as invalid
|
|
309
|
+
}
|
|
310
|
+
if (!isValid) {
|
|
311
|
+
if (fs.existsSync(destPath))
|
|
312
|
+
fs.unlinkSync(destPath);
|
|
313
|
+
throw new Error('Downloaded file is not a valid image.');
|
|
314
|
+
}
|
|
315
|
+
const buffer = fs.readFileSync(destPath);
|
|
316
|
+
if (!buffer.length) {
|
|
317
|
+
throw new Error('Downloaded image is empty.');
|
|
318
|
+
}
|
|
319
|
+
await handleSavedImage(ctx, destPath, ctx.message?.caption);
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
const errorMessage = sanitizeError(error);
|
|
323
|
+
console.error('[ImageDoc] Error:', errorMessage);
|
|
324
|
+
await ctx.reply(`โ Image error: ${errorMessage}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
//# sourceMappingURL=photo.handler.js.map
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /prompts โ what you typed in a conversation, a line each, and a way back to
|
|
3
|
+
* any point in it.
|
|
4
|
+
*
|
|
5
|
+
* The list answers "what was this conversation about?" without paying for the
|
|
6
|
+
* replies again โ that's the whole difference from /recap, which re-sends
|
|
7
|
+
* every reply in full and buries the prompts you came back to read. It keys
|
|
8
|
+
* each prompt by a letter the way /tree keys its points, and the buttons are
|
|
9
|
+
* just the letters. A letter opens its prompt โ the exchange it started โ and
|
|
10
|
+
* what can be done from where that exchange ended:
|
|
11
|
+
*
|
|
12
|
+
* ๐ฑ New branch from here carry on just after that reply, in a new
|
|
13
|
+
* conversation; this one stays in /resume
|
|
14
|
+
*
|
|
15
|
+
* which is the ๐ด Fork button under that reply, without scrolling up to it.
|
|
16
|
+
* A prompt another branch already splits off at is marked ๐ฟ, and ๐ณ shows
|
|
17
|
+
* the tree, where that branch can be carried on.
|
|
18
|
+
*
|
|
19
|
+
* Callback data has to fit in 64 bytes. A prompt is named by its record's
|
|
20
|
+
* uuid, and its conversation by the first 8 characters of the session id:
|
|
21
|
+
*
|
|
22
|
+
* prompts:l:<session8>:<n> the list, of the last n prompts
|
|
23
|
+
* prompts:o:<session8>:<n>:<uuid> open a prompt; n is for the way back
|
|
24
|
+
* prompts:b:<session8>:<uuid> branch from the end of its exchange
|
|
25
|
+
*
|
|
26
|
+
* Every tap re-reads the transcript, which only ever grows, so a message sent
|
|
27
|
+
* before the conversation moved on still finds each prompt where it was.
|
|
28
|
+
*/
|
|
29
|
+
import * as fs from 'fs';
|
|
30
|
+
import * as path from 'path';
|
|
31
|
+
import { BOT_ID, config } from '../../config.js';
|
|
32
|
+
import { getSessionKeyFromCtx } from '../../utils/session-key.js';
|
|
33
|
+
import { sanitizeError } from '../../utils/sanitize.js';
|
|
34
|
+
import { findHistoryOwners } from '../../claude/session-history.js';
|
|
35
|
+
import { isProcessing } from '../../claude/request-queue.js';
|
|
36
|
+
import { lastAssistantTurnText, lastExchangeIn, sessionJsonlPath, userPromptsIn, } from '../../claude/session-jsonl.js';
|
|
37
|
+
import { splitsAlong, transcriptDir, treeOf } from '../../claude/fork-tree.js';
|
|
38
|
+
import { EntityText, joinMessages, plain } from '../../telegram/entities.js';
|
|
39
|
+
import { replyFormatted } from '../../telegram/send.js';
|
|
40
|
+
import { buildLetterKeyboard, optionLetter } from '../../telegram/lettered-options.js';
|
|
41
|
+
import { cutLabel, promptLabel } from '../../telegram/prompt-label.js';
|
|
42
|
+
import { getSessionTopic } from './command.handler.js';
|
|
43
|
+
import { formatTimeAgo } from './command/shared.js';
|
|
44
|
+
import { NO_PROJECT_MESSAGE, whereChatIs } from './session-guard.js';
|
|
45
|
+
import { LEFT_ABOVE, loadFork, replyQuote, youLine } from './fork.handler.js';
|
|
46
|
+
import { showTreeButton } from './tree.handler.js';
|
|
47
|
+
import { refuseWhileBusy, sendView } from './view.js';
|
|
48
|
+
// Most prompts are short (a median line of 72 characters across 40 recent
|
|
49
|
+
// sessions), so the default can reach well back: 15 fit in one message in all
|
|
50
|
+
// 40, about two phone screens. 25 fit in 35 of them, and the budget below cuts
|
|
51
|
+
// the rest oldest-first, so a higher cap would mostly buy a "trimmed" note.
|
|
52
|
+
// Past 300 characters a prompt shows by its start and its end, as /tree and
|
|
53
|
+
// the status line show one.
|
|
54
|
+
const PROMPTS_MAX_CHARS = 300;
|
|
55
|
+
const PROMPTS_DEFAULT_N = 15;
|
|
56
|
+
const PROMPTS_MAX_N = 25;
|
|
57
|
+
// Telegram's hard cap is 4096 chars per message. Budget below it for the
|
|
58
|
+
// lines, leaving room for the header, the legend and the newlines.
|
|
59
|
+
const PROMPTS_BUDGET_CHARS = 3800;
|
|
60
|
+
/**
|
|
61
|
+
* How much of the reply a prompt's view shows: as much as a /tree point's
|
|
62
|
+
* view. It's a menu, read before choosing, and the whole reply is up in the
|
|
63
|
+
* chat.
|
|
64
|
+
*/
|
|
65
|
+
const PROMPT_REPLY_LEN = 1200;
|
|
66
|
+
/** The first 8 characters of a session id: enough to find it among one project's transcripts. */
|
|
67
|
+
const session8Of = (conversation) => conversation.sessionId.slice(0, 8);
|
|
68
|
+
// โโ Reading โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
69
|
+
function readConversation(projectPath, sessionId) {
|
|
70
|
+
let raw;
|
|
71
|
+
try {
|
|
72
|
+
raw = fs.readFileSync(sessionJsonlPath(projectPath, sessionId), 'utf-8');
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
// A /compact and the records it leaves aren't prompts, and would each take
|
|
78
|
+
// one of the n lines.
|
|
79
|
+
const turns = userPromptsIn(raw).flatMap((p) => {
|
|
80
|
+
const label = promptLabel(p.text);
|
|
81
|
+
return label ? [{ ...p, label }] : [];
|
|
82
|
+
});
|
|
83
|
+
// A branch splitting off anywhere between one prompt and the next splits off
|
|
84
|
+
// during the first one's exchange.
|
|
85
|
+
const tree = treeOf(projectPath, sessionId);
|
|
86
|
+
const forked = tree && tree.transcripts.size > 1 ? tree : undefined;
|
|
87
|
+
const splits = forked ? splitsAlong(forked, sessionId) : [];
|
|
88
|
+
const prompts = turns.map((p, i) => {
|
|
89
|
+
const next = turns[i + 1]?.line ?? Infinity;
|
|
90
|
+
return { ...p, branched: splits.some((s) => s.line >= p.line && s.line < next) };
|
|
91
|
+
});
|
|
92
|
+
return { projectPath, sessionId, raw, prompts, tree: forked };
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The conversation a button names by `session8`, in the chat's project โ the
|
|
96
|
+
* chat's own when its id starts that way โ holding the prompt `uuid` when one
|
|
97
|
+
* is named.
|
|
98
|
+
*/
|
|
99
|
+
function findConversation(projectPath, session8, chatSessionId, uuid) {
|
|
100
|
+
const holds = (c) => c && (!uuid || c.prompts.some((p) => p.uuid === uuid));
|
|
101
|
+
if (chatSessionId?.startsWith(session8)) {
|
|
102
|
+
const conversation = readConversation(projectPath, chatSessionId);
|
|
103
|
+
if (holds(conversation))
|
|
104
|
+
return conversation;
|
|
105
|
+
}
|
|
106
|
+
let names = [];
|
|
107
|
+
try {
|
|
108
|
+
names = fs.readdirSync(transcriptDir(projectPath));
|
|
109
|
+
}
|
|
110
|
+
catch { /* nothing has run in this project */ }
|
|
111
|
+
for (const name of names) {
|
|
112
|
+
if (!name.startsWith(session8) || !name.endsWith('.jsonl'))
|
|
113
|
+
continue;
|
|
114
|
+
const sessionId = name.slice(0, -'.jsonl'.length);
|
|
115
|
+
if (sessionId === chatSessionId)
|
|
116
|
+
continue;
|
|
117
|
+
const conversation = readConversation(projectPath, sessionId);
|
|
118
|
+
if (holds(conversation))
|
|
119
|
+
return conversation;
|
|
120
|
+
}
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
/** The topic of the history that last had the conversation open, in any bot. */
|
|
124
|
+
function lastTopicOf(sessionId) {
|
|
125
|
+
return [...findHistoryOwners([sessionId], BOT_ID).values()].flat()
|
|
126
|
+
.sort((a, b) => b.entry.lastActivity.localeCompare(a.entry.lastActivity))[0]?.entry.topic;
|
|
127
|
+
}
|
|
128
|
+
/** The transcript up to the end of `prompt`'s exchange: what a branch from just after its reply starts with. */
|
|
129
|
+
function cutAfter(conversation, prompt) {
|
|
130
|
+
return conversation.raw.split('\n').slice(0, prompt.endLine).join('\n') + '\n';
|
|
131
|
+
}
|
|
132
|
+
// โโ Views โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
133
|
+
const timeOf = (prompt) => (prompt.timestamp ? formatTimeAgo(new Date(prompt.timestamp)) : 'earlier');
|
|
134
|
+
/** A prompt's line in the list. Its marks sit by the time, where a long prompt doesn't bury them. */
|
|
135
|
+
function listLine(prompt, letter) {
|
|
136
|
+
const marks = `${prompt.branched ? ' ๐ฟ' : ''}${prompt.pending ? ' โณ' : ''}`;
|
|
137
|
+
return new EntityText()
|
|
138
|
+
.bold(letter).add(' ยท ').italic(timeOf(prompt))
|
|
139
|
+
.add(`${marks} โ ${cutLabel(prompt.label, PROMPTS_MAX_CHARS)}`)
|
|
140
|
+
.build();
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The prompts the list shows: the last `n`, less the oldest of them when they
|
|
144
|
+
* won't all fit in one message.
|
|
145
|
+
*
|
|
146
|
+
* The budget is spent newest-first: 25 pasted prompts can exceed one Telegram
|
|
147
|
+
* message, and when something has to go it should be the oldest, not the one
|
|
148
|
+
* you just sent. Every letter is one character, so measuring each line as `A`
|
|
149
|
+
* measures it as whichever letter it ends up with.
|
|
150
|
+
*/
|
|
151
|
+
function listed(conversation, n) {
|
|
152
|
+
const recent = conversation.prompts.slice(-n);
|
|
153
|
+
let from = recent.length;
|
|
154
|
+
let used = 0;
|
|
155
|
+
while (from > 0) {
|
|
156
|
+
const length = listLine(recent[from - 1], 'A').text.length + 1;
|
|
157
|
+
if (from < recent.length && used + length > PROMPTS_BUDGET_CHARS)
|
|
158
|
+
break;
|
|
159
|
+
used += length;
|
|
160
|
+
from--;
|
|
161
|
+
}
|
|
162
|
+
return recent.slice(from);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* The last `n` prompts of a conversation in one message, oldest first so it
|
|
166
|
+
* reads in the same order as the chat above it: a letter per prompt and a
|
|
167
|
+
* button per letter, the way /tree draws its points.
|
|
168
|
+
*/
|
|
169
|
+
export function renderPrompts(conversation, n) {
|
|
170
|
+
const shown = listed(conversation, n);
|
|
171
|
+
const project = path.basename(conversation.projectPath);
|
|
172
|
+
const heading = new EntityText().add('๐ฌ ').bold(project);
|
|
173
|
+
if (shown.length === 0)
|
|
174
|
+
return { text: heading.add(' โ no prompts yet.').build(), keyboard: [] };
|
|
175
|
+
const noun = shown.length === 1 ? 'prompt' : 'prompts';
|
|
176
|
+
const count = shown.length === conversation.prompts.length ? `${shown.length} ${noun}` : `last ${shown.length} ${noun}`;
|
|
177
|
+
const dropped = Math.min(n, conversation.prompts.length) - shown.length;
|
|
178
|
+
const legend = [
|
|
179
|
+
...(shown.some((p) => p.branched) ? ['๐ฟ a branch splits off here'] : []),
|
|
180
|
+
...(shown.some((p) => p.pending) ? ['โณ no reply'] : []),
|
|
181
|
+
];
|
|
182
|
+
const text = joinMessages([
|
|
183
|
+
heading.add(` โ ${count}${dropped > 0 ? ` (${dropped} older trimmed to fit)` : ''}`).build(),
|
|
184
|
+
plain(''),
|
|
185
|
+
...shown.map((p, i) => listLine(p, optionLetter(i))),
|
|
186
|
+
plain(''),
|
|
187
|
+
...(legend.length > 0 ? [new EntityText().italic(legend.join(' ยท ')).build()] : []),
|
|
188
|
+
plain('Tap a letter to open that prompt.'),
|
|
189
|
+
], '\n');
|
|
190
|
+
const keyboard = [
|
|
191
|
+
...buildLetterKeyboard(shown.map((p) => `prompts:o:${session8Of(conversation)}:${n}:${p.uuid}`)),
|
|
192
|
+
...(conversation.tree && shown.some((p) => p.branched) ? [[showTreeButton(conversation.tree)]] : []),
|
|
193
|
+
];
|
|
194
|
+
return { text, keyboard };
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* One prompt: the exchange it started, and what can be done from where that
|
|
198
|
+
* exchange ended. `running` says the chat's reply to it is being written now.
|
|
199
|
+
*/
|
|
200
|
+
export function renderPrompt(conversation, prompt, n, running = false) {
|
|
201
|
+
// Its letter in the list as it stands now; one the conversation has since
|
|
202
|
+
// moved past the last n of goes without.
|
|
203
|
+
const index = listed(conversation, n).indexOf(prompt);
|
|
204
|
+
const facts = [timeOf(prompt)];
|
|
205
|
+
if (prompt.pending)
|
|
206
|
+
facts.push(running ? 'being answered now' : 'no reply');
|
|
207
|
+
const reply = prompt.pending ? undefined : lastExchangeIn(cutAfter(conversation, prompt))?.assistant;
|
|
208
|
+
const title = new EntityText().add('๐ฌ ');
|
|
209
|
+
if (index >= 0)
|
|
210
|
+
title.bold(optionLetter(index)).add(' ยท ');
|
|
211
|
+
const text = joinMessages([
|
|
212
|
+
title.add(facts.join(' ยท ')).build(),
|
|
213
|
+
...(prompt.branched ? [plain('๐ฟ Another branch splits off here.')] : []),
|
|
214
|
+
plain(''),
|
|
215
|
+
youLine(prompt.text, PROMPTS_MAX_CHARS),
|
|
216
|
+
// Cut without pointing at /recap: that shows the last few exchanges, which
|
|
217
|
+
// this one may not be among.
|
|
218
|
+
...(reply ? replyQuote(reply, PROMPT_REPLY_LEN, null) : []),
|
|
219
|
+
], '\n');
|
|
220
|
+
const keyboard = [
|
|
221
|
+
// A prompt with no reply has no end to its exchange to branch from.
|
|
222
|
+
...(prompt.pending
|
|
223
|
+
? []
|
|
224
|
+
: [[{ text: '๐ฑ New branch from here', callback_data: `prompts:b:${session8Of(conversation)}:${prompt.uuid}` }]]),
|
|
225
|
+
...(prompt.branched && conversation.tree ? [[showTreeButton(conversation.tree)]] : []),
|
|
226
|
+
[{ text: 'โฌ
๏ธ Back to the prompts', callback_data: `prompts:l:${session8Of(conversation)}:${n}` }],
|
|
227
|
+
];
|
|
228
|
+
return { text, keyboard };
|
|
229
|
+
}
|
|
230
|
+
// โโ Commands and taps โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
231
|
+
/** `n` as the list takes it: the default when missing or not a count, never past the most. */
|
|
232
|
+
function countOf(arg) {
|
|
233
|
+
if (!arg)
|
|
234
|
+
return PROMPTS_DEFAULT_N;
|
|
235
|
+
const parsed = parseInt(arg, 10);
|
|
236
|
+
return Number.isNaN(parsed) || parsed < 1 ? undefined : Math.min(parsed, PROMPTS_MAX_N);
|
|
237
|
+
}
|
|
238
|
+
export async function handlePromptsCommand(ctx) {
|
|
239
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
240
|
+
if (!keyInfo)
|
|
241
|
+
return;
|
|
242
|
+
const n = countOf((ctx.message?.text || '').split(' ').slice(1).join(' ').trim());
|
|
243
|
+
if (n === undefined) {
|
|
244
|
+
await replyFormatted(ctx, new EntityText()
|
|
245
|
+
.add('โ ๏ธ Usage: ').code('/prompts [N]')
|
|
246
|
+
.add(` where N is the number of prompts (default ${PROMPTS_DEFAULT_N}, max ${PROMPTS_MAX_N}).`)
|
|
247
|
+
.build());
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
// Read, never loaded: after a restart it's where the chat left off, as /tree draws it.
|
|
251
|
+
const where = whereChatIs(keyInfo.sessionKey);
|
|
252
|
+
if (!where) {
|
|
253
|
+
await replyFormatted(ctx, NO_PROJECT_MESSAGE);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
if (!where.sessionId) {
|
|
257
|
+
await replyFormatted(ctx, 'โน๏ธ This session has no recorded messages yet.');
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const conversation = readConversation(where.projectPath, where.sessionId);
|
|
261
|
+
if (!conversation || conversation.prompts.length === 0) {
|
|
262
|
+
await replyFormatted(ctx, 'โน๏ธ No prompts found in this session yet.');
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
await sendView(ctx, renderPrompts(conversation, n), 'reply');
|
|
266
|
+
}
|
|
267
|
+
export async function handlePromptsCallback(ctx) {
|
|
268
|
+
const data = ctx.callbackQuery?.data;
|
|
269
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
270
|
+
if (!data || !keyInfo)
|
|
271
|
+
return;
|
|
272
|
+
const { sessionKey } = keyInfo;
|
|
273
|
+
const [, action, session8, ...rest] = data.split(':');
|
|
274
|
+
const n = countOf(action === 'b' ? undefined : rest[0]) ?? PROMPTS_DEFAULT_N;
|
|
275
|
+
const uuid = action === 'o' ? rest[1] : action === 'b' ? rest[0] : undefined;
|
|
276
|
+
try {
|
|
277
|
+
const where = whereChatIs(sessionKey);
|
|
278
|
+
const conversation = where && session8 ? findConversation(where.projectPath, session8, where.sessionId, uuid) : undefined;
|
|
279
|
+
if (!where || !conversation) {
|
|
280
|
+
await ctx.answerCallbackQuery({ text: "That conversation isn't in this chat's project any more โ send /prompts again." });
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (action === 'l') {
|
|
284
|
+
await ctx.answerCallbackQuery();
|
|
285
|
+
await sendView(ctx, renderPrompts(conversation, n), 'edit');
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
const prompt = conversation.prompts.find((p) => p.uuid === uuid);
|
|
289
|
+
if (!prompt) {
|
|
290
|
+
await ctx.answerCallbackQuery({ text: "That prompt isn't in the conversation any more โ send /prompts again." });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
// The chat is on this conversation: not a restart's leftover, which isn't loaded.
|
|
294
|
+
const onIt = where.live && where.sessionId === conversation.sessionId;
|
|
295
|
+
if (action === 'o') {
|
|
296
|
+
await ctx.answerCallbackQuery();
|
|
297
|
+
const running = onIt && isProcessing(sessionKey) && prompt === conversation.prompts.at(-1);
|
|
298
|
+
await sendView(ctx, renderPrompt(conversation, prompt, n, running), 'edit');
|
|
299
|
+
}
|
|
300
|
+
else if (action === 'b') {
|
|
301
|
+
await onBranch(ctx, sessionKey, conversation, prompt, onIt);
|
|
302
|
+
}
|
|
303
|
+
else {
|
|
304
|
+
await ctx.answerCallbackQuery({ text: 'Unknown prompts action.' });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
catch (err) {
|
|
308
|
+
console.error('[Prompts] callback failed:', sanitizeError(err));
|
|
309
|
+
try {
|
|
310
|
+
await ctx.answerCallbackQuery({ text: 'That failed โ see bot logs.' });
|
|
311
|
+
}
|
|
312
|
+
catch { /* already answered */ }
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Start a conversation in this chat from the transcript cut just after
|
|
317
|
+
* `prompt`'s reply: a branch, loaded straight away, the way /tree branches
|
|
318
|
+
* from a point and the ๐ด under a reply does.
|
|
319
|
+
*/
|
|
320
|
+
async function onBranch(ctx, sessionKey, conversation, prompt, onIt) {
|
|
321
|
+
if (prompt.pending) {
|
|
322
|
+
await ctx.answerCallbackQuery({ text: 'That prompt has no reply to branch after.' });
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (await refuseWhileBusy(ctx, sessionKey))
|
|
326
|
+
return;
|
|
327
|
+
const jsonl = cutAfter(conversation, prompt);
|
|
328
|
+
const fork = {
|
|
329
|
+
fromBotName: config.BOT_NAME,
|
|
330
|
+
fromBotId: BOT_ID,
|
|
331
|
+
fromChatId: ctx.chat?.id,
|
|
332
|
+
projectPath: conversation.projectPath,
|
|
333
|
+
jsonl,
|
|
334
|
+
topic: onIt ? getSessionTopic(sessionKey) : lastTopicOf(conversation.sessionId),
|
|
335
|
+
assistantPreview: lastAssistantTurnText(jsonl)?.substring(0, 200),
|
|
336
|
+
createdAt: new Date().toISOString(),
|
|
337
|
+
};
|
|
338
|
+
// Above the banner is the conversation branched from, unless the chat had
|
|
339
|
+
// moved on from it before the tap.
|
|
340
|
+
await loadFork(ctx, sessionKey, fork, onIt ? {} : { above: LEFT_ABOVE });
|
|
341
|
+
await ctx.answerCallbackQuery({ text: 'Branched.' });
|
|
342
|
+
}
|
|
343
|
+
//# sourceMappingURL=prompts.handler.js.map
|