@xenosystem/primitives 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +17 -0
  2. package/dist/cjs/sessions/cli.d.ts +2 -0
  3. package/dist/cjs/sessions/cli.js +152 -0
  4. package/dist/cjs/sessions/convert.d.ts +41 -0
  5. package/dist/cjs/sessions/convert.js +193 -0
  6. package/dist/cjs/sessions/index.d.ts +12 -0
  7. package/dist/cjs/sessions/index.js +37 -0
  8. package/dist/cjs/sessions/read.d.ts +36 -0
  9. package/dist/cjs/sessions/read.js +576 -0
  10. package/dist/cjs/sessions/run.d.ts +9 -0
  11. package/dist/cjs/sessions/run.js +60 -0
  12. package/dist/cjs/sessions/stores.d.ts +9 -0
  13. package/dist/cjs/sessions/stores.js +23 -0
  14. package/dist/cjs/sessions/transcript.d.ts +38 -0
  15. package/dist/cjs/sessions/transcript.js +105 -0
  16. package/dist/cjs/sessions/types.d.ts +61 -0
  17. package/dist/cjs/sessions/types.js +10 -0
  18. package/dist/cjs/sessions/write.d.ts +56 -0
  19. package/dist/cjs/sessions/write.js +216 -0
  20. package/dist/esm/sessions/cli.d.ts +2 -0
  21. package/dist/esm/sessions/cli.js +150 -0
  22. package/dist/esm/sessions/convert.d.ts +41 -0
  23. package/dist/esm/sessions/convert.js +187 -0
  24. package/dist/esm/sessions/index.d.ts +12 -0
  25. package/dist/esm/sessions/index.js +12 -0
  26. package/dist/esm/sessions/read.d.ts +36 -0
  27. package/dist/esm/sessions/read.js +565 -0
  28. package/dist/esm/sessions/run.d.ts +9 -0
  29. package/dist/esm/sessions/run.js +55 -0
  30. package/dist/esm/sessions/stores.d.ts +9 -0
  31. package/dist/esm/sessions/stores.js +20 -0
  32. package/dist/esm/sessions/transcript.d.ts +38 -0
  33. package/dist/esm/sessions/transcript.js +99 -0
  34. package/dist/esm/sessions/types.d.ts +61 -0
  35. package/dist/esm/sessions/types.js +7 -0
  36. package/dist/esm/sessions/write.d.ts +56 -0
  37. package/dist/esm/sessions/write.js +208 -0
  38. package/native/win32-x64/process.node +0 -0
  39. package/package.json +14 -3
package/README.md CHANGED
@@ -42,6 +42,23 @@ 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: `xeno-sessions list`, `xeno-sessions plan claude <id> --to agy`, `xeno-sessions convert agy <id> --to
59
+ claude`, `xeno-sessions copies`, `xeno-sessions remove <copy-id>`. A copy into agy is a hand-over document (agy has no
60
+ import); every other target gets a session it resumes as its own.
61
+
45
62
  Rules: no `homedir()` and no hand-built XENO path in a product; run `npx xeno-dirs-check` in CI
46
63
  (`--self-test` proves it can fail); `xeno-home doctor` lists unregistered entries; `xeno-home migrate` is a dry run
47
64
  until `--confirm` and never deletes anything.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // xeno-sessions list [--agent <name>] [--json] every agent session on this machine, newest first
