@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
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.claudeProjectsDir = void 0;
4
+ exports.ownedPath = ownedPath;
5
+ /**
6
+ * Where a converter may write and delete: strictly inside an agent's own store, with no link anywhere on the way. Shared by the writers
7
+ * (write.ts) and the removal (convert.ts), so a path refused for deletion is refused for creation too.
8
+ *
9
+ * 🔴 A copy is never written THROUGH a junction or symlink (0.8.1, moved down from XENO Spawn's `ownedFiles.js`): a store reached
10
+ * through a link puts the copy somewhere the person did not choose, and its removal later deletes there too. A prefix check on the
11
+ * string cannot see a link; only walking the path with lstat can.
12
+ */
13
+ const node_fs_1 = require("node:fs");
14
+ const node_path_1 = require("node:path");
15
+ /** `path`, strictly inside `root`, with no symlink or junction at any component up to the filesystem root. Throws otherwise. */
16
+ function ownedPath(root, path) {
17
+ const base = (0, node_path_1.resolve)(root), target = (0, node_path_1.resolve)(path), rel = (0, node_path_1.relative)(base, target);
18
+ if (!rel || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../') || (0, node_path_1.isAbsolute)(rel))
19
+ throw new Error(`Path is not strictly inside its ownership root: ${target}`);
20
+ for (let part = target;;) {
21
+ try {
22
+ if ((0, node_fs_1.lstatSync)(part).isSymbolicLink())
23
+ throw new Error(`Refusing reparse point/symlink: ${part}`);
24
+ }
25
+ catch (e) {
26
+ if (e.code !== 'ENOENT')
27
+ throw e;
28
+ }
29
+ const parent = (0, node_path_1.dirname)(part);
30
+ if (parent === part)
31
+ break;
32
+ part = parent;
33
+ }
34
+ return target;
35
+ }
36
+ /** Claude Code's project folders: `stores.claudeProjects` when a caller keeps them elsewhere, else `<claude>/projects`. */
37
+ const claudeProjectsDir = (stores) => stores.claudeProjects ?? (0, node_path_1.join)(stores.claude, 'projects');
38
+ exports.claudeProjectsDir = claudeProjectsDir;
@@ -6,6 +6,11 @@ export interface ReadContext {
6
6
  }
7
7
  /** A session id an agent's command can take as one word, or null. */
8
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;
9
14
  /**
10
15
  * What the person typed, out of agy's own wrapping. agy records every message as `<USER_REQUEST>…</USER_REQUEST>` followed by its own
11
16
  * `<ADDITIONAL_METADATA>` block, and at times `<USER_SETTINGS_CHANGE>`: measured 2026-11-27, 232 of 232 messages on this machine.
@@ -26,6 +31,18 @@ export declare function listSessions(vendor: string, ctx: ReadContext): Promise<
26
31
  * match is refused, never guessed.
27
32
  */
28
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>;
29
46
  /** A session's transcript as Turns. */
30
47
  export declare function readSession(ref: SessionRef, ctx: ReadContext, o?: {
31
48
  maxBytes?: number;
@@ -1,10 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.safeSessionId = void 0;
3
+ exports.OUTPUT_KEPT = exports.safeSessionId = void 0;
4
4
  exports.agyRequest = agyRequest;
5
5
  exports.exportOpencodeSession = exportOpencodeSession;
6
6
  exports.listSessions = listSessions;
7
7
  exports.findSession = findSession;
8
+ exports.findAnySession = findAnySession;
9
+ exports.newestSessionIn = newestSessionIn;
8
10
  exports.readSession = readSession;
9
11
  exports.readSubagents = readSubagents;
10
12
  exports.resumeArgs = resumeArgs;
@@ -22,12 +24,19 @@ const node_fs_1 = require("node:fs");
22
24
  const node_path_1 = require("node:path");
23
25
  const node_readline_1 = require("node:readline");
24
26
  const types_ts_1 = require("./types.js");
27
+ const owned_ts_1 = require("./owned.js");
25
28
  const TITLE_CAP = 160, LINE_CAP = 8 << 20;
26
29
  const SAFE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
27
30
  /** A session id an agent's command can take as one word, or null. */
28
31
  const safeSessionId = (id) => typeof id === 'string' && SAFE_ID.test(id) ? id : null;
29
32
  exports.safeSessionId = safeSessionId;
30
33
  const clip = (s, n = TITLE_CAP) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
34
+ /**
35
+ * 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
36
+ * 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).
37
+ */
38
+ exports.OUTPUT_KEPT = 65536;
39
+ const kept = (s) => s.length > exports.OUTPUT_KEPT ? `${s.slice(0, exports.OUTPUT_KEPT)}\n… [${s.length - exports.OUTPUT_KEPT} more characters not read]` : s;
31
40
  const num = (v) => { const n = typeof v === 'number' ? v : Date.parse(String(v ?? '')); return Number.isFinite(n) ? n : 0; };
32
41
  async function openReadOnly(path) {
33
42
  const { DatabaseSync } = await Promise.resolve().then(() => require('node:sqlite'));
@@ -122,7 +131,7 @@ function claudeHeadIn(text) {
122
131
  const claude = {
123
132
  vendor: 'Claude Code',
124
133
  async list({ stores }) {
125
- const root = (0, node_path_1.join)(stores.claude, 'projects');
134
+ const root = (0, owned_ts_1.claudeProjectsDir)(stores);
126
135
  if (!(0, node_fs_1.existsSync)(root))
127
136
  return [];
128
137
  const out = [];
@@ -165,6 +174,17 @@ const claude = {
165
174
  if (r.isSidechain)
166
175
  return;
167
176
  const at = r.timestamp ?? null, c = r.message?.content;
177
+ // 🔴 A message that arrives while a turn is running is kept as a `queued_command` attachment, not a user record (measured
178
+ // 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
179
+ // were also user records). Skipping them dropped the person's own words from every copy.
180
+ const q = r.type === 'attachment' && r.attachment?.type === 'queued_command' ? r.attachment : null;
181
+ if (q) {
182
+ const text = typeof q.prompt === 'string' ? q.prompt : blocksText(q.prompt);
183
+ const last = turns[turns.length - 1];
184
+ if (text.trim() && !(last?.role === 'user' && last.text === text))
185
+ turns.push({ role: 'user', text, at: q.timestamp ?? at, ...(q.origin?.kind === 'human' ? {} : { from: q.origin?.kind === 'peer' ? 'peer' : 'harness' }) });
186
+ return;
187
+ }
168
188
  if (r.type === 'system' && r.subtype === 'compact_boundary') {
169
189
  turns.push({ role: 'system', text: '[conversation compacted]', compaction: true, at });
170
190
  return;
@@ -183,7 +203,7 @@ const claude = {
183
203
  if (b?.type === 'text' && !r.isMeta)
184
204
  turns.push({ role: 'user', text: b.text, at });
185
205
  else if (b?.type === 'tool_result')
186
- turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: blocksText(b.content), at });
206
+ turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: kept(blocksText(b.content)), at });
187
207
  }
188
208
  }
189
209
  else if (r.type === 'assistant') {
@@ -353,7 +373,7 @@ const codex = {
353
373
  }
354
374
  else if (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') {
355
375
  const o = typeof p.output === 'string' ? p.output : p.output?.content ?? JSON.stringify(p.output ?? '');
356
- turns.push({ role: 'tool', text: '', callId: p.call_id, output: String(o), at });
376
+ turns.push({ role: 'tool', text: '', callId: p.call_id, output: kept(String(o)), at });
357
377
  }
358
378
  }, opts);
359
379
  return turns;
@@ -382,33 +402,45 @@ function agyRequest(content) {
382
402
  const m = /<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(content);
383
403
  return (m ? m[1] : content.replace(/<(ADDITIONAL_METADATA|USER_SETTINGS_CHANGE)>[\s\S]*?<\/\1>/g, '')).trim();
384
404
  }
405
+ /** One Antigravity data folder's conversations: the CLI's and the desktop app's share a layout. */
406
+ async function agyList(h, app) {
407
+ const db = (0, node_path_1.join)(h, 'conversation_summaries.db');
408
+ if (!(0, node_fs_1.existsSync)(db))
409
+ return [];
410
+ const d = await openReadOnly(db);
411
+ try {
412
+ 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();
413
+ const out = [];
414
+ for (const r of rows) {
415
+ const id = (0, exports.safeSessionId)(r.conversation_id);
416
+ if (!id)
417
+ continue;
418
+ const t = (0, node_path_1.join)(h, 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl');
419
+ let size = 0;
420
+ try {
421
+ size = (0, node_fs_1.statSync)(t).size;
422
+ }
423
+ catch { /* summary only */ }
424
+ 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 });
425
+ }
426
+ return out;
427
+ }
428
+ finally {
429
+ d.close();
430
+ }
431
+ }
385
432
  const agy = {
386
433
  vendor: 'agy',
387
434
  async list({ stores }) {
388
- const h = stores.agy, db = (0, node_path_1.join)(h, 'conversation_summaries.db');
389
- if (!(0, node_fs_1.existsSync)(db))
390
- return [];
391
- const d = await openReadOnly(db);
392
- try {
393
- 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();
394
- const out = [];
395
- for (const r of rows) {
396
- const id = (0, exports.safeSessionId)(r.conversation_id);
397
- if (!id)
398
- continue;
399
- const t = (0, node_path_1.join)(h, 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl');
400
- let size = 0;
401
- try {
402
- size = (0, node_fs_1.statSync)(t).size;
403
- }
404
- catch { /* summary only */ }
405
- 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 : '' });
406
- }
407
- return out;
408
- }
409
- finally {
410
- d.close();
435
+ // The desktop app's store is read too (where people mostly use Antigravity); an id kept by both is listed once, newest copy.
436
+ const all = [...await agyList(stores.agy, 'Antigravity CLI'), ...(stores.agyDesktop ? await agyList(stores.agyDesktop, 'Antigravity') : [])];
437
+ const byId = new Map();
438
+ for (const s of all) {
439
+ const seen = byId.get(s.id);
440
+ if (!seen || s.updated > seen.updated)
441
+ byId.set(s.id, s);
411
442
  }
443
+ return [...byId.values()];
412
444
  },
413
445
  async read(ref, _ctx, opts = {}) {
414
446
  if (!ref.locator)
@@ -430,7 +462,7 @@ const agy = {
430
462
  turns.push({ role: 'assistant', text: '', tool: c.name, input: c.args, at });
431
463
  }
432
464
  else if (s.type === 'GENERIC' && s.content)
433
- turns.push({ role: 'tool', text: '', output: s.content, at });
465
+ turns.push({ role: 'tool', text: '', output: kept(String(s.content)), at });
434
466
  else if (s.type === 'CHECKPOINT')
435
467
  turns.push({ role: 'system', text: '[conversation checkpoint]', compaction: true, at });
436
468
  }, opts);
@@ -481,7 +513,7 @@ const opencode = {
481
513
  else if (p.type === 'tool') {
482
514
  turns.push({ role: 'assistant', text: '', tool: p.tool, callId: p.callID, input: p.state?.input, at });
483
515
  if (p.state?.output != null)
484
- turns.push({ role: 'tool', text: '', callId: p.callID, output: String(p.state.output), at });
516
+ turns.push({ role: 'tool', text: '', callId: p.callID, output: kept(String(p.state.output)), at });
485
517
  }
486
518
  }
487
519
  }
@@ -525,7 +557,7 @@ const xenoAgent = {
525
557
  else if (e.type === 'tool_call')
526
558
  turns.push({ role: 'assistant', text: '', tool: d.toolName, callId: d.id ?? e.id, input: d.input, at });
527
559
  else if (e.type === 'tool_result')
528
- turns.push({ role: 'tool', text: '', callId: d.callId ?? d.id, output: String(d.output ?? ''), at });
560
+ turns.push({ role: 'tool', text: '', callId: d.callId ?? d.id, output: kept(String(d.output ?? '')), at });
529
561
  }, opts);
