@xenosystem/primitives 0.6.0 → 0.8.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/README.md +28 -0
- package/dist/cjs/sessions/cli.d.ts +2 -0
- package/dist/cjs/sessions/cli.js +196 -0
- package/dist/cjs/sessions/convert.d.ts +44 -0
- package/dist/cjs/sessions/convert.js +208 -0
- package/dist/cjs/sessions/index.d.ts +13 -0
- package/dist/cjs/sessions/index.js +46 -0
- package/dist/cjs/sessions/layers.d.ts +28 -0
- package/dist/cjs/sessions/layers.js +126 -0
- package/dist/cjs/sessions/read.d.ts +53 -0
- package/dist/cjs/sessions/read.js +637 -0
- package/dist/cjs/sessions/run.d.ts +9 -0
- package/dist/cjs/sessions/run.js +60 -0
- package/dist/cjs/sessions/stores.d.ts +9 -0
- package/dist/cjs/sessions/stores.js +24 -0
- package/dist/cjs/sessions/transcript.d.ts +43 -0
- package/dist/cjs/sessions/transcript.js +117 -0
- package/dist/cjs/sessions/types.d.ts +73 -0
- package/dist/cjs/sessions/types.js +10 -0
- package/dist/cjs/sessions/write.d.ts +66 -0
- package/dist/cjs/sessions/write.js +234 -0
- package/dist/esm/sessions/cli.d.ts +2 -0
- package/dist/esm/sessions/cli.js +194 -0
- package/dist/esm/sessions/convert.d.ts +44 -0
- package/dist/esm/sessions/convert.js +200 -0
- package/dist/esm/sessions/index.d.ts +13 -0
- package/dist/esm/sessions/index.js +13 -0
- package/dist/esm/sessions/layers.d.ts +28 -0
- package/dist/esm/sessions/layers.js +121 -0
- package/dist/esm/sessions/read.d.ts +53 -0
- package/dist/esm/sessions/read.js +624 -0
- package/dist/esm/sessions/run.d.ts +9 -0
- package/dist/esm/sessions/run.js +55 -0
- package/dist/esm/sessions/stores.d.ts +9 -0
- package/dist/esm/sessions/stores.js +21 -0
- package/dist/esm/sessions/transcript.d.ts +43 -0
- package/dist/esm/sessions/transcript.js +111 -0
- package/dist/esm/sessions/types.d.ts +73 -0
- package/dist/esm/sessions/types.js +7 -0
- package/dist/esm/sessions/write.d.ts +66 -0
- package/dist/esm/sessions/write.js +225 -0
- package/native/win32-x64/process.node +0 -0
- package/package.json +14 -3
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Runner, SessionRef, Stores, Subagent, Turn } from './types.ts';
|
|
2
|
+
/** What reading needs: where each agent keeps its sessions, and how to run an agent's command (opencode reads through its own export). */
|
|
3
|
+
export interface ReadContext {
|
|
4
|
+
stores: Stores;
|
|
5
|
+
run: Runner;
|
|
6
|
+
}
|
|
7
|
+
/** A session id an agent's command can take as one word, or null. */
|
|
8
|
+
export declare const safeSessionId: (id: unknown) => string | null;
|
|
9
|
+
/**
|
|
10
|
+
* A tool's output as a reader keeps it: the first 64 KiB. Every use takes far less (a copy keeps 4,000 characters), and keeping all of it
|
|
11
|
+
* held a long session's every file read and build log in memory at once (a real Claude Code session on this machine is 2.5 GB).
|
|
12
|
+
*/
|
|
13
|
+
export declare const OUTPUT_KEPT = 65536;
|
|
14
|
+
/**
|
|
15
|
+
* What the person typed, out of agy's own wrapping. agy records every message as `<USER_REQUEST>…</USER_REQUEST>` followed by its own
|
|
16
|
+
* `<ADDITIONAL_METADATA>` block, and at times `<USER_SETTINGS_CHANGE>`: measured 2026-11-27, 232 of 232 messages on this machine.
|
|
17
|
+
*/
|
|
18
|
+
export declare function agyRequest(content: string): string;
|
|
19
|
+
/** opencode's own export of a session (its supported read path), checked to be the session asked for. */
|
|
20
|
+
export declare function exportOpencodeSession(id: string, { run }: {
|
|
21
|
+
run: Runner;
|
|
22
|
+
}, env?: NodeJS.ProcessEnv): Promise<any>;
|
|
23
|
+
/** One agent's sessions, newest first, or the reason they cannot be listed: a failure is a status, never an empty list. */
|
|
24
|
+
export declare function listSessions(vendor: string, ctx: ReadContext): Promise<{
|
|
25
|
+
vendor: string;
|
|
26
|
+
sessions: SessionRef[];
|
|
27
|
+
error: string | null;
|
|
28
|
+
}>;
|
|
29
|
+
/**
|
|
30
|
+
* Find a session in its agent's store at the moment of use. `id` may be the whole id or its first 8 or more characters; more than one
|
|
31
|
+
* match is refused, never guessed.
|
|
32
|
+
*/
|
|
33
|
+
export declare function findSession(vendor: string, id: string, ctx: ReadContext): Promise<SessionRef>;
|
|
34
|
+
/**
|
|
35
|
+
* Find a session by its id alone, in whichever agent keeps it: ids are unique across agents (UUIDs, `ses_…`, `xeno-copy-…`), so the
|
|
36
|
+
* agent is read from the store that has it. A prefix matching sessions of two agents is refused, never guessed; an agent whose store
|
|
37
|
+
* cannot be read is named when nothing is found, since the session may be there.
|
|
38
|
+
*/
|
|
39
|
+
export declare function findAnySession(id: string, ctx: ReadContext, { except }?: {
|
|
40
|
+
except?: string;
|
|
41
|
+
}): Promise<SessionRef>;
|
|
42
|
+
/** The most recently used session whose folder is `cwd` (compared the way the OS does: case-insensitive on Windows), in any agent but `except`. */
|
|
43
|
+
export declare function newestSessionIn(cwd: string, ctx: ReadContext, { except }?: {
|
|
44
|
+
except?: string;
|
|
45
|
+
}): Promise<SessionRef | null>;
|
|
46
|
+
/** A session's transcript as Turns. */
|
|
47
|
+
export declare function readSession(ref: SessionRef, ctx: ReadContext, o?: {
|
|
48
|
+
maxBytes?: number;
|
|
49
|
+
}): Promise<Turn[]>;
|
|
50
|
+
/** A session's sub-agent conversations, for agents that keep them separately (Claude Code); none for the others. */
|
|
51
|
+
export declare function readSubagents(ref: SessionRef): Promise<Subagent[]>;
|
|
52
|
+
/** The words an agent's own command takes to reopen a session. */
|
|
53
|
+
export declare function resumeArgs(vendor: string, id: string): string[];
|
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read every agent's sessions in that agent's own format. Moved down from XENO Spawn (server/src/sessionAdapters.js, where each reader
|
|
3
|
+
* was measured against the real agents: Claude Code 2.1.283, Codex 0.155.0, agy 1.2.11, opencode 1.18.32, XENO agent 0.5.74).
|
|
4
|
+
*
|
|
5
|
+
* 🔴 READ-ONLY. Nothing here writes an agent's store. SQLite stores (Codex's thread index, opencode's database, agy's summaries) are
|
|
6
|
+
* opened read-only; a store that is locked or missing is reported with its reason, never read as empty.
|
|
7
|
+
*
|
|
8
|
+
* One reader per agent, one contract: `list` (cheap metadata, newest first), `read` (the transcript as Turns), `subagents` (where the
|
|
9
|
+
* agent keeps them apart), and `resumeArgs` (the words the agent's own command takes to reopen a session).
|
|
10
|
+
*/
|
|
11
|
+
import { closeSync, createReadStream, existsSync, lstatSync, openSync, readdirSync, readFileSync, readSync, statSync } from 'node:fs';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
import { createInterface } from 'node:readline';
|
|
14
|
+
import { VENDORS } from "./types.js";
|
|
15
|
+
const TITLE_CAP = 160, LINE_CAP = 8 << 20;
|
|
16
|
+
const SAFE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
17
|
+
/** A session id an agent's command can take as one word, or null. */
|
|
18
|
+
export const safeSessionId = (id) => typeof id === 'string' && SAFE_ID.test(id) ? id : null;
|
|
19
|
+
const clip = (s, n = TITLE_CAP) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
|
|
20
|
+
/**
|
|
21
|
+
* A tool's output as a reader keeps it: the first 64 KiB. Every use takes far less (a copy keeps 4,000 characters), and keeping all of it
|
|
22
|
+
* held a long session's every file read and build log in memory at once (a real Claude Code session on this machine is 2.5 GB).
|
|
23
|
+
*/
|
|
24
|
+
export const OUTPUT_KEPT = 65536;
|
|
25
|
+
const kept = (s) => s.length > OUTPUT_KEPT ? `${s.slice(0, OUTPUT_KEPT)}\n… [${s.length - OUTPUT_KEPT} more characters not read]` : s;
|
|
26
|
+
const num = (v) => { const n = typeof v === 'number' ? v : Date.parse(String(v ?? '')); return Number.isFinite(n) ? n : 0; };
|
|
27
|
+
async function openReadOnly(path) {
|
|
28
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
29
|
+
return new DatabaseSync(path, { readOnly: true });
|
|
30
|
+
}
|
|
31
|
+
function head(path, max = 65536) {
|
|
32
|
+
const fd = openSync(path, 'r');
|
|
33
|
+
try {
|
|
34
|
+
const b = Buffer.alloc(max);
|
|
35
|
+
const n = readSync(fd, b, 0, max, 0);
|
|
36
|
+
return b.subarray(0, n).toString('utf8');
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
closeSync(fd);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Each JSON line of a file, streamed and bounded: a line over 8 MiB (a pasted file, an image) is skipped rather than parsed. */
|
|
43
|
+
async function eachJson(path, fn, { maxBytes = Infinity } = {}) {
|
|
44
|
+
const rl = createInterface({ input: createReadStream(path, maxBytes === Infinity ? {} : { end: maxBytes - 1 }), crlfDelay: Infinity });
|
|
45
|
+
for await (const line of rl) {
|
|
46
|
+
if (!line.trim() || line.length > LINE_CAP)
|
|
47
|
+
continue;
|
|
48
|
+
let o;
|
|
49
|
+
try {
|
|
50
|
+
o = JSON.parse(line);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (fn(o) === false)
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
rl.close();
|
|
59
|
+
}
|
|
60
|
+
/** The text of an Anthropic-style content array. */
|
|
61
|
+
const blocksText = (c) => typeof c === 'string' ? c : Array.isArray(c) ? c.map((b) => typeof b === 'string' ? b : b?.type === 'text' ? b.text : '').filter(Boolean).join('\n') : '';
|
|
62
|
+
/* ------------------------------------------------------------------ Claude Code */
|
|
63
|
+
/**
|
|
64
|
+
* Title, folder and first time from the head of a Claude transcript. 🔴 Two real shapes put the first turn beyond a 64 KB parse
|
|
65
|
+
* (measured 2026-09-29): a first message that is ONE pasted line of 250-400 KB, and 465 KB of bookkeeping records before the first
|
|
66
|
+
* turn. A record's `type` and `cwd` sit near the start of its line, so a line that does not parse is still read by its prefix; only a
|
|
67
|
+
* file that shows no turn gets one wider pass.
|
|
68
|
+
*/
|
|
69
|
+
function claudeHead(path, size = Infinity) {
|
|
70
|
+
const first = claudeHeadIn(head(path));
|
|
71
|
+
return first.hasTurn || size <= 65536 ? first : claudeHeadIn(head(path, Math.min(size, 4 << 20)));
|
|
72
|
+
}
|
|
73
|
+
function claudeHeadIn(text) {
|
|
74
|
+
let cwd = null, title = '', created = 0, hasTurn = false;
|
|
75
|
+
for (const line of text.split('\n')) {
|
|
76
|
+
let r;
|
|
77
|
+
try {
|
|
78
|
+
r = JSON.parse(line);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
const pre = line.slice(0, 8192);
|
|
82
|
+
if (/"type":"(user|assistant)"/.test(pre) && !/"isSidechain":true/.test(pre))
|
|
83
|
+
hasTurn = true;
|
|
84
|
+
if (!cwd) {
|
|
85
|
+
const m = /"cwd":"((?:[^"\\]|\\.)*)"/.exec(pre);
|
|
86
|
+
if (m) {
|
|
87
|
+
try {
|
|
88
|
+
cwd = JSON.parse(`"${m[1]}"`);
|
|
89
|
+
}
|
|
90
|
+
catch { /* not a string */ }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (cwd && title && created && hasTurn)
|
|
94
|
+
break;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (!cwd && typeof r.cwd === 'string')
|
|
98
|
+
cwd = r.cwd;
|
|
99
|
+
if (!created && r.timestamp)
|
|
100
|
+
created = num(r.timestamp);
|
|
101
|
+
if (r.type === 'custom-title' || r.type === 'ai-title' || r.type === 'summary')
|
|
102
|
+
title = clip(r.customTitle ?? r.aiTitle ?? r.title ?? r.summary) || title;
|
|
103
|
+
if (r.type === 'user' || r.type === 'assistant')
|
|
104
|
+
hasTurn = true;
|
|
105
|
+
if (!title && r.type === 'user' && !r.isMeta && !r.isSidechain) {
|
|
106
|
+
const t = blocksText(r.message?.content);
|
|
107
|
+
if (t && !/^\s*</.test(t))
|
|
108
|
+
title = clip(t);
|
|
109
|
+
}
|
|
110
|
+
// 🔴 `hasTurn` is part of the stop condition: without it a RENAMED session stopped early and was dropped as turnless
|
|
111
|
+
// (measured 2026-09-29: 8 real sessions, up to 482 MB, invisible).
|
|
112
|
+
if (cwd && title && created && hasTurn)
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
return { cwd, title, created, hasTurn };
|
|
116
|
+
}
|
|
117
|
+
const claude = {
|
|
118
|
+
vendor: 'Claude Code',
|
|
119
|
+
async list({ stores }) {
|
|
120
|
+
const root = join(stores.claude, 'projects');
|
|
121
|
+
if (!existsSync(root))
|
|
122
|
+
return [];
|
|
123
|
+
const out = [];
|
|
124
|
+
for (const p of readdirSync(root)) {
|
|
125
|
+
const pd = join(root, p);
|
|
126
|
+
let names;
|
|
127
|
+
try {
|
|
128
|
+
names = readdirSync(pd);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
for (const n of names) {
|
|
134
|
+
if (!n.endsWith('.jsonl'))
|
|
135
|
+
continue;
|
|
136
|
+
const id = safeSessionId(n.slice(0, -6));
|
|
137
|
+
if (!id)
|
|
138
|
+
continue;
|
|
139
|
+
const path = join(pd, n);
|
|
140
|
+
let st;
|
|
141
|
+
try {
|
|
142
|
+
st = statSync(path);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (!st.isFile() || st.size === 0)
|
|
148
|
+
continue;
|
|
149
|
+
const m = claudeHead(path, st.size);
|
|
150
|
+
if (!m.hasTurn)
|
|
151
|
+
continue;
|
|
152
|
+
out.push({ vendor: 'Claude Code', id, cwd: m.cwd, title: m.title || id, created: m.created || st.birthtimeMs, updated: st.mtimeMs, size: st.size, locator: path });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return out;
|
|
156
|
+
},
|
|
157
|
+
async read(ref, _ctx, opts = {}) {
|
|
158
|
+
const turns = [];
|
|
159
|
+
await eachJson(ref.locator, (r) => {
|
|
160
|
+
if (r.isSidechain)
|
|
161
|
+
return;
|
|
162
|
+
const at = r.timestamp ?? null, c = r.message?.content;
|
|
163
|
+
// 🔴 A message that arrives while a turn is running is kept as a `queued_command` attachment, not a user record (measured
|
|
164
|
+
// 2026-11-28 on a real session: 271 messages the person typed, 131 from other sessions, 416 job notices; only 3 of the typed ones
|
|
165
|
+
// were also user records). Skipping them dropped the person's own words from every copy.
|
|
166
|
+
const q = r.type === 'attachment' && r.attachment?.type === 'queued_command' ? r.attachment : null;
|
|
167
|
+
if (q) {
|
|
168
|
+
const text = typeof q.prompt === 'string' ? q.prompt : blocksText(q.prompt);
|
|
169
|
+
const last = turns[turns.length - 1];
|
|
170
|
+
if (text.trim() && !(last?.role === 'user' && last.text === text))
|
|
171
|
+
turns.push({ role: 'user', text, at: q.timestamp ?? at, ...(q.origin?.kind === 'human' ? {} : { from: q.origin?.kind === 'peer' ? 'peer' : 'harness' }) });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
if (r.type === 'system' && r.subtype === 'compact_boundary') {
|
|
175
|
+
turns.push({ role: 'system', text: '[conversation compacted]', compaction: true, at });
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (r.type === 'user') {
|
|
179
|
+
if (r.isCompactSummary) {
|
|
180
|
+
turns.push({ role: 'user', text: blocksText(c), compaction: true, at });
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (typeof c === 'string') {
|
|
184
|
+
if (!r.isMeta)
|
|
185
|
+
turns.push({ role: 'user', text: c, at });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
for (const b of Array.isArray(c) ? c : []) {
|
|
189
|
+
if (b?.type === 'text' && !r.isMeta)
|
|
190
|
+
turns.push({ role: 'user', text: b.text, at });
|
|
191
|
+
else if (b?.type === 'tool_result')
|
|
192
|
+
turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: kept(blocksText(b.content)), at });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
else if (r.type === 'assistant') {
|
|
196
|
+
for (const b of Array.isArray(c) ? c : []) {
|
|
197
|
+
if (b?.type === 'text')
|
|
198
|
+
turns.push({ role: 'assistant', text: b.text, at });
|
|
199
|
+
else if (b?.type === 'thinking' || b?.type === 'redacted_thinking')
|
|
200
|
+
turns.push({ role: 'assistant', text: '', thinking: true, at });
|
|
201
|
+
else if (b?.type === 'tool_use')
|
|
202
|
+
turns.push({ role: 'assistant', text: '', tool: b.name, callId: b.id, input: b.input, at });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}, opts);
|
|
206
|
+
return turns;
|
|
207
|
+
},
|
|
208
|
+
async subagents(ref) {
|
|
209
|
+
const dir = join(ref.locator.replace(/\.jsonl$/, ''), 'subagents');
|
|
210
|
+
if (!existsSync(dir))
|
|
211
|
+
return [];
|
|
212
|
+
const out = [];
|
|
213
|
+
for (const n of readdirSync(dir).filter((x) => x.endsWith('.jsonl')).sort()) {
|
|
214
|
+
const turns = [];
|
|
215
|
+
await eachJson(join(dir, n), (r) => {
|
|
216
|
+
const c = r.message?.content, at = r.timestamp ?? null;
|
|
217
|
+
if (r.type === 'user') {
|
|
218
|
+
const t = blocksText(c);
|
|
219
|
+
if (t && !r.isMeta)
|
|
220
|
+
turns.push({ role: 'user', text: t, at });
|
|
221
|
+
}
|
|
222
|
+
else if (r.type === 'assistant')
|
|
223
|
+
for (const b of Array.isArray(c) ? c : [])
|
|
224
|
+
if (b?.type === 'text')
|
|
225
|
+
turns.push({ role: 'assistant', text: b.text, at });
|
|
226
|
+
});
|
|
227
|
+
out.push({ name: n.replace(/\.jsonl$/, ''), turns });
|
|
228
|
+
}
|
|
229
|
+
return out;
|
|
230
|
+
},
|
|
231
|
+
resumeArgs: (id) => ['--resume', id],
|
|
232
|
+
};
|
|
233
|
+
/* ------------------------------------------------------------------ Codex */
|
|
234
|
+
async function codexScan(stores) {
|
|
235
|
+
const root = join(stores.codex, 'sessions');
|
|
236
|
+
if (!existsSync(root))
|
|
237
|
+
return [];
|
|
238
|
+
const out = [];
|
|
239
|
+
const walk = (d, depth = 0) => {
|
|
240
|
+
let es;
|
|
241
|
+
try {
|
|
242
|
+
es = readdirSync(d, { withFileTypes: true });
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
for (const e of es) {
|
|
248
|
+
const p = join(d, e.name);
|
|
249
|
+
if (e.isDirectory() && depth < 3)
|
|
250
|
+
walk(p, depth + 1);
|
|
251
|
+
else if (e.isFile() && e.name.startsWith('rollout-') && e.name.endsWith('.jsonl')) {
|
|
252
|
+
try {
|
|
253
|
+
const meta = JSON.parse(head(p, 32768).split('\n')[0] ?? '{}')?.payload ?? {};
|
|
254
|
+
const id = safeSessionId(meta.id ?? meta.session_id);
|
|
255
|
+
if (!id)
|
|
256
|
+
continue;
|
|
257
|
+
const st = statSync(p);
|
|
258
|
+
out.push({ vendor: 'Codex', id, cwd: meta.cwd ?? null, title: id, created: num(meta.timestamp), updated: st.mtimeMs, size: st.size, locator: p });
|
|
259
|
+
}
|
|
260
|
+
catch { /* not a rollout */ }
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
walk(root);
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
const codex = {
|
|
268
|
+
vendor: 'Codex',
|
|
269
|
+
async list({ stores }) {
|
|
270
|
+
const h = stores.codex;
|
|
271
|
+
if (!existsSync(h))
|
|
272
|
+
return [];
|
|
273
|
+
// The thread index Codex keeps itself is the cheap path; the rollout scan is the fallback.
|
|
274
|
+
const db = join(h, 'state_5.sqlite');
|
|
275
|
+
if (existsSync(db)) {
|
|
276
|
+
try {
|
|
277
|
+
const d = await openReadOnly(db);
|
|
278
|
+
try {
|
|
279
|
+
const rows = d.prepare("SELECT id, rollout_path, cwd, substr(title, 1, 200) AS title, substr(first_user_message, 1, 200) AS first_user_message, created_at, updated_at, archived FROM threads WHERE archived = 0 AND (source IN ('cli','vscode','exec','unknown') OR source IS NULL) ORDER BY updated_at DESC").all();
|
|
280
|
+
const out = [];
|
|
281
|
+
for (const r of rows) {
|
|
282
|
+
const id = safeSessionId(r.id);
|
|
283
|
+
if (!id || !r.rollout_path)
|
|
284
|
+
continue;
|
|
285
|
+
let size = 0;
|
|
286
|
+
try {
|
|
287
|
+
size = statSync(r.rollout_path).size;
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const secs = (v) => { const n = Number(v); return Number.isFinite(n) ? (n < 1e12 ? n * 1000 : n) : 0; };
|
|
293
|
+
out.push({ vendor: 'Codex', id, cwd: r.cwd || null, title: clip(r.title || r.first_user_message) || id, created: secs(r.created_at), updated: secs(r.updated_at), size, locator: r.rollout_path });
|
|
294
|
+
}
|
|
295
|
+
// A shared sessions folder holds rollouts another home wrote, which this home's index has not seen: list those too.
|
|
296
|
+
let shared = false;
|
|
297
|
+
try {
|
|
298
|
+
shared = lstatSync(join(h, 'sessions')).isSymbolicLink();
|
|
299
|
+
}
|
|
300
|
+
catch { /* no sessions folder */ }
|
|
301
|
+
if (shared) {
|
|
302
|
+
const known = new Set(out.map((s) => s.id));
|
|
303
|
+
for (const s of await codexScan(stores))
|
|
304
|
+
if (!known.has(s.id))
|
|
305
|
+
out.push(s);
|
|
306
|
+
}
|
|
307
|
+
return out;
|
|
308
|
+
}
|
|
309
|
+
finally {
|
|
310
|
+
d.close();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
catch { /* locked or a different schema: scan the rollouts instead */ }
|
|
314
|
+
}
|
|
315
|
+
return codexScan(stores);
|
|
316
|
+
},
|
|
317
|
+
async read(ref, _ctx, opts = {}) {
|
|
318
|
+
const turns = [];
|
|
319
|
+
await eachJson(ref.locator, (l) => {
|
|
320
|
+
const p = l.payload ?? {}, at = l.timestamp ?? null;
|
|
321
|
+
if (l.type === 'compacted') {
|
|
322
|
+
turns.push({ role: 'system', text: '[conversation compacted]', compaction: true, at });
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
// Codex records the end of each turn (event_msg/task_complete): it marks the turn's last reply, as Claude Code's end_turn does.
|
|
326
|
+
if (l.type === 'event_msg' && p.type === 'task_complete') {
|
|
327
|
+
for (let i = turns.length - 1; i >= 0; i--) {
|
|
328
|
+
const t = turns[i];
|
|
329
|
+
if (t.role === 'user' && !t.compaction)
|
|
330
|
+
break;
|
|
331
|
+
if (t.role === 'assistant' && t.text && !t.tool && !t.thinking) {
|
|
332
|
+
t.turnEnd = true;
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (l.type !== 'response_item')
|
|
339
|
+
return;
|
|
340
|
+
if (p.type === 'message') {
|
|
341
|
+
const t = (Array.isArray(p.content) ? p.content : []).map((c) => c?.text ?? '').filter(Boolean).join('\n');
|
|
342
|
+
if (!t || p.role === 'developer' || p.role === 'system')
|
|
343
|
+
return;
|
|
344
|
+
// Codex writes its own environment and instructions preamble as user messages.
|
|
345
|
+
if (p.role === 'user' && /^\s*<(environment_context|user_instructions|permissions instructions|INSTRUCTIONS)/i.test(t))
|
|
346
|
+
return;
|
|
347
|
+
turns.push({ role: p.role === 'assistant' ? 'assistant' : 'user', text: t, at });
|
|
348
|
+
}
|
|
349
|
+
else if (p.type === 'reasoning')
|
|
350
|
+
turns.push({ role: 'assistant', text: '', thinking: true, at });
|
|
351
|
+
else if (p.type === 'function_call' || p.type === 'custom_tool_call') {
|
|
352
|
+
let input = p.arguments ?? p.input;
|
|
353
|
+
try {
|
|
354
|
+
if (typeof input === 'string')
|
|
355
|
+
input = JSON.parse(input);
|
|
356
|
+
}
|
|
357
|
+
catch { /* keep as text */ }
|
|
358
|
+
turns.push({ role: 'assistant', text: '', tool: p.name, callId: p.call_id, input, at });
|
|
359
|
+
}
|
|
360
|
+
else if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') {
|
|
361
|
+
const o = typeof p.output === 'string' ? p.output : p.output?.content ?? JSON.stringify(p.output ?? '');
|
|
362
|
+
turns.push({ role: 'tool', text: '', callId: p.call_id, output: kept(String(o)), at });
|
|
363
|
+
}
|
|
364
|
+
}, opts);
|
|
365
|
+
return turns;
|
|
366
|
+
},
|
|
367
|
+
resumeArgs: (id) => ['resume', id],
|
|
368
|
+
};
|
|
369
|
+
/* ------------------------------------------------------------------ agy (Antigravity CLI) */
|
|
370
|
+
/** The first `file://` workspace in agy's stored list, as a path. */
|
|
371
|
+
function fileUri(v) {
|
|
372
|
+
const s = typeof v === 'string' ? v : Buffer.isBuffer(v) ? v.toString('utf8') : '';
|
|
373
|
+
const m = s.match(/file:\/\/\/?([^\s"',\]]+)/);
|
|
374
|
+
if (!m || !m[1])
|
|
375
|
+
return null;
|
|
376
|
+
let p = decodeURIComponent(m[1]);
|
|
377
|
+
if (/^[A-Za-z]:/.test(p) || /^[A-Za-z]%3A/i.test(m[1]))
|
|
378
|
+
p = p.replace(/\//g, '\\');
|
|
379
|
+
else
|
|
380
|
+
p = '/' + p.replace(/^\/+/, '');
|
|
381
|
+
return p;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* What the person typed, out of agy's own wrapping. agy records every message as `<USER_REQUEST>…</USER_REQUEST>` followed by its own
|
|
385
|
+
* `<ADDITIONAL_METADATA>` block, and at times `<USER_SETTINGS_CHANGE>`: measured 2026-11-27, 232 of 232 messages on this machine.
|
|
386
|
+
*/
|
|
387
|
+
export function agyRequest(content) {
|
|
388
|
+
const m = /<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(content);
|
|
389
|
+
return (m ? m[1] : content.replace(/<(ADDITIONAL_METADATA|USER_SETTINGS_CHANGE)>[\s\S]*?<\/\1>/g, '')).trim();
|
|
390
|
+
}
|
|
391
|
+
/** One Antigravity data folder's conversations: the CLI's and the desktop app's share a layout. */
|
|
392
|
+
async function agyList(h, app) {
|
|
393
|
+
const db = join(h, 'conversation_summaries.db');
|
|
394
|
+
if (!existsSync(db))
|
|
395
|
+
return [];
|
|
396
|
+
const d = await openReadOnly(db);
|
|
397
|
+
try {
|
|
398
|
+
const rows = d.prepare('SELECT conversation_id, title, preview, last_modified_time, workspace_uris, step_count FROM conversation_summaries ORDER BY last_modified_time DESC').all();
|
|
399
|
+
const out = [];
|
|
400
|
+
for (const r of rows) {
|
|
401
|
+
const id = safeSessionId(r.conversation_id);
|
|
402
|
+
if (!id)
|
|
403
|
+
continue;
|
|
404
|
+
const t = join(h, 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl');
|
|
405
|
+
let size = 0;
|
|
406
|
+
try {
|
|
407
|
+
size = statSync(t).size;
|
|
408
|
+
}
|
|
409
|
+
catch { /* summary only */ }
|
|
410
|
+
out.push({ vendor: 'agy', id, cwd: fileUri(r.workspace_uris), title: clip(r.title || r.preview) || id, created: 0, updated: num(r.last_modified_time), size, locator: size ? t : '', app });
|
|
411
|
+
}
|
|
412
|
+
return out;
|
|
413
|
+
}
|
|
414
|
+
finally {
|
|
415
|
+
d.close();
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
const agy = {
|
|
419
|
+
vendor: 'agy',
|
|
420
|
+
async list({ stores }) {
|
|
421
|
+
// The desktop app's store is read too (where people mostly use Antigravity); an id kept by both is listed once, newest copy.
|
|
422
|
+
const all = [...await agyList(stores.agy, 'Antigravity CLI'), ...(stores.agyDesktop ? await agyList(stores.agyDesktop, 'Antigravity') : [])];
|
|
423
|
+
const byId = new Map();
|
|
424
|
+
for (const s of all) {
|
|
425
|
+
const seen = byId.get(s.id);
|
|
426
|
+
if (!seen || s.updated > seen.updated)
|
|
427
|
+
byId.set(s.id, s);
|
|
428
|
+
}
|
|
429
|
+
return [...byId.values()];
|
|
430
|
+
},
|
|
431
|
+
async read(ref, _ctx, opts = {}) {
|
|
432
|
+
if (!ref.locator)
|
|
433
|
+
throw new Error('agy recorded no readable transcript for this conversation (only its summary).');
|
|
434
|
+
const turns = [];
|
|
435
|
+
await eachJson(ref.locator, (s) => {
|
|
436
|
+
const at = s.created_at ?? null;
|
|
437
|
+
if (s.type === 'USER_INPUT' && s.content) {
|
|
438
|
+
const text = agyRequest(String(s.content));
|
|
439
|
+
if (text)
|
|
440
|
+
turns.push({ role: 'user', text, at });
|
|
441
|
+
}
|
|
442
|
+
else if (s.type === 'PLANNER_RESPONSE') {
|
|
443
|
+
if (s.thinking)
|
|
444
|
+
turns.push({ role: 'assistant', text: '', thinking: true, at });
|
|
445
|
+
if (s.content)
|
|
446
|
+
turns.push({ role: 'assistant', text: s.content, at });
|
|
447
|
+
for (const c of s.tool_calls ?? [])
|
|
448
|
+
turns.push({ role: 'assistant', text: '', tool: c.name, input: c.args, at });
|
|
449
|
+
}
|
|
450
|
+
else if (s.type === 'GENERIC' && s.content)
|
|
451
|
+
turns.push({ role: 'tool', text: '', output: kept(String(s.content)), at });
|
|
452
|
+
else if (s.type === 'CHECKPOINT')
|
|
453
|
+
turns.push({ role: 'system', text: '[conversation checkpoint]', compaction: true, at });
|
|
454
|
+
}, opts);
|
|
455
|
+
return turns;
|
|
456
|
+
},
|
|
457
|
+
resumeArgs: (id) => ['--conversation', id],
|
|
458
|
+
};
|
|
459
|
+
/* ------------------------------------------------------------------ opencode */
|
|
460
|
+
/** opencode's own export of a session (its supported read path), checked to be the session asked for. */
|
|
461
|
+
export async function exportOpencodeSession(id, { run }, env) {
|
|
462
|
+
const sid = safeSessionId(id);
|
|
463
|
+
if (!sid)
|
|
464
|
+
throw new Error('Invalid opencode session id.');
|
|
465
|
+
const text = await run('opencode', ['export', sid], { env, timeoutMs: 120_000 });
|
|
466
|
+
const json = JSON.parse(text.slice(text.indexOf('{')));
|
|
467
|
+
if (json.info?.id !== sid || !Array.isArray(json.messages))
|
|
468
|
+
throw new Error('opencode export returned a different session.');
|
|
469
|
+
return json;
|
|
470
|
+
}
|
|
471
|
+
const opencode = {
|
|
472
|
+
vendor: 'opencode',
|
|
473
|
+
async list({ stores }) {
|
|
474
|
+
// 🔴 `opencode session list` covers only the CURRENT project, so the machine-wide list is read from its database, read-only.
|
|
475
|
+
// Transcripts are still read through `opencode export`, its supported path.
|
|
476
|
+
const path = join(stores.opencode, 'opencode.db');
|
|
477
|
+
if (!existsSync(path))
|
|
478
|
+
return [];
|
|
479
|
+
const d = await openReadOnly(path);
|
|
480
|
+
try {
|
|
481
|
+
const rows = d.prepare('SELECT id, directory, title, time_created, time_updated, parent_id FROM session WHERE time_archived IS NULL AND parent_id IS NULL ORDER BY time_updated DESC').all();
|
|
482
|
+
return rows.map((r) => ({ vendor: 'opencode', id: safeSessionId(r.id) ?? '', cwd: r.directory ?? null, title: clip(r.title) || r.id,
|
|
483
|
+
created: num(r.time_created), updated: num(r.time_updated), size: 0, locator: r.id })).filter((s) => s.id);
|
|
484
|
+
}
|
|
485
|
+
finally {
|
|
486
|
+
d.close();
|
|
487
|
+
}
|
|
488
|
+
},
|
|
489
|
+
async read(ref, ctx) {
|
|
490
|
+
const j = await exportOpencodeSession(ref.id, ctx);
|
|
491
|
+
const turns = [];
|
|
492
|
+
for (const m of j.messages ?? []) {
|
|
493
|
+
const role = m.info?.role, at = m.info?.time?.created ? new Date(m.info.time.created).toISOString() : null;
|
|
494
|
+
for (const p of m.parts ?? []) {
|
|
495
|
+
if (p.type === 'text' && p.text && !p.synthetic)
|
|
496
|
+
turns.push({ role: role === 'assistant' ? 'assistant' : 'user', text: p.text, at });
|
|
497
|
+
else if (p.type === 'reasoning')
|
|
498
|
+
turns.push({ role: 'assistant', text: '', thinking: true, at });
|
|
499
|
+
else if (p.type === 'tool') {
|
|
500
|
+
turns.push({ role: 'assistant', text: '', tool: p.tool, callId: p.callID, input: p.state?.input, at });
|
|
501
|
+
if (p.state?.output != null)
|
|
502
|
+
turns.push({ role: 'tool', text: '', callId: p.callID, output: kept(String(p.state.output)), at });
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
return turns;
|
|
507
|
+
},
|
|
508
|
+
resumeArgs: (id) => ['--session', id],
|
|
509
|
+
};
|
|
510
|
+
/* ------------------------------------------------------------------ XENO agent */
|
|
511
|
+
const xenoAgent = {
|
|
512
|
+
vendor: 'XENO agent',
|
|
513
|
+
async list({ stores }) {
|
|
514
|
+
const root = join(stores.xenoAgent, 'sessions');
|
|
515
|
+
if (!existsSync(root))
|
|
516
|
+
return [];
|
|
517
|
+
const out = [];
|
|
518
|
+
for (const n of readdirSync(root)) {
|
|
519
|
+
const d = join(root, n), t = join(d, 'transcript.jsonl');
|
|
520
|
+
try {
|
|
521
|
+
const m = JSON.parse(readFileSync(join(d, 'meta.json'), 'utf8'));
|
|
522
|
+
const id = safeSessionId(m.id ?? n);
|
|
523
|
+
if (!id || !m.messageCount)
|
|
524
|
+
continue;
|
|
525
|
+
const st = statSync(t);
|
|
526
|
+
out.push({ vendor: 'XENO agent', id, cwd: m.workingDirectory ?? null, title: clip(m.name || m.title) || id, created: num(m.createdAt), updated: num(m.lastActivity ?? m.updatedAt) || st.mtimeMs, size: st.size, locator: t });
|
|
527
|
+
}
|
|
528
|
+
catch { /* not a session */ }
|
|
529
|
+
}
|
|
530
|
+
return out;
|
|
531
|
+
},
|
|
532
|
+
async read(ref, _ctx, opts = {}) {
|
|
533
|
+
const turns = [];
|
|
534
|
+
await eachJson(ref.locator, (e) => {
|
|
535
|
+
const d = e.data ?? {}, at = e.timestamp ?? null;
|
|
536
|
+
if (e.type === 'user_message')
|
|
537
|
+
turns.push({ role: 'user', text: blocksText(d.content), at });
|
|
538
|
+
else if (e.type === 'assistant_message') {
|
|
539
|
+
const t = blocksText(d.content);
|
|
540
|
+
if (t)
|
|
541
|
+
turns.push({ role: 'assistant', text: t, at });
|
|
542
|
+
}
|
|
543
|
+
else if (e.type === 'tool_call')
|
|
544
|
+
turns.push({ role: 'assistant', text: '', tool: d.toolName, callId: d.id ?? e.id, input: d.input, at });
|
|
545
|
+
else if (e.type === 'tool_result')
|
|
546
|
+
turns.push({ role: 'tool', text: '', callId: d.callId ?? d.id, output: kept(String(d.output ?? '')), at });
|
|
547
|
+
}, opts);
|
|
548
|
+
return turns;
|
|
549
|
+
},
|
|
550
|
+
resumeArgs: (id) => ['--resume', id],
|
|
551
|
+
};
|
|
552
|
+
/* ------------------------------------------------------------------ the contract */
|
|
553
|
+
const READERS = { 'Claude Code': claude, Codex: codex, agy, opencode, 'XENO agent': xenoAgent };
|
|
554
|
+
const readerOf = (vendor) => {
|
|
555
|
+
if (!VENDORS.includes(vendor))
|
|
556
|
+
throw new Error(`Unknown agent: ${vendor}. Known: ${VENDORS.join(', ')}.`);
|
|
557
|
+
return READERS[vendor];
|
|
558
|
+
};
|
|
559
|
+
/** One agent's sessions, newest first, or the reason they cannot be listed: a failure is a status, never an empty list. */
|
|
560
|
+
export async function listSessions(vendor, ctx) {
|
|
561
|
+
try {
|
|
562
|
+
return { vendor, sessions: (await readerOf(vendor).list(ctx)).filter((s) => s.id).sort((a, b) => b.updated - a.updated), error: null };
|
|
563
|
+
}
|
|
564
|
+
catch (e) {
|
|
565
|
+
return { vendor, sessions: [], error: clip(e instanceof Error ? e.message : String(e), 300) };
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Find a session in its agent's store at the moment of use. `id` may be the whole id or its first 8 or more characters; more than one
|
|
570
|
+
* match is refused, never guessed.
|
|
571
|
+
*/
|
|
572
|
+
export async function findSession(vendor, id, ctx) {
|
|
573
|
+
const want = String(id ?? '').trim();
|
|
574
|
+
if (!safeSessionId(want))
|
|
575
|
+
throw new Error('That is not a session id.');
|
|
576
|
+
const { sessions, error } = await listSessions(vendor, ctx);
|
|
577
|
+
if (error)
|
|
578
|
+
throw new Error(`${vendor} sessions cannot be read: ${error}`);
|
|
579
|
+
const exact = sessions.find((s) => s.id === want);
|
|
580
|
+
if (exact)
|
|
581
|
+
return exact;
|
|
582
|
+
const hits = want.length >= 8 ? sessions.filter((s) => s.id.toLowerCase().startsWith(want.toLowerCase())) : [];
|
|
583
|
+
if (hits.length === 1)
|
|
584
|
+
return hits[0];
|
|
585
|
+
if (hits.length > 1)
|
|
586
|
+
throw new Error(`${want} matches ${hits.length} ${vendor} sessions; give more of its id.`);
|
|
587
|
+
throw new Error(`${vendor} has no session ${want} on this machine.`);
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Find a session by its id alone, in whichever agent keeps it: ids are unique across agents (UUIDs, `ses_…`, `xeno-copy-…`), so the
|
|
591
|
+
* agent is read from the store that has it. A prefix matching sessions of two agents is refused, never guessed; an agent whose store
|
|
592
|
+
* cannot be read is named when nothing is found, since the session may be there.
|
|
593
|
+
*/
|
|
594
|
+
export async function findAnySession(id, ctx, { except } = {}) {
|
|
595
|
+
const want = String(id ?? '').trim();
|
|
596
|
+
if (!safeSessionId(want))
|
|
597
|
+
throw new Error('That is not a session id.');
|
|
598
|
+
const results = await Promise.all(VENDORS.filter((v) => v !== except).map((v) => listSessions(v, ctx)));
|
|
599
|
+
const all = results.flatMap((r) => r.sessions);
|
|
600
|
+
const exact = all.filter((s) => s.id === want);
|
|
601
|
+
if (exact.length === 1)
|
|
602
|
+
return exact[0];
|
|
603
|
+
const hits = exact.length ? exact : want.length >= 8 ? all.filter((s) => s.id.toLowerCase().startsWith(want.toLowerCase())) : [];
|
|
604
|
+
if (hits.length === 1)
|
|
605
|
+
return hits[0];
|
|
606
|
+
if (hits.length > 1)
|
|
607
|
+
throw new Error(`${want} matches ${hits.length} sessions (${hits.map((s) => `${s.vendor} ${s.id.slice(0, 12)}`).join(', ')}); give more of its id, or name the agent.`);
|
|
608
|
+
const unread = results.filter((r) => r.error).map((r) => `${r.vendor} (${r.error})`);
|
|
609
|
+
throw new Error(`No session ${want} on this machine.${unread.length ? ` These could not be read: ${unread.join('; ')}.` : ''}`);
|
|
610
|
+
}
|
|
611
|
+
/** The most recently used session whose folder is `cwd` (compared the way the OS does: case-insensitive on Windows), in any agent but `except`. */
|
|
612
|
+
export async function newestSessionIn(cwd, ctx, { except } = {}) {
|
|
613
|
+
const norm = (p) => { const r = p.replace(/[\\/]+$/, ''); return process.platform === 'win32' ? r.replace(/\//g, '\\').toLowerCase() : r; };
|
|
614
|
+
const here = norm(cwd);
|
|
615
|
+
const results = await Promise.all(VENDORS.filter((v) => v !== except).map((v) => listSessions(v, ctx)));
|
|
616
|
+
const mine = results.flatMap((r) => r.sessions).filter((s) => s.cwd && norm(s.cwd) === here).sort((a, b) => b.updated - a.updated);
|
|
617
|
+
return mine[0] ?? null;
|
|
618
|
+
}
|
|
619
|
+
/** A session's transcript as Turns. */
|
|
620
|
+
export function readSession(ref, ctx, o = {}) { return readerOf(ref.vendor).read(ref, ctx, o); }
|
|
621
|
+
/** A session's sub-agent conversations, for agents that keep them separately (Claude Code); none for the others. */
|
|
622
|
+
export async function readSubagents(ref) { const r = readerOf(ref.vendor); return r.subagents ? r.subagents(ref) : []; }
|
|
623
|
+
/** The words an agent's own command takes to reopen a session. */
|
|
624
|
+
export function resumeArgs(vendor, id) { const sid = safeSessionId(id); return sid ? readerOf(vendor).resumeArgs(sid) : []; }
|