@xenosystem/primitives 0.7.0 → 0.8.1

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 (37) hide show
  1. package/README.md +14 -3
  2. package/dist/cjs/sessions/cli.js +71 -27
  3. package/dist/cjs/sessions/convert.d.ts +12 -9
  4. package/dist/cjs/sessions/convert.js +37 -42
  5. package/dist/cjs/sessions/index.d.ts +5 -3
  6. package/dist/cjs/sessions/index.js +13 -1
  7. package/dist/cjs/sessions/layers.d.ts +28 -0
  8. package/dist/cjs/sessions/layers.js +126 -0
  9. package/dist/cjs/sessions/owned.d.ts +5 -0
  10. package/dist/cjs/sessions/owned.js +38 -0
  11. package/dist/cjs/sessions/read.d.ts +17 -0
  12. package/dist/cjs/sessions/read.js +92 -30
  13. package/dist/cjs/sessions/stores.js +1 -0
  14. package/dist/cjs/sessions/transcript.d.ts +6 -1
  15. package/dist/cjs/sessions/transcript.js +30 -18
  16. package/dist/cjs/sessions/types.d.ts +17 -0
  17. package/dist/cjs/sessions/write.d.ts +11 -1
  18. package/dist/cjs/sessions/write.js +25 -5
  19. package/dist/esm/sessions/cli.js +72 -28
  20. package/dist/esm/sessions/convert.d.ts +12 -9
  21. package/dist/esm/sessions/convert.js +33 -40
  22. package/dist/esm/sessions/index.d.ts +5 -3
  23. package/dist/esm/sessions/index.js +5 -3
  24. package/dist/esm/sessions/layers.d.ts +28 -0
  25. package/dist/esm/sessions/layers.js +121 -0
  26. package/dist/esm/sessions/owned.d.ts +5 -0
  27. package/dist/esm/sessions/owned.js +33 -0
  28. package/dist/esm/sessions/read.d.ts +17 -0
  29. package/dist/esm/sessions/read.js +89 -29
  30. package/dist/esm/sessions/stores.js +1 -0
  31. package/dist/esm/sessions/transcript.d.ts +6 -1
  32. package/dist/esm/sessions/transcript.js +30 -18
  33. package/dist/esm/sessions/types.d.ts +17 -0
  34. package/dist/esm/sessions/write.d.ts +11 -1
  35. package/dist/esm/sessions/write.js +23 -4
  36. package/native/win32-x64/process.node +0 -0
  37. package/package.json +1 -1
