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,480 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /tree — the branches of a forked 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 fork-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 { forkedConversations, nodeById, nodeWhereEnds, preorder, promptsIn, transcriptUpTo, treeByRoot, treeOf, } from '../../claude/fork-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 { restoreTopicAndRefreshBotName, 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, loadFork, postMarker, replyQuote, youLine, } from './fork.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 forked
|
|
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
|
+
/** Forked 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 /recap: 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 forked conversations in a project, for when there is no tree to show —
|
|
286
|
+
* the chat is on one that was never forked, or on none at all.
|
|
287
|
+
*/
|
|
288
|
+
export function renderTreeList(projectPath, intro) {
|
|
289
|
+
const project = path.basename(projectPath);
|
|
290
|
+
const conversations = forkedConversations(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 forked yet.').build(),
|
|
296
|
+
plain(''),
|
|
297
|
+
plain('Tap 🍴 Fork under a reply to branch 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('Forked 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 forked yet."
|
|
328
|
+
: "The conversation this chat left off in hasn't been forked.";
|
|
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
|
+
await restoreTopicAndRefreshBotName(ctx, 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 fork,
|
|
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 fork = {
|
|
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 loadFork(ctx, sessionKey, fork, { above: LEFT_ABOVE });
|
|
478
|
+
return true;
|
|
479
|
+
}
|
|
480
|
+
//# sourceMappingURL=tree.handler.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A view: one message that /tree and /prompts redraw in place as their
|
|
3
|
+
* buttons are tapped — a list keyed by letters, the item a letter opens, back
|
|
4
|
+
* to the list — and the check the buttons that switch conversations share.
|
|
5
|
+
*/
|
|
6
|
+
import { isProcessing } from '../../claude/request-queue.js';
|
|
7
|
+
import { editCallbackMessage, replyFormatted } from '../../telegram/send.js';
|
|
8
|
+
/**
|
|
9
|
+
* Send `view` as a reply, or put it in place of the tapped message. A view
|
|
10
|
+
* Telegram won't format goes out as plain text instead (the send helpers
|
|
11
|
+
* retry it), so a formatting slip costs the formatting and not the view.
|
|
12
|
+
*/
|
|
13
|
+
export async function sendView(ctx, view, how) {
|
|
14
|
+
const reply_markup = { inline_keyboard: view.keyboard };
|
|
15
|
+
try {
|
|
16
|
+
if (how === 'edit')
|
|
17
|
+
await editCallbackMessage(ctx, view.text, { reply_markup });
|
|
18
|
+
else
|
|
19
|
+
await replyFormatted(ctx, view.text, { reply_markup });
|
|
20
|
+
}
|
|
21
|
+
catch (err) {
|
|
22
|
+
// "message is not modified": the same view, tapped again. Nothing to do.
|
|
23
|
+
if (err instanceof Error && err.message.includes('not modified'))
|
|
24
|
+
return;
|
|
25
|
+
throw err;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Switching conversations under a running reply would cut it off, so the
|
|
30
|
+
* switches wait for it. Says so on the button and returns true when busy.
|
|
31
|
+
*/
|
|
32
|
+
export async function refuseWhileBusy(ctx, sessionKey) {
|
|
33
|
+
if (!isProcessing(sessionKey))
|
|
34
|
+
return false;
|
|
35
|
+
await ctx.answerCallbackQuery({
|
|
36
|
+
text: 'A reply is still running here — wait for it to finish, or /cancel it, then tap again.',
|
|
37
|
+
show_alert: true,
|
|
38
|
+
});
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=view.js.map
|