5
+ // xeno-sessions plan <agent> <id> --to <agent> [--json] what a conversion would copy and lose; writes nothing
6
+ // xeno-sessions convert <agent> <id> --to <agent> copy the session into the other agent (the original is never written)
7
+ // xeno-sessions copies [--json] the copies this command made
8
+ // xeno-sessions remove <copy-id> remove exactly what one copy created
9
+ //
10
+ // Agents: "Claude Code" (or claude), Codex (codex), agy, opencode, "XENO agent" (xeno). An id may be its first 8 or more characters.
11
+ // A copy's record and its staging files live in the XENO local home: state/agents/sessions/conversions/.
12
+ const node_crypto_1 = require("node:crypto");
13
+ const node_fs_1 = require("node:fs");
14
+ const dirs_ts_1 = require("../dirs/dirs.js");
15
+ const atomic_ts_1 = require("../dirs/atomic.js");
16
+ const convert_ts_1 = require("./convert.js");
17
+ const read_ts_1 = require("./read.js");
18
+ const run_ts_1 = require("./run.js");
19
+ const stores_ts_1 = require("./stores.js");
20
+ const types_ts_1 = require("./types.js");
21
+ const ALIASES = { claude: 'Claude Code', 'claude-code': 'Claude Code', codex: 'Codex', agy: 'agy', antigravity: 'agy', opencode: 'opencode', xeno: 'XENO agent', 'xeno-agent': 'XENO agent' };
22
+ const vendorOf = (s) => {
23
+ const v = s && (types_ts_1.VENDORS.find((x) => x.toLowerCase() === s.toLowerCase()) ?? ALIASES[s.toLowerCase()]);
24
+ if (!v)
25
+ throw new Error(`Unknown agent: ${s ?? '(none)'}. Known: ${types_ts_1.VENDORS.join(', ')}.`);
26
+ return v;
27
+ };
28
+ const argv = process.argv.slice(2);
29
+ const flag = (name) => { const i = argv.indexOf(name); if (i < 0)
30
+ return undefined; const v = argv[i + 1]; argv.splice(i, 2); return v; };
31
+ const json = argv.includes('--json');
32
+ if (json)
33
+ argv.splice(argv.indexOf('--json'), 1);
34
+ const out = (v) => console.log(JSON.stringify(v, null, 2));
35
+ 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`; };
36
+ async function main() {
37
+ const ctx = { stores: (0, stores_ts_1.defaultStores)(), run: run_ts_1.runAgent };
38
+ const dirs = (0, dirs_ts_1.createDirs)();
39
+ const copiesDir = () => dirs.path('state', 'agents/sessions', 'conversions');
40
+ const [cmd, ...rest] = argv;
41
+ if (cmd === 'list') {
42
+ const only = flag('--agent');
43
+ const vendors = only ? [vendorOf(only)] : [...types_ts_1.VENDORS];
44
+ const results = await Promise.all(vendors.map((v) => (0, read_ts_1.listSessions)(v, ctx)));
45
+ if (json) {
46
+ out(results);
47
+ return 0;
48
+ }
49
+ for (const r of results) {
50
+ console.log(`${r.vendor}: ${r.error ? `cannot be read (${r.error})` : `${r.sessions.length} session${r.sessions.length === 1 ? '' : 's'}`}`);
51
+ for (const s of r.sessions.slice(0, only ? 200 : 10))
52
+ console.log(` ${s.id.slice(0, 12).padEnd(12)} ${ago(s.updated).padStart(4)} ${s.title.slice(0, 70)}${s.cwd ? ` (${s.cwd})` : ''}`);
53
+ }
54
+ return 0;
55
+ }
56
+ if (cmd === 'plan' || cmd === 'convert') {
57
+ const to = flag('--to');
58
+ const [agent, id] = rest.filter((x) => !x.startsWith('--'));
59
+ if (!agent || !id || !to) {
60
+ console.error(`usage: xeno-sessions ${cmd} <agent> <id> --to <agent>`);
61
+ return 2;
62
+ }
63
+ const source = { vendor: vendorOf(agent), id }, target = vendorOf(to);
64
+ const plan = await (0, convert_ts_1.planConversion)(source, target, ctx);
65
+ if (cmd === 'plan') {
66
+ if (json) {
67
+ out(plan);
68
+ return 0;
69
+ }
70
+ console.log(`${plan.source.vendor} ${plan.source.id} → ${plan.target} (${plan.fidelity}: ${plan.via})`);
71
+ console.log(` ${plan.report.total} messages: ${plan.report.userTurns} from the user, ${plan.report.assistantTurns} replies, ${plan.report.toolCalls} tool calls`);
72
+ for (const l of plan.losses)
73
+ console.log(` - ${l}`);
74
+ return 0;
75
+ }
76
+ const cid = (0, node_crypto_1.randomUUID)(), base = copiesDir(), record = `${base}/${cid}.json`;
77
+ const artifacts = [];
78
+ 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');
79
+ let saving = save({ failed: true });
80
+ const queue = (extra) => { saving = saving.then(() => save(extra)); return saving; };
81
+ await saving;
82
+ try {
83
+ const done = await (0, convert_ts_1.convertSession)(source, target, { ...ctx, workDir: `${base}/${cid}`, record: (a) => { artifacts.push(a); void queue({ failed: true }); }, onStep: (s) => { if (!json)
84
+ console.error(s); } });
85
+ await queue({ targetId: done.written.id, open: done.written.resume ? { resume: done.written.resume } : { handoff: done.written.handoff }, sourceSha256: done.sourceSha256 });
86
+ if (json) {
87
+ out({ copy: cid, ...done });
88
+ return 0;
89
+ }
90
+ if (done.written.resume)
91
+ console.log(`Copied. Continue it with: ${target === 'Claude Code' ? 'claude' : target === 'XENO agent' ? 'xeno' : target.toLowerCase()} ${done.written.resume.join(' ')} (in ${done.written.cwd})`);
92
+ else if (done.written.handoff)
93
+ console.log(`agy has no import, so this is a hand-over document: ${done.written.handoff.file}\nStart agy in ${done.written.cwd} and give it this prompt:\n ${done.written.handoff.prompt}`);
94
+ console.log(`Copy id ${cid} (remove it with: xeno-sessions remove ${cid})`);
95
+ return 0;
96
+ }
97
+ catch (e) {
98
+ await saving.catch(() => { });
99
+ // convertSession already removed what it created; the record goes only when nothing is left.
100
+ try {
101
+ const left = JSON.parse((0, node_fs_1.readFileSync)(record, 'utf8'));
102
+ if (!left.artifacts?.length || !/could not be removed/.test(String(e)))
103
+ (0, node_fs_1.unlinkSync)(record);
104
+ }
105
+ catch { /* kept */ }
106
+ throw e;
107
+ }
108
+ }
109
+ if (cmd === 'copies') {
110
+ const d = copiesDir();
111
+ const list = (0, node_fs_1.existsSync)(d) ? (0, node_fs_1.readdirSync)(d).filter((n) => n.endsWith('.json')).map((n) => { try {
112
+ return JSON.parse((0, node_fs_1.readFileSync)(`${d}/${n}`, 'utf8'));
113
+ }
114
+ catch {
115
+ return null;
116
+ } }).filter(Boolean) : [];
117
+ list.sort((a, b) => String(b.created).localeCompare(String(a.created)));
118
+ if (json) {
119
+ out(list);
120
+ return 0;
121
+ }
122
+ if (!list.length)
123
+ console.log('No copies.');
124
+ for (const c of list)
125
+ console.log(`${c.id} ${c.created.slice(0, 16)} ${c.source.vendor} → ${c.target}${c.failed ? ' (unfinished)' : ''} ${c.source.title ?? ''}`);
126
+ return 0;
127
+ }
128
+ if (cmd === 'remove') {
129
+ const cid = rest[0];
130
+ if (!cid || !/^[0-9a-f-]{36}$/.test(cid)) {
131
+ console.error('usage: xeno-sessions remove <copy-id>');
132
+ return 2;
133
+ }
134
+ const record = `${copiesDir()}/${cid}.json`;
135
+ if (!(0, node_fs_1.existsSync)(record)) {
136
+ console.error(`No copy ${cid}.`);
137
+ return 1;
138
+ }
139
+ const m = JSON.parse((0, node_fs_1.readFileSync)(record, 'utf8'));
140
+ const failed = await (0, convert_ts_1.removeArtifacts)(m.artifacts ?? [], ctx);
141
+ if (failed.length) {
142
+ console.error(`Part of the copy could not be removed, so its record is kept: ${failed.join('; ')}`);
143
+ return 1;
144
+ }
145
+ (0, node_fs_1.unlinkSync)(record);
146
+ console.log(`Removed copy ${cid}.`);
147
+ return 0;
148
+ }
149
+ console.error('usage: xeno-sessions list | plan <agent> <id> --to <agent> | convert <agent> <id> --to <agent> | copies | remove <copy-id>');
150
+ return cmd ? 2 : 0;
151
+ }
152
+ main().then((code) => { process.exitCode = code; }, (e) => { console.error(e instanceof Error ? e.message : String(e)); process.exitCode = 1; });
@@ -0,0 +1,41 @@
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
+ /** sha256 of the session's file, or of the turns its agent exports when its store is not one file. */
14
+ export declare function fingerprint(ref: SessionRef, ctx: ReadContext): Promise<string>;
15
+ /** What a conversion WOULD do, writing nothing. */
16
+ export declare function planConversion(source: {
17
+ vendor: string;
18
+ id: string;
19
+ }, target: string, ctx: ReadContext): Promise<Plan>;
20
+ export interface Conversion extends Plan {
21
+ sourceSha256: string;
22
+ written: Written;
23
+ }
24
+ /**
25
+ * Run a conversion. On any failure it removes only what it created and says what, if anything, could not be removed.
26
+ * @param workDir a new folder this conversion owns (it must not exist yet).
27
+ */
28
+ export declare function convertSession(source: {
29
+ vendor: string;
30
+ id: string;
31
+ }, target: string, ctx: ReadContext & {
32
+ workDir: string;
33
+ record?: (a: Artifact) => void;
34
+ onStep?: (s: string) => void;
35
+ }): Promise<Conversion>;
36
+ /**
37
+ * Delete exactly the artifacts a conversion reported, newest first. Returns what could NOT be removed, so a caller keeps its record of
38
+ * them and says so. 🔴 `codex delete` refuses without a terminal unless given `--force`; without it every Codex copy stayed behind while
39
+ * its record said removed (found by Spawn's live smoke, 2026-09-28).
40
+ */
41
+ export declare function removeArtifacts(artifacts: Artifact[], ctx: ReadContext): Promise<string[]>;
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fingerprint = fingerprint;
4
+ exports.planConversion = planConversion;
5
+ exports.convertSession = convertSession;
6
+ exports.removeArtifacts = removeArtifacts;
7
+ /**
8
+ * Convert a COPY of a session so another agent can continue it, and remove a copy again. Moved down from XENO Spawn
9
+ * (server/src/sessionConvert.js).
10
+ *
11
+ * 🔴 THE ORIGINAL IS NEVER WRITTEN. It is read, fingerprinted before and after, and a changed fingerprint fails the conversion. The copy
12
+ * 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
13
+ * and nothing else.
14
+ */
15
+ const node_crypto_1 = require("node:crypto");
16
+ const node_fs_1 = require("node:fs");
17
+ const node_path_1 = require("node:path");
18
+ const read_ts_1 = require("./read.js");
19
+ const transcript_ts_1 = require("./transcript.js");
20
+ const write_ts_1 = require("./write.js");
21
+ const types_ts_1 = require("./types.js");
22
+ const asVendor = (v) => {
23
+ if (!types_ts_1.VENDORS.includes(v))
24
+ throw new Error(`Unknown agent: ${v}. Known: ${types_ts_1.VENDORS.join(', ')}.`);
25
+ return v;
26
+ };
27
+ /** sha256 of the session's file, or of the turns its agent exports when its store is not one file. */
28
+ async function fingerprint(ref, ctx) {
29
+ if (ref.locator && (0, node_fs_1.existsSync)(ref.locator) && (0, node_fs_1.statSync)(ref.locator).isFile())
30
+ return (0, node_crypto_1.createHash)('sha256').update((0, node_fs_1.readFileSync)(ref.locator)).digest('hex');
31
+ return (0, node_crypto_1.createHash)('sha256').update(JSON.stringify(await (0, read_ts_1.readSession)(ref, ctx))).digest('hex');
32
+ }
33
+ /** What a conversion WOULD do, writing nothing. */
34
+ async function planConversion(source, target, ctx) {
35
+ const to = asVendor(target), t = write_ts_1.TARGETS[to];
36
+ if (source.vendor === to)
37
+ throw new Error('That session already belongs to this agent: open it directly.');
38
+ const ref = await (0, read_ts_1.findSession)(source.vendor, source.id, ctx);
39
+ const { messages, report } = (0, transcript_ts_1.toTranscript)(await (0, read_ts_1.readSession)(ref, ctx), await (0, read_ts_1.readSubagents)(ref));
40
+ if (!messages.length)
41
+ throw new Error('That session has no conversation to copy.');
42
+ return { source: { vendor: ref.vendor, id: ref.id, title: ref.title, cwd: ref.cwd }, target: to, fidelity: t.fidelity, via: t.via, report, losses: (0, transcript_ts_1.losses)(report, to, t.fidelity === 'handoff') };
43
+ }
44
+ /**
45
+ * Run a conversion. On any failure it removes only what it created and says what, if anything, could not be removed.
46
+ * @param workDir a new folder this conversion owns (it must not exist yet).
47
+ */
48
+ async function convertSession(source, target, ctx) {
49
+ const step = ctx.onStep ?? (() => { });
50
+ const plan = await planConversion(source, target, ctx);
51
+ const ref = await (0, read_ts_1.findSession)(source.vendor, source.id, ctx);
52
+ step('Reading the original');
53
+ const before = await fingerprint(ref, ctx);
54
+ const { messages } = (0, transcript_ts_1.toTranscript)(await (0, read_ts_1.readSession)(ref, ctx), await (0, read_ts_1.readSubagents)(ref));
55
+ const artifacts = [];
56
+ try {
57
+ step(`Creating the ${plan.target} copy`);
58
+ const written = await (0, write_ts_1.writeSession)(plan.target, messages, plan.source, { ...ctx, record: (a) => { artifacts.push(a); ctx.record?.(a); } });
59
+ step('Verifying');
60
+ if (await fingerprint(ref, ctx) !== before)
61
+ throw new Error('The original session changed while it was being copied. Nothing was kept; try again when that agent is idle.');
62
+ if (written.id) {
63
+ const seen = await (0, read_ts_1.findSession)(plan.target, written.id, ctx).catch(() => null);
64
+ if (!seen)
65
+ throw new Error(`${plan.target} does not list the copy it was given.`);
66
+ }
67
+ step('Done');
68
+ return { ...plan, sourceSha256: before, written };
69
+ }
70
+ catch (e) {
71
+ const left = await removeArtifacts(artifacts, ctx);
72
+ const after = await fingerprint(ref, ctx).catch(() => null);
73
+ const tail = after && after !== before ? ' (the original changed on its own during the copy; it was not written here)' : '';
74
+ const rest = left.length ? ` Part of the unfinished copy could not be removed: ${left.join('; ')}.` : '';
75
+ throw new Error(`${e instanceof Error ? e.message : String(e)}${tail}${rest}`);
76
+ }
77
+ }
78
+ /* ------------------------------------------------------------------ removal, of exactly what a conversion created */
79
+ /** `path`, strictly inside `root`, with no link anywhere on its way. */
80
+ function ownedPath(root, path) {
81
+ const base = (0, node_path_1.resolve)(root), target = (0, node_path_1.resolve)(path), rel = (0, node_path_1.relative)(base, target);
82
+ if (!rel || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../') || (0, node_path_1.isAbsolute)(rel))
83
+ throw new Error(`Path is not strictly inside its ownership root: ${target}`);
84
+ for (let part = target;;) {
85
+ try {
86
+ if ((0, node_fs_1.lstatSync)(part).isSymbolicLink())
87
+ throw new Error(`Refusing reparse point/symlink: ${part}`);
88
+ }
89
+ catch (e) {
90
+ if (e.code !== 'ENOENT')
91
+ throw e;
92
+ }
93
+ const parent = (0, node_path_1.dirname)(part);
94
+ if (parent === part)
95
+ break;
96
+ part = parent;
97
+ }
98
+ return target;
99
+ }
100
+ /**
101
+ * 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
102
+ * staging folder. `allowed` limits a vendor folder to the files a writer creates.
103
+ */
104
+ function removeOwnedPath(root, path, allowed = null) {
105
+ const target = ownedPath(root, path);
106
+ const entries = [];
107
+ const walk = (p) => {
108
+ ownedPath(root, p);
109
+ let st;
110
+ try {
111
+ st = (0, node_fs_1.lstatSync)(p);
112
+ }
113
+ catch (e) {
114
+ if (e.code === 'ENOENT')
115
+ return;
116
+ throw e;
117
+ }
118
+ if (st.isDirectory())
119
+ for (const n of (0, node_fs_1.readdirSync)(p))
120
+ walk((0, node_path_1.join)(p, n));
121
+ else {
122
+ if (!st.isFile())
123
+ throw new Error(`Refusing non-file artifact: ${p}`);
124
+ if (allowed && !allowed.includes((0, node_path_1.relative)(target, p)))
125
+ throw new Error(`${target} holds files this conversion did not create; left in place`);
126
+ }
127
+ entries.push({ path: p, dir: st.isDirectory(), dev: st.dev, ino: st.ino });
128
+ };
129
+ walk(target);
130
+ for (const e of entries) {
131
+ ownedPath(root, e.path);
132
+ const st = (0, node_fs_1.lstatSync)(e.path);
133
+ if (st.dev !== e.dev || st.ino !== e.ino || st.isDirectory() !== e.dir)
134
+ throw new Error(`Artifact changed during cleanup: ${e.path}`);
135
+ if (e.dir)
136
+ (0, node_fs_1.rmdirSync)(e.path);
137
+ else
138
+ (0, node_fs_1.unlinkSync)(e.path);
139
+ }
140
+ }
141
+ /**
142
+ * Delete exactly the artifacts a conversion reported, newest first. Returns what could NOT be removed, so a caller keeps its record of
143
+ * them and says so. 🔴 `codex delete` refuses without a terminal unless given `--force`; without it every Codex copy stayed behind while
144
+ * its record said removed (found by Spawn's live smoke, 2026-09-28).
145
+ */
146
+ async function removeArtifacts(artifacts, ctx) {
147
+ const failed = [];
148
+ const workdir = artifacts.find((a) => a.kind === 'workdir')?.path;
149
+ for (const a of artifacts.slice().reverse()) {
150
+ const label = a.kind === 'vendor-session' ? `${a.vendor} ${a.id}` : `${a.kind} ${a.path}`;
151
+ try {
152
+ if (a.kind === 'vendor-session') {
153
+ if (a.vendor === 'Codex') {
154
+ if (!(0, read_ts_1.safeSessionId)(a.id) || !/^[0-9a-f-]{36}$/i.test(a.id))
155
+ throw new Error(`not a Codex thread id: ${a.id}`);
156
+ await ctx.run('codex', ['delete', '--force', a.id]);
157
+ }
158
+ else if (a.vendor === 'opencode') {
159
+ if (!(0, read_ts_1.safeSessionId)(a.id))
160
+ throw new Error(`not an opencode session id: ${a.id}`);
161
+ await ctx.run('opencode', ['session', 'delete', a.id]);
162
+ }
163
+ else
164
+ throw new Error(`no deletion path for a ${a.vendor} session`);
165
+ }
166
+ else if (a.kind === 'workdir') {
167
+ removeOwnedPath((0, node_path_1.dirname)(a.path), a.path);
168
+ }
169
+ else if (a.kind === 'file') {
170
+ const rel = workdir ? (0, node_path_1.relative)((0, node_path_1.resolve)(workdir), (0, node_path_1.resolve)(a.path)) : '';
171
+ if (workdir && rel && !rel.startsWith('..') && !(0, node_path_1.isAbsolute)(rel)) {
172
+ removeOwnedPath(workdir, a.path);
173
+ continue;
174
+ }
175
+ const projects = (0, node_path_1.join)(ctx.stores.claude, 'projects');
176
+ ownedPath(projects, a.path);
177
+ if (!/^[0-9a-f-]{36}\.jsonl$/i.test((0, node_path_1.basename)(a.path)))
178
+ throw new Error(`not a converted Claude session file: ${a.path}`);
179
+ removeOwnedPath(projects, a.path);
180
+ }
181
+ else if (a.kind === 'dir') {
182
+ const sessions = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions'), path = ownedPath(sessions, a.path);
183
+ 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)))
184
+ throw new Error(`not a converted XENO agent session: ${path}`);
185
+ removeOwnedPath(sessions, path, ['meta.json', 'transcript.jsonl', 'session.lock', 'audit.jsonl', 'transcript.md']);
186
+ }
187
+ }
188
+ catch (e) {
189
+ failed.push(`${label}: ${e instanceof Error ? e.message.split('\n')[0] : String(e)}`);
190
+ }
191
+ }
192
+ return failed;
193
+ }
@@ -0,0 +1,12 @@
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, readSession, readSubagents, resumeArgs, safeSessionId, exportOpencodeSession, type ReadContext } from './read.ts';
10
+ export { toTranscript, losses, type Transcript, type Message, type Report } from './transcript.ts';
11
+ export { TARGETS, writeSession, handoffDocument, claudeLines, slugForCwd, type Artifact, type Written, type WriteContext } from './write.ts';
12
+ export { planConversion, convertSession, removeArtifacts, fingerprint, type Plan, type Conversion } from './convert.ts';
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fingerprint = exports.removeArtifacts = exports.convertSession = exports.planConversion = exports.slugForCwd = exports.claudeLines = exports.handoffDocument = exports.writeSession = exports.TARGETS = exports.losses = exports.toTranscript = exports.exportOpencodeSession = exports.safeSessionId = exports.resumeArgs = exports.readSubagents = exports.readSession = 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, "readSession", { enumerable: true, get: function () { return read_ts_1.readSession; } });
20
+ Object.defineProperty(exports, "readSubagents", { enumerable: true, get: function () { return read_ts_1.readSubagents; } });
21
+ Object.defineProperty(exports, "resumeArgs", { enumerable: true, get: function () { return read_ts_1.resumeArgs; } });
22
+ Object.defineProperty(exports, "safeSessionId", { enumerable: true, get: function () { return read_ts_1.safeSessionId; } });
23
+ Object.defineProperty(exports, "exportOpencodeSession", { enumerable: true, get: function () { return read_ts_1.exportOpencodeSession; } });
24
+ var transcript_ts_1 = require("./transcript.js");
25
+ Object.defineProperty(exports, "toTranscript", { enumerable: true, get: function () { return transcript_ts_1.toTranscript; } });
26
+ Object.defineProperty(exports, "losses", { enumerable: true, get: function () { return transcript_ts_1.losses; } });
27
+ var write_ts_1 = require("./write.js");
28
+ Object.defineProperty(exports, "TARGETS", { enumerable: true, get: function () { return write_ts_1.TARGETS; } });
29
+ Object.defineProperty(exports, "writeSession", { enumerable: true, get: function () { return write_ts_1.writeSession; } });
30
+ Object.defineProperty(exports, "handoffDocument", { enumerable: true, get: function () { return write_ts_1.handoffDocument; } });
31
+ Object.defineProperty(exports, "claudeLines", { enumerable: true, get: function () { return write_ts_1.claudeLines; } });
32
+ Object.defineProperty(exports, "slugForCwd", { enumerable: true, get: function () { return write_ts_1.slugForCwd; } });
33
+ var convert_ts_1 = require("./convert.js");
34
+ Object.defineProperty(exports, "planConversion", { enumerable: true, get: function () { return convert_ts_1.planConversion; } });
35
+ Object.defineProperty(exports, "convertSession", { enumerable: true, get: function () { return convert_ts_1.convertSession; } });
36
+ Object.defineProperty(exports, "removeArtifacts", { enumerable: true, get: function () { return convert_ts_1.removeArtifacts; } });
37
+ Object.defineProperty(exports, "fingerprint", { enumerable: true, get: function () { return convert_ts_1.fingerprint; } });
@@ -0,0 +1,36 @@
1
+ import type { Runner, SessionRef, Stores, Subagent, Turn } from './types.ts';
2
+ /** What reading needs: where each agent keeps its sessions, and how to run an agent's command (opencode reads through its own export). */
3
+ export interface ReadContext {
4
+ stores: Stores;
5
+ run: Runner;
6
+ }
7
+ /** A session id an agent's command can take as one word, or null. */
8
+ export declare const safeSessionId: (id: unknown) => string | null;
9
+ /**
10
+ * What the person typed, out of agy's own wrapping. agy records every message as `<USER_REQUEST>…</USER_REQUEST>` followed by its own
11
+ * `<ADDITIONAL_METADATA>` block, and at times `<USER_SETTINGS_CHANGE>`: measured 2026-11-27, 232 of 232 messages on this machine.
12
+ */
13
+ export declare function agyRequest(content: string): string;
14
+ /** opencode's own export of a session (its supported read path), checked to be the session asked for. */
15
+ export declare function exportOpencodeSession(id: string, { run }: {
16
+ run: Runner;
17
+ }, env?: NodeJS.ProcessEnv): Promise<any>;
18
+ /** One agent's sessions, newest first, or the reason they cannot be listed: a failure is a status, never an empty list. */
19
+ export declare function listSessions(vendor: string, ctx: ReadContext): Promise<{
20
+ vendor: string;
21
+ sessions: SessionRef[];
22
+ error: string | null;
23
+ }>;
24
+ /**
25
+ * Find a session in its agent's store at the moment of use. `id` may be the whole id or its first 8 or more characters; more than one
26
+ * match is refused, never guessed.
27
+ */
28
+ export declare function findSession(vendor: string, id: string, ctx: ReadContext): Promise<SessionRef>;
29
+ /** A session's transcript as Turns. */
30
+ export declare function readSession(ref: SessionRef, ctx: ReadContext, o?: {
31
+ maxBytes?: number;
32
+ }): Promise<Turn[]>;
33
+ /** A session's sub-agent conversations, for agents that keep them separately (Claude Code); none for the others. */
34
+ export declare function readSubagents(ref: SessionRef): Promise<Subagent[]>;
35
+ /** The words an agent's own command takes to reopen a session. */
36
+ export declare function resumeArgs(vendor: string, id: string): string[];