@xenosystem/primitives 0.8.1 → 0.10.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 (50) hide show
  1. package/dist/cjs/dirs/procinfo.js +5 -0
  2. package/dist/cjs/process/index.d.ts +1 -0
  3. package/dist/cjs/process/index.js +10 -21
  4. package/dist/cjs/process/native.d.ts +22 -0
  5. package/dist/cjs/process/native.js +50 -0
  6. package/dist/cjs/secrets/dpapi.d.ts +9 -0
  7. package/dist/cjs/secrets/dpapi.js +53 -0
  8. package/dist/cjs/secrets/index.d.ts +1 -0
  9. package/dist/cjs/secrets/index.js +5 -1
  10. package/dist/cjs/sessions/agyNative.d.ts +90 -0
  11. package/dist/cjs/sessions/agyNative.js +392 -0
  12. package/dist/cjs/sessions/agyWire.d.ts +181 -0
  13. package/dist/cjs/sessions/agyWire.js +97 -0
  14. package/dist/cjs/sessions/convert.js +19 -2
  15. package/dist/cjs/sessions/index.d.ts +1 -0
  16. package/dist/cjs/sessions/index.js +9 -1
  17. package/dist/cjs/sessions/protowire.d.ts +29 -0
  18. package/dist/cjs/sessions/protowire.js +114 -0
  19. package/dist/cjs/sessions/read.js +2 -2
  20. package/dist/cjs/sessions/transcript.d.ts +1 -1
  21. package/dist/cjs/sessions/transcript.js +4 -2
  22. package/dist/cjs/sessions/types.d.ts +4 -0
  23. package/dist/cjs/sessions/write.d.ts +1 -0
  24. package/dist/cjs/sessions/write.js +18 -18
  25. package/dist/esm/dirs/procinfo.js +5 -0
  26. package/dist/esm/process/index.d.ts +1 -0
  27. package/dist/esm/process/index.js +8 -21
  28. package/dist/esm/process/native.d.ts +22 -0
  29. package/dist/esm/process/native.js +46 -0
  30. package/dist/esm/secrets/dpapi.d.ts +9 -0
  31. package/dist/esm/secrets/dpapi.js +48 -0
  32. package/dist/esm/secrets/index.d.ts +1 -0
  33. package/dist/esm/secrets/index.js +1 -0
  34. package/dist/esm/sessions/agyNative.d.ts +90 -0
  35. package/dist/esm/sessions/agyNative.js +383 -0
  36. package/dist/esm/sessions/agyWire.d.ts +181 -0
  37. package/dist/esm/sessions/agyWire.js +94 -0
  38. package/dist/esm/sessions/convert.js +19 -2
  39. package/dist/esm/sessions/index.d.ts +1 -0
  40. package/dist/esm/sessions/index.js +1 -0
  41. package/dist/esm/sessions/protowire.d.ts +29 -0
  42. package/dist/esm/sessions/protowire.js +105 -0
  43. package/dist/esm/sessions/read.js +2 -2
  44. package/dist/esm/sessions/transcript.d.ts +1 -1
  45. package/dist/esm/sessions/transcript.js +4 -2
  46. package/dist/esm/sessions/types.d.ts +4 -0
  47. package/dist/esm/sessions/write.d.ts +1 -0
  48. package/dist/esm/sessions/write.js +19 -19
  49. package/native/win32-x64/process.node +0 -0
  50. package/package.json +1 -1
