@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,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
+ };
@@ -21,6 +21,7 @@ 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
23
  const owned_ts_1 = require("./owned.js");
24
+ const agyNative_ts_1 = require("./agyNative.js");
24
25
  const asVendor = (v) => {
25
26
  if (!types_ts_1.VENDORS.includes(v))
26
27
  throw new Error(`Unknown agent: ${v}. Known: ${types_ts_1.VENDORS.join(', ')}.`);
@@ -50,7 +51,7 @@ async function prepare(source, target, ctx, fullRecord) {
50
51
  const transcript = (0, transcript_ts_1.toTranscript)(turns, subagents, { fullRecord });
51
52
  if (!transcript.messages.length)
52
53
  throw new Error('That session has no conversation to copy.');
53
- 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) };
54
55
  return { ref, turns, subagents, transcript, plan };
55
56
  }
56
57
  /** What a conversion WOULD do, writing nothing. The source's agent may be left out: it is found from the id. */
@@ -75,7 +76,14 @@ async function convertSession(source, target, ctx) {
75
76
  step('Verifying');
76
77
  if (await fingerprint(ref, ctx) !== before)
77
78
  throw new Error('The original session changed while it was being copied. Nothing was kept; try again when that agent is idle.');
78
- 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) {
79
87
  const seen = await (0, read_ts_1.findSession)(plan.target, written.id, ctx).catch(() => null);
80
88
  if (!seen)
81
89
  throw new Error(`${plan.target} does not list the copy it was given.`);
@@ -155,6 +163,15 @@ async function removeArtifacts(artifacts, ctx) {
155
163
  throw new Error(`not an opencode session id: ${a.id}`);
156
164
  await ctx.run('opencode', ['session', 'delete', a.id]);
157
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
+ }
158
175
  else
159
176
  throw new Error(`no deletion path for a ${a.vendor} session`);
160
177
  }
@@ -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';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- 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;
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.
@@ -47,3 +47,11 @@ Object.defineProperty(exports, "locateSession", { enumerable: true, get: functio
47
47
  var owned_ts_1 = require("./owned.js");
48
48
  Object.defineProperty(exports, "ownedPath", { enumerable: true, get: function () { return owned_ts_1.ownedPath; } });
49
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,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;
@@ -182,7 +182,7 @@ const claude = {
182
182
  const text = typeof q.prompt === 'string' ? q.prompt : blocksText(q.prompt);
183
183
  const last = turns[turns.length - 1];
184
184
  if (text.trim() && !(last?.role === 'user' && last.text === text))
185
- 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' }) });
186
186
  return;
187
187
  }
188
188
  if (r.type === 'system' && r.subtype === 'compact_boundary') {
@@ -203,7 +203,7 @@ const claude = {
203
203
  if (b?.type === 'text' && !r.isMeta)
204
204
  turns.push({ role: 'user', text: b.text, at });
205
205
  else if (b?.type === 'tool_result')
206
- 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 } : {}) });
207
207
  }
208
208
  }
209
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 {
@@ -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
  */
@@ -30,13 +32,14 @@ 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");
32
34
  const owned_ts_1 = require("./owned.js");
35
+ const agyNative_ts_1 = require("./agyNative.js");
33
36
  /** How each agent takes a copy, and whether it can resume it as its own conversation. */
34
37
  exports.TARGETS = Object.freeze({
35
- 'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout" },
36
- Codex: { fidelity: 'native', via: "Codex's own external-session importer (from a Claude-shaped copy)" },
37
- opencode: { fidelity: 'native', via: 'opencode import' },
38
- 'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout" },
39
- 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' },
40
43
  });
41
44
  /** Where a conversion keeps the layered record of the original, inside its own folder. */
42
45
  const transcriptDir = (workDir) => (0, node_path_1.join)(workDir, 'transcript');
@@ -223,14 +226,11 @@ async function writeSession(target, msgs, source, ctx) {
223
226
  .map((r, i) => JSON.stringify({ id: `e${i}`, timestamp: at, sequence: i, ...r })).join('\n') + '\n');
224
227
  return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
225
228
  }
