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