@xenosystem/primitives 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +28 -0
  2. package/dist/cjs/sessions/cli.d.ts +2 -0
  3. package/dist/cjs/sessions/cli.js +196 -0
  4. package/dist/cjs/sessions/convert.d.ts +44 -0
  5. package/dist/cjs/sessions/convert.js +208 -0
  6. package/dist/cjs/sessions/index.d.ts +13 -0
  7. package/dist/cjs/sessions/index.js +46 -0
  8. package/dist/cjs/sessions/layers.d.ts +28 -0
  9. package/dist/cjs/sessions/layers.js +126 -0
  10. package/dist/cjs/sessions/read.d.ts +53 -0
  11. package/dist/cjs/sessions/read.js +637 -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 +24 -0
  16. package/dist/cjs/sessions/transcript.d.ts +43 -0
  17. package/dist/cjs/sessions/transcript.js +117 -0
  18. package/dist/cjs/sessions/types.d.ts +73 -0
  19. package/dist/cjs/sessions/types.js +10 -0
  20. package/dist/cjs/sessions/write.d.ts +66 -0
  21. package/dist/cjs/sessions/write.js +234 -0
  22. package/dist/esm/sessions/cli.d.ts +2 -0
  23. package/dist/esm/sessions/cli.js +194 -0
  24. package/dist/esm/sessions/convert.d.ts +44 -0
  25. package/dist/esm/sessions/convert.js +200 -0
  26. package/dist/esm/sessions/index.d.ts +13 -0
  27. package/dist/esm/sessions/index.js +13 -0
  28. package/dist/esm/sessions/layers.d.ts +28 -0
  29. package/dist/esm/sessions/layers.js +121 -0
  30. package/dist/esm/sessions/read.d.ts +53 -0
  31. package/dist/esm/sessions/read.js +624 -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 +21 -0
  36. package/dist/esm/sessions/transcript.d.ts +43 -0
  37. package/dist/esm/sessions/transcript.js +111 -0
  38. package/dist/esm/sessions/types.d.ts +73 -0
  39. package/dist/esm/sessions/types.js +7 -0
  40. package/dist/esm/sessions/write.d.ts +66 -0
  41. package/dist/esm/sessions/write.js +225 -0
  42. package/native/win32-x64/process.node +0 -0
  43. package/package.json +14 -3
