@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,82 @@
1
+ import { createHash } from "node:crypto";
2
+ import { dirname, join } from "node:path";
3
+ import type { ConfigImage } from "./json.ts";
4
+ import { digest, isConfigImage, readReceiptValue, type ReceiptTarget } from "./receipt.ts";
5
+ import { SETUP_CONFIG_BYTES } from "./toml.ts";
6
+ import { EntryRefusal } from "./refusal.ts";
7
+
8
+ export type LegacyReceipt =
9
+ | { kind: "agent-mem"; path: string; before: ConfigImage; after: ConfigImage; intent: string }
10
+ | { kind: "entry"; path: string; existed: boolean; keyExisted: boolean; prior: unknown; priorToml?: string; installed: unknown };
11
+
12
+ const record = (value: unknown): value is Record<string, unknown> =>
13
+ value !== null && typeof value === "object" && !Array.isArray(value);
14
+
15
+ function invalid(path: string, reason: string): never {
16
+ throw new EntryRefusal("invalid-receipt", `${path}: ${reason}; inspect the receipt or use the consumer release that wrote it`, { file: path });
17
+ }
18
+
19
+ function memoryReceipt(path: string, target: ReceiptTarget, candidates: readonly string[], raw: unknown): LegacyReceipt {
20
+ if (!record(raw) || (raw.version !== 1 && raw.version !== 2) || raw.target !== target.host
21
+ || typeof raw.intent !== "string" || !/^[a-f0-9]{64}$/.test(raw.intent) || !Array.isArray(raw.changes)) {
22
+ return invalid(path, "invalid or foreign agent-mem receipt");
23
+ }
24
+ if (raw.phase !== "applied") return invalid(path, "agent-mem setup is incomplete");
25
+ const change: unknown = raw.changes[0];
26
+ if (!record(change) || change.key !== `${target.host}:0` || typeof change.path !== "string"
27
+ || !candidates.includes(change.path) || !isConfigImage(change.before) || !isConfigImage(change.after)
28
+ || change.after.bytes === null || (change.start !== undefined && !isConfigImage(change.start))) {
29
+ return invalid(path, "agent-mem MCP image does not match the selected configuration");
30
+ }
31
+ return { kind: "agent-mem", path, before: change.before, after: change.after, intent: raw.intent };
32
+ }
33
+
34
+ function entryReceipt(path: string, target: ReceiptTarget, file: string, raw: unknown): LegacyReceipt {
35
+ const vault = target.name === "vmem";
36
+ if (!record(raw) || (vault ? raw.version !== 1 : raw.v !== 1) || raw.target !== target.host || raw.file !== file
37
+ || typeof raw.existed !== "boolean" || (raw.keyExisted !== undefined && typeof raw.keyExisted !== "boolean")
38
+ || !record(raw.installed) || typeof raw.installed.command !== "string" || !Array.isArray(raw.installed.args)
39
+ || !raw.installed.args.every((arg: unknown) => typeof arg === "string")) {
40
+ return invalid(path, "invalid or foreign setup receipt");
41
+ }
42
+ if (!vault && (typeof raw.keyExisted !== "boolean" || typeof raw.priorPresent !== "boolean"
43
+ || (raw.priorPresent && !Object.hasOwn(raw, "prior")))) return invalid(path, "invalid agent-research prior entry");
44
+ const prior = vault ? raw.prior ?? undefined : raw.priorPresent ? raw.prior : undefined;
45
+ let priorToml: string | undefined;
46
+ if (raw.priorToml !== undefined) {
47
+ if (vault && Array.isArray(raw.priorToml) && raw.priorToml.every((line: unknown) => typeof line === "string")) {
48
+ priorToml = raw.priorToml.join("\n") + "\n";
49
+ } else if (!vault && typeof raw.priorToml === "string") {
50
+ priorToml = raw.priorToml;
51
+ } else return invalid(path, "invalid prior TOML block");
52
+ if (target.host !== "codex" || prior === undefined || Buffer.byteLength(priorToml) > SETUP_CONFIG_BYTES) {
53
+ return invalid(path, "unexpected or oversized prior TOML block");
54
+ }
55
+ }
56
+ return { kind: "entry", path, existed: raw.existed, keyExisted: raw.keyExisted === true, prior, priorToml, installed: raw.installed };
57
+ }
58
+
59
+ export function readLegacyReceipt(directory: string, target: ReceiptTarget, legacyPaths: readonly string[] = []): LegacyReceipt | undefined {
60
+ const candidates = [...new Set([target.file, ...legacyPaths])];
61
+ if (target.name === "amem") {
62
+ // Agent-mem keys its direct agy journal by the Git workspace root.
63
+ const workspace = target.host === "agy" ? dirname(dirname(target.file)) : undefined;
64
+ const filename = workspace === undefined ? `${target.host}.json` : `agy-${digest(workspace)}.json`;
65
+ const path = join(directory, filename);
66
+ const { image, value } = readReceiptValue(path, 12 * SETUP_CONFIG_BYTES);
67
+ return image.bytes === null ? undefined : memoryReceipt(path, target, workspace === undefined ? candidates : [target.file], value);
68
+ }
69
+ if (target.name !== "vmem" && target.name !== "ares") return undefined;
70
+
71
+ const limit = target.name === "vmem" ? 4 * 1024 * 1024 : 8 * 1024 * 1024;
72
+ let found: LegacyReceipt | undefined;
73
+ for (const file of candidates) {
74
+ const hash = createHash("sha256").update(file).digest("hex").slice(0, 16);
75
+ const path = join(directory, `${target.host}-${hash}.json`);
76
+ const { image, value } = readReceiptValue(path, limit);
77
+ if (image.bytes === null) continue;
78
+ if (found) return invalid(path, `multiple setup receipts match ${target.file}`);
79
+ found = entryReceipt(path, target, file, value);
80
+ }
81
+ return found;
82
+ }
package/src/receipt.ts ADDED
@@ -0,0 +1,117 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isAbsolute, join, resolve } from "node:path";
3
+ import { publishImage, readImage } from "./fs-safe.ts";
4
+ import type { HostId } from "./hosts.ts";
5
+ import type { ConfigImage } from "./json.ts";
6
+ import { SETUP_CONFIG_BYTES } from "./toml.ts";
7
+ import { EntryRefusal } from "./refusal.ts";
8
+
9
+ const BASE64_LIMIT = Math.ceil(SETUP_CONFIG_BYTES / 3) * 4;
10
+ // Two full configuration images plus metadata and pending-operation hashes.
11
+ const RECEIPT_BYTES = 2 * BASE64_LIMIT + 64 * 1024;
12
+ const hashPattern = /^[a-f0-9]{64}$/;
13
+ export const digest = (value: unknown): string =>
14
+ createHash("sha256").update(JSON.stringify(value)).digest("hex");
15
+ export const imageDigest = (image: ConfigImage): string => digest([image.bytes, image.bytes === null ? null : image.mode]);
16
+
17
+ export interface ReceiptTarget {
18
+ host: HostId;
19
+ file: string;
20
+ name: string;
21
+ }
22
+
23
+ export interface Receipt extends ReceiptTarget {
24
+ version: 1;
25
+ intent: string;
26
+ before: ConfigImage;
27
+ after: ConfigImage;
28
+ pending?: { kind: "apply" | "undo"; start: string; result: string };
29
+ }
30
+
31
+ export function receiptPath(directory: string, target: ReceiptTarget): string {
32
+ if (!isAbsolute(directory) || resolve(directory) !== directory) {
33
+ throw new EntryRefusal("unsafe-path", `${directory}: supply an absolute receipt directory without redirects or parent segments`, { file: directory });
34
+ }
35
+ return join(directory, `entry-${digest([target.file, target.name])}.json`);
36
+ }
37
+
38
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
39
+ value !== null && typeof value === "object" && !Array.isArray(value);
40
+ const isDigest = (value: unknown): value is string => typeof value === "string" && hashPattern.test(value);
41
+
42
+ export function isConfigImage(value: unknown): value is ConfigImage {
43
+ if (!isRecord(value) || typeof value.mode !== "number" || !Number.isInteger(value.mode)
44
+ || value.mode < 0 || value.mode > 0o7777) return false;
45
+ if (value.bytes === null) return true;
46
+ if (typeof value.bytes !== "string" || value.bytes.length > BASE64_LIMIT) return false;
47
+ const bytes = Buffer.from(value.bytes, "base64");
48
+ return bytes.length <= SETUP_CONFIG_BYTES && bytes.toString("base64") === value.bytes;
49
+ }
50
+
51
+ export function readReceiptValue(path: string, limit: number): { image: ConfigImage; value?: unknown } {
52
+ const image = readImage(path, limit);
53
+ if (image.bytes === null) return { image };
54
+ try {
55
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(image.bytes, "base64"));
56
+ return { image, value: JSON.parse(text) };
57
+ } catch (cause) {
58
+ throw new EntryRefusal("invalid-receipt", `${path}: invalid receipt JSON; inspect or restore the original receipt before retrying`, { cause, file: path });
59
+ }
60
+ }
61
+
62
+ export function readReceipt(path: string, target: ReceiptTarget): { image: ConfigImage; receipt?: Receipt } {
63
+ const { image, value } = readReceiptValue(path, RECEIPT_BYTES);
64
+ if (image.bytes === null) return { image };
65
+ const refuse = (): never => {
66
+ throw new EntryRefusal("invalid-receipt", `${path}: invalid or unsupported receipt; inspect or restore the original receipt before retrying`, { file: path });
67
+ };
68
+ if (!isRecord(value) || value.version !== 1 || value.host !== target.host || value.file !== target.file
69
+ || value.name !== target.name || !isDigest(value.intent) || !isConfigImage(value.before) || !isConfigImage(value.after)) return refuse();
70
+ const pending = value.pending;
71
+ if (pending !== undefined && (!isRecord(pending) || (pending.kind !== "apply" && pending.kind !== "undo")
72
+ || !isDigest(pending.start) || !isDigest(pending.result)
73
+ || pending.kind === "apply" && pending.result !== imageDigest(value.after))) return refuse();
74
+ return { image, receipt: value as unknown as Receipt };
75
+ }
76
+
77
+ export function writeReceipt(path: string, expected: ConfigImage, receipt?: Receipt): ConfigImage {
78
+ const bytes = receipt ? Buffer.from(JSON.stringify(receipt)).toString("base64") : null;
79
+ const image = { bytes, mode: 0o600 };
80
+ publishImage(path, RECEIPT_BYTES, expected, image);
81
+ return image;
82
+ }
83
+
84
+ export function findPackageReceipt(directory: string, target: ReceiptTarget, legacyPaths: readonly string[] = []) {
85
+ const path = receiptPath(directory, target);
86
+ const selected = readReceipt(path, target);
87
+ if (selected.receipt) return { path, ...selected };
88
+ for (const file of new Set(legacyPaths)) {
89
+ if (file === target.file) continue;
90
+ const historical = { ...target, file };
91
+ const legacyPath = receiptPath(directory, historical);
92
+ const found = readReceipt(legacyPath, historical);
93
+ if (found.receipt) return { path: legacyPath, ...found };
94
+ }
95
+ return { path, ...selected };
96
+ }
97
+
98
+ // Save the previous completed v1 receipt independently of the new v1 journal.
99
+ // The pending hashes bind the sidecar to the operation that can roll it back.
100
+ export function recoveryPath(path: string, pending: NonNullable<Receipt["pending"]>): string {
101
+ return path + ".previous-" + digest([pending.start, pending.result]);
102
+ }
103
+
104
+ export function writeRecovery(path: string, pending: NonNullable<Receipt["pending"]>, previous: Receipt): void {
105
+ const backup = recoveryPath(path, pending);
106
+ const { image } = readReceipt(backup, previous);
107
+ writeReceipt(backup, image, previous);
108
+ }
109
+
110
+ export function readRecovery(path: string, receipt: Receipt & { pending: NonNullable<Receipt["pending"]> }) {
111
+ const backup = recoveryPath(path, receipt.pending);
112
+ const saved = readReceipt(backup, receipt);
113
+ if (saved.receipt?.pending) {
114
+ throw new EntryRefusal("invalid-receipt", `${backup}: invalid recovery receipt; inspect it before retrying`, { file: backup });
115
+ }
116
+ return { path: backup, ...saved };
117
+ }
package/src/refusal.ts ADDED
@@ -0,0 +1,43 @@
1
+ /** Stable identifiers for machine-readable path and entry refusals. */
2
+ export const REFUSAL_CODES = [
3
+ "relative-override",
4
+ "empty-override",
5
+ "opencode-config-route",
6
+ "opencode-environment-required",
7
+ "opencode-merged-config",
8
+ "jcode-interpolation",
9
+ "invalid-target",
10
+ "invalid-entry",
11
+ "invalid-configuration",
12
+ "size-limit",
13
+ "unsafe-path",
14
+ "lock-held",
15
+ "changed-since-preview",
16
+ "file-changed",
17
+ "invalid-plan",
18
+ "invalid-receipt",
19
+ "managed-entry-changed",
20
+ "pending-operation",
21
+ "io-error",
22
+ ] as const;
23
+
24
+ export type RefusalCode = typeof REFUSAL_CODES[number];
25
+
26
+ /** Apply and undo throw this error. Plan and path results carry the same reason and code. */
27
+ export class EntryRefusal extends Error {
28
+ readonly file?: string;
29
+
30
+ constructor(readonly code: RefusalCode, readonly reason: string, options?: ErrorOptions & { file?: string }) {
31
+ super(reason, options);
32
+ this.name = "EntryRefusal";
33
+ if (options?.file !== undefined) this.file = options.file;
34
+ }
35
+ }
36
+
37
+ export function asEntryRefusal(error: unknown, context: string, file?: string): EntryRefusal {
38
+ if (error instanceof EntryRefusal) {
39
+ return !error.file && file ? new EntryRefusal(error.code, error.reason, { file, cause: error }) : error;
40
+ }
41
+ const detail = error instanceof Error ? error.message : String(error);
42
+ return new EntryRefusal("io-error", `${context}: ${detail}; inspect the path and its permissions before retrying`, { cause: error, file });
43
+ }
package/src/toml.ts ADDED
@@ -0,0 +1,367 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { EntryRefusal } from "./refusal.ts";
3
+
4
+ export const SETUP_CONFIG_BYTES = 8 * 1024 * 1024;
5
+ const MAX_NODES = 65536, MAX_DEPTH = 32;
6
+ const temporal = new Set(["[object Temporal.Instant]", "[object Temporal.PlainDate]", "[object Temporal.PlainTime]", "[object Temporal.PlainDateTime]"]);
7
+ const plain = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));
8
+ const prefix = (left: readonly string[], right: readonly string[]) => left.length <= right.length && left.every((key, index) => key === right[index]);
9
+ const error = (): never => { throw Error("setup TOML unavailable or unsupported; no configuration changed"); };
10
+ const size = (): never => {
11
+ throw new EntryRefusal("size-limit", "setup TOML exceeds 8 MiB; reduce the file size before retrying; no configuration changed");
12
+ };
13
+ function parse(text: string): Record<string, unknown> {
14
+ if (Buffer.byteLength(text) > SETUP_CONFIG_BYTES) return size();
15
+ try { const value: unknown = Bun.TOML.parse(text); return plain(value) ? value : error(); } catch { return error(); }
16
+ }
17
+ /** Compare Temporal values and nonfinite numbers explicitly rather than relying on enumerable object properties. */
18
+ function shape(value: unknown, depth = 0, count = { value: 0, bytes: 0 }, seen = new Set<object>()): unknown {
19
+ if (depth > MAX_DEPTH || ++count.value > MAX_NODES) return error();
20
+ if (typeof value === "string") { count.bytes += Buffer.byteLength(value); if (count.bytes > SETUP_CONFIG_BYTES) return size(); return ["string", value]; }
21
+ if (typeof value === "boolean") return ["boolean", value];
22
+ if (typeof value === "number") return ["number", Number.isNaN(value) ? "nan" : Object.is(value, -0) ? "-0" : String(value)];
23
+ if (!value || typeof value !== "object" || seen.has(value)) return error();
24
+ const tag = Object.prototype.toString.call(value);
25
+ if (temporal.has(tag)) return [tag, String(value)];
26
+ if (!Array.isArray(value) && !plain(value)) return error();
27
+ if (Object.getOwnPropertySymbols(value).length) return error();
28
+ seen.add(value);
29
+ try {
30
+ if (Array.isArray(value)) return ["array", Array.from({ length: value.length }, (_, index) => shape(value[index], depth + 1, count, seen))];
31
+ return ["table", Object.keys(value).sort().map(key => {
32
+ count.bytes += Buffer.byteLength(key); if (count.bytes > SETUP_CONFIG_BYTES) return size();
33
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
34
+ if (!descriptor || !("value" in descriptor)) return error();
35
+ return [key, shape(descriptor.value, depth + 1, count, seen)];
36
+ })];
37
+ } finally { seen.delete(value); }
38
+ }
39
+ function inline(value: unknown): string {
40
+ shape(value);
41
+ // Bun emits scalars and many arrays as one assignment. Reuse that literal when it is safe in this scope.
42
+ // Objects/AOTs may become headers; those need the inline form below to avoid changing subsequent table scope.
43
+ let rendered = "";
44
+ try { rendered = Bun.TOML.stringify({ setup_value: value }) ?? ""; } catch { /* The validated inline encoder covers values the built-in writer cannot emit. */ }
45
+ const literal = /^setup_value\s*=\s*([^\r\n]*)\r?\n?$/.exec(rendered)?.[1];
46
+ if (literal !== undefined && isDeepStrictEqual(shape(parse(rendered).setup_value), shape(value))) return literal;
47
+ const encode = (part: unknown): string => {
48
+ if (typeof part === "string") return JSON.stringify(part);
49
+ if (typeof part === "boolean") return String(part);
50
+ if (typeof part === "number") return Number.isNaN(part) ? "nan" : part === Infinity ? "inf" : part === -Infinity ? "-inf" : Object.is(part, -0) ? "-0.0" : String(part);
51
+ if (temporal.has(Object.prototype.toString.call(part))) return String(part);
52
+ if (Array.isArray(part)) return `[${part.map(encode).join(", ")}]`;
53
+ if (plain(part)) return `{ ${Object.keys(part).map(key => `${JSON.stringify(key)} = ${encode(part[key])}`).join(", ")} }`;
54
+ return error();
55
+ };
56
+ return encode(value);
57
+ }
58
+ function at(document: Record<string, unknown>, path: readonly string[]): unknown {
59
+ let value: unknown = document;
60
+ for (const key of path) { if (!plain(value) || !Object.hasOwn(value, key)) return undefined; value = value[key]; }
61
+ return value;
62
+ }
63
+ function edit(document: Record<string, unknown>, path: readonly string[], value: unknown): void {
64
+ let parent = document;
65
+ for (const key of path.slice(0, -1)) {
66
+ if (!Object.hasOwn(parent, key)) Object.defineProperty(parent, key, { value: Object.create(null), writable: true, configurable: true, enumerable: true });
67
+ if (!plain(parent[key])) return error(); // String paths cannot identify one element of an array of tables.
68
+ parent = parent[key] as Record<string, unknown>;
69
+ }
70
+ const key = path.at(-1)!;
71
+ if (value === undefined) delete parent[key];
72
+ else Object.defineProperty(parent, key, { value, writable: true, configurable: true, enumerable: true });
73
+ }
74
+ interface Statement { start: number; end: number; equal?: number; comment?: number; path: string[]; header: boolean; array: boolean }
75
+ /** Bun decodes quoted/dotted keys; the lexical scan below only locates complete statement boundaries. */
76
+ function keyPath(source: string, header: boolean): string[] {
77
+ let value: unknown = parse(header ? source : `${source} = 0`); const keys: string[] = [];
78
+ while (plain(value) && Object.keys(value).length === 1) {
79
+ const key = Object.keys(value)[0]!; keys.push(key); value = value[key];
80
+ if (Array.isArray(value)) { if (value.length !== 1) return error(); value = value[0]; }
81
+ }
82
+ if (!keys.length || header && (!plain(value) || Object.keys(value).length)) return error();
83
+ return keys;
84
+ }
85
+ function statements(text: string): Statement[] {
86
+ const out: Statement[] = []; let offset = 0, table: string[] = [];
87
+ while (offset < text.length) {
88
+ while (offset < text.length) {
89
+ if (/\s/.test(text[offset]!)) { offset++; continue; }
90
+ if (text[offset] === "#") { while (offset < text.length && text[offset] !== "\n") offset++; continue; }
91
+ break;
92
+ }
93
+ if (offset >= text.length) break;
94
+ const start = offset; let equal: number | undefined, comment: number | undefined, depth = 0, quote: string | undefined, multi = false;
95
+ while (offset < text.length) {
96
+ const char = text[offset]!;
97
+ if (quote) {
98
+ if (quote === '"' && char === "\\") { offset += Math.min(2, text.length - offset); continue; }
99
+ if (char === quote) {
100
+ let run = 1; while (text[offset + run] === quote) run++;
101
+ if (!multi || run >= 3) { quote = undefined; offset += multi ? run : 1; multi = false; continue; }
102
+ offset += run; continue;
103
+ }
104
+ offset++; continue;
105
+ }
106
+ if (char === '"' || char === "'") { quote = char; multi = text.slice(offset, offset + 3) === char.repeat(3); offset += multi ? 3 : 1; continue; }
107
+ if (char === "#") {
108
+ if (depth === 0) comment = offset;
109
+ while (offset < text.length && text[offset] !== "\n") offset++;
110
+ if (depth === 0) { if (offset < text.length) offset++; break; } continue;
111
+ }
112
+ if (char === "[" || char === "{") depth++;
113
+ else if (char === "]" || char === "}") depth--;
114
+ else if (char === "=" && depth === 0 && equal === undefined) equal = offset;
115
+ if (depth < 0 || depth > MAX_DEPTH) return error();
116
+ offset++;
117
+ if (char === "\n" && depth === 0) break;
118
+ }
119
+ if (quote || depth !== 0 || out.length >= MAX_NODES) return error();
120
+ const header = text[start] === "[", array = header && text[start + 1] === "[";
121
+ if (header) table = keyPath(text.slice(start, comment ?? offset).trim(), true);
122
+ else if (equal === undefined) return error();
123
+ out.push({ start, end: offset, equal, comment, path: header ? [...table] : [...table, ...keyPath(text.slice(start, equal), false)], header, array });
124
+ }
125
+ return out;
126
+ }
127
+ interface Replacement { start: number; end: number; text: string }
128
+ function replace(text: string, changes: Replacement[]): string {
129
+ for (const change of changes.sort((a, b) => b.start - a.start || b.end - a.end)) text = text.slice(0, change.start) + change.text + text.slice(change.end);
130
+ return text;
131
+ }
132
+ /**
133
+ * Change one configuration subtree while preserving other statements/comments byte-for-byte.
134
+ * ponytail: <=8 MiB, depth32 and string table paths only. Array-element editing requires a richer host API;
135
+ * unsupported layouts/values refuse after Bun parse/semantic verification, never fall back to rewriting the document.
136
+ */
137
+ export function setTomlPath(
138
+ text: string,
139
+ path: readonly string[],
140
+ value: unknown | undefined,
141
+ options?: { refuseInlineParent?: boolean },
142
+ ): string {
143
+ return editTomlPath(text, path, value, undefined, options?.refuseInlineParent);
144
+ }
145
+ function editTomlPath(text: string, path: readonly string[], value: unknown | undefined, eol = text.includes("\r\n") ? "\r\n" : "\n", refuseInlineParent = false): string {
146
+ if (!path.length || path.length > 8 || path.some(key => typeof key !== "string" || Buffer.byteLength(key) > 256 || /[\p{Cc}\p{Cf}]/u.test(key))) return error();
147
+ const original = parse(text), current = at(original, path);
148
+ shape(original);
149
+ let parent: unknown = original;
150
+ for (const key of path.slice(0, -1)) {
151
+ if (!plain(parent)) return error();
152
+ if (!Object.hasOwn(parent, key)) break;
153
+ parent = parent[key]; if (!plain(parent)) return error();
154
+ }
155
+ if (value === undefined && current === undefined || value !== undefined && current !== undefined && isDeepStrictEqual(shape(current), shape(value))) return text;
156
+ if (value !== undefined) shape(value);
157
+ const expected = parse(text); edit(expected, path, value); shape(expected);
158
+ const units = statements(text), ancestor = units.find(unit => !unit.header && prefix(unit.path, path));
159
+ let output: string;
160
+ if (ancestor) {
161
+ if (refuseInlineParent && ancestor.path.length < path.length) {
162
+ throw new Error("cannot edit one entry without rewriting its inline parent; convert the parent to standard TOML tables");
163
+ }
164
+ const replacement = at(expected, ancestor.path);
165
+ const suffix = ancestor.comment !== undefined ? " " + text.slice(ancestor.comment, ancestor.end) : /\r?\n$/.exec(text.slice(ancestor.start, ancestor.end))?.[0] ?? "";
166
+ output = replace(text, [{ start: ancestor.start, end: ancestor.end, text: replacement === undefined ? "" : `${text.slice(ancestor.start, ancestor.equal! + 1)} ${inline(replacement)}${suffix}` }]);
167
+ } else {
168
+ const changes: Replacement[] = units.filter(unit => prefix(path, unit.path)).map(unit => ({ start: unit.start, end: unit.end, text: "" }));
169
+ if (value !== undefined) {
170
+ const parent = units.filter(unit => unit.header && !unit.array && unit.path.length < path.length && prefix(unit.path, path)).sort((a, b) => b.path.length - a.path.length)[0];
171
+ const position = parent?.end ?? units.find(unit => unit.header)?.start ?? text.length;
172
+ const key = path.slice(parent?.path.length ?? 0).map(part => JSON.stringify(part)).join(".");
173
+ const newline = position > 0 && text[position - 1] !== "\n" ? eol : "";
174
+ changes.push({ start: position, end: position, text: `${newline}${key} = ${inline(value)}${eol}` });
175
+ }
176
+ output = replace(text, changes);
177
+ }
178
+ // Removing the only child of an implicit table must retain its parsed empty parent value.
179
+ for (let depth = path.length - 1; depth > 0; depth--) {
180
+ const parent = path.slice(0, depth), wanted = at(expected, parent);
181
+ if (plain(wanted) && !Object.keys(wanted).length && at(parse(output), parent) === undefined) output += `${output && !output.endsWith("\n") ? eol : ""}[${parent.map(part => JSON.stringify(part)).join(".")}]${eol}`;
182
+ }
183
+ if (!isDeepStrictEqual(shape(parse(output)), shape(expected))) return error();
184
+ return output;
185
+ }
186
+
187
+ function quotedEnd(text: string, start: number): number {
188
+ const quote = text[start]!, multi = text.slice(start, start + 3) === quote.repeat(3); let offset = start + (multi ? 3 : 1);
189
+ while (offset < text.length) {
190
+ if (quote === '"' && text[offset] === "\\") { offset += 2; continue; }
191
+ if (text[offset] === quote) {
192
+ let run = 1; while (text[offset + run] === quote) run++;
193
+ if (!multi || run >= 3) return offset + (multi ? run : 1);
194
+ offset += run; continue;
195
+ }
196
+ offset++;
197
+ }
198
+ return error();
199
+ }
200
+ interface ArrayElement { start: number; end: number; removeFrom: number; comma?: number }
201
+ function arrayElements(text: string, open: number): { close: number; elements: ArrayElement[] } {
202
+ if (text[open] !== "[") return error();
203
+ let offset = open + 1; const elements: ArrayElement[] = [];
204
+ while (offset < text.length) {
205
+ let removeFrom = offset;
206
+ while (offset < text.length) {
207
+ if (/\s/.test(text[offset]!)) { offset++; continue; }
208
+ if (text[offset] === "#") {
209
+ while (offset < text.length && text[offset] !== "\n") offset++;
210
+ // Trim indentation after a comment, but preserve its terminating newline.
211
+ removeFrom = offset < text.length ? offset + 1 : offset; continue;
212
+ }
213
+ break;
214
+ }
215
+ if (text[offset] === "]") return { close: offset, elements };
216
+ const start = offset; let end = offset, depth = 0;
217
+ while (offset < text.length) {
218
+ const char = text[offset]!;
219
+ if (char === '"' || char === "'") { offset = quotedEnd(text, offset); end = offset; continue; }
220
+ if (char === "#") { while (offset < text.length && text[offset] !== "\n") offset++; continue; }
221
+ if (char === "," && depth === 0) { elements.push({ start, end, removeFrom, comma: offset }); offset++; break; }
222
+ if (char === "]" && depth === 0) { elements.push({ start, end, removeFrom }); return { close: offset, elements }; }
223
+ if (char === "[" || char === "{") depth++;
224
+ else if (char === "]" || char === "}") depth--;
225
+ if (depth < 0 || depth > MAX_DEPTH) return error();
226
+ offset++; if (!/\s/.test(char)) end = offset;
227
+ }
228
+ if (elements.length > MAX_NODES) return error();
229
+ }
230
+ return error();
231
+ }
232
+ /** Reinsert only rows removed by this installer, anchored to surviving original rows.
233
+ * Current rows stay in their own order; unrelated additions/deletions are never reversed. */
234
+ export function restoreRemovedItems<T>(before: readonly T[], after: readonly T[], current: readonly T[], key: (value: T) => string): T[] {
235
+ const counts = (rows: readonly T[]) => { const found = new Map<string, number>(); for (const row of rows) found.set(key(row), (found.get(key(row)) ?? 0) + 1); return found; };
236
+ const original = counts(before), installed = counts(after), live = counts(current), seen = new Map<string, number>();
237
+ const ordinals = before.map(row => { const id = key(row), ordinal = seen.get(id) ?? 0; seen.set(id, ordinal + 1); return ordinal; });
238
+ const result = [...current];
239
+ const anchor = (index: number) => { const id = key(before[index]!); let ordinal = ordinals[index]!;
240
+ return result.findIndex(row => key(row) === id && ordinal-- === 0); };
241
+ for (let index = 0; index < before.length; index++) {
242
+ const row = before[index]!, id = key(row), retained = installed.get(id) ?? 0;
243
+ if (retained) { installed.set(id, retained - 1); continue; }
244
+ if ((live.get(id) ?? 0) >= original.get(id)!) continue;
245
+ let at = result.length, found = false;
246
+ for (let next = index + 1; next < before.length; next++) { const position = anchor(next); if (position >= 0) { at = position; found = true; break; } }
247
+ if (!found) for (let prior = index - 1; prior >= 0; prior--) { const position = anchor(prior); if (position >= 0) { at = position + 1; break; } }
248
+ result.splice(at, 0, row); live.set(id, (live.get(id) ?? 0) + 1);
249
+ }
250
+ return result;
251
+ }
252
+ /** Keep an ordered subsequence of existing elements, optionally adding new elements only at the tail. */
253
+ function arrayEdit(before: readonly unknown[], after: readonly unknown[]): { keep: Set<number>; append: readonly unknown[] } {
254
+ const old = before.map(value => JSON.stringify(shape(value))), next = after.map(value => JSON.stringify(shape(value)));
255
+ const keep = new Set<number>(); let cursor = 0, tail = next.length;
256
+ for (let i = 0; i < next.length; i++) {
257
+ while (cursor < old.length && old[cursor] !== next[i]) cursor++;
258
+ if (cursor === old.length) { tail = i; break; }
259
+ keep.add(cursor++);
260
+ }
261
+ const removed = new Set(old.filter((_value, index) => !keep.has(index)));
262
+ // A reorder must not masquerade as deleting an old element and appending its normalized serialization.
263
+ if (next.slice(tail).some(value => removed.has(value))) return error();
264
+ if (keep.size < before.length && tail < after.length) return error(); // Refuse replacement disguised as simultaneous remove/append.
265
+ return { keep, append: after.slice(tail) };
266
+ }
267
+ function appendedTables(path: readonly string[], values: readonly unknown[], eol: string): string {
268
+ if (!values.every(plain)) return error();
269
+ const document: Record<string, unknown> = {}; edit(document, path, [...values]);
270
+ let source: string | undefined; try { source = Bun.TOML.stringify(document); } catch { return error(); }
271
+ if (source === undefined) return error();
272
+ const sourceUnits = statements(source), rows = sourceUnits.filter(unit => prefix(path, unit.path));
273
+ if (rows.filter(unit => unit.header && unit.array && unit.path.length === path.length).length !== values.length) return error();
274
+ return rows.map(unit => source.slice(unit.start, unit.end)).join("").replace(/\r?\n/g, eol);
275
+ }
276
+ /**
277
+ * Append/remove an array subsequence without reserializing surviving elements or their comments/numeric spelling.
278
+ * ponytail: exact array assignments and arrays of tables only; arrays nested inside inline parent tables and
279
+ * simultaneous remove+append, element replacement and reordering refuse. Use setTomlPath for an explicitly authorized whole-subtree replacement.
280
+ */
281
+ export function updateTomlArray(text: string, path: readonly string[], expectedArray: readonly unknown[]): string {
282
+ if (!path.length || path.length > 8 || path.some(key => typeof key !== "string" || Buffer.byteLength(key) > 256 || /[\p{Cc}\p{Cf}]/u.test(key)) || !Array.isArray(expectedArray)) return error();
283
+ const original = parse(text), current = at(original, path); shape(original); shape(expectedArray);
284
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
285
+ if (current === undefined) return editTomlPath(text, path, [...expectedArray], eol);
286
+ if (!Array.isArray(current)) return error();
287
+ if (isDeepStrictEqual(shape(current), shape(expectedArray))) return text;
288
+ const expected = parse(text); edit(expected, path, [...expectedArray]);
289
+ const { keep, append } = arrayEdit(current, expectedArray), units = statements(text);
290
+ const assignment = units.find(unit => !unit.header && unit.path.length === path.length && prefix(path, unit.path));
291
+ const changes: Replacement[] = []; let output: string;
292
+ if (assignment) {
293
+ let open = assignment.equal! + 1; while (/\s/.test(text[open] ?? "")) open++;
294
+ const array = arrayElements(text, open);
295
+ if (array.elements.length !== current.length) return error();
296
+ for (let index = 0; index < array.elements.length; index++) if (!keep.has(index)) {
297
+ const element = array.elements[index]!; changes.push({ start: element.removeFrom, end: element.end, text: "" });
298
+ if (element.comma !== undefined) changes.push({ start: element.comma, end: element.comma + 1, text: "" });
299
+ else {
300
+ // The last element has no comma of its own: drop the same-line comma that append inserted after the kept element before it, or `[a,]` remains. A comma followed by a comment or newline was the person's own and stays.
301
+ const before = [...keep].filter(kept => kept < index).at(-1), previous = before === undefined ? undefined : array.elements[before];
302
+ if (previous?.comma !== undefined && !append.length && /^[ \t]*$/.test(text.slice(previous.comma + 1, element.start))) changes.push({ start: previous.comma, end: previous.comma + 1, text: "" });
303
+ }
304
+ }
305
+ if (append.length) {
306
+ const last = [...keep].at(-1), element = last === undefined ? undefined : array.elements[last];
307
+ const adjacentComma = element && element.comma === undefined && element.end === array.close ? "," : "";
308
+ if (element && element.comma === undefined && !adjacentComma) changes.push({ start: element.end, end: element.end, text: "," });
309
+ const multiline = text.slice(open, array.close).includes("\n"), indent = /(?:^|\n)([\t ]*)$/.exec(text.slice(open, array.close))?.[1] ?? "";
310
+ changes.push({ start: array.close, end: array.close, text: `${adjacentComma} ${append.map(inline).join(multiline ? `,${eol}${indent}` : ", ")}${multiline ? eol + indent : ""}` });
311
+ }
312
+ output = replace(text, changes);
313
+ } else {
314
+ let index = -1, headers = 0;
315
+ for (const unit of units) {
316
+ if (unit.header && unit.array && unit.path.length === path.length && prefix(path, unit.path)) { index++; headers++; }
317
+ if (prefix(path, unit.path)) {
318
+ if (index < 0) return error();
319
+ if (!keep.has(index)) changes.push({ start: unit.start, end: unit.end, text: "" });
320
+ }
321
+ }
322
+ if (headers !== current.length) return error();
323
+ output = replace(text, changes);
324
+ if (append.length) output += `${output && !output.endsWith("\n") ? eol : ""}${appendedTables(path, append, eol)}`;
325
+ if (!keep.size && !append.length) output = editTomlPath(output, path, [], eol);
326
+ }
327
+ if (!isDeepStrictEqual(shape(parse(output)), shape(expected))) return error();
328
+ return output;
329
+ }
330
+
331
+ /** Insert restored rows without deleting/reordering or reserializing surviving TOML elements. */
332
+ export function insertTomlArrayItems(text: string, path: readonly string[], expectedArray: readonly unknown[]): string {
333
+ if (!path.length || path.length > 8 || path.some(key => typeof key !== "string" || Buffer.byteLength(key) > 256 || /[\p{Cc}\p{Cf}]/u.test(key)) || !Array.isArray(expectedArray)) return error();
334
+ const original = parse(text), current = at(original, path); shape(original); shape(expectedArray);
335
+ if (current === undefined || Array.isArray(current) && current.length === 0) return updateTomlArray(text, path, expectedArray);
336
+ if (!Array.isArray(current)) return error();
337
+ const key = (value: unknown) => JSON.stringify(shape(value)), pending = new Map<number, unknown[]>(); let cursor = 0;
338
+ for (const value of expectedArray) {
339
+ if (cursor < current.length && key(value) === key(current[cursor])) cursor++;
340
+ else pending.set(cursor, [...(pending.get(cursor) ?? []), value]);
341
+ }
342
+ if (cursor !== current.length) return error(); // Every original element must survive in order.
343
+ if (!pending.size) return text;
344
+ const units = statements(text), assignment = units.find(unit => !unit.header && unit.path.length === path.length && prefix(path, unit.path));
345
+ const eol = text.includes("\r\n") ? "\r\n" : "\n", changes: Replacement[] = [];
346
+ if (assignment) {
347
+ let open = assignment.equal! + 1; while (/\s/.test(text[open] ?? "")) open++;
348
+ const array = arrayElements(text, open); if (array.elements.length !== current.length) return error();
349
+ for (const [index, values] of pending) if (index < current.length) {
350
+ const start = index ? array.elements[index - 1]!.comma! + 1 : open + 1;
351
+ changes.push({ start, end: start, text: ` ${values.map(inline).join(", ")}, ` });
352
+ }
353
+ } else {
354
+ const headers = units.filter(unit => unit.header && unit.array && unit.path.length === path.length && prefix(path, unit.path));
355
+ if (headers.length !== current.length) return error();
356
+ for (const [index, values] of pending) if (index < current.length) {
357
+ const header = headers[index]!, prior = units[units.indexOf(header) - 1], start = prior?.end ?? 0;
358
+ changes.push({ start, end: start, text: `${start && text[start - 1] !== "\n" ? eol : ""}${appendedTables(path, values, eol)}` });
359
+ }
360
+ }
361
+ let output = replace(text, changes);
362
+ const tail = pending.get(current.length);
363
+ if (tail?.length) output = updateTomlArray(output, path, [...(at(parse(output), path) as unknown[]), ...tail]);
364
+ const expected = parse(text); edit(expected, path, [...expectedArray]);
365
+ if (!isDeepStrictEqual(shape(parse(output)), shape(expected))) return error();
366
+ return output;
367
+ }