@@ -12,11 +12,18 @@ import { closeSync, createReadStream, existsSync, lstatSync, openSync, readdirSy
12
12
  import { join } from 'node:path';
13
13
  import { createInterface } from 'node:readline';
14
14
  import { VENDORS } from "./types.js";
15
+ import { claudeProjectsDir } from "./owned.js";
15
16
  const TITLE_CAP = 160, LINE_CAP = 8 << 20;
16
17
  const SAFE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
17
18
  /** A session id an agent's command can take as one word, or null. */
18
19
  export const safeSessionId = (id) => typeof id === 'string' && SAFE_ID.test(id) ? id : null;
19
20
  const clip = (s, n = TITLE_CAP) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
21
+ /**
22
+ * 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
23
+ * 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).
24
+ */
25
+ export const OUTPUT_KEPT = 65536;
26
+ const kept = (s) => s.length > OUTPUT_KEPT ? `${s.slice(0, OUTPUT_KEPT)}\n… [${s.length - OUTPUT_KEPT} more characters not read]` : s;
20
27
  const num = (v) => { const n = typeof v === 'number' ? v : Date.parse(String(v ?? '')); return Number.isFinite(n) ? n : 0; };
21
28
  async function openReadOnly(path) {
22
29
  const { DatabaseSync } = await import('node:sqlite');
@@ -111,7 +118,7 @@ function claudeHeadIn(text) {
111
118
  const claude = {
112
119
  vendor: 'Claude Code',
113
120
  async list({ stores }) {
114
- const root = join(stores.claude, 'projects');
121
+ const root = claudeProjectsDir(stores);
115
122
  if (!existsSync(root))
116
123
  return [];
117
124
  const out = [];
@@ -154,6 +161,17 @@ const claude = {
154
161
  if (r.isSidechain)
155
162
  return;
156
163
  const at = r.timestamp ?? null, c = r.message?.content;
164
+ // šŸ”“ A message that arrives while a turn is running is kept as a `queued_command` attachment, not a user record (measured
165
+ // 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
166
+ // were also user records). Skipping them dropped the person's own words from every copy.
167
+ const q = r.type === 'attachment' && r.attachment?.type === 'queued_command' ? r.attachment : null;
168
+ if (q) {
169
+ const text = typeof q.prompt === 'string' ? q.prompt : blocksText(q.prompt);
170
+ const last = turns[turns.length - 1];
171
+ if (text.trim() && !(last?.role === 'user' && last.text === text))
172
+ turns.push({ role: 'user', text, at: q.timestamp ?? at, ...(q.origin?.kind === 'human' ? {} : { from: q.origin?.kind === 'peer' ? 'peer' : 'harness' }) });
173
+ return;
174
+ }
157
175
  if (r.type === 'system' && r.subtype === 'compact_boundary') {
158
176
  turns.push({ role: 'system', text: '[conversation compacted]', compaction: true, at });
159
177
  return;
@@ -172,7 +190,7 @@ const claude = {
172
190
  if (b?.type === 'text' && !r.isMeta)
173
191
  turns.push({ role: 'user', text: b.text, at });
174
192
  else if (b?.type === 'tool_result')
175
- turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: blocksText(b.content), at });
193
+ turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: kept(blocksText(b.content)), at });
176
194
  }
177
195
  }
178
196
  else if (r.type === 'assistant') {
@@ -342,7 +360,7 @@ const codex = {
342
360
  }
343
361
  else if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') {
344
362
  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 });
363
+ turns.push({ role: 'tool', text: '', callId: p.call_id, output: kept(String(o)), at });
346
364
  }
347
365
  }, opts);
348
366
  return turns;
@@ -371,33 +389,45 @@ export function agyRequest(content) {
371
389
  const m = /<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(content);
372
390
  return (m ? m[1] : content.replace(/<(ADDITIONAL_METADATA|USER_SETTINGS_CHANGE)>[\s\S]*?<\/\1>/g, '')).trim();
373
391
  }
392
+ /** One Antigravity data folder's conversations: the CLI's and the desktop app's share a layout. */
393
+ async function agyList(h, app) {
394
+ const db = join(h, 'conversation_summaries.db');
395
+ if (!existsSync(db))
396
+ return [];
397
+ const d = await openReadOnly(db);
398
+ try {
399
+ 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();
400
+ const out = [];
401
+ for (const r of rows) {
402
+ const id = safeSessionId(r.conversation_id);
403
+ if (!id)
404
+ continue;
405
+ const t = join(h, 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl');
406
+ let size = 0;
407
+ try {
408
+ size = statSync(t).size;
409
+ }
410
+ catch { /* summary only */ }
411
+ 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 });
412
+ }
413
+ return out;
414
+ }
415
+ finally {
416
+ d.close();
417
+ }
418
+ }
374
419
  const agy = {
375
420
  vendor: 'agy',
376
421
  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();
422
+ // The desktop app's store is read too (where people mostly use Antigravity); an id kept by both is listed once, newest copy.
423
+ const all = [...await agyList(stores.agy, 'Antigravity CLI'), ...(stores.agyDesktop ? await agyList(stores.agyDesktop, 'Antigravity') : [])];
424
+ const byId = new Map();
425
+ for (const s of all) {
426
+ const seen = byId.get(s.id);
427
+ if (!seen || s.updated > seen.updated)
428
+ byId.set(s.id, s);
400
429
  }
430
+ return [...byId.values()];
401
431
  },
402
432
  async read(ref, _ctx, opts = {}) {
403
433
  if (!ref.locator)
@@ -419,7 +449,7 @@ const agy = {
419
449
  turns.push({ role: 'assistant', text: '', tool: c.name, input: c.args, at });
420
450
  }
421
451
  else if (s.type === 'GENERIC' && s.content)
422
- turns.push({ role: 'tool', text: '', output: s.content, at });
452
+ turns.push({ role: 'tool', text: '', output: kept(String(s.content)), at });
423
453
  else if (s.type === 'CHECKPOINT')
424
454
  turns.push({ role: 'system', text: '[conversation checkpoint]', compaction: true, at });
425
455
  }, opts);
