@xenosystem/primitives 0.5.0 → 0.7.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.
Files changed (43) hide show
  1. package/README.md +17 -0
  2. package/dist/cjs/private-file/index.d.ts +41 -0
  3. package/dist/cjs/private-file/index.js +91 -0
  4. package/dist/cjs/sessions/cli.d.ts +2 -0
  5. package/dist/cjs/sessions/cli.js +152 -0
  6. package/dist/cjs/sessions/convert.d.ts +41 -0
  7. package/dist/cjs/sessions/convert.js +193 -0
  8. package/dist/cjs/sessions/index.d.ts +12 -0
  9. package/dist/cjs/sessions/index.js +37 -0
  10. package/dist/cjs/sessions/read.d.ts +36 -0
  11. package/dist/cjs/sessions/read.js +576 -0
  12. package/dist/cjs/sessions/run.d.ts +9 -0
  13. package/dist/cjs/sessions/run.js +60 -0
  14. package/dist/cjs/sessions/stores.d.ts +9 -0
  15. package/dist/cjs/sessions/stores.js +23 -0
  16. package/dist/cjs/sessions/transcript.d.ts +38 -0
  17. package/dist/cjs/sessions/transcript.js +105 -0
  18. package/dist/cjs/sessions/types.d.ts +61 -0
  19. package/dist/cjs/sessions/types.js +10 -0
  20. package/dist/cjs/sessions/write.d.ts +56 -0
  21. package/dist/cjs/sessions/write.js +216 -0
  22. package/dist/esm/private-file/index.d.ts +41 -0
  23. package/dist/esm/private-file/index.js +86 -0
  24. package/dist/esm/sessions/cli.d.ts +2 -0
  25. package/dist/esm/sessions/cli.js +150 -0
  26. package/dist/esm/sessions/convert.d.ts +41 -0
  27. package/dist/esm/sessions/convert.js +187 -0
  28. package/dist/esm/sessions/index.d.ts +12 -0
  29. package/dist/esm/sessions/index.js +12 -0
  30. package/dist/esm/sessions/read.d.ts +36 -0
  31. package/dist/esm/sessions/read.js +565 -0
  32. package/dist/esm/sessions/run.d.ts +9 -0
  33. package/dist/esm/sessions/run.js +55 -0
  34. package/dist/esm/sessions/stores.d.ts +9 -0
  35. package/dist/esm/sessions/stores.js +20 -0
  36. package/dist/esm/sessions/transcript.d.ts +38 -0
  37. package/dist/esm/sessions/transcript.js +99 -0
  38. package/dist/esm/sessions/types.d.ts +61 -0
  39. package/dist/esm/sessions/types.js +7 -0
  40. package/dist/esm/sessions/write.d.ts +56 -0
  41. package/dist/esm/sessions/write.js +208 -0
  42. package/native/win32-x64/process.node +0 -0
  43. package/package.json +24 -3