package/README.md CHANGED
@@ -42,6 +42,34 @@ if (!secrets.status().available) { /* show secrets.status().reason; do not save
42
42
  await secrets.set('identity', 'refresh-token', value);
43
43
  ```
44
44
 
45
+ ### sessions: move a conversation between agents
46
+
47
+ ```ts
48
+ import { convertSession, defaultStores, listSessions, planConversion, runAgent } from '@xenosystem/primitives/sessions';
49
+
50
+ const ctx = { stores: defaultStores(), run: runAgent }; // each agent's own store; pass a profile's folders instead
51
+ const { sessions, error } = await listSessions('Claude Code', ctx); // error is a reason, never an empty list
52
+ const plan = await planConversion({ vendor: 'Claude Code', id: sessions[0].id }, 'agy', ctx); // writes nothing
53
+ plan.losses; // what the copy loses, in plain words
54
+ const done = await convertSession({ vendor: 'agy', id: '…' }, 'Claude Code', { ...ctx, workDir: aNewFolder });
55
+ done.written.resume; // ['--resume', '<new id>']: the copy is a new session; the original is never written
56
+ ```
57
+
58
+ From a terminal:
59
+
60
+ ```
61
+ xeno-sessions to agy # this folder's newest session, into Antigravity
62
+ xeno-sessions to claude 9f3c1a2b # one session by its id (8 characters are enough); its agent is found from the id
63
+ xeno-sessions to codex 9f3c1a2b --dry-run # what would be copied and lost; writes nothing
64
+ xeno-sessions list # every agent's sessions, newest first
65
+ xeno-sessions copies # what this command made
66
+ xeno-sessions remove <copy-id> # remove exactly one copy
67
+ ```
68
+
69
+ Every copy carries the full record of the original beside it (`<copy>/transcript/`: `README.md`, `your-messages.md`,
70
+ `recent.md`, `compactions.md`, `full.md`). A copy into agy is that record and a prompt for a new conversation (agy has
71
+ no import); every other target gets a session it resumes as its own. agy covers both the CLI and the desktop app.
72
+
45
73
  Rules: no `homedir()` and no hand-built XENO path in a product; run `npx xeno-dirs-check` in CI
46
74
  (`--self-test` proves it can fail); `xeno-home doctor` lists unregistered entries; `xeno-home migrate` is a dry run
47
75
  until `--confirm` and never deletes anything.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,196 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // xeno-sessions to <agent> [<id>] [--dry-run] copy a session into another agent: by its id, or this folder's newest session
5
+ // xeno-sessions list [--agent <name>] [--json] every agent session on this machine, newest first
6
+ // xeno-sessions plan [<agent>] <id> --to <agent> what a conversion would copy and lose; writes nothing
7
+ // xeno-sessions convert [<agent>] <id> --to <agent> the long form of `to` (the original is never written)
8
+ // xeno-sessions copies [--json] the copies this command made
9
+ // xeno-sessions remove <copy-id> remove exactly what one copy created
10
+ //
11
+ // Agents: "Claude Code" (or claude), Codex (codex), agy (or antigravity: the desktop app and the CLI), opencode, "XENO agent" (xeno).
12
+ // An id may be its first 8 or more characters, and its agent may be left out: it is found from the id (owner, 2026-11-28: "quick and
13
+ // fast commands"). A copy's record, its staging files and the full record of the original live in the XENO local home:
14
+ // state/agents/sessions/conversions/.
15
+ const node_crypto_1 = require("node:crypto");
16
+ const node_fs_1 = require("node:fs");
17
+ const dirs_ts_1 = require("../dirs/dirs.js");
18
+ const atomic_ts_1 = require("../dirs/atomic.js");
19
+ const convert_ts_1 = require("./convert.js");
20
+ const read_ts_1 = require("./read.js");
21
+ const run_ts_1 = require("./run.js");
22
+ const stores_ts_1 = require("./stores.js");
23
+ const types_ts_1 = require("./types.js");
24
+ const ALIASES = { claude: 'Claude Code', 'claude-code': 'Claude Code', codex: 'Codex', agy: 'agy', antigravity: 'agy', opencode: 'opencode', xeno: 'XENO agent', 'xeno-agent': 'XENO agent' };
25
+ const vendorOf = (s) => {
26
+ const v = s && (types_ts_1.VENDORS.find((x) => x.toLowerCase() === s.toLowerCase()) ?? ALIASES[s.toLowerCase()]);
27
+ if (!v)
28
+ throw new Error(`Unknown agent: ${s ?? '(none)'}. Known: ${types_ts_1.VENDORS.join(', ')}.`);
29
+ return v;
30
+ };
31
+ const isVendor = (s) => types_ts_1.VENDORS.some((x) => x.toLowerCase() === s.toLowerCase()) || s.toLowerCase() in ALIASES;
32
+ const argv = process.argv.slice(2);
33
+ const flag = (name) => { const i = argv.indexOf(name); if (i < 0)
34
+ return undefined; const v = argv[i + 1]; argv.splice(i, 2); return v; };
35
+ const bool = (name) => { const i = argv.indexOf(name); if (i < 0)
36
+ return false; argv.splice(i, 1); return true; };
37
+ const json = bool('--json');
38
+ const out = (v) => console.log(JSON.stringify(v, null, 2));
39
+ const ago = (ms) => { const s = (Date.now() - ms) / 1000; return s < 3600 ? `${Math.max(1, Math.round(s / 60))}m` : s < 86400 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`; };
40
+ const command = (v) => v === 'Claude Code' ? 'claude' : v === 'XENO agent' ? 'xeno' : v.toLowerCase();
41
+ function printPlan(plan) {
42
+ console.log(`${plan.source.vendor} ${plan.source.id}${plan.source.title ? ` "${plan.source.title}"` : ''} → ${plan.target} (${plan.fidelity}: ${plan.via})`);
43
+ // A turn is everything one side said before the other answered, so many replies and tool steps in a row are one turn of the copy.
44
+ console.log(` ${plan.report.userTurns} messages from the person, ${plan.report.assistantTurns} replies and ${plan.report.toolCalls} tool calls, carried as ${plan.report.total} turns`);
45
+ for (const l of plan.losses)
46
+ console.log(` - ${l}`);
47
+ }
48
+ async function main() {
49
+ const ctx = { stores: (0, stores_ts_1.defaultStores)(), run: run_ts_1.runAgent };
50
+ const dirs = (0, dirs_ts_1.createDirs)();
51
+ const copiesDir = () => dirs.path('state', 'agents/sessions', 'conversions');
52
+ const [cmd, ...rest] = argv;
53
+ if (cmd === 'list') {
54
+ const only = flag('--agent');
55
+ const vendors = only ? [vendorOf(only)] : [...types_ts_1.VENDORS];
56
+ const results = await Promise.all(vendors.map((v) => (0, read_ts_1.listSessions)(v, ctx)));
57
+ if (json) {
58
+ out(results);
59
+ return 0;
60
+ }
61
+ for (const r of results) {
62
+ console.log(`${r.vendor}: ${r.error ? `cannot be read (${r.error})` : `${r.sessions.length} session${r.sessions.length === 1 ? '' : 's'}`}`);
63
+ for (const s of r.sessions.slice(0, only ? 200 : 10))
64
+ console.log(` ${s.id.slice(0, 12).padEnd(12)} ${ago(s.updated).padStart(4)} ${s.title.slice(0, 70)}${s.app && s.app !== r.vendor ? ` [${s.app}]` : ''}${s.cwd ? ` (${s.cwd})` : ''}`);
65
+ }
66
+ return 0;
67
+ }
68
+ let source = null, target = null, dryRun = false;
69
+ if (cmd === 'to') {
70
+ dryRun = bool('--dry-run');
71
+ const [to, id] = rest.filter((x) => !x.startsWith('--'));
72
+ if (!to) {
73
+ console.error('usage: xeno-sessions to <agent> [<id>] [--dry-run]');
74
+ return 2;
75
+ }
76
+ target = vendorOf(to);
77
+ if (id)
78
+ source = { id };
79
+ else {
80
+ const here = await (0, read_ts_1.newestSessionIn)(process.cwd(), ctx, { except: target });
81
+ if (!here) {
82
+ console.error(`No session of another agent was used in ${process.cwd()}. Give its id (xeno-sessions list shows them).`);
83
+ return 1;
84
+ }
85
+ if (!json)
86
+ console.error(`This folder's newest session: ${here.vendor} ${here.id} "${here.title}" (${ago(here.updated)} ago)`);
87
+ source = { vendor: here.vendor, id: here.id };
88
+ }
89
+ }
90
+ else if (cmd === 'plan' || cmd === 'convert') {
91
+ const to = flag('--to');
92
+ const words = rest.filter((x) => !x.startsWith('--'));
93
+ const [agent, id] = words.length >= 2 ? words : [undefined, words[0]];
94
+ if (!id || !to) {
95
+ console.error(`usage: xeno-sessions ${cmd} [<agent>] <id> --to <agent>`);
96
+ return 2;
97
+ }
98
+ if (agent && !isVendor(agent)) {
99
+ console.error(`Unknown agent: ${agent}. Known: ${types_ts_1.VENDORS.join(', ')}.`);
100
+ return 2;
101
+ }
102
+ source = agent ? { vendor: vendorOf(agent), id } : { id };
103
+ target = vendorOf(to);
104
+ dryRun = cmd === 'plan';
105
+ }
106
+ if (source && target) {
107
+ const plan = await (0, convert_ts_1.planConversion)(source, target, ctx);
108
+ if (dryRun) {
109
+ if (json)
110
+ out(plan);
111
+ else
112
+ printPlan(plan);
113
+ return 0;
114
+ }
115
+ if (!json)
116
+ printPlan(plan);
117
+ const exact = { vendor: plan.source.vendor, id: plan.source.id };
118
+ const cid = (0, node_crypto_1.randomUUID)(), base = copiesDir(), record = `${base}/${cid}.json`;
119
+ const artifacts = [];
120
+ const save = (extra) => (0, atomic_ts_1.atomicWriteFile)(record, JSON.stringify({ schema: 1, id: cid, created: new Date().toISOString(), source: plan.source, target: plan.target, fidelity: plan.fidelity, losses: plan.losses, artifacts, ...extra }, null, 2) + '\n');
121
+ let saving = save({ failed: true });
122
+ const queue = (extra) => { saving = saving.then(() => save(extra)); return saving; };
123
+ await saving;
124
+ try {
125
+ const done = await (0, convert_ts_1.convertSession)(exact, target, { ...ctx, workDir: `${base}/${cid}`, record: (a) => { artifacts.push(a); void queue({ failed: true }); }, onStep: (s) => { if (!json)
126
+ console.error(s); } });
127
+ await queue({ targetId: done.written.id, open: done.written.resume ? { resume: done.written.resume } : { handoff: done.written.handoff }, sourceSha256: done.sourceSha256, record: `${base}/${cid}/transcript` });
128
+ if (json) {
129
+ out({ copy: cid, ...done });
130
+ return 0;
131
+ }
132
+ console.log(`The original is unchanged (sha256 ${done.sourceSha256.slice(0, 16)}…, the same before and after).`);
133
+ if (done.written.resume)
134
+ console.log(`Copied. Continue it with: ${command(target)} ${done.written.resume.join(' ')} (in ${done.written.cwd})`);
135
+ else if (done.written.handoff)
136
+ console.log(`Antigravity has no import, so it gets the full record and an index: ${done.written.handoff.file}\nOpen ${done.written.cwd} in Antigravity (or start agy there) and give it this prompt:\n ${done.written.handoff.prompt}`);
137
+ console.log(`The full record of the original: ${base}/${cid}/transcript`);
138
+ console.log(`Copy id ${cid} (remove it with: xeno-sessions remove ${cid})`);
139
+ return 0;
140
+ }
141
+ catch (e) {
142
+ await saving.catch(() => { });
143
+ // convertSession already removed what it created; the record goes only when nothing is left.
144
+ try {
145
+ const left = JSON.parse((0, node_fs_1.readFileSync)(record, 'utf8'));
146
+ if (!left.artifacts?.length || !/could not be removed/.test(String(e)))
147
+ (0, node_fs_1.unlinkSync)(record);
148
+ }
149
+ catch { /* kept */ }
150
+ throw e;
151
+ }
152
+ }
153
+ if (cmd === 'copies') {
154
+ const d = copiesDir();
155
+ const list = (0, node_fs_1.existsSync)(d) ? (0, node_fs_1.readdirSync)(d).filter((n) => n.endsWith('.json')).map((n) => { try {
156
+ return JSON.parse((0, node_fs_1.readFileSync)(`${d}/${n}`, 'utf8'));
157
+ }
158
+ catch {
159
+ return null;
160
+ } }).filter(Boolean) : [];
161
+ list.sort((a, b) => String(b.created).localeCompare(String(a.created)));
162
+ if (json) {
163
+ out(list);
164
+ return 0;
165
+ }
166
+ if (!list.length)
167
+ console.log('No copies.');
168
+ for (const c of list)
169
+ console.log(`${c.id} ${c.created.slice(0, 16)} ${c.source.vendor} → ${c.target}${c.failed ? ' (unfinished)' : ''} ${c.source.title ?? ''}`);
170
+ return 0;
171
+ }
172
+ if (cmd === 'remove') {
173
+ const cid = rest[0];
174
+ if (!cid || !/^[0-9a-f-]{36}$/.test(cid)) {
175
+ console.error('usage: xeno-sessions remove <copy-id>');
176
+ return 2;
177
+ }
178
+ const record = `${copiesDir()}/${cid}.json`;
179
+ if (!(0, node_fs_1.existsSync)(record)) {
180
+ console.error(`No copy ${cid}.`);
181
+ return 1;
182
+ }
183
+ const m = JSON.parse((0, node_fs_1.readFileSync)(record, 'utf8'));
184
+ const failed = await (0, convert_ts_1.removeArtifacts)(m.artifacts ?? [], ctx);
185
+ if (failed.length) {
186
+ console.error(`Part of the copy could not be removed, so its record is kept: ${failed.join('; ')}`);
187
+ return 1;
188
+ }
189
+ (0, node_fs_1.unlinkSync)(record);
190
+ console.log(`Removed copy ${cid}.`);
191
+ return 0;
192
+ }
193
+ console.error('usage: xeno-sessions to <agent> [<id>] [--dry-run] | list | plan [<agent>] <id> --to <agent> | convert [<agent>] <id> --to <agent> | copies | remove <copy-id>');
194
+ return cmd ? 2 : 0;
195
+ }
196
+ main().then((code) => { process.exitCode = code; }, (e) => { console.error(e instanceof Error ? e.message : String(e)); process.exitCode = 1; });
@@ -0,0 +1,44 @@
1
+ import { type ReadContext } from './read.ts';
2
+ import { type Report } from './transcript.ts';
3
+ import { type Artifact, type Written } from './write.ts';
4
+ import type { SessionRef, Vendor } from './types.ts';
5
+ export interface Plan {
6
+ source: Pick<SessionRef, 'vendor' | 'id' | 'title' | 'cwd'>;
7
+ target: Vendor;
8
+ fidelity: 'native' | 'handoff';
9
+ via: string;
10
+ report: Report;
11
+ losses: string[];
12
+ }
13
+ /**
14
+ * sha256 of the session's file, streamed (🔴 a whole-file read refuses anything over 2 GiB, and real Claude Code sessions reach 2.5 GB),
15
+ * or of the turns its agent exports when its store is not one file.
16
+ */
17
+ export declare function fingerprint(ref: SessionRef, ctx: ReadContext): Promise<string>;
18
+ /** Which session is meant: with its agent named, in that agent's store; with only its id, in whichever agent keeps it. */
19
+ export interface SourceSpec {
20
+ vendor?: string;
21
+ id: string;
22
+ }
23
+ export declare const locateSession: (source: SourceSpec, ctx: ReadContext) => Promise<SessionRef>;
24
+ /** What a conversion WOULD do, writing nothing. The source's agent may be left out: it is found from the id. */
25
+ export declare function planConversion(source: SourceSpec, target: string, ctx: ReadContext): Promise<Plan>;
26
+ export interface Conversion extends Plan {
27
+ sourceSha256: string;
28
+ written: Written;
29
+ }
30
+ /**
31
+ * Run a conversion. On any failure it removes only what it created and says what, if anything, could not be removed.
32
+ * @param workDir a new folder this conversion owns (it must not exist yet).
33
+ */
34
+ export declare function convertSession(source: SourceSpec, target: string, ctx: ReadContext & {
35
+ workDir: string;
36
+ record?: (a: Artifact) => void;
37
+ onStep?: (s: string) => void;
38
+ }): Promise<Conversion>;
39
+ /**
40
+ * Delete exactly the artifacts a conversion reported, newest first. Returns what could NOT be removed, so a caller keeps its record of
41
+ * them and says so. 🔴 `codex delete` refuses without a terminal unless given `--force`; without it every Codex copy stayed behind while
42
+ * its record said removed (found by Spawn's live smoke, 2026-09-28).
43
+ */
44
+ export declare function removeArtifacts(artifacts: Artifact[], ctx: ReadContext): Promise<string[]>;
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.locateSession = void 0;
4
+ exports.fingerprint = fingerprint;
5
+ exports.planConversion = planConversion;
6
+ exports.convertSession = convertSession;
7
+ exports.removeArtifacts = removeArtifacts;
8
+ /**
9
+ * Convert a COPY of a session so another agent can continue it, and remove a copy again. Moved down from XENO Spawn
10
+ * (server/src/sessionConvert.js).
11
+ *
12
+ * 🔴 THE ORIGINAL IS NEVER WRITTEN. It is read, fingerprinted before and after, and a changed fingerprint fails the conversion. The copy
13
+ * gets a NEW id in the target, and every artifact it creates is reported as it is created, so removing a copy deletes exactly those
14
+ * and nothing else.
15
+ */
16
+ const node_crypto_1 = require("node:crypto");
17
+ const node_fs_1 = require("node:fs");
18
+ const node_path_1 = require("node:path");
19
+ const read_ts_1 = require("./read.js");
20
+ const transcript_ts_1 = require("./transcript.js");
21
+ const write_ts_1 = require("./write.js");
22
+ const types_ts_1 = require("./types.js");
23
+ const asVendor = (v) => {
24
+ if (!types_ts_1.VENDORS.includes(v))
25
+ throw new Error(`Unknown agent: ${v}. Known: ${types_ts_1.VENDORS.join(', ')}.`);
26
+ return v;
27
+ };
28
+ /**
29
+ * sha256 of the session's file, streamed (🔴 a whole-file read refuses anything over 2 GiB, and real Claude Code sessions reach 2.5 GB),
30
+ * or of the turns its agent exports when its store is not one file.
31
+ */
32
+ async function fingerprint(ref, ctx) {
33
+ if (ref.locator && (0, node_fs_1.existsSync)(ref.locator) && (0, node_fs_1.statSync)(ref.locator).isFile()) {
34
+ const h = (0, node_crypto_1.createHash)('sha256');
35
+ for await (const chunk of (0, node_fs_1.createReadStream)(ref.locator, { highWaterMark: 1 << 20 }))
36
+ h.update(chunk);
37
+ return h.digest('hex');
38
+ }
39
+ return (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(await (0, read_ts_1.readSession)(ref, ctx))).digest('hex');
40
+ }
41
+ const locateSession = (source, ctx) => source.vendor ? (0, read_ts_1.findSession)(source.vendor, source.id, ctx) : (0, read_ts_1.findAnySession)(source.id, ctx);
42
+ exports.locateSession = locateSession;
43
+ async function prepare(source, target, ctx, fullRecord) {
44
+ const to = asVendor(target), t = write_ts_1.TARGETS[to];
45
+ const ref = await (0, exports.locateSession)(source, ctx);
46
+ if (ref.vendor === to)
47
+ throw new Error('That session already belongs to this agent: open it directly.');
48
+ const turns = await (0, read_ts_1.readSession)(ref, ctx), subagents = await (0, read_ts_1.readSubagents)(ref);
49
+ const transcript = (0, transcript_ts_1.toTranscript)(turns, subagents, { fullRecord });
50
+ if (!transcript.messages.length)
51
+ throw new Error('That session has no conversation to copy.');
52
+ const plan = { source: { vendor: ref.vendor, id: ref.id, title: ref.title, cwd: ref.cwd }, target: to, fidelity: t.fidelity, via: t.via, report: transcript.report, losses: (0, transcript_ts_1.losses)(transcript.report, to, t.fidelity === 'handoff') };
53
+ return { ref, turns, subagents, transcript, plan };
54
+ }
55
+ /** What a conversion WOULD do, writing nothing. The source's agent may be left out: it is found from the id. */
56
+ async function planConversion(source, target, ctx) {
57
+ return (await prepare(source, target, ctx)).plan;
58
+ }
59
+ /**
60
+ * Run a conversion. On any failure it removes only what it created and says what, if anything, could not be removed.
61
+ * @param workDir a new folder this conversion owns (it must not exist yet).
62
+ */
63
+ async function convertSession(source, target, ctx) {
64
+ const step = ctx.onStep ?? (() => { });
65
+ step('Reading the original');
66
+ const ref0 = await (0, exports.locateSession)(source, ctx);
67
+ // The fingerprint is taken BEFORE the read the copy is made from, so a change during the read is caught by the second one.
68
+ const before = await fingerprint(ref0, ctx);
69
+ const { ref, turns, subagents, transcript, plan } = await prepare({ vendor: ref0.vendor, id: ref0.id }, target, ctx, (0, node_path_1.join)((0, write_ts_1.transcriptDir)(ctx.workDir), 'full.md'));
70
+ const artifacts = [];
71
+ try {
72
+ step(`Creating the ${plan.target} copy`);
73
+ const written = await (0, write_ts_1.writeSession)(plan.target, transcript.messages, plan.source, { ...ctx, layers: { turns, subagents }, record: (a) => { artifacts.push(a); ctx.record?.(a); } });
74
+ step('Verifying');
75
+ if (await fingerprint(ref, ctx) !== before)
76
+ throw new Error('The original session changed while it was being copied. Nothing was kept; try again when that agent is idle.');
77
+ if (written.id) {
78
+ const seen = await (0, read_ts_1.findSession)(plan.target, written.id, ctx).catch(() => null);
79
+ if (!seen)
80
+ throw new Error(`${plan.target} does not list the copy it was given.`);
81
+ }
82
+ step('Done');
83
+ return { ...plan, sourceSha256: before, written };
84
+ }
85
+ catch (e) {
86
+ const left = await removeArtifacts(artifacts, ctx);
87
+ const after = await fingerprint(ref, ctx).catch(() => null);
88
+ const tail = after && after !== before ? ' (the original changed on its own during the copy; it was not written here)' : '';
89
+ const rest = left.length ? ` Part of the unfinished copy could not be removed: ${left.join('; ')}.` : '';
90
+ throw new Error(`${e instanceof Error ? e.message : String(e)}${tail}${rest}`);
91
+ }
92
+ }
93
+ /* ------------------------------------------------------------------ removal, of exactly what a conversion created */
94
+ /** `path`, strictly inside `root`, with no link anywhere on its way. */
95
+ function ownedPath(root, path) {
96
+ const base = (0, node_path_1.resolve)(root), target = (0, node_path_1.resolve)(path), rel = (0, node_path_1.relative)(base, target);
97
+ if (!rel || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../') || (0, node_path_1.isAbsolute)(rel))
98
+ throw new Error(`Path is not strictly inside its ownership root: ${target}`);
99
+ for (let part = target;;) {
100
+ try {
101
+ if ((0, node_fs_1.lstatSync)(part).isSymbolicLink())
102
+ throw new Error(`Refusing reparse point/symlink: ${part}`);
103
+ }
104
+ catch (e) {
105
+ if (e.code !== 'ENOENT')
106
+ throw e;
107
+ }
108
+ const parent = (0, node_path_1.dirname)(part);
109
+ if (parent === part)
110
+ break;
111
+ part = parent;
112
+ }
113
+ return target;
114
+ }
115
+ /**
116
+ * Remove a tree only after checking ALL of it: never a recursive rm, because an agent may have placed a junction even inside a private
117
+ * staging folder. `allowed` limits a vendor folder to the files a writer creates.
118
+ */
119
+ function removeOwnedPath(root, path, allowed = null) {
120
+ const target = ownedPath(root, path);
121
+ const entries = [];
122
+ const walk = (p) => {
123
+ ownedPath(root, p);
124
+ let st;
125
+ try {
126
+ st = (0, node_fs_1.lstatSync)(p);
127
+ }
128
+ catch (e) {
129
+ if (e.code === 'ENOENT')
130
+ return;
131
+ throw e;
132
+ }
133
+ if (st.isDirectory())
134
+ for (const n of (0, node_fs_1.readdirSync)(p))
135
+ walk((0, node_path_1.join)(p, n));
136
+ else {
137
+ if (!st.isFile())
138
+ throw new Error(`Refusing non-file artifact: ${p}`);
139
+ if (allowed && !allowed.includes((0, node_path_1.relative)(target, p)))
140
+ throw new Error(`${target} holds files this conversion did not create; left in place`);
141
+ }
142
+ entries.push({ path: p, dir: st.isDirectory(), dev: st.dev, ino: st.ino });
143
+ };
144
+ walk(target);
145
+ for (const e of entries) {
146
+ ownedPath(root, e.path);
147
+ const st = (0, node_fs_1.lstatSync)(e.path);
148
+ if (st.dev !== e.dev || st.ino !== e.ino || st.isDirectory() !== e.dir)
149
+ throw new Error(`Artifact changed during cleanup: ${e.path}`);
150
+ if (e.dir)
151
+ (0, node_fs_1.rmdirSync)(e.path);
152
+ else
153
+ (0, node_fs_1.unlinkSync)(e.path);
154
+ }
155
+ }
156
+ /**
157
+ * Delete exactly the artifacts a conversion reported, newest first. Returns what could NOT be removed, so a caller keeps its record of
158
+ * them and says so. 🔴 `codex delete` refuses without a terminal unless given `--force`; without it every Codex copy stayed behind while
159
+ * its record said removed (found by Spawn's live smoke, 2026-09-28).
160
+ */
161
+ async function removeArtifacts(artifacts, ctx) {
162
+ const failed = [];
163
+ const workdir = artifacts.find((a) => a.kind === 'workdir')?.path;
164
+ for (const a of artifacts.slice().reverse()) {
165
+ const label = a.kind === 'vendor-session' ? `${a.vendor} ${a.id}` : `${a.kind} ${a.path}`;
166
+ try {
167
+ if (a.kind === 'vendor-session') {
168
+ if (a.vendor === 'Codex') {
169
+ if (!(0, read_ts_1.safeSessionId)(a.id) || !/^[0-9a-f-]{36}$/i.test(a.id))
170
+ throw new Error(`not a Codex thread id: ${a.id}`);
171
+ await ctx.run('codex', ['delete', '--force', a.id]);
172
+ }
173
+ else if (a.vendor === 'opencode') {
174
+ if (!(0, read_ts_1.safeSessionId)(a.id))
175
+ throw new Error(`not an opencode session id: ${a.id}`);
176
+ await ctx.run('opencode', ['session', 'delete', a.id]);
177
+ }
178
+ else
179
+ throw new Error(`no deletion path for a ${a.vendor} session`);
180
+ }
181
+ else if (a.kind === 'workdir') {
182
+ removeOwnedPath((0, node_path_1.dirname)(a.path), a.path);
183
+ }
184
+ else if (a.kind === 'file') {
185
+ const rel = workdir ? (0, node_path_1.relative)((0, node_path_1.resolve)(workdir), (0, node_path_1.resolve)(a.path)) : '';
186
+ if (workdir && rel && !rel.startsWith('..') && !(0, node_path_1.isAbsolute)(rel)) {
187
+ removeOwnedPath(workdir, a.path);
188
+ continue;
189
+ }
190
+ const projects = (0, node_path_1.join)(ctx.stores.claude, 'projects');
191
+ ownedPath(projects, a.path);
192
+ if (!/^[0-9a-f-]{36}\.jsonl$/i.test((0, node_path_1.basename)(a.path)))
193
+ throw new Error(`not a converted Claude session file: ${a.path}`);
194
+ removeOwnedPath(projects, a.path);
195
+ }
196
+ else if (a.kind === 'dir') {
197
+ const sessions = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions'), path = ownedPath(sessions, a.path);
198
+ if ((0, node_path_1.dirname)(path) !== (0, node_path_1.resolve)(sessions) || !/^xeno-copy-\d{14}-[0-9a-f]{5}$/.test((0, node_path_1.basename)(path)))
199
+ throw new Error(`not a converted XENO agent session: ${path}`);
200
+ removeOwnedPath(sessions, path, ['meta.json', 'transcript.jsonl', 'session.lock', 'audit.jsonl', 'transcript.md']);
201
+ }
202
+ }
203
+ catch (e) {
204
+ failed.push(`${label}: ${e instanceof Error ? e.message.split('\n')[0] : String(e)}`);
205
+ }
206
+ }
207
+ return failed;
208
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @xenosystem/primitives/sessions: one agent-neutral conversation format, with a reader and a writer for each agent (Claude Code,
3
+ * Codex, agy, opencode, the XENO agent), so a session started in one can be continued in another. Back-end rung 1: no product logic.
4
+ * Products (XENO Spawn, the XENO agent) are its clients; the `xeno-sessions` command uses it outside XENO.
5
+ */
6
+ export { VENDORS, type Vendor, type SessionRef, type Turn, type Subagent, type Stores, type Runner } from './types.ts';
7
+ export { defaultStores } from './stores.ts';
8
+ export { runAgent, spawnAgent } from './run.ts';
9
+ export { listSessions, findSession, findAnySession, newestSessionIn, readSession, readSubagents, resumeArgs, safeSessionId, exportOpencodeSession, OUTPUT_KEPT, type ReadContext } from './read.ts';
10
+ export { toTranscript, losses, type Transcript, type Message, type Report } from './transcript.ts';
11
+ export { buildLayers, layersPrompt, RECENT_CAP, type Layer, type Layers } from './layers.ts';
12
+ export { TARGETS, writeSession, handoffDocument, claudeLines, slugForCwd, transcriptDir, type Artifact, type Written, type WriteContext } from './write.ts';
13
+ export { planConversion, convertSession, removeArtifacts, fingerprint, locateSession, type Plan, type Conversion, type SourceSpec } from './convert.ts';
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.locateSession = exports.fingerprint = exports.removeArtifacts = exports.convertSession = exports.planConversion = exports.transcriptDir = exports.slugForCwd = exports.claudeLines = exports.handoffDocument = exports.writeSession = exports.TARGETS = exports.RECENT_CAP = exports.layersPrompt = exports.buildLayers = exports.losses = exports.toTranscript = exports.OUTPUT_KEPT = exports.exportOpencodeSession = exports.safeSessionId = exports.resumeArgs = exports.readSubagents = exports.readSession = exports.newestSessionIn = exports.findAnySession = exports.findSession = exports.listSessions = exports.spawnAgent = exports.runAgent = exports.defaultStores = exports.VENDORS = void 0;
4
+ /**
5
+ * @xenosystem/primitives/sessions: one agent-neutral conversation format, with a reader and a writer for each agent (Claude Code,
6
+ * Codex, agy, opencode, the XENO agent), so a session started in one can be continued in another. Back-end rung 1: no product logic.
7
+ * Products (XENO Spawn, the XENO agent) are its clients; the `xeno-sessions` command uses it outside XENO.
8
+ */
9
+ var types_ts_1 = require("./types.js");
10
+ Object.defineProperty(exports, "VENDORS", { enumerable: true, get: function () { return types_ts_1.VENDORS; } });
11
+ var stores_ts_1 = require("./stores.js");
12
+ Object.defineProperty(exports, "defaultStores", { enumerable: true, get: function () { return stores_ts_1.defaultStores; } });
13
+ var run_ts_1 = require("./run.js");
14
+ Object.defineProperty(exports, "runAgent", { enumerable: true, get: function () { return run_ts_1.runAgent; } });
15
+ Object.defineProperty(exports, "spawnAgent", { enumerable: true, get: function () { return run_ts_1.spawnAgent; } });
16
+ var read_ts_1 = require("./read.js");
17
+ Object.defineProperty(exports, "listSessions", { enumerable: true, get: function () { return read_ts_1.listSessions; } });
18
+ Object.defineProperty(exports, "findSession", { enumerable: true, get: function () { return read_ts_1.findSession; } });
19
+ Object.defineProperty(exports, "findAnySession", { enumerable: true, get: function () { return read_ts_1.findAnySession; } });
20
+ Object.defineProperty(exports, "newestSessionIn", { enumerable: true, get: function () { return read_ts_1.newestSessionIn; } });
21
+ Object.defineProperty(exports, "readSession", { enumerable: true, get: function () { return read_ts_1.readSession; } });
22
+ Object.defineProperty(exports, "readSubagents", { enumerable: true, get: function () { return read_ts_1.readSubagents; } });
23
+ Object.defineProperty(exports, "resumeArgs", { enumerable: true, get: function () { return read_ts_1.resumeArgs; } });
24
+ Object.defineProperty(exports, "safeSessionId", { enumerable: true, get: function () { return read_ts_1.safeSessionId; } });
25
+ Object.defineProperty(exports, "exportOpencodeSession", { enumerable: true, get: function () { return read_ts_1.exportOpencodeSession; } });
26
+ Object.defineProperty(exports, "OUTPUT_KEPT", { enumerable: true, get: function () { return read_ts_1.OUTPUT_KEPT; } });
27
+ var transcript_ts_1 = require("./transcript.js");
28
+ Object.defineProperty(exports, "toTranscript", { enumerable: true, get: function () { return transcript_ts_1.toTranscript; } });
29
+ Object.defineProperty(exports, "losses", { enumerable: true, get: function () { return transcript_ts_1.losses; } });
30
+ var layers_ts_1 = require("./layers.js");
31
+ Object.defineProperty(exports, "buildLayers", { enumerable: true, get: function () { return layers_ts_1.buildLayers; } });
32
+ Object.defineProperty(exports, "layersPrompt", { enumerable: true, get: function () { return layers_ts_1.layersPrompt; } });
33
+ Object.defineProperty(exports, "RECENT_CAP", { enumerable: true, get: function () { return layers_ts_1.RECENT_CAP; } });
34
+ var write_ts_1 = require("./write.js");
35
+ Object.defineProperty(exports, "TARGETS", { enumerable: true, get: function () { return write_ts_1.TARGETS; } });
36
+ Object.defineProperty(exports, "writeSession", { enumerable: true, get: function () { return write_ts_1.writeSession; } });
37
+ Object.defineProperty(exports, "handoffDocument", { enumerable: true, get: function () { return write_ts_1.handoffDocument; } });
38
+ Object.defineProperty(exports, "claudeLines", { enumerable: true, get: function () { return write_ts_1.claudeLines; } });
39
+ Object.defineProperty(exports, "slugForCwd", { enumerable: true, get: function () { return write_ts_1.slugForCwd; } });
40
+ Object.defineProperty(exports, "transcriptDir", { enumerable: true, get: function () { return write_ts_1.transcriptDir; } });
41
+ var convert_ts_1 = require("./convert.js");
42
+ Object.defineProperty(exports, "planConversion", { enumerable: true, get: function () { return convert_ts_1.planConversion; } });
43
+ Object.defineProperty(exports, "convertSession", { enumerable: true, get: function () { return convert_ts_1.convertSession; } });
44
+ Object.defineProperty(exports, "removeArtifacts", { enumerable: true, get: function () { return convert_ts_1.removeArtifacts; } });
45
+ Object.defineProperty(exports, "fingerprint", { enumerable: true, get: function () { return convert_ts_1.fingerprint; } });
46
+ Object.defineProperty(exports, "locateSession", { enumerable: true, get: function () { return convert_ts_1.locateSession; } });
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The whole conversation as a set of files at different depths, written beside every copy (owner, 2026-11-28: a session converted "in
3
+ * full", whatever its size). One document cannot do it: a month-long Claude Code session on this machine is 2.5 GB and renders to about
4
+ * 17 MB of text, which no agent reads in one go. The shape follows what an Antigravity conversation built for itself, by hand, to take
5
+ * over that session (`~/.gemini/antigravity/brain/6412c38c…/scratch/extract_session.py`, 2026-11-27): the person's own messages, the
6
+ * compaction summaries with an index, the latest stretch in full, and the complete dialog kept for searching.
7
+ *
8
+ * Pure: it renders text and writes nothing. The writer puts the files in the copy's own folder, so removing the copy removes them.
9
+ */
10
+ import type { SessionRef, Subagent, Turn } from './types.ts';
11
+ /** The latest stretch, in full: from the last compaction to the end, at most this many characters (the end is always kept). */
12
+ export declare const RECENT_CAP = 1500000;
13
+ /** ...and at least this many, reaching back past the last compaction when it fell near the end. */
14
+ export declare const RECENT_MIN = 400000;
15
+ export interface Layer {
16
+ name: string;
17
+ title: string;
18
+ purpose: string;
19
+ text: string;
20
+ }
21
+ export interface Layers {
22
+ readme: Layer;
23
+ files: Layer[];
24
+ }
25
+ /** The layered record of one conversation. `dir` is where the files will live, so the index can name each by its full path. */
26
+ export declare function buildLayers(turns: Turn[], subagents: Subagent[], ref: Pick<SessionRef, 'vendor' | 'id' | 'title' | 'cwd'>, dir: string): Layers;
27
+ /** The prompt that hands the layered record to a fresh agent. */
28
+ export declare function layersPrompt(readmePath: string, vendor: string): string;