@staix/agent-hosts 0.0.0-stage → 0.2.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/src/fs-safe.ts ADDED
@@ -0,0 +1,150 @@
1
+ import {
2
+ closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync,
3
+ openSync, readSync, renameSync, unlinkSync, writeFileSync, type Stats,
4
+ } from "node:fs";
5
+ import { randomUUID } from "node:crypto";
6
+ import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
7
+ import type { ConfigImage } from "./json.ts";
8
+ import { realPath } from "./platform.ts";
9
+ import { EntryRefusal } from "./refusal.ts";
10
+
11
+ const missing = (error: unknown): boolean => (error as NodeJS.ErrnoException)?.code === "ENOENT";
12
+ const sameNode = (left: Stats, right: Stats): boolean => left.dev === right.dev && left.ino === right.ino;
13
+ export const sameImage = (left: ConfigImage, right: ConfigImage): boolean =>
14
+ left.bytes === right.bytes && left.mode === right.mode;
15
+
16
+ function checkPath(file: string, directory = false): Stats | undefined {
17
+ if (!isAbsolute(file) || resolve(file) !== file) {
18
+ throw new EntryRefusal("unsafe-path", `${file}: supply an absolute path without redirects or parent segments`, { file: file });
19
+ }
20
+ const root = parse(file).root;
21
+ let path = root;
22
+ const parts = file.slice(root.length).split(sep).filter(Boolean);
23
+ let stat: Stats | undefined;
24
+ let existing = root;
25
+ for (const [index, part] of parts.entries()) {
26
+ path = join(path, part);
27
+ try {
28
+ stat = lstatSync(path);
29
+ } catch (error) {
30
+ if (missing(error)) {
31
+ assertPhysical(file, existing);
32
+ return undefined;
33
+ }
34
+ throw error;
35
+ }
36
+ const needsDirectory = directory || index < parts.length - 1;
37
+ if (stat.isSymbolicLink() || (needsDirectory ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1)) {
38
+ throw new EntryRefusal("unsafe-path", `${file}: unsafe path component ${path}; use a plain file and directories without links`, { file: file });
39
+ }
40
+ existing = path;
41
+ }
42
+ assertPhysical(file, existing);
43
+ return stat;
44
+ }
45
+
46
+ function assertPhysical(file: string, existing: string): void {
47
+ if (realPath(existing) !== existing) {
48
+ throw new EntryRefusal("unsafe-path", `${file}: redirected path; use the exact physical path spelling`, { file: file });
49
+ }
50
+ }
51
+
52
+ function ensureDirectory(directory: string): void {
53
+ checkPath(directory, true);
54
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
55
+ checkPath(directory, true);
56
+ }
57
+
58
+ export function readImage(file: string, limit: number): ConfigImage {
59
+ const absent = { bytes: null, mode: 0o600 };
60
+ const named = checkPath(file);
61
+ if (!named) return absent;
62
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
63
+ try {
64
+ const stat = fstatSync(fd);
65
+ if (!stat.isFile() || stat.nlink !== 1 || !sameNode(named, stat)) {
66
+ throw new EntryRefusal("file-changed", `${file}: path changed while opening; check the file and retry`, { file: file });
67
+ }
68
+ if (stat.size > limit) throw new EntryRefusal("size-limit", `${file}: exceeds ${limit} bytes; reduce the file size before retrying`, { file: file });
69
+ // Read one extra byte to detect growth, with a fixed upper bound even for a changing file.
70
+ const buffer = Buffer.alloc(stat.size + 1);
71
+ let length = 0;
72
+ while (length < buffer.length) {
73
+ const count = readSync(fd, buffer, length, buffer.length - length, length);
74
+ if (!count) break;
75
+ length += count;
76
+ }
77
+ const end = fstatSync(fd);
78
+ if (length !== stat.size || end.size !== stat.size || end.mtimeMs !== stat.mtimeMs || end.ctimeMs !== stat.ctimeMs) {
79
+ throw new EntryRefusal("file-changed", `${file}: changed while reading; rerun after the writer finishes`, { file: file });
80
+ }
81
+ const current = checkPath(file);
82
+ if (!current || !sameNode(current, end)) throw new EntryRefusal("file-changed", `${file}: path changed while reading; check the file and retry`, { file: file });
83
+ return { bytes: buffer.subarray(0, length).toString("base64"), mode: stat.mode & 0o7777 };
84
+ } finally {
85
+ closeSync(fd);
86
+ }
87
+ }
88
+
89
+ function verifyImage(file: string, limit: number, expected: ConfigImage): void {
90
+ if (!sameImage(readImage(file, limit), expected)) {
91
+ throw new EntryRefusal("file-changed", `${file}: changed before publication; rerun the operation using the current file`, { file: file });
92
+ }
93
+ }
94
+
95
+ export function publishImage(file: string, limit: number, expected: ConfigImage, next: ConfigImage): void {
96
+ verifyImage(file, limit, expected);
97
+ if (sameImage(expected, next)) return;
98
+ if (next.bytes === null) {
99
+ unlinkSync(file);
100
+ return;
101
+ }
102
+ const bytes = Buffer.from(next.bytes, "base64");
103
+ if (bytes.length > limit) throw new EntryRefusal("size-limit", `${file}: output exceeds ${limit} bytes; reduce the entry size before retrying`, { file: file });
104
+ const directory = dirname(file);
105
+ ensureDirectory(directory);
106
+ const parent = lstatSync(directory);
107
+ const temporary = join(directory, `.agent-hosts-${randomUUID()}.tmp`);
108
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
109
+ try {
110
+ writeFileSync(fd, bytes);
111
+ fchmodSync(fd, next.mode);
112
+ fsyncSync(fd);
113
+ verifyImage(file, limit, expected);
114
+ const named = checkPath(temporary);
115
+ if (!named || !sameNode(named, fstatSync(fd)) || !sameNode(parent, lstatSync(directory))) {
116
+ throw new EntryRefusal("file-changed", `${file}: directory or temporary file changed; check the path and retry`, { file: file });
117
+ }
118
+ renameSync(temporary, file);
119
+ } finally {
120
+ try {
121
+ const named = checkPath(temporary);
122
+ if (named && sameNode(named, fstatSync(fd))) unlinkSync(temporary);
123
+ } finally {
124
+ closeSync(fd);
125
+ }
126
+ }
127
+ }
128
+
129
+ export function withConfigLock<T>(file: string, work: () => T): T {
130
+ checkPath(file);
131
+ ensureDirectory(dirname(file));
132
+ const lock = file + ".agent-hosts.lock";
133
+ let fd: number;
134
+ try {
135
+ fd = openSync(lock, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
136
+ } catch (error) {
137
+ if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") throw error;
138
+ throw new EntryRefusal("lock-held", `${lock}: another apply or undo holds this lock; wait for it, or remove the lock manually after confirming the writer has stopped`, { file: lock });
139
+ }
140
+ try {
141
+ return work();
142
+ } finally {
143
+ try {
144
+ const named = checkPath(lock);
145
+ if (named && sameNode(named, fstatSync(fd))) unlinkSync(lock);
146
+ } finally {
147
+ closeSync(fd);
148
+ }
149
+ }
150
+ }
package/src/hosts.ts ADDED
@@ -0,0 +1,121 @@
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", "0.172.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", "1.6.1"],
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", "0.27.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", "1.0.3"],
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", "1.19.5"],
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", "0.67.0"],
111
+ },
112
+ agy: {
113
+ id: "agy",
114
+ files: [{ scope: "project", path: ".agents/mcp_config.json" }],
115
+ format: mcpServers,
116
+ entry: stdio,
117
+ verified: ["1.5.18"],
118
+ },
119
+ } as const satisfies Record<string, HostDefinition>;
120
+
121
+ 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
+ }
@@ -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
+ }