@@ -0,0 +1,565 @@
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
+ const num = (v) => { const n = typeof v === 'number' ? v : Date.parse(String(v ?? '')); return Number.isFinite(n) ? n : 0; };
21
+ async function openReadOnly(path) {
22
+ const { DatabaseSync } = await import('node:sqlite');
23
+ return new DatabaseSync(path, { readOnly: true });
24
+ }
25
+ function head(path, max = 65536) {
26
+ const fd = openSync(path, 'r');
27
+ try {
28
+ const b = Buffer.alloc(max);
29
+ const n = readSync(fd, b, 0, max, 0);
30
+ return b.subarray(0, n).toString('utf8');
31
+ }
32
+ finally {
33
+ closeSync(fd);
34
+ }
35
+ }
36
+ /** Each JSON line of a file, streamed and bounded: a line over 8 MiB (a pasted file, an image) is skipped rather than parsed. */
37
+ async function eachJson(path, fn, { maxBytes = Infinity } = {}) {
38
+ const rl = createInterface({ input: createReadStream(path, maxBytes === Infinity ? {} : { end: maxBytes - 1 }), crlfDelay: Infinity });
39
+ for await (const line of rl) {
40
+ if (!line.trim() || line.length > LINE_CAP)
41
+ continue;
42
+ let o;
43
+ try {
44
+ o = JSON.parse(line);
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ if (fn(o) === false)
50
+ break;
51
+ }
52
+ rl.close();
53
+ }
54
+ /** The text of an Anthropic-style content array. */
55
+ 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') : '';
56
+ /* ------------------------------------------------------------------ Claude Code */
57
+ /**
58
+ * Title, folder and first time from the head of a Claude transcript. 🔴 Two real shapes put the first turn beyond a 64 KB parse
59
+ * (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
60
+ * 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
61
+ * file that shows no turn gets one wider pass.
62
+ */
63
+ function claudeHead(path, size = Infinity) {
64
+ const first = claudeHeadIn(head(path));
65
+ return first.hasTurn || size <= 65536 ? first : claudeHeadIn(head(path, Math.min(size, 4 << 20)));
66
+ }
67
+ function claudeHeadIn(text) {
68
+ let cwd = null, title = '', created = 0, hasTurn = false;
69
+ for (const line of text.split('\n')) {
70
+ let r;
71
+ try {
72
+ r = JSON.parse(line);
73
+ }
74
+ catch {
75
+ const pre = line.slice(0, 8192);
76
+ if (/"type":"(user|assistant)"/.test(pre) && !/"isSidechain":true/.test(pre))
77
+ hasTurn = true;
78
+ if (!cwd) {
79
+ const m = /"cwd":"((?:[^"\\]|\\.)*)"/.exec(pre);
80
+ if (m) {
81
+ try {
82
+ cwd = JSON.parse(`"${m[1]}"`);
83
+ }
84
+ catch { /* not a string */ }
85
+ }
86
+ }
87
+ if (cwd && title && created && hasTurn)
88
+ break;
89
+ continue;
90
+ }
91
+ if (!cwd && typeof r.cwd === 'string')
92
+ cwd = r.cwd;
93
+ if (!created && r.timestamp)
94
+ created = num(r.timestamp);
95
+ if (r.type === 'custom-title' || r.type === 'ai-title' || r.type === 'summary')
96
+ title = clip(r.customTitle ?? r.aiTitle ?? r.title ?? r.summary) || title;
97
+ if (r.type === 'user' || r.type === 'assistant')
98
+ hasTurn = true;
99
+ if (!title && r.type === 'user' && !r.isMeta && !r.isSidechain) {
100
+ const t = blocksText(r.message?.content);
101
+ if (t && !/^\s*</.test(t))
102
+ title = clip(t);
103
+ }
104
+ // 🔴 `hasTurn` is part of the stop condition: without it a RENAMED session stopped early and was dropped as turnless
105
+ // (measured 2026-09-29: 8 real sessions, up to 482 MB, invisible).
106
+ if (cwd && title && created && hasTurn)
107
+ break;
108
+ }
109
+ return { cwd, title, created, hasTurn };
110
+ }
111
+ const claude = {
112
+ vendor: 'Claude Code',
113
+ async list({ stores }) {
114
+ const root = join(stores.claude, 'projects');
115
+ if (!existsSync(root))
116
+ return [];
117
+ const out = [];
118
+ for (const p of readdirSync(root)) {
119
+ const pd = join(root, p);
120
+ let names;
121
+ try {
122
+ names = readdirSync(pd);
123
+ }
124
+ catch {
125
+ continue;
126
+ }
127
+ for (const n of names) {
128
+ if (!n.endsWith('.jsonl'))
129
+ continue;
130
+ const id = safeSessionId(n.slice(0, -6));
131
+ if (!id)
132
+ continue;
133
+ const path = join(pd, n);
134
+ let st;
135
+ try {
136
+ st = statSync(path);
137
+ }
138
+ catch {
139
+ continue;
140
+ }
141
+ if (!st.isFile() || st.size === 0)
142
+ continue;
143
+ const m = claudeHead(path, st.size);
144
+ if (!m.hasTurn)
145
+ continue;
146
+ 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 });
147
+ }
148
+ }
149
+ return out;
150
+ },
151
+ async read(ref, _ctx, opts = {}) {
152
+ const turns = [];
153
+ await eachJson(ref.locator, (r) => {
154
+ if (r.isSidechain)
155
+ return;
156
+ const at = r.timestamp ?? null, c = r.message?.content;
157
+ if (r.type === 'system' && r.subtype === 'compact_boundary') {
158
+ turns.push({ role: 'system', text: '[conversation compacted]', compaction: true, at });
159
+ return;
160
+ }
161
+ if (r.type === 'user') {
162
+ if (r.isCompactSummary) {
163
+ turns.push({ role: 'user', text: blocksText(c), compaction: true, at });
164
+ return;
165
+ }
166
+ if (typeof c === 'string') {
167
+ if (!r.isMeta)
168
+ turns.push({ role: 'user', text: c, at });
169
+ return;
170
+ }
171
+ for (const b of Array.isArray(c) ? c : []) {
172
+ if (b?.type === 'text' && !r.isMeta)
173
+ turns.push({ role: 'user', text: b.text, at });
174
+ else if (b?.type === 'tool_result')
175
+ turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: blocksText(b.content), at });
176
+ }
177
+ }
178
+ else if (r.type === 'assistant') {
179
+ for (const b of Array.isArray(c) ? c : []) {
180
+ if (b?.type === 'text')
181
+ turns.push({ role: 'assistant', text: b.text, at });
182
+ else if (b?.type === 'thinking' || b?.type === 'redacted_thinking')
183
+ turns.push({ role: 'assistant', text: '', thinking: true, at });
184
+ else if (b?.type === 'tool_use')
185
+ turns.push({ role: 'assistant', text: '', tool: b.name, callId: b.id, input: b.input, at });
186
+ }
187
+ }
188
+ }, opts);
189
+ return turns;
190
+ },
191
+ async subagents(ref) {
192
+ const dir = join(ref.locator.replace(/\.jsonl$/, ''), 'subagents');
193
+ if (!existsSync(dir))
194
+ return [];
195
+ const out = [];
196
+ for (const n of readdirSync(dir).filter((x) => x.endsWith('.jsonl')).sort()) {
197
+ const turns = [];
198
+ await eachJson(join(dir, n), (r) => {
199
+ const c = r.message?.content, at = r.timestamp ?? null;
200
+ if (r.type === 'user') {
201
+ const t = blocksText(c);
202
+ if (t && !r.isMeta)
203
+ turns.push({ role: 'user', text: t, at });
204
+ }
205
+ else if (r.type === 'assistant')
206
+ for (const b of Array.isArray(c) ? c : [])
207
+ if (b?.type === 'text')
208
+ turns.push({ role: 'assistant', text: b.text, at });
209
+ });
210
+ out.push({ name: n.replace(/\.jsonl$/, ''), turns });
211
+ }
212
+ return out;
213
+ },
214
+ resumeArgs: (id) => ['--resume', id],
215
+ };
216
+ /* ------------------------------------------------------------------ Codex */
217
+ async function codexScan(stores) {
218
+ const root = join(stores.codex, 'sessions');
219
+ if (!existsSync(root))
220
+ return [];
221
+ const out = [];
222
+ const walk = (d, depth = 0) => {
223
+ let es;
224
+ try {
225
+ es = readdirSync(d, { withFileTypes: true });
226
+ }
227
+ catch {
228
+ return;
229
+ }
230
+ for (const e of es) {
231
+ const p = join(d, e.name);
232
+ if (e.isDirectory() && depth < 3)
233
+ walk(p, depth + 1);
234
+ else if (e.isFile() && e.name.startsWith('rollout-') && e.name.endsWith('.jsonl')) {
235
+ try {
236
+ const meta = JSON.parse(head(p, 32768).split('\n')[0] ?? '{}')?.payload ?? {};
237
+ const id = safeSessionId(meta.id ?? meta.session_id);
238
+ if (!id)
239
+ continue;
240
+ const st = statSync(p);
241
+ out.push({ vendor: 'Codex', id, cwd: meta.cwd ?? null, title: id, created: num(meta.timestamp), updated: st.mtimeMs, size: st.size, locator: p });
242
+ }
243
+ catch { /* not a rollout */ }
244
+ }
245
+ }
246
+ };
247
+ walk(root);
248
+ return out;
249
+ }
250
+ const codex = {
251
+ vendor: 'Codex',
252
+ async list({ stores }) {
253
+ const h = stores.codex;
254
+ if (!existsSync(h))
255
+ return [];
256
+ // The thread index Codex keeps itself is the cheap path; the rollout scan is the fallback.
257
+ const db = join(h, 'state_5.sqlite');
258
+ if (existsSync(db)) {
259
+ try {
260
+ const d = await openReadOnly(db);
261
+ try {
262
+ 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();
263
+ const out = [];
264
+ for (const r of rows) {
265
+ const id = safeSessionId(r.id);
266
+ if (!id || !r.rollout_path)
267
+ continue;
268
+ let size = 0;
269
+ try {
270
+ size = statSync(r.rollout_path).size;
271
+ }
272
+ catch {
273
+ continue;
274
+ }
275
+ const secs = (v) => { const n = Number(v); return Number.isFinite(n) ? (n < 1e12 ? n * 1000 : n) : 0; };
276
+ 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 });
277
+ }
278
+ // A shared sessions folder holds rollouts another home wrote, which this home's index has not seen: list those too.
279
+ let shared = false;
280
+ try {
281
+ shared = lstatSync(join(h, 'sessions')).isSymbolicLink();
282
+ }
283
+ catch { /* no sessions folder */ }
284
+ if (shared) {
285
+ const known = new Set(out.map((s) => s.id));
286
+ for (const s of await codexScan(stores))
287
+ if (!known.has(s.id))
288
+ out.push(s);
289
+ }
290
+ return out;
291
+ }
292
+ finally {
293
+ d.close();
294
+ }
295
+ }
296
+ catch { /* locked or a different schema: scan the rollouts instead */ }
297
+ }
298
+ return codexScan(stores);
299
+ },
300
+ async read(ref, _ctx, opts = {}) {
301
+ const turns = [];
302
+ await eachJson(ref.locator, (l) => {
303
+ const p = l.payload ?? {}, at = l.timestamp ?? null;
304
+ if (l.type === 'compacted') {
305
+ turns.push({ role: 'system', text: '[conversation compacted]', compaction: true, at });
306
+ return;
307
+ }
308
+ // 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.
309
+ if (l.type === 'event_msg' && p.type === 'task_complete') {
310
+ for (let i = turns.length - 1; i >= 0; i--) {
311
+ const t = turns[i];
312
+ if (t.role === 'user' && !t.compaction)
313
+ break;
314
+ if (t.role === 'assistant' && t.text && !t.tool && !t.thinking) {
315
+ t.turnEnd = true;
316
+ break;
317
+ }
318
+ }
319
+ return;
320
+ }
321
+ if (l.type !== 'response_item')
322
+ return;
323
+ if (p.type === 'message') {
324
+ const t = (Array.isArray(p.content) ? p.content : []).map((c) => c?.text ?? '').filter(Boolean).join('\n');
325
+ if (!t || p.role === 'developer' || p.role === 'system')
326
+ return;
327
+ // Codex writes its own environment and instructions preamble as user messages.
328
+ if (p.role === 'user' && /^\s*<(environment_context|user_instructions|permissions instructions|INSTRUCTIONS)/i.test(t))
329
+ return;
330
+ turns.push({ role: p.role === 'assistant' ? 'assistant' : 'user', text: t, at });
331
+ }
332
+ else if (p.type === 'reasoning')
333
+ turns.push({ role: 'assistant', text: '', thinking: true, at });
334
+ else if (p.type === 'function_call' || p.type === 'custom_tool_call') {
335
+ let input = p.arguments ?? p.input;
336
+ try {
337
+ if (typeof input === 'string')
338
+ input = JSON.parse(input);
339
+ }
340
+ catch { /* keep as text */ }
341
+ turns.push({ role: 'assistant', text: '', tool: p.name, callId: p.call_id, input, at });
342
+ }
343
+ else if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') {
344
+ const o = typeof p.output === 'string' ? p.output : p.output?.content ?? JSON.stringify(p.output ?? '');
345
+ turns.push({ role: 'tool', text: '', callId: p.call_id, output: String(o), at });
346
+ }
347
+ }, opts);
348
+ return turns;
349
+ },
350
+ resumeArgs: (id) => ['resume', id],
351
+ };
352
+ /* ------------------------------------------------------------------ agy (Antigravity CLI) */
353
+ /** The first `file://` workspace in agy's stored list, as a path. */
354
+ function fileUri(v) {
355
+ const s = typeof v === 'string' ? v : Buffer.isBuffer(v) ? v.toString('utf8') : '';
356
+ const m = s.match(/file:\/\/\/?([^\s"',\]]+)/);
357
+ if (!m || !m[1])
358
+ return null;
359
+ let p = decodeURIComponent(m[1]);
360
+ if (/^[A-Za-z]:/.test(p) || /^[A-Za-z]%3A/i.test(m[1]))
361
+ p = p.replace(/\//g, '\\');
362
+ else
363
+ p = '/' + p.replace(/^\/+/, '');
364
+ return p;
365
+ }
366
+ /**
367
+ * What the person typed, out of agy's own wrapping. agy records every message as `<USER_REQUEST>…</USER_REQUEST>` followed by its own
368
+ * `<ADDITIONAL_METADATA>` block, and at times `<USER_SETTINGS_CHANGE>`: measured 2026-11-27, 232 of 232 messages on this machine.
369
+ */
370
+ export function agyRequest(content) {
371
+ const m = /<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(content);
372
+ return (m ? m[1] : content.replace(/<(ADDITIONAL_METADATA|USER_SETTINGS_CHANGE)>[\s\S]*?<\/\1>/g, '')).trim();
373
+ }
374
+ const agy = {
375
+ vendor: 'agy',
376
+ async list({ stores }) {
377
+ const h = stores.agy, db = join(h, 'conversation_summaries.db');
378
+ if (!existsSync(db))
379
+ return [];
380
+ const d = await openReadOnly(db);
381
+ try {
382
+ 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();
383
+ const out = [];
384
+ for (const r of rows) {
385
+ const id = safeSessionId(r.conversation_id);
386
+ if (!id)
387
+ continue;
388
+ const t = join(h, 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl');
389
+ let size = 0;
390
+ try {
391
+ size = statSync(t).size;
392
+ }
393
+ catch { /* summary only */ }
394
+ 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 : '' });
395
+ }
396
+ return out;
397
+ }
398
+ finally {
399
+ d.close();
400
+ }
401
+ },
402
+ async read(ref, _ctx, opts = {}) {
403
+ if (!ref.locator)
404
+ throw new Error('agy recorded no readable transcript for this conversation (only its summary).');
405
+ const turns = [];
406
+ await eachJson(ref.locator, (s) => {
407
+ const at = s.created_at ?? null;
408
+ if (s.type === 'USER_INPUT' && s.content) {
409
+ const text = agyRequest(String(s.content));
410
+ if (text)
411
+ turns.push({ role: 'user', text, at });
412
+ }
413
+ else if (s.type === 'PLANNER_RESPONSE') {
414
+ if (s.thinking)
415
+ turns.push({ role: 'assistant', text: '', thinking: true, at });
416
+ if (s.content)
417
+ turns.push({ role: 'assistant', text: s.content, at });
418
+ for (const c of s.tool_calls ?? [])
419
+ turns.push({ role: 'assistant', text: '', tool: c.name, input: c.args, at });
420
+ }
421
+ else if (s.type === 'GENERIC' && s.content)
422
+ turns.push({ role: 'tool', text: '', output: s.content, at });
423
+ else if (s.type === 'CHECKPOINT')
424
+ turns.push({ role: 'system', text: '[conversation checkpoint]', compaction: true, at });
425
+ }, opts);
426
+ return turns;
427
+ },
428
+ resumeArgs: (id) => ['--conversation', id],
429
+ };
430
+ /* ------------------------------------------------------------------ opencode */
431
+ /** opencode's own export of a session (its supported read path), checked to be the session asked for. */
432
+ export async function exportOpencodeSession(id, { run }, env) {
433
+ const sid = safeSessionId(id);
434
+ if (!sid)
435
+ throw new Error('Invalid opencode session id.');
436
+ const text = await run('opencode', ['export', sid], { env, timeoutMs: 120_000 });
437
+ const json = JSON.parse(text.slice(text.indexOf('{')));
438
+ if (json.info?.id !== sid || !Array.isArray(json.messages))
439
+ throw new Error('opencode export returned a different session.');
440
+ return json;
441
+ }
442
+ const opencode = {
443
+ vendor: 'opencode',
444
+ async list({ stores }) {
445
+ // 🔴 `opencode session list` covers only the CURRENT project, so the machine-wide list is read from its database, read-only.
446
+ // Transcripts are still read through `opencode export`, its supported path.
447
+ const path = join(stores.opencode, 'opencode.db');
448
+ if (!existsSync(path))
449
+ return [];
450
+ const d = await openReadOnly(path);
451
+ try {
452
+ 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();
453
+ return rows.map((r) => ({ vendor: 'opencode', id: safeSessionId(r.id) ?? '', cwd: r.directory ?? null, title: clip(r.title) || r.id,
454
+ created: num(r.time_created), updated: num(r.time_updated), size: 0, locator: r.id })).filter((s) => s.id);
455
+ }
456
+ finally {
457
+ d.close();
458
+ }
459
+ },
460
+ async read(ref, ctx) {
461
+ const j = await exportOpencodeSession(ref.id, ctx);
462
+ const turns = [];
463
+ for (const m of j.messages ?? []) {
464
+ const role = m.info?.role, at = m.info?.time?.created ? new Date(m.info.time.created).toISOString() : null;
465
+ for (const p of m.parts ?? []) {
466
+ if (p.type === 'text' && p.text && !p.synthetic)
467
+ turns.push({ role: role === 'assistant' ? 'assistant' : 'user', text: p.text, at });
468
+ else if (p.type === 'reasoning')
469
+ turns.push({ role: 'assistant', text: '', thinking: true, at });
470
+ else if (p.type === 'tool') {
471
+ turns.push({ role: 'assistant', text: '', tool: p.tool, callId: p.callID, input: p.state?.input, at });
472
+ if (p.state?.output != null)
473
+ turns.push({ role: 'tool', text: '', callId: p.callID, output: String(p.state.output), at });
474
+ }
475
+ }
476
+ }
477
+ return turns;
478
+ },
479
+ resumeArgs: (id) => ['--session', id],
480
+ };
481
+ /* ------------------------------------------------------------------ XENO agent */
482
+ const xenoAgent = {
483
+ vendor: 'XENO agent',
484
+ async list({ stores }) {
485
+ const root = join(stores.xenoAgent, 'sessions');
486
+ if (!existsSync(root))
487
+ return [];
488
+ const out = [];
489
+ for (const n of readdirSync(root)) {
490
+ const d = join(root, n), t = join(d, 'transcript.jsonl');
491
+ try {
492
+ const m = JSON.parse(readFileSync(join(d, 'meta.json'), 'utf8'));
493
+ const id = safeSessionId(m.id ?? n);
494
+ if (!id || !m.messageCount)
495
+ continue;
496
+ const st = statSync(t);
497
+ 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 });
498
+ }
499
+ catch { /* not a session */ }
500
+ }
501
+ return out;
502
+ },
503
+ async read(ref, _ctx, opts = {}) {
504
+ const turns = [];
505
+ await eachJson(ref.locator, (e) => {
506
+ const d = e.data ?? {}, at = e.timestamp ?? null;
507
+ if (e.type === 'user_message')
508
+ turns.push({ role: 'user', text: blocksText(d.content), at });
509
+ else if (e.type === 'assistant_message') {
510
+ const t = blocksText(d.content);
511
+ if (t)
512
+ turns.push({ role: 'assistant', text: t, at });
513
+ }
514
+ else if (e.type === 'tool_call')
515
+ turns.push({ role: 'assistant', text: '', tool: d.toolName, callId: d.id ?? e.id, input: d.input, at });
516
+ else if (e.type === 'tool_result')
517
+ turns.push({ role: 'tool', text: '', callId: d.callId ?? d.id, output: String(d.output ?? ''), at });
518
+ }, opts);
519
+ return turns;
520
+ },
521
+ resumeArgs: (id) => ['--resume', id],
522
+ };
523
+ /* ------------------------------------------------------------------ the contract */
524
+ const READERS = { 'Claude Code': claude, Codex: codex, agy, opencode, 'XENO agent': xenoAgent };
525
+ const readerOf = (vendor) => {
526
+ if (!VENDORS.includes(vendor))
527
+ throw new Error(`Unknown agent: ${vendor}. Known: ${VENDORS.join(', ')}.`);
528
+ return READERS[vendor];
529
+ };
530
+ /** One agent's sessions, newest first, or the reason they cannot be listed: a failure is a status, never an empty list. */
531
+ export async function listSessions(vendor, ctx) {
532
+ try {
533
+ return { vendor, sessions: (await readerOf(vendor).list(ctx)).filter((s) => s.id).sort((a, b) => b.updated - a.updated), error: null };
534
+ }
535
+ catch (e) {
536
+ return { vendor, sessions: [], error: clip(e instanceof Error ? e.message : String(e), 300) };
537
+ }
538
+ }
539
+ /**
540
+ * 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
541
+ * match is refused, never guessed.
542
+ */
543
+ export async function findSession(vendor, id, ctx) {
544
+ const want = String(id ?? '').trim();
545
+ if (!safeSessionId(want))
546
+ throw new Error('That is not a session id.');
547
+ const { sessions, error } = await listSessions(vendor, ctx);
548
+ if (error)
549
+ throw new Error(`${vendor} sessions cannot be read: ${error}`);
550
+ const exact = sessions.find((s) => s.id === want);
551
+ if (exact)
552
+ return exact;
553
+ const hits = want.length >= 8 ? sessions.filter((s) => s.id.toLowerCase().startsWith(want.toLowerCase())) : [];
554
+ if (hits.length === 1)
555
+ return hits[0];
556
+ if (hits.length > 1)
557
+ throw new Error(`${want} matches ${hits.length} ${vendor} sessions; give more of its id.`);
558
+ throw new Error(`${vendor} has no session ${want} on this machine.`);
559
+ }
560
+ /** A session's transcript as Turns. */
561
+ export function readSession(ref, ctx, o = {}) { return readerOf(ref.vendor).read(ref, ctx, o); }
562
+ /** A session's sub-agent conversations, for agents that keep them separately (Claude Code); none for the others. */
563
+ export async function readSubagents(ref) { const r = readerOf(ref.vendor); return r.subagents ? r.subagents(ref) : []; }
564
+ /** The words an agent's own command takes to reopen a session. */
565
+ export function resumeArgs(vendor, id) { const sid = safeSessionId(id); return sid ? readerOf(vendor).resumeArgs(sid) : []; }
@@ -0,0 +1,9 @@
1
+ import { type ChildProcess, type SpawnOptions } from 'node:child_process';
2
+ import type { Runner } from './types.ts';
3
+ /**
4
+ * Start an agent's own command without a shell. On Windows an npm-installed agent is a `.cmd` shim, which only cmd.exe can run: it is
5
+ * found on PATH and run through cmd.exe with every word quoted, and a word holding shell syntax is refused, never run.
6
+ */
7
+ export declare function spawnAgent(command: string, args: string[], options?: SpawnOptions): ChildProcess;
8
+ /** The default Runner: an agent's command, its standard output collected up to a limit; its diagnostics are never kept. */
9
+ export declare const runAgent: Runner;
@@ -0,0 +1,55 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { statSync } from 'node:fs';
3
+ import { delimiter, extname, join } from 'node:path';
4
+ /**
5
+ * Start an agent's own command without a shell. On Windows an npm-installed agent is a `.cmd` shim, which only cmd.exe can run: it is
6
+ * found on PATH and run through cmd.exe with every word quoted, and a word holding shell syntax is refused, never run.
7
+ */
8
+ export function spawnAgent(command, args, options = {}) {
9
+ if (!/^[a-z][a-z0-9-]*$/.test(command))
10
+ throw new Error('Invalid agent command name');
11
+ const env = options.env ?? process.env;
12
+ let executable = command;
13
+ if (process.platform === 'win32') {
14
+ outer: for (const dir of String(env.PATH ?? env.Path ?? '').split(delimiter).filter(Boolean)) {
15
+ for (const suffix of ['.exe', '.com', '.cmd', '.bat']) {
16
+ const path = join(dir, command + suffix);
17
+ try {
18
+ if (statSync(path).isFile()) {
19
+ executable = path;
20
+ break outer;
21
+ }
22
+ }
23
+ catch { /* next candidate */ }
24
+ }
25
+ }
26
+ if (/^\.(cmd|bat)$/i.test(extname(executable))) {
27
+ const words = [executable, ...args];
28
+ if (words.some((w) => /[%!^&|<>"\r\n\x00]/.test(w)))
29
+ throw new Error('Agent shim arguments contain shell syntax; no command was run.');
30
+ const line = words.map((w) => `"${w}"`).join(' ');
31
+ return spawn(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${line}"`], { ...options, shell: false, windowsVerbatimArguments: true });
32
+ }
33
+ }
34
+ return spawn(executable, args, { ...options, shell: false });
35
+ }
36
+ /** The default Runner: an agent's command, its standard output collected up to a limit; its diagnostics are never kept. */
37
+ export const runAgent = (command, args, { cwd, env, timeoutMs = 60_000, maxBytes = 256 << 20 } = {}) => new Promise((resolve, reject) => {
38
+ const child = spawnAgent(command, args, { cwd, env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
39
+ const chunks = [];
40
+ let bytes = 0, failed = false;
41
+ const fail = (e) => { if (failed)
42
+ return; failed = true; child.kill(); reject(e); };
43
+ const timer = setTimeout(() => fail(new Error(`${command} timed out`)), timeoutMs);
44
+ child.stdout?.on('data', (b) => { bytes += b.length; if (bytes > maxBytes)
45
+ fail(new Error(`${command} output exceeds its limit`));
46
+ else
47
+ chunks.push(b); });
48
+ child.stderr?.on('data', () => { });
49
+ child.on('error', (e) => { clearTimeout(timer); fail(e); });
50
+ child.on('close', (code) => { clearTimeout(timer); if (failed)
51
+ return; if (code !== 0)
52
+ reject(new Error(`${command} exited ${code}`));
53
+ else
54
+ resolve(Buffer.concat(chunks).toString('utf8')); });
55
+ });
@@ -0,0 +1,9 @@
1
+ import type { Stores } from './types.ts';
2
+ /**
3
+ * Each agent's own default place for its sessions, by the same rules each agent applies itself: Claude Code honours CLAUDE_CONFIG_DIR,
4
+ * Codex CODEX_HOME, opencode XDG_DATA_HOME, the XENO agent XENO_AGENT_HOME. These are the AGENTS' stores, read where each agent writes
5
+ * them, never XENO's own layout; a product that runs agents in their own profiles passes those folders instead
6
+ * (`{ ...defaultStores(), claude: profileFolder }`).
7
+ * @param home the user folder they are under; the current user's by default (from the dirs resolver).
8
+ */
9
+ export declare function defaultStores(home?: string, env?: Readonly<Record<string, string | undefined>>): Stores;
@@ -0,0 +1,20 @@
1
+ import { join } from 'node:path';
2
+ import { hostEnv, hostHome } from "../dirs/host.js";
3
+ /**
4
+ * Each agent's own default place for its sessions, by the same rules each agent applies itself: Claude Code honours CLAUDE_CONFIG_DIR,
5
+ * Codex CODEX_HOME, opencode XDG_DATA_HOME, the XENO agent XENO_AGENT_HOME. These are the AGENTS' stores, read where each agent writes
6
+ * them, never XENO's own layout; a product that runs agents in their own profiles passes those folders instead
7
+ * (`{ ...defaultStores(), claude: profileFolder }`).
8
+ * @param home the user folder they are under; the current user's by default (from the dirs resolver).
9
+ */
10
+ export function defaultStores(home = hostHome(), env = hostEnv()) {
11
+ return {
12
+ claude: env.CLAUDE_CONFIG_DIR || join(home, '.claude'),
13
+ codex: env.CODEX_HOME || join(home, '.codex'),
14
+ agy: join(home, '.gemini', 'antigravity-cli'),
15
+ // xeno-dirs-allow: opencode's own data folder, by opencode's own XDG rule; read where opencode writes it, never a XENO path
16
+ opencode: join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'opencode'),
17
+ // xeno-dirs-allow: the XENO agent still writes its sessions here (ADOPTION.md: xeno-agent-cli sessions "not moved"); read where they are until it moves them to agents/sessions
18
+ xenoAgent: env.XENO_AGENT_HOME || join(home, '.xeno-agent'),
19
+ };
20
+ }