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,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /resume, the way Claude Code's own /resume works: every conversation Claude
|
|
3
|
+
* Code has on disk for this project, newest first â from a terminal, another
|
|
4
|
+
* bot or this chat alike â with a toggle to every project, `/resume <words>`
|
|
5
|
+
* to search them, and `/resume <session id>` to open one directly.
|
|
6
|
+
*
|
|
7
|
+
* Picking one that another Claude process still has open starts a copy, as
|
|
8
|
+
* Claude Code does, so two writers never append to one transcript. Picking
|
|
9
|
+
* one another backend wrote (DeepSeek via CCR, or Claude while on CCR) goes on
|
|
10
|
+
* as a new session that starts with a recap: the old one's thinking blocks
|
|
11
|
+
* can't be replayed across backends.
|
|
12
|
+
*
|
|
13
|
+
* The `resume:<conversationId>` callback of the older, history-based picker is
|
|
14
|
+
* still what the âŠī¸ Back button sends; session.ts handles it.
|
|
15
|
+
*/
|
|
16
|
+
import * as crypto from 'crypto';
|
|
17
|
+
import * as fs from 'fs';
|
|
18
|
+
import * as path from 'path';
|
|
19
|
+
import { BOT_ID } from '../../../config.js';
|
|
20
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
21
|
+
import { sessionHistory, allHistoryOwners } from '../../../claude/session-history.js';
|
|
22
|
+
import { detectOwnerProvider, rewriteJsonlSessionId } from '../../../claude/session-jsonl.js';
|
|
23
|
+
import { findSession, isSessionId, isSessionOpenElsewhere, listSessions, matchesQuery, } from '../../../claude/session-scan.js';
|
|
24
|
+
import { setPendingCarryOver } from '../../../claude/carry-over.js';
|
|
25
|
+
import { isProcessing } from '../../../claude/request-queue.js';
|
|
26
|
+
import { clearConversation, getActiveProviderName } from '../../../providers/provider-router.js';
|
|
27
|
+
import { prewarmClaude } from '../../../claude/prewarm.js';
|
|
28
|
+
import { buildCarryOverPreamble } from '../../../providers/provider-switch.js';
|
|
29
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
30
|
+
import { buildLetteredKeyboard, letteredOptionLines } from '../../../telegram/lettered-options.js';
|
|
31
|
+
import { cutLabel, promptLabel } from '../../../telegram/prompt-label.js';
|
|
32
|
+
import { editCallbackMessage, replyFormatted } from '../../../telegram/send.js';
|
|
33
|
+
import { taskListDisplay } from '../../../telegram/task-list.js';
|
|
34
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
35
|
+
import { formatTimeAgo, parseCallback, projectStatusSuffix, replyMd, resumeCommandMessage } from './shared.js';
|
|
36
|
+
import { restoreTopic } from './topic.js';
|
|
37
|
+
import { sendView } from '../view.js';
|
|
38
|
+
import { resumeHistoryEntry, sendRecapHint } from './session.js';
|
|
39
|
+
/** Sessions per page: letters AâH, short enough to read on a phone. */
|
|
40
|
+
const PAGE_SIZE = 8;
|
|
41
|
+
const MAX_NAME_CHARS = 90;
|
|
42
|
+
export function buildResumePicker(p) {
|
|
43
|
+
const options = p.entries.map((e) => ({
|
|
44
|
+
label: e.name,
|
|
45
|
+
description: [formatTimeAgo(new Date(e.mtimeMs)), ...e.marks].join(' ¡ '),
|
|
46
|
+
}));
|
|
47
|
+
const text = new EntityText().add('đ ').bold(p.heading).add('\n\n').add(letteredOptionLines(options).join('\n'));
|
|
48
|
+
if (p.paging && (p.paging.page > 0 || p.paging.more))
|
|
49
|
+
text.add(`\n\nPage ${p.paging.page + 1}`);
|
|
50
|
+
if (p.footer)
|
|
51
|
+
text.add('\n\n').italic(p.footer);
|
|
52
|
+
const keyboard = buildLetteredKeyboard(p.entries.map((e) => ({ label: e.name, callbackData: `resume:s:${e.sessionId}` })));
|
|
53
|
+
const nav = [];
|
|
54
|
+
if (p.paging && p.paging.page > 0) {
|
|
55
|
+
nav.push({ text: 'â Newer', callback_data: `resume:l:${p.paging.scope}:${p.paging.page - 1}` });
|
|
56
|
+
}
|
|
57
|
+
if (p.paging?.more) {
|
|
58
|
+
nav.push({ text: 'Older âļ', callback_data: `resume:l:${p.paging.scope}:${p.paging.page + 1}` });
|
|
59
|
+
}
|
|
60
|
+
if (nav.length)
|
|
61
|
+
keyboard.push(nav);
|
|
62
|
+
if (p.toggle)
|
|
63
|
+
keyboard.push([{ text: p.toggle.label, callback_data: `resume:l:${p.toggle.scope}:0` }]);
|
|
64
|
+
return { text: text.build(), keyboard };
|
|
65
|
+
}
|
|
66
|
+
/** The newest TeleCoder topic any chat gave each conversation. */
|
|
67
|
+
function topicsById(owners) {
|
|
68
|
+
const topics = new Map();
|
|
69
|
+
for (const [id, list] of owners) {
|
|
70
|
+
const latest = list
|
|
71
|
+
.filter((o) => o.entry.topic)
|
|
72
|
+
.sort((a, b) => b.entry.lastActivity.localeCompare(a.entry.lastActivity))[0];
|
|
73
|
+
if (latest?.entry.topic)
|
|
74
|
+
topics.set(id, latest.entry.topic);
|
|
75
|
+
}
|
|
76
|
+
return topics;
|
|
77
|
+
}
|
|
78
|
+
/** What a session is called: a /rename, then a chat's topic, then Claude Code's title, then the first prompt. */
|
|
79
|
+
function titleOf(s, topics) {
|
|
80
|
+
const firstPrompt = s.firstPrompt ? promptLabel(s.firstPrompt) : undefined;
|
|
81
|
+
return s.customTitle ?? topics.get(s.sessionId) ?? s.aiTitle ?? firstPrompt ?? 'Untitled';
|
|
82
|
+
}
|
|
83
|
+
function isForeignModel(model) {
|
|
84
|
+
return model !== undefined && !model.startsWith('claude-');
|
|
85
|
+
}
|
|
86
|
+
function toEntry(s, topics, withProject, currentId) {
|
|
87
|
+
const title = titleOf(s, topics);
|
|
88
|
+
const name = withProject ? `${path.basename(s.projectPath)} ¡ ${title}` : title;
|
|
89
|
+
const marks = [];
|
|
90
|
+
if (s.sessionId === currentId)
|
|
91
|
+
marks.push('current');
|
|
92
|
+
else if (isSessionOpenElsewhere(s.sessionId))
|
|
93
|
+
marks.push('open elsewhere');
|
|
94
|
+
if (isForeignModel(s.lastModel))
|
|
95
|
+
marks.push('via CCR');
|
|
96
|
+
return { sessionId: s.sessionId, name: cutLabel(name, MAX_NAME_CHARS), mtimeMs: s.mtimeMs, marks };
|
|
97
|
+
}
|
|
98
|
+
/** The picker for `scope` at `page`, or undefined when there is nothing to list. */
|
|
99
|
+
function listView(sessionKey, scope, page) {
|
|
100
|
+
const session = sessionManager.getSession(sessionKey);
|
|
101
|
+
const projectPath = scope === 'p' ? session?.workingDirectory : undefined;
|
|
102
|
+
const owners = allHistoryOwners(BOT_ID);
|
|
103
|
+
const { sessions, more } = listSessions({
|
|
104
|
+
projectPath,
|
|
105
|
+
knownIds: new Set(owners.keys()),
|
|
106
|
+
offset: page * PAGE_SIZE,
|
|
107
|
+
limit: PAGE_SIZE,
|
|
108
|
+
});
|
|
109
|
+
if (sessions.length === 0 && page === 0)
|
|
110
|
+
return undefined;
|
|
111
|
+
const topics = topicsById(owners);
|
|
112
|
+
const projectName = projectPath ? path.basename(projectPath) : undefined;
|
|
113
|
+
return buildResumePicker({
|
|
114
|
+
heading: projectName ? `Sessions in ${projectName}` : 'Sessions in all projects',
|
|
115
|
+
entries: sessions.map((s) => toEntry(s, topics, !projectPath, session?.claudeSessionId)),
|
|
116
|
+
paging: { scope: projectPath ? 'p' : 'a', page, more },
|
|
117
|
+
toggle: projectPath
|
|
118
|
+
? { label: 'đ All projects', scope: 'a' }
|
|
119
|
+
: session ? { label: `đ Only ${path.basename(session.workingDirectory)}`, scope: 'p' } : undefined,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
// ââ /resume ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
|
|
123
|
+
export async function handleResume(ctx) {
|
|
124
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
125
|
+
if (!keyInfo)
|
|
126
|
+
return;
|
|
127
|
+
const { sessionKey } = keyInfo;
|
|
128
|
+
// After a restart the chat's project is only on disk; it decides the scope.
|
|
129
|
+
const { session } = sessionManager.getOrRestoreSession(sessionKey);
|
|
130
|
+
const arg = (ctx.message?.text ?? '').split(' ').slice(1).join(' ').trim();
|
|
131
|
+
if (!arg) {
|
|
132
|
+
const view = listView(sessionKey, session ? 'p' : 'a', 0) ?? (session ? listView(sessionKey, 'a', 0) : undefined);
|
|
133
|
+
if (!view) {
|
|
134
|
+
await replyMd(ctx, 'âšī¸ No conversations to resume yet.\n\nUse `/dir <name>` to start one.');
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
await sendView(ctx, view, 'reply');
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (isSessionId(arg)) {
|
|
141
|
+
const found = findSession(arg, session?.workingDirectory);
|
|
142
|
+
if (!found) {
|
|
143
|
+
await replyMd(ctx, `âšī¸ No session \`${arg}\` on this machine.`);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
await resumeScanned(ctx, sessionKey, found);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
await searchSessions(ctx, sessionKey, arg);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* `/resume <words>`: this project's sessions whose title or first prompt has
|
|
153
|
+
* every word, or every project's when none here do. One match opens straight
|
|
154
|
+
* away, as `claude --resume <name>` does.
|
|
155
|
+
*/
|
|
156
|
+
async function searchSessions(ctx, sessionKey, query) {
|
|
157
|
+
const session = sessionManager.getSession(sessionKey);
|
|
158
|
+
const owners = allHistoryOwners(BOT_ID);
|
|
159
|
+
const knownIds = new Set(owners.keys());
|
|
160
|
+
const topics = topicsById(owners);
|
|
161
|
+
const match = (s) => matchesQuery(s, query, topics.get(s.sessionId));
|
|
162
|
+
const search = (projectPath) => listSessions({ projectPath, knownIds, match, offset: 0, limit: PAGE_SIZE });
|
|
163
|
+
let projectPath = session?.workingDirectory;
|
|
164
|
+
let found = projectPath ? search(projectPath) : { sessions: [], more: false };
|
|
165
|
+
if (found.sessions.length === 0) {
|
|
166
|
+
projectPath = undefined;
|
|
167
|
+
found = search();
|
|
168
|
+
}
|
|
169
|
+
if (found.sessions.length === 0) {
|
|
170
|
+
await replyFormatted(ctx, new EntityText().add('âšī¸ No session matches â').add(query).add('â.').build());
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (found.sessions.length === 1) {
|
|
174
|
+
await resumeScanned(ctx, sessionKey, found.sessions[0]);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
await sendView(ctx, buildResumePicker({
|
|
178
|
+
heading: `Sessions matching â${query}â` + (projectPath ? ` in ${path.basename(projectPath)}` : ''),
|
|
179
|
+
entries: found.sessions.map((s) => toEntry(s, topics, !projectPath, session?.claudeSessionId)),
|
|
180
|
+
footer: found.more ? `Showing the newest ${PAGE_SIZE}. Add words to narrow it down.` : undefined,
|
|
181
|
+
}), 'reply');
|
|
182
|
+
}
|
|
183
|
+
export async function handleResumeCallback(ctx) {
|
|
184
|
+
const cb = parseCallback(ctx, 'resume:');
|
|
185
|
+
if (!cb)
|
|
186
|
+
return;
|
|
187
|
+
const { sessionKey, data } = cb;
|
|
188
|
+
const list = /^resume:l:([pa]):(\d+)$/.exec(data);
|
|
189
|
+
if (list) {
|
|
190
|
+
const view = listView(sessionKey, list[1], Number(list[2]));
|
|
191
|
+
if (!view) {
|
|
192
|
+
await ctx.answerCallbackQuery({ text: 'Nothing more to list.' });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
await sendView(ctx, view, 'edit');
|
|
196
|
+
await ctx.answerCallbackQuery();
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (data.startsWith('resume:s:')) {
|
|
200
|
+
const id = data.slice('resume:s:'.length);
|
|
201
|
+
const found = findSession(id, sessionManager.getSession(sessionKey)?.workingDirectory);
|
|
202
|
+
if (!found) {
|
|
203
|
+
await ctx.answerCallbackQuery({ text: "That session's transcript is gone from disk." });
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
await resumeScanned(ctx, sessionKey, found);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
await resumeHistoryEntry(ctx, sessionKey, data.slice('resume:'.length));
|
|
210
|
+
}
|
|
211
|
+
// ââ Opening one ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
|
|
212
|
+
const BACKEND_NAMES = { claude: 'Claude', ccr: 'CCR' };
|
|
213
|
+
/**
|
|
214
|
+
* A copy of a transcript under a fresh id, for a session another process is
|
|
215
|
+
* still writing to. A line it was halfway through writing is left out.
|
|
216
|
+
*/
|
|
217
|
+
function copyTranscript(s) {
|
|
218
|
+
try {
|
|
219
|
+
let raw = fs.readFileSync(s.file, 'utf-8');
|
|
220
|
+
if (!raw.endsWith('\n'))
|
|
221
|
+
raw = raw.slice(0, raw.lastIndexOf('\n') + 1);
|
|
222
|
+
const newId = crypto.randomUUID();
|
|
223
|
+
// Beside the original: Claude Code names the directory, and encodes more
|
|
224
|
+
// of a path's characters than sessionJsonlPath does.
|
|
225
|
+
const target = path.join(path.dirname(s.file), `${newId}.jsonl`);
|
|
226
|
+
fs.writeFileSync(target, rewriteJsonlSessionId(raw, newId), { mode: 0o600 });
|
|
227
|
+
return newId;
|
|
228
|
+
}
|
|
229
|
+
catch (err) {
|
|
230
|
+
console.error('[Resume] Could not copy transcript:', err);
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** Answer a button tap, or reply to the command. */
|
|
235
|
+
async function tell(ctx, text) {
|
|
236
|
+
if (ctx.callbackQuery)
|
|
237
|
+
await ctx.answerCallbackQuery({ text, show_alert: text.length > 60 });
|
|
238
|
+
else
|
|
239
|
+
await ctx.reply(text);
|
|
240
|
+
}
|
|
241
|
+
async function resumeScanned(ctx, sessionKey, s) {
|
|
242
|
+
const current = sessionManager.getSession(sessionKey);
|
|
243
|
+
if (current?.claudeSessionId === s.sessionId) {
|
|
244
|
+
await tell(ctx, "You're already in this conversation.");
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
if (isProcessing(sessionKey)) {
|
|
248
|
+
await tell(ctx, 'A reply is still running here â wait for it to finish, or /cancel it, then try again.');
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (!fs.existsSync(s.projectPath)) {
|
|
252
|
+
await tell(ctx, `That conversation ran in ${s.projectPath}, which no longer exists.`);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
const notes = [];
|
|
256
|
+
let sessionId = s.sessionId;
|
|
257
|
+
if (isSessionOpenElsewhere(s.sessionId)) {
|
|
258
|
+
const copyId = copyTranscript(s);
|
|
259
|
+
if (!copyId) {
|
|
260
|
+
await tell(ctx, 'That session is open in another Claude Code process, and copying it failed.');
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
// Claude Code's own wording for the same case.
|
|
264
|
+
notes.push(`Session ${s.sessionId} is open in another Claude Code process, so this started a copy as ${copyId}. The original conversation is unchanged.`);
|
|
265
|
+
sessionId = copyId;
|
|
266
|
+
}
|
|
267
|
+
// This chat's own entry brings back its conversation and topic; any other
|
|
268
|
+
// chat's or bot's topic is the next best name for it.
|
|
269
|
+
const own = sessionHistory.findByClaudeSessionId(sessionId).find((o) => o.sessionKey === sessionKey)?.entry;
|
|
270
|
+
let topic;
|
|
271
|
+
if (own) {
|
|
272
|
+
sessionManager.resumeSession(sessionKey, own.conversationId);
|
|
273
|
+
topic = own.topic;
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
if (current && current.workingDirectory === s.projectPath)
|
|
277
|
+
sessionManager.startNewConversation(sessionKey);
|
|
278
|
+
else
|
|
279
|
+
sessionManager.setWorkingDirectory(sessionKey, s.projectPath);
|
|
280
|
+
topic = topicsById(allHistoryOwners(BOT_ID)).get(s.sessionId);
|
|
281
|
+
}
|
|
282
|
+
topic ??= s.customTitle ?? s.aiTitle;
|
|
283
|
+
const owner = own?.ownerProvider ?? detectOwnerProvider(s.file);
|
|
284
|
+
sessionManager.setClaudeSessionId(sessionKey, sessionId, owner);
|
|
285
|
+
// Drops the live process and in-memory state of the conversation this chat
|
|
286
|
+
// was in, so the next turn resumes the one just picked. After
|
|
287
|
+
// setClaudeSessionId, which it leaves alone.
|
|
288
|
+
clearConversation(sessionKey);
|
|
289
|
+
const provider = getActiveProviderName(sessionKey);
|
|
290
|
+
let carriedOver = false;
|
|
291
|
+
if (owner && owner !== provider) {
|
|
292
|
+
const preamble = buildCarryOverPreamble(sessionKey);
|
|
293
|
+
if (preamble)
|
|
294
|
+
setPendingCarryOver(sessionKey, preamble);
|
|
295
|
+
sessionManager.startNewConversation(sessionKey);
|
|
296
|
+
carriedOver = true;
|
|
297
|
+
notes.push(`This conversation ran on ${BACKEND_NAMES[owner] ?? owner} and this chat is on ${BACKEND_NAMES[provider] ?? provider}, ` +
|
|
298
|
+
`which can't replay its thinking. It goes on as a new session that starts with a recap of the last exchanges. ` +
|
|
299
|
+
`To continue it as it is, switch backends with /ccr and resume it again.`);
|
|
300
|
+
}
|
|
301
|
+
restoreTopic(sessionKey, topic);
|
|
302
|
+
const message = new EntityText()
|
|
303
|
+
.add('â
Resumed ').bold(topic ?? sessionId)
|
|
304
|
+
.add('\n\nWorking directory: ').code(s.projectPath)
|
|
305
|
+
.append(projectStatusSuffix(sessionKey));
|
|
306
|
+
for (const note of notes)
|
|
307
|
+
message.add('\n\n').italic(note);
|
|
308
|
+
const text = message.build();
|
|
309
|
+
if (ctx.callbackQuery) {
|
|
310
|
+
await ctx.answerCallbackQuery({ text: 'Session resumed!' });
|
|
311
|
+
await editCallbackMessage(ctx, text);
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
await replyFormatted(ctx, text);
|
|
315
|
+
}
|
|
316
|
+
// Last of the state changes above is long done; the claude this starts is
|
|
317
|
+
// the one the first message would have.
|
|
318
|
+
void prewarmClaude(ctx, sessionKey);
|
|
319
|
+
if (carriedOver)
|
|
320
|
+
return;
|
|
321
|
+
await replyFormatted(ctx, resumeCommandMessage(sessionId));
|
|
322
|
+
await taskListDisplay.showRestored(ctx.api, sessionKey, sessionId);
|
|
323
|
+
await sendRecapHint(ctx, sessionKey);
|
|
324
|
+
}
|
|
325
|
+
//# sourceMappingURL=resume.js.map
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session lifecycle: /clear, /history, /resend and /terminal, and the
|
|
3
|
+
* âļī¸ Continue button under a restart notice. /prompts, which branches as well
|
|
4
|
+
* as lists, lives beside /tree in prompts.handler.ts.
|
|
5
|
+
*
|
|
6
|
+
* All of these move a chat between conversations â starting a fresh one,
|
|
7
|
+
* picking an older one back up, or summarising what a previous one did â so
|
|
8
|
+
* they share the session history, the JSONL reader and the topic restore.
|
|
9
|
+
*/
|
|
10
|
+
import * as path from 'path';
|
|
11
|
+
import { config } from '../../../config.js';
|
|
12
|
+
import { sessionManager } from '../../../claude/session-manager.js';
|
|
13
|
+
import { sessionHistory } from '../../../claude/session-history.js';
|
|
14
|
+
import { clearConversation, getCachedUsage } from '../../../providers/provider-router.js';
|
|
15
|
+
import { prewarmClaude } from '../../../claude/prewarm.js';
|
|
16
|
+
import { messageSender } from '../../../telegram/message-sender.js';
|
|
17
|
+
import { EntityText } from '../../../telegram/entities.js';
|
|
18
|
+
import { replyFormatted, editCallbackMessage, replyMarkdown } from '../../../telegram/send.js';
|
|
19
|
+
import { taskListDisplay } from '../../../telegram/task-list.js';
|
|
20
|
+
import { summarizeUserPrompt, unwrapPaste, cutLabel } from '../../../telegram/prompt-label.js';
|
|
21
|
+
import { readRecentExchanges, readLastAssistantTurnText, } from '../../../claude/session-jsonl.js';
|
|
22
|
+
import { getSessionKeyFromCtx } from '../../../utils/session-key.js';
|
|
23
|
+
import { replyMd, projectStatusSuffix, resumeCommandMessage, withBackToPrevious, } from './shared.js';
|
|
24
|
+
import { clearTopic, restoreTopic, setSessionTopic, } from './topic.js';
|
|
25
|
+
import { sendStatusLine } from './settings.js';
|
|
26
|
+
/** What `-y` and its spellings were for: skipping a confirmation /clear no longer asks. */
|
|
27
|
+
const OLD_SKIP_FLAGS = new Set(['-y', '--yes', 'yes', 'force']);
|
|
28
|
+
/**
|
|
29
|
+
* /clear [name] (and /reset, /new, Claude Code's names for it): a new
|
|
30
|
+
* conversation in the same project, at once, as in Claude Code. Nothing is
|
|
31
|
+
* lost: the previous conversation stays on disk, behind the âŠī¸ Back button and
|
|
32
|
+
* in /resume. A name starts the new one under that topic, which names the
|
|
33
|
+
* thread as /topic does; Claude Code's `/clear <name>` titles the new session
|
|
34
|
+
* the same way. `-y` from when /clear asked first is accepted and ignored.
|
|
35
|
+
*/
|
|
36
|
+
export async function handleClear(ctx) {
|
|
37
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
38
|
+
if (!keyInfo)
|
|
39
|
+
return;
|
|
40
|
+
const { sessionKey } = keyInfo;
|
|
41
|
+
// After a bot restart the in-memory session map is empty; without this
|
|
42
|
+
// pull-from-disk, startNewConversation silently no-ops and the project is
|
|
43
|
+
// dropped, forcing the user to /dir again. The default auto-restore
|
|
44
|
+
// age cap doesn't apply here â the user is explicitly invoking /clear, so
|
|
45
|
+
// any restorable project on disk should come back.
|
|
46
|
+
sessionManager.getOrRestoreSession(sessionKey, Number.MAX_SAFE_INTEGER);
|
|
47
|
+
const arg = (ctx.message?.text ?? '').replace(/^\/\S*\s*/, '').trim();
|
|
48
|
+
const name = OLD_SKIP_FLAGS.has(arg.toLowerCase()) ? '' : arg;
|
|
49
|
+
// Preserve the working directory (project) â only the conversation is new,
|
|
50
|
+
// matching Claude Code's /clear.
|
|
51
|
+
clearConversation(sessionKey);
|
|
52
|
+
sessionManager.startNewConversation(sessionKey);
|
|
53
|
+
if (name)
|
|
54
|
+
setSessionTopic(sessionKey, name);
|
|
55
|
+
else
|
|
56
|
+
clearTopic(sessionKey);
|
|
57
|
+
const session = sessionManager.getSession(sessionKey);
|
|
58
|
+
const projectName = session ? path.basename(session.workingDirectory) : null;
|
|
59
|
+
const back = withBackToPrevious(clearedMessage(projectName, name), sessionKey, session?.conversationId);
|
|
60
|
+
await replyFormatted(ctx, back.text, back.options);
|
|
61
|
+
void prewarmClaude(ctx, sessionKey);
|
|
62
|
+
}
|
|
63
|
+
/** The note once a conversation is cleared: the project kept, the topic given, where the old one went. */
|
|
64
|
+
function clearedMessage(projectName, name = '') {
|
|
65
|
+
const msg = new EntityText().add('đ New conversation');
|
|
66
|
+
if (name)
|
|
67
|
+
msg.add(': ').bold(name);
|
|
68
|
+
msg.add('.');
|
|
69
|
+
if (projectName)
|
|
70
|
+
msg.add(' Project ').bold(projectName).add(' is still selected.');
|
|
71
|
+
msg.add(' The previous conversation stays in /resume.');
|
|
72
|
+
return msg.build();
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Go back to a conversation from this chat's history â what the âŠī¸ Back
|
|
76
|
+
* button does (`resume:<conversationId>`), and what the history-based /resume
|
|
77
|
+
* picker did before /resume read Claude Code's transcripts (resume.ts).
|
|
78
|
+
*/
|
|
79
|
+
export async function resumeHistoryEntry(ctx, sessionKey, conversationId) {
|
|
80
|
+
const session = sessionManager.resumeSession(sessionKey, conversationId);
|
|
81
|
+
if (!session) {
|
|
82
|
+
await ctx.answerCallbackQuery({ text: 'Session not found' });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
clearConversation(sessionKey);
|
|
86
|
+
const entry = sessionHistory.getSessionByConversationId(sessionKey, conversationId);
|
|
87
|
+
restoreTopic(sessionKey, entry?.topic);
|
|
88
|
+
await ctx.answerCallbackQuery({ text: 'Session resumed!' });
|
|
89
|
+
await editCallbackMessage(ctx, sessionRestoredMessage('â
Resumed session for ', session.workingDirectory, sessionKey));
|
|
90
|
+
// Send session ID as separate message for easy copying
|
|
91
|
+
if (session.claudeSessionId) {
|
|
92
|
+
await replyFormatted(ctx, resumeCommandMessage(session.claudeSessionId));
|
|
93
|
+
}
|
|
94
|
+
await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
|
|
95
|
+
await sendRecapHint(ctx, sessionKey);
|
|
96
|
+
void prewarmClaude(ctx, sessionKey);
|
|
97
|
+
}
|
|
98
|
+
/** "<lead><project>", the working directory and the project status block. */
|
|
99
|
+
function sessionRestoredMessage(lead, workingDirectory, sessionKey) {
|
|
100
|
+
return new EntityText()
|
|
101
|
+
.add(lead).bold(path.basename(workingDirectory))
|
|
102
|
+
.add('\n\nWorking directory: ').code(workingDirectory)
|
|
103
|
+
.append(projectStatusSuffix(sessionKey))
|
|
104
|
+
.build();
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Pick the chat's most recent session back up: what the âļī¸ Continue button
|
|
108
|
+
* under a restart notice does. Startup continues a chat by itself these days
|
|
109
|
+
* (startup/auto-continue.ts); this is the manual path for one it left alone.
|
|
110
|
+
*/
|
|
111
|
+
export async function continueLastSession(ctx) {
|
|
112
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
113
|
+
if (!keyInfo)
|
|
114
|
+
return;
|
|
115
|
+
const { sessionKey } = keyInfo;
|
|
116
|
+
const session = sessionManager.resumeLastSession(sessionKey);
|
|
117
|
+
if (!session) {
|
|
118
|
+
await replyMd(ctx, 'âšī¸ No previous session to continue.\n\nUse `/resume` to pick one, or `/dir <name>` to start a new session.');
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
clearConversation(sessionKey);
|
|
122
|
+
const entry = sessionHistory.getLastSession(sessionKey);
|
|
123
|
+
restoreTopic(sessionKey, entry?.topic);
|
|
124
|
+
await replyFormatted(ctx, sessionRestoredMessage('â
Continuing ', session.workingDirectory, sessionKey));
|
|
125
|
+
// Send session ID as separate message for easy copying
|
|
126
|
+
if (session.claudeSessionId) {
|
|
127
|
+
await replyFormatted(ctx, resumeCommandMessage(session.claudeSessionId));
|
|
128
|
+
}
|
|
129
|
+
await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
|
|
130
|
+
await sendRecapHint(ctx, sessionKey);
|
|
131
|
+
void prewarmClaude(ctx, sessionKey);
|
|
132
|
+
}
|
|
133
|
+
// Cap for the user-prompt blockquote â long pasted prompts shouldn't dominate
|
|
134
|
+
// the recap. Assistant replies are NOT truncated: they go through the same
|
|
135
|
+
// markdown-to-entities converter and splitter as the original delivery, so
|
|
136
|
+
// their markdown renders (bold, code, lists) instead of showing raw marks.
|
|
137
|
+
const RECAP_USER_MAX_CHARS = 500;
|
|
138
|
+
const RECAP_DEFAULT_N = 3;
|
|
139
|
+
const RECAP_MAX_N = 10;
|
|
140
|
+
function truncateUserPrompt(text, max = RECAP_USER_MAX_CHARS) {
|
|
141
|
+
return cutLabel(summarizeUserPrompt(unwrapPaste(text)).replace(/\s+/g, ' ').trim(), max);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Post the recap as a sequence of messages: a header, then for each exchange
|
|
145
|
+
* the user prompt as a blockquote followed by the assistant reply rendered
|
|
146
|
+
* with its original markdown intact. This mirrors how the assistant text
|
|
147
|
+
* looked on first delivery, instead of cramming everything into one
|
|
148
|
+
* blockquote where `**bold**` / backticks / lists show as raw characters.
|
|
149
|
+
*/
|
|
150
|
+
async function sendRecap(ctx, exchanges) {
|
|
151
|
+
await replyFormatted(ctx, new EntityText()
|
|
152
|
+
.add('đ ').bold('Recap')
|
|
153
|
+
.add(` â last ${exchanges.length} exchange${exchanges.length === 1 ? '' : 's'}`)
|
|
154
|
+
.build());
|
|
155
|
+
for (const ex of exchanges) {
|
|
156
|
+
const userText = truncateUserPrompt(ex.user);
|
|
157
|
+
await replyFormatted(ctx, new EntityText().wrap('blockquote', (b) => b.bold('You:').add(` ${userText}`)).build());
|
|
158
|
+
// replyMarkdown already falls back to plain text when Telegram refuses the
|
|
159
|
+
// formatting; this only keeps one undeliverable reply from ending the
|
|
160
|
+
// whole recap.
|
|
161
|
+
try {
|
|
162
|
+
await replyMarkdown(ctx, ex.assistant);
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
console.error('[Recap] Failed to send an assistant reply:', error);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** Post a one-line tip pointing the user at /history. Used after explicit restore. */
|
|
170
|
+
export async function sendRecapHint(ctx, sessionKey) {
|
|
171
|
+
const session = sessionManager.getSession(sessionKey);
|
|
172
|
+
if (!session?.claudeSessionId)
|
|
173
|
+
return;
|
|
174
|
+
const exchanges = readRecentExchanges(session.workingDirectory, session.claudeSessionId, 1);
|
|
175
|
+
if (exchanges.length === 0)
|
|
176
|
+
return;
|
|
177
|
+
await replyMd(ctx, 'đĄ Tip: use `/history` to see your last messages from this session.');
|
|
178
|
+
}
|
|
179
|
+
export async function handleHistory(ctx) {
|
|
180
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
181
|
+
if (!keyInfo)
|
|
182
|
+
return;
|
|
183
|
+
const { chatId, sessionKey } = keyInfo;
|
|
184
|
+
const text = ctx.message?.text || '';
|
|
185
|
+
const arg = text.split(' ').slice(1).join(' ').trim();
|
|
186
|
+
let n = RECAP_DEFAULT_N;
|
|
187
|
+
if (arg) {
|
|
188
|
+
const parsed = parseInt(arg, 10);
|
|
189
|
+
if (Number.isNaN(parsed) || parsed < 1) {
|
|
190
|
+
await replyMd(ctx, 'â ī¸ Usage: `/history [N]` where N is the number of exchanges (default 3, max 10).');
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
n = Math.min(parsed, RECAP_MAX_N);
|
|
194
|
+
}
|
|
195
|
+
const session = sessionManager.getSession(sessionKey);
|
|
196
|
+
if (!session) {
|
|
197
|
+
await replyMd(ctx, 'â ī¸ No active session. Use `/resume` first.');
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (!session.claudeSessionId) {
|
|
201
|
+
await replyMd(ctx, 'âšī¸ This session has no recorded messages yet.');
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const exchanges = readRecentExchanges(session.workingDirectory, session.claudeSessionId, n);
|
|
205
|
+
if (exchanges.length === 0) {
|
|
206
|
+
await replyMd(ctx, 'âšī¸ No recoverable exchanges found in this session.');
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
await sendRecap(ctx, exchanges);
|
|
210
|
+
// End the way a turn ends. A long reply leaves the chat on its tail, with the
|
|
211
|
+
// prompt it answers scrolled away, and after a jump to a branch or an earlier
|
|
212
|
+
// point the context is no longer the figure last shown.
|
|
213
|
+
const usage = getCachedUsage(sessionKey);
|
|
214
|
+
await sendStatusLine(ctx, chatId, sessionKey, usage, exchanges[exchanges.length - 1].user);
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Manual safety net for the PTY â Telegram translation. Reads the canonical
|
|
218
|
+
* latest assistant turn from Claude Code's session JSONL and posts whatever
|
|
219
|
+
* the user hasn't seen yet. Mirrors the proactive catch-up that runs after
|
|
220
|
+
* each turn (relayCatchUpIfMissed in message.handler.ts); /resend exists for
|
|
221
|
+
* cases where the user suspects a miss outside that automatic window â e.g.
|
|
222
|
+
* a quietly-failed catch-up, or after a bot restart that wiped the relayed
|
|
223
|
+
* tracker.
|
|
224
|
+
*/
|
|
225
|
+
export async function handleResend(ctx) {
|
|
226
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
227
|
+
if (!keyInfo)
|
|
228
|
+
return;
|
|
229
|
+
const { sessionKey } = keyInfo;
|
|
230
|
+
const session = sessionManager.getSession(sessionKey);
|
|
231
|
+
if (!session) {
|
|
232
|
+
await replyMd(ctx, 'â ī¸ No active session. Use `/resume` first.');
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (!session.claudeSessionId) {
|
|
236
|
+
await replyMd(ctx, 'âšī¸ This session has no recorded messages yet.');
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
const jsonlText = readLastAssistantTurnText(session.workingDirectory, session.claudeSessionId);
|
|
240
|
+
if (!jsonlText) {
|
|
241
|
+
await replyMd(ctx, 'âšī¸ No assistant reply found for the current turn.');
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const relayed = sessionManager.getLastRelayedAssistantText(sessionKey);
|
|
245
|
+
// Same 20-char slack as the proactive check â trim/whitespace deltas don't
|
|
246
|
+
// count as a real miss.
|
|
247
|
+
if (jsonlText.length <= relayed.length + 20) {
|
|
248
|
+
await replyMd(ctx, "â
You're caught up â nothing new in the session log.");
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const missing = jsonlText.startsWith(relayed) && relayed.length > 0
|
|
252
|
+
? jsonlText.slice(relayed.length).trim()
|
|
253
|
+
: jsonlText;
|
|
254
|
+
if (!missing) {
|
|
255
|
+
await replyMd(ctx, "â
You're caught up â nothing new in the session log.");
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
await replyMd(ctx, 'đ¨ **Sync** â from session log');
|
|
259
|
+
await messageSender.sendMessage(ctx, missing);
|
|
260
|
+
sessionManager.setLastRelayedAssistantText(sessionKey, jsonlText);
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* /terminal: the command line that carries this session on in a terminal, as
|
|
264
|
+
* a fork. It was /teleport until Claude Code had a /teleport of its own (send
|
|
265
|
+
* a session to the cloud, or resume one from claude.ai), which the bot's
|
|
266
|
+
* command of that name kept anyone from reaching.
|
|
267
|
+
*/
|
|
268
|
+
export async function handleTerminal(ctx) {
|
|
269
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
270
|
+
if (!keyInfo)
|
|
271
|
+
return;
|
|
272
|
+
const { sessionKey } = keyInfo;
|
|
273
|
+
const session = sessionManager.getSession(sessionKey);
|
|
274
|
+
if (!session) {
|
|
275
|
+
await replyMd(ctx, 'âšī¸ No active session to continue in a terminal.\n\nStart a conversation first with `/dir <name>`.');
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (!session.claudeSessionId) {
|
|
279
|
+
await replyMd(ctx, 'âšī¸ No Claude session available yet.\n\nSend a message first to start a session, then use `/terminal`.');
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const projectName = path.basename(session.workingDirectory);
|
|
283
|
+
const claudeBin = config.CLAUDE_EXECUTABLE_PATH ?? 'claude';
|
|
284
|
+
// --fork-session: the chat's own claude still has this session open, and a
|
|
285
|
+
// plain --resume would have two processes appending to one log. The fork
|
|
286
|
+
// starts with the whole conversation under an id of its own.
|
|
287
|
+
const command = `cd "${session.workingDirectory}" && ${claudeBin} --resume ${session.claudeSessionId} --fork-session`;
|
|
288
|
+
const message = new EntityText()
|
|
289
|
+
.add('đģ ').bold('Continue in a terminal')
|
|
290
|
+
.add('\n\n').bold('Project:').add(' ').code(projectName)
|
|
291
|
+
.newline().bold('Session:').add(' ').code(`${session.claudeSessionId.substring(0, 8)}...`)
|
|
292
|
+
.add('\n\nCopy and run in your terminal:\n\n')
|
|
293
|
+
.pre(command)
|
|
294
|
+
.add('\n\n')
|
|
295
|
+
.italic('The terminal gets a copy of the conversation as a new session, so this chat and the terminal can each carry on.')
|
|
296
|
+
.build();
|
|
297
|
+
await replyFormatted(ctx, message);
|
|
298
|
+
}
|
|
299
|
+
//# sourceMappingURL=session.js.map
|