@xenosystem/primitives 0.5.0 → 0.7.0

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