@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/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
+ }
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
+ }