pi-agent-swarm 0.0.0 → 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
+ const RELOAD_HANDOFFS = Symbol.for("pi-agent-swarm/reload-handoffs");
2
+
3
+ export interface SwarmReloadHandoff {
4
+ invite: string;
5
+ acceptsRequests: boolean;
6
+ launchId?: string;
7
+ kickoffCapability?: string;
8
+ kickoffConsumed: boolean;
9
+ name?: string;
10
+ color?: string;
11
+ parentSessionId?: string;
12
+ expiresAt: number;
13
+ }
14
+
15
+ export function putReloadHandoff(owner: object, handoff: SwarmReloadHandoff): void {
16
+ reloadHandoffs().set(owner, handoff);
17
+ }
18
+
19
+ export function takeReloadHandoff(owner: object, now: number): SwarmReloadHandoff | undefined {
20
+ const store = reloadHandoffs();
21
+ const value = store.get(owner);
22
+ store.delete(owner);
23
+ return value && value.expiresAt >= now ? value : undefined;
24
+ }
25
+
26
+ function reloadHandoffs(): WeakMap<object, SwarmReloadHandoff> {
27
+ const root = globalThis as unknown as Record<PropertyKey, unknown>;
28
+ const existing = root[RELOAD_HANDOFFS];
29
+ if (existing instanceof WeakMap) return existing as WeakMap<object, SwarmReloadHandoff>;
30
+ const created = new WeakMap<object, SwarmReloadHandoff>();
31
+ root[RELOAD_HANDOFFS] = created;
32
+ return created;
33
+ }
@@ -0,0 +1,30 @@
1
+ import type { MessageRenderer } from "@earendil-works/pi-coding-agent";
2
+ import { Text } from "@earendil-works/pi-tui";
3
+ import type { SwarmMessage } from "./protocol.js";
4
+ import { safeTerminalLine, safeTerminalText } from "./text.js";
5
+
6
+ export const SWARM_MESSAGE_TYPE = "pi-agent-swarm-message";
7
+
8
+ export interface SwarmMessageDetails {
9
+ message: SwarmMessage;
10
+ }
11
+
12
+ export const renderSwarmMessage: MessageRenderer<SwarmMessageDetails> = (message, options, theme) => {
13
+ const details = message.details;
14
+ if (!details?.message) return undefined;
15
+ const value = details.message;
16
+ const sender = safeTerminalLine(value.fromName ?? value.fromSessionId) || "unknown session";
17
+ const mode = value.mode === "request" || value.mode === "kickoff" ? "request" : value.mode;
18
+ const lines = [theme.fg("accent", theme.bold(`Pi Agent Swarm ${mode} · ${sender}`)), safeTerminalText(value.text)];
19
+ if (options.expanded) {
20
+ lines.push(
21
+ theme.fg("dim", `Session: ${safeTerminalLine(value.fromSessionId)}`),
22
+ theme.fg("dim", `Cwd: ${safeTerminalLine(value.fromCwd ?? "unknown")}`),
23
+ theme.fg("dim", `Message: ${safeTerminalLine(value.id)}`),
24
+ );
25
+ if (value.replyTo) {
26
+ lines.push(theme.fg("dim", `Reply to: ${safeTerminalLine(value.replyTo)}`));
27
+ }
28
+ }
29
+ return new Text(lines.join("\n"), options.outputPad, 0);
30
+ };
@@ -0,0 +1,249 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmod, lstat, mkdir, open, opendir, realpath, rename, rm, stat } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
5
+
6
+ export const MAX_UNIX_SOCKET_PATH_BYTES = 103;
7
+ export const MAX_MANIFEST_BYTES = 8 * 1024;
8
+ export const ORPHAN_GRACE_MS = 60_000;
9
+ export const MAX_RUNTIME_SCAN_ENTRIES = 512;
10
+ const SAFE_GROUP_ID = /^[a-f0-9]{32}$/u;
11
+ const SAFE_ENDPOINT_ID = /^[a-f0-9]{24}$/u;
12
+ const SAFE_SOCKET_NAME = /^([a-f0-9]{24})\.sock$/u;
13
+ const SAFE_MANIFEST_NAME = /^([a-f0-9]{24})\.json$/u;
14
+ const SAFE_TEMPORARY_NAME = /^\.([a-f0-9]{24})\.json\.[a-f0-9]{16}\.tmp$/u;
15
+ const SAFE_LAUNCHER_NAME = /^launch-[a-f0-9]{16}\.sh$/u;
16
+
17
+ export interface RuntimeDirectoryOptions {
18
+ baseDirectory?: string;
19
+ }
20
+
21
+ export interface EndpointPaths {
22
+ directory: string;
23
+ endpointId: string;
24
+ socketPath: string;
25
+ manifestPath: string;
26
+ }
27
+
28
+ export interface RuntimeCleanupResult {
29
+ removedSockets: number;
30
+ removedTemporaryFiles: number;
31
+ saturated: boolean;
32
+ }
33
+
34
+ export function defaultRuntimeBaseDirectory(): string {
35
+ if (process.platform === "win32") {
36
+ throw new Error("Pi Agent Swarm local transport requires a POSIX platform");
37
+ }
38
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
39
+ if (process.platform === "darwin") return join("/tmp", `pi-swarm-${uid}`);
40
+ const runtime = process.env.XDG_RUNTIME_DIR;
41
+ if (
42
+ runtime &&
43
+ isAbsolute(runtime) &&
44
+ Buffer.byteLength(join(runtime, "pi-swarm", "x".repeat(32), `${"x".repeat(24)}.sock`)) <= MAX_UNIX_SOCKET_PATH_BYTES
45
+ ) {
46
+ return join(runtime, "pi-swarm");
47
+ }
48
+ const systemTmp = resolve(tmpdir());
49
+ const candidate = join(systemTmp, `pi-swarm-${uid}`);
50
+ const socketCandidate = join(candidate, "x".repeat(32), `${"x".repeat(24)}.sock`);
51
+ return Buffer.byteLength(socketCandidate) <= MAX_UNIX_SOCKET_PATH_BYTES ? candidate : join("/tmp", `pi-swarm-${uid}`);
52
+ }
53
+
54
+ export async function ensureGroupRuntimeDirectory(
55
+ groupId: string,
56
+ options: RuntimeDirectoryOptions = {},
57
+ ): Promise<string> {
58
+ if (!SAFE_GROUP_ID.test(groupId)) throw new Error("Pi Agent Swarm runtime group id is invalid");
59
+ const baseDirectory = resolve(options.baseDirectory ?? defaultRuntimeBaseDirectory());
60
+ const directory = join(baseDirectory, groupId);
61
+ const longestSocket = join(directory, `${"x".repeat(24)}.sock`);
62
+ if (Buffer.byteLength(longestSocket) > MAX_UNIX_SOCKET_PATH_BYTES) {
63
+ throw new Error("Pi Agent Swarm runtime directory exceeds the Unix socket path limit");
64
+ }
65
+ await ensurePrivateDirectory(baseDirectory);
66
+ await ensurePrivateDirectory(directory);
67
+ return directory;
68
+ }
69
+
70
+ export function createEndpointPaths(directory: string, endpointId: string): EndpointPaths {
71
+ if (!SAFE_ENDPOINT_ID.test(endpointId)) throw new Error("Pi Agent Swarm endpoint id is invalid");
72
+ const socketPath = join(directory, `${endpointId}.sock`);
73
+ if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH_BYTES) {
74
+ throw new Error("Pi Agent Swarm socket path exceeds the Unix path limit");
75
+ }
76
+ return {
77
+ directory,
78
+ endpointId,
79
+ socketPath,
80
+ manifestPath: join(directory, `${endpointId}.json`),
81
+ };
82
+ }
83
+
84
+ export function randomEndpointId(): string {
85
+ return randomBytes(12).toString("hex");
86
+ }
87
+
88
+ export async function publishManifest(manifestPath: string, manifest: object): Promise<void> {
89
+ const parent = dirname(manifestPath);
90
+ await assertPrivateDirectory(parent);
91
+ assertOwnedPath(parent, manifestPath, ".json");
92
+ const body = `${JSON.stringify(manifest)}\n`;
93
+ if (Buffer.byteLength(body) > MAX_MANIFEST_BYTES) {
94
+ throw new Error("Pi Agent Swarm endpoint manifest is too large");
95
+ }
96
+ const temporaryPath = join(parent, `.${basename(manifestPath)}.${randomBytes(8).toString("hex")}.tmp`);
97
+ let handle: Awaited<ReturnType<typeof open>> | undefined;
98
+ try {
99
+ handle = await open(temporaryPath, "wx", 0o600);
100
+ await handle.writeFile(body, "utf8");
101
+ await handle.sync();
102
+ await handle.close();
103
+ handle = undefined;
104
+ await rename(temporaryPath, manifestPath);
105
+ await chmod(manifestPath, 0o600);
106
+ } finally {
107
+ await handle?.close().catch(() => undefined);
108
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
109
+ }
110
+ }
111
+
112
+ export async function cleanupStaleRuntimeEntries(directory: string, now = Date.now()): Promise<RuntimeCleanupResult> {
113
+ await assertPrivateDirectory(directory);
114
+ const names = new Set<string>();
115
+ let scanned = 0;
116
+ let saturated = false;
117
+ const handle = await opendir(directory);
118
+ try {
119
+ for await (const entry of handle) {
120
+ if (scanned >= MAX_RUNTIME_SCAN_ENTRIES) {
121
+ saturated = true;
122
+ break;
123
+ }
124
+ scanned += 1;
125
+ names.add(entry.name);
126
+ }
127
+ } finally {
128
+ await handle.close().catch(() => undefined);
129
+ }
130
+ let removedSockets = 0;
131
+ let removedTemporaryFiles = 0;
132
+ for (const name of names) {
133
+ const socketMatch = SAFE_SOCKET_NAME.exec(name);
134
+ if (socketMatch) {
135
+ const manifestPath = join(directory, `${socketMatch[1]}.json`);
136
+ if (!(await pathExists(manifestPath))) {
137
+ if (await removeStaleOwnedEntry(directory, name, "socket", now)) removedSockets += 1;
138
+ }
139
+ continue;
140
+ }
141
+ if (SAFE_TEMPORARY_NAME.test(name) || SAFE_LAUNCHER_NAME.test(name)) {
142
+ if (await removeStaleOwnedEntry(directory, name, "file", now)) {
143
+ removedTemporaryFiles += 1;
144
+ }
145
+ }
146
+ }
147
+ return { removedSockets, removedTemporaryFiles, saturated };
148
+ }
149
+
150
+ export async function removeOwnedEndpoint(paths: EndpointPaths): Promise<void> {
151
+ for (const path of [paths.manifestPath, paths.socketPath]) {
152
+ assertOwnedPath(paths.directory, path);
153
+ await rm(path, { force: true }).catch(() => undefined);
154
+ }
155
+ }
156
+
157
+ export function endpointIdFromManifestName(name: string): string | undefined {
158
+ return SAFE_MANIFEST_NAME.exec(name)?.[1];
159
+ }
160
+
161
+ export function assertOwnedPath(parent: string, candidate: string, suffix?: string): void {
162
+ const resolvedParent = resolve(parent);
163
+ const resolvedCandidate = resolve(candidate);
164
+ const rel = relative(resolvedParent, resolvedCandidate);
165
+ if (!rel || rel === ".." || rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`)) {
166
+ throw new Error("Pi Agent Swarm runtime path escapes its owner directory");
167
+ }
168
+ if (suffix && !basename(resolvedCandidate).endsWith(suffix)) {
169
+ throw new Error("Pi Agent Swarm runtime path has an invalid suffix");
170
+ }
171
+ }
172
+
173
+ async function removeStaleOwnedEntry(
174
+ directory: string,
175
+ name: string,
176
+ kind: "file" | "socket",
177
+ now: number,
178
+ ): Promise<boolean> {
179
+ const path = join(directory, name);
180
+ assertOwnedPath(directory, path);
181
+ try {
182
+ const first = await lstat(path, { bigint: true });
183
+ assertOwner(Number(first.uid));
184
+ if (kind === "file" ? !first.isFile() : !first.isSocket()) return false;
185
+ if (now - Number(first.mtimeMs) < ORPHAN_GRACE_MS) return false;
186
+ const current = await lstat(path, { bigint: true });
187
+ if (
188
+ current.dev !== first.dev ||
189
+ current.ino !== first.ino ||
190
+ current.mtimeMs !== first.mtimeMs ||
191
+ (kind === "file" ? !current.isFile() : !current.isSocket())
192
+ ) {
193
+ return false;
194
+ }
195
+ await rm(path);
196
+ return true;
197
+ } catch (error) {
198
+ if (isMissing(error)) return false;
199
+ throw error;
200
+ }
201
+ }
202
+
203
+ async function ensurePrivateDirectory(path: string): Promise<void> {
204
+ try {
205
+ const info = await lstat(path);
206
+ if (info.isSymbolicLink()) throw new Error("Pi Agent Swarm runtime directory is a symbolic link");
207
+ if (!info.isDirectory()) throw new Error("Pi Agent Swarm runtime path is not a directory");
208
+ assertOwner(info.uid);
209
+ if ((info.mode & 0o777) !== 0o700) await chmod(path, 0o700);
210
+ await assertPrivateDirectory(path);
211
+ } catch (error) {
212
+ if (!isMissing(error)) throw error;
213
+ await mkdir(path, { recursive: true, mode: 0o700 });
214
+ await chmod(path, 0o700);
215
+ await assertPrivateDirectory(path);
216
+ }
217
+ }
218
+
219
+ async function assertPrivateDirectory(path: string): Promise<void> {
220
+ const info = await lstat(path);
221
+ if (info.isSymbolicLink()) throw new Error("Pi Agent Swarm runtime directory is a symbolic link");
222
+ if (!info.isDirectory()) throw new Error("Pi Agent Swarm runtime path is not a directory");
223
+ assertOwner(info.uid);
224
+ if ((info.mode & 0o777) !== 0o700) {
225
+ throw new Error("Pi Agent Swarm runtime directory permissions are not private");
226
+ }
227
+ const resolved = await realpath(path);
228
+ const resolvedInfo = await stat(resolved);
229
+ assertOwner(resolvedInfo.uid);
230
+ }
231
+
232
+ function assertOwner(uid: number): void {
233
+ if (typeof process.getuid !== "function") return;
234
+ if (uid !== process.getuid()) throw new Error("Pi Agent Swarm runtime path is owned by another user");
235
+ }
236
+
237
+ async function pathExists(path: string): Promise<boolean> {
238
+ try {
239
+ await lstat(path);
240
+ return true;
241
+ } catch (error) {
242
+ if (isMissing(error)) return false;
243
+ throw error;
244
+ }
245
+ }
246
+
247
+ function isMissing(error: unknown): boolean {
248
+ return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
249
+ }
@@ -0,0 +1,369 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
4
+ import { basename, dirname, join } from "node:path";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import type { SwarmColorPaletteName } from "./color.js";
7
+
8
+ export const SWARM_SETTINGS_FILE = "pi-agent-swarm.json";
9
+ export const MAX_SWARM_SETTINGS_BYTES = 64 * 1024;
10
+ export const DEFAULT_SWARM_SETTINGS: Readonly<SwarmSettings> = Object.freeze({
11
+ colorPalette: "muted",
12
+ confirmSessionLaunch: true,
13
+ externalCommand: "alacritty -e",
14
+ pinToLeadWorkspace: false,
15
+ });
16
+
17
+ export interface SwarmSettings {
18
+ colorPalette: SwarmColorPaletteName;
19
+ confirmSessionLaunch: boolean;
20
+ externalCommand: string;
21
+ pinToLeadWorkspace: boolean;
22
+ }
23
+
24
+ export type SwarmSettingsField = keyof SwarmSettings;
25
+ export type SwarmSettingsSource = "built-in" | "user";
26
+ export type SwarmSettingsPatch = Partial<SwarmSettings>;
27
+
28
+ export interface NormalizedSwarmSettings {
29
+ settings: SwarmSettings;
30
+ sources: Record<SwarmSettingsField, SwarmSettingsSource>;
31
+ }
32
+
33
+ export interface SwarmSettingsIssue {
34
+ kind: "invalid";
35
+ message: string;
36
+ }
37
+
38
+ export interface SwarmSettingsState extends NormalizedSwarmSettings {
39
+ issue?: SwarmSettingsIssue;
40
+ canSave: boolean;
41
+ }
42
+
43
+ export type SwarmSettingsLoadResult =
44
+ | (NormalizedSwarmSettings & {
45
+ kind: "missing";
46
+ path: string;
47
+ document: Record<string, unknown>;
48
+ })
49
+ | (NormalizedSwarmSettings & {
50
+ kind: "loaded";
51
+ path: string;
52
+ document: Record<string, unknown>;
53
+ })
54
+ | (NormalizedSwarmSettings & {
55
+ kind: "invalid";
56
+ path: string;
57
+ issue: SwarmSettingsIssue;
58
+ });
59
+
60
+ export interface SwarmSettingsOperations {
61
+ writeFile: typeof writeFile;
62
+ rename: typeof rename;
63
+ }
64
+
65
+ export interface SwarmSettingsRuntime {
66
+ get(): Readonly<SwarmSettingsState>;
67
+ getPath(): string;
68
+ reload(signal?: AbortSignal): Promise<Readonly<SwarmSettingsState>>;
69
+ update(patch: SwarmSettingsPatch): Promise<Readonly<SwarmSettingsState>>;
70
+ flush(): Promise<void>;
71
+ }
72
+
73
+ export interface SwarmSettingsRuntimeOptions {
74
+ path?: string | (() => string);
75
+ operations?: Partial<SwarmSettingsOperations>;
76
+ }
77
+
78
+ const SETTING_FIELDS = [
79
+ "colorPalette",
80
+ "confirmSessionLaunch",
81
+ "externalCommand",
82
+ "pinToLeadWorkspace",
83
+ ] as const satisfies readonly SwarmSettingsField[];
84
+ const SETTING_FIELD_SET = new Set<string>(SETTING_FIELDS);
85
+
86
+ export function swarmSettingsFilePath(): string {
87
+ return join(getAgentDir(), SWARM_SETTINGS_FILE);
88
+ }
89
+
90
+ export function normalizeSwarmSettingsDocument(value: unknown): NormalizedSwarmSettings | undefined {
91
+ if (!isRecord(value)) return undefined;
92
+ const settings: SwarmSettings = { ...DEFAULT_SWARM_SETTINGS };
93
+ const sources = builtInSources();
94
+
95
+ if (Object.hasOwn(value, "colorPalette")) {
96
+ if (value.colorPalette !== "muted" && value.colorPalette !== "bright") return undefined;
97
+ settings.colorPalette = value.colorPalette;
98
+ sources.colorPalette = "user";
99
+ }
100
+ if (Object.hasOwn(value, "confirmSessionLaunch")) {
101
+ if (typeof value.confirmSessionLaunch !== "boolean") return undefined;
102
+ settings.confirmSessionLaunch = value.confirmSessionLaunch;
103
+ sources.confirmSessionLaunch = "user";
104
+ }
105
+ if (Object.hasOwn(value, "externalCommand")) {
106
+ if (typeof value.externalCommand !== "string" || value.externalCommand.trim().length === 0) {
107
+ return undefined;
108
+ }
109
+ settings.externalCommand = value.externalCommand.trim();
110
+ sources.externalCommand = "user";
111
+ }
112
+ if (Object.hasOwn(value, "pinToLeadWorkspace")) {
113
+ if (typeof value.pinToLeadWorkspace !== "boolean") return undefined;
114
+ settings.pinToLeadWorkspace = value.pinToLeadWorkspace;
115
+ sources.pinToLeadWorkspace = "user";
116
+ }
117
+ return { settings, sources };
118
+ }
119
+
120
+ export async function loadSwarmSettings(
121
+ path = swarmSettingsFilePath(),
122
+ signal?: AbortSignal,
123
+ ): Promise<SwarmSettingsLoadResult> {
124
+ let text: string;
125
+ try {
126
+ text = await readSettingsDocument(path, signal);
127
+ } catch (error) {
128
+ if (signal?.aborted) throw error;
129
+ if (isNodeError(error) && error.code === "ENOENT") {
130
+ return {
131
+ kind: "missing",
132
+ path,
133
+ document: {},
134
+ settings: { ...DEFAULT_SWARM_SETTINGS },
135
+ sources: builtInSources(),
136
+ };
137
+ }
138
+ return invalidLoad(path, formatError(error));
139
+ }
140
+
141
+ try {
142
+ const document = JSON.parse(text) as unknown;
143
+ const normalized = normalizeSwarmSettingsDocument(document);
144
+ if (!normalized || !isRecord(document)) {
145
+ return invalidLoad(path, "the document is malformed or contains an invalid setting");
146
+ }
147
+ return { kind: "loaded", path, document, ...normalized };
148
+ } catch (error) {
149
+ return invalidLoad(path, formatError(error));
150
+ }
151
+ }
152
+
153
+ export function createInMemorySwarmSettingsRuntime(): SwarmSettingsRuntime {
154
+ let state: SwarmSettingsState = {
155
+ settings: { ...DEFAULT_SWARM_SETTINGS },
156
+ sources: builtInSources(),
157
+ canSave: true,
158
+ };
159
+ return {
160
+ get: () => freezeState(state),
161
+ getPath: () => "",
162
+ reload: async () => freezeState(state),
163
+ update: async (patch) => {
164
+ const canonical = normalizePatch(patch);
165
+ state = {
166
+ settings: { ...state.settings, ...canonical },
167
+ sources: {
168
+ ...state.sources,
169
+ ...(canonical.colorPalette !== undefined ? { colorPalette: "user" as const } : {}),
170
+ ...(canonical.confirmSessionLaunch !== undefined ? { confirmSessionLaunch: "user" as const } : {}),
171
+ ...(canonical.externalCommand ? { externalCommand: "user" as const } : {}),
172
+ ...(canonical.pinToLeadWorkspace !== undefined ? { pinToLeadWorkspace: "user" as const } : {}),
173
+ },
174
+ canSave: true,
175
+ };
176
+ return freezeState(state);
177
+ },
178
+ flush: async () => undefined,
179
+ };
180
+ }
181
+
182
+ export function createSwarmSettingsRuntime(options: SwarmSettingsRuntimeOptions = {}): SwarmSettingsRuntime {
183
+ let resolvedPath: string | undefined;
184
+ const getPath = () => {
185
+ resolvedPath ??= typeof options.path === "function" ? options.path() : (options.path ?? swarmSettingsFilePath());
186
+ return resolvedPath;
187
+ };
188
+ const operations: SwarmSettingsOperations = {
189
+ writeFile,
190
+ rename,
191
+ ...options.operations,
192
+ };
193
+ let state: SwarmSettingsState = {
194
+ settings: { ...DEFAULT_SWARM_SETTINGS },
195
+ sources: builtInSources(),
196
+ canSave: true,
197
+ };
198
+ let queue = Promise.resolve();
199
+
200
+ const enqueue = <T>(operation: () => Promise<T>): Promise<T> => {
201
+ const result = queue.then(operation, operation);
202
+ queue = result.then(
203
+ () => undefined,
204
+ () => undefined,
205
+ );
206
+ return result;
207
+ };
208
+
209
+ return {
210
+ get: () => freezeState(state),
211
+ getPath,
212
+ reload(signal) {
213
+ return enqueue(async () => {
214
+ const loaded = await loadSwarmSettings(getPath(), signal);
215
+ if (loaded.kind === "invalid") {
216
+ state = { ...state, issue: loaded.issue, canSave: false };
217
+ return freezeState(state);
218
+ }
219
+ state = { settings: loaded.settings, sources: loaded.sources, canSave: true };
220
+ return freezeState(state);
221
+ });
222
+ },
223
+ update(patch) {
224
+ return enqueue(async () => {
225
+ const canonicalPatch = normalizePatch(patch);
226
+ const latest = await loadSwarmSettings(getPath());
227
+ if (latest.kind === "invalid") {
228
+ state = { ...state, issue: latest.issue, canSave: false };
229
+ throw new Error(`Cannot update malformed or invalid settings: ${latest.issue.message}`);
230
+ }
231
+ const document = { ...latest.document, ...canonicalPatch };
232
+ const normalized = normalizeSwarmSettingsDocument(document);
233
+ if (!normalized) throw new Error("Refusing to publish invalid Pi Agent Swarm settings.");
234
+ await publishSettingsDocument(document, getPath(), operations);
235
+ state = { ...normalized, canSave: true };
236
+ return freezeState(state);
237
+ });
238
+ },
239
+ async flush() {
240
+ await queue;
241
+ },
242
+ };
243
+ }
244
+
245
+ function normalizePatch(patch: SwarmSettingsPatch): SwarmSettingsPatch {
246
+ if (!isRecord(patch) || Object.keys(patch).some((key) => !SETTING_FIELD_SET.has(key))) {
247
+ throw new Error("Refusing to update unknown Pi Agent Swarm settings.");
248
+ }
249
+ const normalized = normalizeSwarmSettingsDocument(patch);
250
+ if (!normalized) throw new Error("Refusing to update invalid Pi Agent Swarm settings.");
251
+ const canonical: SwarmSettingsPatch = {};
252
+ for (const field of SETTING_FIELDS) {
253
+ if (Object.hasOwn(patch, field)) assignSetting(canonical, field, normalized.settings[field]);
254
+ }
255
+ return canonical;
256
+ }
257
+
258
+ function assignSetting<K extends SwarmSettingsField>(
259
+ settings: SwarmSettingsPatch,
260
+ field: K,
261
+ value: SwarmSettings[K],
262
+ ): void {
263
+ settings[field] = value;
264
+ }
265
+
266
+ async function publishSettingsDocument(
267
+ document: Record<string, unknown>,
268
+ path: string,
269
+ operations: SwarmSettingsOperations,
270
+ ): Promise<void> {
271
+ const contents = `${JSON.stringify(document, null, "\t")}\n`;
272
+ if (Buffer.byteLength(contents, "utf8") > MAX_SWARM_SETTINGS_BYTES) {
273
+ throw new Error(`settings document exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
274
+ }
275
+ await mkdir(dirname(path), { recursive: true });
276
+ const temporaryPath = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
277
+ try {
278
+ await operations.writeFile(temporaryPath, contents, {
279
+ encoding: "utf8",
280
+ flag: "wx",
281
+ mode: 0o600,
282
+ });
283
+ await operations.rename(temporaryPath, path);
284
+ } finally {
285
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
286
+ }
287
+ }
288
+
289
+ async function readSettingsDocument(path: string, signal?: AbortSignal): Promise<string> {
290
+ throwIfAborted(signal);
291
+ const flags = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0);
292
+ const handle = await open(path, flags);
293
+ try {
294
+ throwIfAborted(signal);
295
+ const [descriptorStats, pathStats] = await Promise.all([handle.stat(), lstat(path)]);
296
+ throwIfAborted(signal);
297
+ if (pathStats.isSymbolicLink()) throw new Error("symbolic links are not accepted");
298
+ if (!descriptorStats.isFile() || !pathStats.isFile()) {
299
+ throw new Error("settings path is not a regular file");
300
+ }
301
+ if (descriptorStats.dev !== pathStats.dev || descriptorStats.ino !== pathStats.ino) {
302
+ throw new Error("settings path changed while it was being opened");
303
+ }
304
+ if (descriptorStats.size > MAX_SWARM_SETTINGS_BYTES) {
305
+ throw new Error(`settings file exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
306
+ }
307
+ const buffer = Buffer.alloc(MAX_SWARM_SETTINGS_BYTES + 1);
308
+ let offset = 0;
309
+ while (offset < buffer.length) {
310
+ const result = await handle.read(buffer, offset, buffer.length - offset, offset);
311
+ throwIfAborted(signal);
312
+ if (result.bytesRead === 0) break;
313
+ offset += result.bytesRead;
314
+ }
315
+ if (offset > MAX_SWARM_SETTINGS_BYTES) {
316
+ throw new Error(`settings file exceeds ${MAX_SWARM_SETTINGS_BYTES} bytes`);
317
+ }
318
+ try {
319
+ return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, offset));
320
+ } catch {
321
+ throw new Error("settings file is not valid UTF-8");
322
+ }
323
+ } finally {
324
+ await handle.close();
325
+ }
326
+ }
327
+
328
+ function throwIfAborted(signal?: AbortSignal): void {
329
+ if (signal?.aborted) throw signal.reason;
330
+ }
331
+
332
+ function invalidLoad(path: string, reason: string): SwarmSettingsLoadResult {
333
+ return {
334
+ kind: "invalid",
335
+ path,
336
+ settings: { ...DEFAULT_SWARM_SETTINGS },
337
+ sources: builtInSources(),
338
+ issue: { kind: "invalid", message: `${SWARM_SETTINGS_FILE} ignored (${path}: ${reason})` },
339
+ };
340
+ }
341
+
342
+ function builtInSources(): Record<SwarmSettingsField, SwarmSettingsSource> {
343
+ return {
344
+ colorPalette: "built-in",
345
+ confirmSessionLaunch: "built-in",
346
+ externalCommand: "built-in",
347
+ pinToLeadWorkspace: "built-in",
348
+ };
349
+ }
350
+
351
+ function freezeState(state: SwarmSettingsState): Readonly<SwarmSettingsState> {
352
+ return Object.freeze({
353
+ ...state,
354
+ settings: Object.freeze({ ...state.settings }),
355
+ sources: Object.freeze({ ...state.sources }),
356
+ });
357
+ }
358
+
359
+ function isRecord(value: unknown): value is Record<string, unknown> {
360
+ return typeof value === "object" && value !== null && !Array.isArray(value);
361
+ }
362
+
363
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
364
+ return error instanceof Error && "code" in error;
365
+ }
366
+
367
+ function formatError(error: unknown): string {
368
+ return error instanceof Error ? error.message : String(error);
369
+ }