@@ -0,0 +1,181 @@
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 declare const AGY_DB_SQL: readonly ["CREATE TABLE `trajectory_meta` (`trajectory_id` text,`cascade_id` text,`trajectory_type` integer,`source` integer,PRIMARY KEY (`trajectory_id`))", "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`))", "CREATE INDEX `idx_steps_status` ON `steps`(`status`)", "CREATE INDEX `idx_steps_step_type` ON `steps`(`step_type`)", "CREATE TABLE `gen_metadata` (`idx` integer,`data` blob,`size` integer NOT NULL DEFAULT 0,PRIMARY KEY (`idx`))", "CREATE TABLE `executor_metadata` (`idx` integer,`data` blob,PRIMARY KEY (`idx`))", "CREATE TABLE `parent_references` (`idx` integer,`data` blob,PRIMARY KEY (`idx`))", "CREATE TABLE `trajectory_metadata_blob` (`id` text DEFAULT \"main\",`data` blob,PRIMARY KEY (`id`))", "CREATE TABLE `battle_mode_infos` (`idx` integer,`data` blob,PRIMARY KEY (`idx`))"];
12
+ /**
13
+ * 🔴 agy refuses a database without these ("trajectory db is not initialized", measured 2026-11-28): schema version 1, and the page
14
+ * size and journal mode it creates its own with.
15
+ */
16
+ export declare const AGY_DB_PRAGMAS: readonly ["pragma page_size = 32768", "pragma journal_mode = wal", "pragma user_version = 1"];
17
+ /** `trajectory_meta` columns for a conversation, as agy writes them (CORTEX_TRAJECTORY_TYPE_CASCADE, and its source code 17). */
18
+ export declare const AGY_TRAJECTORY: {
19
+ readonly type: 4;
20
+ readonly source: 17;
21
+ };
22
+ export declare const F: {
23
+ readonly Step: {
24
+ readonly type: 1;
25
+ readonly status: 4;
26
+ readonly metadata: 5;
27
+ readonly user_input: 19;
28
+ readonly planner_response: 20;
29
+ readonly error_message: 24;
30
+ readonly conversation_history: 111;
31
+ readonly system_message: 114;
32
+ readonly generic: 140;
33
+ };
34
+ readonly CortexStepMetadata: {
35
+ readonly created_at: 1;
36
+ readonly source: 3;
37
+ readonly tool_call: 4;
38
+ readonly viewable_at: 6;
39
+ readonly finished_generating_at: 7;
40
+ readonly completed_at: 8;
41
+ readonly execution_id: 12;
42
+ readonly source_trajectory_step_info: 20;
43
+ readonly started_at: 32;
44
+ readonly model_api_content_id: 35;
45
+ readonly tool_source: 38;
46
+ };
47
+ readonly SourceTrajectoryStepInfo: {
48
+ readonly trajectory_id: 1;
49
+ readonly step_index: 2;
50
+ readonly cascade_id: 4;
51
+ };
52
+ readonly CortexStepUserInput: {
53
+ readonly query: 1;
54
+ readonly user_response: 2;
55
+ readonly items: 3;
56
+ readonly is_queued_message: 6;
57
+ };
58
+ readonly TextOrScopeItem: {
59
+ readonly text: 1;
60
+ };
61
+ readonly CortexStepPlannerResponse: {
62
+ readonly response: 1;
63
+ readonly thinking: 3;
64
+ readonly message_id: 6;
65
+ readonly tool_calls: 7;
66
+ };
67
+ readonly ChatToolCall: {
68
+ readonly id: 1;
69
+ readonly name: 2;
70
+ readonly arguments_json: 3;
71
+ };
72
+ readonly CortexStepGeneric: {
73
+ readonly args: 1;
74
+ readonly result: 2;
75
+ };
76
+ readonly GenericStepResult: {
77
+ readonly result: 1;
78
+ readonly step_render_info: 3;
79
+ };
80
+ readonly StepRenderInfo: {
81
+ readonly title: 1;
82
+ readonly markdown: 2;
83
+ readonly hidden: 4;
84
+ readonly title_prefix: 5;
85
+ readonly icon: 6;
86
+ readonly aggregation_key: 7;
87
+ readonly title_parts: 9;
88
+ readonly content_blocks: 10;
89
+ };
90
+ readonly TitlePart: {
91
+ readonly text: 1;
92
+ readonly file: 2;
93
+ readonly file_diff: 4;
94
+ };
95
+ readonly FileRef: {
96
+ readonly uri: 1;
97
+ readonly start_line: 2;
98
+ readonly end_line: 3;
99
+ readonly total_lines: 4;
100
+ readonly total_bytes: 5;
101
+ };
102
+ readonly FileDiffRef: {
103
+ readonly uri: 1;
104
+ readonly diff_stats: 2;
105
+ };
106
+ readonly DiffStats: {
107
+ readonly additions: 1;
108
+ readonly deletions: 2;
109
+ };
110
+ readonly ContentBlock: {
111
+ readonly markdown: 1;
112
+ readonly terminal: 3;
113
+ };
114
+ readonly TerminalBlock: {
115
+ readonly command: 1;
116
+ readonly cwd: 2;
117
+ readonly exit_code: 3;
118
+ readonly output: 4;
119
+ };
120
+ readonly CortexStepSystemMessage: {
121
+ readonly message: 1;
122
+ };
123
+ readonly CortexStepConversationHistory: {
124
+ readonly content: 1;
125
+ };
126
+ readonly CortexTrajectoryMetadata: {
127
+ readonly workspaces: 1;
128
+ readonly created_at: 2;
129
+ readonly root_conversation_id: 6;
130
+ readonly workspace_uris: 7;
131
+ readonly project_id: 18;
132
+ };
133
+ readonly CortexWorkspaceMetadata: {
134
+ readonly workspace_folder_absolute_uri: 1;
135
+ readonly repository: 3;
136
+ };
137
+ readonly CascadeTrajectorySummary: {
138
+ readonly summary: 1;
139
+ readonly step_count: 2;
140
+ readonly last_modified_time: 3;
141
+ readonly trajectory_id: 4;
142
+ readonly status: 5;
143
+ readonly created_time: 7;
144
+ readonly workspaces: 9;
145
+ readonly last_user_input_time: 10;
146
+ readonly last_user_input_step_index: 16;
147
+ readonly trajectory_metadata: 17;
148
+ };
149
+ readonly Timestamp: {
150
+ readonly seconds: 1;
151
+ readonly nanos: 2;
152
+ };
153
+ };
154
+ /** The schema message each table above is, for the check against `agy-schema.json`. */
155
+ export declare const MESSAGE_NAMES: Record<keyof typeof F, string>;
156
+ export declare const E: {
157
+ readonly StepType: {
158
+ readonly USER_INPUT: 14;
159
+ readonly PLANNER_RESPONSE: 15;
160
+ readonly ERROR_MESSAGE: 17;
161
+ readonly CONVERSATION_HISTORY: 98;
162
+ readonly SYSTEM_MESSAGE: 101;
163
+ readonly GENERIC: 132;
164
+ };
165
+ readonly StepStatus: {
166
+ readonly DONE: 3;
167
+ };
168
+ readonly StepSource: {
169
+ readonly MODEL: 2;
170
+ readonly USER_EXPLICIT: 4;
171
+ readonly SYSTEM: 5;
172
+ };
173
+ readonly RunStatus: {
174
+ readonly IDLE: 1;
175
+ };
176
+ readonly ComponentSource: {
177
+ readonly BUILTIN: 1;
178
+ };
179
+ };
180
+ /** The schema enum and value prefix each table above is, for the same check. */
181
+ export declare const ENUM_NAMES: Record<keyof typeof E, [string, string]>;
@@ -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
+ };
@@ -14,6 +14,7 @@ import { losses, toTranscript } from "./transcript.js";
14
14
  import { TARGETS, transcriptDir, writeSession } from "./write.js";