226
- // agy
227
- if (index) {
228
- record({ kind: 'file', path: index });
229
- return { id: null, cwd, artifacts, handoff: { file: index, prompt: (0, layers_ts_1.layersPrompt)(index, source.vendor) } };
230
- }
231
- const doc = handoffDocument(msgs, source);
232
- const file = (0, node_path_1.join)(ctx.workDir, 'handoff.md');
233
- writeNew(file, doc.full);
234
- record({ kind: 'file', path: file });
235
- 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] };
236
236
  }
@@ -1,5 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { readFile } from 'node:fs/promises';
3
+ import { processCreationTime } from "../process/native.js";
3
4
  /** True when a process with this pid exists (a process we may not signal still exists). */
4
5
  export function isProcessAlive(pid) {
5
6
  if (!Number.isInteger(pid) || pid <= 0)
@@ -40,6 +41,10 @@ export async function processStartTime(pid) {
40
41
  return out ? `darwin:${out}` : null;
41
42
  }
42
43
  if (process.platform === 'win32') {
44
+ // One GetProcessTimes call (0.06 ms) when the package's binary is here; the same FILETIME PowerShell prints.
45
+ const native = processCreationTime(pid);
46
+ if (native !== undefined)
47
+ return native === null ? null : `win32:${native}`;
43
48
  const root = process.env['SystemRoot'] ?? 'C:\\Windows';
44
49
  const ps = `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
45
50
  const out = await run(ps, [
@@ -38,6 +38,7 @@ export interface ProcessGroup {
38
38
  /** Processes still running in the group, where the platform can count them (Windows job only). */
39
39
  activeProcesses(): number | undefined;
40
40
  }
41
+ export { processCreationTime } from './native.ts';
41
42
  /** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
42
43
  export declare function processGroupSupport(): {
43
44
  containment: Containment;
@@ -18,33 +18,20 @@
18
18
  * that needs the guarantee can refuse rather than assume it.
19
19
  */
20
20
  import { spawn } from 'node:child_process';
21
- import { existsSync } from 'node:fs';
22
- import { createRequire } from 'node:module';
23
- import { join } from 'node:path';
24
- import { moduleDir } from "./here.js";
21
+ import { loadNativeBinding } from "./native.js";
25
22
  let nativeCache;
26
23
  /** The native job binding, or why it is not available. Windows only. */
27
24
  function loadNative() {
28
25
  if (nativeCache)
29
26
  return nativeCache;
30
- if (process.platform !== 'win32')
31
- return (nativeCache = { reason: 'not Windows' });
32
- const name = `win32-${process.arch}`;
33
- // src/process (tests) and dist/{esm,cjs}/process (published) both sit under the package directory.
34
- const candidates = [join(moduleDir, '..', '..', 'native', name, 'process.node'), join(moduleDir, '..', '..', '..', 'native', name, 'process.node')];
35
- const file = candidates.find((p) => existsSync(p));
36
- if (!file)
37
- return (nativeCache = { reason: `no native binary for ${name}` });
38
- try {
39
- const binding = createRequire(file)(file);
40
- if (typeof binding.ProcessJob !== 'function')
41
- return (nativeCache = { reason: 'native binary has no ProcessJob' });
42
- return (nativeCache = { ctor: binding.ProcessJob });
43
- }
44
- catch (error) {
45
- return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
46
- }
27
+ const { binding, reason } = loadNativeBinding();
28
+ if (!binding)
29
+ return (nativeCache = { reason: reason ?? 'unknown reason' });
30
+ if (typeof binding.ProcessJob !== 'function')
31
+ return (nativeCache = { reason: 'native binary has no ProcessJob' });
32
+ return (nativeCache = { ctor: binding.ProcessJob });
47
33
  }
34
+ export { processCreationTime } from "./native.js";
48
35
  /** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
49
36
  export function processGroupSupport() {
50
37
  if (process.platform !== 'win32')
@@ -0,0 +1,22 @@
1
+ /** The functions the binary exports. Each is checked before use, so an older binary simply lacks the newer ones. */
2
+ export interface NativeBinding {
3
+ ProcessJob?: unknown;
4
+ privateFileOperation?: unknown;
5
+ processCreationTime?: (pid: number) => string | null;
6
+ dpapiProtect?: (data: Buffer) => Buffer;
7
+ dpapiUnprotect?: (data: Buffer) => Buffer;
8
+ }
9
+ /** The binary, or why it is not available. Windows only. */
10
+ export declare function loadNativeBinding(): {
11
+ binding?: NativeBinding;
12
+ reason?: string;
13
+ };
14
+ /**
15
+ * The creation time of a process, as a decimal Windows FILETIME (100 ns since 1601-01-01 UTC), read with one
16
+ * `GetProcessTimes` call. Null when the process cannot be opened (it has ended, or belongs to another user).
17
+ * Undefined when this machine has no native binary that can answer (not Windows, or an older binary): the caller
18
+ * decides what to do then. It replaces starting `powershell.exe` for the same value, which took 2-3 s under load
19
+ * (measured 2026-11-29: 0.06 ms native, identical value to `StartTime.ToFileTimeUtc()`).
20
+ * Exported by `@xenosystem/primitives/process`.
21
+ */
22
+ export declare function processCreationTime(pid: number): string | null | undefined;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The one loader of this package's Windows binary (`native/win32-<arch>/process.node`), shared by the families that
3
+ * call into it: `process` (the job object), `dirs` (a process's start time, for lock staleness) and `secrets` (DPAPI).
4
+ * Internal: not an export of the package.
5
+ */
6
+ import { existsSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { join } from 'node:path';
9
+ import { moduleDir } from "./here.js";
10
+ let cache;
11
+ /** The binary, or why it is not available. Windows only. */
12
+ export function loadNativeBinding() {
13
+ if (cache)
14
+ return cache;
15
+ if (process.platform !== 'win32')
16
+ return (cache = { reason: 'not Windows' });
17
+ const name = `win32-${process.arch}`;
18
+ // src/process (tests) and dist/{esm,cjs}/process (published) both sit under the package directory.
19
+ const candidates = [join(moduleDir, '..', '..', 'native', name, 'process.node'), join(moduleDir, '..', '..', '..', 'native', name, 'process.node')];
20
+ const file = candidates.find((p) => existsSync(p));
21
+ if (!file)
22
+ return (cache = { reason: `no native binary for ${name}` });
23
+ try {
24
+ return (cache = { binding: createRequire(file)(file) });
25
+ }
26
+ catch (error) {
27
+ return (cache = { reason: `native binary failed to load: ${error.message}` });
28
+ }
29
+ }
30
+ /**
31
+ * The creation time of a process, as a decimal Windows FILETIME (100 ns since 1601-01-01 UTC), read with one
32
+ * `GetProcessTimes` call. Null when the process cannot be opened (it has ended, or belongs to another user).
33
+ * Undefined when this machine has no native binary that can answer (not Windows, or an older binary): the caller
34
+ * decides what to do then. It replaces starting `powershell.exe` for the same value, which took 2-3 s under load
35
+ * (measured 2026-11-29: 0.06 ms native, identical value to `StartTime.ToFileTimeUtc()`).
36
+ * Exported by `@xenosystem/primitives/process`.
37
+ */
38
+ export function processCreationTime(pid) {
39
+ if (!Number.isInteger(pid) || pid <= 0 || pid > 0xffffffff)
40
+ return null;
41
+ const read = loadNativeBinding().binding?.processCreationTime;
42
+ if (typeof read !== 'function')
43
+ return undefined;
44
+ const value = read(pid);
45
+ return typeof value === 'string' && /^\d+$/.test(value) ? value : null;
46
+ }
@@ -0,0 +1,9 @@
1
+ /** Whether this machine can protect in process, and why not when it cannot. */
2
+ export declare function dpapiSupport(): {
3
+ available: boolean;
4
+ reason?: string;
5
+ };
6
+ /** Encrypt for the current Windows user. Throws a SecretsError when DPAPI is unavailable or refuses. */
7
+ export declare function dpapiProtect(data: Uint8Array): Buffer;
8
+ /** Decrypt a blob protected for the current Windows user. Throws (never returns empty bytes) when it does not decrypt. */
9
+ export declare function dpapiUnprotect(data: Uint8Array): Buffer;