@@ -470,7 +500,7 @@ const opencode = {
470
500
  else if (p.type === 'tool') {
471
501
  turns.push({ role: 'assistant', text: '', tool: p.tool, callId: p.callID, input: p.state?.input, at });
472
502
  if (p.state?.output != null)
473
- turns.push({ role: 'tool', text: '', callId: p.callID, output: String(p.state.output), at });
503
+ turns.push({ role: 'tool', text: '', callId: p.callID, output: kept(String(p.state.output)), at });
474
504
  }
475
505
  }
476
506
  }
@@ -514,7 +544,7 @@ const xenoAgent = {
514
544
  else if (e.type === 'tool_call')
515
545
  turns.push({ role: 'assistant', text: '', tool: d.toolName, callId: d.id ?? e.id, input: d.input, at });
516
546
  else if (e.type === 'tool_result')
517
- turns.push({ role: 'tool', text: '', callId: d.callId ?? d.id, output: String(d.output ?? ''), at });
547
+ turns.push({ role: 'tool', text: '', callId: d.callId ?? d.id, output: kept(String(d.output ?? '')), at });
518
548
  }, opts);
519
549
  return turns;
520
550
  },
@@ -557,6 +587,36 @@ export async function findSession(vendor, id, ctx) {
557
587
  throw new Error(`${want} matches ${hits.length} ${vendor} sessions; give more of its id.`);
558
588
  throw new Error(`${vendor} has no session ${want} on this machine.`);
559
589
  }
