@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.
@@ -0,0 +1,33 @@
1
+ {
2
+ "commit": "05699c24953a0cd5a37721fc8255703d20a9b295",
3
+ "host": "agy",
4
+ "name": "ares",
5
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
6
+ "workspaceRoot": "$FIXTURE/workspace",
7
+ "receiptDir": "$FIXTURE/hub/research/setup",
8
+ "mode": 384,
9
+ "before": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"ares\": {\"command\":\"/fixture/prior\",\"args\":[\"mcp\"]}\n },\n \"fixture\": true\n}\n",
10
+ "after": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"ares\": {\n \"command\": \"bun\",\n \"args\": [\n \"--smol\",\n \"$FIXTURE/release/bin/ares.js\",\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
11
+ "receipt": {
12
+ "v": 1,
13
+ "target": "agy",
14
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
15
+ "existed": true,
16
+ "keyExisted": true,
17
+ "priorPresent": true,
18
+ "prior": {
19
+ "command": "/fixture/prior",
20
+ "args": [
21
+ "mcp"
22
+ ]
23
+ },
24
+ "installed": {
25
+ "command": "bun",
26
+ "args": [
27
+ "--smol",
28
+ "$FIXTURE/release/bin/ares.js",
29
+ "mcp"
30
+ ]
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "commit": "05699c24953a0cd5a37721fc8255703d20a9b295",
3
+ "host": "kimi",
4
+ "name": "ares",
5
+ "file": "$FIXTURE/.kimi-code/mcp.json",
6
+ "receiptDir": "$FIXTURE/hub/research/setup",
7
+ "mode": 384,
8
+ "before": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"ares\": {\"command\":\"/fixture/prior\",\"args\":[\"mcp\"]}\n },\n \"fixture\": true\n}\n",
9
+ "after": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"ares\": {\n \"command\": \"bun\",\n \"args\": [\n \"--smol\",\n \"$FIXTURE/release/bin/ares.js\",\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
10
+ "receipt": {
11
+ "v": 1,
12
+ "target": "kimi",
13
+ "file": "$FIXTURE/.kimi-code/mcp.json",
14
+ "existed": true,
15
+ "keyExisted": true,
16
+ "priorPresent": true,
17
+ "prior": {
18
+ "command": "/fixture/prior",
19
+ "args": [
20
+ "mcp"
21
+ ]
22
+ },
23
+ "installed": {
24
+ "command": "bun",
25
+ "args": [
26
+ "--smol",
27
+ "$FIXTURE/release/bin/ares.js",
28
+ "mcp"
29
+ ]
30
+ }
31
+ }
32
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "commit": "9b9a4a5333aaa73453858a541b82028c63f8f7f8",
3
+ "host": "agy",
4
+ "name": "vmem",
5
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
6
+ "workspaceRoot": "$FIXTURE/workspace",
7
+ "receiptDir": "$FIXTURE/vault/setup",
8
+ "mode": 384,
9
+ "before": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"vmem\": {\"command\":\"/fixture/prior\",\"args\":[\"mcp\"]}\n },\n \"fixture\": true\n}\n",
10
+ "after": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"vmem\": {\n \"command\": \"$FIXTURE/bin/bun\",\n \"args\": [\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
11
+ "receipt": {
12
+ "version": 1,
13
+ "target": "agy",
14
+ "file": "$FIXTURE/workspace/.agents/mcp_config.json",
15
+ "existed": true,
16
+ "keyExisted": true,
17
+ "prior": {
18
+ "command": "/fixture/prior",
19
+ "args": [
20
+ "mcp"
21
+ ]
22
+ },
23
+ "installed": {
24
+ "command": "$FIXTURE/bin/bun",
25
+ "args": [
26
+ "mcp"
27
+ ]
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "commit": "9b9a4a5333aaa73453858a541b82028c63f8f7f8",
3
+ "host": "kimi",
4
+ "name": "vmem",
5
+ "file": "$FIXTURE/.kimi-code/mcp.json",
6
+ "receiptDir": "$FIXTURE/vault/setup",
7
+ "mode": 384,
8
+ "before": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"vmem\": {\"command\":\"/fixture/prior\",\"args\":[\"mcp\"]}\n },\n \"fixture\": true\n}\n",
9
+ "after": "{\n \"mcpServers\": {\n \"other\": {\n \"command\": \"keep\"\n },\n \"vmem\": {\n \"command\": \"$FIXTURE/bin/bun\",\n \"args\": [\n \"mcp\"\n ]\n }\n },\n \"fixture\": true\n}\n",
10
+ "receipt": {
11
+ "version": 1,
12
+ "target": "kimi",
13
+ "file": "$FIXTURE/.kimi-code/mcp.json",
14
+ "existed": true,
15
+ "keyExisted": true,
16
+ "prior": {
17
+ "command": "/fixture/prior",
18
+ "args": [
19
+ "mcp"
20
+ ]
21
+ },
22
+ "installed": {
23
+ "command": "$FIXTURE/bin/bun",
24
+ "args": [
25
+ "mcp"
26
+ ]
27
+ }
28
+ }
29
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@staix/agent-hosts",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Host configuration and MCP server entry management for Bun",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/STAIxBWLB/agent-hosts.git"
9
+ },
10
+ "exports": "./src/index.ts",
11
+ "types": "./src/index.ts",
12
+ "files": [
13
+ "src",
14
+ "fixtures",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "engines": {
19
+ "bun": ">=1.4.4"
20
+ },
21
+ "scripts": {
22
+ "test": "bun test",
23
+ "typecheck": "tsc --noEmit"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "1.4.4",
27
+ "typescript": "5.9.3"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "license": "MIT"
33
+ }
package/src/entry.ts ADDED
@@ -0,0 +1,450 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { HOSTS, type HostFormat, type HostId } from "./hosts.ts";
5
+ import { openCodeRouteReason, type HostPaths, type ResolveHostPathsOptions } from "./paths.ts";
6
+ import { createJsonMcpCodec, type ConfigImage } from "./json.ts";
7
+ import { SETUP_CONFIG_BYTES, setTomlPath } from "./toml.ts";
8
+ import { publishImage, readImage, sameImage, withConfigLock } from "./fs-safe.ts";
9
+ import { digest, findPackageReceipt, imageDigest, readRecovery, writeReceipt, writeRecovery, type Receipt, type ReceiptTarget } from "./receipt.ts";
10
+ import { readLegacyReceipt, type LegacyReceipt } from "./receipt-legacy.ts";
11
+ import { asEntryRefusal, EntryRefusal, type RefusalCode } from "./refusal.ts";
12
+
13
+ export interface EntryTarget {
14
+ host: HostId;
15
+ paths: HostPaths;
16
+ name: string;
17
+ }
18
+
19
+ export interface PlanEntryOptions extends EntryTarget {
20
+ entry: Readonly<Record<string, unknown>> | null;
21
+ }
22
+
23
+ export interface ApplyEntryOptions {
24
+ receiptDir: string;
25
+ /** A fresh injected environment is required for OpenCode. */
26
+ env?: ResolveHostPathsOptions["env"];
27
+ }
28
+
29
+ export const UNDO_NOOP_CODES = ["no-receipt", "entry-already-absent", "entry-already-restored"] as const;
30
+ export type UndoNoopCode = typeof UNDO_NOOP_CODES[number];
31
+
32
+ type Change = "add" | "replace" | "remove" | "unchanged";
33
+ type PlannedEntry = ReceiptTarget & {
34
+ change: Change;
35
+ entry: Readonly<Record<string, unknown>> | null;
36
+ current: unknown;
37
+ legacyPaths: readonly string[];
38
+ before: ConfigImage;
39
+ after: ConfigImage;
40
+ intent: string;
41
+ /** OpenCode routing-variable names observed at preview. Values are never kept. */
42
+ opencodeRoutes?: readonly string[];
43
+ };
44
+ export type EntryPlan = PlannedEntry | { change: "refused"; code: RefusalCode; reason: string; file?: string };
45
+
46
+ export interface EntryResult {
47
+ change: Change | "restored" | "removed";
48
+ file: string;
49
+ receipt: string;
50
+ code?: UndoNoopCode;
51
+ intent?: string;
52
+ supersedes?: string;
53
+ /** A retained consumer receipt that the caller manages. */
54
+ legacy?: true;
55
+ }
56
+
57
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
58
+ const record = (value: unknown): value is Record<string, unknown> =>
59
+ value !== null && typeof value === "object" && !Array.isArray(value);
60
+ const message = (error: unknown): string => error instanceof Error ? error.message : String(error);
61
+
62
+ function target(options: EntryTarget): ReceiptTarget {
63
+ const { host, paths, name } = options;
64
+ // OpenCode routing blocks writes but leaves the global path available for undo.
65
+ const refusal = paths.refusals.find((item) => item.host === host && item.code !== "opencode-config-route");
66
+ if (refusal) throw new EntryRefusal(refusal.code, refusal.reason, { file: refusal.file });
67
+ const files = paths.paths[host];
68
+ if (!Object.hasOwn(HOSTS, host) || files?.length !== 1 || !files[0]) {
69
+ throw new EntryRefusal("invalid-target", `${host}: select exactly one supported configuration path before planning or undoing an entry`);
70
+ }
71
+ if (!name || /[\p{Cc}\p{Cf}]/u.test(name) || Buffer.byteLength(name) > 256) {
72
+ throw new EntryRefusal("invalid-entry", `${files[0]}: provide a nonempty entry name of up to 256 bytes without control characters`, { file: files[0] });
73
+ }
74
+ return { host, file: files[0], name };
75
+ }
76
+
77
+ function configCodec({ host, file, name }: ReceiptTarget, legacy = false) {
78
+ const format: HostFormat = HOSTS[host].format;
79
+ if (format.kind === "json") {
80
+ return createJsonMcpCodec({
81
+ canonicalKey: format.key, aliases: format.aliases, entryName: name, label: file, preferCanonical: legacy && host === "jcode",
82
+ });
83
+ }
84
+ const tablePath = format.table;
85
+ const path = [...tablePath, name];
86
+ const text = (image: ConfigImage) => image.bytes === null ? "" : decoder.decode(Buffer.from(image.bytes, "base64"));
87
+ function read(image: ConfigImage): unknown {
88
+ let value: unknown = Bun.TOML.parse(text(image));
89
+ for (const part of path) {
90
+ if (!record(value)) throw new Error("expected an unambiguous TOML table");
91
+ if (!Object.hasOwn(value, part)) return undefined;
92
+ value = value[part];
93
+ }
94
+ return value;
95
+ }
96
+ function put(image: ConfigImage, value: unknown, options?: { keepEmpty?: boolean }): ConfigImage {
97
+ const input = text(image);
98
+ let output = setTomlPath(input, path, value, { refuseInlineParent: true });
99
+ if (value === undefined && options?.keepEmpty === false) {
100
+ const doc = Bun.TOML.parse(output) as Record<string, unknown>;
101
+ const parent = doc[tablePath[0]!];
102
+ if (record(parent) && !Object.keys(parent).length) output = setTomlPath(output, tablePath, undefined);
103
+ }
104
+ return output === input ? image : { bytes: Buffer.from(output).toString("base64"), mode: image.mode };
105
+ }
106
+ function restore(before: ConfigImage, _after: ConfigImage, current: ConfigImage, _options?: { ownedOnly?: boolean }): ConfigImage {
107
+ const prior = Bun.TOML.parse(text(before)) as Record<string, unknown>;
108
+ const restored = put(current, read(before), { keepEmpty: Object.hasOwn(prior, tablePath[0]!) });
109
+ return before.bytes === null && text(restored).trim() === "" ? { bytes: null, mode: current.mode } : restored;
110
+ }
111
+ return { read, put, restore };
112
+ }
113
+
114
+ function editConfig<T>(file: string, work: () => T): T {
115
+ try {
116
+ return work();
117
+ } catch (error) {
118
+ const code = error instanceof EntryRefusal ? error.code : "invalid-configuration";
119
+ throw new EntryRefusal(code, `${file}: ${message(error)}; inspect the configuration syntax and the managed entry before retrying`, { cause: error, file });
120
+ }
121
+ }
122
+
123
+ function assertHostEdit(selection: ReceiptTarget, entry: PlanEntryOptions["entry"], opencodeRoutes: readonly string[] | undefined): void {
124
+ const { host, file } = selection;
125
+ if (host === "opencode") {
126
+ const variable = opencodeRoutes?.[0];
127
+ if (variable) throw new EntryRefusal("opencode-config-route", openCodeRouteReason(variable, file));
128
+ for (const sibling of HOSTS.opencode.files[0].mergedFiles) {
129
+ const other = join(dirname(file), sibling);
130
+ if (lstatSync(other, { throwIfNoEntry: false })) {
131
+ throw new EntryRefusal(
132
+ "opencode-merged-config",
133
+ `${other} is merged with ${file}; consolidate the configuration into opencode.json before applying`,
134
+ );
135
+ }
136
+ }
137
+ }
138
+ if (host === "jcode" && entry !== null) {
139
+ const args: readonly unknown[] = Array.isArray(entry.args) ? entry.args : [];
140
+ const interpolates = (value: unknown) => typeof value === "string" && value.includes("${");
141
+ if (interpolates(entry.command) || args.some(interpolates)) {
142
+ throw new EntryRefusal("jcode-interpolation", `${file}: Jcode interpolates \${ in a command or argument; remove the placeholder before applying`);
143
+ }
144
+ }
145
+ }
146
+
147
+ function makePlan(
148
+ selection: ReceiptTarget,
149
+ requested: PlanEntryOptions["entry"],
150
+ before: ConfigImage,
151
+ opencodeRoutes?: readonly string[],
152
+ legacyPaths: readonly string[] = [],
153
+ ): PlannedEntry {
154
+ assertHostEdit(selection, requested, opencodeRoutes);
155
+ return editConfig(selection.file, () => {
156
+ const encoded = JSON.stringify(requested);
157
+ if (encoded === undefined) throw new EntryRefusal("invalid-entry", "provide a plain JSON-compatible entry object");
158
+ if (Buffer.byteLength(encoded) > SETUP_CONFIG_BYTES) throw new EntryRefusal("size-limit", "reduce the entry to at most 8 MiB");
159
+ const entry: unknown = JSON.parse(encoded);
160
+ if ((entry !== null && !record(entry)) || !isDeepStrictEqual(entry, requested)) throw new EntryRefusal("invalid-entry", "provide a plain JSON-compatible entry object");
161
+ const codec = configCodec(selection);
162
+ const current = codec.read(before);
163
+ const desired = entry === null ? undefined : entry;
164
+ const after = entry === null && current === undefined ? before : codec.put(before, desired);
165
+ if (!isDeepStrictEqual(codec.read(after), desired)) throw new EntryRefusal("invalid-entry", "codec did not produce the requested entry");
166
+ const intent = digest([selection.host, selection.file, selection.name, entry]);
167
+ return { ...selection, entry, change: sameImage(before, after) ? "unchanged" : entry === null ? "remove" : current === undefined ? "add" : "replace",
168
+ before, after, current, intent, legacyPaths, ...(opencodeRoutes ? { opencodeRoutes } : {}) };
169
+ });
170
+ }
171
+
172
+ export function planEntry(options: PlanEntryOptions): EntryPlan {
173
+ let file: string | undefined;
174
+ try {
175
+ const selection = target(options);
176
+ file = selection.file;
177
+ const routes = selection.host === "opencode"
178
+ ? options.paths.refusals.flatMap((item) => item.host === "opencode" && item.code === "opencode-config-route" && item.variable ? [item.variable] : [])
179
+ : undefined;
180
+ return makePlan(selection, options.entry, readImage(selection.file, SETUP_CONFIG_BYTES), routes, [...options.paths.legacyPaths[selection.host] ?? []]);
181
+ } catch (error) {
182
+ const refusal = asEntryRefusal(error, file ?? options.host, file);
183
+ return { change: "refused", code: refusal.code, reason: refusal.reason, ...(refusal.file ? { file: refusal.file } : {}) };
184
+ }
185
+ }
186
+
187
+ function result(selection: ReceiptTarget, receipt: string, change: EntryResult["change"], intent?: string): EntryResult {
188
+ return { file: selection.file, receipt, change, ...(intent ? { intent } : {}) };
189
+ }
190
+
191
+ function assertInstalled(current: unknown, installed: unknown): void {
192
+ if (!isDeepStrictEqual(current, installed)) {
193
+ throw new EntryRefusal("managed-entry-changed", "managed entry changed since installation; restore the installed entry or resolve the conflict manually");
194
+ }
195
+ }
196
+
197
+ function restoreOwned(receipt: Receipt, current: ConfigImage, file: string): ConfigImage {
198
+ return editConfig(file, () => {
199
+ const codec = configCodec({ ...receipt, file });
200
+ assertInstalled(codec.read(current), codec.read(receipt.after));
201
+ const restored = current.bytes === receipt.after.bytes
202
+ ? receipt.before
203
+ : codec.restore(receipt.before, receipt.after, current);
204
+ return { bytes: restored.bytes, mode: current.mode };
205
+ });
206
+ }
207
+
208
+ function assertPending(receipt: Receipt, current: ConfigImage): "start" | "result" {
209
+ const active = receipt.pending!;
210
+ const actual = imageDigest(current);
211
+ if (actual === active.result) return "result";
212
+ if (actual === active.start) return "start";
213
+ throw new EntryRefusal("pending-operation", `${receipt.file}: configuration changed during an interrupted ${active.kind}; inspect the configuration and receipt before retrying`);
214
+ }
215
+
216
+ export function applyEntry(plan: EntryPlan, options: ApplyEntryOptions): EntryResult {
217
+ if (plan.change === "refused") throw new EntryRefusal(plan.code, plan.reason, { file: plan.file });
218
+ return withRefusals(plan.file, () => applyPlan(plan, options), plan.file);
219
+ }
220
+
221
+ function applyPlan(plan: PlannedEntry, { receiptDir, env }: ApplyEntryOptions): EntryResult {
222
+ if (!Object.hasOwn(HOSTS, plan.host)) throw new EntryRefusal("invalid-target", `${plan.host}: select a supported host and replan`);
223
+ const selection = { host: plan.host, file: plan.file, name: plan.name };
224
+ return withConfigLock(plan.file, () => {
225
+ const current = readImage(plan.file, SETUP_CONFIG_BYTES);
226
+ const { path, image, receipt } = findPackageReceipt(receiptDir, selection, plan.legacyPaths);
227
+ let routes: readonly string[] | undefined;
228
+ if (plan.host === "opencode") {
229
+ if (!env) throw new EntryRefusal("opencode-environment-required", `${plan.file}: supply a fresh OpenCode environment in applyEntry options`);
230
+ if (!Array.isArray(plan.opencodeRoutes)) {
231
+ throw new EntryRefusal("invalid-plan", `${plan.file}: OpenCode routing snapshot is missing; generate a fresh plan`);
232
+ }
233
+ const updated = HOSTS.opencode.files[0].routeVariables.filter((variable) => env[variable]?.trim());
234
+ routes = [...plan.opencodeRoutes, ...updated];
235
+ }
236
+ const next = makePlan(selection, plan.entry, current, routes);
237
+ if (next.intent !== plan.intent) throw new EntryRefusal("invalid-plan", `${plan.file}: plan intent changed; generate a fresh plan`);
238
+ if (receipt?.pending) {
239
+ if (receipt.pending.kind !== "apply" || receipt.intent !== plan.intent) {
240
+ throw new EntryRefusal("pending-operation", `${path}: another write is pending; retry the interrupted operation first`, { file: path });
241
+ }
242
+ const backup = readRecovery(path, { ...receipt, pending: receipt.pending });
243
+ if (assertPending(receipt, current) === "start") {
244
+ if (!sameImage(next.after, receipt.after)) throw new EntryRefusal("pending-operation", `${path}: pending image changed; inspect the receipt before retrying`);
245
+ publishImage(plan.file, SETUP_CONFIG_BYTES, current, next.after);
246
+ }
247
+ const legacy = !backup.receipt ? readLegacyReceipt(receiptDir, selection, plan.legacyPaths) : undefined;
248
+ const { pending, ...completed } = receipt;
249
+ writeReceipt(path, image, completed);
250
+ if (backup.receipt) writeReceipt(backup.path, backup.image);
251
+ return appliedResult(selection, path, next.change, receipt.intent, legacy);
252
+ }
253
+ if (receipt && receipt.intent === plan.intent && next.change === "unchanged") {
254
+ return result(selection, path, "unchanged", receipt.intent);
255
+ }
256
+ if (!sameImage(current, plan.before) || !sameImage(next.after, plan.after)) {
257
+ throw new EntryRefusal("changed-since-preview", `${plan.file}: configuration changed since preview; generate a fresh plan`);
258
+ }
259
+
260
+ const legacy = receipt ? undefined : readLegacyReceipt(receiptDir, selection, plan.legacyPaths);
261
+ const baseline = receipt ? restoreOwned(receipt, current, plan.file) : legacy ? legacyBaseline(selection, legacy, current) : current;
262
+ if (next.change === "unchanged" && !legacy) return result(selection, path, "unchanged", next.intent);
263
+ const completed: Receipt = {
264
+ version: 1, ...selection, file: receipt?.file ?? selection.file, intent: next.intent, before: baseline, after: next.after,
265
+ };
266
+ if (next.change === "unchanged") {
267
+ writeReceipt(path, image, completed);
268
+ return appliedResult(selection, path, "unchanged", next.intent, legacy);
269
+ }
270
+ const pending = { kind: "apply", start: imageDigest(current), result: imageDigest(next.after) } as const;
271
+ if (receipt) {
272
+ writeRecovery(path, pending, receipt);
273
+ } else {
274
+ // A crash after finalizing an older write can leave its sidecar behind.
275
+ // A fresh install must never inherit that backup.
276
+ const stale = readRecovery(path, { ...completed, pending });
277
+ if (stale.receipt) writeReceipt(stale.path, stale.image);
278
+ }
279
+ const journal = writeReceipt(path, image, { ...completed, pending });
280
+ publishImage(plan.file, SETUP_CONFIG_BYTES, current, next.after);
281
+ writeReceipt(path, journal, completed);
282
+ if (receipt) {
283
+ const backup = readRecovery(path, { ...completed, pending });
284
+ if (backup.receipt) writeReceipt(backup.path, backup.image);
285
+ }
286
+ return appliedResult(selection, path, next.change, next.intent, legacy);
287
+ });
288
+ }
289
+
290
+ function appliedResult(selection: ReceiptTarget, path: string, change: Change, intent: string, legacy?: LegacyReceipt): EntryResult {
291
+ return { ...result(selection, path, change, intent), ...(legacy ? { legacy: true, supersedes: legacy.path } : {}) };
292
+ }
293
+
294
+ export function undoEntry(options: EntryTarget & { receiptDir: string }): EntryResult {
295
+ const file = options.paths.paths[options.host]?.[0];
296
+ return withRefusals(file ?? options.host, () => undoTarget(options), file);
297
+ }
298
+
299
+ function withRefusals<T>(context: string, operation: () => T, file?: string): T {
300
+ try {
301
+ return operation();
302
+ } catch (error) {
303
+ throw asEntryRefusal(error, context, file);
304
+ }
305
+ }
306
+
307
+ function undoTarget(options: EntryTarget & { receiptDir: string }): EntryResult {
308
+ const selection = target(options);
309
+ const { file } = selection;
310
+ const legacyPaths = options.paths.legacyPaths[selection.host];
311
+ const { receiptDir } = options;
312
+ const first = findPackageReceipt(receiptDir, selection, legacyPaths);
313
+ const noReceipt = { ...result(selection, first.path, "unchanged"), code: "no-receipt" } as const;
314
+ if (!first.receipt && !readLegacyReceipt(receiptDir, selection, legacyPaths)) return noReceipt;
315
+ return withConfigLock(file, () => {
316
+ let { path, image, receipt } = findPackageReceipt(receiptDir, selection, legacyPaths);
317
+ if (!receipt) {
318
+ const legacy = readLegacyReceipt(receiptDir, selection, legacyPaths);
319
+ return legacy ? undoLegacy(selection, legacy) : noReceipt;
320
+ }
321
+ const current = readImage(file, SETUP_CONFIG_BYTES);
322
+ if (receipt.pending?.kind === "apply") {
323
+ if (imageDigest(current) !== receipt.pending.start) {
324
+ throw new EntryRefusal("pending-operation", `${path}: an apply is pending; retry the interrupted apply before undoing`, { file: path });
325
+ }
326
+ const backup = readRecovery(path, { ...receipt, pending: receipt.pending });
327
+ image = writeReceipt(path, image, backup.receipt);
328
+ receipt = backup.receipt;
329
+ if (receipt) writeReceipt(backup.path, backup.image);
330
+ if (!receipt) {
331
+ const legacy = readLegacyReceipt(receiptDir, selection, legacyPaths);
332
+ return legacy ? undoLegacy(selection, legacy) : noReceipt;
333
+ }
334
+ }
335
+ const codec = configCodec(selection);
336
+ const change = editConfig(file, () => codec.read(receipt.before) === undefined ? "removed" : "restored");
337
+ if (receipt.pending && assertPending(receipt, current) === "result") {
338
+ writeReceipt(path, image);
339
+ return result(selection, path, change, receipt.intent);
340
+ }
341
+ const missing = editConfig(file, () => codec.read(current) === undefined && codec.read(receipt.after) !== undefined);
342
+ if (missing) {
343
+ writeReceipt(path, image);
344
+ return { ...result(selection, path, "unchanged", receipt.intent), code: "entry-already-absent" };
345
+ }
346
+ const restored = restoreOwned(receipt, current, file);
347
+ const pending = { kind: "undo", start: imageDigest(current), result: imageDigest(restored) } as const;
348
+ if (receipt.pending && receipt.pending.result !== pending.result) {
349
+ throw new EntryRefusal("pending-operation", `${path}: pending undo changed; inspect the receipt before retrying`);
350
+ }
351
+ const journal = receipt.pending ? image : writeReceipt(path, image, { ...receipt, pending });
352
+ publishImage(file, SETUP_CONFIG_BYTES, current, restored);
353
+ writeReceipt(path, journal);
354
+ return result(selection, path, change, receipt.intent);
355
+ });
356
+ }
357
+
358
+ function legacyPrior(legacy: Extract<LegacyReceipt, { kind: "entry" }>, codec: ReturnType<typeof configCodec>, mode: number): unknown {
359
+ if (legacy.priorToml === undefined) return legacy.prior;
360
+ const prior = codec.read({ bytes: Buffer.from(legacy.priorToml).toString("base64"), mode });
361
+ if (prior === undefined) throw new EntryRefusal("invalid-receipt", "prior TOML block has no managed entry");
362
+ return prior;
363
+ }
364
+
365
+ function legacyBaseline(selection: ReceiptTarget, legacy: LegacyReceipt, current: ConfigImage): ConfigImage {
366
+ return editConfig(selection.file, () => {
367
+ const codec = configCodec(selection, true);
368
+ const live = codec.read(current);
369
+ if (legacy.kind === "agent-mem") {
370
+ const installed = codec.read(legacy.after);
371
+ if (!record(installed)) throw new EntryRefusal("invalid-receipt", "legacy receipt has no installed MCP entry");
372
+ if (live === undefined || isDeepStrictEqual(live, codec.read(legacy.before))) return current;
373
+ assertInstalled(live, installed);
374
+ const restored = codec.restore(legacy.before, legacy.after, current, { ownedOnly: true });
375
+ return { bytes: restored.bytes, mode: current.mode };
376
+ }
377
+ const prior = legacyPrior(legacy, codec, current.mode);
378
+ if (live === undefined || isDeepStrictEqual(live, prior)) return current;
379
+ assertInstalled(live, legacy.installed);
380
+ const restored = codec.put(current, prior, { keepEmpty: legacy.keyExisted });
381
+ if (!legacy.existed && restored.bytes !== null) {
382
+ const text = decoder.decode(Buffer.from(restored.bytes, "base64"));
383
+ const empty = HOSTS[selection.host].format.kind === "toml" ? text.trim() === "" : /^\s*\{\s*\}\s*$/.test(text);
384
+ if (empty) return { bytes: null, mode: current.mode };
385
+ }
386
+ return restored;
387
+ });
388
+ }
389
+
390
+ export interface EntryReceipt {
391
+ file: string;
392
+ receipt: string;
393
+ intent: string;
394
+ before: ConfigImage;
395
+ after: ConfigImage;
396
+ pending?: Receipt["pending"];
397
+ legacy?: true;
398
+ }
399
+
400
+ function legacyView(selection: ReceiptTarget, legacy: LegacyReceipt): EntryReceipt {
401
+ const { file } = selection;
402
+ if (legacy.kind === "agent-mem") {
403
+ return { file, receipt: legacy.path, intent: legacy.intent, before: legacy.before, after: legacy.after, legacy: true };
404
+ }
405
+ const empty = { bytes: null, mode: 0o600 };
406
+ const codec = configCodec(selection, true);
407
+ return editConfig(file, () => {
408
+ const prior = legacyPrior(legacy, codec, empty.mode);
409
+ const format = HOSTS[selection.host].format;
410
+ const initialText = format.kind === "json" ? "{}" : legacy.keyExisted ? `[${format.table.join(".")}]\n` : "";
411
+ const initial = legacy.existed ? { ...empty, bytes: Buffer.from(initialText).toString("base64") } : empty;
412
+ const before = codec.put(initial, prior, { keepEmpty: legacy.keyExisted });
413
+ return {
414
+ file, receipt: legacy.path, intent: digest([selection.host, file, selection.name, legacy.installed]),
415
+ before, after: codec.put(before, legacy.installed), legacy: true,
416
+ };
417
+ });
418
+ }
419
+
420
+ export function readEntryReceipt(options: EntryTarget & { receiptDir: string }): EntryReceipt | undefined {
421
+ const file = options.paths.paths[options.host]?.[0];
422
+ return withRefusals(file ?? options.host, () => {
423
+ const selection = target(options);
424
+ const legacyPaths = options.paths.legacyPaths[options.host];
425
+ const { path, receipt } = findPackageReceipt(options.receiptDir, selection, legacyPaths);
426
+ if (receipt) {
427
+ const { file, intent, before, after, pending } = receipt;
428
+ return { file, receipt: path, intent, before, after, ...(pending ? { pending } : {}) };
429
+ }
430
+ const legacy = readLegacyReceipt(options.receiptDir, selection, legacyPaths);
431
+ return legacy ? legacyView(selection, legacy) : undefined;
432
+ }, file);
433
+ }
434
+
435
+ function undoLegacy(selection: ReceiptTarget, legacy: LegacyReceipt): EntryResult {
436
+ const { file } = selection;
437
+ const current = readImage(file, SETUP_CONFIG_BYTES);
438
+ const view = legacyView(selection, legacy);
439
+ const { live, prior } = editConfig(file, () => {
440
+ const codec = configCodec(selection, true);
441
+ return { live: codec.read(current), prior: codec.read(view.before) };
442
+ });
443
+ if (live === undefined || isDeepStrictEqual(live, prior)) {
444
+ const code = live === undefined ? "entry-already-absent" : "entry-already-restored";
445
+ return { ...result(selection, legacy.path, "unchanged", view.intent), code, legacy: true };
446
+ }
447
+ const restored = legacyBaseline(selection, legacy, current);
448
+ publishImage(file, SETUP_CONFIG_BYTES, current, restored);
449
+ return { ...result(selection, legacy.path, prior === undefined ? "removed" : "restored", view.intent), legacy: true };
450
+ }