@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,48 @@
1
+ /**
2
+ * Windows DPAPI for the current user, in process: `CryptProtectData` / `CryptUnprotectData`, no entropy, never any UI.
3
+ * The blob is the one .NET `ProtectedData.Protect(data, null, CurrentUser)` writes, so a record written by a product
4
+ * that used PowerShell for this reads here, and the other way round (proven both ways, 2026-11-29).
5
+ *
6
+ * Why it exists: products protected records by starting `powershell.exe` per call. That costs about 0.5 s idle and
7
+ * 2-3 s under load, and Spawn's startup made two such calls (measured 2026-11-29: native protect 4 ms, unprotect 1 ms).
8
+ *
9
+ * The bytes are the caller's to encode: this never decides a text encoding, and never logs or echoes what it is given.
10
+ */
11
+ import { loadNativeBinding } from "../process/native.js";
12
+ import { SecretsError } from "./errors.js";
13
+ /** Whether this machine can protect in process, and why not when it cannot. */
14
+ export function dpapiSupport() {
15
+ const { binding, reason } = loadNativeBinding();
16
+ if (!binding)
17
+ return { available: false, reason: reason ?? 'unknown reason' };
18
+ if (typeof binding.dpapiProtect !== 'function' || typeof binding.dpapiUnprotect !== 'function')
19
+ return { available: false, reason: 'native binary has no DPAPI' };
20
+ return { available: true };
21
+ }
22
+ function binding() {
23
+ const b = loadNativeBinding().binding;
24
+ if (!b || typeof b.dpapiProtect !== 'function' || typeof b.dpapiUnprotect !== 'function') {
25
+ throw new SecretsError('key-unavailable', `DPAPI is unavailable: ${dpapiSupport().reason ?? 'unknown reason'}`);
26
+ }
27
+ return { protect: b.dpapiProtect, unprotect: b.dpapiUnprotect };
28
+ }
29
+ /** Encrypt for the current Windows user. Throws a SecretsError when DPAPI is unavailable or refuses. */
30
+ export function dpapiProtect(data) {
31
+ const { protect } = binding();
32
+ try {
33
+ return protect(Buffer.from(data));
34
+ }
35
+ catch {
36
+ throw new SecretsError('key-unavailable', 'DPAPI refused to protect the data');
37
+ }
38
+ }
39
+ /** Decrypt a blob protected for the current Windows user. Throws (never returns empty bytes) when it does not decrypt. */
40
+ export function dpapiUnprotect(data) {
41
+ const { unprotect } = binding();
42
+ try {
43
+ return unprotect(Buffer.from(data));
44
+ }
45
+ catch {
46
+ throw new SecretsError('key-unavailable', 'DPAPI could not decrypt the data (another user, another machine, or damaged bytes)');
47
+ }
48
+ }
@@ -1,4 +1,5 @@
1
1
  export { SecretsError, isSecretsError, type SecretsErrorCode } from './errors.ts';
2
2
  export { SecretStore, createSecretStore, type SecretStoreOptions } from './store.ts';
3
3
  export { electronSafeStorageKeyStore, unprotectedKeyStore, type BlobLocation, type KeyStore, type SafeStorageLike, } from './keystore.ts';
4
+ export { dpapiProtect, dpapiSupport, dpapiUnprotect } from './dpapi.ts';
4
5
  export { createLibsecretKeyStore, createMacKeychainKeyStore, createOsKeyStore, createWindowsCredentialKeyStore, type OsStoreOptions, } from './os-stores.ts';
@@ -1,4 +1,5 @@
1
1
  export { SecretsError, isSecretsError } from "./errors.js";
2
2
  export { SecretStore, createSecretStore } from "./store.js";
3
3
  export { electronSafeStorageKeyStore, unprotectedKeyStore, } from "./keystore.js";
4
+ export { dpapiProtect, dpapiSupport, dpapiUnprotect } from "./dpapi.js";
4
5
  export { createLibsecretKeyStore, createMacKeychainKeyStore, createOsKeyStore, createWindowsCredentialKeyStore, } from "./os-stores.js";