590
+ /**
591
+ * Find a session by its id alone, in whichever agent keeps it: ids are unique across agents (UUIDs, `ses_…`, `xeno-copy-…`), so the
592
+ * agent is read from the store that has it. A prefix matching sessions of two agents is refused, never guessed; an agent whose store
593
+ * cannot be read is named when nothing is found, since the session may be there.
594
+ */
595
+ export async function findAnySession(id, ctx, { except } = {}) {
596
+ const want = String(id ?? '').trim();
597
+ if (!safeSessionId(want))
598
+ throw new Error('That is not a session id.');
599
+ const results = await Promise.all(VENDORS.filter((v) => v !== except).map((v) => listSessions(v, ctx)));
600
+ const all = results.flatMap((r) => r.sessions);
601
+ const exact = all.filter((s) => s.id === want);
602
+ if (exact.length === 1)
603
+ return exact[0];
604
+ const hits = exact.length ? exact : want.length >= 8 ? all.filter((s) => s.id.toLowerCase().startsWith(want.toLowerCase())) : [];
605
+ if (hits.length === 1)
606
+ return hits[0];
607
+ if (hits.length > 1)
608
+ 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.`);
609
+ const unread = results.filter((r) => r.error).map((r) => `${r.vendor} (${r.error})`);
610
+ throw new Error(`No session ${want} on this machine.${unread.length ? ` These could not be read: ${unread.join('; ')}.` : ''}`);
611
+ }
612
+ /** The most recently used session whose folder is `cwd` (compared the way the OS does: case-insensitive on Windows), in any agent but `except`. */
613
+ export async function newestSessionIn(cwd, ctx, { except } = {}) {
614
+ const norm = (p) => { const r = p.replace(/[\\/]+$/, ''); return process.platform === 'win32' ? r.replace(/\//g, '\\').toLowerCase() : r; };
615
+ const here = norm(cwd);
616
+ const results = await Promise.all(VENDORS.filter((v) => v !== except).map((v) => listSessions(v, ctx)));
617
+ const mine = results.flatMap((r) => r.sessions).filter((s) => s.cwd && norm(s.cwd) === here).sort((a, b) => b.updated - a.updated);
618
+ return mine[0] ?? null;
619
+ }
560
620
  /** A session's transcript as Turns. */
561
621
  export function readSession(ref, ctx, o = {}) { return readerOf(ref.vendor).read(ref, ctx, o); }
562
622
  /** A session's sub-agent conversations, for agents that keep them separately (Claude Code); none for the others. */
@@ -12,6 +12,7 @@ export function defaultStores(home = hostHome(), env = hostEnv()) {
12
12
  claude: env.CLAUDE_CONFIG_DIR || join(home, '.claude'),
13
13
  codex: env.CODEX_HOME || join(home, '.codex'),
14
14
  agy: join(home, '.gemini', 'antigravity-cli'),
15
+ agyDesktop: join(home, '.gemini', 'antigravity'),
15
16
  // xeno-dirs-allow: opencode's own data folder, by opencode's own XDG rule; read where opencode writes it, never a XENO path
16
17
  opencode: join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'opencode'),
17
18
  // 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
@@ -26,6 +26,8 @@ export interface Report {
26
26
  total: number;
27
27
  subagents: number;
28
28
  subagentTurns: number;
29
+ /** The earliest messages left out of the copy itself because the conversation is over the copy limit (the end is always kept). */
30
+ omitted: number;
29
31
  }
30
32
  export interface Transcript {
31
33
  messages: Message[];
@@ -33,6 +35,9 @@ export interface Transcript {
33
35
  }
34
36
  export declare const OUTPUT_CAP = 4000, TOTAL_CAP = 1500000;
35
37
  export declare const cap: (s: string, n: number) => string;
36
- export declare function toTranscript(turns: Turn[], subagents?: Subagent[]): Transcript;
38
+ /** @param opts.fullRecord where the whole conversation is kept, named in the copy when its earliest messages are left out. */
39
+ export declare function toTranscript(turns: Turn[], subagents?: Subagent[], opts?: {
40
+ fullRecord?: string;
41
+ }): Transcript;
37
42
  /** What the move loses, in plain words, for a person to read before it runs. */
38
43
  export declare function losses(report: Report, target: string, handoff: boolean): string[];
@@ -8,9 +8,10 @@ catch {
8
8
  return String(v);
9
9
  } };
10
10
  export const cap = (s, n) => s.length > n ? `${s.slice(0, n)}\n… [${s.length - n} more characters not copied]` : s;
11
- export function toTranscript(turns, subagents = []) {
11
+ /** @param opts.fullRecord where the whole conversation is kept, named in the copy when its earliest messages are left out. */
12
+ export function toTranscript(turns, subagents = [], opts = {}) {
12
13
  const msgs = [];
13
- const report = { userTurns: 0, assistantTurns: 0, toolCalls: 0, toolResults: 0, thinkingDropped: 0, compactions: 0, truncated: 0, total: 0, subagents: subagents.length, subagentTurns: 0 };
14
+ const report = { userTurns: 0, assistantTurns: 0, toolCalls: 0, toolResults: 0, thinkingDropped: 0, compactions: 0, truncated: 0, total: 0, subagents: subagents.length, subagentTurns: 0, omitted: 0 };
14
15
  const outputs = new Map();
15
16
  const calls = new Set();
16
17
  for (const t of turns) {
@@ -28,13 +29,19 @@ export function toTranscript(turns, subagents = []) {
28
29
  else
29
30
  msgs.push({ role, text, at: at ?? null });
30
31
  };
32
+ let inCompaction = false;
31
33
  for (const t of turns) {
32
34
  if (t.thinking) {
33
35
  report.thinkingDropped++;
34
36
  continue;
35
37
  }
38
+ // Claude Code records one compaction twice, a boundary and then its summary: counted once (a real session read 128 for 62).
39
+ if (!t.compaction)
40
+ inCompaction = false;
36
41
  if (t.compaction) {
37
- report.compactions++;
42
+ if (!inCompaction)
43
+ report.compactions++;
44
+ inCompaction = true;
38
45
  push('user', `[Earlier context was compacted by the original agent]${t.text && t.text !== '[conversation compacted]' && t.text !== '[conversation checkpoint]' ? `\n${t.text}` : ''}`, t.at);
39
46
  continue;
40
47
  }
@@ -67,22 +74,25 @@ export function toTranscript(turns, subagents = []) {
67
74
  if (lines.length)
68
75
  push('assistant', `[sub-agent ${sa.name}, which ran separately in the original session]\n${cap(lines.join('\n'), 6000)}`, null);
69
76
  }
70
- // Not every agent accepts a conversation that opens with the assistant: give it a leading user turn.
71
- if (msgs[0]?.role === 'assistant')
72
- msgs.unshift({ role: 'user', text: '[Conversation copied from another agent. It continues below.]', at: msgs[0].at });
73
- let total = 0;
74
- const kept = [];
75
- for (const m of msgs) {
76
- total += m.text.length;
77
- if (total > TOTAL_CAP) {
78
- report.truncated++;
79
- break;
80
- }
81
- kept.push(m);
77
+ // šŸ”“ Over the limit, the END is kept: it is where the conversation stopped and what the next agent continues. Keeping the start (as
78
+ // 0.7.0 did) dropped exactly that, so a long session's copy resumed weeks back. What is left out is named, with where to read it.
79
+ let total = 0, from = msgs.length;
80
+ while (from > 0 && total + msgs[from - 1].text.length <= TOTAL_CAP)
81
+ total += msgs[--from].text.length;
82
+ if (from === msgs.length && msgs.length)
83
+ from--; // one message larger than the limit is still carried, shortened below
84
+ const kept = msgs.slice(from);
85
+ if (kept.length === 1 && kept[0].text.length > TOTAL_CAP)
86
+ kept[0] = { ...kept[0], text: `… ${kept[0].text.slice(-TOTAL_CAP)}` };
87
+ report.omitted = from;
88
+ if (from) {
89
+ const where = opts.fullRecord ? ` The whole conversation, those included, is in ${opts.fullRecord}: read it when you need something from earlier.` : '';
90
+ kept.unshift({ role: 'user', text: `[The ${from} earliest messages are not in this copy: the conversation is longer than a copy can carry, so the most recent part was kept.${where}]`, at: null });
82
91
  }
92
+ // Not every agent accepts a conversation that opens with the assistant: give it a leading user turn.
93
+ if (kept[0]?.role === 'assistant')
94
+ kept.unshift({ role: 'user', text: '[Conversation copied from another agent. It continues below.]', at: kept[0].at });
83
95
  report.total = kept.length;
84
- if (kept.length < msgs.length)
85
- kept.push({ role: 'user', text: `[${msgs.length - kept.length} later messages were not copied: the conversation exceeded the copy limit]`, at: null });
86
96
  return { messages: kept, report };
87
97
  }
88
98
  /** What the move loses, in plain words, for a person to read before it runs. */
@@ -91,8 +101,10 @@ export function losses(report, target, handoff) {
91
101
  return [
92
102
  report.thinkingDropped && `${report.thinkingDropped} thinking block${s(report.thinkingDropped)} dropped (signed by the original agent; never forged)`,
93
103
  report.toolCalls && `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} labelled text (${target} cannot re-run another agent's tools)`,
104
+ // A hand-over IS the full record, so only a resumable copy leaves anything out.
105
+ !handoff && report.omitted && `the ${report.omitted} earliest message${s(report.omitted)} left out of the resumable copy (over the copy limit; it keeps the most recent part and points to the full record of the whole conversation, written beside it)`,
94
106
  report.truncated && `${report.truncated} long output${s(report.truncated)} shortened`,
95
- report.compactions && `${report.compactions} compaction${s(report.compactions)} kept as markers`,
107
+ report.compactions && `${report.compactions} compaction${s(report.compactions)} kept as markers${handoff ? ', their summaries indexed in compactions.md' : ''}`,
96
108
  report.subagents && `${report.subagents} sub-agent${s(report.subagents)} carried as labelled summaries (${report.subagentTurns} messages; their tool calls are not copied)`,
97
109
  handoff && `${target} cannot import a conversation: it starts a NEW one with this transcript as context`,
98
110
  ].filter((x) => typeof x === 'string');