15
15
  import { VENDORS } from "./types.js";
16
16
  import { claudeProjectsDir, ownedPath } from "./owned.js";
17
+ import { agyEnv } from "./agyNative.js";
17
18
  const asVendor = (v) => {
18
19
  if (!VENDORS.includes(v))
19
20
  throw new Error(`Unknown agent: ${v}. Known: ${VENDORS.join(', ')}.`);
@@ -42,7 +43,7 @@ async function prepare(source, target, ctx, fullRecord) {
42
43
  const transcript = toTranscript(turns, subagents, { fullRecord });
43
44
  if (!transcript.messages.length)
44
45
  throw new Error('That session has no conversation to copy.');
45
- 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) };
46
47
  return { ref, turns, subagents, transcript, plan };
47
48
  }
48
49
  /** What a conversion WOULD do, writing nothing. The source's agent may be left out: it is found from the id. */
@@ -67,7 +68,14 @@ export async function convertSession(source, target, ctx) {
67
68
  step('Verifying');
68
69
  if (await fingerprint(ref, ctx) !== before)
69
70
  throw new Error('The original session changed while it was being copied. Nothing was kept; try again when that agent is idle.');
70
- 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) {
71
79
  const seen = await findSession(plan.target, written.id, ctx).catch(() => null);
72
80
  if (!seen)
73
81
  throw new Error(`${plan.target} does not list the copy it was given.`);
@@ -147,6 +155,15 @@ export async function removeArtifacts(artifacts, ctx) {
147
155
  throw new Error(`not an opencode session id: ${a.id}`);
148
156
  await ctx.run('opencode', ['session', 'delete', a.id]);
149
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
+ }
150
167
  else
151
168
  throw new Error(`no deletion path for a ${a.vendor} session`);
152
169
  }