@@ -0,0 +1,90 @@
1
+ import { type Msg } from './protowire.ts';
2
+ import type { Subagent, Turn } from './types.ts';
3
+ /** Per step, the most of a tool's output or a message the copy carries (the full record beside the copy keeps everything). */
4
+ export declare const AGY_STEP_CAP = 32000;
5
+ /** The most text the copy carries in all; over it the END is kept (where the conversation stopped), as for every target. */
6
+ export declare const AGY_TOTAL_CAP = 1500000;
7
+ /** A file path as agy writes it in a render: `file:///X:/a/b`. */
8
+ export declare function fileUri(path: string, cwd: string): string;
9
+ /**
10
+ * The environment that points the `agy` command at a store: agy keeps its data in `<home>/.gemini/antigravity-cli`, found from HOME and
11
+ * USERPROFILE, so a store elsewhere (an isolated home, a Spawn profile) is reached by giving agy that home.
12
+ */
13
+ export declare function agyEnv(store: string): NodeJS.ProcessEnv;
14
+ interface Render {
15
+ prefix?: string;
16
+ icon?: string;
17
+ agg?: string;
18
+ title?: string;
19
+ parts?: Msg[];
20
+ blocks?: Msg[];
21
+ markdown?: string;
22
+ }
23
+ export interface ToolStep {
24
+ name: string;
25
+ args: Record<string, string>;
26
+ render: Render;
27
+ }
28
+ /**
29
+ * agy's own tool, arguments and drawing for one call. Names and drawings follow what agy writes for its own tools (read from its
30
+ * conversations, 2026-11-28): run_command, read_file, write_file, update_steps, … A tool agy has no equivalent for keeps its own name
31
+ * and is drawn as agy draws any tool, with what it was given and what it answered.
32
+ */
33
+ export declare function agyTool(t: Turn, output: string, isError: boolean, cwd: string): ToolStep;
34
+ /** What a Claude Code user record holds when it is not the person typing. */
35
+ export type UserKind = {
36
+ kind: 'typed';
37
+ text: string;
38
+ } | {
39
+ kind: 'system';
40
+ text: string;
41
+ } | {
42
+ kind: 'skip';
43
+ };
44
+ /** Claude Code wraps slash commands, notices and shell input in tags: give each its meaning. */
45
+ export declare function userKind(t: Turn): UserKind;
46
+ export interface AgyStep {
47
+ type: number;
48
+ source: number;
49
+ at: string | null | undefined;
50
+ body: Msg;
51
+ tool?: {
52
+ id: string;
53
+ name: string;
54
+ args: string;
55
+ };
56
+ }
57
+ export interface AgyReport {
58
+ steps: number;
59
+ userInputs: number;
60
+ replies: number;
61
+ tools: number;
62
+ systemMessages: number;
63
+ compactions: number;
64
+ thinkingDropped: number;
65
+ omitted: number;
66
+ }
67
+ /** The turns as agy steps, in agy's grouping: a reply carries its tool calls, then one step per tool follows it with its result. */
68
+ export declare function agySteps(turns: Turn[], subagents: Subagent[], cwd: string, opts?: {
69
+ fullRecord?: string;
70
+ }): {
71
+ steps: AgyStep[];
72
+ report: AgyReport;
73
+ };
74
+ export interface AgyWritten {
75
+ id: string;
76
+ file: string;
77
+ report: AgyReport;
78
+ }
79
+ /**
80
+ * Write the conversation as a new file in agy's store (`<store>/conversations/<id>.db`). It is built at a private name in the same
81
+ * folder and then linked to its final name, which fails if anything holds that name: nothing is ever replaced, and agy never sees a
82
+ * half-written conversation.
83
+ */
84
+ export declare function writeAgyConversation(turns: Turn[], subagents: Subagent[], opts: {
85
+ store: string;
86
+ cwd: string;
87
+ fullRecord?: string;
88
+ now?: number;
89
+ }): Promise<AgyWritten>;
90
+ export {};
@@ -0,0 +1,383 @@
1
+ /**
2
+ * A NATIVE agy (Antigravity) conversation, written in agy's own format, so agy resumes it as one of its own with
3
+ * `agy --conversation <id>` (owner, 2026-11-28: "we need proper session resume not handover").
4
+ *
5
+ * How it was established, measured 2026-11-28 on agy 1.5.19 in an isolated home:
6
+ * - agy keeps a conversation as ONE SQLite file, `conversations/<id>.db`, whose `steps` rows are protobuf `gemini_coder.Step`
7
+ * messages; the schema is compiled into agy.exe and was extracted from it (agyWire.ts).
8
+ * - A conversation written from turns, with no reply of agy's in it, was resumed and recalled both a codeword from the person's turn
9
+ * and a number from the reply's turn.
10
+ * - The file ALONE is enough: agy lists it, resumes it and writes its own row in `conversation_summaries.db`. So nothing here writes
11
+ * the list database the running desktop app holds open; the only write is one new file, created exclusively.
12
+ *
13
+ * 🔴 1:1, kind by kind (the kinds counted in the owner's 12 largest Claude Code sessions, 1.6 million records, 2026-11-28): every
14
+ * kind becomes agy's own step for it, drawn as agy draws its own (agy's `StepRenderInfo`), never a block of labelled text:
15
+ * the person's words USER_INPUT; typed while a turn ran → is_queued_message; a slash command → "/name args"
16
+ * another session, a job SYSTEM_MESSAGE, saying who sent it
17
+ * the reply PLANNER_RESPONSE, with its tool calls as agy tool calls
18
+ * a tool call + result GENERIC: agy's own tool name and arguments, the result, and its render (a terminal block for a command,
19
+ * file links and diff counts for reads and edits, a checklist for plans and tasks, …): see TOOLS
20
+ * a compaction CONVERSATION_HISTORY, carrying the original agent's summary
21
+ * signed thinking dropped and counted (never forged), as for every target
22
+ */
23
+ import { randomUUID } from 'node:crypto';
24
+ import { existsSync, linkSync, mkdirSync, unlinkSync } from 'node:fs';
25
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
26
+ import { AGY_DB_PRAGMAS, AGY_DB_SQL, AGY_TRAJECTORY, E, F } from "./agyWire.js";
27
+ import { encode, mapEntries, timestamp } from "./protowire.js";
28
+ import { ownedPath } from "./owned.js";
29
+ /** Per step, the most of a tool's output or a message the copy carries (the full record beside the copy keeps everything). */
30
+ export const AGY_STEP_CAP = 32_000;
31
+ /** The most text the copy carries in all; over it the END is kept (where the conversation stopped), as for every target. */
32
+ export const AGY_TOTAL_CAP = 1_500_000;
33
+ const clip = (s, n = AGY_STEP_CAP) => s.length > n ? `${s.slice(0, n)}\n… [${s.length - n} more characters are in the full record]` : s;
34
+ const json = (v) => { try {
35
+ return typeof v === 'string' ? v : JSON.stringify(v ?? {});
36
+ }
37
+ catch {
38
+ return String(v);
39
+ } };
40
+ const str = (v) => typeof v === 'string' ? v : v == null ? '' : json(v);
41
+ /** A file path as agy writes it in a render: `file:///X:/a/b`. */
42
+ export function fileUri(path, cwd) {
43
+ const p = (isAbsolute(path) ? path : resolve(cwd, path)).replace(/\\/g, '/');
44
+ return `file:///${p.replace(/^\/+/, '')}`;
45
+ }
46
+ /**
47
+ * The environment that points the `agy` command at a store: agy keeps its data in `<home>/.gemini/antigravity-cli`, found from HOME and
48
+ * USERPROFILE, so a store elsewhere (an isolated home, a Spawn profile) is reached by giving agy that home.
49
+ */
50
+ export function agyEnv(store) {
51
+ const s = resolve(store), home = dirname(dirname(s));
52
+ return basename(s) === 'antigravity-cli' && basename(dirname(s)) === '.gemini' ? { ...process.env, HOME: home, USERPROFILE: home } : { ...process.env };
53
+ }
54
+ const textPart = (t) => ({ [F.TitlePart.text]: t });
55
+ const filePart = (uri) => ({ [F.TitlePart.file]: { [F.FileRef.uri]: uri } });
56
+ const diffPart = (uri, add, del) => ({ [F.TitlePart.file_diff]: { [F.FileDiffRef.uri]: uri, [F.FileDiffRef.diff_stats]: { [F.DiffStats.additions]: add, [F.DiffStats.deletions]: del } } });
57
+ const mdBlock = (m) => ({ [F.ContentBlock.markdown]: clip(m) });
58
+ const lines = (s) => typeof s === 'string' && s ? s.split('\n').length : 0;
59
+ /** A plan as agy's own checklist (`update_steps` draws `- [x]`, `- [>]`, `- [ ]`). */
60
+ function checklist(input) {
61
+ const items = Array.isArray(input?.todos) ? input.todos : Array.isArray(input?.plan) ? input.plan : Array.isArray(input?.steps) ? input.steps
62
+ : Array.isArray(input?.tasks) ? input.tasks : input && typeof input === 'object' ? [input] : [];
63
+ return items.map((i) => {
64
+ const s = String(i?.status ?? '').toLowerCase(), mark = /complete|done/.test(s) ? 'x' : /progress|active|doing/.test(s) ? '>' : ' ';
65
+ return `- [${mark}] ${str(i?.content ?? i?.step ?? i?.title ?? i?.subject ?? i?.description ?? i?.taskId ?? '')}`.trimEnd();
66
+ }).join('\n');
67
+ }
68
+ /**
69
+ * agy's own tool, arguments and drawing for one call. Names and drawings follow what agy writes for its own tools (read from its
70
+ * conversations, 2026-11-28): run_command, read_file, write_file, update_steps, … A tool agy has no equivalent for keeps its own name
71
+ * and is drawn as agy draws any tool, with what it was given and what it answered.
72
+ */
73
+ export function agyTool(t, output, isError, cwd) {
74
+ const tool = t.tool ?? 'tool', i = t.input ?? {};
75
+ const allArgs = () => Object.fromEntries(Object.entries(i && typeof i === 'object' ? i : { input: i }).map(([k, v]) => [k, clip(str(v), 4000)]));
76
+ if (/^(Bash|PowerShell|BashOutput|run_command|shell|exec_command|local_shell)$/i.test(tool)) {
77
+ const command = str(i.command ?? i.cmd ?? i.CommandLine ?? i.bash_id ?? ''), summary = str(i.description ?? '') || command.split('\n')[0].slice(0, 80);
78
+ const code = /^Exit code (\d+)/m.exec(output)?.[1];
79
+ const exit = code !== undefined ? Number(code) : isError ? 1 : 0;
80
+ return { name: 'run_command', args: { CommandLine: clip(command, 8000), ...(summary ? { toolSummary: summary } : {}) },
81
+ render: { prefix: 'Ran', icon: 'terminal', agg: 'terminal', parts: [textPart(summary || tool)],
82
+ blocks: [{ [F.ContentBlock.terminal]: { [F.TerminalBlock.command]: clip(command, 8000), [F.TerminalBlock.cwd]: cwd, [F.TerminalBlock.exit_code]: exit, [F.TerminalBlock.output]: clip(output) } }] } };
83
+ }
84
+ const path = str(i.file_path ?? i.path ?? i.notebook_path ?? i.file ?? '');
85
+ if (/^(Read|read_file|view_file)$/i.test(tool) && path) {
86
+ const uri = fileUri(path, cwd);
87
+ return { name: 'read_file', args: { Path: path }, render: { prefix: 'Analyzed', icon: 'description', agg: 'files', parts: [{ [F.TitlePart.file]: {
88
+ [F.FileRef.uri]: uri, [F.FileRef.start_line]: Number(i.offset) || 0, [F.FileRef.end_line]: i.limit ? (Number(i.offset) || 1) + Number(i.limit) - 1 : 0
89
+ } }] } };
90
+ }
91
+ if (/^(Write|write_file|create_file)$/i.test(tool) && path) {
92
+ const uri = fileUri(path, cwd);
93
+ return { name: 'write_file', args: { Path: path, Content: clip(str(i.content), 8000) },
94
+ render: { prefix: isError ? 'Tried to create' : 'Created', icon: 'edit', agg: 'edits', parts: [filePart(uri), diffPart(uri, lines(i.content), 0)] } };
95
+ }
96
+ if (/^(Edit|MultiEdit|NotebookEdit|edit_file|apply_patch|replace)$/i.test(tool)) {
97
+ const edits = Array.isArray(i.edits) ? i.edits : [i];
98
+ const add = edits.reduce((n, e) => n + lines(e.new_string ?? e.new_source ?? ''), 0), del = edits.reduce((n, e) => n + lines(e.old_string ?? ''), 0);
99
+ const uri = path ? fileUri(path, cwd) : '';
100
+ return { name: 'edit_file', args: allArgs(), render: { prefix: isError ? 'Tried to edit' : 'Edited', icon: 'edit', agg: 'edits',
101
+ parts: uri ? [filePart(uri), diffPart(uri, add, del)] : [textPart(tool)] } };
102
+ }
103
+ if (/^(Grep|grep_search|search_files)$/i.test(tool)) {
104
+ return { name: 'grep_search', args: allArgs(), render: { prefix: 'Searched', icon: 'search', agg: 'search', parts: [textPart(str(i.pattern ?? i.query ?? ''))], blocks: [mdBlock('```\n' + output + '\n```')] } };
105
+ }
106
+ if (/^(Glob|find_by_name|list_dir|LS)$/i.test(tool)) {
107
+ return { name: /LS|list_dir/i.test(tool) ? 'list_dir' : 'find_by_name', args: allArgs(), render: { prefix: 'Searched', icon: 'folder', agg: 'search', parts: [textPart(str(i.pattern ?? i.path ?? ''))], blocks: [mdBlock('```\n' + output + '\n```')] } };
108
+ }
109
+ if (/^(TodoWrite|TaskCreate|TaskUpdate|TaskList|update_plan|update_steps|mcp__ccd_turn__update_plan)$/i.test(tool)) {
110
+ const md = checklist(i);
111
+ return { name: 'update_steps', args: allArgs(), render: { prefix: 'Updated', icon: 'checklist', agg: 'steps', parts: [textPart(/Task/.test(tool) ? 'tasks' : 'plan')], markdown: md || undefined } };
112
+ }
113
+ if (/^(Agent|Task)$/i.test(tool)) {
114
+ const name = str(i.subagent_type ?? i.description ?? 'sub-agent');
115
+ return { name: 'invoke_subagent', args: allArgs(), render: { prefix: 'Ran sub-agent', icon: 'smart_toy', agg: 'subagents', parts: [textPart(name)],
116
+ blocks: [mdBlock(`**Asked:** ${clip(str(i.prompt), 6000)}\n\n**Answered:**\n\n${output}`)] } };
117
+ }
118
+ if (/^AskUserQuestion$/i.test(tool)) {
119
+ const qs = Array.isArray(i.questions) ? i.questions : [];
120
+ const md = qs.map((q) => `**${str(q.question)}**\n${(Array.isArray(q.options) ? q.options : []).map((o) => `- ${str(o.label)}${o.description ? `: ${str(o.description)}` : ''}`).join('\n')}`).join('\n\n');
121
+ return { name: 'ask_question', args: allArgs(), render: { prefix: 'Asked', icon: 'help', agg: 'questions', parts: [textPart(`${qs.length || 1} question${qs.length === 1 ? '' : 's'}`)],
122
+ blocks: [mdBlock(`${md}\n\n**Answer:** ${output}`)] } };
123
+ }
124
+ if (/^(ScheduleWakeup|CronCreate|CronDelete|CronList|Monitor|RemoteTrigger)$/i.test(tool)) {
125
+ const when = str(i.cron ?? i.delaySeconds ?? i.schedule ?? i.interval ?? '');
126
+ return { name: 'schedule', args: allArgs(), render: { prefix: /Delete/.test(tool) ? 'Cancelled schedule' : 'Scheduled', icon: 'schedule', agg: 'schedule',
127
+ parts: [textPart(when ? `${tool} ${when}` : tool)], blocks: [mdBlock(`${str(i.prompt ?? i.reason ?? i.command ?? '')}\n\n${output}`.trim())] } };
128
+ }
129
+ if (/^(WebSearch|search_web)$/i.test(tool)) {
130
+ return { name: 'search_web', args: allArgs(), render: { prefix: 'Searched the web', icon: 'travel_explore', agg: 'web', parts: [textPart(str(i.query))], blocks: [mdBlock(output)] } };
131
+ }
132
+ if (/^(WebFetch|read_url_content)$/i.test(tool)) {
133
+ return { name: 'read_url_content', args: allArgs(), render: { prefix: 'Read', icon: 'language', agg: 'web', parts: [textPart(str(i.url))], blocks: [mdBlock(output)] } };
134
+ }
135
+ if (/^SendMessage$/i.test(tool)) {
136
+ return { name: 'send_message', args: allArgs(), render: { prefix: 'Sent a message to', icon: 'send', agg: 'messages', parts: [textPart(str(i.to ?? i.recipient ?? ''))], blocks: [mdBlock(str(i.message ?? i.text ?? ''))] } };
137
+ }
138
+ if (/^Skill$/i.test(tool)) {
139
+ return { name: 'skill', args: allArgs(), render: { prefix: 'Used skill', icon: 'auto_awesome', agg: 'skills', parts: [textPart(str(i.skill ?? i.name ?? ''))], blocks: output ? [mdBlock(output)] : [] } };
140
+ }
141
+ const mcp = /^mcp__(.+?)__(.+)$/.exec(tool);
142
+ if (mcp) {
143
+ return { name: tool, args: allArgs(), render: { prefix: `Used ${mcp[1].replace(/_/g, ' ')}`, icon: 'extension', agg: 'mcp', parts: [textPart(mcp[2])], blocks: output ? [mdBlock(output)] : [] } };
144
+ }
145
+ return { name: tool, args: allArgs(), render: { prefix: 'Used', icon: 'build', agg: 'tools', parts: [textPart(tool)], blocks: output ? [mdBlock(output)] : [] } };
146
+ }
147
+ function renderInfo(r) {
148
+ return { [F.StepRenderInfo.title]: r.title, [F.StepRenderInfo.markdown]: r.markdown, [F.StepRenderInfo.title_prefix]: r.prefix, [F.StepRenderInfo.icon]: r.icon,
149
+ [F.StepRenderInfo.aggregation_key]: r.agg, [F.StepRenderInfo.title_parts]: r.parts, [F.StepRenderInfo.content_blocks]: r.blocks?.length ? r.blocks : undefined };
150
+ }
151
+ /** Claude Code wraps slash commands, notices and shell input in tags: give each its meaning. */
152
+ export function userKind(t) {
153
+ const raw = t.text ?? '', s = raw.trim();
154
+ if (!s)
155
+ return { kind: 'skip' };
156
+ if (t.from === 'peer')
157
+ return { kind: 'system', text: `Message from another session:\n${raw}` };
158
+ if (t.from === 'harness' || /^<task-notification>/.test(s))
159
+ return { kind: 'system', text: `A background job reported:\n${raw}` };
160
+ const name = /<command-name>\s*\/?([^<]+?)\s*<\/command-name>/.exec(s);
161
+ if (name) {
162
+ const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(s)?.[1]?.trim();
163
+ return { kind: 'typed', text: `/${name[1]}${args ? ` ${args}` : ''}` };
164
+ }
165
+ const bash = /^<bash-input>([\s\S]*?)<\/bash-input>$/.exec(s);
166
+ if (bash)
167
+ return { kind: 'typed', text: `!${bash[1]}` };
168
+ const out = /^<(local-command-stdout|bash-stdout|bash-stderr)>([\s\S]*?)<\/\1>/.exec(s);
169
+ if (out)
170
+ return out[2].trim() ? { kind: 'system', text: `Command output:\n${out[2]}` } : { kind: 'skip' };
171
+ if (/^<(local-command-caveat|system-reminder)>[\s\S]*<\/(local-command-caveat|system-reminder)>$/.test(s))
172
+ return { kind: 'skip' };
173
+ return { kind: 'typed', text: raw };
174
+ }
175
+ /** The turns as agy steps, in agy's grouping: a reply carries its tool calls, then one step per tool follows it with its result. */
176
+ export function agySteps(turns, subagents, cwd, opts = {}) {
177
+ const report = { steps: 0, userInputs: 0, replies: 0, tools: 0, systemMessages: 0, compactions: 0, thinkingDropped: 0, omitted: 0 };
178
+ const results = new Map(), calls = new Set();
179
+ for (const t of turns) {
180
+ if (t.role === 'tool' && t.callId)
181
+ results.set(t.callId, t);
182
+ if (t.tool && t.callId)
183
+ calls.add(t.callId);
184
+ }
185
+ const steps = [];
186
+ let reply = null;
187
+ const flush = () => {
188
+ if (!reply)
189
+ return;
190
+ const r = reply;
191
+ reply = null;
192
+ const toolSteps = r.tools.map((t) => {
193
+ const res = t.callId ? results.get(t.callId) : undefined;
194
+ const step = agyTool(t, res?.output ?? '', !!res?.isError, cwd);
195
+ return { t, res, step, id: t.callId ?? `call_${randomUUID().replace(/-/g, '').slice(0, 24)}` };
196
+ });
197
+ if (!r.text.length && !toolSteps.length)
198
+ return;
199
+ steps.push({ type: E.StepType.PLANNER_RESPONSE, source: E.StepSource.MODEL, at: r.at, body: { [F.Step.planner_response]: {
200
+ [F.CortexStepPlannerResponse.response]: clip(r.text.join('\n\n')), [F.CortexStepPlannerResponse.message_id]: randomUUID(),
201
+ [F.CortexStepPlannerResponse.tool_calls]: toolSteps.map((x) => ({ [F.ChatToolCall.id]: x.id, [F.ChatToolCall.name]: x.step.name, [F.ChatToolCall.arguments_json]: json(x.step.args) }))
202
+ } } });
203
+ report.replies++;
204
+ for (const x of toolSteps) {
205
+ steps.push({ type: E.StepType.GENERIC, source: E.StepSource.MODEL, at: x.res?.at ?? x.t.at, tool: { id: x.id, name: x.step.name, args: json(x.step.args) },
206
+ body: { [F.Step.generic]: { [F.CortexStepGeneric.args]: mapEntries(x.step.args), [F.CortexStepGeneric.result]: {
207
+ [F.GenericStepResult.result]: clip(x.res ? x.res.output ?? '' : '(the original session recorded no result for this call)'),
208
+ [F.GenericStepResult.step_render_info]: renderInfo(x.step.render)
209
+ } } } });
210
+ report.tools++;
211
+ }
212
+ };
213
+ const system = (text, at) => {
214
+ flush();
215
+ steps.push({ type: E.StepType.SYSTEM_MESSAGE, source: E.StepSource.SYSTEM, at, body: { [F.Step.system_message]: { [F.CortexStepSystemMessage.message]: clip(text) } } });
216
+ report.systemMessages++;
217
+ };
218
+ let inCompaction = false;
219
+ for (const t of turns) {
220
+ if (t.thinking) {
221
+ report.thinkingDropped++;
222
+ continue;
223
+ }
224
+ if (!t.compaction)
225
+ inCompaction = false;
226
+ if (t.compaction) {
227
+ if (!inCompaction)
228
+ report.compactions++;
229
+ inCompaction = true;
230
+ const summary = t.text && !/^\[conversation (compacted|checkpoint)\]$/.test(t.text) ? t.text : '';
231
+ if (summary) {
232
+ flush();
233
+ steps.push({ type: E.StepType.CONVERSATION_HISTORY, source: E.StepSource.SYSTEM, at: t.at, body: { [F.Step.conversation_history]: {
234
+ [F.CortexStepConversationHistory.content]: clip(`The original agent compacted the conversation here. Its summary of what came before:\n\n${summary}`, 200_000)
235
+ } } });
236
+ }
237
+ continue;
238
+ }
239
+ if (t.role === 'assistant') {
240
+ if (!reply)
241
+ reply = { text: [], tools: [], at: t.at };
242
+ // A reply's text that follows its own tool calls starts the next reply, as agy's planner does.
243
+ if (t.text && !t.tool && reply.tools.length) {
244
+ flush();
245
+ reply = { text: [], tools: [], at: t.at };
246
+ }
247
+ if (t.tool)
248
+ reply.tools.push(t);
249
+ else if (t.text)
250
+ reply.text.push(t.text);
251
+ continue;
252
+ }
253
+ if (t.role === 'tool') {
254
+ if (t.callId && calls.has(t.callId))
255
+ continue; // carried with its call
256
+ system(`A tool result whose call is not in the original transcript:\n${t.output ?? ''}`, t.at);
257
+ continue;
258
+ }
259
+ if (t.role === 'system') {
260
+ if (t.text)
261
+ system(t.text, t.at);
262
+ continue;
263
+ }
264
+ const k = userKind(t);
265
+ if (k.kind === 'skip')
266
+ continue;
267
+ if (k.kind === 'system') {
268
+ system(k.text, t.at);
269
+ continue;
270
+ }
271
+ flush();
272
+ steps.push({ type: E.StepType.USER_INPUT, source: E.StepSource.USER_EXPLICIT, at: t.at, body: { [F.Step.user_input]: {
273
+ [F.CortexStepUserInput.user_response]: clip(k.text), [F.CortexStepUserInput.items]: [{ [F.TextOrScopeItem.text]: clip(k.text) }],
274
+ [F.CortexStepUserInput.is_queued_message]: !!t.queued
275
+ } } });
276
+ report.userInputs++;
277
+ }
278
+ flush();
279
+ for (const sa of subagents) {
280
+ const lines = sa.turns.filter((t) => t.text).map((t) => `${t.role === 'user' ? 'asked' : 'answered'}: ${t.text}`);
281
+ if (lines.length)
282
+ system(`Sub-agent ${sa.name} ran separately in the original session:\n${lines.join('\n')}`, null);
283
+ }
284
+ // 🔴 Over the limit, the END is kept, from a person's message so the conversation still opens with one.
285
+ let total = 0, from = steps.length;
286
+ const size = (s) => encode(s.body).length;
287
+ while (from > 0 && total + size(steps[from - 1]) <= AGY_TOTAL_CAP)
288
+ total += size(steps[--from]);
289
+ while (from > 0 && from < steps.length && steps[from].type !== E.StepType.USER_INPUT)
290
+ from++;
291
+ const lastIndex = (end, type) => { for (let i = end - 1; i >= 0; i--)
292
+ if (steps[i].type === type)
293
+ return i; return -1; };
294
+ if (from >= steps.length)
295
+ from = Math.max(0, lastIndex(steps.length, E.StepType.USER_INPUT));
296
+ let kept = steps.slice(from);
297
+ if (from > 0) {
298
+ // The last compaction summary before the cut carries what the left-out part said, and the full record holds all of it.
299
+ const s = lastIndex(from, E.StepType.CONVERSATION_HISTORY), lastSummary = s >= 0 ? steps[s] : undefined;
300
+ const where = opts.fullRecord ? ` The whole conversation is in ${opts.fullRecord}: read it when you need something from earlier.` : '';
301
+ kept = [{ type: E.StepType.CONVERSATION_HISTORY, source: E.StepSource.SYSTEM, at: kept[0]?.at, body: { [F.Step.conversation_history]: {
302
+ [F.CortexStepConversationHistory.content]: `This conversation was copied from another agent. Everything from here on is its most recent part, in full, up to where it stopped: answer about recent work from it directly. Its ${from} earliest steps are not in this copy, because the conversation is longer than a copy carries.${where}`
303
+ } } },
304
+ ...(lastSummary ? [lastSummary] : []), ...kept];
305
+ }
306
+ report.omitted = from;
307
+ report.steps = kept.length;
308
+ return { steps: kept, report };
309
+ }
310
+ /**
311
+ * Write the conversation as a new file in agy's store (`<store>/conversations/<id>.db`). It is built at a private name in the same
312
+ * folder and then linked to its final name, which fails if anything holds that name: nothing is ever replaced, and agy never sees a
313
+ * half-written conversation.
314
+ */
315
+ export async function writeAgyConversation(turns, subagents, opts) {
316
+ const { steps, report } = agySteps(turns, subagents, opts.cwd, { fullRecord: opts.fullRecord });
317
+ if (!steps.some((s) => s.type === E.StepType.USER_INPUT))
318
+ throw new Error('There is no message from the person to start the agy conversation with.');
319
+ const dir = ownedPath(opts.store, join(opts.store, 'conversations'));
320
+ mkdirSync(dir, { recursive: true });
321
+ const cid = randomUUID(), tid = randomUUID(), file = ownedPath(opts.store, join(dir, `${cid}.db`)), tmp = join(dir, `.${cid}.xeno-copy`);
322
+ if (existsSync(file) || existsSync(tmp))
323
+ throw new Error(`Refusing to overwrite ${file}`);
324
+ const now = opts.now ?? Date.now(), uri = fileUri(opts.cwd, opts.cwd);
325
+ const workspace = { [F.CortexWorkspaceMetadata.workspace_folder_absolute_uri]: uri, [F.CortexWorkspaceMetadata.repository]: {} };
326
+ const meta = encode({ [F.CortexTrajectoryMetadata.workspaces]: [workspace], [F.CortexTrajectoryMetadata.created_at]: timestamp(steps[0]?.at, now),
327
+ [F.CortexTrajectoryMetadata.root_conversation_id]: cid, [F.CortexTrajectoryMetadata.workspace_uris]: [uri], [F.CortexTrajectoryMetadata.project_id]: 'default-cli-project' });
328
+ const { DatabaseSync } = await import('node:sqlite');
329
+ const db = new DatabaseSync(tmp);
330
+ try {
331
+ for (const p of AGY_DB_PRAGMAS)
332
+ db.exec(p);
333
+ for (const s of AGY_DB_SQL)
334
+ db.exec(s);
335
+ db.exec('BEGIN');
336
+ db.prepare('insert into trajectory_meta values (?,?,?,?)').run(tid, cid, AGY_TRAJECTORY.type, AGY_TRAJECTORY.source);
337
+ db.prepare("insert into trajectory_metadata_blob values ('main', ?)").run(meta);
338
+ const insert = db.prepare('insert into steps (idx,step_type,status,has_subtrajectory,metadata,step_payload,step_format) values (?,?,?,0,?,?,0)');
339
+ let execution = randomUUID(), last = now - steps.length * 1000;
340
+ steps.forEach((s, idx) => {
341
+ if (s.type === E.StepType.USER_INPUT)
342
+ execution = randomUUID();
343
+ // Times are the original's where it recorded them, and never run backwards.
344
+ const t = Math.max(last + 1, Number.isFinite(Date.parse(s.at ?? '')) ? Date.parse(s.at) : last + 1000);
345
+ last = t;
346
+ const stamp = timestamp(t, now);
347
+ const metadata = { [F.CortexStepMetadata.created_at]: stamp, [F.CortexStepMetadata.source]: s.source, [F.CortexStepMetadata.completed_at]: stamp,
348
+ [F.CortexStepMetadata.execution_id]: execution, [F.CortexStepMetadata.source_trajectory_step_info]: { [F.SourceTrajectoryStepInfo.trajectory_id]: tid,
349
+ [F.SourceTrajectoryStepInfo.step_index]: idx, [F.SourceTrajectoryStepInfo.cascade_id]: cid },
350
+ [F.CortexStepMetadata.model_api_content_id]: randomUUID().replace(/-/g, ''),
351
+ ...(s.tool ? { [F.CortexStepMetadata.tool_call]: { [F.ChatToolCall.id]: s.tool.id, [F.ChatToolCall.name]: s.tool.name, [F.ChatToolCall.arguments_json]: s.tool.args },
352
+ [F.CortexStepMetadata.tool_source]: E.ComponentSource.BUILTIN } : {}) };
353
+ const payload = encode({ [F.Step.type]: s.type, [F.Step.status]: E.StepStatus.DONE, [F.Step.metadata]: metadata, ...s.body });
354
+ insert.run(idx, s.type, E.StepStatus.DONE, encode(metadata), payload);
355
+ });
356
+ db.exec('COMMIT');
357
+ }
358
+ catch (e) {
359
+ try {
360
+ db.close();
361
+ }
362
+ catch { /* closing */ }
363
+ for (const f of [tmp, `${tmp}-wal`, `${tmp}-shm`])
364
+ try {
365
+ unlinkSync(f);
366
+ }
367
+ catch { /* absent */ }
368
+ throw e;
369
+ }
370
+ db.close();
371
+ try {
372
+ linkSync(tmp, file);
373
+ }
374
+ finally {
375
+ unlinkSync(tmp);
376
+ for (const f of [`${tmp}-wal`, `${tmp}-shm`])
377
+ try {
378
+ unlinkSync(f);
379
+ }
380
+ catch { /* absent */ }
381
+ }
382
+ return { id: cid, file, report };
383
+ }