@@ -16,6 +16,8 @@ export interface SessionRef {
16
16
  updated: number;
17
17
  size: number;
18
18
  locator: string;
19
+ /** Which of the agent's own apps keeps it, where one agent has two (agy: "Antigravity" for the desktop app, "Antigravity CLI"). */
20
+ app?: string;
19
21
  }
20
22
  /**
21
23
  * One step of a conversation. A tool call is an assistant turn with `tool`; its result is a `tool` turn with the same `callId`.
@@ -33,6 +35,11 @@ export interface Turn {
33
35
  thinking?: boolean;
34
36
  turnEnd?: boolean;
35
37
  compaction?: boolean;
38
+ /**
39
+ * A user turn the person did not type, where the agent records who sent it: another session's message ('peer') or the agent's own
40
+ * harness (a finished background job, 'harness'). Absent for the person's own words.
41
+ */
42
+ from?: 'peer' | 'harness';
36
43
  }
37
44
  /** A sub-agent's own conversation, which some agents (Claude Code) keep in separate files. */
38
45
  export interface Subagent {
@@ -43,10 +50,20 @@ export interface Subagent {
43
50
  export interface Stores {
44
51
  /** Claude Code's configuration folder (its sessions are under `projects/`). */
45
52
  claude: string;
53
+ /**
54
+ * Claude Code's project folders, when a caller keeps them somewhere other than `<claude>/projects` (XENO Spawn's isolated test homes
55
+ * do). Optional; absent means `<claude>/projects`.
56
+ */
57
+ claudeProjects?: string;
46
58
  /** Codex's home (`sessions/`, `state_5.sqlite`). */
47
59
  codex: string;
48
60
  /** agy's (Antigravity CLI) data folder (`conversation_summaries.db`, `brain/`). */
49
61
  agy: string;
62
+ /**
63
+ * The Antigravity desktop app's data folder, the same layout as the CLI's (measured 2026-11-28: one `conversation_summaries` schema,
64
+ * `brain/<id>/.system_generated/logs/transcript_full.jsonl`). Both are read as agy; optional so a caller's own Stores still type-check.
65
+ */
66
+ agyDesktop?: string;
50
67
  /** opencode's data folder (`opencode.db`). */
51
68
  opencode: string;
52
69
  /** The XENO agent's home (`sessions/`). */
@@ -1,5 +1,5 @@
1
1
  import type { Message } from './transcript.ts';
2
- import type { Runner, SessionRef, Stores, Vendor } from './types.ts';
2
+ import type { Runner, SessionRef, Stores, Subagent, Turn, Vendor } from './types.ts';
3
3
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
4
4
  export declare const TARGETS: Readonly<Record<Vendor, {
5
5
  fidelity: 'native' | 'handoff';
@@ -27,7 +27,17 @@ export interface WriteContext {
27
27
  workDir: string;
28
28
  /** Called with each artifact the moment it exists, before the next step, so a crash still leaves an accurate list. */
29
29
  record?: (a: Artifact) => void;
30
+ /**
31
+ * The original conversation as read, for the layered record written beside the copy (`<workDir>/transcript/`): the index, the
32
+ * person's messages, the latest stretch in full, the compactions and the whole dialog. Without it agy gets the single 0.7.0 document.
33
+ */
34
+ layers?: {
35
+ turns: Turn[];
36
+ subagents: Subagent[];
37
+ };
30
38
  }
39
+ /** Where a conversion keeps the layered record of the original, inside its own folder. */
40
+ export declare const transcriptDir: (workDir: string) => string;
31
41
  export interface Written {
32
42
  id: string | null;
33
43
  cwd: string;
@@ -9,9 +9,11 @@
9
9
  * private home (it reads only Claude files under its detection root)
10
10
  * opencode `opencode import <export.json>`, recording a model opencode itself lists
11
11
  * XENO agent `sessions/<id>/{meta.json,transcript.jsonl}` in its documented layout
12
- * agy no ingestion path exists (its conversations are private protobuf records in SQLite) → a HANDOFF: a document a new agy
12
+ * agy no ingestion path exists (its list is a SQLite table the running app writes, each conversation eight tables of
13
+ * undocumented protobuf; measured 2026-11-28) → a HANDOFF: the full record, layered, with an index a new agy
13
14
  * conversation is asked to read, declared as such
14
- * Every file is created exclusively at its final name, so nothing that exists is ever replaced.
15
+ * Every copy also carries the full record of the original in `<workDir>/transcript/` (layers.ts), so nothing the copy itself cannot
16
+ * hold is lost. Every file is created exclusively at its final name, so nothing that exists is ever replaced.
15
17
  */
16
18
  import { randomUUID } from 'node:crypto';
17
19
  import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, unlinkSync, writeSync } from 'node:fs';
@@ -19,6 +21,8 @@ import { dirname, join, resolve, sep } from 'node:path';
19
21
  import { spawnAgent } from "./run.js";
20
22
  import { safeSessionId } from "./read.js";
21
23
  import { cap } from "./transcript.js";
24
+ import { buildLayers, layersPrompt } from "./layers.js";
25
+ import { claudeProjectsDir, ownedPath } from "./owned.js";
22
26
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
23
27
  export const TARGETS = Object.freeze({
24
28
  'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout" },
@@ -27,6 +31,8 @@ export const TARGETS = Object.freeze({
27
31
  'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout" },
28
32
  agy: { fidelity: 'handoff', via: 'a new conversation given the transcript as context (agy has no import)' },
29
33
  });
34
+ /** Where a conversion keeps the layered record of the original, inside its own folder. */
35
+ export const transcriptDir = (workDir) => join(workDir, 'transcript');
30
36
  /** Claude Code's project folder name for a working folder. */
31
37
  export const slugForCwd = (cwd) => resolve(cwd).split(sep).join('-').replace(/[^A-Za-z0-9]/g, '-');
32
38
  /** Create a new file exclusively at its final name and flush it: a competing creator makes this fail, never clobbered. */
@@ -138,12 +144,21 @@ export async function writeSession(target, msgs, source, ctx) {
138
144
  const record = (a) => { artifacts.push(a); ctx.record?.(a); };
139
145
  if (existsSync(ctx.workDir))
140
146
  throw new Error(`Refusing to reuse ${ctx.workDir}: a conversion's folder must be new.`);
147
+ ownedPath(dirname(ctx.workDir), ctx.workDir);
141
148
  mkdirSync(dirname(ctx.workDir), { recursive: true });
142
149
  mkdirSync(ctx.workDir);
143
150
  record({ kind: 'workdir', path: ctx.workDir });
144
151
  const title = `Copy of ${source.title || source.id}`.slice(0, 160);
152
+ let index = null;
153
+ if (ctx.layers) {
154
+ const dir = transcriptDir(ctx.workDir), l = buildLayers(ctx.layers.turns, ctx.layers.subagents, source, dir);
155
+ for (const f of l.files)
156
+ writeNew(join(dir, f.name), f.text);
157
+ index = join(dir, l.readme.name);
158
+ writeNew(index, l.readme.text);
159
+ }
145
160
  if (target === 'Claude Code') {
146
- const sid = randomUUID(), file = join(ctx.stores.claude, 'projects', slugForCwd(cwd), `${sid}.jsonl`);
161
+ const projects = claudeProjectsDir(ctx.stores), sid = randomUUID(), file = ownedPath(projects, join(projects, slugForCwd(cwd), `${sid}.jsonl`));
147
162
  writeNew(file, claudeLines(msgs, sid, cwd));
148
163
  record({ kind: 'file', path: file });
149
164
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
@@ -185,7 +200,7 @@ export async function writeSession(target, msgs, source, ctx) {
185
200
  }
186
201
  if (target === 'XENO agent') {
187
202
  const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
188
- const sid = `xeno-copy-${stamp}-${randomUUID().slice(0, 5)}`, dir = join(ctx.stores.xenoAgent, 'sessions', sid);
203
+ const sessions = join(ctx.stores.xenoAgent, 'sessions'), sid = `xeno-copy-${stamp}-${randomUUID().slice(0, 5)}`, dir = ownedPath(sessions, join(sessions, sid));
189
204
  if (existsSync(dir))
190
205
  throw new Error(`Refusing to overwrite ${dir}`);
191
206
  mkdirSync(dirname(dir), { recursive: true });
@@ -200,6 +215,10 @@ export async function writeSession(target, msgs, source, ctx) {
200
215
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
201
216
  }
202
217
  // agy
218
+ if (index) {
219
+ record({ kind: 'file', path: index });
220
+ return { id: null, cwd, artifacts, handoff: { file: index, prompt: layersPrompt(index, source.vendor) } };
221
+ }
203
222
  const doc = handoffDocument(msgs, source);
204
223
  const file = join(ctx.workDir, 'handoff.md');
205
224
  writeNew(file, doc.full);
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/primitives",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials), updates (the gated app updater), live (the client for XENO Multiplayer) process (start a command so that stopping it stops everything it started), private-file (owner-only files, published atomically, without a helper process) and sessions (one conversation format with a reader and a writer for each agent, so a session moves between Claude Code, Codex, agy, opencode and the XENO agent).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",