@@ -12,3 +12,4 @@ export { buildLayers, layersPrompt, RECENT_CAP, type Layer, type Layers } from '
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
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';
@@ -12,3 +12,4 @@ 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
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,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);
@@ -169,7 +169,7 @@ const claude = {
169
169
  const text = typeof q.prompt === 'string' ? q.prompt : blocksText(q.prompt);
170
170
  const last = turns[turns.length - 1];
171
171
  if (text.trim() && !(last?.role === 'user' && last.text === text))
172
- 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' }) });
173
173
  return;
174
174
  }
175
175
  if (r.type === 'system' && r.subtype === 'compact_boundary') {
@@ -190,7 +190,7 @@ const claude = {
190
190
  if (b?.type === 'text' && !r.isMeta)
191
191
  turns.push({ role: 'user', text: b.text, at });
192
192
  else if (b?.type === 'tool_result')
193
- 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 } : {}) });
194
194
  }
195
195
  }
196
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 && `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} labelled text (${target} cannot re-run another agent's tools)`,
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 {
@@ -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 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
14
- * conversation is asked to read, declared as such
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,15 +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, layersPrompt } from "./layers.js";
26
+ import { buildLayers } from "./layers.js";
25
27
  import { claudeProjectsDir, ownedPath } from "./owned.js";
28
+ import { writeAgyConversation } from "./agyNative.js";
26
29
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
27
30
  export const TARGETS = Object.freeze({
28
- 'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout" },
29
- Codex: { fidelity: 'native', via: "Codex's own external-session importer (from a Claude-shaped copy)" },
30
- opencode: { fidelity: 'native', via: 'opencode import' },
31
- 'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout" },
32
- agy: { fidelity: 'handoff', via: 'a new conversation given the transcript as context (agy has no import)' },
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' },
33
36
  });
34
37
  /** Where a conversion keeps the layered record of the original, inside its own folder. */
35
38
  export const transcriptDir = (workDir) => join(workDir, 'transcript');
@@ -214,14 +217,11 @@ export async function writeSession(target, msgs, source, ctx) {
214
217
  .map((r, i) => JSON.stringify({ id: `e${i}`, timestamp: at, sequence: i, ...r })).join('\n') + '\n');
215
218
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
216
219
  }
217
- // agy
218
- if (index) {
219
- record({ kind: 'file', path: index });
220
- return { id: null, cwd, artifacts, handoff: { file: index, prompt: layersPrompt(index, source.vendor) } };
221
- }
222
- const doc = handoffDocument(msgs, source);
223
- const file = join(ctx.workDir, 'handoff.md');
224
- writeNew(file, doc.full);
225
- record({ kind: 'file', path: file });
226
- 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] };
227
227
  }
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xenosystem/primitives",
3
- "version": "0.8.1",
3
+ "version": "0.10.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",