@staix/agent-hosts 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +115 -2
- package/fixtures/DIVERGENCES.md +23 -0
- package/fixtures/copies/agent-mem.json +585 -0
- package/fixtures/copies/agent-research.json +473 -0
- package/fixtures/copies/vault-mem.json +457 -0
- package/fixtures/receipts/agent-mem/v1.json +50 -0
- package/fixtures/receipts/agent-mem/v2.json +50 -0
- package/fixtures/receipts/agent-research/v1.json +32 -0
- package/fixtures/receipts/vault-mem/v1.json +29 -0
- package/package.json +31 -4
- package/src/entry.ts +450 -0
- package/src/fs-safe.ts +150 -0
- package/src/hosts.ts +114 -0
- package/src/index.ts +7 -0
- package/src/json.ts +162 -0
- package/src/paths.ts +144 -0
- package/src/platform.ts +31 -0
- package/src/receipt-legacy.ts +79 -0
- package/src/receipt.ts +117 -0
- package/src/refusal.ts +43 -0
- package/src/toml.ts +367 -0
package/src/hosts.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
export type HostScope = "user" | "project";
|
|
2
|
+
|
|
3
|
+
export interface HomeOverride {
|
|
4
|
+
key: string;
|
|
5
|
+
rule: "trim-presence" | "empty-means-set" | "expand-tilde" | "absolute-only";
|
|
6
|
+
directory: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface HostConfig {
|
|
10
|
+
scope: HostScope;
|
|
11
|
+
path: string;
|
|
12
|
+
override?: HomeOverride;
|
|
13
|
+
defaultSiblingRoot?: string;
|
|
14
|
+
routeVariables?: readonly string[];
|
|
15
|
+
mergedFiles?: readonly string[];
|
|
16
|
+
personalSource?: { profile: "claude" | "codex"; orcaHomeVariable: "ORCA_USER_DATA_PATH" };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type HostFormat =
|
|
20
|
+
| { kind: "json"; key: string; aliases?: readonly string[] }
|
|
21
|
+
| { kind: "toml"; table: readonly string[] };
|
|
22
|
+
|
|
23
|
+
export interface HostDefinition {
|
|
24
|
+
id: string;
|
|
25
|
+
files: readonly HostConfig[];
|
|
26
|
+
format: HostFormat;
|
|
27
|
+
/** Minimum fields read by the host. Additional entry fields pass through. */
|
|
28
|
+
entry: Readonly<Record<string, string>>;
|
|
29
|
+
verified: readonly [string, ...string[]];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const stdio = { command: "string", args: "string[]" } as const;
|
|
33
|
+
const mcpServers = { kind: "json", key: "mcpServers" } as const;
|
|
34
|
+
|
|
35
|
+
export const HOSTS = {
|
|
36
|
+
claude: {
|
|
37
|
+
id: "claude",
|
|
38
|
+
files: [{
|
|
39
|
+
scope: "user",
|
|
40
|
+
path: ".claude.json",
|
|
41
|
+
defaultSiblingRoot: ".claude",
|
|
42
|
+
override: { key: "CLAUDE_CONFIG_DIR", rule: "trim-presence", directory: "" },
|
|
43
|
+
personalSource: { profile: "claude", orcaHomeVariable: "ORCA_USER_DATA_PATH" },
|
|
44
|
+
}],
|
|
45
|
+
format: mcpServers,
|
|
46
|
+
entry: { ...stdio, type: "stdio", env: "Record<string, string>" },
|
|
47
|
+
verified: ["2.1.332"],
|
|
48
|
+
},
|
|
49
|
+
codex: {
|
|
50
|
+
id: "codex",
|
|
51
|
+
files: [{
|
|
52
|
+
scope: "user",
|
|
53
|
+
path: "config.toml",
|
|
54
|
+
override: { key: "CODEX_HOME", rule: "trim-presence", directory: ".codex" },
|
|
55
|
+
personalSource: { profile: "codex", orcaHomeVariable: "ORCA_USER_DATA_PATH" },
|
|
56
|
+
}],
|
|
57
|
+
format: { kind: "toml", table: ["mcp_servers"] },
|
|
58
|
+
entry: stdio,
|
|
59
|
+
verified: ["0.165.0"],
|
|
60
|
+
},
|
|
61
|
+
kimi: {
|
|
62
|
+
id: "kimi",
|
|
63
|
+
files: [
|
|
64
|
+
{ scope: "user", path: "mcp.json", override: { key: "KIMI_CODE_HOME", rule: "trim-presence", directory: ".kimi-code" } },
|
|
65
|
+
{ scope: "project", path: ".kimi-code/mcp.json" },
|
|
66
|
+
],
|
|
67
|
+
format: mcpServers,
|
|
68
|
+
entry: stdio,
|
|
69
|
+
verified: ["2.7.2"],
|
|
70
|
+
},
|
|
71
|
+
pi: {
|
|
72
|
+
id: "pi",
|
|
73
|
+
files: [{ scope: "user", path: "mcp.json", override: { key: "PI_CODING_AGENT_DIR", rule: "trim-presence", directory: ".pi/agent" } }],
|
|
74
|
+
format: mcpServers,
|
|
75
|
+
entry: stdio,
|
|
76
|
+
verified: ["1.6.0"],
|
|
77
|
+
},
|
|
78
|
+
qwen: {
|
|
79
|
+
id: "qwen",
|
|
80
|
+
files: [{ scope: "user", path: "settings.json", override: { key: "QWEN_HOME", rule: "expand-tilde", directory: ".qwen" } }],
|
|
81
|
+
format: mcpServers,
|
|
82
|
+
entry: stdio,
|
|
83
|
+
verified: ["0.26.1"],
|
|
84
|
+
},
|
|
85
|
+
jcode: {
|
|
86
|
+
id: "jcode",
|
|
87
|
+
files: [{ scope: "user", path: "mcp.json", override: { key: "JCODE_HOME", rule: "empty-means-set", directory: ".jcode" } }],
|
|
88
|
+
format: { kind: "json", key: "servers", aliases: ["mcpServers"] },
|
|
89
|
+
entry: { ...stdio, shared: "boolean" },
|
|
90
|
+
verified: ["0.99.1"],
|
|
91
|
+
},
|
|
92
|
+
opencode: {
|
|
93
|
+
id: "opencode",
|
|
94
|
+
files: [{
|
|
95
|
+
scope: "user",
|
|
96
|
+
path: "opencode/opencode.json",
|
|
97
|
+
override: { key: "XDG_CONFIG_HOME", rule: "absolute-only", directory: ".config" },
|
|
98
|
+
routeVariables: ["OPENCODE_CONFIG", "OPENCODE_CONFIG_DIR", "OPENCODE_CONFIG_CONTENT"],
|
|
99
|
+
mergedFiles: ["opencode.jsonc", "config.json"],
|
|
100
|
+
}],
|
|
101
|
+
format: { kind: "json", key: "mcp" },
|
|
102
|
+
entry: { type: "local", command: "string[]", enabled: "boolean" },
|
|
103
|
+
verified: ["1.18.35"],
|
|
104
|
+
},
|
|
105
|
+
gemini: {
|
|
106
|
+
id: "gemini",
|
|
107
|
+
files: [{ scope: "user", path: ".gemini/settings.json", override: { key: "GEMINI_CLI_HOME", rule: "absolute-only", directory: "" } }],
|
|
108
|
+
format: mcpServers,
|
|
109
|
+
entry: stdio,
|
|
110
|
+
verified: ["0.61.0"],
|
|
111
|
+
},
|
|
112
|
+
} as const satisfies Record<string, HostDefinition>;
|
|
113
|
+
|
|
114
|
+
export type HostId = keyof typeof HOSTS;
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { realPath } from "./platform.ts";
|
|
2
|
+
export { createJsonMcpCodec, type ConfigImage, type JsonMcpCodecOptions } from "./json.ts";
|
|
3
|
+
export { SETUP_CONFIG_BYTES, insertTomlArrayItems, restoreRemovedItems, setTomlPath, updateTomlArray } from "./toml.ts";
|
|
4
|
+
export { HOSTS, type HostConfig, type HostDefinition, type HostFormat, type HostId, type HostScope, type HomeOverride } from "./hosts.ts";
|
|
5
|
+
export { resolveHostPaths, type HostPaths, type HostRedirect, type HostRefusal, type ResolveHostPathsOptions } from "./paths.ts";
|
|
6
|
+
export { applyEntry, planEntry, readEntryReceipt, undoEntry, UNDO_NOOP_CODES, type ApplyEntryOptions, type EntryPlan, type EntryReceipt, type EntryResult, type EntryTarget, type PlanEntryOptions, type UndoNoopCode } from "./entry.ts";
|
|
7
|
+
export { EntryRefusal, REFUSAL_CODES, type RefusalCode } from "./refusal.ts";
|
package/src/json.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { SETUP_CONFIG_BYTES } from "./toml.ts";
|
|
3
|
+
import { EntryRefusal } from "./refusal.ts";
|
|
4
|
+
|
|
5
|
+
export interface ConfigImage { bytes: string | null; mode: number }
|
|
6
|
+
|
|
7
|
+
interface Member { key: string; keyStart: number; keyEnd: number; valueStart: number; valueEnd: number; comma?: number }
|
|
8
|
+
interface ObjectSpan { close: number; members: Member[] }
|
|
9
|
+
interface Document { text: string; root: ObjectSpan; container?: Member; servers?: ObjectSpan; owned?: Member }
|
|
10
|
+
interface Edit { start: number; end: number; text: string }
|
|
11
|
+
const decode = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
12
|
+
const same = (a: ConfigImage, b: ConfigImage) => a.bytes === b.bytes && a.mode === b.mode;
|
|
13
|
+
export interface JsonMcpCodecOptions { canonicalKey: string; entryName: string; aliases?: readonly string[]; label: string; preferCanonical?: boolean }
|
|
14
|
+
|
|
15
|
+
/** Strict JSON only. Shared lexical edits never re-render unrelated configuration data. */
|
|
16
|
+
export function createJsonMcpCodec(options: JsonMcpCodecOptions) {
|
|
17
|
+
const { canonicalKey, entryName, label, preferCanonical } = options, keys = new Set([canonicalKey, ...(options.aliases ?? [])]);
|
|
18
|
+
const fail = (): never => { throw Error(`setup ${label} MCP configuration unavailable or ambiguous; no configuration changed`); };
|
|
19
|
+
const size = (): never => {
|
|
20
|
+
throw new EntryRefusal("size-limit", `setup ${label} MCP configuration exceeds 8 MiB; reduce the file size before retrying`);
|
|
21
|
+
};
|
|
22
|
+
const whitespace = (text: string, start: number) => { let at = start; while (at < text.length && /[ \t\r\n]/.test(text[at]!)) at++; return at; };
|
|
23
|
+
function stringEnd(text: string, start: number): number {
|
|
24
|
+
let at = start + 1;
|
|
25
|
+
while (at < text.length) { if (text[at] === "\\") at += 2; else if (text[at++] === '"') return at; }
|
|
26
|
+
return fail();
|
|
27
|
+
}
|
|
28
|
+
/** JSON.parse validates syntax first; this scanner retains only lexical edit boundaries. */
|
|
29
|
+
function valueEnd(text: string, start: number): number {
|
|
30
|
+
if (text[start] === '"') return stringEnd(text, start);
|
|
31
|
+
if (text[start] === "{" || text[start] === "[") {
|
|
32
|
+
let depth = 0, at = start;
|
|
33
|
+
while (at < text.length) {
|
|
34
|
+
const char = text[at]!;
|
|
35
|
+
if (char === '"') { at = stringEnd(text, at); continue; }
|
|
36
|
+
if (char === "{" || char === "[") depth++;
|
|
37
|
+
else if ((char === "}" || char === "]") && --depth === 0) return at + 1;
|
|
38
|
+
at++;
|
|
39
|
+
}
|
|
40
|
+
return fail();
|
|
41
|
+
}
|
|
42
|
+
let at = start; while (at < text.length && !/[ \t\r\n,}\]]/.test(text[at]!)) at++; return at;
|
|
43
|
+
}
|
|
44
|
+
function objectSpan(text: string, start: number): ObjectSpan {
|
|
45
|
+
if (text[start] !== "{") return fail();
|
|
46
|
+
const members: Member[] = []; let at = whitespace(text, start + 1);
|
|
47
|
+
while (text[at] !== "}") {
|
|
48
|
+
const keyStart = at, keyEnd = stringEnd(text, at), key: unknown = JSON.parse(text.slice(keyStart, keyEnd));
|
|
49
|
+
if (typeof key !== "string") return fail();
|
|
50
|
+
const valueStart = whitespace(text, whitespace(text, keyEnd) + 1), end = valueEnd(text, valueStart), next = whitespace(text, end);
|
|
51
|
+
const comma = text[next] === "," ? next : undefined;
|
|
52
|
+
members.push({ key, keyStart, keyEnd, valueStart, valueEnd: end, ...(comma === undefined ? {} : { comma }) });
|
|
53
|
+
at = comma === undefined ? next : whitespace(text, comma + 1);
|
|
54
|
+
}
|
|
55
|
+
return { close: at, members };
|
|
56
|
+
}
|
|
57
|
+
/** Only the owned value requires recursive key uniqueness; unrelated JSON stays opaque. */
|
|
58
|
+
function uniqueOwnedKeys(text: string, member: Member): void {
|
|
59
|
+
const objects: (Set<string> | null)[] = [];
|
|
60
|
+
let at = member.valueStart;
|
|
61
|
+
while (at < member.valueEnd) {
|
|
62
|
+
const char = text[at]!;
|
|
63
|
+
if (char === '"') {
|
|
64
|
+
const end = stringEnd(text, at), current = objects.at(-1);
|
|
65
|
+
if (text[whitespace(text, end)] === ":" && current) {
|
|
66
|
+
const key = JSON.parse(text.slice(at, end)) as string;
|
|
67
|
+
if (current.has(key)) return fail();
|
|
68
|
+
current.add(key);
|
|
69
|
+
}
|
|
70
|
+
at = end;
|
|
71
|
+
} else {
|
|
72
|
+
if (char === "{") objects.push(new Set());
|
|
73
|
+
else if (char === "[") objects.push(null);
|
|
74
|
+
else if (char === "}" || char === "]") objects.pop();
|
|
75
|
+
at++;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function document(image: ConfigImage): Document {
|
|
80
|
+
let text = "{}";
|
|
81
|
+
if (image.bytes !== null) {
|
|
82
|
+
if (image.bytes.length > Math.ceil(SETUP_CONFIG_BYTES / 3) * 4) return size();
|
|
83
|
+
const bytes = Buffer.from(image.bytes, "base64");
|
|
84
|
+
if (bytes.length > SETUP_CONFIG_BYTES) return size();
|
|
85
|
+
if (bytes.toString("base64") !== image.bytes) return fail();
|
|
86
|
+
try { text = decode.decode(bytes); } catch { return fail(); }
|
|
87
|
+
}
|
|
88
|
+
let value: unknown; try { value = JSON.parse(text); } catch { return fail(); }
|
|
89
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return fail();
|
|
90
|
+
const root = objectSpan(text, whitespace(text, 0));
|
|
91
|
+
const canonical = options.preferCanonical ? root.members.filter(member => member.key === canonicalKey) : [];
|
|
92
|
+
const containers = canonical.length ? canonical : root.members.filter(member => keys.has(member.key));
|
|
93
|
+
if (containers.length > 1) return fail();
|
|
94
|
+
const container = containers[0]; if (!container) return { text, root };
|
|
95
|
+
const servers = objectSpan(text, container.valueStart), owned = servers.members.filter(member => member.key === entryName);
|
|
96
|
+
if (owned.length > 1) return fail();
|
|
97
|
+
if (owned[0]) uniqueOwnedKeys(text, owned[0]);
|
|
98
|
+
return { text, root, container, servers, ...(owned[0] ? { owned: owned[0] } : {}) };
|
|
99
|
+
}
|
|
100
|
+
const entry = (doc: Document): unknown => doc.owned ? JSON.parse(doc.text.slice(doc.owned.valueStart, doc.owned.valueEnd)) : undefined;
|
|
101
|
+
function readMcp(image: ConfigImage): unknown { return entry(document(image)); }
|
|
102
|
+
|
|
103
|
+
function insert(object: ObjectSpan, text: string): Edit {
|
|
104
|
+
const last = object.members.at(-1);
|
|
105
|
+
const at = last?.valueEnd ?? object.close;
|
|
106
|
+
return { start: at, end: at, text: `${last ? "," : ""}${text}` };
|
|
107
|
+
}
|
|
108
|
+
function remove(object: ObjectSpan, member: Member): Edit {
|
|
109
|
+
if (member.comma !== undefined) return { start: member.keyStart, end: member.comma + 1, text: "" };
|
|
110
|
+
const previous = object.members[object.members.indexOf(member) - 1];
|
|
111
|
+
return { start: previous?.comma ?? member.keyStart, end: member.valueEnd, text: "" };
|
|
112
|
+
}
|
|
113
|
+
function publish(image: ConfigImage, doc: Document, edits: Edit[]): ConfigImage {
|
|
114
|
+
let text = doc.text;
|
|
115
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) text = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
116
|
+
if (text === doc.text) return image;
|
|
117
|
+
if (Buffer.byteLength(text) > SETUP_CONFIG_BYTES) return size();
|
|
118
|
+
const result = { bytes: Buffer.from(text).toString("base64"), mode: image.mode };
|
|
119
|
+
document(result); return result;
|
|
120
|
+
}
|
|
121
|
+
function put(image: ConfigImage, value: unknown, options: { key?: string; keepEmpty?: boolean; rawValue?: string; emptyContainer?: string } = {}): ConfigImage {
|
|
122
|
+
const doc = document(image), edits: Edit[] = [];
|
|
123
|
+
const hasOtherKey = doc.root.members.some(member => member.key !== canonicalKey && keys.has(member.key));
|
|
124
|
+
const key = preferCanonical && doc.container?.key === canonicalKey && hasOtherKey ? canonicalKey : options.key ?? canonicalKey;
|
|
125
|
+
if (!doc.container) {
|
|
126
|
+
if (value === undefined && !options.keepEmpty) return image;
|
|
127
|
+
const body = value === undefined ? options.emptyContainer ?? "{}" : `{${JSON.stringify(entryName)}:${options.rawValue ?? JSON.stringify(value)}}`;
|
|
128
|
+
edits.push(insert(doc.root, `${JSON.stringify(key)}:${body}`));
|
|
129
|
+
} else if (value === undefined && !options.keepEmpty && doc.servers!.members.every(member => member.key === entryName)) {
|
|
130
|
+
edits.push(remove(doc.root, doc.container));
|
|
131
|
+
} else {
|
|
132
|
+
if (doc.container.key !== key) edits.push({ start: doc.container.keyStart, end: doc.container.keyEnd, text: JSON.stringify(key) });
|
|
133
|
+
if (value === undefined && doc.owned) edits.push(remove(doc.servers!, doc.owned));
|
|
134
|
+
else if (value !== undefined && !isDeepStrictEqual(entry(doc), value)) {
|
|
135
|
+
const rendered = options.rawValue ?? JSON.stringify(value); if (rendered === undefined) return fail();
|
|
136
|
+
edits.push(doc.owned ? { start: doc.owned.valueStart, end: doc.owned.valueEnd, text: rendered } : insert(doc.servers!, `${JSON.stringify(entryName)}:${rendered}`));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return publish(image, doc, edits);
|
|
140
|
+
}
|
|
141
|
+
/** Canonicalize only the owned container key; all unrelated bytes remain untouched. */
|
|
142
|
+
function putMcp(image: ConfigImage, value: unknown, options?: { keepEmpty?: boolean }): ConfigImage {
|
|
143
|
+
return put(image, value, options);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Restore the owned entry (and our alias rename), preserving unrelated lexical edits. */
|
|
147
|
+
function restoreMcp(before: ConfigImage, after: ConfigImage, current: ConfigImage, options?: { ownedOnly?: boolean }): ConfigImage {
|
|
148
|
+
const original = document(before), installed = document(after), live = document(current);
|
|
149
|
+
if (!options?.ownedOnly && same(current, after)) return before;
|
|
150
|
+
if (same(current, before)) return current;
|
|
151
|
+
const previous = entry(original), expected = entry(installed), present = entry(live);
|
|
152
|
+
const previousRestored = isDeepStrictEqual(present, previous);
|
|
153
|
+
const pendingLayout = !!original.container && !!installed.container && original.container.key !== installed.container.key && live.container?.key === installed.container.key;
|
|
154
|
+
if (previousRestored && !pendingLayout) return current;
|
|
155
|
+
if (!previousRestored && !isDeepStrictEqual(present, expected)) throw Error(`setup-owned ${label} MCP entry changed; refusing to overwrite it`);
|
|
156
|
+
const restored = put(current, previous, { key: original.container?.key ?? canonicalKey, keepEmpty: !!original.container,
|
|
157
|
+
...(original.owned ? { rawValue: original.text.slice(original.owned.valueStart, original.owned.valueEnd) } : {}),
|
|
158
|
+
...(original.container && !original.servers!.members.length ? { emptyContainer: original.text.slice(original.container.valueStart, original.container.valueEnd) } : {}) });
|
|
159
|
+
return before.bytes === null && !document(restored).root.members.length ? { bytes: null, mode: current.mode } : restored;
|
|
160
|
+
}
|
|
161
|
+
return { read: readMcp, put: putMcp, restore: restoreMcp };
|
|
162
|
+
}
|
package/src/paths.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
2
|
+
import { HOSTS, type HostDefinition, type HostId, type HostScope, type HomeOverride } from "./hosts.ts";
|
|
3
|
+
import { realPath } from "./platform.ts";
|
|
4
|
+
import type { RefusalCode } from "./refusal.ts";
|
|
5
|
+
|
|
6
|
+
type Environment = Readonly<Record<string, string | undefined>>;
|
|
7
|
+
|
|
8
|
+
export interface ResolveHostPathsOptions {
|
|
9
|
+
env: Environment;
|
|
10
|
+
home: string;
|
|
11
|
+
workspaceRoot?: string;
|
|
12
|
+
hosts?: readonly HostId[];
|
|
13
|
+
/** The existing setup tools write user options by default. Project files are opt-in. */
|
|
14
|
+
scopes?: readonly HostScope[];
|
|
15
|
+
/** Older setup tools can select the literal override, without the managed-profile redirect. */
|
|
16
|
+
redirectManagedProfiles?: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface HostRedirect {
|
|
20
|
+
target: HostId;
|
|
21
|
+
from: string;
|
|
22
|
+
to: string;
|
|
23
|
+
reason: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface HostRefusal {
|
|
27
|
+
host: HostId;
|
|
28
|
+
code: RefusalCode;
|
|
29
|
+
variable?: string;
|
|
30
|
+
file?: string;
|
|
31
|
+
reason: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface HostPaths {
|
|
35
|
+
home: string;
|
|
36
|
+
paths: Partial<Record<HostId, string[]>>;
|
|
37
|
+
/** Pre-redirect paths for validating receipts from older setup versions. */
|
|
38
|
+
legacyPaths: Partial<Record<HostId, string[]>>;
|
|
39
|
+
redirects: HostRedirect[];
|
|
40
|
+
roots: Partial<Record<HostId, { current: string[]; legacy: string[] }>>;
|
|
41
|
+
refusals: HostRefusal[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function canonical(path: string): string {
|
|
45
|
+
const absolute = resolve(path);
|
|
46
|
+
try {
|
|
47
|
+
return realPath(absolute);
|
|
48
|
+
} catch {
|
|
49
|
+
const parent = dirname(absolute);
|
|
50
|
+
return parent === absolute ? absolute : join(canonical(parent), basename(absolute));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function orcaHome(root: string, kind: "claude" | "codex", orcaRoot: string): boolean {
|
|
55
|
+
const parts = relative(canonical(orcaRoot), canonical(root)).split(sep);
|
|
56
|
+
return kind === "claude"
|
|
57
|
+
? parts.length === 3 && parts[0] === "claude-profiles" && !!parts[1] && parts[2] === "home"
|
|
58
|
+
: parts.length === 3 && parts[0] === "codex-accounts" && !!parts[1] && parts[2] === "home"
|
|
59
|
+
|| parts.length === 2 && parts[0] === "codex-runtime-home" && parts[1] === "home";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function configRoot(override: HomeOverride, env: Environment, home: string): string | Omit<HostRefusal, "host"> {
|
|
63
|
+
const { directory, key, rule } = override;
|
|
64
|
+
const setting = rule === "trim-presence" ? env[key]?.trim() : env[key];
|
|
65
|
+
if (setting === undefined) return join(home, directory);
|
|
66
|
+
if (setting === "") {
|
|
67
|
+
return rule === "empty-means-set"
|
|
68
|
+
? { code: "empty-override", variable: key, reason: `${key} is set but empty; unset it or supply an absolute directory` }
|
|
69
|
+
: join(home, directory);
|
|
70
|
+
}
|
|
71
|
+
const expanded = rule === "expand-tilde" && /^~(?:[/\\]|$)/.test(setting)
|
|
72
|
+
? join(home, ...setting.slice(2).split(/[/\\]/))
|
|
73
|
+
: setting;
|
|
74
|
+
if (!isAbsolute(expanded)) {
|
|
75
|
+
return { code: "relative-override", variable: key, reason: `${key} is relative; unset it or supply an absolute directory` };
|
|
76
|
+
}
|
|
77
|
+
const given = resolve(expanded);
|
|
78
|
+
if (rule === "absolute-only") return given;
|
|
79
|
+
const withinHome = relative(resolve(env.HOME?.trim() || home), given);
|
|
80
|
+
return withinHome !== ".." && !withinHome.startsWith(".." + sep) && !isAbsolute(withinHome) ? join(home, withinHome) : given;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function openCodeRouteReason(variable: string, file: string): string {
|
|
84
|
+
return `${variable} routes OpenCode away from ${file}; unset it and resolve paths again before applying`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Resolve MCP paths, without opening configuration files. Publishers still guard the selected paths. */
|
|
88
|
+
export function resolveHostPaths(options: ResolveHostPathsOptions): HostPaths {
|
|
89
|
+
const { env, home, workspaceRoot, hosts, scopes = ["user"], redirectManagedProfiles = true } = options;
|
|
90
|
+
const paths: HostPaths["paths"] = {};
|
|
91
|
+
const legacyPaths: HostPaths["legacyPaths"] = {};
|
|
92
|
+
const redirects: HostRedirect[] = [];
|
|
93
|
+
const roots: HostPaths["roots"] = {};
|
|
94
|
+
const refusals: HostRefusal[] = [];
|
|
95
|
+
for (const target of new Set(hosts ?? (Object.keys(HOSTS) as HostId[]))) {
|
|
96
|
+
const host: HostDefinition = HOSTS[target];
|
|
97
|
+
const firstRefusal = refusals.length;
|
|
98
|
+
const current: string[] = [];
|
|
99
|
+
const legacy: string[] = [];
|
|
100
|
+
const currentRoots: string[] = [], legacyRoots: string[] = [];
|
|
101
|
+
for (const file of host.files) {
|
|
102
|
+
if (!scopes.includes(file.scope)) continue;
|
|
103
|
+
const base = file.scope === "project" ? workspaceRoot : home;
|
|
104
|
+
if (base === undefined) continue;
|
|
105
|
+
const root = file.override ? configRoot(file.override, env, base) : base;
|
|
106
|
+
if (typeof root !== "string") {
|
|
107
|
+
refusals.push({ host: target, ...root });
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const from = join(root, file.path);
|
|
111
|
+
for (const variable of file.routeVariables ?? []) {
|
|
112
|
+
if (env[variable]?.trim()) {
|
|
113
|
+
refusals.push({
|
|
114
|
+
host: target, code: "opencode-config-route", variable, file: from,
|
|
115
|
+
reason: openCodeRouteReason(variable, from),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
legacy.push(from);
|
|
120
|
+
const siblingRoot = file.defaultSiblingRoot && file.override && !env[file.override.key]?.trim()
|
|
121
|
+
? join(base, file.defaultSiblingRoot)
|
|
122
|
+
: dirname(from);
|
|
123
|
+
legacyRoots.push(siblingRoot);
|
|
124
|
+
const personal = file.personalSource;
|
|
125
|
+
if (redirectManagedProfiles && personal) {
|
|
126
|
+
const orcaRoot = env[personal.orcaHomeVariable]?.trim() || join(home, "Library", "Application Support", "orca");
|
|
127
|
+
const to = join(home, file.override?.directory ?? "", file.path);
|
|
128
|
+
if (from !== to && orcaHome(root, personal.profile, orcaRoot)) {
|
|
129
|
+
current.push(to);
|
|
130
|
+
currentRoots.push(file.defaultSiblingRoot ? join(home, file.defaultSiblingRoot) : dirname(to));
|
|
131
|
+
redirects.push({ target, from, to, reason: "Orca re-syncs this managed file from the personal source" });
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
current.push(from);
|
|
136
|
+
currentRoots.push(siblingRoot);
|
|
137
|
+
}
|
|
138
|
+
if (!current.length && refusals.length !== firstRefusal) continue;
|
|
139
|
+
paths[target] = current;
|
|
140
|
+
legacyPaths[target] = legacy;
|
|
141
|
+
roots[target] = { current: currentRoots, legacy: legacyRoots };
|
|
142
|
+
}
|
|
143
|
+
return { home, paths, legacyPaths, redirects, refusals, roots };
|
|
144
|
+
}
|
package/src/platform.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { resolve, sep } from "node:path";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
const require = createRequire(import.meta.url);
|
|
5
|
+
let processes: typeof import("node:child_process") | undefined;
|
|
6
|
+
// Path/policy-only hook parents never need a process module. Node-safe synchronous users load it on demand.
|
|
7
|
+
const childProcess = () => processes ??= require("node:child_process") as typeof import("node:child_process");
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Resolve existing paths physically. Bun folds `..` after symlinks lexically (#403), so parent segments use the
|
|
11
|
+
* system realpath. Bun versions that reject literal backslashes also use that fallback (#26, #121). It returns
|
|
12
|
+
* names as stored on disk for guardPath's name checks and refuses missing paths and dangling symlinks.
|
|
13
|
+
*/
|
|
14
|
+
export function realPath(path: string): string {
|
|
15
|
+
const hasParent = path.split(sep).includes("..");
|
|
16
|
+
let error: unknown;
|
|
17
|
+
if (!hasParent) {
|
|
18
|
+
try {
|
|
19
|
+
return realpathSync(path);
|
|
20
|
+
} catch (caught) {
|
|
21
|
+
if (!resolve(path).includes("\\")) throw caught; // a relative path can sit under a backslash directory too
|
|
22
|
+
error = caught;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// Keep the original spelling: resolve() would fold a `..` after a symlink by text. GNU realpath accepts a
|
|
26
|
+
// dangling last component unless told -e; the BSD one on macOS refuses it by default.
|
|
27
|
+
const argv = process.platform === "darwin" ? ["/bin/realpath", "--", path] : ["realpath", "-e", "--", path];
|
|
28
|
+
const r = childProcess().spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8" });
|
|
29
|
+
if (r.status !== 0 || !r.stdout.endsWith("\n")) throw error ?? new Error(`Cannot resolve existing path: ${path}`);
|
|
30
|
+
return r.stdout.slice(0, -1);
|
|
31
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { ConfigImage } from "./json.ts";
|
|
4
|
+
import { isConfigImage, readReceiptValue, type ReceiptTarget } from "./receipt.ts";
|
|
5
|
+
import { SETUP_CONFIG_BYTES } from "./toml.ts";
|
|
6
|
+
import { EntryRefusal } from "./refusal.ts";
|
|
7
|
+
|
|
8
|
+
export type LegacyReceipt =
|
|
9
|
+
| { kind: "agent-mem"; path: string; before: ConfigImage; after: ConfigImage; intent: string }
|
|
10
|
+
| { kind: "entry"; path: string; existed: boolean; keyExisted: boolean; prior: unknown; priorToml?: string; installed: unknown };
|
|
11
|
+
|
|
12
|
+
const record = (value: unknown): value is Record<string, unknown> =>
|
|
13
|
+
value !== null && typeof value === "object" && !Array.isArray(value);
|
|
14
|
+
|
|
15
|
+
function invalid(path: string, reason: string): never {
|
|
16
|
+
throw new EntryRefusal("invalid-receipt", `${path}: ${reason}; inspect the receipt or use the consumer release that wrote it`, { file: path });
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function memoryReceipt(path: string, target: ReceiptTarget, candidates: readonly string[], raw: unknown): LegacyReceipt {
|
|
20
|
+
if (!record(raw) || (raw.version !== 1 && raw.version !== 2) || raw.target !== target.host
|
|
21
|
+
|| typeof raw.intent !== "string" || !/^[a-f0-9]{64}$/.test(raw.intent) || !Array.isArray(raw.changes)) {
|
|
22
|
+
return invalid(path, "invalid or foreign agent-mem receipt");
|
|
23
|
+
}
|
|
24
|
+
if (raw.phase !== "applied") return invalid(path, "agent-mem setup is incomplete");
|
|
25
|
+
const change: unknown = raw.changes[0];
|
|
26
|
+
if (!record(change) || change.key !== `${target.host}:0` || typeof change.path !== "string"
|
|
27
|
+
|| !candidates.includes(change.path) || !isConfigImage(change.before) || !isConfigImage(change.after)
|
|
28
|
+
|| change.after.bytes === null || (change.start !== undefined && !isConfigImage(change.start))) {
|
|
29
|
+
return invalid(path, "agent-mem MCP image does not match the selected configuration");
|
|
30
|
+
}
|
|
31
|
+
return { kind: "agent-mem", path, before: change.before, after: change.after, intent: raw.intent };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function entryReceipt(path: string, target: ReceiptTarget, file: string, raw: unknown): LegacyReceipt {
|
|
35
|
+
const vault = target.name === "vmem";
|
|
36
|
+
if (!record(raw) || (vault ? raw.version !== 1 : raw.v !== 1) || raw.target !== target.host || raw.file !== file
|
|
37
|
+
|| typeof raw.existed !== "boolean" || (raw.keyExisted !== undefined && typeof raw.keyExisted !== "boolean")
|
|
38
|
+
|| !record(raw.installed) || typeof raw.installed.command !== "string" || !Array.isArray(raw.installed.args)
|
|
39
|
+
|| !raw.installed.args.every((arg: unknown) => typeof arg === "string")) {
|
|
40
|
+
return invalid(path, "invalid or foreign setup receipt");
|
|
41
|
+
}
|
|
42
|
+
if (!vault && (typeof raw.keyExisted !== "boolean" || typeof raw.priorPresent !== "boolean"
|
|
43
|
+
|| (raw.priorPresent && !Object.hasOwn(raw, "prior")))) return invalid(path, "invalid agent-research prior entry");
|
|
44
|
+
const prior = vault ? raw.prior ?? undefined : raw.priorPresent ? raw.prior : undefined;
|
|
45
|
+
let priorToml: string | undefined;
|
|
46
|
+
if (raw.priorToml !== undefined) {
|
|
47
|
+
if (vault && Array.isArray(raw.priorToml) && raw.priorToml.every((line: unknown) => typeof line === "string")) {
|
|
48
|
+
priorToml = raw.priorToml.join("\n") + "\n";
|
|
49
|
+
} else if (!vault && typeof raw.priorToml === "string") {
|
|
50
|
+
priorToml = raw.priorToml;
|
|
51
|
+
} else return invalid(path, "invalid prior TOML block");
|
|
52
|
+
if (target.host !== "codex" || prior === undefined || Buffer.byteLength(priorToml) > SETUP_CONFIG_BYTES) {
|
|
53
|
+
return invalid(path, "unexpected or oversized prior TOML block");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { kind: "entry", path, existed: raw.existed, keyExisted: raw.keyExisted === true, prior, priorToml, installed: raw.installed };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function readLegacyReceipt(directory: string, target: ReceiptTarget, legacyPaths: readonly string[] = []): LegacyReceipt | undefined {
|
|
60
|
+
const candidates = [...new Set([target.file, ...legacyPaths])];
|
|
61
|
+
if (target.name === "amem") {
|
|
62
|
+
const path = join(directory, `${target.host}.json`);
|
|
63
|
+
const { image, value } = readReceiptValue(path, 12 * SETUP_CONFIG_BYTES);
|
|
64
|
+
return image.bytes === null ? undefined : memoryReceipt(path, target, candidates, value);
|
|
65
|
+
}
|
|
66
|
+
if (target.name !== "vmem" && target.name !== "ares") return undefined;
|
|
67
|
+
|
|
68
|
+
const limit = target.name === "vmem" ? 4 * 1024 * 1024 : 8 * 1024 * 1024;
|
|
69
|
+
let found: LegacyReceipt | undefined;
|
|
70
|
+
for (const file of candidates) {
|
|
71
|
+
const hash = createHash("sha256").update(file).digest("hex").slice(0, 16);
|
|
72
|
+
const path = join(directory, `${target.host}-${hash}.json`);
|
|
73
|
+
const { image, value } = readReceiptValue(path, limit);
|
|
74
|
+
if (image.bytes === null) continue;
|
|
75
|
+
if (found) return invalid(path, `multiple setup receipts match ${target.file}`);
|
|
76
|
+
found = entryReceipt(path, target, file, value);
|
|
77
|
+
}
|
|
78
|
+
return found;
|
|
79
|
+
}
|
package/src/receipt.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
import { publishImage, readImage } from "./fs-safe.ts";
|
|
4
|
+
import type { HostId } from "./hosts.ts";
|
|
5
|
+
import type { ConfigImage } from "./json.ts";
|
|
6
|
+
import { SETUP_CONFIG_BYTES } from "./toml.ts";
|
|
7
|
+
import { EntryRefusal } from "./refusal.ts";
|
|
8
|
+
|
|
9
|
+
const BASE64_LIMIT = Math.ceil(SETUP_CONFIG_BYTES / 3) * 4;
|
|
10
|
+
// Two full configuration images plus metadata and pending-operation hashes.
|
|
11
|
+
const RECEIPT_BYTES = 2 * BASE64_LIMIT + 64 * 1024;
|
|
12
|
+
const hashPattern = /^[a-f0-9]{64}$/;
|
|
13
|
+
export const digest = (value: unknown): string =>
|
|
14
|
+
createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
15
|
+
export const imageDigest = (image: ConfigImage): string => digest([image.bytes, image.bytes === null ? null : image.mode]);
|
|
16
|
+
|
|
17
|
+
export interface ReceiptTarget {
|
|
18
|
+
host: HostId;
|
|
19
|
+
file: string;
|
|
20
|
+
name: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface Receipt extends ReceiptTarget {
|
|
24
|
+
version: 1;
|
|
25
|
+
intent: string;
|
|
26
|
+
before: ConfigImage;
|
|
27
|
+
after: ConfigImage;
|
|
28
|
+
pending?: { kind: "apply" | "undo"; start: string; result: string };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function receiptPath(directory: string, target: ReceiptTarget): string {
|
|
32
|
+
if (!isAbsolute(directory) || resolve(directory) !== directory) {
|
|
33
|
+
throw new EntryRefusal("unsafe-path", `${directory}: supply an absolute receipt directory without redirects or parent segments`, { file: directory });
|
|
34
|
+
}
|
|
35
|
+
return join(directory, `entry-${digest([target.file, target.name])}.json`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
39
|
+
value !== null && typeof value === "object" && !Array.isArray(value);
|
|
40
|
+
const isDigest = (value: unknown): value is string => typeof value === "string" && hashPattern.test(value);
|
|
41
|
+
|
|
42
|
+
export function isConfigImage(value: unknown): value is ConfigImage {
|
|
43
|
+
if (!isRecord(value) || typeof value.mode !== "number" || !Number.isInteger(value.mode)
|
|
44
|
+
|| value.mode < 0 || value.mode > 0o7777) return false;
|
|
45
|
+
if (value.bytes === null) return true;
|
|
46
|
+
if (typeof value.bytes !== "string" || value.bytes.length > BASE64_LIMIT) return false;
|
|
47
|
+
const bytes = Buffer.from(value.bytes, "base64");
|
|
48
|
+
return bytes.length <= SETUP_CONFIG_BYTES && bytes.toString("base64") === value.bytes;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function readReceiptValue(path: string, limit: number): { image: ConfigImage; value?: unknown } {
|
|
52
|
+
const image = readImage(path, limit);
|
|
53
|
+
if (image.bytes === null) return { image };
|
|
54
|
+
try {
|
|
55
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(image.bytes, "base64"));
|
|
56
|
+
return { image, value: JSON.parse(text) };
|
|
57
|
+
} catch (cause) {
|
|
58
|
+
throw new EntryRefusal("invalid-receipt", `${path}: invalid receipt JSON; inspect or restore the original receipt before retrying`, { cause, file: path });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function readReceipt(path: string, target: ReceiptTarget): { image: ConfigImage; receipt?: Receipt } {
|
|
63
|
+
const { image, value } = readReceiptValue(path, RECEIPT_BYTES);
|
|
64
|
+
if (image.bytes === null) return { image };
|
|
65
|
+
const refuse = (): never => {
|
|
66
|
+
throw new EntryRefusal("invalid-receipt", `${path}: invalid or unsupported receipt; inspect or restore the original receipt before retrying`, { file: path });
|
|
67
|
+
};
|
|
68
|
+
if (!isRecord(value) || value.version !== 1 || value.host !== target.host || value.file !== target.file
|
|
69
|
+
|| value.name !== target.name || !isDigest(value.intent) || !isConfigImage(value.before) || !isConfigImage(value.after)) return refuse();
|
|
70
|
+
const pending = value.pending;
|
|
71
|
+
if (pending !== undefined && (!isRecord(pending) || (pending.kind !== "apply" && pending.kind !== "undo")
|
|
72
|
+
|| !isDigest(pending.start) || !isDigest(pending.result)
|
|
73
|
+
|| pending.kind === "apply" && pending.result !== imageDigest(value.after))) return refuse();
|
|
74
|
+
return { image, receipt: value as unknown as Receipt };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function writeReceipt(path: string, expected: ConfigImage, receipt?: Receipt): ConfigImage {
|
|
78
|
+
const bytes = receipt ? Buffer.from(JSON.stringify(receipt)).toString("base64") : null;
|
|
79
|
+
const image = { bytes, mode: 0o600 };
|
|
80
|
+
publishImage(path, RECEIPT_BYTES, expected, image);
|
|
81
|
+
return image;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function findPackageReceipt(directory: string, target: ReceiptTarget, legacyPaths: readonly string[] = []) {
|
|
85
|
+
const path = receiptPath(directory, target);
|
|
86
|
+
const selected = readReceipt(path, target);
|
|
87
|
+
if (selected.receipt) return { path, ...selected };
|
|
88
|
+
for (const file of new Set(legacyPaths)) {
|
|
89
|
+
if (file === target.file) continue;
|
|
90
|
+
const historical = { ...target, file };
|
|
91
|
+
const legacyPath = receiptPath(directory, historical);
|
|
92
|
+
const found = readReceipt(legacyPath, historical);
|
|
93
|
+
if (found.receipt) return { path: legacyPath, ...found };
|
|
94
|
+
}
|
|
95
|
+
return { path, ...selected };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Save the previous completed v1 receipt independently of the new v1 journal.
|
|
99
|
+
// The pending hashes bind the sidecar to the operation that can roll it back.
|
|
100
|
+
export function recoveryPath(path: string, pending: NonNullable<Receipt["pending"]>): string {
|
|
101
|
+
return path + ".previous-" + digest([pending.start, pending.result]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function writeRecovery(path: string, pending: NonNullable<Receipt["pending"]>, previous: Receipt): void {
|
|
105
|
+
const backup = recoveryPath(path, pending);
|
|
106
|
+
const { image } = readReceipt(backup, previous);
|
|
107
|
+
writeReceipt(backup, image, previous);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function readRecovery(path: string, receipt: Receipt & { pending: NonNullable<Receipt["pending"]> }) {
|
|
111
|
+
const backup = recoveryPath(path, receipt.pending);
|
|
112
|
+
const saved = readReceipt(backup, receipt);
|
|
113
|
+
if (saved.receipt?.pending) {
|
|
114
|
+
throw new EntryRefusal("invalid-receipt", `${backup}: invalid recovery receipt; inspect it before retrying`, { file: backup });
|
|
115
|
+
}
|
|
116
|
+
return { path: backup, ...saved };
|
|
117
|
+
}
|