@xenosystem/primitives 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/cjs/private-file/index.d.ts +41 -0
- package/dist/cjs/private-file/index.js +91 -0
- package/dist/cjs/sessions/cli.d.ts +2 -0
- package/dist/cjs/sessions/cli.js +152 -0
- package/dist/cjs/sessions/convert.d.ts +41 -0
- package/dist/cjs/sessions/convert.js +193 -0
- package/dist/cjs/sessions/index.d.ts +12 -0
- package/dist/cjs/sessions/index.js +37 -0
- package/dist/cjs/sessions/read.d.ts +36 -0
- package/dist/cjs/sessions/read.js +576 -0
- package/dist/cjs/sessions/run.d.ts +9 -0
- package/dist/cjs/sessions/run.js +60 -0
- package/dist/cjs/sessions/stores.d.ts +9 -0
- package/dist/cjs/sessions/stores.js +23 -0
- package/dist/cjs/sessions/transcript.d.ts +38 -0
- package/dist/cjs/sessions/transcript.js +105 -0
- package/dist/cjs/sessions/types.d.ts +61 -0
- package/dist/cjs/sessions/types.js +10 -0
- package/dist/cjs/sessions/write.d.ts +56 -0
- package/dist/cjs/sessions/write.js +216 -0
- package/dist/esm/private-file/index.d.ts +41 -0
- package/dist/esm/private-file/index.js +86 -0
- package/dist/esm/sessions/cli.d.ts +2 -0
- package/dist/esm/sessions/cli.js +150 -0
- package/dist/esm/sessions/convert.d.ts +41 -0
- package/dist/esm/sessions/convert.js +187 -0
- package/dist/esm/sessions/index.d.ts +12 -0
- package/dist/esm/sessions/index.js +12 -0
- package/dist/esm/sessions/read.d.ts +36 -0
- package/dist/esm/sessions/read.js +565 -0
- package/dist/esm/sessions/run.d.ts +9 -0
- package/dist/esm/sessions/run.js +55 -0
- package/dist/esm/sessions/stores.d.ts +9 -0
- package/dist/esm/sessions/stores.js +20 -0
- package/dist/esm/sessions/transcript.d.ts +38 -0
- package/dist/esm/sessions/transcript.js +99 -0
- package/dist/esm/sessions/types.d.ts +61 -0
- package/dist/esm/sessions/types.js +7 -0
- package/dist/esm/sessions/write.d.ts +56 -0
- package/dist/esm/sessions/write.js +208 -0
- package/native/win32-x64/process.node +0 -0
- package/package.json +24 -3
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.defaultStores = defaultStores;
|
|
4
|
+
const node_path_1 = require("node:path");
|
|
5
|
+
const host_ts_1 = require("../dirs/host.js");
|
|
6
|
+
/**
|
|
7
|
+
* Each agent's own default place for its sessions, by the same rules each agent applies itself: Claude Code honours CLAUDE_CONFIG_DIR,
|
|
8
|
+
* Codex CODEX_HOME, opencode XDG_DATA_HOME, the XENO agent XENO_AGENT_HOME. These are the AGENTS' stores, read where each agent writes
|
|
9
|
+
* them, never XENO's own layout; a product that runs agents in their own profiles passes those folders instead
|
|
10
|
+
* (`{ ...defaultStores(), claude: profileFolder }`).
|
|
11
|
+
* @param home the user folder they are under; the current user's by default (from the dirs resolver).
|
|
12
|
+
*/
|
|
13
|
+
function defaultStores(home = (0, host_ts_1.hostHome)(), env = (0, host_ts_1.hostEnv)()) {
|
|
14
|
+
return {
|
|
15
|
+
claude: env.CLAUDE_CONFIG_DIR || (0, node_path_1.join)(home, '.claude'),
|
|
16
|
+
codex: env.CODEX_HOME || (0, node_path_1.join)(home, '.codex'),
|
|
17
|
+
agy: (0, node_path_1.join)(home, '.gemini', 'antigravity-cli'),
|
|
18
|
+
// xeno-dirs-allow: opencode's own data folder, by opencode's own XDG rule; read where opencode writes it, never a XENO path
|
|
19
|
+
opencode: (0, node_path_1.join)(env.XDG_DATA_HOME || (0, node_path_1.join)(home, '.local', 'share'), 'opencode'),
|
|
20
|
+
// xeno-dirs-allow: the XENO agent still writes its sessions here (ADOPTION.md: xeno-agent-cli sessions "not moved"); read where they are until it moves them to agents/sessions
|
|
21
|
+
xenoAgent: env.XENO_AGENT_HOME || (0, node_path_1.join)(home, '.xeno-agent'),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The portable transcript every writer is built from: alternating user and assistant messages of plain text, with a report of what
|
|
3
|
+
* the move keeps and what it loses. Moved down from XENO Spawn (server/src/sessionConvert.js `portable`).
|
|
4
|
+
*
|
|
5
|
+
* Fidelity, by rule and never by accident:
|
|
6
|
+
* - user and assistant text, in order;
|
|
7
|
+
* - a tool call and its result become labelled text: tool names differ per agent, and a mis-paired native call is worse than an
|
|
8
|
+
* honest transcript;
|
|
9
|
+
* - thinking the original agent signed is DROPPED and counted, never forged;
|
|
10
|
+
* - a compaction stays as a marker; sub-agents follow as labelled summaries.
|
|
11
|
+
*/
|
|
12
|
+
import type { Subagent, Turn } from './types.ts';
|
|
13
|
+
export interface Message {
|
|
14
|
+
role: 'user' | 'assistant';
|
|
15
|
+
text: string;
|
|
16
|
+
at: string | null;
|
|
17
|
+
}
|
|
18
|
+
export interface Report {
|
|
19
|
+
userTurns: number;
|
|
20
|
+
assistantTurns: number;
|
|
21
|
+
toolCalls: number;
|
|
22
|
+
toolResults: number;
|
|
23
|
+
thinkingDropped: number;
|
|
24
|
+
compactions: number;
|
|
25
|
+
truncated: number;
|
|
26
|
+
total: number;
|
|
27
|
+
subagents: number;
|
|
28
|
+
subagentTurns: number;
|
|
29
|
+
}
|
|
30
|
+
export interface Transcript {
|
|
31
|
+
messages: Message[];
|
|
32
|
+
report: Report;
|
|
33
|
+
}
|
|
34
|
+
export declare const OUTPUT_CAP = 4000, TOTAL_CAP = 1500000;
|
|
35
|
+
export declare const cap: (s: string, n: number) => string;
|
|
36
|
+
export declare function toTranscript(turns: Turn[], subagents?: Subagent[]): Transcript;
|
|
37
|
+
/** What the move loses, in plain words, for a person to read before it runs. */
|
|
38
|
+
export declare function losses(report: Report, target: string, handoff: boolean): string[];
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.cap = exports.TOTAL_CAP = exports.OUTPUT_CAP = void 0;
|
|
4
|
+
exports.toTranscript = toTranscript;
|
|
5
|
+
exports.losses = losses;
|
|
6
|
+
exports.OUTPUT_CAP = 4000, exports.TOTAL_CAP = 1_500_000;
|
|
7
|
+
const stringify = (v) => { if (v == null)
|
|
8
|
+
return ''; if (typeof v === 'string')
|
|
9
|
+
return v; try {
|
|
10
|
+
return JSON.stringify(v);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return String(v);
|
|
14
|
+
} };
|
|
15
|
+
const cap = (s, n) => s.length > n ? `${s.slice(0, n)}\n… [${s.length - n} more characters not copied]` : s;
|
|
16
|
+
exports.cap = cap;
|
|
17
|
+
function toTranscript(turns, subagents = []) {
|
|
18
|
+
const msgs = [];
|
|
19
|
+
const report = { userTurns: 0, assistantTurns: 0, toolCalls: 0, toolResults: 0, thinkingDropped: 0, compactions: 0, truncated: 0, total: 0, subagents: subagents.length, subagentTurns: 0 };
|
|
20
|
+
const outputs = new Map();
|
|
21
|
+
const calls = new Set();
|
|
22
|
+
for (const t of turns) {
|
|
23
|
+
if (t.role === 'tool' && t.callId)
|
|
24
|
+
outputs.set(t.callId, t.output ?? '');
|
|
25
|
+
if (t.tool && t.callId)
|
|
26
|
+
calls.add(t.callId);
|
|
27
|
+
}
|
|
28
|
+
const push = (role, text, at) => {
|
|
29
|
+
if (!text.trim())
|
|
30
|
+
return;
|
|
31
|
+
const last = msgs[msgs.length - 1];
|
|
32
|
+
if (last && last.role === role)
|
|
33
|
+
last.text += `\n\n${text}`;
|
|
34
|
+
else
|
|
35
|
+
msgs.push({ role, text, at: at ?? null });
|
|
36
|
+
};
|
|
37
|
+
for (const t of turns) {
|
|
38
|
+
if (t.thinking) {
|
|
39
|
+
report.thinkingDropped++;
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (t.compaction) {
|
|
43
|
+
report.compactions++;
|
|
44
|
+
push('user', `[Earlier context was compacted by the original agent]${t.text && t.text !== '[conversation compacted]' && t.text !== '[conversation checkpoint]' ? `\n${t.text}` : ''}`, t.at);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (t.role === 'user') {
|
|
48
|
+
report.userTurns++;
|
|
49
|
+
push('user', t.text, t.at);
|
|
50
|
+
}
|
|
51
|
+
else if (t.role === 'assistant' && t.tool) {
|
|
52
|
+
report.toolCalls++;
|
|
53
|
+
const out = t.callId !== undefined ? outputs.get(t.callId) : undefined;
|
|
54
|
+
if (out !== undefined)
|
|
55
|
+
report.toolResults++;
|
|
56
|
+
if (out !== undefined && out.length > exports.OUTPUT_CAP)
|
|
57
|
+
report.truncated++;
|
|
58
|
+
push('assistant', `[tool ${t.tool}: ${(0, exports.cap)(stringify(t.input), 1200)}]${out === undefined ? '' : `\n→ ${(0, exports.cap)(out, exports.OUTPUT_CAP)}`}`, t.at);
|
|
59
|
+
}
|
|
60
|
+
else if (t.role === 'assistant') {
|
|
61
|
+
report.assistantTurns++;
|
|
62
|
+
push('assistant', t.text, t.at);
|
|
63
|
+
}
|
|
64
|
+
else if (t.role === 'tool' && !(t.callId && calls.has(t.callId))) {
|
|
65
|
+
// A result whose call is not in the transcript is still kept, labelled.
|
|
66
|
+
report.toolResults++;
|
|
67
|
+
push('assistant', `[tool result]\n${(0, exports.cap)(t.output ?? '', exports.OUTPUT_CAP)}`, t.at);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const sa of subagents) {
|
|
71
|
+
const lines = sa.turns.filter((t) => t.text).map((t) => `${t.role === 'user' ? 'asked' : 'answered'}: ${(0, exports.cap)(t.text, 1500)}`);
|
|
72
|
+
report.subagentTurns += lines.length;
|
|
73
|
+
if (lines.length)
|
|
74
|
+
push('assistant', `[sub-agent ${sa.name}, which ran separately in the original session]\n${(0, exports.cap)(lines.join('\n'), 6000)}`, null);
|
|
75
|
+
}
|
|
76
|
+
// Not every agent accepts a conversation that opens with the assistant: give it a leading user turn.
|
|
77
|
+
if (msgs[0]?.role === 'assistant')
|
|
78
|
+
msgs.unshift({ role: 'user', text: '[Conversation copied from another agent. It continues below.]', at: msgs[0].at });
|
|
79
|
+
let total = 0;
|
|
80
|
+
const kept = [];
|
|
81
|
+
for (const m of msgs) {
|
|
82
|
+
total += m.text.length;
|
|
83
|
+
if (total > exports.TOTAL_CAP) {
|
|
84
|
+
report.truncated++;
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
kept.push(m);
|
|
88
|
+
}
|
|
89
|
+
report.total = kept.length;
|
|
90
|
+
if (kept.length < msgs.length)
|
|
91
|
+
kept.push({ role: 'user', text: `[${msgs.length - kept.length} later messages were not copied: the conversation exceeded the copy limit]`, at: null });
|
|
92
|
+
return { messages: kept, report };
|
|
93
|
+
}
|
|
94
|
+
/** What the move loses, in plain words, for a person to read before it runs. */
|
|
95
|
+
function losses(report, target, handoff) {
|
|
96
|
+
const s = (n) => n === 1 ? '' : 's';
|
|
97
|
+
return [
|
|
98
|
+
report.thinkingDropped && `${report.thinkingDropped} thinking block${s(report.thinkingDropped)} dropped (signed by the original agent; never forged)`,
|
|
99
|
+
report.toolCalls && `${report.toolCalls} tool call${s(report.toolCalls)} ${report.toolCalls === 1 ? 'becomes' : 'become'} labelled text (${target} cannot re-run another agent's tools)`,
|
|
100
|
+
report.truncated && `${report.truncated} long output${s(report.truncated)} shortened`,
|
|
101
|
+
report.compactions && `${report.compactions} compaction${s(report.compactions)} kept as markers`,
|
|
102
|
+
report.subagents && `${report.subagents} sub-agent${s(report.subagents)} carried as labelled summaries (${report.subagentTurns} messages; their tool calls are not copied)`,
|
|
103
|
+
handoff && `${target} cannot import a conversation: it starts a NEW one with this transcript as context`,
|
|
104
|
+
].filter((x) => typeof x === 'string');
|
|
105
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent-neutral conversation every reader produces and every writer consumes (owner, 2026-11-27: one converter "agent agnostic,
|
|
3
|
+
* so it works between all of them"). A reader turns one agent's own session format into Turns; a writer turns a transcript of Turns into
|
|
4
|
+
* a new session in another agent's own format. Two pieces per agent, never one converter per pair.
|
|
5
|
+
*/
|
|
6
|
+
/** The agents this family reads and writes, by the names every XENO product already uses. */
|
|
7
|
+
export declare const VENDORS: readonly ["Claude Code", "Codex", "agy", "opencode", "XENO agent"];
|
|
8
|
+
export type Vendor = (typeof VENDORS)[number];
|
|
9
|
+
/** One session as its agent lists it: cheap metadata, read before any content. `locator` is where the agent keeps it. */
|
|
10
|
+
export interface SessionRef {
|
|
11
|
+
vendor: Vendor;
|
|
12
|
+
id: string;
|
|
13
|
+
cwd: string | null;
|
|
14
|
+
title: string;
|
|
15
|
+
created: number;
|
|
16
|
+
updated: number;
|
|
17
|
+
size: number;
|
|
18
|
+
locator: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* One step of a conversation. A tool call is an assistant turn with `tool`; its result is a `tool` turn with the same `callId`.
|
|
22
|
+
* `thinking` marks reasoning the original agent signed (it is never copied, only counted); `compaction` marks where the original
|
|
23
|
+
* agent compacted its context; `turnEnd` marks the last reply of a turn where the agent records it.
|
|
24
|
+
*/
|
|
25
|
+
export interface Turn {
|
|
26
|
+
role: 'user' | 'assistant' | 'tool' | 'system';
|
|
27
|
+
text: string;
|
|
28
|
+
tool?: string;
|
|
29
|
+
callId?: string;
|
|
30
|
+
input?: unknown;
|
|
31
|
+
output?: string;
|
|
32
|
+
at?: string | null;
|
|
33
|
+
thinking?: boolean;
|
|
34
|
+
turnEnd?: boolean;
|
|
35
|
+
compaction?: boolean;
|
|
36
|
+
}
|
|
37
|
+
/** A sub-agent's own conversation, which some agents (Claude Code) keep in separate files. */
|
|
38
|
+
export interface Subagent {
|
|
39
|
+
name: string;
|
|
40
|
+
turns: Turn[];
|
|
41
|
+
}
|
|
42
|
+
/** Where each agent keeps its sessions on this machine. `defaultStores()` gives each agent's own default. */
|
|
43
|
+
export interface Stores {
|
|
44
|
+
/** Claude Code's configuration folder (its sessions are under `projects/`). */
|
|
45
|
+
claude: string;
|
|
46
|
+
/** Codex's home (`sessions/`, `state_5.sqlite`). */
|
|
47
|
+
codex: string;
|
|
48
|
+
/** agy's (Antigravity CLI) data folder (`conversation_summaries.db`, `brain/`). */
|
|
49
|
+
agy: string;
|
|
50
|
+
/** opencode's data folder (`opencode.db`). */
|
|
51
|
+
opencode: string;
|
|
52
|
+
/** The XENO agent's home (`sessions/`). */
|
|
53
|
+
xenoAgent: string;
|
|
54
|
+
}
|
|
55
|
+
/** Runs an agent's own command and answers what it printed. Injected so a product can scope it (a profile's environment, a timeout). */
|
|
56
|
+
export type Runner = (command: string, args: string[], options?: {
|
|
57
|
+
cwd?: string;
|
|
58
|
+
env?: NodeJS.ProcessEnv;
|
|
59
|
+
timeoutMs?: number;
|
|
60
|
+
maxBytes?: number;
|
|
61
|
+
}) => Promise<string>;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The agent-neutral conversation every reader produces and every writer consumes (owner, 2026-11-27: one converter "agent agnostic,
|
|
4
|
+
* so it works between all of them"). A reader turns one agent's own session format into Turns; a writer turns a transcript of Turns into
|
|
5
|
+
* a new session in another agent's own format. Two pieces per agent, never one converter per pair.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.VENDORS = void 0;
|
|
9
|
+
/** The agents this family reads and writes, by the names every XENO product already uses. */
|
|
10
|
+
exports.VENDORS = ['Claude Code', 'Codex', 'agy', 'opencode', 'XENO agent'];
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Message } from './transcript.ts';
|
|
2
|
+
import type { Runner, SessionRef, Stores, Vendor } from './types.ts';
|
|
3
|
+
/** How each agent takes a copy, and whether it can resume it as its own conversation. */
|
|
4
|
+
export declare const TARGETS: Readonly<Record<Vendor, {
|
|
5
|
+
fidelity: 'native' | 'handoff';
|
|
6
|
+
via: string;
|
|
7
|
+
}>>;
|
|
8
|
+
/** What a writer created, so a caller can remove exactly that and nothing else. */
|
|
9
|
+
export type Artifact = {
|
|
10
|
+
kind: 'file';
|
|
11
|
+
path: string;
|
|
12
|
+
} | {
|
|
13
|
+
kind: 'dir';
|
|
14
|
+
path: string;
|
|
15
|
+
} | {
|
|
16
|
+
kind: 'workdir';
|
|
17
|
+
path: string;
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'vendor-session';
|
|
20
|
+
vendor: Vendor;
|
|
21
|
+
id: string;
|
|
22
|
+
};
|
|
23
|
+
export interface WriteContext {
|
|
24
|
+
stores: Stores;
|
|
25
|
+
run: Runner;
|
|
26
|
+
/** A new folder this conversion owns (it must not exist yet): staging files and a handoff document live here. */
|
|
27
|
+
workDir: string;
|
|
28
|
+
/** Called with each artifact the moment it exists, before the next step, so a crash still leaves an accurate list. */
|
|
29
|
+
record?: (a: Artifact) => void;
|
|
30
|
+
}
|
|
31
|
+
export interface Written {
|
|
32
|
+
id: string | null;
|
|
33
|
+
cwd: string;
|
|
34
|
+
artifacts: Artifact[];
|
|
35
|
+
resume?: string[];
|
|
36
|
+
handoff?: {
|
|
37
|
+
file: string;
|
|
38
|
+
prompt: string;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/** Claude Code's project folder name for a working folder. */
|
|
42
|
+
export declare const slugForCwd: (cwd: string) => string;
|
|
43
|
+
/** Create a new file exclusively at its final name and flush it: a competing creator makes this fail, never clobbered. */
|
|
44
|
+
export declare function writeNew(path: string, data: string): void;
|
|
45
|
+
/** Claude Code records for a portable transcript. */
|
|
46
|
+
export declare function claudeLines(msgs: Message[], sid: string, cwd: string): string;
|
|
47
|
+
/** The transcript as a document a fresh agent is asked to read, and the prompt that asks it. */
|
|
48
|
+
export declare function handoffDocument(msgs: Message[], ref: Pick<SessionRef, 'vendor' | 'id' | 'title' | 'cwd'>): {
|
|
49
|
+
full: string;
|
|
50
|
+
prompt: (file: string) => string;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Write the transcript into `target` as a new session belonging to `cwd`. Returns the new session's id, the artifacts created, and how
|
|
54
|
+
* to open it: the resume words, or for a handoff the document and the prompt that hands it over.
|
|
55
|
+
*/
|
|
56
|
+
export declare function writeSession(target: Vendor, msgs: Message[], source: Pick<SessionRef, 'vendor' | 'id' | 'title' | 'cwd'>, ctx: WriteContext): Promise<Written>;
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.slugForCwd = exports.TARGETS = void 0;
|
|
4
|
+
exports.writeNew = writeNew;
|
|
5
|
+
exports.claudeLines = claudeLines;
|
|
6
|
+
exports.handoffDocument = handoffDocument;
|
|
7
|
+
exports.writeSession = writeSession;
|
|
8
|
+
/**
|
|
9
|
+
* Create a NEW session in an agent's own format from a portable transcript. Moved down from XENO Spawn
|
|
10
|
+
* (server/src/sessionConvert.js `createCopy`), where each path was probed in throwaway homes and each target then resumed the copy and
|
|
11
|
+
* recalled a codeword from the imported turns (2026-09-28).
|
|
12
|
+
*
|
|
13
|
+
* 🔴 ONLY THE TARGET'S OWN INGESTION PATH, never a private database write:
|
|
14
|
+
* Claude Code a new `<uuid>.jsonl` in its documented project layout
|
|
15
|
+
* Codex its app-server `externalAgentConfig/import`, Codex's OWN Claude-to-Codex importer, given a Claude-shaped file staged in a
|
|
16
|
+
* private home (it reads only Claude files under its detection root)
|
|
17
|
+
* opencode `opencode import <export.json>`, recording a model opencode itself lists
|
|
18
|
+
* XENO agent `sessions/<id>/{meta.json,transcript.jsonl}` in its documented layout
|
|
19
|
+
* agy no ingestion path exists (its conversations are private protobuf records in SQLite) → a HANDOFF: a document a new agy
|
|
20
|
+
* conversation is asked to read, declared as such
|
|
21
|
+
* Every file is created exclusively at its final name, so nothing that exists is ever replaced.
|
|
22
|
+
*/
|
|
23
|
+
const node_crypto_1 = require("node:crypto");
|
|
24
|
+
const node_fs_1 = require("node:fs");
|
|
25
|
+
const node_path_1 = require("node:path");
|
|
26
|
+
const run_ts_1 = require("./run.js");
|
|
27
|
+
const read_ts_1 = require("./read.js");
|
|
28
|
+
const transcript_ts_1 = require("./transcript.js");
|
|
29
|
+
/** How each agent takes a copy, and whether it can resume it as its own conversation. */
|
|
30
|
+
exports.TARGETS = Object.freeze({
|
|
31
|
+
'Claude Code': { fidelity: 'native', via: "a new session file in Claude Code's own layout" },
|
|
32
|
+
Codex: { fidelity: 'native', via: "Codex's own external-session importer (from a Claude-shaped copy)" },
|
|
33
|
+
opencode: { fidelity: 'native', via: 'opencode import' },
|
|
34
|
+
'XENO agent': { fidelity: 'native', via: "a new session in the XENO agent's own layout" },
|
|
35
|
+
agy: { fidelity: 'handoff', via: 'a new conversation given the transcript as context (agy has no import)' },
|
|
36
|
+
});
|
|
37
|
+
/** Claude Code's project folder name for a working folder. */
|
|
38
|
+
const slugForCwd = (cwd) => (0, node_path_1.resolve)(cwd).split(node_path_1.sep).join('-').replace(/[^A-Za-z0-9]/g, '-');
|
|
39
|
+
exports.slugForCwd = slugForCwd;
|
|
40
|
+
/** Create a new file exclusively at its final name and flush it: a competing creator makes this fail, never clobbered. */
|
|
41
|
+
function writeNew(path, data) {
|
|
42
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(path), { recursive: true });
|
|
43
|
+
const fd = (0, node_fs_1.openSync)(path, 'wx', 0o600);
|
|
44
|
+
try {
|
|
45
|
+
const bytes = Buffer.from(data);
|
|
46
|
+
for (let off = 0; off < bytes.length;)
|
|
47
|
+
off += (0, node_fs_1.writeSync)(fd, bytes, off);
|
|
48
|
+
(0, node_fs_1.fsyncSync)(fd);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
(0, node_fs_1.closeSync)(fd);
|
|
52
|
+
try {
|
|
53
|
+
(0, node_fs_1.unlinkSync)(path);
|
|
54
|
+
}
|
|
55
|
+
catch { /* already gone */ }
|
|
56
|
+
throw e;
|
|
57
|
+
}
|
|
58
|
+
(0, node_fs_1.closeSync)(fd);
|
|
59
|
+
}
|
|
60
|
+
/** Claude Code records for a portable transcript. */
|
|
61
|
+
function claudeLines(msgs, sid, cwd) {
|
|
62
|
+
let parent = null;
|
|
63
|
+
const base = Date.now() - msgs.length * 1000;
|
|
64
|
+
return msgs.map((m, i) => {
|
|
65
|
+
const uuid = (0, node_crypto_1.randomUUID)(), at = new Date(base + i * 1000).toISOString();
|
|
66
|
+
const r = { parentUuid: parent, isSidechain: false, userType: 'external', entrypoint: 'cli', cwd, sessionId: sid, version: '2.1.283', gitBranch: '',
|
|
67
|
+
type: m.role, uuid, timestamp: at,
|
|
68
|
+
message: m.role === 'user' ? { role: 'user', content: m.text }
|
|
69
|
+
: { id: `msg_${uuid.replace(/-/g, '').slice(0, 24)}`, type: 'message', role: 'assistant', model: 'imported', content: [{ type: 'text', text: m.text }], stop_reason: 'end_turn', stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } };
|
|
70
|
+
parent = uuid;
|
|
71
|
+
return JSON.stringify(r);
|
|
72
|
+
}).join('\n') + '\n';
|
|
73
|
+
}
|
|
74
|
+
/** Codex's app-server: one import request and its completion notice. */
|
|
75
|
+
function codexImport(codexHome, stageHome, path, cwd, title) {
|
|
76
|
+
return new Promise((yes, no) => {
|
|
77
|
+
// HOME points Codex's detection at the staged Claude file; CODEX_HOME keeps the thread it creates in the store the reader lists.
|
|
78
|
+
// Without CODEX_HOME, Codex would put the thread under the staging home, where nothing lists it.
|
|
79
|
+
const env = { ...process.env, HOME: stageHome, USERPROFILE: stageHome, CODEX_HOME: codexHome };
|
|
80
|
+
const p = (0, run_ts_1.spawnAgent)('codex', ['app-server'], { env, windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
81
|
+
let buf = '', n = 0;
|
|
82
|
+
const timer = setTimeout(() => end(null, new Error('Codex did not finish importing in time.')), 60_000);
|
|
83
|
+
function end(v, e) { clearTimeout(timer); try {
|
|
84
|
+
p.kill();
|
|
85
|
+
}
|
|
86
|
+
catch { /* gone */ } if (e)
|
|
87
|
+
no(e);
|
|
88
|
+
else
|
|
89
|
+
yes(v); }
|
|
90
|
+
const send = (method, params, id = ++n) => p.stdin?.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
|
|
91
|
+
p.on('error', (e) => end(null, e));
|
|
92
|
+
p.stdout?.on('data', (d) => {
|
|
93
|
+
buf += d;
|
|
94
|
+
let i;
|
|
95
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
96
|
+
const l = buf.slice(0, i);
|
|
97
|
+
buf = buf.slice(i + 1);
|
|
98
|
+
let m;
|
|
99
|
+
try {
|
|
100
|
+
m = JSON.parse(l);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (m.id === 1) {
|
|
106
|
+
p.stdin?.write('{"jsonrpc":"2.0","method":"initialized"}\n');
|
|
107
|
+
send('externalAgentConfig/import', { migrationItems: [{ itemType: 'SESSIONS', description: 'XENO session copy', cwd: null, details: { sessions: [{ path, cwd, title }] } }], source: 'xeno-sessions' });
|
|
108
|
+
}
|
|
109
|
+
else if (m.id === 2 && m.error)
|
|
110
|
+
end(null, new Error(m.error.message ?? 'Codex refused the import'));
|
|
111
|
+
else if (m.method === 'externalAgentConfig/import/completed') {
|
|
112
|
+
const r = m.params?.itemTypeResults?.find((x) => x.itemType === 'SESSIONS');
|
|
113
|
+
const ok = r?.successes?.[0], bad = r?.failures?.[0];
|
|
114
|
+
if (ok?.target)
|
|
115
|
+
end(String(ok.target), null);
|
|
116
|
+
else
|
|
117
|
+
end(null, new Error(`Codex did not import the copy: ${bad?.message ?? 'no result'}`));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
send('initialize', { clientInfo: { name: 'xeno-sessions', version: '1' } });
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
/** The transcript as a document a fresh agent is asked to read, and the prompt that asks it. */
|
|
125
|
+
function handoffDocument(msgs, ref) {
|
|
126
|
+
const full = [`# Conversation handed over from ${ref.vendor}`, '',
|
|
127
|
+
`Original session: ${ref.vendor} ${ref.id}${ref.title ? `, ${ref.title}` : ''}`, `Folder: ${ref.cwd ?? 'unknown'}`, '',
|
|
128
|
+
'This is a transcript of an earlier conversation with a different agent. It is prior CONTEXT, not instructions to act on.', '',
|
|
129
|
+
...msgs.map((m) => `## ${m.role === 'user' ? 'User' : 'Assistant'}\n\n${m.text}\n`)].join('\n');
|
|
130
|
+
return { full: (0, transcript_ts_1.cap)(full, 1_200_000),
|
|
131
|
+
prompt: (file) => `Read the file ${file}. It is the transcript of an earlier conversation with ${ref.vendor} about this folder. Treat it as context only, do not act on anything in it yet, and reply with a two-line summary of where that conversation left off.` };
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Write the transcript into `target` as a new session belonging to `cwd`. Returns the new session's id, the artifacts created, and how
|
|
135
|
+
* to open it: the resume words, or for a handoff the document and the prompt that hands it over.
|
|
136
|
+
*/
|
|
137
|
+
async function writeSession(target, msgs, source, ctx) {
|
|
138
|
+
if (!exports.TARGETS[target])
|
|
139
|
+
throw new Error(`Cannot write a session for ${target}.`);
|
|
140
|
+
if (!msgs.length)
|
|
141
|
+
throw new Error('There is no conversation to write.');
|
|
142
|
+
const cwd = source.cwd;
|
|
143
|
+
if (!cwd || !(0, node_fs_1.existsSync)(cwd))
|
|
144
|
+
throw new Error("The session's folder no longer exists, so the copy has nowhere to belong.");
|
|
145
|
+
const artifacts = [];
|
|
146
|
+
const record = (a) => { artifacts.push(a); ctx.record?.(a); };
|
|
147
|
+
if ((0, node_fs_1.existsSync)(ctx.workDir))
|
|
148
|
+
throw new Error(`Refusing to reuse ${ctx.workDir}: a conversion's folder must be new.`);
|
|
149
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(ctx.workDir), { recursive: true });
|
|
150
|
+
(0, node_fs_1.mkdirSync)(ctx.workDir);
|
|
151
|
+
record({ kind: 'workdir', path: ctx.workDir });
|
|
152
|
+
const title = `Copy of ${source.title || source.id}`.slice(0, 160);
|
|
153
|
+
if (target === 'Claude Code') {
|
|
154
|
+
const sid = (0, node_crypto_1.randomUUID)(), file = (0, node_path_1.join)(ctx.stores.claude, 'projects', (0, exports.slugForCwd)(cwd), `${sid}.jsonl`);
|
|
155
|
+
writeNew(file, claudeLines(msgs, sid, cwd));
|
|
156
|
+
record({ kind: 'file', path: file });
|
|
157
|
+
return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
|
|
158
|
+
}
|
|
159
|
+
if (target === 'Codex') {
|
|
160
|
+
const stageHome = (0, node_path_1.join)(ctx.workDir, 'stage-home'), sid = (0, node_crypto_1.randomUUID)();
|
|
161
|
+
const file = (0, node_path_1.join)(stageHome, '.claude', 'projects', (0, exports.slugForCwd)(cwd), `${sid}.jsonl`);
|
|
162
|
+
writeNew(file, claudeLines(msgs, sid, cwd));
|
|
163
|
+
const thread = (0, read_ts_1.safeSessionId)(await codexImport(ctx.stores.codex, stageHome, file, cwd, title));
|
|
164
|
+
if (!thread)
|
|
165
|
+
throw new Error('Codex reported an import without a thread id.');
|
|
166
|
+
record({ kind: 'vendor-session', vendor: 'Codex', id: thread });
|
|
167
|
+
return { id: thread, cwd, artifacts, resume: ['resume', thread] };
|
|
168
|
+
}
|
|
169
|
+
if (target === 'opencode') {
|
|
170
|
+
// 🔴 opencode resumes with the model RECORDED on the session's messages, and an unknown one fails the resume with "Unexpected server
|
|
171
|
+
// error" (measured: modelID "imported" did exactly that). So the copy records a model opencode itself lists in that folder.
|
|
172
|
+
const listed = (await ctx.run('opencode', ['models'], { cwd }).catch(() => '')).split(/\r?\n/).map((l) => l.trim()).find((l) => /^[\w.-]+\/[\w.:-]+$/.test(l));
|
|
173
|
+
if (!listed)
|
|
174
|
+
throw new Error('opencode lists no model, so a copy could not be resumed there. Run `opencode models` to check its setup.');
|
|
175
|
+
const [providerID, ...rest] = listed.split('/'), modelID = rest.join('/');
|
|
176
|
+
const now = Date.now(), sid = `ses_${(0, node_crypto_1.randomUUID)().replace(/-/g, '').slice(0, 26)}`;
|
|
177
|
+
const mid = (i) => `msg_${sid.slice(4, 16)}${String(i).padStart(14, '0')}`;
|
|
178
|
+
const exp = { info: { id: sid, slug: `xeno-copy-${sid.slice(4, 12)}`, projectID: 'global', directory: cwd, title, version: '1.18.32', time: { created: now, updated: now } },
|
|
179
|
+
messages: msgs.map((m, i) => ({
|
|
180
|
+
info: m.role === 'user'
|
|
181
|
+
? { id: mid(i), sessionID: sid, role: 'user', time: { created: now + i }, agent: 'build', model: { providerID, modelID } }
|
|
182
|
+
: { id: mid(i), sessionID: sid, role: 'assistant', parentID: i ? mid(i - 1) : undefined, time: { created: now + i, completed: now + i }, mode: 'build', agent: 'build',
|
|
183
|
+
modelID, providerID, path: { cwd, root: cwd }, cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, finish: 'stop' },
|
|
184
|
+
parts: [{ id: `prt_${mid(i).slice(4)}`, sessionID: sid, messageID: mid(i), type: 'text', text: m.text }]
|
|
185
|
+
})) };
|
|
186
|
+
const file = (0, node_path_1.join)(ctx.workDir, 'opencode-import.json');
|
|
187
|
+
writeNew(file, JSON.stringify(exp));
|
|
188
|
+
const out = await ctx.run('opencode', ['import', file], { cwd, timeoutMs: 120_000 });
|
|
189
|
+
record({ kind: 'vendor-session', vendor: 'opencode', id: sid });
|
|
190
|
+
if (!out.includes(sid))
|
|
191
|
+
throw new Error('opencode did not confirm the imported session id.');
|
|
192
|
+
return { id: sid, cwd, artifacts, resume: ['--session', sid] };
|
|
193
|
+
}
|
|
194
|
+
if (target === 'XENO agent') {
|
|
195
|
+
const stamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
|
|
196
|
+
const sid = `xeno-copy-${stamp}-${(0, node_crypto_1.randomUUID)().slice(0, 5)}`, dir = (0, node_path_1.join)(ctx.stores.xenoAgent, 'sessions', sid);
|
|
197
|
+
if ((0, node_fs_1.existsSync)(dir))
|
|
198
|
+
throw new Error(`Refusing to overwrite ${dir}`);
|
|
199
|
+
(0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(dir), { recursive: true });
|
|
200
|
+
(0, node_fs_1.mkdirSync)(dir);
|
|
201
|
+
record({ kind: 'dir', path: dir });
|
|
202
|
+
const at = new Date().toISOString();
|
|
203
|
+
writeNew((0, node_path_1.join)(dir, 'meta.json'), JSON.stringify({ id: sid, role: 'assistant', status: 'active', createdAt: at, updatedAt: at, lastActivity: at, workingDirectory: cwd,
|
|
204
|
+
model: '', checkpoints: [], messageCount: msgs.length, tokenUsage: { input: 0, output: 0, total: 0 }, formatVersion: 1, executionMode: 'agent', name: title }, null, 2));
|
|
205
|
+
writeNew((0, node_path_1.join)(dir, 'transcript.jsonl'), [{ type: 'session_start', data: { sessionId: sid, role: 'assistant', workingDirectory: cwd, model: '', formatVersion: 1 } },
|
|
206
|
+
...msgs.map((m, i) => ({ type: m.role === 'user' ? 'user_message' : 'assistant_message', data: { id: `m${i}`, role: m.role, content: m.role === 'user' ? m.text : [{ type: 'text', text: m.text }] } }))]
|
|
207
|
+
.map((r, i) => JSON.stringify({ id: `e${i}`, timestamp: at, sequence: i, ...r })).join('\n') + '\n');
|
|
208
|
+
return { id: sid, cwd, artifacts, resume: ['--resume', sid] };
|
|
209
|
+
}
|
|
210
|
+
// agy
|
|
211
|
+
const doc = handoffDocument(msgs, source);
|
|
212
|
+
const file = (0, node_path_1.join)(ctx.workDir, 'handoff.md');
|
|
213
|
+
writeNew(file, doc.full);
|
|
214
|
+
record({ kind: 'file', path: file });
|
|
215
|
+
return { id: null, cwd, artifacts, handoff: { file, prompt: doc.prompt(file) } };
|
|
216
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Largest file this family reads or writes (1 MiB). */
|
|
2
|
+
export declare const PRIVATE_FILE_MAX_BYTES = 1048576;
|
|
3
|
+
export interface PrivateFileReceipt {
|
|
4
|
+
/**
|
|
5
|
+
* `committed`: done (for a read or delete this is also the answer when there was no file).
|
|
6
|
+
* `exists`: a write with `ifAbsent` found a file and left it alone.
|
|
7
|
+
* `not-committed`: refused or failed before anything was published.
|
|
8
|
+
* `uncertain`: failed during publication; the target may hold either version. `retainedFiles` are kept as evidence.
|
|
9
|
+
*/
|
|
10
|
+
outcome: 'committed' | 'not-committed' | 'uncertain' | 'exists';
|
|
11
|
+
/** The step that was running when the operation ended. */
|
|
12
|
+
phase: string;
|
|
13
|
+
/** The Windows error code of a failure, 0 on success. */
|
|
14
|
+
errorCode: number;
|
|
15
|
+
/** Temp or backup files left behind in the directory (file names only). */
|
|
16
|
+
retainedFiles: string[];
|
|
17
|
+
/** A read's bytes, or null when the file does not exist. */
|
|
18
|
+
data: Uint8Array | null;
|
|
19
|
+
/** True when a delete removed a file. */
|
|
20
|
+
deleted: boolean;
|
|
21
|
+
}
|
|
22
|
+
export interface PrivateFileRequest {
|
|
23
|
+
path: string;
|
|
24
|
+
operation: 'read' | 'write' | 'delete';
|
|
25
|
+
/** The bytes to write. */
|
|
26
|
+
payload?: Uint8Array;
|
|
27
|
+
/** Write only when the file does not exist yet. */
|
|
28
|
+
ifAbsent?: boolean;
|
|
29
|
+
/** A lower-case UUID naming this operation's temp and backup files. */
|
|
30
|
+
operationId: string;
|
|
31
|
+
}
|
|
32
|
+
/** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
|
|
33
|
+
export declare function privateFileSupport(): {
|
|
34
|
+
available: boolean;
|
|
35
|
+
reason?: string;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
|
|
39
|
+
* binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
|
|
40
|
+
*/
|
|
41
|
+
export declare function privateFileOperation(request: PrivateFileRequest): PrivateFileReceipt;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xenosystem/primitives/private-file` — read, write or delete one file that only its owner and SYSTEM may open.
|
|
3
|
+
*
|
|
4
|
+
* Each operation takes a gate file in the same directory (so processes take turns), and a write is published so
|
|
5
|
+
* that a reader sees the old bytes or the new bytes, never a partial file: new bytes go to a private temp file,
|
|
6
|
+
* are flushed, and replace the target in one step (`ReplaceFileW`), or are linked into place when the target does
|
|
7
|
+
* not exist yet (so a create never overwrites).
|
|
8
|
+
*
|
|
9
|
+
* Why this exists: the agent SDK ran exactly this through a PowerShell helper that compiled C# on every call.
|
|
10
|
+
* Measured 2026-11-11: 0.6 to 1.2 s per operation on a quiet machine, more under load. A sign-out does many of
|
|
11
|
+
* them, passed the 30 s the Agent host allows one account request, and left the owner signed in on a blank
|
|
12
|
+
* window. Here the same steps run inside the calling process from a binary that ships in this package
|
|
13
|
+
* (`native/win32-<arch>/process.node`); nothing is compiled or started at run time.
|
|
14
|
+
*
|
|
15
|
+
* The files on disk are the same as the helper's (gate `.xeno-protected-write.lock`, temp and backup
|
|
16
|
+
* `.xeno-protected-<operation id>.tmp|.backup`), so a process still using the helper and a process using this
|
|
17
|
+
* can share a directory and still take turns.
|
|
18
|
+
*
|
|
19
|
+
* Windows only. `privateFileSupport()` says whether it can be used; a caller keeps its own fallback otherwise.
|
|
20
|
+
*/
|
|
21
|
+
import { existsSync } from 'node:fs';
|
|
22
|
+
import { createRequire } from 'node:module';
|
|
23
|
+
import { join } from 'node:path';
|
|
24
|
+
import { moduleDir } from "../process/here.js";
|
|
25
|
+
/** Largest file this family reads or writes (1 MiB). */
|
|
26
|
+
export const PRIVATE_FILE_MAX_BYTES = 1_048_576;
|
|
27
|
+
let nativeCache;
|
|
28
|
+
function loadNative() {
|
|
29
|
+
if (nativeCache)
|
|
30
|
+
return nativeCache;
|
|
31
|
+
if (process.platform !== 'win32')
|
|
32
|
+
return (nativeCache = { reason: 'not Windows' });
|
|
33
|
+
const name = `win32-${process.arch}`;
|
|
34
|
+
// src/private-file (tests) and dist/{esm,cjs}/private-file (published) both sit under the package directory.
|
|
35
|
+
const candidates = [join(moduleDir, '..', '..', 'native', name, 'process.node'), join(moduleDir, '..', '..', '..', 'native', name, 'process.node')];
|
|
36
|
+
const file = candidates.find((p) => existsSync(p));
|
|
37
|
+
if (!file)
|
|
38
|
+
return (nativeCache = { reason: `no native binary for ${name}` });
|
|
39
|
+
try {
|
|
40
|
+
const binding = createRequire(file)(file);
|
|
41
|
+
if (typeof binding.privateFileOperation !== 'function')
|
|
42
|
+
return (nativeCache = { reason: 'native binary has no privateFileOperation' });
|
|
43
|
+
return (nativeCache = { run: binding.privateFileOperation });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
|
|
50
|
+
export function privateFileSupport() {
|
|
51
|
+
const native = loadNative();
|
|
52
|
+
return native.run ? { available: true } : { available: false, ...(native.reason ? { reason: native.reason } : {}) };
|
|
53
|
+
}
|
|
54
|
+
const OUTCOMES = new Set(['committed', 'not-committed', 'uncertain', 'exists']);
|
|
55
|
+
/**
|
|
56
|
+
* Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
|
|
57
|
+
* binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
|
|
58
|
+
*/
|
|
59
|
+
export function privateFileOperation(request) {
|
|
60
|
+
const native = loadNative();
|
|
61
|
+
if (!native.run)
|
|
62
|
+
throw new Error(`private-file is unavailable: ${native.reason ?? 'unknown reason'}`);
|
|
63
|
+
if (typeof request.path !== 'string' || !request.path)
|
|
64
|
+
throw new TypeError('private-file: path is required');
|
|
65
|
+
if (!['read', 'write', 'delete'].includes(request.operation))
|
|
66
|
+
throw new TypeError('private-file: unknown operation');
|
|
67
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request.operationId))
|
|
68
|
+
throw new TypeError('private-file: operationId must be a lower-case UUID');
|
|
69
|
+
const payload = request.operation === 'write' ? request.payload ?? new Uint8Array(0) : null;
|
|
70
|
+
if (payload && payload.byteLength > PRIVATE_FILE_MAX_BYTES) {
|
|
71
|
+
return { outcome: 'not-committed', phase: 'validate', errorCode: 0, retainedFiles: [], data: null, deleted: false };
|
|
72
|
+
}
|
|
73
|
+
// The binding takes a Buffer; a plain Uint8Array view is wrapped without copying.
|
|
74
|
+
const bytes = payload ? Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength) : null;
|
|
75
|
+
const raw = native.run(request.path, request.operation, bytes, request.ifAbsent === true, request.operationId);
|
|
76
|
+
if (!OUTCOMES.has(raw.outcome))
|
|
77
|
+
throw new Error('private-file: native binary returned an unknown outcome');
|
|
78
|
+
return {
|
|
79
|
+
outcome: raw.outcome,
|
|
80
|
+
phase: raw.phase,
|
|
81
|
+
errorCode: raw.errorCode,
|
|
82
|
+
retainedFiles: [...raw.retainedFiles],
|
|
83
|
+
data: raw.data ?? null,
|
|
84
|
+
deleted: raw.deleted === true,
|
|
85
|
+
};
|
|
86
|
+
}
|