@xenosystem/primitives 0.8.0 → 0.9.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 (36) hide show
  1. package/dist/cjs/sessions/agyNative.d.ts +90 -0
  2. package/dist/cjs/sessions/agyNative.js +392 -0
  3. package/dist/cjs/sessions/agyWire.d.ts +181 -0
  4. package/dist/cjs/sessions/agyWire.js +97 -0
  5. package/dist/cjs/sessions/convert.js +26 -29
  6. package/dist/cjs/sessions/index.d.ts +2 -0
  7. package/dist/cjs/sessions/index.js +12 -1
  8. package/dist/cjs/sessions/owned.d.ts +5 -0
  9. package/dist/cjs/sessions/owned.js +38 -0
  10. package/dist/cjs/sessions/protowire.d.ts +29 -0
  11. package/dist/cjs/sessions/protowire.js +114 -0
  12. package/dist/cjs/sessions/read.js +4 -3
  13. package/dist/cjs/sessions/transcript.d.ts +1 -1
  14. package/dist/cjs/sessions/transcript.js +4 -2
  15. package/dist/cjs/sessions/types.d.ts +9 -0
  16. package/dist/cjs/sessions/write.d.ts +1 -0
  17. package/dist/cjs/sessions/write.js +22 -20
  18. package/dist/esm/sessions/agyNative.d.ts +90 -0
  19. package/dist/esm/sessions/agyNative.js +383 -0
  20. package/dist/esm/sessions/agyWire.d.ts +181 -0
  21. package/dist/esm/sessions/agyWire.js +94 -0
  22. package/dist/esm/sessions/convert.js +21 -24
  23. package/dist/esm/sessions/index.d.ts +2 -0
  24. package/dist/esm/sessions/index.js +2 -0
  25. package/dist/esm/sessions/owned.d.ts +5 -0
  26. package/dist/esm/sessions/owned.js +33 -0
  27. package/dist/esm/sessions/protowire.d.ts +29 -0
  28. package/dist/esm/sessions/protowire.js +105 -0
  29. package/dist/esm/sessions/read.js +4 -3
  30. package/dist/esm/sessions/transcript.d.ts +1 -1
  31. package/dist/esm/sessions/transcript.js +4 -2
  32. package/dist/esm/sessions/types.d.ts +9 -0
  33. package/dist/esm/sessions/write.d.ts +1 -0
  34. package/dist/esm/sessions/write.js +23 -21
  35. package/native/win32-x64/process.node +0 -0
  36. package/package.json +1 -1
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ /**
3
+ * agy's (Antigravity's) conversation format: the field numbers and enum values a native conversation is written with.
4
+ *
5
+ * Source: the protobuf schema compiled into agy.exe 1.5.19, extracted with the scripts in `scripts/agy-schema/` (Go programs embed
6
+ * every .proto file they use). `agy-schema.json` beside this file is that extraction, and `agyWire.test.ts` checks every number here
7
+ * against it, so a typo or a schema change fails a test rather than writing a conversation agy misreads.
8
+ *
9
+ * Named as agy's schema names them: `Step` is gemini_coder.Step, the rest are in exa.cortex_pb.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ENUM_NAMES = exports.E = exports.MESSAGE_NAMES = exports.F = exports.AGY_TRAJECTORY = exports.AGY_DB_PRAGMAS = exports.AGY_DB_SQL = void 0;
13
+ /** A conversation is one SQLite file, `conversations/<id>.db`, with these tables exactly as agy creates them. */
14
+ exports.AGY_DB_SQL = [
15
+ 'CREATE TABLE `trajectory_meta` (`trajectory_id` text,`cascade_id` text,`trajectory_type` integer,`source` integer,PRIMARY KEY (`trajectory_id`))',
16
+ 'CREATE TABLE `steps` (`idx` integer,`step_type` integer NOT NULL DEFAULT 0,`status` integer NOT NULL DEFAULT 0,`has_subtrajectory` numeric NOT NULL DEFAULT false,`metadata` blob,`error_details` blob,`permissions` blob,`task_details` blob,`render_info` blob,`step_payload` blob,`step_format` integer NOT NULL DEFAULT 0,PRIMARY KEY (`idx`))',
17
+ 'CREATE INDEX `idx_steps_status` ON `steps`(`status`)',
18
+ 'CREATE INDEX `idx_steps_step_type` ON `steps`(`step_type`)',
19
+ 'CREATE TABLE `gen_metadata` (`idx` integer,`data` blob,`size` integer NOT NULL DEFAULT 0,PRIMARY KEY (`idx`))',
20
+ 'CREATE TABLE `executor_metadata` (`idx` integer,`data` blob,PRIMARY KEY (`idx`))',
21
+ 'CREATE TABLE `parent_references` (`idx` integer,`data` blob,PRIMARY KEY (`idx`))',
22
+ 'CREATE TABLE `trajectory_metadata_blob` (`id` text DEFAULT "main",`data` blob,PRIMARY KEY (`id`))',
23
+ 'CREATE TABLE `battle_mode_infos` (`idx` integer,`data` blob,PRIMARY KEY (`idx`))',
24
+ ];
25
+ /**
26
+ * 🔴 agy refuses a database without these ("trajectory db is not initialized", measured 2026-11-28): schema version 1, and the page
27
+ * size and journal mode it creates its own with.
28
+ */
29
+ exports.AGY_DB_PRAGMAS = ['pragma page_size = 32768', 'pragma journal_mode = wal', 'pragma user_version = 1'];
30
+ /** `trajectory_meta` columns for a conversation, as agy writes them (CORTEX_TRAJECTORY_TYPE_CASCADE, and its source code 17). */
31
+ exports.AGY_TRAJECTORY = { type: 4, source: 17 };
32
+ exports.F = {
33
+ Step: { type: 1, status: 4, metadata: 5, user_input: 19, planner_response: 20, error_message: 24, conversation_history: 111, system_message: 114, generic: 140 },
34
+ CortexStepMetadata: { created_at: 1, source: 3, tool_call: 4, viewable_at: 6, finished_generating_at: 7, completed_at: 8, execution_id: 12,
35
+ source_trajectory_step_info: 20, started_at: 32, model_api_content_id: 35, tool_source: 38 },
36
+ SourceTrajectoryStepInfo: { trajectory_id: 1, step_index: 2, cascade_id: 4 },
37
+ CortexStepUserInput: { query: 1, user_response: 2, items: 3, is_queued_message: 6 },
38
+ TextOrScopeItem: { text: 1 },
39
+ CortexStepPlannerResponse: { response: 1, thinking: 3, message_id: 6, tool_calls: 7 },
40
+ ChatToolCall: { id: 1, name: 2, arguments_json: 3 },
41
+ CortexStepGeneric: { args: 1, result: 2 },
42
+ GenericStepResult: { result: 1, step_render_info: 3 },
43
+ StepRenderInfo: { title: 1, markdown: 2, hidden: 4, title_prefix: 5, icon: 6, aggregation_key: 7, title_parts: 9, content_blocks: 10 },
44
+ TitlePart: { text: 1, file: 2, file_diff: 4 },
45
+ FileRef: { uri: 1, start_line: 2, end_line: 3, total_lines: 4, total_bytes: 5 },
46
+ FileDiffRef: { uri: 1, diff_stats: 2 },
47
+ DiffStats: { additions: 1, deletions: 2 },
48
+ ContentBlock: { markdown: 1, terminal: 3 },
49
+ TerminalBlock: { command: 1, cwd: 2, exit_code: 3, output: 4 },
50
+ CortexStepSystemMessage: { message: 1 },
51
+ CortexStepConversationHistory: { content: 1 },
52
+ CortexTrajectoryMetadata: { workspaces: 1, created_at: 2, root_conversation_id: 6, workspace_uris: 7, project_id: 18 },
53
+ CortexWorkspaceMetadata: { workspace_folder_absolute_uri: 1, repository: 3 },
54
+ CascadeTrajectorySummary: { summary: 1, step_count: 2, last_modified_time: 3, trajectory_id: 4, status: 5, created_time: 7, workspaces: 9,
55
+ last_user_input_time: 10, last_user_input_step_index: 16, trajectory_metadata: 17 },
56
+ Timestamp: { seconds: 1, nanos: 2 },
57
+ };
58
+ /** The schema message each table above is, for the check against `agy-schema.json`. */
59
+ exports.MESSAGE_NAMES = {
60
+ Step: 'gemini_coder.Step',
61
+ CortexStepMetadata: 'exa.cortex_pb.CortexStepMetadata',
62
+ SourceTrajectoryStepInfo: 'exa.cortex_pb.SourceTrajectoryStepInfo',
63
+ CortexStepUserInput: 'exa.cortex_pb.CortexStepUserInput',
64
+ TextOrScopeItem: 'exa.codeium_common_pb.TextOrScopeItem',
65
+ CortexStepPlannerResponse: 'exa.cortex_pb.CortexStepPlannerResponse',
66
+ ChatToolCall: 'exa.codeium_common_pb.ChatToolCall',
67
+ CortexStepGeneric: 'exa.cortex_pb.CortexStepGeneric',
68
+ GenericStepResult: 'exa.cortex_pb.GenericStepResult',
69
+ StepRenderInfo: 'exa.cortex_pb.StepRenderInfo',
70
+ TitlePart: 'exa.cortex_pb.StepRenderInfo.TitlePart',
71
+ FileRef: 'exa.cortex_pb.StepRenderInfo.FileRef',
72
+ FileDiffRef: 'exa.cortex_pb.StepRenderInfo.FileDiffRef',
73
+ DiffStats: 'exa.cortex_pb.DiffStats',
74
+ ContentBlock: 'exa.cortex_pb.StepRenderInfo.ContentBlock',
75
+ TerminalBlock: 'exa.cortex_pb.StepRenderInfo.TerminalBlock',
76
+ CortexStepSystemMessage: 'exa.cortex_pb.CortexStepSystemMessage',
77
+ CortexStepConversationHistory: 'exa.cortex_pb.CortexStepConversationHistory',
78
+ CortexTrajectoryMetadata: 'exa.cortex_pb.CortexTrajectoryMetadata',
79
+ CortexWorkspaceMetadata: 'exa.cortex_pb.CortexWorkspaceMetadata',
80
+ CascadeTrajectorySummary: 'exa.jetski_cortex_pb.CascadeTrajectorySummary',
81
+ Timestamp: 'google.protobuf.Timestamp',
82
+ };
83
+ exports.E = {
84
+ StepType: { USER_INPUT: 14, PLANNER_RESPONSE: 15, ERROR_MESSAGE: 17, CONVERSATION_HISTORY: 98, SYSTEM_MESSAGE: 101, GENERIC: 132 },
85
+ StepStatus: { DONE: 3 },
86
+ StepSource: { MODEL: 2, USER_EXPLICIT: 4, SYSTEM: 5 },
87
+ RunStatus: { IDLE: 1 },
88
+ ComponentSource: { BUILTIN: 1 },
89
+ };
90
+ /** The schema enum and value prefix each table above is, for the same check. */
91
+ exports.ENUM_NAMES = {
92
+ StepType: ['exa.cortex_pb.CortexStepType', 'CORTEX_STEP_TYPE_'],
93
+ StepStatus: ['exa.cortex_pb.CortexStepStatus', 'CORTEX_STEP_STATUS_'],
94
+ StepSource: ['exa.cortex_pb.CortexStepSource', 'CORTEX_STEP_SOURCE_'],
95
+ RunStatus: ['exa.cortex_pb.CascadeRunStatus', 'CASCADE_RUN_STATUS_'],
96
+ ComponentSource: ['exa.cortex_pb.CortexComponentSource', 'CORTEX_COMPONENT_SOURCE_'],
97
+ };
@@ -20,6 +20,8 @@ const read_ts_1 = require("./read.js");
20
20
  const transcript_ts_1 = require("./transcript.js");
