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,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The "is there a project to work in?" preamble every handler needs.
|
|
3
|
+
*
|
|
4
|
+
* This existed in eleven hand-written copies — three in the photo handler, one
|
|
5
|
+
* in voice, six across the command handlers and one in the message domain —
|
|
6
|
+
* with the message text drifting between two wordings along the way. Handlers
|
|
7
|
+
* import it from here so a change to the wording, or to what counts as a
|
|
8
|
+
* usable session, lands everywhere at once.
|
|
9
|
+
*/
|
|
10
|
+
import * as path from 'path';
|
|
11
|
+
import { sessionManager } from '../../claude/session-manager.js';
|
|
12
|
+
import { sessionHistory } from '../../claude/session-history.js';
|
|
13
|
+
import { EntityText } from '../../telegram/entities.js';
|
|
14
|
+
import { replyFormatted } from '../../telegram/send.js';
|
|
15
|
+
import { taskListDisplay } from '../../telegram/task-list.js';
|
|
16
|
+
import { homeProject } from '../../utils/home-project.js';
|
|
17
|
+
/** Shown when a handler needs a working directory and no session supplies one. */
|
|
18
|
+
export const NO_PROJECT_MESSAGE = new EntityText()
|
|
19
|
+
.add('⚠️ No project set.\n\nIf the bot restarted, use ').code('/resume')
|
|
20
|
+
.add(' to restore your last session.\nOr use ').code('/dir').add(' to open a project first.')
|
|
21
|
+
.build();
|
|
22
|
+
/**
|
|
23
|
+
* Where the chat is: the conversation it's on — or, when a restart dropped
|
|
24
|
+
* that and nothing has brought it back, the one it left off in (`live` false).
|
|
25
|
+
*
|
|
26
|
+
* Only ever read. Drawing /tree or listing /prompts mustn't load a
|
|
27
|
+
* conversation behind the chat's back: the next message would land in
|
|
28
|
+
* whatever it loaded.
|
|
29
|
+
*/
|
|
30
|
+
export function whereChatIs(sessionKey) {
|
|
31
|
+
const session = sessionManager.getSession(sessionKey);
|
|
32
|
+
if (session)
|
|
33
|
+
return { projectPath: session.workingDirectory, sessionId: session.claudeSessionId, live: true };
|
|
34
|
+
const last = sessionHistory.getLastSession(sessionKey);
|
|
35
|
+
return last ? { projectPath: last.projectPath, sessionId: last.claudeSessionId, live: false } : undefined;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Require a session that is already live in memory.
|
|
39
|
+
*
|
|
40
|
+
* For commands that inspect or act on the current session but shouldn't
|
|
41
|
+
* silently revive a dead one — if the bot restarted, the user is told to
|
|
42
|
+
* /resume rather than having a session rehydrated underneath them.
|
|
43
|
+
* Returns null after replying, so callers just early-return.
|
|
44
|
+
*/
|
|
45
|
+
export async function requireActiveSession(ctx, sessionKey) {
|
|
46
|
+
const session = sessionManager.getSession(sessionKey);
|
|
47
|
+
if (!session) {
|
|
48
|
+
await replyFormatted(ctx, NO_PROJECT_MESSAGE);
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
return session;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Require a session, restoring from disk if the bot restarted since the last
|
|
55
|
+
* message.
|
|
56
|
+
*
|
|
57
|
+
* For the paths where the user is mid-conversation — a typed message, a photo,
|
|
58
|
+
* a voice note — and a restart shouldn't be their problem. Announces the
|
|
59
|
+
* restore so the recovered context isn't invisible. With nothing to restore, a
|
|
60
|
+
* bot with a home project starts a fresh conversation there. Returns null
|
|
61
|
+
* after replying, so callers just early-return.
|
|
62
|
+
*/
|
|
63
|
+
export async function requireSession(ctx, sessionKey) {
|
|
64
|
+
const { session: restoredSession, restored } = sessionManager.getOrRestoreSession(sessionKey);
|
|
65
|
+
// A bot made for one project starts there instead of asking for /dir.
|
|
66
|
+
const home = restoredSession ? undefined : homeProject();
|
|
67
|
+
const session = restoredSession ?? (home ? sessionManager.createSession(sessionKey, home) : undefined);
|
|
68
|
+
if (!session) {
|
|
69
|
+
await replyFormatted(ctx, NO_PROJECT_MESSAGE);
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
if (restored) {
|
|
73
|
+
await replyFormatted(ctx, new EntityText().add('↩️ Resumed previous session: ').bold(path.basename(session.workingDirectory)).build());
|
|
74
|
+
await taskListDisplay.showRestored(ctx.api, sessionKey, session.claudeSessionId);
|
|
75
|
+
}
|
|
76
|
+
return session;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=session-guard.js.map
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Suggestion-tap callback handler.
|
|
3
|
+
*
|
|
4
|
+
* When a user taps a "💡 …" inline button — under an assistant response, or on
|
|
5
|
+
* a suggestion card of its own — we look up the stored suggestion text
|
|
6
|
+
* (callback_data only carries a short id) and dispatch it through the same
|
|
7
|
+
* path as a user-typed message:
|
|
8
|
+
* - show what was effectively sent, so the conversation log reads like a
|
|
9
|
+
* real exchange: an echo line under a button, or the card rewritten in
|
|
10
|
+
* place when it is already spelling the prompt out
|
|
11
|
+
* - remove the buttons so the same suggestion can't be replayed accidentally
|
|
12
|
+
* - push the prompt through the normal request queue and streaming path
|
|
13
|
+
*/
|
|
14
|
+
import { consumeSuggestion } from '../../claude/pending-suggestions.js';
|
|
15
|
+
import { getSessionKeyFromCtx } from '../../utils/session-key.js';
|
|
16
|
+
import { sessionManager } from '../../claude/session-manager.js';
|
|
17
|
+
import { EntityText } from '../../telegram/entities.js';
|
|
18
|
+
import { editCallbackMessage, replyFormatted } from '../../telegram/send.js';
|
|
19
|
+
import { buildSuggestionCardText } from '../../telegram/prompt-suggestion.js';
|
|
20
|
+
export async function handleSuggestionTapCallback(ctx) {
|
|
21
|
+
const data = ctx.callbackQuery?.data;
|
|
22
|
+
if (!data?.startsWith('sgt:'))
|
|
23
|
+
return;
|
|
24
|
+
const id = data.slice('sgt:'.length);
|
|
25
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
26
|
+
if (!keyInfo) {
|
|
27
|
+
await ctx.answerCallbackQuery({ text: 'Session not found' });
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const { sessionKey } = keyInfo;
|
|
31
|
+
const entry = consumeSuggestion(id);
|
|
32
|
+
if (!entry) {
|
|
33
|
+
await ctx.answerCallbackQuery({ text: 'Suggestion expired or already used' });
|
|
34
|
+
try {
|
|
35
|
+
await ctx.editMessageReplyMarkup({ reply_markup: undefined });
|
|
36
|
+
}
|
|
37
|
+
catch { /* ignore */ }
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
// A button tap can sometimes outlive the session it came from (bot
|
|
41
|
+
// restarted between the response posting and the tap). Bail with a clear
|
|
42
|
+
// message rather than dispatching a prompt against no session.
|
|
43
|
+
const session = sessionManager.getSession(sessionKey);
|
|
44
|
+
if (!session) {
|
|
45
|
+
await ctx.answerCallbackQuery({ text: 'No active session' });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
await ctx.answerCallbackQuery({ text: 'Sending…' });
|
|
49
|
+
if (entry.presentation === 'card') {
|
|
50
|
+
// The card is the only place this prompt is written out, so it stays —
|
|
51
|
+
// rewritten to say it was sent, which drops the keyboard in the same
|
|
52
|
+
// edit. Echoing underneath would just repeat the line above it.
|
|
53
|
+
try {
|
|
54
|
+
await editCallbackMessage(ctx, buildSuggestionCardText(entry.text, { sent: true }));
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
console.debug('[Suggestion] card edit failed:', err instanceof Error ? err.message : err);
|
|
58
|
+
// Fall back to at least taking the button away, so the card can't be
|
|
59
|
+
// tapped again into an "expired" answer.
|
|
60
|
+
try {
|
|
61
|
+
await ctx.editMessageReplyMarkup({ reply_markup: undefined });
|
|
62
|
+
}
|
|
63
|
+
catch { /* ignore */ }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
try {
|
|
68
|
+
await ctx.editMessageReplyMarkup({ reply_markup: undefined });
|
|
69
|
+
}
|
|
70
|
+
catch { /* ignore */ }
|
|
71
|
+
// Echo what we're sending so the chat scroll reads like a real conversation.
|
|
72
|
+
try {
|
|
73
|
+
await replyFormatted(ctx, new EntityText().add('💡 ').italic(entry.text).build());
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
console.debug('[Suggestion] echo failed:', err instanceof Error ? err.message : err);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// Dispatch through the normal pipeline. Lazy import avoids a circular
|
|
80
|
+
// import between this file and message.handler.ts.
|
|
81
|
+
const { dispatchPromptFromCallback, runQueuedTurn } = await import('./message.handler.js');
|
|
82
|
+
await runQueuedTurn(ctx, sessionKey, entry.text, 'Suggestion', () => dispatchPromptFromCallback(ctx, sessionKey, entry.text));
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=suggestion.handler.js.map
|
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /tree — the branches of a branched conversation, drawn in one message, and a
|
|
3
|
+
* way back to any point in them.
|
|
4
|
+
*
|
|
5
|
+
* The tree is read off the transcripts (see branch-tree.ts), so it holds every
|
|
6
|
+
* branch still on disk: ones handed to sibling bots, and ones long gone from
|
|
7
|
+
* /resume. The message draws it whole, each point keyed by a letter the way
|
|
8
|
+
* /resume keys its sessions, and the buttons are just the letters. A letter
|
|
9
|
+
* opens its point — the exchange it ends on, and what can be done from there:
|
|
10
|
+
*
|
|
11
|
+
* ▶️ Carry on this branch the end of a branch: go back to it
|
|
12
|
+
* 🌱 New branch from here any point: start another branch from it
|
|
13
|
+
*
|
|
14
|
+
* Carrying on only ever resumes a branch this chat's own /resume holds. Any
|
|
15
|
+
* other branch is carried on as a copy: that another chat or bot has it, or
|
|
16
|
+
* that none does any more, says nothing about whether something — a sibling,
|
|
17
|
+
* a terminal — has it open, and two writers would interleave one transcript.
|
|
18
|
+
* The copy ends where the branch does, so the tree still draws one branch end.
|
|
19
|
+
*
|
|
20
|
+
* Callback data has to fit in 64 bytes, and a uuid takes 36, so a point's
|
|
21
|
+
* button names its tree by the first 8 characters of the tree's root:
|
|
22
|
+
*
|
|
23
|
+
* tree:show 🌳 on a banner: send the current tree
|
|
24
|
+
* tree:f:<rootId> show a tree in this message
|
|
25
|
+
* tree:n:<root8>:<nodeId> open a point
|
|
26
|
+
* tree:c:<root8>:<nodeId> carry on the branch ending at that point
|
|
27
|
+
* tree:b:<root8>:<nodeId> start a new branch from that point
|
|
28
|
+
*
|
|
29
|
+
* Every tap re-reads the tree, so a message sent before the conversation moved
|
|
30
|
+
* on still acts on what is on disk now. A point is its last record's uuid,
|
|
31
|
+
* which a transcript that only ever grows never takes back.
|
|
32
|
+
*/
|
|
33
|
+
import * as fs from 'fs';
|
|
34
|
+
import * as path from 'path';
|
|
35
|
+
import { BOT_ID, config } from '../../config.js';
|
|
36
|
+
import { getSessionKeyFromCtx } from '../../utils/session-key.js';
|
|
37
|
+
import { sanitizeError } from '../../utils/sanitize.js';
|
|
38
|
+
import { findBotById } from '../../utils/instances.js';
|
|
39
|
+
import { sessionManager } from '../../claude/session-manager.js';
|
|
40
|
+
import { findHistoryOwners } from '../../claude/session-history.js';
|
|
41
|
+
import { countJsonlLines } from '../../claude/message-offsets.js';
|
|
42
|
+
import { lastAssistantTurnText, lastExchangeIn, sessionJsonlPath } from '../../claude/session-jsonl.js';
|
|
43
|
+
import { branchedConversations, nodeById, nodeWhereEnds, preorder, promptsIn, transcriptUpTo, treeByRoot, treeOf, } from '../../claude/branch-tree.js';
|
|
44
|
+
import { clearConversation } from '../../providers/provider-router.js';
|
|
45
|
+
import { EntityText, joinMessages, plain } from '../../telegram/entities.js';
|
|
46
|
+
import { replyFormatted } from '../../telegram/send.js';
|
|
47
|
+
import { taskListDisplay } from '../../telegram/task-list.js';
|
|
48
|
+
import { buildLetterKeyboard, buildLetteredKeyboard, letteredOptionLines, optionLetter, } from '../../telegram/lettered-options.js';
|
|
49
|
+
import { cutLabel, promptLabel } from '../../telegram/prompt-label.js';
|
|
50
|
+
import { restoreTopic, getSessionTopic } from './command.handler.js';
|
|
51
|
+
import { formatTimeAgo } from './command/shared.js';
|
|
52
|
+
import { NO_PROJECT_MESSAGE, whereChatIs } from './session-guard.js';
|
|
53
|
+
import { refuseWhileBusy, sendView } from './view.js';
|
|
54
|
+
import { LEFT_ABOVE, buildBackOnBranchMarker, loadBranch, postMarker, replyQuote, youLine, } from './branch.handler.js';
|
|
55
|
+
/**
|
|
56
|
+
* How far a line of the drawn tree may run. It sits in a code block so the
|
|
57
|
+
* branches line up, and a phone wraps a code block's lines — which would break
|
|
58
|
+
* them apart — somewhere past this. So a point's prompt is wrapped here
|
|
59
|
+
* instead, onto lines of its own with the branches carried on down beside.
|
|
60
|
+
*/
|
|
61
|
+
const TREE_LINE_WIDTH = 32;
|
|
62
|
+
/** The narrowest a point's prompt wraps to, however deep the point sits. */
|
|
63
|
+
const MIN_LABEL_WIDTH = 8;
|
|
64
|
+
/** Points one message draws. Past this the rest are counted, not drawn. */
|
|
65
|
+
const MAX_TREE_NODES = 40;
|
|
66
|
+
/**
|
|
67
|
+
* How long a prompt can run before /tree shows only its start and its end —
|
|
68
|
+
* as long as /prompts and the status line let one run. Across the branched
|
|
69
|
+
* conversations on disk, the prompt naming a point has a median of 95
|
|
70
|
+
* characters, where a line of the tree has room for about 23; 93% fit in this.
|
|
71
|
+
*/
|
|
72
|
+
const PROMPT_MAX = 300;
|
|
73
|
+
/**
|
|
74
|
+
* What the drawn tree may take of its message. Telegram caps a message at
|
|
75
|
+
* 4096 characters, and the rest of the view takes a couple of hundred.
|
|
76
|
+
*/
|
|
77
|
+
const TREE_BUDGET_CHARS = 3800;
|
|
78
|
+
/** How much of a point's label its own view spells out. */
|
|
79
|
+
const NODE_TITLE_LEN = 60;
|
|
80
|
+
/**
|
|
81
|
+
* How much of the reply a point ends on its view shows. Less than a banner
|
|
82
|
+
* gets: this is a menu, read before choosing, and the whole reply is one tap
|
|
83
|
+
* away in the conversation it belongs to.
|
|
84
|
+
*/
|
|
85
|
+
const NODE_REPLY_LEN = 1200;
|
|
86
|
+
/** Branched conversations the list offers when there is no tree to show. */
|
|
87
|
+
const MAX_LISTED_TREES = 8;
|
|
88
|
+
/** The first 8 characters of a tree's root: enough to find it among one project's trees. */
|
|
89
|
+
const rootKey = (tree) => tree.rootId.slice(0, 8);
|
|
90
|
+
// ── Labels ───────────────────────────────────────────────────────────────
|
|
91
|
+
/** A point's name: the first prompt in its stretch that was a turn. */
|
|
92
|
+
function nodeLabel(node) {
|
|
93
|
+
for (const prompt of node.prompts) {
|
|
94
|
+
const label = promptLabel(prompt);
|
|
95
|
+
if (label)
|
|
96
|
+
return label;
|
|
97
|
+
}
|
|
98
|
+
// A stretch with no prompt of its own carries on the reply above it.
|
|
99
|
+
return '…';
|
|
100
|
+
}
|
|
101
|
+
/** Turns taken in a point's own stretch — prompts, not commands. */
|
|
102
|
+
function turnsIn(node) {
|
|
103
|
+
return node.prompts.filter((prompt) => promptLabel(prompt) !== undefined).length;
|
|
104
|
+
}
|
|
105
|
+
// ── The tree ─────────────────────────────────────────────────────────────
|
|
106
|
+
const isLastChild = (node) => node.parent?.children.at(-1) === node;
|
|
107
|
+
/**
|
|
108
|
+
* The rails running down past a point, beside its own lines and its
|
|
109
|
+
* descendants': one for it and for every ancestor that has a sibling still to
|
|
110
|
+
* come below.
|
|
111
|
+
*/
|
|
112
|
+
function railsOf(node) {
|
|
113
|
+
let out = '';
|
|
114
|
+
for (let n = node; n.parent; n = n.parent)
|
|
115
|
+
out = (isLastChild(n) ? ' ' : '│') + out;
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
/** The branch lines leading to a point: the rails down to its parent, and its own connector. */
|
|
119
|
+
function connectorsOf(node) {
|
|
120
|
+
return node.parent ? railsOf(node.parent) + (isLastChild(node) ? '└' : '├') : '';
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* `words` in rows of at most `width` characters. A word longer than a row — a
|
|
124
|
+
* path, a URL — starts a row of its own and is split where the row ends.
|
|
125
|
+
* Counted by code point, so an emoji isn't split in half.
|
|
126
|
+
*/
|
|
127
|
+
function wrap(words, width) {
|
|
128
|
+
const rows = [];
|
|
129
|
+
for (const word of words) {
|
|
130
|
+
const chars = Array.from(word);
|
|
131
|
+
const row = rows.at(-1);
|
|
132
|
+
if (row && row.length + 1 + chars.length <= width) {
|
|
133
|
+
row.push(' ', ...chars);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
for (let i = 0; i < chars.length; i += width)
|
|
137
|
+
rows.push(chars.slice(i, i + width));
|
|
138
|
+
}
|
|
139
|
+
return rows.map((row) => row.join(''));
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* A point's lines: its letter, then `label` and `tail` wrapped to the width
|
|
143
|
+
* its branches leave, with the rails carried on down beside them — and one
|
|
144
|
+
* under the letter too when there are points below it.
|
|
145
|
+
*/
|
|
146
|
+
function treeLines(node, letter, label, tail) {
|
|
147
|
+
const first = `${connectorsOf(node)}${letter} `;
|
|
148
|
+
const next = `${railsOf(node)}${node.children.length > 0 ? '│' : ' '}`.padEnd(first.length);
|
|
149
|
+
const width = Math.max(MIN_LABEL_WIDTH, TREE_LINE_WIDTH - first.length);
|
|
150
|
+
return wrap([...label.split(' '), tail], width).map((row, i) => (i === 0 ? first : next) + row);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The longest a prompt can run with the drawn tree fitting its message:
|
|
154
|
+
* PROMPT_MAX, unless the tree is too big for that, and then one cap for every
|
|
155
|
+
* point, so the longest prompts give way first.
|
|
156
|
+
*/
|
|
157
|
+
function capToFit(draw) {
|
|
158
|
+
const fits = (cap) => draw(cap).join('\n').length <= TREE_BUDGET_CHARS;
|
|
159
|
+
if (fits(PROMPT_MAX))
|
|
160
|
+
return PROMPT_MAX;
|
|
161
|
+
// The narrowest line's worth each, two lines at most, fits every point a message draws.
|
|
162
|
+
let lo = MIN_LABEL_WIDTH;
|
|
163
|
+
let hi = PROMPT_MAX - 1;
|
|
164
|
+
while (lo < hi) {
|
|
165
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
166
|
+
if (fits(mid))
|
|
167
|
+
lo = mid;
|
|
168
|
+
else
|
|
169
|
+
hi = mid - 1;
|
|
170
|
+
}
|
|
171
|
+
return lo;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* A tree drawn whole, a letter per point, with a button per letter. 📍 marks
|
|
175
|
+
* where `hereSessionId` ends — the chat's conversation, or with `leftOff`, the
|
|
176
|
+
* one it left off in before a restart dropped it.
|
|
177
|
+
*/
|
|
178
|
+
export function renderTree(tree, hereSessionId, leftOff = false) {
|
|
179
|
+
const nodes = preorder(tree);
|
|
180
|
+
const shown = nodes.slice(0, MAX_TREE_NODES);
|
|
181
|
+
const here = hereSessionId ? nodeWhereEnds(tree, hereSessionId) : undefined;
|
|
182
|
+
const ends = nodes.filter((node) => node.endsHere.length > 0).length;
|
|
183
|
+
// Worked out once, since capToFit may draw the tree a few times over. The
|
|
184
|
+
// turn count and its mark stay together, after the prompt's last word.
|
|
185
|
+
const points = shown.map((node, i) => ({
|
|
186
|
+
node,
|
|
187
|
+
letter: optionLetter(i),
|
|
188
|
+
label: nodeLabel(node),
|
|
189
|
+
tail: `·${turnsIn(node)}${node === here ? ' 📍' : node.endsHere.length > 0 ? ' ▸' : ''}`,
|
|
190
|
+
}));
|
|
191
|
+
const draw = (cap) => points
|
|
192
|
+
.flatMap((p) => treeLines(p.node, p.letter, cutLabel(p.label, cap), p.tail));
|
|
193
|
+
const drawn = draw(capToFit(draw));
|
|
194
|
+
const hidden = nodes.length - shown.length;
|
|
195
|
+
const text = joinMessages([
|
|
196
|
+
new EntityText()
|
|
197
|
+
.add('🌳 ').bold(path.basename(tree.projectPath)).add(` — ${ends} ${ends === 1 ? 'branch' : 'branches'}`)
|
|
198
|
+
.build(),
|
|
199
|
+
new EntityText().pre(drawn.join('\n')).build(),
|
|
200
|
+
...(hidden > 0 ? [plain(`${hidden} more ${hidden === 1 ? 'point isn’t' : 'points aren’t'} drawn.`)] : []),
|
|
201
|
+
new EntityText()
|
|
202
|
+
.italic(`·N turns · ▸ branch end${here ? ` · 📍 ${leftOff ? 'where this chat left off' : 'you are here'}` : ''}`)
|
|
203
|
+
.build(),
|
|
204
|
+
plain('Tap a letter to open that point.'),
|
|
205
|
+
], '\n');
|
|
206
|
+
const keyboard = buildLetterKeyboard(shown.map((node) => `tree:n:${rootKey(tree)}:${node.id}`));
|
|
207
|
+
return { text, keyboard };
|
|
208
|
+
}
|
|
209
|
+
function carryOnAt(node, sessionKey, hereSessionId) {
|
|
210
|
+
const ends = node.endsHere;
|
|
211
|
+
if (ends.length === 0)
|
|
212
|
+
return undefined;
|
|
213
|
+
if (hereSessionId && ends.includes(hereSessionId))
|
|
214
|
+
return { kind: 'here' };
|
|
215
|
+
const owners = findHistoryOwners(ends, BOT_ID);
|
|
216
|
+
for (const sessionId of ends) {
|
|
217
|
+
const mine = owners.get(sessionId)?.find((o) => o.botId === BOT_ID && o.sessionKey === sessionKey);
|
|
218
|
+
if (mine)
|
|
219
|
+
return { kind: 'resume', sessionId, owner: mine };
|
|
220
|
+
}
|
|
221
|
+
const sessionId = ends[0];
|
|
222
|
+
return { kind: 'copy', sessionId, owner: owners.get(sessionId)?.[0] };
|
|
223
|
+
}
|
|
224
|
+
/** Where a branch end is, and so what carrying it on will do — for the point's view. */
|
|
225
|
+
function describeCarryOn(carry) {
|
|
226
|
+
switch (carry.kind) {
|
|
227
|
+
case 'here':
|
|
228
|
+
return '📍 You are on this branch.';
|
|
229
|
+
case 'resume':
|
|
230
|
+
return "It's in this chat's /resume.";
|
|
231
|
+
case 'copy': {
|
|
232
|
+
if (!carry.owner) {
|
|
233
|
+
return "No chat's /resume has it any more. Carrying it on here makes a copy; the original stays as it is.";
|
|
234
|
+
}
|
|
235
|
+
const where = carry.owner.botId === BOT_ID
|
|
236
|
+
? 'another chat with this bot'
|
|
237
|
+
: (findBotById(carry.owner.botId)?.name ?? 'another bot');
|
|
238
|
+
return `It lives in ${where} — carrying it on here makes a copy, and that one stays as it is.`;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/** "D", "D and H", "D, H and I". */
|
|
243
|
+
function listLetters(letters) {
|
|
244
|
+
return letters.length <= 1 ? letters.join('') : `${letters.slice(0, -1).join(', ')} and ${letters.at(-1)}`;
|
|
245
|
+
}
|
|
246
|
+
/** One point of a tree: the exchange it ends on, and what can be done from it. */
|
|
247
|
+
export function renderNode(tree, node, sessionKey, hereSessionId) {
|
|
248
|
+
const nodes = preorder(tree);
|
|
249
|
+
const letterOf = (n) => optionLetter(nodes.indexOf(n));
|
|
250
|
+
const carry = carryOnAt(node, sessionKey, hereSessionId);
|
|
251
|
+
const turns = turnsIn(node);
|
|
252
|
+
const facts = [`${turns} ${turns === 1 ? 'turn' : 'turns'}`];
|
|
253
|
+
if (node.endsHere.length > 0) {
|
|
254
|
+
facts.push('branch end');
|
|
255
|
+
const mtimeMs = tree.transcripts.get(node.endsHere[0])?.mtimeMs;
|
|
256
|
+
if (mtimeMs)
|
|
257
|
+
facts.push(`last active ${formatTimeAgo(new Date(mtimeMs))}`);
|
|
258
|
+
}
|
|
259
|
+
const upTo = transcriptUpTo(tree, node);
|
|
260
|
+
const exchange = upTo ? lastExchangeIn(upTo) : undefined;
|
|
261
|
+
const text = joinMessages([
|
|
262
|
+
new EntityText().add('🌳 ').bold(letterOf(node)).add(` · ${cutLabel(nodeLabel(node), NODE_TITLE_LEN)}`).build(),
|
|
263
|
+
new EntityText().italic(facts.join(' · ')).build(),
|
|
264
|
+
...(carry ? [plain(describeCarryOn(carry))] : []),
|
|
265
|
+
...(node.children.length > 0 ? [plain(`Splits into ${listLetters(node.children.map(letterOf))}.`)] : []),
|
|
266
|
+
...(exchange
|
|
267
|
+
? [
|
|
268
|
+
plain(''),
|
|
269
|
+
youLine(exchange.user, PROMPT_MAX),
|
|
270
|
+
// Cut without pointing at /history: that shows the chat's conversation,
|
|
271
|
+
// which this point may not be on.
|
|
272
|
+
...replyQuote(exchange.assistant, NODE_REPLY_LEN, null),
|
|
273
|
+
]
|
|
274
|
+
: []),
|
|
275
|
+
], '\n');
|
|
276
|
+
const ref = `${rootKey(tree)}:${node.id}`;
|
|
277
|
+
const keyboard = [
|
|
278
|
+
...(carry && carry.kind !== 'here' ? [[{ text: '▶️ Carry on this branch', callback_data: `tree:c:${ref}` }]] : []),
|
|
279
|
+
[{ text: '🌱 New branch from here', callback_data: `tree:b:${ref}` }],
|
|
280
|
+
[{ text: '⬅️ Back to the tree', callback_data: `tree:f:${tree.rootId}` }],
|
|
281
|
+
];
|
|
282
|
+
return { text, keyboard };
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* The branched conversations in a project, for when there is no tree to show —
|
|
286
|
+
* the chat is on one that was never branched, or on none at all.
|
|
287
|
+
*/
|
|
288
|
+
export function renderTreeList(projectPath, intro) {
|
|
289
|
+
const project = path.basename(projectPath);
|
|
290
|
+
const conversations = branchedConversations(projectPath).slice(0, MAX_LISTED_TREES);
|
|
291
|
+
if (conversations.length === 0) {
|
|
292
|
+
return {
|
|
293
|
+
text: joinMessages([
|
|
294
|
+
...(intro ? [plain(intro), plain('')] : []),
|
|
295
|
+
new EntityText().add('🌳 No conversation in ').bold(project).add(' has been branched yet.').build(),
|
|
296
|
+
plain(''),
|
|
297
|
+
plain('Tap 🌱 Branch under a reply to start one.'),
|
|
298
|
+
], '\n'),
|
|
299
|
+
keyboard: [],
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
const options = conversations.map((c) => ({
|
|
303
|
+
label: cutLabel(promptsIn(projectPath, c.sessionIds[0]).map(promptLabel).find(Boolean) ?? 'Untitled', PROMPT_MAX),
|
|
304
|
+
description: `${c.sessionIds.length} branches · ${formatTimeAgo(new Date(c.lastActiveMs))}`,
|
|
305
|
+
}));
|
|
306
|
+
return {
|
|
307
|
+
text: joinMessages([
|
|
308
|
+
...(intro ? [plain(intro), plain('')] : []),
|
|
309
|
+
new EntityText().add('🌳 ').bold('Branched conversations').add(` · ${project}`).build(),
|
|
310
|
+
plain(''),
|
|
311
|
+
...letteredOptionLines(options).map(plain),
|
|
312
|
+
], '\n'),
|
|
313
|
+
keyboard: buildLetteredKeyboard(options.map((o, i) => ({ label: o.label, callbackData: `tree:f:${conversations[i].rootId}` }))),
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/** The tree the chat is in, or the list of trees when it isn't in one. */
|
|
317
|
+
function currentView(sessionKey) {
|
|
318
|
+
const where = whereChatIs(sessionKey);
|
|
319
|
+
if (!where)
|
|
320
|
+
return undefined;
|
|
321
|
+
const tree = where.sessionId ? treeOf(where.projectPath, where.sessionId) : undefined;
|
|
322
|
+
if (tree && tree.transcripts.size > 1)
|
|
323
|
+
return renderTree(tree, where.sessionId, !where.live);
|
|
324
|
+
const intro = !where.sessionId
|
|
325
|
+
? undefined
|
|
326
|
+
: where.live
|
|
327
|
+
? "This conversation hasn't been branched yet."
|
|
328
|
+
: "The conversation this chat left off in hasn't been branched.";
|
|
329
|
+
return renderTreeList(where.projectPath, intro);
|
|
330
|
+
}
|
|
331
|
+
/** A button that draws `tree` in place of the message it's on: the way into it from another view. */
|
|
332
|
+
export function showTreeButton(tree) {
|
|
333
|
+
return { text: '🌳 Show the tree', callback_data: `tree:f:${tree.rootId}` };
|
|
334
|
+
}
|
|
335
|
+
// ── Commands and taps ────────────────────────────────────────────────────
|
|
336
|
+
export async function handleTreeCommand(ctx) {
|
|
337
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
338
|
+
if (!keyInfo)
|
|
339
|
+
return;
|
|
340
|
+
const view = currentView(keyInfo.sessionKey);
|
|
341
|
+
if (!view) {
|
|
342
|
+
await replyFormatted(ctx, NO_PROJECT_MESSAGE);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
await sendView(ctx, view, 'reply');
|
|
346
|
+
}
|
|
347
|
+
export async function handleTreeCallback(ctx) {
|
|
348
|
+
const data = ctx.callbackQuery?.data;
|
|
349
|
+
const keyInfo = getSessionKeyFromCtx(ctx);
|
|
350
|
+
if (!data || !keyInfo)
|
|
351
|
+
return;
|
|
352
|
+
const { sessionKey } = keyInfo;
|
|
353
|
+
const [, action, rootId, nodeId] = data.split(':');
|
|
354
|
+
try {
|
|
355
|
+
if (action === 'show') {
|
|
356
|
+
// Answered first: the first tree a bot draws reads the project's
|
|
357
|
+
// transcripts, and the button shouldn't sit spinning meanwhile.
|
|
358
|
+
await ctx.answerCallbackQuery();
|
|
359
|
+
const view = currentView(sessionKey);
|
|
360
|
+
if (!view) {
|
|
361
|
+
await replyFormatted(ctx, NO_PROJECT_MESSAGE);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
await sendView(ctx, view, 'reply');
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const where = whereChatIs(sessionKey);
|
|
368
|
+
const tree = where && rootId ? treeByRoot(where.projectPath, rootId, nodeId) : undefined;
|
|
369
|
+
if (!where || !tree) {
|
|
370
|
+
await ctx.answerCallbackQuery({ text: "That tree isn't in this chat's project any more — send /tree again." });
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
// The branch the chat is on, for "you're on it already". A conversation a
|
|
374
|
+
// restart left unloaded isn't one the chat is on.
|
|
375
|
+
const here = where.live ? where.sessionId : undefined;
|
|
376
|
+
if (action === 'f') {
|
|
377
|
+
await ctx.answerCallbackQuery();
|
|
378
|
+
await sendView(ctx, renderTree(tree, where.sessionId, !where.live), 'edit');
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const node = nodeId ? nodeById(tree, nodeId) : undefined;
|
|
382
|
+
if (!node) {
|
|
383
|
+
await ctx.answerCallbackQuery({ text: "That point isn't in the tree any more — send /tree again." });
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (action === 'n') {
|
|
387
|
+
await ctx.answerCallbackQuery();
|
|
388
|
+
await sendView(ctx, renderNode(tree, node, sessionKey, here), 'edit');
|
|
389
|
+
}
|
|
390
|
+
else if (action === 'c') {
|
|
391
|
+
await onCarryOn(ctx, sessionKey, tree, node, here);
|
|
392
|
+
}
|
|
393
|
+
else if (action === 'b') {
|
|
394
|
+
await onBranch(ctx, sessionKey, tree, node, here);
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
await ctx.answerCallbackQuery({ text: 'Unknown tree action.' });
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
catch (err) {
|
|
401
|
+
console.error('[Tree] callback failed:', sanitizeError(err));
|
|
402
|
+
try {
|
|
403
|
+
await ctx.answerCallbackQuery({ text: 'That failed — see bot logs.' });
|
|
404
|
+
}
|
|
405
|
+
catch { /* already answered */ }
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
async function onCarryOn(ctx, sessionKey, tree, node, here) {
|
|
409
|
+
const carry = carryOnAt(node, sessionKey, here);
|
|
410
|
+
if (!carry) {
|
|
411
|
+
await ctx.answerCallbackQuery({ text: 'No branch ends at that point.' });
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
if (carry.kind === 'here') {
|
|
415
|
+
await ctx.answerCallbackQuery({ text: "You're on this branch already." });
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
if (await refuseWhileBusy(ctx, sessionKey))
|
|
419
|
+
return;
|
|
420
|
+
if (carry.kind === 'copy') {
|
|
421
|
+
const copied = await branchFrom(ctx, sessionKey, tree, node, carry.owner);
|
|
422
|
+
await ctx.answerCallbackQuery({ text: copied ? 'Carried on as a copy.' : "That branch's transcript is gone from disk." });
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
// Back to a conversation in this chat's /resume — what /resume itself does.
|
|
426
|
+
if (!sessionManager.resumeSession(sessionKey, carry.owner.entry.conversationId)) {
|
|
427
|
+
await ctx.answerCallbackQuery({ text: "That branch isn't in this chat's /resume any more — send /tree again." });
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
clearConversation(sessionKey);
|
|
431
|
+
restoreTopic(sessionKey, carry.owner.entry.topic);
|
|
432
|
+
const file = sessionJsonlPath(tree.projectPath, carry.sessionId);
|
|
433
|
+
let jsonl = '';
|
|
434
|
+
try {
|
|
435
|
+
jsonl = fs.readFileSync(file, 'utf-8');
|
|
436
|
+
}
|
|
437
|
+
catch { /* the banner just goes without the exchange */ }
|
|
438
|
+
await postMarker(ctx, sessionKey, buildBackOnBranchMarker({ projectPath: tree.projectPath, topic: getSessionTopic(sessionKey), jsonl }), { claudeSessionId: carry.sessionId, projectPath: tree.projectPath, lineCount: countJsonlLines(file) });
|
|
439
|
+
await taskListDisplay.showRestored(ctx.api, sessionKey, carry.sessionId);
|
|
440
|
+
await ctx.answerCallbackQuery({ text: 'Back on that branch.' });
|
|
441
|
+
}
|
|
442
|
+
async function onBranch(ctx, sessionKey, tree, node, here) {
|
|
443
|
+
if (await refuseWhileBusy(ctx, sessionKey))
|
|
444
|
+
return;
|
|
445
|
+
// The topic of the branch this point is on: the chat's own, when the chat
|
|
446
|
+
// is on it, else whichever history last had one of its transcripts open.
|
|
447
|
+
const owners = findHistoryOwners(node.sessionIds, BOT_ID);
|
|
448
|
+
const latest = [...owners.values()].flat()
|
|
449
|
+
.sort((a, b) => b.entry.lastActivity.localeCompare(a.entry.lastActivity))[0];
|
|
450
|
+
const topic = here && node.sessionIds.includes(here) ? getSessionTopic(sessionKey) : latest?.entry.topic;
|
|
451
|
+
if (!(await branchFrom(ctx, sessionKey, tree, node, undefined, topic))) {
|
|
452
|
+
await ctx.answerCallbackQuery({ text: "That point's transcript is gone from disk." });
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
await ctx.answerCallbackQuery({ text: 'Branched.' });
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Start a conversation in this chat from the transcript cut at `node`: a branch,
|
|
459
|
+
* loaded straight away. From another bot's branch it is named as that bot's,
|
|
460
|
+
* so the banner says where it came from. False if the transcript is gone.
|
|
461
|
+
*/
|
|
462
|
+
async function branchFrom(ctx, sessionKey, tree, node, owner, topic = owner?.entry.topic) {
|
|
463
|
+
const jsonl = transcriptUpTo(tree, node);
|
|
464
|
+
if (!jsonl)
|
|
465
|
+
return false;
|
|
466
|
+
const fromOtherBot = owner && owner.botId !== BOT_ID;
|
|
467
|
+
const branch = {
|
|
468
|
+
fromBotName: fromOtherBot ? (findBotById(owner.botId)?.name ?? 'another bot') : config.BOT_NAME,
|
|
469
|
+
fromBotId: fromOtherBot ? owner.botId : BOT_ID,
|
|
470
|
+
fromChatId: ctx.chat?.id,
|
|
471
|
+
projectPath: tree.projectPath,
|
|
472
|
+
jsonl,
|
|
473
|
+
topic,
|
|
474
|
+
assistantPreview: lastAssistantTurnText(jsonl)?.substring(0, 200),
|
|
475
|
+
createdAt: new Date().toISOString(),
|
|
476
|
+
};
|
|
477
|
+
await loadBranch(ctx, sessionKey, branch, { above: LEFT_ABOVE });
|
|
478
|
+
return true;
|
|
479
|
+
}
|
|
480
|
+
//# sourceMappingURL=tree.handler.js.map
|