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,393 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fork tree: every transcript that grew out of one conversation, arranged
|
|
3
|
+
* by where each one split off.
|
|
4
|
+
*
|
|
5
|
+
* Nothing records that tree, and nothing has to. A fork is a copy of its
|
|
6
|
+
* source's transcript up to the fork point with every record id intact —
|
|
7
|
+
* loadFork rewrites only the session id — so transcripts that start with the
|
|
8
|
+
* same record grew out of the same conversation, and the last record two of
|
|
9
|
+
* them share is where they split. Reading the tree off the transcripts covers
|
|
10
|
+
* forks made before this module existed, forks handed between bots (they all
|
|
11
|
+
* write under the one ~/.claude/projects), and branches that fell out of every
|
|
12
|
+
* /resume list long ago but are still on disk.
|
|
13
|
+
*
|
|
14
|
+
* Structure is kept here and wording is not: which prompts are real turns, and
|
|
15
|
+
* how a point is labelled, is for the handler to decide.
|
|
16
|
+
*/
|
|
17
|
+
import * as fs from 'fs';
|
|
18
|
+
import * as path from 'path';
|
|
19
|
+
import { StringDecoder } from 'string_decoder';
|
|
20
|
+
import { extractText, isSyntheticUserRecord, sessionJsonlPath } from './session-jsonl.js';
|
|
21
|
+
/**
|
|
22
|
+
* How much of a prompt to keep from each end. A label needs a line; stripping
|
|
23
|
+
* a paste's tags or skipping a quoted passage to find the user's own words
|
|
24
|
+
* needs more, and a prompt too long to show whole shows its end as well as
|
|
25
|
+
* its start. Past this the middle is never shown.
|
|
26
|
+
*/
|
|
27
|
+
const PROMPT_KEEP_CHARS = 4000;
|
|
28
|
+
/** `text` with anything past PROMPT_KEEP_CHARS from either end left out. */
|
|
29
|
+
function keepEnds(text) {
|
|
30
|
+
if (text.length <= 2 * PROMPT_KEEP_CHARS)
|
|
31
|
+
return text;
|
|
32
|
+
return `${text.slice(0, PROMPT_KEEP_CHARS)} … ${text.slice(-PROMPT_KEEP_CHARS)}`;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Transcripts kept parsed between calls. A long transcript parses to a few
|
|
36
|
+
* hundred KB, and every bot keeps its own cache; this holds a tree or two,
|
|
37
|
+
* which is what a run of taps on one message reads again.
|
|
38
|
+
*/
|
|
39
|
+
const PARSE_CACHE_MAX = 16;
|
|
40
|
+
/**
|
|
41
|
+
* How much of a transcript to read at a time looking for its first record.
|
|
42
|
+
* That record is almost always within the first few KB, and a project can
|
|
43
|
+
* hold thousands of transcripts, so the first read is kept small.
|
|
44
|
+
*/
|
|
45
|
+
const ROOT_SCAN_CHUNK_BYTES = 8 * 1024;
|
|
46
|
+
/** How far into a transcript to look for its first record before giving up on it. */
|
|
47
|
+
const ROOT_SCAN_MAX_BYTES = 8 * 1024 * 1024;
|
|
48
|
+
/** Where Claude Code keeps the transcripts of conversations run in `projectPath`. */
|
|
49
|
+
export function transcriptDir(projectPath) {
|
|
50
|
+
return path.dirname(sessionJsonlPath(projectPath, 'x'));
|
|
51
|
+
}
|
|
52
|
+
// ── Which conversation each transcript grew out of ───────────────────────
|
|
53
|
+
/**
|
|
54
|
+
* First record uuid per transcript file. A transcript only ever grows, so once
|
|
55
|
+
* found its first record never changes and isn't looked up again; a file that
|
|
56
|
+
* has none yet is retried once it changes.
|
|
57
|
+
*/
|
|
58
|
+
const rootCache = new Map();
|
|
59
|
+
function firstRecordUuid(file) {
|
|
60
|
+
let fd;
|
|
61
|
+
try {
|
|
62
|
+
fd = fs.openSync(file, 'r');
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
const decoder = new StringDecoder('utf8');
|
|
69
|
+
const buf = Buffer.alloc(ROOT_SCAN_CHUNK_BYTES);
|
|
70
|
+
let pending = '';
|
|
71
|
+
let read = 0;
|
|
72
|
+
for (;;) {
|
|
73
|
+
const n = fs.readSync(fd, buf, 0, buf.length, read);
|
|
74
|
+
const atEof = n === 0;
|
|
75
|
+
read += n;
|
|
76
|
+
pending += atEof ? decoder.end() : decoder.write(buf.subarray(0, n));
|
|
77
|
+
const lines = pending.split('\n');
|
|
78
|
+
// The last piece is a line still being read — unless the file is done.
|
|
79
|
+
pending = atEof ? '' : lines.pop();
|
|
80
|
+
for (const line of lines) {
|
|
81
|
+
const uuid = uuidOf(line);
|
|
82
|
+
if (uuid)
|
|
83
|
+
return uuid;
|
|
84
|
+
}
|
|
85
|
+
if (atEof || read >= ROOT_SCAN_MAX_BYTES)
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
fs.closeSync(fd);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** The record's own uuid, or undefined for a bookkeeping line that has none. */
|
|
94
|
+
function uuidOf(line) {
|
|
95
|
+
// Bookkeeping lines (mode, titles, file snapshots) carry no uuid, and there
|
|
96
|
+
// is no point parsing them to find that out.
|
|
97
|
+
if (!line.includes('"uuid"'))
|
|
98
|
+
return undefined;
|
|
99
|
+
try {
|
|
100
|
+
const rec = JSON.parse(line);
|
|
101
|
+
return typeof rec.uuid === 'string' ? rec.uuid : undefined;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function rootOf(file) {
|
|
108
|
+
const cached = rootCache.get(file);
|
|
109
|
+
if (cached?.root)
|
|
110
|
+
return cached.root;
|
|
111
|
+
let stat;
|
|
112
|
+
try {
|
|
113
|
+
stat = fs.statSync(file);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
if (cached?.root === null && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size)
|
|
119
|
+
return undefined;
|
|
120
|
+
const root = firstRecordUuid(file);
|
|
121
|
+
rootCache.set(file, root ? { root } : { root: null, mtimeMs: stat.mtimeMs, size: stat.size });
|
|
122
|
+
return root;
|
|
123
|
+
}
|
|
124
|
+
/** Session ids in the project, grouped by the conversation they grew out of. */
|
|
125
|
+
function conversationsIn(projectPath) {
|
|
126
|
+
const dir = transcriptDir(projectPath);
|
|
127
|
+
let names;
|
|
128
|
+
try {
|
|
129
|
+
names = fs.readdirSync(dir);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return new Map();
|
|
133
|
+
}
|
|
134
|
+
const byRoot = new Map();
|
|
135
|
+
for (const name of names) {
|
|
136
|
+
if (!name.endsWith('.jsonl'))
|
|
137
|
+
continue;
|
|
138
|
+
const root = rootOf(path.join(dir, name));
|
|
139
|
+
if (!root)
|
|
140
|
+
continue;
|
|
141
|
+
const sessionId = name.slice(0, -'.jsonl'.length);
|
|
142
|
+
const members = byRoot.get(root);
|
|
143
|
+
if (members)
|
|
144
|
+
members.push(sessionId);
|
|
145
|
+
else
|
|
146
|
+
byRoot.set(root, [sessionId]);
|
|
147
|
+
}
|
|
148
|
+
return byRoot;
|
|
149
|
+
}
|
|
150
|
+
function mtimeMsOf(file) {
|
|
151
|
+
try {
|
|
152
|
+
return fs.statSync(file).mtimeMs;
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return 0;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Conversations in the project that have been forked — more than one
|
|
160
|
+
* transcript starting from the same record — most recently active first.
|
|
161
|
+
*/
|
|
162
|
+
export function forkedConversations(projectPath) {
|
|
163
|
+
const dir = transcriptDir(projectPath);
|
|
164
|
+
const out = [];
|
|
165
|
+
for (const [rootId, sessionIds] of conversationsIn(projectPath)) {
|
|
166
|
+
if (sessionIds.length < 2)
|
|
167
|
+
continue;
|
|
168
|
+
const lastActiveMs = Math.max(...sessionIds.map((id) => mtimeMsOf(path.join(dir, `${id}.jsonl`))));
|
|
169
|
+
out.push({ rootId, sessionIds, lastActiveMs });
|
|
170
|
+
}
|
|
171
|
+
return out.sort((a, b) => b.lastActiveMs - a.lastActiveMs);
|
|
172
|
+
}
|
|
173
|
+
// ── Reading a transcript ─────────────────────────────────────────────────
|
|
174
|
+
const parseCache = new Map();
|
|
175
|
+
function readTranscript(projectPath, sessionId) {
|
|
176
|
+
const file = sessionJsonlPath(projectPath, sessionId);
|
|
177
|
+
let stat;
|
|
178
|
+
try {
|
|
179
|
+
stat = fs.statSync(file);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
const cached = parseCache.get(file);
|
|
185
|
+
if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
|
|
186
|
+
// Refresh its place: the cache drops whatever was used longest ago.
|
|
187
|
+
parseCache.delete(file);
|
|
188
|
+
parseCache.set(file, cached);
|
|
189
|
+
return cached.transcript;
|
|
190
|
+
}
|
|
191
|
+
let raw;
|
|
192
|
+
try {
|
|
193
|
+
raw = fs.readFileSync(file, 'utf-8');
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
const records = [];
|
|
199
|
+
const lines = raw.split('\n');
|
|
200
|
+
for (let i = 0; i < lines.length; i++) {
|
|
201
|
+
const line = lines[i];
|
|
202
|
+
if (!line.includes('"uuid"'))
|
|
203
|
+
continue;
|
|
204
|
+
let rec;
|
|
205
|
+
try {
|
|
206
|
+
rec = JSON.parse(line);
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (typeof rec.uuid !== 'string')
|
|
212
|
+
continue;
|
|
213
|
+
const record = { uuid: rec.uuid, lineCount: i + 1 };
|
|
214
|
+
if (typeof rec.timestamp === 'string')
|
|
215
|
+
record.timestamp = rec.timestamp;
|
|
216
|
+
if (rec.type === 'user' && !isSyntheticUserRecord(rec)) {
|
|
217
|
+
// tool_result records are user records too, with no prose — extractText
|
|
218
|
+
// leaves those empty, so only what the user typed gets through.
|
|
219
|
+
const text = extractText(rec.message?.content);
|
|
220
|
+
if (text)
|
|
221
|
+
record.prompt = keepEnds(text);
|
|
222
|
+
}
|
|
223
|
+
records.push(record);
|
|
224
|
+
}
|
|
225
|
+
const transcript = { sessionId, records, mtimeMs: stat.mtimeMs };
|
|
226
|
+
parseCache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, transcript });
|
|
227
|
+
while (parseCache.size > PARSE_CACHE_MAX) {
|
|
228
|
+
parseCache.delete(parseCache.keys().next().value);
|
|
229
|
+
}
|
|
230
|
+
return transcript;
|
|
231
|
+
}
|
|
232
|
+
/** The prompts typed in a transcript, raw and in order — to name a conversation before its tree is built. */
|
|
233
|
+
export function promptsIn(projectPath, sessionId) {
|
|
234
|
+
return readTranscript(projectPath, sessionId)?.records.flatMap((r) => (r.prompt ? [r.prompt] : [])) ?? [];
|
|
235
|
+
}
|
|
236
|
+
// ── Building the tree ────────────────────────────────────────────────────
|
|
237
|
+
/**
|
|
238
|
+
* The node covering what `sessionIds` share from `start` on, with a child per
|
|
239
|
+
* way they part. Every transcript passed in shares its records up to `start`,
|
|
240
|
+
* and — for a child — record `start` too, which is what grouped them.
|
|
241
|
+
*/
|
|
242
|
+
function buildNode(sessionIds, transcripts, start, parent) {
|
|
243
|
+
const recordsOf = (id) => transcripts.get(id).records;
|
|
244
|
+
const base = recordsOf(sessionIds[0]);
|
|
245
|
+
// Run on while every transcript still has the same record.
|
|
246
|
+
let end = Math.min(...sessionIds.map((id) => recordsOf(id).length));
|
|
247
|
+
for (const id of sessionIds.slice(1)) {
|
|
248
|
+
const records = recordsOf(id);
|
|
249
|
+
let i = start;
|
|
250
|
+
while (i < end && records[i].uuid === base[i].uuid)
|
|
251
|
+
i++;
|
|
252
|
+
end = i;
|
|
253
|
+
}
|
|
254
|
+
const node = {
|
|
255
|
+
id: base[end - 1].uuid,
|
|
256
|
+
start,
|
|
257
|
+
end,
|
|
258
|
+
sessionIds,
|
|
259
|
+
endsHere: [],
|
|
260
|
+
prompts: base.slice(start, end).flatMap((r) => (r.prompt ? [r.prompt] : [])),
|
|
261
|
+
children: [],
|
|
262
|
+
parent,
|
|
263
|
+
};
|
|
264
|
+
const ways = new Map();
|
|
265
|
+
for (const id of sessionIds) {
|
|
266
|
+
const records = recordsOf(id);
|
|
267
|
+
if (records.length === end) {
|
|
268
|
+
node.endsHere.push(id);
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const next = records[end].uuid;
|
|
272
|
+
const way = ways.get(next);
|
|
273
|
+
if (way)
|
|
274
|
+
way.push(id);
|
|
275
|
+
else
|
|
276
|
+
ways.set(next, [id]);
|
|
277
|
+
}
|
|
278
|
+
// Branches in the order they were started, so the older a branch, the
|
|
279
|
+
// earlier its letter, and starting a new one doesn't reshuffle the rest.
|
|
280
|
+
const startedAt = (ids) => recordsOf(ids[0])[end].timestamp ?? '';
|
|
281
|
+
node.children = [...ways.values()]
|
|
282
|
+
.sort((a, b) => startedAt(a).localeCompare(startedAt(b)))
|
|
283
|
+
.map((ids) => buildNode(ids, transcripts, end, node));
|
|
284
|
+
// The most recently written copy first, so it is the one a caller reaching
|
|
285
|
+
// for "the" branch at this point gets.
|
|
286
|
+
node.endsHere.sort((a, b) => transcripts.get(b).mtimeMs - transcripts.get(a).mtimeMs);
|
|
287
|
+
return node;
|
|
288
|
+
}
|
|
289
|
+
function buildTree(projectPath, rootId, sessionIds) {
|
|
290
|
+
const transcripts = new Map();
|
|
291
|
+
for (const id of sessionIds) {
|
|
292
|
+
const transcript = readTranscript(projectPath, id);
|
|
293
|
+
// A transcript whose first record moved on since the index was taken is
|
|
294
|
+
// not part of this tree any more; leave it out rather than misplace it.
|
|
295
|
+
if (transcript?.records[0]?.uuid === rootId)
|
|
296
|
+
transcripts.set(id, transcript);
|
|
297
|
+
}
|
|
298
|
+
if (transcripts.size === 0)
|
|
299
|
+
return undefined;
|
|
300
|
+
// Oldest first, so the transcript that starts the root is the original.
|
|
301
|
+
const ordered = [...transcripts.keys()].sort((a, b) => (transcripts.get(a).records[0].timestamp ?? '').localeCompare(transcripts.get(b).records[0].timestamp ?? ''));
|
|
302
|
+
return {
|
|
303
|
+
projectPath,
|
|
304
|
+
rootId,
|
|
305
|
+
root: buildNode(ordered, transcripts, 0),
|
|
306
|
+
lastActiveMs: Math.max(...[...transcripts.values()].map((t) => t.mtimeMs)),
|
|
307
|
+
transcripts,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/** The tree the transcript `sessionId` belongs to — just itself, if it was never forked. */
|
|
311
|
+
export function treeOf(projectPath, sessionId) {
|
|
312
|
+
const rootId = rootOf(sessionJsonlPath(projectPath, sessionId));
|
|
313
|
+
if (!rootId)
|
|
314
|
+
return undefined;
|
|
315
|
+
const members = conversationsIn(projectPath).get(rootId) ?? [sessionId];
|
|
316
|
+
return buildTree(projectPath, rootId, members);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* The tree whose first record's uuid is `rootId` — or starts with it, since a
|
|
320
|
+
* button's callback data has no room for a whole uuid next to a node's. Two
|
|
321
|
+
* roots can share a prefix, so given the point a button is for, it is the
|
|
322
|
+
* tree holding that point that comes back.
|
|
323
|
+
*/
|
|
324
|
+
export function treeByRoot(projectPath, rootId, nodeId) {
|
|
325
|
+
let first;
|
|
326
|
+
for (const [id, members] of conversationsIn(projectPath)) {
|
|
327
|
+
if (!id.startsWith(rootId))
|
|
328
|
+
continue;
|
|
329
|
+
const tree = buildTree(projectPath, id, members);
|
|
330
|
+
if (!tree)
|
|
331
|
+
continue;
|
|
332
|
+
if (!nodeId || nodeById(tree, nodeId))
|
|
333
|
+
return tree;
|
|
334
|
+
first ??= tree;
|
|
335
|
+
}
|
|
336
|
+
return first;
|
|
337
|
+
}
|
|
338
|
+
// ── Walking it ───────────────────────────────────────────────────────────
|
|
339
|
+
/** Every node, parents before children: the order a tree is read and lettered in. */
|
|
340
|
+
export function preorder(tree) {
|
|
341
|
+
const out = [];
|
|
342
|
+
const walk = (node) => {
|
|
343
|
+
out.push(node);
|
|
344
|
+
node.children.forEach(walk);
|
|
345
|
+
};
|
|
346
|
+
walk(tree.root);
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
export function nodeById(tree, id) {
|
|
350
|
+
return preorder(tree).find((node) => node.id === id);
|
|
351
|
+
}
|
|
352
|
+
/** Where `sessionId`'s transcript ends: the node it is carried on from. */
|
|
353
|
+
export function nodeWhereEnds(tree, sessionId) {
|
|
354
|
+
return preorder(tree).find((node) => node.endsHere.includes(sessionId));
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* The points along `sessionId`'s transcript where another branch leaves it —
|
|
358
|
+
* goes its own way from there, or was copied there and ends — in the order the
|
|
359
|
+
* transcript reaches them, each with the line of the transcript it falls on.
|
|
360
|
+
*/
|
|
361
|
+
export function splitsAlong(tree, sessionId) {
|
|
362
|
+
const records = tree.transcripts.get(sessionId)?.records;
|
|
363
|
+
if (!records)
|
|
364
|
+
return [];
|
|
365
|
+
return preorder(tree)
|
|
366
|
+
.filter((node) => node.sessionIds.includes(sessionId))
|
|
367
|
+
.filter((node) => node.endsHere.some((id) => id !== sessionId)
|
|
368
|
+
|| node.children.some((child) => !child.sessionIds.includes(sessionId)))
|
|
369
|
+
.map((node) => ({ node, line: records[node.end - 1].lineCount }));
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* The transcript cut at `node`: everything up to and including its last
|
|
373
|
+
* record, read from one of the transcripts running through it. That is what a
|
|
374
|
+
* branch from this point starts with. Undefined if the file has gone.
|
|
375
|
+
*/
|
|
376
|
+
export function transcriptUpTo(tree, node) {
|
|
377
|
+
for (const sessionId of node.sessionIds) {
|
|
378
|
+
const record = tree.transcripts.get(sessionId)?.records[node.end - 1];
|
|
379
|
+
if (!record || record.uuid !== node.id)
|
|
380
|
+
continue;
|
|
381
|
+
let raw;
|
|
382
|
+
try {
|
|
383
|
+
raw = fs.readFileSync(sessionJsonlPath(tree.projectPath, sessionId), 'utf-8');
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
const lines = raw.split('\n').slice(0, record.lineCount);
|
|
389
|
+
return lines.join('\n') + '\n';
|
|
390
|
+
}
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
//# sourceMappingURL=fork-tree.js.map
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An SDK query kept running after its reply, for the background work it
|
|
3
|
+
* started — see userMessage in agent.ts for why the CLI needs its input held
|
|
4
|
+
* open for that.
|
|
5
|
+
*
|
|
6
|
+
* The reply is delivered when the turn ends; the query then belongs to no
|
|
7
|
+
* turn. Its messages are still read, so a finished task's notification gets a
|
|
8
|
+
* sub-turn whose reply is posted on its own. The chat's next message is pushed
|
|
9
|
+
* into the same query's input rather than starting a second CLI on the same
|
|
10
|
+
* session, which would be told the first one's tasks had ended and would
|
|
11
|
+
* leave them to die with it.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* The prompt stream of a query: messages pushed in, in order, until `end`.
|
|
15
|
+
* The CLI treats the stream's end as the end of its input.
|
|
16
|
+
*/
|
|
17
|
+
export class PromptChannel {
|
|
18
|
+
queue = [];
|
|
19
|
+
wake;
|
|
20
|
+
ended = false;
|
|
21
|
+
constructor(first) {
|
|
22
|
+
this.queue.push(first);
|
|
23
|
+
}
|
|
24
|
+
get isOpen() {
|
|
25
|
+
return !this.ended;
|
|
26
|
+
}
|
|
27
|
+
/** False once the stream has ended: the message would never be read. */
|
|
28
|
+
push(message) {
|
|
29
|
+
if (this.ended)
|
|
30
|
+
return false;
|
|
31
|
+
this.queue.push(message);
|
|
32
|
+
this.wake?.();
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
end() {
|
|
36
|
+
this.ended = true;
|
|
37
|
+
this.wake?.();
|
|
38
|
+
}
|
|
39
|
+
async *[Symbol.asyncIterator]() {
|
|
40
|
+
for (;;) {
|
|
41
|
+
const next = this.queue.shift();
|
|
42
|
+
if (next) {
|
|
43
|
+
yield next;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (this.ended)
|
|
47
|
+
return;
|
|
48
|
+
await new Promise((resolve) => { this.wake = resolve; });
|
|
49
|
+
this.wake = undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* A query's messages, read once and passed to one reader at a time.
|
|
55
|
+
*
|
|
56
|
+
* A turn that joins a held query waits as the next reader; it takes over at
|
|
57
|
+
* the first message `takesOver` accepts (its own prompt starting), and the
|
|
58
|
+
* reader before it — still answering a task notification, say — stops there.
|
|
59
|
+
*/
|
|
60
|
+
export class QueryFeed {
|
|
61
|
+
source;
|
|
62
|
+
closeSource;
|
|
63
|
+
current;
|
|
64
|
+
next;
|
|
65
|
+
started = false;
|
|
66
|
+
finished = false;
|
|
67
|
+
resolveClosed;
|
|
68
|
+
/** Settles once the query's stream has ended. */
|
|
69
|
+
closed = new Promise((resolve) => { this.resolveClosed = resolve; });
|
|
70
|
+
constructor(source, closeSource) {
|
|
71
|
+
this.source = source;
|
|
72
|
+
this.closeSource = closeSource;
|
|
73
|
+
}
|
|
74
|
+
attach(takesOver) {
|
|
75
|
+
const sink = { buffer: [], wake: undefined, done: false, handedOver: false, error: undefined };
|
|
76
|
+
if (this.finished) {
|
|
77
|
+
sink.done = true;
|
|
78
|
+
}
|
|
79
|
+
else if (!this.current) {
|
|
80
|
+
this.current = sink;
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
if (this.next)
|
|
84
|
+
this.finish(this.next.sink);
|
|
85
|
+
this.next = { sink, takesOver: takesOver ?? (() => true) };
|
|
86
|
+
}
|
|
87
|
+
if (!this.started) {
|
|
88
|
+
this.started = true;
|
|
89
|
+
void this.pump();
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
messages: { [Symbol.asyncIterator]: () => this.read(sink) },
|
|
93
|
+
handedOver: () => sink.handedOver,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
async pump() {
|
|
97
|
+
let error;
|
|
98
|
+
try {
|
|
99
|
+
for await (const message of this.source) {
|
|
100
|
+
if (this.next && this.next.takesOver(message))
|
|
101
|
+
this.handOver();
|
|
102
|
+
if (this.current)
|
|
103
|
+
this.deliver(this.current, message);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
error = err;
|
|
108
|
+
}
|
|
109
|
+
this.finished = true;
|
|
110
|
+
if (this.current) {
|
|
111
|
+
this.current.error = error;
|
|
112
|
+
this.finish(this.current);
|
|
113
|
+
}
|
|
114
|
+
if (this.next)
|
|
115
|
+
this.finish(this.next.sink);
|
|
116
|
+
this.resolveClosed();
|
|
117
|
+
}
|
|
118
|
+
handOver() {
|
|
119
|
+
if (this.current) {
|
|
120
|
+
this.current.handedOver = true;
|
|
121
|
+
this.finish(this.current);
|
|
122
|
+
}
|
|
123
|
+
this.current = this.next?.sink;
|
|
124
|
+
this.next = undefined;
|
|
125
|
+
}
|
|
126
|
+
deliver(sink, message) {
|
|
127
|
+
sink.buffer.push(message);
|
|
128
|
+
sink.wake?.();
|
|
129
|
+
}
|
|
130
|
+
finish(sink) {
|
|
131
|
+
sink.done = true;
|
|
132
|
+
sink.wake?.();
|
|
133
|
+
}
|
|
134
|
+
async *read(sink) {
|
|
135
|
+
try {
|
|
136
|
+
for (;;) {
|
|
137
|
+
const message = sink.buffer.shift();
|
|
138
|
+
if (message) {
|
|
139
|
+
yield message;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (sink.done) {
|
|
143
|
+
if (sink.error)
|
|
144
|
+
throw sink.error;
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
await new Promise((resolve) => { sink.wake = resolve; });
|
|
148
|
+
sink.wake = undefined;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
finally {
|
|
152
|
+
// A reader that stops early (an abort) leaves the query to the next
|
|
153
|
+
// one if there is one, and otherwise closes it, as breaking out of the
|
|
154
|
+
// SDK's own iterator does.
|
|
155
|
+
if (!sink.done && this.current === sink) {
|
|
156
|
+
if (this.next)
|
|
157
|
+
this.handOver();
|
|
158
|
+
else
|
|
159
|
+
this.closeSource();
|
|
160
|
+
}
|
|
161
|
+
sink.done = true;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const heldQueries = new Map();
|
|
166
|
+
export function holdQuery(sessionKey, held) {
|
|
167
|
+
heldQueries.set(sessionKey, held);
|
|
168
|
+
void held.feed.closed.then(() => {
|
|
169
|
+
if (heldQueries.get(sessionKey) === held)
|
|
170
|
+
heldQueries.delete(sessionKey);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
/** The held query, no longer held: the caller joins it or lets it go. */
|
|
174
|
+
export function takeHeldQuery(sessionKey) {
|
|
175
|
+
const held = heldQueries.get(sessionKey);
|
|
176
|
+
heldQueries.delete(sessionKey);
|
|
177
|
+
return held;
|
|
178
|
+
}
|
|
179
|
+
export function getHeldQuery(sessionKey) {
|
|
180
|
+
return heldQueries.get(sessionKey);
|
|
181
|
+
}
|
|
182
|
+
/** Ends a held query's input; its tasks stop when the CLI exits. */
|
|
183
|
+
export function releaseHeldQuery(sessionKey) {
|
|
184
|
+
const held = heldQueries.get(sessionKey);
|
|
185
|
+
if (!held || !held.input.isOpen)
|
|
186
|
+
return false;
|
|
187
|
+
held.input.end();
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=held-query.js.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import * as path from 'path';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { ensureStateDir, getStateDir, readJsonFile, writeJsonFile } from '../utils/json-store.js';
|
|
4
|
+
import { BOT_ID } from '../config.js';
|
|
5
|
+
/**
|
|
6
|
+
* Tracks Claude tasks that are currently running per-session, persisted to disk.
|
|
7
|
+
* On a clean finish the marker is cleared. If the bot exits unexpectedly while
|
|
8
|
+
* a task is in flight, the marker survives and startup can notify the chat
|
|
9
|
+
* that the task was interrupted.
|
|
10
|
+
*/
|
|
11
|
+
const inFlightEntrySchema = z.object({
|
|
12
|
+
sessionKey: z.string(),
|
|
13
|
+
messagePreview: z.string(),
|
|
14
|
+
startedAt: z.string(),
|
|
15
|
+
});
|
|
16
|
+
const inFlightFileSchema = z.object({
|
|
17
|
+
entries: z.array(inFlightEntrySchema),
|
|
18
|
+
});
|
|
19
|
+
const HISTORY_DIR = getStateDir();
|
|
20
|
+
function getFile() {
|
|
21
|
+
return path.join(HISTORY_DIR, `in-flight-${BOT_ID}.json`);
|
|
22
|
+
}
|
|
23
|
+
function readAll() {
|
|
24
|
+
return readJsonFile(getFile(), inFlightFileSchema, 'InFlight')?.entries ?? [];
|
|
25
|
+
}
|
|
26
|
+
function writeAll(entries) {
|
|
27
|
+
ensureStateDir(HISTORY_DIR, 'InFlight');
|
|
28
|
+
writeJsonFile(getFile(), { entries }, 'InFlight');
|
|
29
|
+
}
|
|
30
|
+
// Cap stored prompt at 50KB so a long interrupted prompt survives the restart
|
|
31
|
+
// notification flow intact. The restore renderer chunks if it exceeds the
|
|
32
|
+
// 4096-char per-Telegram-message limit.
|
|
33
|
+
const MAX_PROMPT_CHARS = 50_000;
|
|
34
|
+
export function markInFlight(sessionKey, messagePreview) {
|
|
35
|
+
const others = readAll().filter((e) => e.sessionKey !== sessionKey);
|
|
36
|
+
others.push({
|
|
37
|
+
sessionKey,
|
|
38
|
+
messagePreview: messagePreview.slice(0, MAX_PROMPT_CHARS),
|
|
39
|
+
startedAt: new Date().toISOString(),
|
|
40
|
+
});
|
|
41
|
+
writeAll(others);
|
|
42
|
+
}
|
|
43
|
+
/** Whether a turn is running for this session right now. */
|
|
44
|
+
export function isInFlight(sessionKey) {
|
|
45
|
+
return readAll().some((e) => e.sessionKey === sessionKey);
|
|
46
|
+
}
|
|
47
|
+
export function clearInFlight(sessionKey) {
|
|
48
|
+
const all = readAll();
|
|
49
|
+
const filtered = all.filter((e) => e.sessionKey !== sessionKey);
|
|
50
|
+
if (filtered.length !== all.length)
|
|
51
|
+
writeAll(filtered);
|
|
52
|
+
}
|
|
53
|
+
/** Read all entries and clear the file. Used at startup to surface tasks that
|
|
54
|
+
* were interrupted by an unexpected exit. */
|
|
55
|
+
export function consumeAllInFlight() {
|
|
56
|
+
const all = readAll();
|
|
57
|
+
if (all.length > 0)
|
|
58
|
+
writeAll([]);
|
|
59
|
+
return all;
|
|
60
|
+
}
|
|
61
|
+
//# sourceMappingURL=in-flight-tracker.js.map
|