@antondanv/brainyard 0.1.0 → 0.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/CHANGELOG.md +108 -0
- package/README.md +322 -104
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +23 -0
- package/dist/ask.js.map +1 -1
- package/dist/brains/adapter.d.ts +16 -2
- package/dist/brains/adapter.d.ts.map +1 -1
- package/dist/brains/adapter.js.map +1 -1
- package/dist/brains/index.d.ts.map +1 -1
- package/dist/brains/index.js +2 -1
- package/dist/brains/index.js.map +1 -1
- package/dist/brains/info.d.ts.map +1 -1
- package/dist/brains/info.js +22 -0
- package/dist/brains/info.js.map +1 -1
- package/dist/brains/opencode-bridge.d.ts +2 -0
- package/dist/brains/opencode-bridge.d.ts.map +1 -0
- package/dist/brains/opencode-bridge.js +332 -0
- package/dist/brains/opencode-bridge.js.map +1 -0
- package/dist/brains/opencode.d.ts +14 -0
- package/dist/brains/opencode.d.ts.map +1 -0
- package/dist/brains/opencode.js +474 -0
- package/dist/brains/opencode.js.map +1 -0
- package/dist/catalog.d.ts +8 -1
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +100 -1
- package/dist/catalog.js.map +1 -1
- package/dist/codex-live.d.ts +12 -0
- package/dist/codex-live.d.ts.map +1 -0
- package/dist/codex-live.js +188 -0
- package/dist/codex-live.js.map +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -0
- package/dist/errors.js.map +1 -1
- package/dist/flags.d.ts.map +1 -1
- package/dist/flags.js +7 -5
- package/dist/flags.js.map +1 -1
- package/dist/humanize.d.ts.map +1 -1
- package/dist/humanize.js +19 -2
- package/dist/humanize.js.map +1 -1
- package/dist/index.d.ts +8 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -4
- package/dist/index.js.map +1 -1
- package/dist/open.d.ts +87 -0
- package/dist/open.d.ts.map +1 -0
- package/dist/open.js +324 -0
- package/dist/open.js.map +1 -0
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +4 -2
- package/dist/options.js.map +1 -1
- package/dist/panes.d.ts +118 -0
- package/dist/panes.d.ts.map +1 -0
- package/dist/panes.js +478 -0
- package/dist/panes.js.map +1 -0
- package/dist/process.d.ts +26 -0
- package/dist/process.d.ts.map +1 -1
- package/dist/process.js +92 -2
- package/dist/process.js.map +1 -1
- package/dist/run.d.ts +1 -1
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +11 -3
- package/dist/run.js.map +1 -1
- package/dist/sessions.d.ts +137 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/sessions.js +1023 -0
- package/dist/sessions.js.map +1 -0
- package/dist/status.d.ts +1 -1
- package/dist/status.d.ts.map +1 -1
- package/dist/status.js +28 -7
- package/dist/status.js.map +1 -1
- package/dist/subscription-limits.d.ts +12 -0
- package/dist/subscription-limits.d.ts.map +1 -0
- package/dist/subscription-limits.js +281 -0
- package/dist/subscription-limits.js.map +1 -0
- package/dist/types.d.ts +14 -8
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +2 -2
- package/dist/types.js.map +1 -1
- package/dist/usage-readers.d.ts +16 -0
- package/dist/usage-readers.d.ts.map +1 -0
- package/dist/usage-readers.js +194 -0
- package/dist/usage-readers.js.map +1 -0
- package/dist/usage.d.ts +71 -0
- package/dist/usage.d.ts.map +1 -0
- package/dist/usage.js +403 -0
- package/dist/usage.js.map +1 -0
- package/package.json +7 -23
- package/README.ru.md +0 -334
- package/dist/cli/main.d.ts +0 -3
- package/dist/cli/main.d.ts.map +0 -1
- package/dist/cli/main.js +0 -520
- package/dist/cli/main.js.map +0 -1
- package/dist/cli/term.d.ts +0 -20
- package/dist/cli/term.d.ts.map +0 -1
- package/dist/cli/term.js +0 -87
- package/dist/cli/term.js.map +0 -1
- package/dist/ui/dashboard.html +0 -693
- package/dist/ui/page.d.ts +0 -9
- package/dist/ui/page.d.ts.map +0 -1
- package/dist/ui/page.js +0 -12
- package/dist/ui/page.js.map +0 -1
- package/dist/ui/server.d.ts +0 -20
- package/dist/ui/server.d.ts.map +0 -1
- package/dist/ui/server.js +0 -409
- package/dist/ui/server.js.map +0 -1
package/dist/sessions.js
ADDED
|
@@ -0,0 +1,1023 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sessions a person comes back to, read from each CLI's own store.
|
|
3
|
+
*
|
|
4
|
+
* Runs started by Brainyard are headless, and Claude Code keeps headless
|
|
5
|
+
* sessions out of its `/resume` picker. The sessions a person works in —
|
|
6
|
+
* terminal, IDE, background — live in four stores with four formats:
|
|
7
|
+
*
|
|
8
|
+
* - Claude Code: `~/.claude/projects/<folder>/<session-id>.jsonl`, where the
|
|
9
|
+
* folder is the working directory with every non-alphanumeric character
|
|
10
|
+
* turned into `-`. A name you gave the session is a `custom-title` entry, the
|
|
11
|
+
* generated one an `ai-title`; `entrypoint: sdk-*` marks a headless run.
|
|
12
|
+
* - Codex: `~/.codex/sessions/YYYY/MM/DD/rollout-…-<id>.jsonl`. The first line
|
|
13
|
+
* is `session_meta` with `cwd` and `source` (`exec` is headless); thread
|
|
14
|
+
* names are in `~/.codex/session_index.jsonl`.
|
|
15
|
+
* - Antigravity: `~/.gemini/antigravity-cli/conversation_summaries.db`
|
|
16
|
+
* (SQLite: title, workspace, status), or `history.jsonl` — one line per
|
|
17
|
+
* prompt with `workspace` and `conversationId` — where `node:sqlite` is
|
|
18
|
+
* missing. Interactive conversations of agy 1.2 leave the workspace empty
|
|
19
|
+
* and the history unwritten; their folder is in the CLI's own log,
|
|
20
|
+
* `log/cli-*.log`, one file per run.
|
|
21
|
+
* - OpenCode: `~/.local/share/opencode/opencode.db` (SQLite), shared with its
|
|
22
|
+
* desktop app: a `session` row per conversation with its folder and title.
|
|
23
|
+
* Subagents have a parent; `opencode run` gives its sessions rules that keep
|
|
24
|
+
* questions out, the TUI none. Until a title is generated it reads
|
|
25
|
+
* `New session - <time>`, and the first prompt says more.
|
|
26
|
+
*
|
|
27
|
+
* None of these is a public API. Every reader skips what it does not
|
|
28
|
+
* understand instead of failing, and a store that is not there is an empty
|
|
29
|
+
* list, not an error.
|
|
30
|
+
*/
|
|
31
|
+
import { closeSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from 'node:fs';
|
|
32
|
+
import { homedir } from 'node:os';
|
|
33
|
+
import { basename, join, resolve } from 'node:path';
|
|
34
|
+
import { BRAINS } from './brains/info.js';
|
|
35
|
+
import { codexPaneStates, codexRolloutState } from './codex-live.js';
|
|
36
|
+
import { BrainyardError } from './errors.js';
|
|
37
|
+
import { oneLine } from './humanize.js';
|
|
38
|
+
import { resolveBrain } from './options.js';
|
|
39
|
+
import { capture, resolveCommand, withoutSessionVars } from './process.js';
|
|
40
|
+
import { BRAIN_IDS } from './types.js';
|
|
41
|
+
/** Where Claude Code keeps its data: `CLAUDE_CONFIG_DIR` or `~/.claude`. */
|
|
42
|
+
export function claudeHome(env = process.env) {
|
|
43
|
+
return env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude');
|
|
44
|
+
}
|
|
45
|
+
/** Where Codex keeps its data: `CODEX_HOME` or `~/.codex`. */
|
|
46
|
+
export function codexHome(env = process.env) {
|
|
47
|
+
return env.CODEX_HOME?.trim() || join(homedir(), '.codex');
|
|
48
|
+
}
|
|
49
|
+
/** Where the Antigravity CLI keeps its conversations. */
|
|
50
|
+
export function agyHome() {
|
|
51
|
+
return join(homedir(), '.gemini', 'antigravity-cli');
|
|
52
|
+
}
|
|
53
|
+
/** Where OpenCode keeps its data: `$XDG_DATA_HOME/opencode` or `~/.local/share/opencode`, on macOS too. */
|
|
54
|
+
export function opencodeHome(env = process.env) {
|
|
55
|
+
return join(env.XDG_DATA_HOME?.trim() || join(homedir(), '.local', 'share'), 'opencode');
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Claude Code's folder name for a working directory. Names over 200
|
|
59
|
+
* characters get a hash appended that is not reproduced here; those are
|
|
60
|
+
* matched by prefix.
|
|
61
|
+
*/
|
|
62
|
+
export function claudeProjectDir(cwd) {
|
|
63
|
+
return cwd.replace(/[^a-zA-Z0-9]/g, '-');
|
|
64
|
+
}
|
|
65
|
+
/** Saved sessions of a folder across the CLIs, newest first. */
|
|
66
|
+
export async function sessions(options = {}) {
|
|
67
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
68
|
+
const places = pathVariants(cwd);
|
|
69
|
+
const brains = [...new Set((options.brains ?? BRAIN_IDS).map((brain) => resolveBrain(String(brain))))];
|
|
70
|
+
const limit = options.limit ?? 200;
|
|
71
|
+
const env = options.env ?? process.env;
|
|
72
|
+
const homes = options.homes ?? {};
|
|
73
|
+
let found = [];
|
|
74
|
+
for (const brain of brains) {
|
|
75
|
+
let list;
|
|
76
|
+
if (brain === 'claude')
|
|
77
|
+
list = claudeSessions(homes.claude ?? claudeHome(env), places);
|
|
78
|
+
else if (brain === 'codex')
|
|
79
|
+
list = codexSessions(homes.codex ?? codexHome(env), places);
|
|
80
|
+
else if (brain === 'opencode')
|
|
81
|
+
list = await opencodeSessions(homes.opencode ?? opencodeHome(env), places);
|
|
82
|
+
else
|
|
83
|
+
list = await agySessions(homes.antigravity ?? agyHome(), places);
|
|
84
|
+
if (!options.headless)
|
|
85
|
+
list = list.filter((session) => session.interactive);
|
|
86
|
+
found.push(...newestFirst(list).slice(0, limit));
|
|
87
|
+
}
|
|
88
|
+
if (options.live !== false) {
|
|
89
|
+
const live = await liveSessions({
|
|
90
|
+
cwd,
|
|
91
|
+
brains,
|
|
92
|
+
...(options.command ? { command: options.command } : {}),
|
|
93
|
+
env,
|
|
94
|
+
...(options.homes ? { homes: options.homes } : {}),
|
|
95
|
+
});
|
|
96
|
+
// A headless run that is working right now is still not a session to come back to.
|
|
97
|
+
found = mergeLive(found, live.filter((session) => options.headless || session.interactive));
|
|
98
|
+
}
|
|
99
|
+
return newestFirst(found);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Sessions running on this machine and what they are doing, in every CLI.
|
|
103
|
+
* Each tells it differently:
|
|
104
|
+
*
|
|
105
|
+
* - Claude Code says it outright: `claude agents --json` lists interactive
|
|
106
|
+
* and background sessions with `busy`, `waiting` (and why) or `idle`.
|
|
107
|
+
* - Codex writes a turn into its rollout as it goes and closes it with
|
|
108
|
+
* `task_complete`: a turn still open is work in progress; unanswered
|
|
109
|
+
* requests mean it waits for you. `panes` also checks native approval dialogs.
|
|
110
|
+
* - Antigravity keeps a status per conversation in its summaries database.
|
|
111
|
+
* - OpenCode writes an answer into its database as it goes and marks it
|
|
112
|
+
* completed at the end: an answer still open is work in progress. Waiting
|
|
113
|
+
* for a permission is not stored.
|
|
114
|
+
*
|
|
115
|
+
* A CLI that is not installed, or a store that is not there, adds nothing.
|
|
116
|
+
*/
|
|
117
|
+
export async function liveSessions(options = {}) {
|
|
118
|
+
const env = options.env ?? process.env;
|
|
119
|
+
const brains = new Set((options.brains ?? BRAIN_IDS).map((brain) => resolveBrain(String(brain))));
|
|
120
|
+
const places = options.cwd ? pathVariants(resolve(options.cwd)) : undefined;
|
|
121
|
+
const homes = options.homes ?? {};
|
|
122
|
+
const [claude, codex, agy, opencode] = await Promise.all([
|
|
123
|
+
brains.has('claude') ? claudeLive(options, env) : [],
|
|
124
|
+
brains.has('codex') ? codexLive(homes.codex ?? codexHome(env)) : [],
|
|
125
|
+
brains.has('antigravity') ? agyLive(homes.antigravity ?? agyHome()) : [],
|
|
126
|
+
brains.has('opencode') ? opencodeLive(homes.opencode ?? opencodeHome(env)) : [],
|
|
127
|
+
]);
|
|
128
|
+
const codexStates = brains.has('codex') && options.panes
|
|
129
|
+
? await codexPaneStates(codex, { ...options.panes, env: { ...env, ...options.panes.env } })
|
|
130
|
+
: codex;
|
|
131
|
+
return [...claude, ...codexStates, ...agy, ...opencode].filter((session) => !places || (session.cwd !== undefined && places.has(session.cwd)));
|
|
132
|
+
}
|
|
133
|
+
/** Stops a Claude Code background session through its CLI, keeping its conversation resumable. */
|
|
134
|
+
export async function stopSession(options) {
|
|
135
|
+
const brain = resolveBrain(options.brain);
|
|
136
|
+
if (brain !== 'claude') {
|
|
137
|
+
throw new BrainyardError('invalid_option', 'only Claude Code has background sessions to stop', { brain });
|
|
138
|
+
}
|
|
139
|
+
const env = withoutSessionVars({ ...process.env, ...options.env });
|
|
140
|
+
// Refresh the full-id to short-id mapping; a remembered PID is not a session identity.
|
|
141
|
+
const list = await claudeLive(options, env, true);
|
|
142
|
+
const session = list.find((candidate) => candidate.id === options.sessionId);
|
|
143
|
+
if (!session)
|
|
144
|
+
return 'not-running';
|
|
145
|
+
if (session.live?.kind !== 'background') {
|
|
146
|
+
throw new BrainyardError('invalid_option', 'this session is open in another terminal, not in the background', {
|
|
147
|
+
brain,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
151
|
+
if (!session.cwd || !pathVariants(cwd).has(session.cwd)) {
|
|
152
|
+
throw new BrainyardError('invalid_option', 'the background session belongs to another folder', { brain });
|
|
153
|
+
}
|
|
154
|
+
const shortId = session.live.shortId;
|
|
155
|
+
if (!shortId || !/^[0-9a-f]{6,}$/i.test(shortId)) {
|
|
156
|
+
throw new BrainyardError('failed', "Claude Code did not report the background session's short id", { brain });
|
|
157
|
+
}
|
|
158
|
+
const command = resolveCommand(options.command, BRAINS.claude.binary, BRAINS.claude.envVar, env);
|
|
159
|
+
const got = await capture(command, ['stop', shortId], { cwd, env, timeoutMs: 15_000 });
|
|
160
|
+
if (got.code !== 0 || got.timedOut || got.error) {
|
|
161
|
+
throw new BrainyardError(got.error ? 'not_installed' : 'failed', got.timedOut
|
|
162
|
+
? 'Claude Code timed out stopping the background session'
|
|
163
|
+
: got.stderr.trim() || got.stdout.trim() || got.error?.message || 'Claude Code did not stop the session', { brain });
|
|
164
|
+
}
|
|
165
|
+
return 'stopped';
|
|
166
|
+
}
|
|
167
|
+
async function claudeLive(options, env, strict = false) {
|
|
168
|
+
const failed = (kind, message) => {
|
|
169
|
+
if (strict)
|
|
170
|
+
throw new BrainyardError(kind, message, { brain: 'claude' });
|
|
171
|
+
return [];
|
|
172
|
+
};
|
|
173
|
+
const command = resolveCommand(options.command, BRAINS.claude.binary, BRAINS.claude.envVar, env);
|
|
174
|
+
if (!command)
|
|
175
|
+
return failed('not_installed', 'Claude Code is not installed');
|
|
176
|
+
const args = ['agents', '--json'];
|
|
177
|
+
if (options.all)
|
|
178
|
+
args.push('--all');
|
|
179
|
+
const got = await capture(command, args, { timeoutMs: 10_000, env });
|
|
180
|
+
if (got.code !== 0 || got.timedOut || got.error) {
|
|
181
|
+
return failed('failed', got.stderr.trim() || got.error?.message || 'Claude Code could not list live sessions');
|
|
182
|
+
}
|
|
183
|
+
let rows;
|
|
184
|
+
try {
|
|
185
|
+
rows = JSON.parse(got.stdout);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return failed('failed', 'Claude Code returned invalid live-session JSON');
|
|
189
|
+
}
|
|
190
|
+
if (!Array.isArray(rows))
|
|
191
|
+
return failed('failed', 'Claude Code returned an invalid live-session list');
|
|
192
|
+
const out = [];
|
|
193
|
+
for (const row of rows) {
|
|
194
|
+
const session = liveRow(row);
|
|
195
|
+
if (session)
|
|
196
|
+
out.push(session);
|
|
197
|
+
}
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
/** A Codex turn with no write for this long is not running: the CLI was closed or killed mid-turn. */
|
|
201
|
+
const CODEX_STALE_MS = 10 * 60 * 1000;
|
|
202
|
+
function codexLive(home) {
|
|
203
|
+
const now = Date.now();
|
|
204
|
+
const out = [];
|
|
205
|
+
// Only today's and yesterday's folders can hold a turn that is still open.
|
|
206
|
+
for (const path of rolloutFiles(join(home, 'sessions')).slice(0, 400)) {
|
|
207
|
+
let mtime;
|
|
208
|
+
try {
|
|
209
|
+
mtime = statSync(path).mtimeMs;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (now - mtime > CODEX_STALE_MS)
|
|
215
|
+
continue;
|
|
216
|
+
const meta = firstLine(path);
|
|
217
|
+
if (meta?.type !== 'session_meta')
|
|
218
|
+
continue;
|
|
219
|
+
const payload = record(meta.payload);
|
|
220
|
+
if (payload.thread_source === 'subagent' || 'subagent' in record(payload.source))
|
|
221
|
+
continue;
|
|
222
|
+
const id = text(payload.id) || text(payload.session_id);
|
|
223
|
+
if (!id)
|
|
224
|
+
continue;
|
|
225
|
+
const state = codexRolloutState(path);
|
|
226
|
+
if (!state)
|
|
227
|
+
continue;
|
|
228
|
+
const session = {
|
|
229
|
+
brain: 'codex',
|
|
230
|
+
id,
|
|
231
|
+
interactive: text(payload.source) !== 'exec',
|
|
232
|
+
updatedAt: new Date(mtime).toISOString(),
|
|
233
|
+
live: { ...state, kind: 'interactive' },
|
|
234
|
+
};
|
|
235
|
+
if (text(payload.cwd))
|
|
236
|
+
session.cwd = text(payload.cwd);
|
|
237
|
+
out.push(session);
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
async function agyLive(home) {
|
|
242
|
+
const path = join(home, 'conversation_summaries.db');
|
|
243
|
+
try {
|
|
244
|
+
statSync(path);
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
return [];
|
|
248
|
+
}
|
|
249
|
+
const open = await openSqlite();
|
|
250
|
+
if (!open)
|
|
251
|
+
return [];
|
|
252
|
+
let db;
|
|
253
|
+
try {
|
|
254
|
+
db = open(path);
|
|
255
|
+
const rows = db
|
|
256
|
+
.prepare('SELECT conversation_id, title, workspace_uris, status, not_fully_idle, killed, last_modified_time ' +
|
|
257
|
+
"FROM conversation_summaries WHERE last_modified_time > datetime('now', '-1 day')")
|
|
258
|
+
.all();
|
|
259
|
+
const out = [];
|
|
260
|
+
for (const row of rows) {
|
|
261
|
+
const r = record(row);
|
|
262
|
+
const id = text(r.conversation_id);
|
|
263
|
+
if (!id || Number(r.killed) === 1)
|
|
264
|
+
continue;
|
|
265
|
+
const status = text(r.status).toUpperCase();
|
|
266
|
+
let state;
|
|
267
|
+
if (/WAIT|INPUT|APPROV|CONFIRM|PAUSE/.test(status))
|
|
268
|
+
state = 'waiting';
|
|
269
|
+
else if (/RUNNING|PROGRESS|BUSY|ACTIVE/.test(status) || Number(r.not_fully_idle) === 1)
|
|
270
|
+
state = 'busy';
|
|
271
|
+
if (!state)
|
|
272
|
+
continue;
|
|
273
|
+
const session = {
|
|
274
|
+
brain: 'antigravity',
|
|
275
|
+
id,
|
|
276
|
+
interactive: true,
|
|
277
|
+
live: { status: state, kind: 'interactive' },
|
|
278
|
+
};
|
|
279
|
+
const cwd = workspaces(text(r.workspace_uris))[0] ?? agyLogWorkspaces(join(home, 'log')).get(id)?.[0];
|
|
280
|
+
if (cwd)
|
|
281
|
+
session.cwd = cwd;
|
|
282
|
+
if (text(r.title)) {
|
|
283
|
+
session.title = text(r.title);
|
|
284
|
+
session.titleSource = 'generated';
|
|
285
|
+
}
|
|
286
|
+
const updated = isoFromSql(text(r.last_modified_time));
|
|
287
|
+
if (updated)
|
|
288
|
+
session.updatedAt = updated;
|
|
289
|
+
out.push(session);
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
return [];
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
db?.close();
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function liveRow(row) {
|
|
301
|
+
const r = record(row);
|
|
302
|
+
const id = text(r.sessionId);
|
|
303
|
+
if (!id)
|
|
304
|
+
return undefined;
|
|
305
|
+
const kind = text(r.kind) || 'interactive';
|
|
306
|
+
const live = { status: text(r.status) || 'idle', kind };
|
|
307
|
+
if (text(r.waitingFor))
|
|
308
|
+
live.waitingFor = text(r.waitingFor);
|
|
309
|
+
if (typeof r.pid === 'number')
|
|
310
|
+
live.pid = r.pid;
|
|
311
|
+
if (text(r.id))
|
|
312
|
+
live.shortId = text(r.id);
|
|
313
|
+
if (text(r.state))
|
|
314
|
+
live.state = text(r.state);
|
|
315
|
+
const session = { brain: 'claude', id, interactive: true, live };
|
|
316
|
+
const cwd = text(r.cwd);
|
|
317
|
+
if (cwd)
|
|
318
|
+
session.cwd = cwd;
|
|
319
|
+
const name = text(r.name);
|
|
320
|
+
if (name && !isDefaultLabel(name, cwd)) {
|
|
321
|
+
session.title = name;
|
|
322
|
+
session.titleSource = 'name';
|
|
323
|
+
}
|
|
324
|
+
const started = isoFromMs(r.startedAt);
|
|
325
|
+
if (started)
|
|
326
|
+
session.startedAt = started;
|
|
327
|
+
if (kind === 'background')
|
|
328
|
+
session.background = true;
|
|
329
|
+
return session;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Claude Code labels an unnamed session with its folder and two characters
|
|
333
|
+
* (`factoyard-3f`) in listings of running sessions. That label is not a
|
|
334
|
+
* title, and it is not something `--resume` accepts.
|
|
335
|
+
*/
|
|
336
|
+
function isDefaultLabel(name, cwd) {
|
|
337
|
+
const folder = basename(cwd)
|
|
338
|
+
.toLowerCase()
|
|
339
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
340
|
+
.replace(/^-|-$/g, '');
|
|
341
|
+
return new RegExp(`^${folder.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-[0-9a-z]{2}$`).test(name);
|
|
342
|
+
}
|
|
343
|
+
/** Stored sessions with the live state of the running ones; running sessions not on disk yet are added. */
|
|
344
|
+
function mergeLive(stored, live) {
|
|
345
|
+
const byId = new Map(live.map((session) => [session.id, session]));
|
|
346
|
+
const out = stored.map((session) => {
|
|
347
|
+
const now = byId.get(session.id);
|
|
348
|
+
if (!now)
|
|
349
|
+
return session;
|
|
350
|
+
byId.delete(session.id);
|
|
351
|
+
const merged = { ...session };
|
|
352
|
+
if (now.live)
|
|
353
|
+
merged.live = now.live;
|
|
354
|
+
if (now.background)
|
|
355
|
+
merged.background = true;
|
|
356
|
+
// A stored name wins over a default display name.
|
|
357
|
+
if (!merged.title && now.title) {
|
|
358
|
+
merged.title = now.title;
|
|
359
|
+
merged.titleSource = 'name';
|
|
360
|
+
}
|
|
361
|
+
return merged;
|
|
362
|
+
});
|
|
363
|
+
return [...out, ...byId.values()];
|
|
364
|
+
}
|
|
365
|
+
// ── Claude Code ─────────────────────────────────────────────────────────────
|
|
366
|
+
const HEAD_BYTES = 96 * 1024;
|
|
367
|
+
const TAIL_BYTES = 256 * 1024;
|
|
368
|
+
function claudeSessions(home, places) {
|
|
369
|
+
return claudeSessionFiles(home, places).flatMap((path) => {
|
|
370
|
+
const session = claudeTranscript(path);
|
|
371
|
+
return session ? [session] : [];
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
/** @internal Shared discovery; usage readers need the whole transcript. */
|
|
375
|
+
export function claudeSessionFiles(home, places) {
|
|
376
|
+
const root = join(home, 'projects');
|
|
377
|
+
const dirs = new Set();
|
|
378
|
+
for (const place of places) {
|
|
379
|
+
const name = claudeProjectDir(place);
|
|
380
|
+
if (name.length <= 200)
|
|
381
|
+
dirs.add(join(root, name));
|
|
382
|
+
else
|
|
383
|
+
for (const entry of listDir(root))
|
|
384
|
+
if (entry.startsWith(name.slice(0, 200)))
|
|
385
|
+
dirs.add(join(root, entry));
|
|
386
|
+
}
|
|
387
|
+
const out = [];
|
|
388
|
+
for (const dir of dirs) {
|
|
389
|
+
for (const file of listDir(dir)) {
|
|
390
|
+
if (!file.endsWith('.jsonl'))
|
|
391
|
+
continue;
|
|
392
|
+
out.push(join(dir, file));
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return out;
|
|
396
|
+
}
|
|
397
|
+
/** One transcript → a session, or undefined when it holds no conversation. */
|
|
398
|
+
export function claudeTranscript(path) {
|
|
399
|
+
const id = basename(path, '.jsonl');
|
|
400
|
+
let size;
|
|
401
|
+
let mtime;
|
|
402
|
+
try {
|
|
403
|
+
const stat = statSync(path);
|
|
404
|
+
size = stat.size;
|
|
405
|
+
mtime = stat.mtime;
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
return undefined;
|
|
409
|
+
}
|
|
410
|
+
// The first user message is near the start, the latest title near the end;
|
|
411
|
+
// transcripts run to many megabytes, so only those two ends are read.
|
|
412
|
+
const head = jsonLines(readRange(path, 0, Math.min(size, HEAD_BYTES)), false);
|
|
413
|
+
const tail = size > HEAD_BYTES ? jsonLines(readRange(path, Math.max(0, size - TAIL_BYTES), TAIL_BYTES), true) : [];
|
|
414
|
+
const entries = [...head, ...tail];
|
|
415
|
+
let first;
|
|
416
|
+
for (const entry of head) {
|
|
417
|
+
if (entry.type === 'user' && userText(entry) !== undefined) {
|
|
418
|
+
first = entry;
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (!first && !entries.some((entry) => entry.type === 'user' || entry.type === 'assistant'))
|
|
423
|
+
return undefined;
|
|
424
|
+
let name;
|
|
425
|
+
let generated;
|
|
426
|
+
let background = false;
|
|
427
|
+
let entrypoint = first ? text(first.entrypoint) : '';
|
|
428
|
+
let cwd = first ? text(first.cwd) : '';
|
|
429
|
+
for (const entry of entries) {
|
|
430
|
+
if (entry.type === 'custom-title' && text(entry.customTitle))
|
|
431
|
+
name = text(entry.customTitle);
|
|
432
|
+
else if (entry.type === 'ai-title' && text(entry.aiTitle))
|
|
433
|
+
generated = text(entry.aiTitle);
|
|
434
|
+
if (entry.sessionKind === 'bg')
|
|
435
|
+
background = true;
|
|
436
|
+
if (!entrypoint && text(entry.entrypoint))
|
|
437
|
+
entrypoint = text(entry.entrypoint);
|
|
438
|
+
if (!cwd && text(entry.cwd))
|
|
439
|
+
cwd = text(entry.cwd);
|
|
440
|
+
}
|
|
441
|
+
const session = {
|
|
442
|
+
brain: 'claude',
|
|
443
|
+
id,
|
|
444
|
+
updatedAt: mtime.toISOString(),
|
|
445
|
+
// The Agent SDK and `claude -p` say `sdk-cli`, `sdk-ts`, `sdk-py`; the
|
|
446
|
+
// terminal says `cli`, the IDE extensions `claude-vscode` and the like.
|
|
447
|
+
interactive: !entrypoint.startsWith('sdk'),
|
|
448
|
+
};
|
|
449
|
+
if (cwd)
|
|
450
|
+
session.cwd = cwd;
|
|
451
|
+
const started = first ? text(first.timestamp) : '';
|
|
452
|
+
if (started)
|
|
453
|
+
session.startedAt = started;
|
|
454
|
+
if (background)
|
|
455
|
+
session.background = true;
|
|
456
|
+
const prompt = first ? userText(first) : undefined;
|
|
457
|
+
if (name) {
|
|
458
|
+
session.title = name;
|
|
459
|
+
session.titleSource = 'name';
|
|
460
|
+
}
|
|
461
|
+
else if (generated) {
|
|
462
|
+
session.title = generated;
|
|
463
|
+
session.titleSource = 'generated';
|
|
464
|
+
}
|
|
465
|
+
else if (prompt) {
|
|
466
|
+
session.title = oneLine(prompt).slice(0, 120);
|
|
467
|
+
session.titleSource = 'prompt';
|
|
468
|
+
}
|
|
469
|
+
return session;
|
|
470
|
+
}
|
|
471
|
+
/** Text of a user message, skipping the wrappers Claude Code adds (`<command-name>`, reminders, tool results). */
|
|
472
|
+
function userText(entry) {
|
|
473
|
+
const message = record(entry.message);
|
|
474
|
+
const content = message.content;
|
|
475
|
+
let value;
|
|
476
|
+
if (typeof content === 'string')
|
|
477
|
+
value = content;
|
|
478
|
+
else if (Array.isArray(content)) {
|
|
479
|
+
for (const part of content) {
|
|
480
|
+
const block = record(part);
|
|
481
|
+
if (block.type === 'text' && typeof block.text === 'string') {
|
|
482
|
+
value = block.text;
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
if (value === undefined)
|
|
488
|
+
return undefined;
|
|
489
|
+
const clean = value.trim();
|
|
490
|
+
if (!clean || clean.startsWith('<'))
|
|
491
|
+
return undefined;
|
|
492
|
+
return clean;
|
|
493
|
+
}
|
|
494
|
+
// ── Codex ───────────────────────────────────────────────────────────────────
|
|
495
|
+
function codexSessions(home, places) {
|
|
496
|
+
const names = codexNames(join(home, 'session_index.jsonl'));
|
|
497
|
+
const out = [];
|
|
498
|
+
for (const path of rolloutFiles(join(home, 'sessions'))) {
|
|
499
|
+
// `session_meta` carries the whole base prompt, tens of kilobytes; `cwd`
|
|
500
|
+
// comes before it, so a short read decides whether the file is ours.
|
|
501
|
+
const start = readRange(path, 0, 4096);
|
|
502
|
+
const where = /"cwd":"((?:[^"\\]|\\.)*)"/.exec(start);
|
|
503
|
+
if (!where?.[1])
|
|
504
|
+
continue;
|
|
505
|
+
let cwd;
|
|
506
|
+
try {
|
|
507
|
+
cwd = JSON.parse(`"${where[1]}"`);
|
|
508
|
+
}
|
|
509
|
+
catch {
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (!places.has(cwd))
|
|
513
|
+
continue;
|
|
514
|
+
const meta = firstLine(path);
|
|
515
|
+
if (meta?.type !== 'session_meta')
|
|
516
|
+
continue;
|
|
517
|
+
const payload = record(meta.payload);
|
|
518
|
+
const id = text(payload.id) || text(payload.session_id);
|
|
519
|
+
if (!id)
|
|
520
|
+
continue;
|
|
521
|
+
// Threads Codex spawns for itself (a guardian review of an approval, a
|
|
522
|
+
// sub-agent) are not anyone's session, and they start after the one that
|
|
523
|
+
// spawned them — skipped, or they would pass for the newest session.
|
|
524
|
+
if (payload.thread_source === 'subagent' || 'subagent' in record(payload.source))
|
|
525
|
+
continue;
|
|
526
|
+
const source = text(payload.source);
|
|
527
|
+
const session = {
|
|
528
|
+
brain: 'codex',
|
|
529
|
+
id,
|
|
530
|
+
cwd,
|
|
531
|
+
interactive: source !== 'exec' && text(payload.originator) !== 'codex_exec',
|
|
532
|
+
};
|
|
533
|
+
const started = text(payload.timestamp) || text(meta.timestamp);
|
|
534
|
+
if (started)
|
|
535
|
+
session.startedAt = started;
|
|
536
|
+
try {
|
|
537
|
+
session.updatedAt = statSync(path).mtime.toISOString();
|
|
538
|
+
}
|
|
539
|
+
catch {
|
|
540
|
+
// Gone between listing and reading.
|
|
541
|
+
}
|
|
542
|
+
const name = names.get(id);
|
|
543
|
+
if (name) {
|
|
544
|
+
session.title = name;
|
|
545
|
+
session.titleSource = 'generated';
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
const prompt = codexFirstPrompt(path);
|
|
549
|
+
if (prompt) {
|
|
550
|
+
session.title = oneLine(prompt).slice(0, 120);
|
|
551
|
+
session.titleSource = 'prompt';
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
out.push(session);
|
|
555
|
+
}
|
|
556
|
+
return out;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* The first thing the person typed. Codex opens a thread with its own
|
|
560
|
+
* context as user messages too (`<environment_context>`, plugin lists,
|
|
561
|
+
* AGENTS.md), so the first message that is not wrapped in a tag is the one.
|
|
562
|
+
*/
|
|
563
|
+
function codexFirstPrompt(path) {
|
|
564
|
+
for (const entry of jsonLines(readRange(path, 0, HEAD_BYTES * 3), false)) {
|
|
565
|
+
const payload = record(entry.payload);
|
|
566
|
+
let value;
|
|
567
|
+
if (entry.type === 'event_msg' && payload.type === 'user_message')
|
|
568
|
+
value = text(payload.message);
|
|
569
|
+
else if (entry.type === 'response_item' && payload.type === 'message' && payload.role === 'user') {
|
|
570
|
+
for (const part of Array.isArray(payload.content) ? payload.content : []) {
|
|
571
|
+
const block = record(part);
|
|
572
|
+
if (block.type === 'input_text' && text(block.text)) {
|
|
573
|
+
value = text(block.text);
|
|
574
|
+
break;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const clean = value?.trim();
|
|
579
|
+
if (clean && !clean.startsWith('<') && !clean.startsWith('# AGENTS.md'))
|
|
580
|
+
return clean;
|
|
581
|
+
}
|
|
582
|
+
return undefined;
|
|
583
|
+
}
|
|
584
|
+
function codexNames(path) {
|
|
585
|
+
const names = new Map();
|
|
586
|
+
for (const entry of jsonLines(readText(path), false)) {
|
|
587
|
+
const id = text(entry.id);
|
|
588
|
+
const name = text(entry.thread_name);
|
|
589
|
+
if (id && name)
|
|
590
|
+
names.set(id, name);
|
|
591
|
+
}
|
|
592
|
+
return names;
|
|
593
|
+
}
|
|
594
|
+
/** `sessions/YYYY/MM/DD/rollout-*.jsonl`, newest day first. */
|
|
595
|
+
export function rolloutFiles(root) {
|
|
596
|
+
const files = [];
|
|
597
|
+
const walk = (dir, depth) => {
|
|
598
|
+
const entries = listDir(dir).sort().reverse();
|
|
599
|
+
for (const entry of entries) {
|
|
600
|
+
const path = join(dir, entry);
|
|
601
|
+
if (depth < 3)
|
|
602
|
+
walk(path, depth + 1);
|
|
603
|
+
else if (entry.startsWith('rollout-') && entry.endsWith('.jsonl'))
|
|
604
|
+
files.push(path);
|
|
605
|
+
}
|
|
606
|
+
};
|
|
607
|
+
walk(root, 0);
|
|
608
|
+
return files;
|
|
609
|
+
}
|
|
610
|
+
// ── Antigravity ─────────────────────────────────────────────────────────────
|
|
611
|
+
async function agySessions(home, places) {
|
|
612
|
+
const fromHistory = agyFromHistory(join(home, 'history.jsonl'), places);
|
|
613
|
+
const fromDb = await agyFromDatabase(join(home, 'conversation_summaries.db'), places, () => agyLogWorkspaces(join(home, 'log')));
|
|
614
|
+
if (!fromDb)
|
|
615
|
+
return fromHistory;
|
|
616
|
+
// The database knows titles and times, but a conversation can sit there
|
|
617
|
+
// with an empty title; the history still has what was typed first.
|
|
618
|
+
const prompts = new Map(fromHistory.map((session) => [session.id, session]));
|
|
619
|
+
for (const session of fromDb) {
|
|
620
|
+
const typed = prompts.get(session.id);
|
|
621
|
+
if (!session.title && typed?.title) {
|
|
622
|
+
session.title = typed.title;
|
|
623
|
+
session.titleSource = 'prompt';
|
|
624
|
+
}
|
|
625
|
+
if (typed?.startedAt && (!session.startedAt || typed.startedAt < session.startedAt)) {
|
|
626
|
+
session.startedAt = typed.startedAt;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const known = new Set(fromDb.map((session) => session.id));
|
|
630
|
+
return [...fromDb, ...fromHistory.filter((session) => !known.has(session.id))];
|
|
631
|
+
}
|
|
632
|
+
let sqlite;
|
|
633
|
+
/** `node:sqlite` where this Node has it, quietly: Node 22 announces it as experimental on stderr. */
|
|
634
|
+
export function openSqlite() {
|
|
635
|
+
sqlite ??= (async () => {
|
|
636
|
+
const emit = process.emitWarning;
|
|
637
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
638
|
+
const message = typeof warning === 'string' ? warning : warning.message;
|
|
639
|
+
if (/sqlite/i.test(message))
|
|
640
|
+
return;
|
|
641
|
+
emit.call(process, warning, ...rest);
|
|
642
|
+
});
|
|
643
|
+
try {
|
|
644
|
+
const mod = (await import('node:sqlite'));
|
|
645
|
+
return (path) => new mod.DatabaseSync(path, { readOnly: true });
|
|
646
|
+
}
|
|
647
|
+
catch {
|
|
648
|
+
return undefined;
|
|
649
|
+
}
|
|
650
|
+
finally {
|
|
651
|
+
process.emitWarning = emit;
|
|
652
|
+
}
|
|
653
|
+
})();
|
|
654
|
+
return sqlite;
|
|
655
|
+
}
|
|
656
|
+
async function agyFromDatabase(path, places, logged) {
|
|
657
|
+
try {
|
|
658
|
+
statSync(path);
|
|
659
|
+
}
|
|
660
|
+
catch {
|
|
661
|
+
return undefined;
|
|
662
|
+
}
|
|
663
|
+
const open = await openSqlite();
|
|
664
|
+
if (!open)
|
|
665
|
+
return undefined;
|
|
666
|
+
let db;
|
|
667
|
+
try {
|
|
668
|
+
db = open(path);
|
|
669
|
+
const rows = db
|
|
670
|
+
.prepare('SELECT conversation_id, title, workspace_uris, status, last_modified_time, last_user_input_time ' +
|
|
671
|
+
'FROM conversation_summaries ORDER BY last_modified_time DESC')
|
|
672
|
+
.all();
|
|
673
|
+
const out = [];
|
|
674
|
+
for (const row of rows) {
|
|
675
|
+
const r = record(row);
|
|
676
|
+
const id = text(r.conversation_id);
|
|
677
|
+
if (!id)
|
|
678
|
+
continue;
|
|
679
|
+
let listed = workspaces(text(r.workspace_uris));
|
|
680
|
+
if (listed.length === 0)
|
|
681
|
+
listed = logged().get(id) ?? [];
|
|
682
|
+
const cwd = listed.find((place) => places.has(place));
|
|
683
|
+
if (!cwd)
|
|
684
|
+
continue;
|
|
685
|
+
const session = { brain: 'antigravity', id, cwd, interactive: true };
|
|
686
|
+
const title = text(r.title);
|
|
687
|
+
if (title) {
|
|
688
|
+
session.title = title;
|
|
689
|
+
session.titleSource = 'generated';
|
|
690
|
+
}
|
|
691
|
+
const updated = isoFromSql(text(r.last_modified_time));
|
|
692
|
+
if (updated)
|
|
693
|
+
session.updatedAt = updated;
|
|
694
|
+
const input = isoFromSql(text(r.last_user_input_time));
|
|
695
|
+
if (input)
|
|
696
|
+
session.startedAt = input;
|
|
697
|
+
out.push(session);
|
|
698
|
+
}
|
|
699
|
+
return out;
|
|
700
|
+
}
|
|
701
|
+
catch {
|
|
702
|
+
return undefined;
|
|
703
|
+
}
|
|
704
|
+
finally {
|
|
705
|
+
db?.close();
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
function workspaces(uris) {
|
|
709
|
+
try {
|
|
710
|
+
const list = JSON.parse(uris);
|
|
711
|
+
if (!Array.isArray(list))
|
|
712
|
+
return [];
|
|
713
|
+
return list
|
|
714
|
+
.map((uri) => String(uri))
|
|
715
|
+
.filter((uri) => uri.startsWith('file://'))
|
|
716
|
+
.map((uri) => decodeURIComponent(uri.slice('file://'.length)));
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
return [];
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
const agyLogs = new Map();
|
|
723
|
+
/**
|
|
724
|
+
* Which folders each conversation ran in, from the CLI's run logs: a run
|
|
725
|
+
* names its workspace once (`workspaceDirs=[…]`) and every conversation it
|
|
726
|
+
* creates or opens. A log is read again only when it changed.
|
|
727
|
+
*/
|
|
728
|
+
export function agyLogWorkspaces(dir) {
|
|
729
|
+
const out = new Map();
|
|
730
|
+
let names;
|
|
731
|
+
try {
|
|
732
|
+
names = readdirSync(dir).filter((name) => /^cli-.*\.log$/.test(name));
|
|
733
|
+
}
|
|
734
|
+
catch {
|
|
735
|
+
return out;
|
|
736
|
+
}
|
|
737
|
+
for (const name of names.sort()) {
|
|
738
|
+
const path = join(dir, name);
|
|
739
|
+
let stamp;
|
|
740
|
+
try {
|
|
741
|
+
const stat = statSync(path);
|
|
742
|
+
stamp = `${stat.size}:${stat.mtimeMs}`;
|
|
743
|
+
}
|
|
744
|
+
catch {
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
let cached = agyLogs.get(path);
|
|
748
|
+
if (cached?.stamp !== stamp) {
|
|
749
|
+
cached = { stamp, found: agyLogFolders(readText(path)) };
|
|
750
|
+
agyLogs.set(path, cached);
|
|
751
|
+
}
|
|
752
|
+
for (const [id, folders] of cached.found)
|
|
753
|
+
out.set(id, folders);
|
|
754
|
+
}
|
|
755
|
+
return out;
|
|
756
|
+
}
|
|
757
|
+
function agyLogFolders(log) {
|
|
758
|
+
const found = new Map();
|
|
759
|
+
// Go prints the list space-separated: a folder with a space in its name
|
|
760
|
+
// stays whole only when it is the only one.
|
|
761
|
+
const dirs = /workspaceDirs=\[([^\]\n]*)\]/.exec(log)?.[1]?.trim();
|
|
762
|
+
if (!dirs)
|
|
763
|
+
return found;
|
|
764
|
+
const folders = [...new Set([dirs, ...dirs.split(' ')])].filter((dir) => dir.startsWith('/'));
|
|
765
|
+
for (const match of log.matchAll(/(?:Created|found) conversation ([0-9a-f][0-9a-f-]{7,})/g)) {
|
|
766
|
+
if (match[1])
|
|
767
|
+
found.set(match[1], folders);
|
|
768
|
+
}
|
|
769
|
+
return found;
|
|
770
|
+
}
|
|
771
|
+
function agyFromHistory(path, places) {
|
|
772
|
+
const byId = new Map();
|
|
773
|
+
for (const entry of jsonLines(readText(path), false)) {
|
|
774
|
+
const id = text(entry.conversationId);
|
|
775
|
+
const workspace = text(entry.workspace);
|
|
776
|
+
if (!id || !places.has(workspace))
|
|
777
|
+
continue;
|
|
778
|
+
const at = isoFromMs(entry.timestamp);
|
|
779
|
+
let session = byId.get(id);
|
|
780
|
+
if (!session) {
|
|
781
|
+
session = { brain: 'antigravity', id, cwd: workspace, interactive: true };
|
|
782
|
+
const prompt = oneLine(text(entry.display)).slice(0, 120);
|
|
783
|
+
if (prompt) {
|
|
784
|
+
session.title = prompt;
|
|
785
|
+
session.titleSource = 'prompt';
|
|
786
|
+
}
|
|
787
|
+
if (at)
|
|
788
|
+
session.startedAt = at;
|
|
789
|
+
byId.set(id, session);
|
|
790
|
+
}
|
|
791
|
+
if (at)
|
|
792
|
+
session.updatedAt = at;
|
|
793
|
+
}
|
|
794
|
+
return [...byId.values()];
|
|
795
|
+
}
|
|
796
|
+
// ── OpenCode ────────────────────────────────────────────────────────────────
|
|
797
|
+
/** What a session is called until OpenCode has generated its title. */
|
|
798
|
+
const OPENCODE_PLACEHOLDER = /^(?:New|Child) session - \d{4}-\d{2}-\d{2}T/;
|
|
799
|
+
/** An answer with no write for this long is not being written: the CLI was closed or killed mid-turn. */
|
|
800
|
+
const OPENCODE_STALE_MS = 10 * 60 * 1000;
|
|
801
|
+
const OPENCODE_COLUMNS = 'id, directory, title, permission, time_created, time_updated';
|
|
802
|
+
async function opencodeSessions(home, places) {
|
|
803
|
+
const folders = [...places];
|
|
804
|
+
const found = await readOpencode(home, (db) => {
|
|
805
|
+
const rows = db
|
|
806
|
+
.prepare(`SELECT ${OPENCODE_COLUMNS} FROM session WHERE parent_id IS NULL AND time_archived IS NULL ` +
|
|
807
|
+
`AND directory IN (${folders.map(() => '?').join(', ')})`)
|
|
808
|
+
.all(...folders);
|
|
809
|
+
return rows.map((row) => opencodeSession(db, record(row))).filter((session) => session !== undefined);
|
|
810
|
+
});
|
|
811
|
+
return found ?? [];
|
|
812
|
+
}
|
|
813
|
+
async function opencodeLive(home) {
|
|
814
|
+
const found = await readOpencode(home, (db) => {
|
|
815
|
+
const rows = db
|
|
816
|
+
.prepare(`SELECT ${OPENCODE_COLUMNS}, (SELECT m.data FROM message m WHERE m.session_id = session.id ` +
|
|
817
|
+
'ORDER BY m.time_created DESC, m.id DESC LIMIT 1) AS last ' +
|
|
818
|
+
'FROM session WHERE parent_id IS NULL AND time_archived IS NULL AND time_updated > ?')
|
|
819
|
+
.all(Date.now() - OPENCODE_STALE_MS);
|
|
820
|
+
const out = [];
|
|
821
|
+
for (const row of rows) {
|
|
822
|
+
const r = record(row);
|
|
823
|
+
const last = record(parseJson(text(r.last)));
|
|
824
|
+
// A prompt with no answer yet, or an answer not completed: the agent is at work.
|
|
825
|
+
const busy = last.role === 'user' || (last.role === 'assistant' && !record(last.time).completed);
|
|
826
|
+
const session = busy ? opencodeSession(db, r) : undefined;
|
|
827
|
+
if (session)
|
|
828
|
+
out.push({ ...session, live: { status: 'busy', kind: 'interactive' } });
|
|
829
|
+
}
|
|
830
|
+
return out;
|
|
831
|
+
});
|
|
832
|
+
return found ?? [];
|
|
833
|
+
}
|
|
834
|
+
function opencodeSession(db, r) {
|
|
835
|
+
const id = text(r.id);
|
|
836
|
+
if (!id)
|
|
837
|
+
return undefined;
|
|
838
|
+
const session = { brain: 'opencode', id, interactive: !opencodeRun(text(r.permission)) };
|
|
839
|
+
if (text(r.directory))
|
|
840
|
+
session.cwd = text(r.directory);
|
|
841
|
+
const started = isoFromMs(r.time_created);
|
|
842
|
+
if (started)
|
|
843
|
+
session.startedAt = started;
|
|
844
|
+
const updated = isoFromMs(r.time_updated);
|
|
845
|
+
if (updated)
|
|
846
|
+
session.updatedAt = updated;
|
|
847
|
+
const title = oneLine(text(r.title));
|
|
848
|
+
if (title && !OPENCODE_PLACEHOLDER.test(title)) {
|
|
849
|
+
session.title = title.slice(0, 120);
|
|
850
|
+
session.titleSource = 'generated';
|
|
851
|
+
return session;
|
|
852
|
+
}
|
|
853
|
+
const [first] = db
|
|
854
|
+
.prepare('SELECT p.data AS data FROM part p JOIN message m ON m.id = p.message_id ' +
|
|
855
|
+
"WHERE p.session_id = ? AND json_extract(m.data, '$.role') = 'user' " +
|
|
856
|
+
"AND json_extract(p.data, '$.type') = 'text' ORDER BY p.time_created, p.id LIMIT 1")
|
|
857
|
+
.all(id);
|
|
858
|
+
const prompt = oneLine(text(record(parseJson(text(record(first).data))).text));
|
|
859
|
+
if (prompt) {
|
|
860
|
+
session.title = prompt.slice(0, 120);
|
|
861
|
+
session.titleSource = 'prompt';
|
|
862
|
+
}
|
|
863
|
+
return session;
|
|
864
|
+
}
|
|
865
|
+
/** `opencode run` gives its sessions rules that keep questions and plan mode out; the TUI gives none. */
|
|
866
|
+
function opencodeRun(permission) {
|
|
867
|
+
const rules = parseJson(permission);
|
|
868
|
+
return (Array.isArray(rules) &&
|
|
869
|
+
rules.some((rule) => record(rule).permission === 'plan_exit' && record(rule).action === 'deny'));
|
|
870
|
+
}
|
|
871
|
+
/** Reads OpenCode's database; undefined when it is not there or not readable. */
|
|
872
|
+
async function readOpencode(home, read) {
|
|
873
|
+
const path = join(home, 'opencode.db');
|
|
874
|
+
try {
|
|
875
|
+
statSync(path);
|
|
876
|
+
}
|
|
877
|
+
catch {
|
|
878
|
+
return undefined;
|
|
879
|
+
}
|
|
880
|
+
const open = await openSqlite();
|
|
881
|
+
if (!open)
|
|
882
|
+
return undefined;
|
|
883
|
+
let db;
|
|
884
|
+
try {
|
|
885
|
+
db = open(path);
|
|
886
|
+
return read(db);
|
|
887
|
+
}
|
|
888
|
+
catch {
|
|
889
|
+
return undefined;
|
|
890
|
+
}
|
|
891
|
+
finally {
|
|
892
|
+
db?.close();
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
// ── Plumbing ────────────────────────────────────────────────────────────────
|
|
896
|
+
/** The folder as given and as the filesystem resolves it: `/tmp` is `/private/tmp` on macOS, and CLIs store either. */
|
|
897
|
+
export function pathVariants(cwd) {
|
|
898
|
+
const places = new Set([cwd]);
|
|
899
|
+
try {
|
|
900
|
+
places.add(realpathSync(cwd));
|
|
901
|
+
}
|
|
902
|
+
catch {
|
|
903
|
+
// A folder that does not exist has no other name.
|
|
904
|
+
}
|
|
905
|
+
return places;
|
|
906
|
+
}
|
|
907
|
+
function newestFirst(list) {
|
|
908
|
+
const time = (session) => Date.parse(session.updatedAt ?? session.startedAt ?? '') || 0;
|
|
909
|
+
return [...list].sort((a, b) => time(b) - time(a));
|
|
910
|
+
}
|
|
911
|
+
function listDir(dir) {
|
|
912
|
+
try {
|
|
913
|
+
return readdirSync(dir);
|
|
914
|
+
}
|
|
915
|
+
catch {
|
|
916
|
+
return [];
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
function readText(path) {
|
|
920
|
+
try {
|
|
921
|
+
return readFileSync(path, 'utf8');
|
|
922
|
+
}
|
|
923
|
+
catch {
|
|
924
|
+
return '';
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
function readRange(path, start, length) {
|
|
928
|
+
if (length <= 0)
|
|
929
|
+
return '';
|
|
930
|
+
let fd;
|
|
931
|
+
try {
|
|
932
|
+
fd = openSync(path, 'r');
|
|
933
|
+
const buffer = Buffer.alloc(length);
|
|
934
|
+
const read = readSync(fd, buffer, 0, length, start);
|
|
935
|
+
return buffer.subarray(0, read).toString('utf8');
|
|
936
|
+
}
|
|
937
|
+
catch {
|
|
938
|
+
return '';
|
|
939
|
+
}
|
|
940
|
+
finally {
|
|
941
|
+
if (fd !== undefined)
|
|
942
|
+
closeSync(fd);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/** The first line of a file, however long, parsed. */
|
|
946
|
+
function firstLine(path) {
|
|
947
|
+
let fd;
|
|
948
|
+
try {
|
|
949
|
+
fd = openSync(path, 'r');
|
|
950
|
+
const chunks = [];
|
|
951
|
+
const chunk = Buffer.alloc(64 * 1024);
|
|
952
|
+
for (let position = 0; position < 8 * 1024 * 1024;) {
|
|
953
|
+
const read = readSync(fd, chunk, 0, chunk.length, position);
|
|
954
|
+
if (read <= 0)
|
|
955
|
+
break;
|
|
956
|
+
const piece = chunk.subarray(0, read);
|
|
957
|
+
const cut = piece.indexOf(10);
|
|
958
|
+
if (cut >= 0) {
|
|
959
|
+
chunks.push(Buffer.from(piece.subarray(0, cut)));
|
|
960
|
+
break;
|
|
961
|
+
}
|
|
962
|
+
chunks.push(Buffer.from(piece));
|
|
963
|
+
position += read;
|
|
964
|
+
}
|
|
965
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
966
|
+
return record(parsed);
|
|
967
|
+
}
|
|
968
|
+
catch {
|
|
969
|
+
return undefined;
|
|
970
|
+
}
|
|
971
|
+
finally {
|
|
972
|
+
if (fd !== undefined)
|
|
973
|
+
closeSync(fd);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
/** JSON objects, one per line. A cut-off first line (`fromMiddle`) and anything unparseable are skipped. */
|
|
977
|
+
function jsonLines(chunk, fromMiddle) {
|
|
978
|
+
const lines = chunk.split('\n');
|
|
979
|
+
if (fromMiddle)
|
|
980
|
+
lines.shift();
|
|
981
|
+
const out = [];
|
|
982
|
+
for (const line of lines) {
|
|
983
|
+
if (!line.trim())
|
|
984
|
+
continue;
|
|
985
|
+
try {
|
|
986
|
+
const value = JSON.parse(line);
|
|
987
|
+
if (value && typeof value === 'object' && !Array.isArray(value))
|
|
988
|
+
out.push(value);
|
|
989
|
+
}
|
|
990
|
+
catch {
|
|
991
|
+
// The last line of a head read is usually cut off too.
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
return out;
|
|
995
|
+
}
|
|
996
|
+
function parseJson(value) {
|
|
997
|
+
try {
|
|
998
|
+
return JSON.parse(value);
|
|
999
|
+
}
|
|
1000
|
+
catch {
|
|
1001
|
+
return undefined;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
function record(value) {
|
|
1005
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
1006
|
+
}
|
|
1007
|
+
function text(value) {
|
|
1008
|
+
return typeof value === 'string' ? value : '';
|
|
1009
|
+
}
|
|
1010
|
+
function isoFromMs(value) {
|
|
1011
|
+
const ms = typeof value === 'number' ? value : Number(value);
|
|
1012
|
+
if (!Number.isFinite(ms) || ms <= 0)
|
|
1013
|
+
return undefined;
|
|
1014
|
+
return new Date(ms).toISOString();
|
|
1015
|
+
}
|
|
1016
|
+
/** `2026-10-01 19:19:06.687213+00:00` → ISO. */
|
|
1017
|
+
function isoFromSql(value) {
|
|
1018
|
+
if (!value)
|
|
1019
|
+
return undefined;
|
|
1020
|
+
const ms = Date.parse(value.replace(' ', 'T'));
|
|
1021
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
|
|
1022
|
+
}
|
|
1023
|
+
//# sourceMappingURL=sessions.js.map
|