@xenosystem/primitives 0.7.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.
@@ -8,9 +8,10 @@ catch {
8
8
  return String(v);
9
9
  } };
10
10
  export const cap = (s, n) => s.length > n ? `${s.slice(0, n)}\n… [${s.length - n} more characters not copied]` : s;
11
- export function toTranscript(turns, subagents = []) {
11
+ /** @param opts.fullRecord where the whole conversation is kept, named in the copy when its earliest messages are left out. */
12
+ export function toTranscript(turns, subagents = [], opts = {}) {
12
13
  const msgs = [];
13
- const report = { userTurns: 0, assistantTurns: 0, toolCalls: 0, toolResults: 0, thinkingDropped: 0, compactions: 0, truncated: 0, total: 0, subagents: subagents.length, subagentTurns: 0 };
14
+ const report = { userTurns: 0, assistantTurns: 0, toolCalls: 0, toolResults: 0, thinkingDropped: 0, compactions: 0, truncated: 0, total: 0, subagents: subagents.length, subagentTurns: 0, omitted: 0 };
14
15
  const outputs = new Map();
15
16
  const calls = new Set();
16
17
  for (const t of turns) {
@@ -28,13 +29,19 @@ export function toTranscript(turns, subagents = []) {
28
29
  else
29
30
  msgs.push({ role, text, at: at ?? null });
30
31
  };
32
+ let inCompaction = false;
31
33
  for (const t of turns) {
32
34
  if (t.thinking) {
33
35
  report.thinkingDropped++;
34
36
  continue;
35
37
  }
38
+ // Claude Code records one compaction twice, a boundary and then its summary: counted once (a real session read 128 for 62).
39
+ if (!t.compaction)
40
+ inCompaction = false;
36
41
  if (t.compaction) {
37
- report.compactions++;
42
+ if (!inCompaction)
43
+ report.compactions++;
44
+ inCompaction = true;
38
45
  push('user', `[Earlier context was compacted by the original agent]${t.text && t.text !== '[conversation compacted]' && t.text !== '[conversation checkpoint]' ? `\n${t.text}` : ''}`, t.at);
39
46
  continue;
40
47
  }
@@ -67,22 +74,25 @@ export function toTranscript(turns, subagents = []) {
67
74
  if (lines.length)
68
75
  push('assistant', `[sub-agent ${sa.name}, which ran separately in the original session]\n${cap(lines.join('\n'), 6000)}`, null);
69
76
  }
70
- // Not every agent accepts a conversation that opens with the assistant: give it a leading user turn.
71
- if (msgs[0]?.role === 'assistant')
72
- msgs.unshift({ role: 'user', text: '[Conversation copied from another agent. It continues below.]', at: msgs[0].at });
73
- let total = 0;
74
- const kept = [];
75
- for (const m of msgs) {
76
- total += m.text.length;
77
- if (total > TOTAL_CAP) {
78
- report.truncated++;
79
- break;
80
- }
81
- kept.push(m);
77
+ // šŸ”“ Over the limit, the END is kept: it is where the conversation stopped and what the next agent continues. Keeping the start (as
78
+ // 0.7.0 did) dropped exactly that, so a long session's copy resumed weeks back. What is left out is named, with where to read it.
79
+ let total = 0, from = msgs.length;
80
+ while (from > 0 && total + msgs[from - 1].text.length <= TOTAL_CAP)
81
+ total += msgs[--from].text.length;
82
+ if (from === msgs.length && msgs.length)
83
+ from--; // one message larger than the limit is still carried, shortened below
84
+ const kept = msgs.slice(from);
85
+ if (kept.length === 1 && kept[0].text.length > TOTAL_CAP)
86
+ kept[0] = { ...kept[0], text: `… ${kept[0].text.slice(-TOTAL_CAP)}` };
87
+ report.omitted = from;
88
+ if (from) {
89
+ const where = opts.fullRecord ? ` The whole conversation, those included, is in ${opts.fullRecord}: read it when you need something from earlier.` : '';
90
+ kept.unshift({ role: 'user', text: `[The ${from} earliest messages are not in this copy: the conversation is longer than a copy can carry, so the most recent part was kept.${where}]`, at: null });
82
91
  }
92
+ // Not every agent accepts a conversation that opens with the assistant: give it a leading user turn.
93
+ if (kept[0]?.role === 'assistant')
94
+ kept.unshift({ role: 'user', text: '[Conversation copied from another agent. It continues below.]', at: kept[0].at });
83
95
  report.total = kept.length;
84
- if (kept.length < msgs.length)
85
- kept.push({ role: 'user', text: `[${msgs.length - kept.length} later messages were not copied: the conversation exceeded the copy limit]`, at: null });
86
96
  return { messages: kept, report };
87
97
  }
88
98
  /** What the move loses, in plain words, for a person to read before it runs. */
@@ -91,8 +101,10 @@ export function losses(report, target, handoff) {
91
101
  return [
92
102
  report.thinkingDropped && `${report.thinkingDropped} thinking block${s(report.thinkingDropped)} dropped (signed by the original agent; never forged)`,
93
103
  report.toolCalls && `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} labelled text (${target} cannot re-run another agent's tools)`,
104
+ // A hand-over IS the full record, so only a resumable copy leaves anything out.
105
+ !handoff && report.omitted && `the ${report.omitted} earliest message${s(report.omitted)} left out of the resumable copy (over the copy limit; it keeps the most recent part and points to the full record of the whole conversation, written beside it)`,
94
106
  report.truncated && `${report.truncated} long output${s(report.truncated)} shortened`,
95
- report.compactions && `${report.compactions} compaction${s(report.compactions)} kept as markers`,
107
+ report.compactions && `${report.compactions} compaction${s(report.compactions)} kept as markers${handoff ? ', their summaries indexed in compactions.md' : ''}`,
96
108
  report.subagents && `${report.subagents} sub-agent${s(report.subagents)} carried as labelled summaries (${report.subagentTurns} messages; their tool calls are not copied)`,
97
109
  handoff && `${target} cannot import a conversation: it starts a NEW one with this transcript as context`,
98
110
  ].filter((x) => typeof x === 'string');
@@ -16,6 +16,8 @@ export interface SessionRef {
16
16
  updated: number;
17
17
  size: number;
18
18
  locator: string;
19
+ /** Which of the agent's own apps keeps it, where one agent has two (agy: "Antigravity" for the desktop app, "Antigravity CLI"). */
20
+ app?: string;
19
21
  }
20
22
  /**
21
23
  * One step of a conversation. A tool call is an assistant turn with `tool`; its result is a `tool` turn with the same `callId`.
@@ -33,6 +35,11 @@ export interface Turn {
33
35
  thinking?: boolean;
34
36
  turnEnd?: boolean;
35
37
  compaction?: boolean;
38
+ /**
39
+ * A user turn the person did not type, where the agent records who sent it: another session's message ('peer') or the agent's own
40
+ * harness (a finished background job, 'harness'). Absent for the person's own words.
41
+ */
42
+ from?: 'peer' | 'harness';
36
43
  }
37
44
  /** A sub-agent's own conversation, which some agents (Claude Code) keep in separate files. */
38
45
  export interface Subagent {
@@ -47,6 +54,11 @@ export interface Stores {
47
54
  codex: string;
48
55
  /** agy's (Antigravity CLI) data folder (`conversation_summaries.db`, `brain/`). */
49
56
  agy: string;
57
+ /**
58
+ * The Antigravity desktop app's data folder, the same layout as the CLI's (measured 2026-11-28: one `conversation_summaries` schema,
59
+ * `brain/<id>/.system_generated/logs/transcript_full.jsonl`). Both are read as agy; optional so a caller's own Stores still type-check.
60
+ */
61
+ agyDesktop?: string;
50
62
  /** opencode's data folder (`opencode.db`). */
51
63
  opencode: string;
52
64
  /** The XENO agent's home (`sessions/`). */
@@ -1,5 +1,5 @@
1
1
  import type { Message } from './transcript.ts';
2
- import type { Runner, SessionRef, Stores, Vendor } from './types.ts';
2
+ import type { Runner, SessionRef, Stores, Subagent, Turn, Vendor } from './types.ts';
3
3
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
4
4
  export declare const TARGETS: Readonly<Record<Vendor, {
5
5
  fidelity: 'native' | 'handoff';
@@ -27,7 +27,17 @@ export interface WriteContext {
27
27
  workDir: string;
28
28
  /** Called with each artifact the moment it exists, before the next step, so a crash still leaves an accurate list. */
29
29
  record?: (a: Artifact) => void;
30
+ /**
31
+ * The original conversation as read, for the layered record written beside the copy (`<workDir>/transcript/`): the index, the
32
+ * person's messages, the latest stretch in full, the compactions and the whole dialog. Without it agy gets the single 0.7.0 document.
33
+ */
34
+ layers?: {
35
+ turns: Turn[];
36
+ subagents: Subagent[];
37
+ };
30
38
  }
39
+ /** Where a conversion keeps the layered record of the original, inside its own folder. */
40
+ export declare const transcriptDir: (workDir: string) => string;
31
41
  export interface Written {
32
42
  id: string | null;
33
43
  cwd: string;
@@ -9,9 +9,11 @@
9
9
  * private home (it reads only Claude files under its detection root)
10
10
  * opencode `opencode import <export.json>`, recording a model opencode itself lists
11
11
  * XENO agent `sessions/<id>/{meta.json,transcript.jsonl}` in its documented layout
12
- * agy no ingestion path exists (its conversations are private protobuf records in SQLite) → a HANDOFF: a document a new agy
12
+ * agy no ingestion path exists (its list is a SQLite table the running app writes, each conversation eight tables of
13
+ * undocumented protobuf; measured 2026-11-28) → a HANDOFF: the full record, layered, with an index a new agy
13
14
  * conversation is asked to read, declared as such
14
- * Every file is created exclusively at its final name, so nothing that exists is ever replaced.
15
+ * Every copy also carries the full record of the original in `<workDir>/transcript/` (layers.ts), so nothing the copy itself cannot
16
+ * hold is lost. Every file is created exclusively at its final name, so nothing that exists is ever replaced.
15
17
  */
16
18
  import { randomUUID } from 'node:crypto';
17
19
  import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, unlinkSync, writeSync } from 'node:fs';
@@ -19,6 +21,7 @@ import { dirname, join, resolve, sep } from 'node:path';
19
21
  import { spawnAgent } from "./run.js";
20
22
  import { safeSessionId } from "./read.js";
21
23
  import { cap } from "./transcript.js";
24
+ import { buildLayers, layersPrompt } from "./layers.js";
22
25
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
23
26
  export const TARGETS = Object.freeze({
24
27
  'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout" },
@@ -27,6 +30,8 @@ export const TARGETS = Object.freeze({
27
30
  'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout" },
28
31
  agy: { fidelity: 'handoff', via: 'a new conversation given the transcript as context (agy has no import)' },
29
32
  });
33
+ /** Where a conversion keeps the layered record of the original, inside its own folder. */
34
+ export const transcriptDir = (workDir) => join(workDir, 'transcript');
30
35
  /** Claude Code's project folder name for a working folder. */
31
36
  export const slugForCwd = (cwd) => resolve(cwd).split(sep).join('-').replace(/[^A-Za-z0-9]/g, '-');
32
37
  /** Create a new file exclusively at its final name and flush it: a competing creator makes this fail, never clobbered. */
@@ -142,6 +147,14 @@ export async function writeSession(target, msgs, source, ctx) {
142
147
  mkdirSync(ctx.workDir);
143
148
  record({ kind: 'workdir', path: ctx.workDir });
144
149
  const title = `Copy of ${source.title || source.id}`.slice(0, 160);
150
+ let index = null;
151
+ if (ctx.layers) {
152
+ const dir = transcriptDir(ctx.workDir), l = buildLayers(ctx.layers.turns, ctx.layers.subagents, source, dir);
153
+ for (const f of l.files)
154
+ writeNew(join(dir, f.name), f.text);
155
+ index = join(dir, l.readme.name);
156
+ writeNew(index, l.readme.text);
157
+ }
145
158
  if (target === 'Claude Code') {
146
159
  const sid = randomUUID(), file = join(ctx.stores.claude, 'projects', slugForCwd(cwd), `${sid}.jsonl`);
147
160
  writeNew(file, claudeLines(msgs, sid, cwd));
@@ -200,6 +213,10 @@ export async function writeSession(target, msgs, source, ctx) {
200
213
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
201
214
  }
202
215
  // agy
216
+ if (index) {
217
+ record({ kind: 'file', path: index });
218
+ return { id: null, cwd, artifacts, handoff: { file: index, prompt: layersPrompt(index, source.vendor) } };
219
+ }
203
220
  const doc = handoffDocument(msgs, source);
204
221
  const file = join(ctx.workDir, 'handoff.md');
205
222
  writeNew(file, doc.full);
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/primitives",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials), updates (the gated app updater), live (the client for XENO Multiplayer) process (start a command so that stopping it stops everything it started), private-file (owner-only files, published atomically, without a helper process) and sessions (one conversation format with a reader and a writer for each agent, so a session moves between Claude Code, Codex, agy, opencode and the XENO agent).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",