21
21
  const write_ts_1 = require("./write.js");
22
22
  const types_ts_1 = require("./types.js");
23
+ const owned_ts_1 = require("./owned.js");
24
+ const agyNative_ts_1 = require("./agyNative.js");
23
25
  const asVendor = (v) => {
24
26
  if (!types_ts_1.VENDORS.includes(v))
25
27
  throw new Error(`Unknown agent: ${v}. Known: ${types_ts_1.VENDORS.join(', ')}.`);
@@ -49,7 +51,7 @@ async function prepare(source, target, ctx, fullRecord) {
49
51
  const transcript = (0, transcript_ts_1.toTranscript)(turns, subagents, { fullRecord });
50
52
  if (!transcript.messages.length)
51
53
  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') };
54
+ 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', t.tools) };
53
55
  return { ref, turns, subagents, transcript, plan };
54
56
  }
55
57
  /** What a conversion WOULD do, writing nothing. The source's agent may be left out: it is found from the id. */
@@ -74,7 +76,14 @@ async function convertSession(source, target, ctx) {
74
76
  step('Verifying');
75
77
  if (await fingerprint(ref, ctx) !== before)
76
78
  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) {
79
+ if (written.id && plan.target === 'agy') {
80
+ // agy writes its summary row for a new conversation file when it next lists, so agy itself is asked; that listing is also what
81
+ // makes the row, so the copy is in agy's list from here on.
82
+ const out = await ctx.run('agy', ['conversations', 'list'], { env: (0, agyNative_ts_1.agyEnv)(ctx.stores.agy) }).catch((e) => String(e));
83
+ if (!out.includes(written.id))
84
+ throw new Error('agy does not list the copy it was given.');
85
+ }
86
+ else if (written.id) {
78
87
  const seen = await (0, read_ts_1.findSession)(plan.target, written.id, ctx).catch(() => null);
79
88
  if (!seen)
80
89
  throw new Error(`${plan.target} does not list the copy it was given.`);
@@ -91,36 +100,15 @@ async function convertSession(source, target, ctx) {
91
100
  }
92
101
  }
93
102
  /* ------------------------------------------------------------------ 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
103
  /**
116
104
  * 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
105
  * staging folder. `allowed` limits a vendor folder to the files a writer creates.
118
106
  */
119
107
  function removeOwnedPath(root, path, allowed = null) {
120
- const target = ownedPath(root, path);
108
+ const target = (0, owned_ts_1.ownedPath)(root, path);
121
109
  const entries = [];
122
110
  const walk = (p) => {
123
- ownedPath(root, p);
111
+ (0, owned_ts_1.ownedPath)(root, p);
124
112
  let st;
125
113
  try {
126
114
  st = (0, node_fs_1.lstatSync)(p);
@@ -143,7 +131,7 @@ function removeOwnedPath(root, path, allowed = null) {
143
131
  };
144
132
  walk(target);
145
133
  for (const e of entries) {
146
- ownedPath(root, e.path);
134
+ (0, owned_ts_1.ownedPath)(root, e.path);
147
135
  const st = (0, node_fs_1.lstatSync)(e.path);
148
136
  if (st.dev !== e.dev || st.ino !== e.ino || st.isDirectory() !== e.dir)
149
137
  throw new Error(`Artifact changed during cleanup: ${e.path}`);
@@ -175,6 +163,15 @@ async function removeArtifacts(artifacts, ctx) {
175
163
  throw new Error(`not an opencode session id: ${a.id}`);
176
164
  await ctx.run('opencode', ['session', 'delete', a.id]);
177
165
  }
166
+ else if (a.vendor === 'agy') {
167
+ // agy's own delete, which also drops its summary row and the brain folder it made when the copy was opened.
168
+ if (!/^[0-9a-f-]{36}$/i.test(a.id))
169
+ throw new Error(`not an agy conversation id: ${a.id}`);
170
+ await ctx.run('agy', ['conversations', 'clean', '--yes', a.id], { env: (0, agyNative_ts_1.agyEnv)(ctx.stores.agy) });
171
+ const left = (0, node_path_1.join)(ctx.stores.agy, 'conversations', `${a.id}.db`);
172
+ if ((0, node_fs_1.existsSync)(left))
173
+ throw new Error(`agy did not delete ${left}`);
174
+ }
178
175
  else
179
176
  throw new Error(`no deletion path for a ${a.vendor} session`);
180
177
  }
@@ -187,14 +184,14 @@ async function removeArtifacts(artifacts, ctx) {
187
184
  removeOwnedPath(workdir, a.path);
188
185
  continue;
189
186
  }
190
- const projects = (0, node_path_1.join)(ctx.stores.claude, 'projects');
191
- ownedPath(projects, a.path);
187
+ const projects = (0, owned_ts_1.claudeProjectsDir)(ctx.stores);
188
+ (0, owned_ts_1.ownedPath)(projects, a.path);
192
189
  if (!/^[0-9a-f-]{36}\.jsonl$/i.test((0, node_path_1.basename)(a.path)))
193
190
  throw new Error(`not a converted Claude session file: ${a.path}`);
194
191
  removeOwnedPath(projects, a.path);
195
192
  }
196
193
  else if (a.kind === 'dir') {
197
- const sessions = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions'), path = ownedPath(sessions, a.path);
194
+ const sessions = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions'), path = (0, owned_ts_1.ownedPath)(sessions, a.path);
198
195
  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
196
  throw new Error(`not a converted XENO agent session: ${path}`);
200
197
  removeOwnedPath(sessions, path, ['meta.json', 'transcript.jsonl', 'session.lock', 'audit.jsonl', 'transcript.md']);
@@ -11,3 +11,5 @@ export { toTranscript, losses, type Transcript, type Message, type Report } from
11
11
  export { buildLayers, layersPrompt, RECENT_CAP, type Layer, type Layers } from './layers.ts';
12
12
  export { TARGETS, writeSession, handoffDocument, claudeLines, slugForCwd, transcriptDir, type Artifact, type Written, type WriteContext } from './write.ts';
13
13
  export { planConversion, convertSession, removeArtifacts, fingerprint, locateSession, type Plan, type Conversion, type SourceSpec } from './convert.ts';
14
+ export { ownedPath, claudeProjectsDir } from './owned.ts';
15
+ export { writeAgyConversation, agySteps, agyTool, agyEnv, userKind, AGY_STEP_CAP, AGY_TOTAL_CAP, type AgyWritten, type AgyReport } from './agyNative.ts';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
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;
3
+ exports.AGY_TOTAL_CAP = exports.AGY_STEP_CAP = exports.userKind = exports.agyEnv = exports.agyTool = exports.agySteps = exports.writeAgyConversation = exports.claudeProjectsDir = exports.ownedPath = 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
4
  /**
5
5
  * @xenosystem/primitives/sessions: one agent-neutral conversation format, with a reader and a writer for each agent (Claude Code,
6
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.
@@ -44,3 +44,14 @@ Object.defineProperty(exports, "convertSession", { enumerable: true, get: functi
44
44
  Object.defineProperty(exports, "removeArtifacts", { enumerable: true, get: function () { return convert_ts_1.removeArtifacts; } });
45
45
  Object.defineProperty(exports, "fingerprint", { enumerable: true, get: function () { return convert_ts_1.fingerprint; } });
46
46
  Object.defineProperty(exports, "locateSession", { enumerable: true, get: function () { return convert_ts_1.locateSession; } });
47
+ var owned_ts_1 = require("./owned.js");
48
+ Object.defineProperty(exports, "ownedPath", { enumerable: true, get: function () { return owned_ts_1.ownedPath; } });
49
+ Object.defineProperty(exports, "claudeProjectsDir", { enumerable: true, get: function () { return owned_ts_1.claudeProjectsDir; } });
50
+ var agyNative_ts_1 = require("./agyNative.js");
51
+ Object.defineProperty(exports, "writeAgyConversation", { enumerable: true, get: function () { return agyNative_ts_1.writeAgyConversation; } });
52
+ Object.defineProperty(exports, "agySteps", { enumerable: true, get: function () { return agyNative_ts_1.agySteps; } });
53
+ Object.defineProperty(exports, "agyTool", { enumerable: true, get: function () { return agyNative_ts_1.agyTool; } });
54
+ Object.defineProperty(exports, "agyEnv", { enumerable: true, get: function () { return agyNative_ts_1.agyEnv; } });
55
+ Object.defineProperty(exports, "userKind", { enumerable: true, get: function () { return agyNative_ts_1.userKind; } });
56
+ Object.defineProperty(exports, "AGY_STEP_CAP", { enumerable: true, get: function () { return agyNative_ts_1.AGY_STEP_CAP; } });
57
+ Object.defineProperty(exports, "AGY_TOTAL_CAP", { enumerable: true, get: function () { return agyNative_ts_1.AGY_TOTAL_CAP; } });
@@ -0,0 +1,5 @@
1
+ import type { Stores } from './types.ts';
2
+ /** `path`, strictly inside `root`, with no symlink or junction at any component up to the filesystem root. Throws otherwise. */
3
+ export declare function ownedPath(root: string, path: string): string;
4
+ /** Claude Code's project folders: `stores.claudeProjects` when a caller keeps them elsewhere, else `<claude>/projects`. */
5
+ export declare const claudeProjectsDir: (stores: Stores) => string;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.claudeProjectsDir = void 0;
4
+ exports.ownedPath = ownedPath;
5
+ /**
6
+ * Where a converter may write and delete: strictly inside an agent's own store, with no link anywhere on the way. Shared by the writers
7
+ * (write.ts) and the removal (convert.ts), so a path refused for deletion is refused for creation too.
8
+ *
9
+ * 🔴 A copy is never written THROUGH a junction or symlink (0.8.1, moved down from XENO Spawn's `ownedFiles.js`): a store reached
10
+ * through a link puts the copy somewhere the person did not choose, and its removal later deletes there too. A prefix check on the
11
+ * string cannot see a link; only walking the path with lstat can.
12
+ */
13
+ const node_fs_1 = require("node:fs");
14
+ const node_path_1 = require("node:path");
15
+ /** `path`, strictly inside `root`, with no symlink or junction at any component up to the filesystem root. Throws otherwise. */
16
+ function ownedPath(root, path) {
17
+ const base = (0, node_path_1.resolve)(root), target = (0, node_path_1.resolve)(path), rel = (0, node_path_1.relative)(base, target);
18
+ if (!rel || rel === '..' || rel.startsWith('..\\') || rel.startsWith('../') || (0, node_path_1.isAbsolute)(rel))
19
+ throw new Error(`Path is not strictly inside its ownership root: ${target}`);
20
+ for (let part = target;;) {
21
+ try {
22
+ if ((0, node_fs_1.lstatSync)(part).isSymbolicLink())
23
+ throw new Error(`Refusing reparse point/symlink: ${part}`);
24
+ }
25
+ catch (e) {
26
+ if (e.code !== 'ENOENT')
27
+ throw e;
28
+ }
29
+ const parent = (0, node_path_1.dirname)(part);
30
+ if (parent === part)
31
+ break;
32
+ part = parent;
33
+ }
34
+ return target;
35
+ }
36
+ /** Claude Code's project folders: `stores.claudeProjects` when a caller keeps them elsewhere, else `<claude>/projects`. */
37
+ const claudeProjectsDir = (stores) => stores.claudeProjects ?? (0, node_path_1.join)(stores.claude, 'projects');
38
+ exports.claudeProjectsDir = claudeProjectsDir;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The protobuf wire format, the part a writer needs: varints, length-delimited fields and nested messages, and a reader for tests.
3
+ * Written here because the package carries no runtime dependency; the schema it encodes against is agy's own (agyWire.ts).
4
+ *
5
+ * A message is built as a list of fields in field-number order, the order protobuf encoders emit, so the bytes match what agy writes.
6
+ */
7
+ /** A field value: a number (varint), a string or bytes (length-delimited), a nested message, or a list of any of these (repeated). */
8
+ export type Value = number | bigint | boolean | string | Uint8Array | Msg | Value[] | null | undefined;
9
+ /** A message as field number to value. Absent, null, undefined, false, 0 and '' are left out, as proto3 does for defaults. */
10
+ export type Msg = {
11
+ [field: number]: Value;
12
+ };
13
+ /** Encode a message. A nested message that is empty is still written when it is given as `{}` explicitly inside a list or as a value. */
14
+ export declare function encode(m: Msg): Uint8Array;
15
+ /** A map<string, string> field: protobuf writes each entry as a message of key (1) and value (2). */
16
+ export declare const mapEntries: (o: Record<string, string>) => Msg[];
17
+ /** A google.protobuf.Timestamp for an ISO time or epoch milliseconds. */
18
+ export declare function timestamp(at: string | number | null | undefined, fallbackMs: number): Msg;
19
+ export interface Field {
20
+ n: number;
21
+ wire: number;
22
+ int?: bigint;
23
+ bytes?: Uint8Array;
24
+ }
25
+ /** Split one message into its raw fields, in order. */
26
+ export declare function fields(b: Uint8Array): Field[];
27
+ /** Follow a path of field numbers through nested messages and answer every value found at its end. */
28
+ export declare function at(b: Uint8Array, ...path: number[]): Field[];
29
+ export declare const text: (f: Field | undefined) => string | undefined;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ /**
3
+ * The protobuf wire format, the part a writer needs: varints, length-delimited fields and nested messages, and a reader for tests.
4
+ * Written here because the package carries no runtime dependency; the schema it encodes against is agy's own (agyWire.ts).
5
+ *
6
+ * A message is built as a list of fields in field-number order, the order protobuf encoders emit, so the bytes match what agy writes.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.text = exports.mapEntries = void 0;
10
+ exports.encode = encode;
11
+ exports.timestamp = timestamp;
12
+ exports.fields = fields;
13
+ exports.at = at;
14
+ function varint(n, out) {
15
+ let v = BigInt.asUintN(64, BigInt(n));
16
+ while (v > 0x7fn) {
17
+ out.push(Number(v & 0x7fn) | 0x80);
18
+ v >>= 7n;
19
+ }
20
+ out.push(Number(v));
21
+ }
22
+ const utf8 = new TextEncoder();
23
+ function isMsg(v) { return typeof v === 'object' && v !== null && !(v instanceof Uint8Array) && !Array.isArray(v); }
24
+ function field(n, v, out) {
25
+ if (v === undefined || v === null || v === false || v === 0 || v === 0n || v === '')
26
+ return;
27
+ if (Array.isArray(v)) {
28
+ for (const item of v)
29
+ field(n, item, out);
30
+ return;
31
+ }
32
+ if (typeof v === 'number' || typeof v === 'bigint' || typeof v === 'boolean') {
33
+ if (typeof v === 'number' && !Number.isInteger(v))
34
+ throw new Error(`field ${n}: ${v} is not an integer`);
35
+ varint(n << 3, out);
36
+ varint(v === true ? 1 : v, out);
37
+ return;
38
+ }
39
+ const bytes = typeof v === 'string' ? utf8.encode(v) : v instanceof Uint8Array ? v : encode(v);
40
+ varint((n << 3) | 2, out);
41
+ varint(bytes.length, out);
42
+ for (const b of bytes)
43
+ out.push(b);
44
+ }
45
+ /** Encode a message. A nested message that is empty is still written when it is given as `{}` explicitly inside a list or as a value. */
46
+ function encode(m) {
47
+ const out = [];
48
+ for (const k of Object.keys(m).map(Number).sort((a, b) => a - b)) {
49
+ const v = m[k];
50
+ // An explicitly empty nested message is meaningful (agy writes `repository {}`), so it is kept, unlike an empty scalar.
51
+ if (isMsg(v) && Object.keys(v).length === 0) {
52
+ varint((k << 3) | 2, out);
53
+ out.push(0);
54
+ continue;
55
+ }
56
+ field(k, v, out);
57
+ }
58
+ return Uint8Array.from(out);
59
+ }
60
+ /** A map<string, string> field: protobuf writes each entry as a message of key (1) and value (2). */
61
+ const mapEntries = (o) => Object.entries(o).map(([k, v]) => ({ 1: k, 2: v }));
62
+ exports.mapEntries = mapEntries;
63
+ /** A google.protobuf.Timestamp for an ISO time or epoch milliseconds. */
64
+ function timestamp(at, fallbackMs) {
65
+ const ms = typeof at === 'number' ? at : at ? Date.parse(at) : NaN;
66
+ const t = Number.isFinite(ms) ? ms : fallbackMs;
67
+ return { 1: Math.floor(t / 1000), 2: Math.round((t % 1000) * 1e6) || 0 };
68
+ }
69
+ /** Split one message into its raw fields, in order. */
70
+ function fields(b) {
71
+ const out = [];
72
+ let i = 0;
73
+ const read = () => { let s = 0n, v = 0n; for (;;) {
74
+ if (i >= b.length)
75
+ throw new Error('truncated varint');
76
+ const c = b[i++];
77
+ v |= BigInt(c & 0x7f) << s;
78
+ if (!(c & 0x80))
79
+ return v;
80
+ s += 7n;
81
+ } };
82
+ while (i < b.length) {
83
+ const tag = Number(read()), n = tag >> 3, wire = tag & 7;
84
+ if (wire === 0)
85
+ out.push({ n, wire, int: read() });
86
+ else if (wire === 2) {
87
+ const len = Number(read());
88
+ if (i + len > b.length)
89
+ throw new Error('truncated field');
90
+ out.push({ n, wire, bytes: b.subarray(i, i + len) });
91
+ i += len;
92
+ }
93
+ else if (wire === 1) {
94
+ out.push({ n, wire, bytes: b.subarray(i, i + 8) });
95
+ i += 8;
96
+ }
97
+ else if (wire === 5) {
98
+ out.push({ n, wire, bytes: b.subarray(i, i + 4) });
99
+ i += 4;
100
+ }
101
+ else
102
+ throw new Error(`unsupported wire type ${wire}`);
103
+ }
104
+ return out;
105
+ }
106
+ /** Follow a path of field numbers through nested messages and answer every value found at its end. */
107
+ function at(b, ...path) {
108
+ let level = [{ n: 0, wire: 2, bytes: b }];
109
+ for (const n of path)
110
+ level = level.flatMap((f) => (f.bytes ? fields(f.bytes) : []).filter((x) => x.n === n));
111
+ return level;
112
+ }
113
+ const text = (f) => (f?.bytes ? new TextDecoder().decode(f.bytes) : undefined);
114
+ exports.text = text;
@@ -24,6 +24,7 @@ const node_fs_1 = require("node:fs");
24
24
  const node_path_1 = require("node:path");
25
25
  const node_readline_1 = require("node:readline");
26
26
  const types_ts_1 = require("./types.js");
27
+ const owned_ts_1 = require("./owned.js");
27
28
  const TITLE_CAP = 160, LINE_CAP = 8 << 20;
28
29
  const SAFE_ID = /^[A-Za-z0-9._:-]{1,128}$/;
29
30
  /** A session id an agent's command can take as one word, or null. */
@@ -130,7 +131,7 @@ function claudeHeadIn(text) {
130
131
  const claude = {
131
132
  vendor: 'Claude Code',
132
133
  async list({ stores }) {
133
- const root = (0, node_path_1.join)(stores.claude, 'projects');
134
+ const root = (0, owned_ts_1.claudeProjectsDir)(stores);
134
135
  if (!(0, node_fs_1.existsSync)(root))
135
136
  return [];
136
137
  const out = [];
@@ -181,7 +182,7 @@ const claude = {
181
182
  const text = typeof q.prompt === 'string' ? q.prompt : blocksText(q.prompt);
182
183
  const last = turns[turns.length - 1];
183
184
  if (text.trim() && !(last?.role === 'user' && last.text === text))
184
- turns.push({ role: 'user', text, at: q.timestamp ?? at, ...(q.origin?.kind === 'human' ? {} : { from: q.origin?.kind === 'peer' ? 'peer' : 'harness' }) });
185
+ turns.push({ role: 'user', text, at: q.timestamp ?? at, ...(q.origin?.kind === 'human' ? { queued: true } : { from: q.origin?.kind === 'peer' ? 'peer' : 'harness' }) });
185
186
  return;
186
187
  }
187
188
  if (r.type === 'system' && r.subtype === 'compact_boundary') {
@@ -202,7 +203,7 @@ const claude = {
202
203
  if (b?.type === 'text' && !r.isMeta)
203
204
  turns.push({ role: 'user', text: b.text, at });
204
205
  else if (b?.type === 'tool_result')
205
- turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: kept(blocksText(b.content)), at });
206
+ turns.push({ role: 'tool', text: '', callId: b.tool_use_id, output: kept(blocksText(b.content)), at, ...(b.is_error ? { isError: true } : {}) });
206
207
  }
207
208
  }
208
209
  else if (r.type === 'assistant') {
@@ -40,4 +40,4 @@ export declare function toTranscript(turns: Turn[], subagents?: Subagent[], opts
40
40
  fullRecord?: string;
41
41
  }): Transcript;
42
42
  /** What the move loses, in plain words, for a person to read before it runs. */
43
- export declare function losses(report: Report, target: string, handoff: boolean): string[];
43
+ export declare function losses(report: Report, target: string, handoff: boolean, tools?: 'native' | 'text'): string[];
@@ -102,11 +102,13 @@ function toTranscript(turns, subagents = [], opts = {}) {
102
102
  return { messages: kept, report };
103
103
  }
104
104
  /** What the move loses, in plain words, for a person to read before it runs. */
105
- function losses(report, target, handoff) {
105
+ function losses(report, target, handoff, tools = 'text') {
106
106
  const s = (n) => n === 1 ? '' : 's';
107
107
  return [
108
108
  report.thinkingDropped && `${report.thinkingDropped} thinking block${s(report.thinkingDropped)} dropped (signed by the original agent; never forged)`,
109
- report.toolCalls && `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} labelled text (${target} cannot re-run another agent's tools)`,
109
+ report.toolCalls && (tools === 'native'
110
+ ? `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} ${target}'s own tool step${s(report.toolCalls)}, with ${report.toolCalls === 1 ? 'its' : 'their'} results (they are not run again)`
111
+ : `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} labelled text (${target} cannot re-run another agent's tools)`),
110
112
  // A hand-over IS the full record, so only a resumable copy leaves anything out.
111
113
  !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)`,
112
114
  report.truncated && `${report.truncated} long output${s(report.truncated)} shortened`,
@@ -40,6 +40,10 @@ export interface Turn {
40
40
  * harness (a finished background job, 'harness'). Absent for the person's own words.
41
41
  */
42
42
  from?: 'peer' | 'harness';
43
+ /** The person typed it while a turn was running (Claude Code keeps those as `queued_command`); agy marks them `is_queued_message`. */
44
+ queued?: boolean;
45
+ /** A tool result the agent recorded as an error (Claude Code's `is_error`). */
46
+ isError?: boolean;
43
47
  }
44
48
  /** A sub-agent's own conversation, which some agents (Claude Code) keep in separate files. */
45
49
  export interface Subagent {
@@ -50,6 +54,11 @@ export interface Subagent {
50
54
  export interface Stores {
51
55
  /** Claude Code's configuration folder (its sessions are under `projects/`). */
52
56
  claude: string;
57
+ /**
58
+ * Claude Code's project folders, when a caller keeps them somewhere other than `<claude>/projects` (XENO Spawn's isolated test homes
59
+ * do). Optional; absent means `<claude>/projects`.
60
+ */
61
+ claudeProjects?: string;
53
62
  /** Codex's home (`sessions/`, `state_5.sqlite`). */
54
63
  codex: string;
55
64
  /** agy's (Antigravity CLI) data folder (`conversation_summaries.db`, `brain/`). */
@@ -4,6 +4,7 @@ import type { Runner, SessionRef, Stores, Subagent, Turn, Vendor } from './types
4
4
  export declare const TARGETS: Readonly<Record<Vendor, {
5
5
  fidelity: 'native' | 'handoff';
6
6
  via: string;
7
+ tools: 'native' | 'text';
7
8
  }>>;
8
9
  /** What a writer created, so a caller can remove exactly that and nothing else. */
9
10
  export type Artifact = {
@@ -16,9 +16,11 @@ exports.writeSession = writeSession;
16
16
  * private home (it reads only Claude files under its detection root)
17
17
  * opencode `opencode import <export.json>`, recording a model opencode itself lists
18
18
  * XENO agent `sessions/<id>/{meta.json,transcript.jsonl}` in its documented layout
19
- * agy no ingestion path exists (its list is a SQLite table the running app writes, each conversation eight tables of
20
- * undocumented protobuf; measured 2026-11-28) → a HANDOFF: the full record, layered, with an index a new agy
21
- * conversation is asked to read, declared as such
19
+ * agy a new `conversations/<id>.db` in agy's own format, with the schema taken from agy.exe (agyNative.ts): agy lists it,
20
+ * resumes it with `--conversation` and writes its own summary row. agy has no import command, so this one file is
21
+ * the target's own layout (as for Claude Code and the XENO agent); the list database is never written. Each tool
22
+ * call becomes agy's own tool step, drawn as agy draws its own (owner, 2026-11-28: "proper session resume not
23
+ * handover", "loops, goals, commands … full scale … 1:1 in the interface").
22
24
  * Every copy also carries the full record of the original in `<workDir>/transcript/` (layers.ts), so nothing the copy itself cannot
23
25
  * hold is lost. Every file is created exclusively at its final name, so nothing that exists is ever replaced.
24
26
  */
@@ -29,13 +31,15 @@ const run_ts_1 = require("./run.js");
29
31
  const read_ts_1 = require("./read.js");
30
32
  const transcript_ts_1 = require("./transcript.js");
31
33
  const layers_ts_1 = require("./layers.js");
34
+ const owned_ts_1 = require("./owned.js");
35
+ const agyNative_ts_1 = require("./agyNative.js");
32
36
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
33
37
  exports.TARGETS = Object.freeze({
34
- 'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout" },
35
- Codex: { fidelity: 'native', via: "Codex's own external-session importer (from a Claude-shaped copy)" },
36
- opencode: { fidelity: 'native', via: 'opencode import' },
37
- 'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout" },
38
- agy: { fidelity: 'handoff', via: 'a new conversation given the transcript as context (agy has no import)' },
38
+ 'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout", tools: 'text' },
39
+ Codex: { fidelity: 'native', via: "Codex's own external-session importer (from a Claude-shaped copy)", tools: 'text' },
40
+ opencode: { fidelity: 'native', via: 'opencode import', tools: 'text' },
41
+ 'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout", tools: 'text' },
42
+ agy: { fidelity: 'native', via: "a new conversation file in agy's own format, resumed with agy --conversation", tools: 'native' },
39
43
  });
40
44
  /** Where a conversion keeps the layered record of the original, inside its own folder. */
41
45
  const transcriptDir = (workDir) => (0, node_path_1.join)(workDir, 'transcript');
@@ -152,6 +156,7 @@ async function writeSession(target, msgs, source, ctx) {
152
156
  const record = (a) => { artifacts.push(a); ctx.record?.(a); };
153
157
  if ((0, node_fs_1.existsSync)(ctx.workDir))
154
158
  throw new Error(`Refusing to reuse ${ctx.workDir}: a conversion's folder must be new.`);
159
+ (0, owned_ts_1.ownedPath)((0, node_path_1.dirname)(ctx.workDir), ctx.workDir);
155
160
  (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(ctx.workDir), { recursive: true });
156
161
  (0, node_fs_1.mkdirSync)(ctx.workDir);
157
162
  record({ kind: 'workdir', path: ctx.workDir });
@@ -165,7 +170,7 @@ async function writeSession(target, msgs, source, ctx) {
165
170
  writeNew(index, l.readme.text);
166
171
  }
167
172
  if (target === 'Claude Code') {
168
- const sid = (0, node_crypto_1.randomUUID)(), file = (0, node_path_1.join)(ctx.stores.claude, 'projects', (0, exports.slugForCwd)(cwd), `${sid}.jsonl`);
173
+ const projects = (0, owned_ts_1.claudeProjectsDir)(ctx.stores), sid = (0, node_crypto_1.randomUUID)(), file = (0, owned_ts_1.ownedPath)(projects, (0, node_path_1.join)(projects, (0, exports.slugForCwd)(cwd), `${sid}.jsonl`));
169
174
  writeNew(file, claudeLines(msgs, sid, cwd));
170
175
  record({ kind: 'file', path: file });
171
176
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
@@ -207,7 +212,7 @@ async function writeSession(target, msgs, source, ctx) {
207
212
  }
208
213
  if (target === 'XENO agent') {
209
214
  const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
210
- const sid = `xeno-copy-${stamp}-${(0, node_crypto_1.randomUUID)().slice(0, 5)}`, dir = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions', sid);
215
+ const sessions = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions'), sid = `xeno-copy-${stamp}-${(0, node_crypto_1.randomUUID)().slice(0, 5)}`, dir = (0, owned_ts_1.ownedPath)(sessions, (0, node_path_1.join)(sessions, sid));
211
216
  if ((0, node_fs_1.existsSync)(dir))
212
217
  throw new Error(`Refusing to overwrite ${dir}`);
213
218
  (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(dir), { recursive: true });
@@ -221,14 +226,11 @@ async function writeSession(target, msgs, source, ctx) {
221
226
  .map((r, i) => JSON.stringify({ id: `e${i}`, timestamp: at, sequence: i, ...r })).join('\n') + '\n');
222
227
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
223
228
  }
224
- // agy
225
- if (index) {
226
- record({ kind: 'file', path: index });
227
- return { id: null, cwd, artifacts, handoff: { file: index, prompt: (0, layers_ts_1.layersPrompt)(index, source.vendor) } };
228
- }
229
- const doc = handoffDocument(msgs, source);
230
- const file = (0, node_path_1.join)(ctx.workDir, 'handoff.md');
231
- writeNew(file, doc.full);
232
- record({ kind: 'file', path: file });
233
- return { id: null, cwd, artifacts, handoff: { file, prompt: doc.prompt(file) } };
229
+ // agy: its own conversation file, from the turns themselves so every tool call keeps its kind. Without the turns (a caller that only
230
+ // has the portable messages), the messages become the turns.
231
+ const turns = ctx.layers?.turns ?? msgs.map((m) => ({ role: m.role, text: m.text, at: m.at }));
232
+ const full = index ? (0, node_path_1.join)((0, node_path_1.dirname)(index), 'full.md') : undefined;
233
+ const written = await (0, agyNative_ts_1.writeAgyConversation)(turns, ctx.layers?.subagents ?? [], { store: ctx.stores.agy, cwd, ...(full ? { fullRecord: full } : {}) });
234
+ record({ kind: 'vendor-session', vendor: 'agy', id: written.id });
235
+ return { id: written.id, cwd, artifacts, resume: ['--conversation', written.id] };
234
236
  }