530
562
  return turns;
531
563
  },
@@ -568,6 +600,36 @@ async function findSession(vendor, id, ctx) {
568
600
  throw new Error(`${want} matches ${hits.length} ${vendor} sessions; give more of its id.`);
569
601
  throw new Error(`${vendor} has no session ${want} on this machine.`);
570
602
  }
603
+ /**
604
+ * Find a session by its id alone, in whichever agent keeps it: ids are unique across agents (UUIDs, `ses_…`, `xeno-copy-…`), so the
605
+ * agent is read from the store that has it. A prefix matching sessions of two agents is refused, never guessed; an agent whose store
606
+ * cannot be read is named when nothing is found, since the session may be there.
607
+ */
608
+ async function findAnySession(id, ctx, { except } = {}) {
609
+ const want = String(id ?? '').trim();
610
+ if (!(0, exports.safeSessionId)(want))
611
+ throw new Error('That is not a session id.');
612
+ const results = await Promise.all(types_ts_1.VENDORS.filter((v) => v !== except).map((v) => listSessions(v, ctx)));
613
+ const all = results.flatMap((r) => r.sessions);
614
+ const exact = all.filter((s) => s.id === want);
615
+ if (exact.length === 1)
616
+ return exact[0];
617
+ const hits = exact.length ? exact : want.length >= 8 ? all.filter((s) => s.id.toLowerCase().startsWith(want.toLowerCase())) : [];
618
+ if (hits.length === 1)
619
+ return hits[0];
620
+ if (hits.length > 1)
621
+ 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.`);
622
+ const unread = results.filter((r) => r.error).map((r) => `${r.vendor} (${r.error})`);
623
+ throw new Error(`No session ${want} on this machine.${unread.length ? ` These could not be read: ${unread.join('; ')}.` : ''}`);
624
+ }
625
+ /** The most recently used session whose folder is `cwd` (compared the way the OS does: case-insensitive on Windows), in any agent but `except`. */
626
+ async function newestSessionIn(cwd, ctx, { except } = {}) {
627
+ const norm = (p) => { const r = p.replace(/[\\/]+$/, ''); return process.platform === 'win32' ? r.replace(/\//g, '\\').toLowerCase() : r; };
628
+ const here = norm(cwd);
629
+ const results = await Promise.all(types_ts_1.VENDORS.filter((v) => v !== except).map((v) => listSessions(v, ctx)));
630
+ const mine = results.flatMap((r) => r.sessions).filter((s) => s.cwd && norm(s.cwd) === here).sort((a, b) => b.updated - a.updated);
631
+ return mine[0] ?? null;
632
+ }
571
633
  /** A session's transcript as Turns. */
572
634
  function readSession(ref, ctx, o = {}) { return readerOf(ref.vendor).read(ref, ctx, o); }
573
635
  /** A session's sub-agent conversations, for agents that keep them separately (Claude Code); none for the others. */
@@ -15,6 +15,7 @@ function defaultStores(home = (0, host_ts_1.hostHome)(), env = (0, host_ts_1.hos
15
15
  claude: env.CLAUDE_CONFIG_DIR || (0, node_path_1.join)(home, '.claude'),
16
16
  codex: env.CODEX_HOME || (0, node_path_1.join)(home, '.codex'),
17
17
  agy: (0, node_path_1.join)(home, '.gemini', 'antigravity-cli'),
18
+ agyDesktop: (0, node_path_1.join)(home, '.gemini', 'antigravity'),
18
19
  // xeno-dirs-allow: opencode's own data folder, by opencode's own XDG rule; read where opencode writes it, never a XENO path
19
20
  opencode: (0, node_path_1.join)(env.XDG_DATA_HOME || (0, node_path_1.join)(home, '.local', 'share'), 'opencode'),
20
21
  // 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[];
@@ -14,9 +14,10 @@ catch {
14
14
  } };
15
15
  const cap = (s, n) => s.length > n ? `${s.slice(0, n)}\n… [${s.length - n} more characters not copied]` : s;
16
16
  exports.cap = cap;
17
- function toTranscript(turns, subagents = []) {
17
+ /** @param opts.fullRecord where the whole conversation is kept, named in the copy when its earliest messages are left out. */
18
+ function toTranscript(turns, subagents = [], opts = {}) {
18
19
  const msgs = [];
19
- const report = { userTurns: 0, assistantTurns: 0, toolCalls: 0, toolResults: 0, thinkingDropped: 0, compactions: 0, truncated: 0, total: 0, subagents: subagents.length, subagentTurns: 0 };
20
+ 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 };
20
21
  const outputs = new Map();
21
22
  const calls = new Set();
22
23
  for (const t of turns) {
@@ -34,13 +35,19 @@ function toTranscript(turns, subagents = []) {
34
35
  else
35
36
  msgs.push({ role, text, at: at ?? null });
36
37
  };
38
+ let inCompaction = false;
37
39
  for (const t of turns) {
38
40
  if (t.thinking) {
39
41
  report.thinkingDropped++;
40
42
  continue;
41
43
  }
44
+ // Claude Code records one compaction twice, a boundary and then its summary: counted once (a real session read 128 for 62).
45
+ if (!t.compaction)
46
+ inCompaction = false;
42
47
  if (t.compaction) {
43
- report.compactions++;
48
+ if (!inCompaction)
49
+ report.compactions++;
50
+ inCompaction = true;
44
51
  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);
45
52
  continue;
46
53
  }
@@ -73,22 +80,25 @@ function toTranscript(turns, subagents = []) {
73
80
  if (lines.length)
74
81
  push('assistant', `[sub-agent ${sa.name}, which ran separately in the original session]\n${(0, exports.cap)(lines.join('\n'), 6000)}`, null);
75
82
  }
76
- // Not every agent accepts a conversation that opens with the assistant: give it a leading user turn.
77
- if (msgs[0]?.role === 'assistant')
78
- msgs.unshift({ role: 'user', text: '[Conversation copied from another agent. It continues below.]', at: msgs[0].at });
79
- let total = 0;
80
- const kept = [];
81
- for (const m of msgs) {
82
- total += m.text.length;
83
- if (total > exports.TOTAL_CAP) {
84
- report.truncated++;
85
- break;
86
- }
87
- kept.push(m);
83
+ // 🔴 Over the limit, the END is kept: it is where the conversation stopped and what the next agent continues. Keeping the start (as
84
+ // 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.
85
+ let total = 0, from = msgs.length;
86
+ while (from > 0 && total + msgs[from - 1].text.length <= exports.TOTAL_CAP)
87
+ total += msgs[--from].text.length;
88
+ if (from === msgs.length && msgs.length)
89
+ from--; // one message larger than the limit is still carried, shortened below
90
+ const kept = msgs.slice(from);
91
+ if (kept.length === 1 && kept[0].text.length > exports.TOTAL_CAP)
92
+ kept[0] = { ...kept[0], text: `… ${kept[0].text.slice(-exports.TOTAL_CAP)}` };
93
+ report.omitted = from;
94
+ if (from) {
95
+ const where = opts.fullRecord ? ` The whole conversation, those included, is in ${opts.fullRecord}: read it when you need something from earlier.` : '';
96
+ 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 });
88
97
  }
98
+ // Not every agent accepts a conversation that opens with the assistant: give it a leading user turn.
99
+ if (kept[0]?.role === 'assistant')
100
+ kept.unshift({ role: 'user', text: '[Conversation copied from another agent. It continues below.]', at: kept[0].at });
89
101
  report.total = kept.length;
90
- if (kept.length < msgs.length)
91
- kept.push({ role: 'user', text: `[${msgs.length - kept.length} later messages were not copied: the conversation exceeded the copy limit]`, at: null });
92
102
  return { messages: kept, report };
93
103
  }
94
104
  /** What the move loses, in plain words, for a person to read before it runs. */
@@ -97,8 +107,10 @@ function losses(report, target, handoff) {
97
107
  return [
98
108
  report.thinkingDropped && `${report.thinkingDropped} thinking block${s(report.thinkingDropped)} dropped (signed by the original agent; never forged)`,
99
109
  report.toolCalls && `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} labelled text (${target} cannot re-run another agent's tools)`,
110
+ // A hand-over IS the full record, so only a resumable copy leaves anything out.
111
+ !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)`,
100
112
  report.truncated && `${report.truncated} long output${s(report.truncated)} shortened`,
101
- report.compactions && `${report.compactions} compaction${s(report.compactions)} kept as markers`,
113
+ report.compactions && `${report.compactions} compaction${s(report.compactions)} kept as markers${handoff ? ', their summaries indexed in compactions.md' : ''}`,
102
114
  report.subagents && `${report.subagents} sub-agent${s(report.subagents)} carried as labelled summaries (${report.subagentTurns} messages; their tool calls are not copied)`,
103
115
  handoff && `${target} cannot import a conversation: it starts a NEW one with this transcript as context`,
104
116
  ].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;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.slugForCwd = exports.TARGETS = void 0;
3
+ exports.slugForCwd = exports.transcriptDir = exports.TARGETS = void 0;
4
4
  exports.writeNew = writeNew;
5
5
  exports.claudeLines = claudeLines;
6
6
  exports.handoffDocument = handoffDocument;
@@ -16,9 +16,11 @@ exports.writeSession = writeSession;
16
16
  * private home (it reads only Claude files under its detection root)
17
17
  * opencode `opencode import <export.json>`, recording a model opencode itself lists
18
18
  * XENO agent `sessions/<id>/{meta.json,transcript.jsonl}` in its documented layout
19
- * agy no ingestion path exists (its conversations are private protobuf records in SQLite) → a HANDOFF: a document a new agy
19
+ * agy no ingestion path exists (its list is a SQLite table the running app writes, each conversation eight tables of
20
+ * undocumented protobuf; measured 2026-11-28) → a HANDOFF: the full record, layered, with an index a new agy
20
21
  * conversation is asked to read, declared as such
21
- * Every file is created exclusively at its final name, so nothing that exists is ever replaced.
22
+ * Every copy also carries the full record of the original in `<workDir>/transcript/` (layers.ts), so nothing the copy itself cannot
23
+ * hold is lost. Every file is created exclusively at its final name, so nothing that exists is ever replaced.
22
24
  */
23
25
  const node_crypto_1 = require("node:crypto");
24
26
  const node_fs_1 = require("node:fs");
@@ -26,6 +28,8 @@ const node_path_1 = require("node:path");
26
28
  const run_ts_1 = require("./run.js");
27
29
  const read_ts_1 = require("./read.js");
28
30
  const transcript_ts_1 = require("./transcript.js");
31
+ const layers_ts_1 = require("./layers.js");
32
+ const owned_ts_1 = require("./owned.js");
29
33
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
30
34
  exports.TARGETS = Object.freeze({
31
35
  'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout" },
@@ -34,6 +38,9 @@ exports.TARGETS = Object.freeze({
34
38
  'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout" },
35
39
  agy: { fidelity: 'handoff', via: 'a new conversation given the transcript as context (agy has no import)' },
36
40
  });
41
+ /** Where a conversion keeps the layered record of the original, inside its own folder. */
42
+ const transcriptDir = (workDir) => (0, node_path_1.join)(workDir, 'transcript');
43
+ exports.transcriptDir = transcriptDir;
37
44
  /** Claude Code's project folder name for a working folder. */
38
45
  const slugForCwd = (cwd) => (0, node_path_1.resolve)(cwd).split(node_path_1.sep).join('-').replace(/[^A-Za-z0-9]/g, '-');
39
46
  exports.slugForCwd = slugForCwd;
@@ -146,12 +153,21 @@ async function writeSession(target, msgs, source, ctx) {
146
153
  const record = (a) => { artifacts.push(a); ctx.record?.(a); };
147
154
  if ((0, node_fs_1.existsSync)(ctx.workDir))
148
155
  throw new Error(`Refusing to reuse ${ctx.workDir}: a conversion's folder must be new.`);
156
+ (0, owned_ts_1.ownedPath)((0, node_path_1.dirname)(ctx.workDir), ctx.workDir);
149
157
  (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(ctx.workDir), { recursive: true });
150
158
  (0, node_fs_1.mkdirSync)(ctx.workDir);
151
159
  record({ kind: 'workdir', path: ctx.workDir });
152
160
  const title = `Copy of ${source.title || source.id}`.slice(0, 160);
161
+ let index = null;
162
+ if (ctx.layers) {
163
+ const dir = (0, exports.transcriptDir)(ctx.workDir), l = (0, layers_ts_1.buildLayers)(ctx.layers.turns, ctx.layers.subagents, source, dir);
164
+ for (const f of l.files)
165
+ writeNew((0, node_path_1.join)(dir, f.name), f.text);
166
+ index = (0, node_path_1.join)(dir, l.readme.name);
167
+ writeNew(index, l.readme.text);
168
+ }
153
169
  if (target === 'Claude Code') {
154
- const sid = (0, node_crypto_1.randomUUID)(), file = (0, node_path_1.join)(ctx.stores.claude, 'projects', (0, exports.slugForCwd)(cwd), `${sid}.jsonl`);
170
+ const projects = (0, owned_ts_1.claudeProjectsDir)(ctx.stores), sid = (0, node_crypto_1.randomUUID)(), file = (0, owned_ts_1.ownedPath)(projects, (0, node_path_1.join)(projects, (0, exports.slugForCwd)(cwd), `${sid}.jsonl`));
155
171
  writeNew(file, claudeLines(msgs, sid, cwd));
156
172
  record({ kind: 'file', path: file });
157
173
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
@@ -193,7 +209,7 @@ async function writeSession(target, msgs, source, ctx) {
193
209
  }
194
210
  if (target === 'XENO agent') {
195
211
  const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
196
- const sid = `xeno-copy-${stamp}-${(0, node_crypto_1.randomUUID)().slice(0, 5)}`, dir = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions', sid);
212
+ const sessions = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions'), sid = `xeno-copy-${stamp}-${(0, node_crypto_1.randomUUID)().slice(0, 5)}`, dir = (0, owned_ts_1.ownedPath)(sessions, (0, node_path_1.join)(sessions, sid));
197
213
  if ((0, node_fs_1.existsSync)(dir))
198
214
  throw new Error(`Refusing to overwrite ${dir}`);
199
215
  (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(dir), { recursive: true });
@@ -208,6 +224,10 @@ async function writeSession(target, msgs, source, ctx) {
208
224
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
209
225
  }
210
226
  // agy
227
+ if (index) {
228
+ record({ kind: 'file', path: index });
229
+ return { id: null, cwd, artifacts, handoff: { file: index, prompt: (0, layers_ts_1.layersPrompt)(index, source.vendor) } };
230
+ }
211
231
  const doc = handoffDocument(msgs, source);
212
232
  const file = (0, node_path_1.join)(ctx.workDir, 'handoff.md');
213
233
  writeNew(file, doc.full);