@narumitw/pi-herdr 0.1.1 → 0.3.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.
@@ -1,281 +1,268 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { EditorStatusWidget } from "@narumitw/pi-tui-kit/editor-status-widget";
3
3
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
4
- import type {
5
- HerdrAgentStatus,
6
- HerdrPane,
7
- HerdrPaneEvent,
8
- HerdrWorkspace,
9
- } from "./herdr-protocol.js";
4
+ import type { HerdrAgentStatus, HerdrPane, HerdrPaneEvent, HerdrWorkspace } from "./herdr-protocol.js";
10
5
 
11
6
  export const HERDR_WIDGET_KEY = "herdr:agents";
12
7
  export const MAX_HERDR_WIDGET_AGENTS = 5;
13
8
 
14
9
  interface ObservedPane {
15
- paneId: string;
16
- workspaceId: string;
17
- agent?: string;
18
- agentName?: string;
19
- agentStatus: HerdrAgentStatus;
20
- displayAgent?: string;
21
- label?: string;
22
- stateLabels: Record<string, string>;
23
- title?: string;
10
+ paneId: string;
11
+ workspaceId: string;
12
+ agent?: string;
13
+ agentName?: string;
14
+ agentStatus: HerdrAgentStatus;
15
+ displayAgent?: string;
16
+ label?: string;
17
+ stateLabels: Record<string, string>;
18
+ title?: string;
24
19
  }
25
20
 
26
21
  export interface HerdrWidgetRow {
27
- agent: string;
28
- pane: string;
29
- paneId: string;
30
- space: string;
31
- state: HerdrAgentStatus;
32
- stateLabel: string;
22
+ agent: string;
23
+ pane: string;
24
+ paneId: string;
25
+ space: string;
26
+ state: HerdrAgentStatus;
27
+ stateLabel: string;
33
28
  }
34
29
 
35
30
  export interface HerdrWidgetSnapshot {
36
- totalAgents: number;
37
- hiddenAgents: number;
38
- rows: readonly HerdrWidgetRow[];
31
+ totalAgents: number;
32
+ hiddenAgents: number;
33
+ rows: readonly HerdrWidgetRow[];
39
34
  }
40
35
 
41
36
  const STATE_ORDER: Record<HerdrAgentStatus, number> = {
42
- blocked: 0,
43
- done: 1,
44
- working: 2,
45
- idle: 3,
46
- unknown: 4,
37
+ blocked: 0,
38
+ done: 1,
39
+ working: 2,
40
+ idle: 3,
41
+ unknown: 4,
47
42
  };
48
43
 
49
44
  function observedPane(pane: HerdrPane): ObservedPane {
50
- return {
51
- paneId: pane.paneId,
52
- workspaceId: pane.workspaceId,
53
- agent: pane.agent,
54
- agentName: pane.agentName,
55
- agentStatus: pane.agentStatus,
56
- displayAgent: pane.displayAgent,
57
- label: pane.label,
58
- stateLabels: { ...pane.stateLabels },
59
- title: pane.title,
60
- };
45
+ return {
46
+ paneId: pane.paneId,
47
+ workspaceId: pane.workspaceId,
48
+ agent: pane.agent,
49
+ agentName: pane.agentName,
50
+ agentStatus: pane.agentStatus,
51
+ displayAgent: pane.displayAgent,
52
+ label: pane.label,
53
+ stateLabels: { ...pane.stateLabels },
54
+ title: pane.title,
55
+ };
61
56
  }
62
57
 
63
58
  function safeDisplay(value: string | undefined): string | undefined {
64
- if (value === undefined) return undefined;
65
- const safe = sanitizeTerminalText(value).trim();
66
- return safe.length > 0 ? safe : undefined;
59
+ if (value === undefined) return undefined;
60
+ const safe = sanitizeTerminalText(value).trim();
61
+ return safe.length > 0 ? safe : undefined;
67
62
  }
68
63
 
69
64
  function shortIdentity(value: string, fallback: string): string {
70
- const safe = safeDisplay(value);
71
- if (!safe) return fallback;
72
- return safe.split(":").at(-1) || fallback;
65
+ const safe = safeDisplay(value);
66
+ if (!safe) return fallback;
67
+ return safe.split(":").at(-1) || fallback;
73
68
  }
74
69
 
75
70
  function agentDisplay(pane: ObservedPane): string {
76
- return (
77
- safeDisplay(pane.agentName) ??
78
- safeDisplay(pane.displayAgent) ??
79
- safeDisplay(pane.agent) ??
80
- "agent"
81
- );
71
+ return safeDisplay(pane.agentName) ?? safeDisplay(pane.displayAgent) ?? safeDisplay(pane.agent) ?? "agent";
82
72
  }
83
73
 
84
74
  function paneDisplay(pane: ObservedPane): string {
85
- const id = shortIdentity(pane.paneId, "pane");
86
- const label = safeDisplay(pane.label) ?? safeDisplay(pane.title);
87
- return label ? `${label}/${id}` : id;
75
+ const id = shortIdentity(pane.paneId, "pane");
76
+ const label = safeDisplay(pane.label) ?? safeDisplay(pane.title);
77
+ return label ? `${label}/${id}` : id;
88
78
  }
89
79
 
90
80
  function spaceDisplay(workspace: HerdrWorkspace): string {
91
- const id = shortIdentity(workspace.workspaceId, "space");
92
- const label = safeDisplay(workspace.label);
93
- return label ? `${label}/${id}` : id;
81
+ const id = shortIdentity(workspace.workspaceId, "space");
82
+ const label = safeDisplay(workspace.label);
83
+ return label ? `${label}/${id}` : id;
94
84
  }
95
85
 
96
86
  function rowForPane(pane: ObservedPane, workspace: HerdrWorkspace): HerdrWidgetRow {
97
- return {
98
- agent: agentDisplay(pane),
99
- pane: paneDisplay(pane),
100
- paneId: safeDisplay(pane.paneId) ?? "pane",
101
- space: spaceDisplay(workspace),
102
- state: pane.agentStatus,
103
- stateLabel:
104
- safeDisplay(pane.stateLabels[pane.agentStatus]) ?? safeDisplay(pane.agentStatus) ?? "unknown",
105
- };
87
+ return {
88
+ agent: agentDisplay(pane),
89
+ pane: paneDisplay(pane),
90
+ paneId: safeDisplay(pane.paneId) ?? "pane",
91
+ space: spaceDisplay(workspace),
92
+ state: pane.agentStatus,
93
+ stateLabel: safeDisplay(pane.stateLabels[pane.agentStatus]) ?? safeDisplay(pane.agentStatus) ?? "unknown",
94
+ };
106
95
  }
107
96
 
108
97
  function immutableSnapshot(rows: HerdrWidgetRow[]): HerdrWidgetSnapshot | undefined {
109
- if (rows.length === 0) return undefined;
110
- const visible = rows.slice(0, MAX_HERDR_WIDGET_AGENTS).map((row) => Object.freeze({ ...row }));
111
- return Object.freeze({
112
- totalAgents: rows.length,
113
- hiddenAgents: Math.max(0, rows.length - visible.length),
114
- rows: Object.freeze(visible),
115
- });
98
+ if (rows.length === 0) return undefined;
99
+ const visible = rows.slice(0, MAX_HERDR_WIDGET_AGENTS).map((row) => Object.freeze({ ...row }));
100
+ return Object.freeze({
101
+ totalAgents: rows.length,
102
+ hiddenAgents: Math.max(0, rows.length - visible.length),
103
+ rows: Object.freeze(visible),
104
+ });
116
105
  }
117
106
 
118
107
  export class HerdrWidgetModel {
119
- private currentPaneId: string | undefined;
120
- private currentWorkspaceId: string | undefined;
121
- private workspace: HerdrWorkspace | undefined;
122
- private panes = new Map<string, ObservedPane>();
108
+ private currentPaneId: string | undefined;
109
+ private currentWorkspaceId: string | undefined;
110
+ private workspace: HerdrWorkspace | undefined;
111
+ private panes = new Map<string, ObservedPane>();
123
112
 
124
- reset(
125
- currentPane: HerdrPane,
126
- panes: readonly HerdrPane[],
127
- workspace: HerdrWorkspace = { workspaceId: currentPane.workspaceId },
128
- ): void {
129
- this.currentPaneId = currentPane.paneId;
130
- this.currentWorkspaceId = currentPane.workspaceId;
131
- this.workspace = { ...workspace };
132
- this.panes = new Map(panes.map((pane) => [pane.paneId, observedPane(pane)]));
133
- }
113
+ reset(
114
+ currentPane: HerdrPane,
115
+ panes: readonly HerdrPane[],
116
+ workspace: HerdrWorkspace = { workspaceId: currentPane.workspaceId },
117
+ ): void {
118
+ this.currentPaneId = currentPane.paneId;
119
+ this.currentWorkspaceId = currentPane.workspaceId;
120
+ this.workspace = { ...workspace };
121
+ this.panes = new Map(panes.map((pane) => [pane.paneId, observedPane(pane)]));
122
+ }
134
123
 
135
- clear(): void {
136
- this.currentPaneId = undefined;
137
- this.currentWorkspaceId = undefined;
138
- this.workspace = undefined;
139
- this.panes.clear();
140
- }
124
+ clear(): void {
125
+ this.currentPaneId = undefined;
126
+ this.currentWorkspaceId = undefined;
127
+ this.workspace = undefined;
128
+ this.panes.clear();
129
+ }
141
130
 
142
- isCurrentPane(paneId: string): boolean {
143
- return this.currentPaneId === paneId;
144
- }
131
+ isCurrentPane(paneId: string): boolean {
132
+ return this.currentPaneId === paneId;
133
+ }
145
134
 
146
- isCurrentWorkspace(workspaceId: string): boolean {
147
- return this.currentWorkspaceId === workspaceId;
148
- }
135
+ isCurrentWorkspace(workspaceId: string): boolean {
136
+ return this.currentWorkspaceId === workspaceId;
137
+ }
149
138
 
150
- apply(event: HerdrPaneEvent): void {
151
- if (event.type === "created") {
152
- this.panes.set(event.pane.paneId, observedPane(event.pane));
153
- return;
154
- }
155
- if (event.type === "closed" || event.type === "exited") {
156
- this.panes.delete(event.paneId);
157
- return;
158
- }
159
- if (event.type === "moved") {
160
- this.panes.delete(event.previousPaneId);
161
- this.panes.set(event.pane.paneId, observedPane(event.pane));
162
- if (this.currentPaneId === event.previousPaneId) {
163
- this.currentPaneId = event.pane.paneId;
164
- this.currentWorkspaceId = event.pane.workspaceId;
165
- this.workspace = { workspaceId: event.pane.workspaceId };
166
- }
167
- return;
168
- }
139
+ apply(event: HerdrPaneEvent): void {
140
+ if (event.type === "created") {
141
+ this.panes.set(event.pane.paneId, observedPane(event.pane));
142
+ return;
143
+ }
144
+ if (event.type === "closed" || event.type === "exited") {
145
+ this.panes.delete(event.paneId);
146
+ return;
147
+ }
148
+ if (event.type === "moved") {
149
+ this.panes.delete(event.previousPaneId);
150
+ this.panes.set(event.pane.paneId, observedPane(event.pane));
151
+ if (this.currentPaneId === event.previousPaneId) {
152
+ this.currentPaneId = event.pane.paneId;
153
+ this.currentWorkspaceId = event.pane.workspaceId;
154
+ this.workspace = { workspaceId: event.pane.workspaceId };
155
+ }
156
+ return;
157
+ }
169
158
 
170
- const existing = this.panes.get(event.paneId);
171
- if (event.type === "agent_detected") {
172
- if (event.released || !event.agent) {
173
- if (existing) this.panes.set(event.paneId, { ...existing, agent: undefined });
174
- return;
175
- }
176
- this.panes.set(event.paneId, {
177
- ...(existing ?? {
178
- paneId: event.paneId,
179
- workspaceId: event.workspaceId,
180
- agentStatus: event.finalStatus ?? "unknown",
181
- stateLabels: {},
182
- }),
183
- agent: event.agent,
184
- agentStatus: event.finalStatus ?? existing?.agentStatus ?? "unknown",
185
- });
186
- return;
187
- }
188
- if (event.type !== "agent_status_changed") return;
159
+ const existing = this.panes.get(event.paneId);
160
+ if (event.type === "agent_detected") {
161
+ if (event.released || !event.agent) {
162
+ if (existing) this.panes.set(event.paneId, { ...existing, agent: undefined });
163
+ return;
164
+ }
165
+ this.panes.set(event.paneId, {
166
+ ...(existing ?? {
167
+ paneId: event.paneId,
168
+ workspaceId: event.workspaceId,
169
+ agentStatus: event.finalStatus ?? "unknown",
170
+ stateLabels: {},
171
+ }),
172
+ agent: event.agent,
173
+ agentStatus: event.finalStatus ?? existing?.agentStatus ?? "unknown",
174
+ });
175
+ return;
176
+ }
177
+ if (event.type !== "agent_status_changed") return;
189
178
 
190
- this.panes.set(event.paneId, {
191
- ...(existing ?? {
192
- paneId: event.paneId,
193
- workspaceId: event.workspaceId,
194
- stateLabels: {},
195
- }),
196
- agent: event.agent ?? existing?.agent,
197
- agentStatus: event.agentStatus,
198
- displayAgent: event.displayAgent ?? existing?.displayAgent,
199
- stateLabels: event.stateLabels ?? existing?.stateLabels ?? {},
200
- title: event.title ?? existing?.title,
201
- });
202
- }
179
+ this.panes.set(event.paneId, {
180
+ ...(existing ?? {
181
+ paneId: event.paneId,
182
+ workspaceId: event.workspaceId,
183
+ stateLabels: {},
184
+ }),
185
+ agent: event.agent ?? existing?.agent,
186
+ agentStatus: event.agentStatus,
187
+ displayAgent: event.displayAgent ?? existing?.displayAgent,
188
+ stateLabels: event.stateLabels ?? existing?.stateLabels ?? {},
189
+ title: event.title ?? existing?.title,
190
+ });
191
+ }
203
192
 
204
- snapshot(): HerdrWidgetSnapshot | undefined {
205
- if (!this.currentPaneId || !this.currentWorkspaceId || !this.workspace) return undefined;
206
- const rows = [...this.panes.values()]
207
- .filter(
208
- (pane) =>
209
- pane.workspaceId === this.currentWorkspaceId &&
210
- pane.paneId !== this.currentPaneId &&
211
- pane.agent !== undefined,
212
- )
213
- .map((pane) => rowForPane(pane, this.workspace as HerdrWorkspace));
214
- rows.sort(
215
- (left, right) =>
216
- STATE_ORDER[left.state] - STATE_ORDER[right.state] ||
217
- left.agent.localeCompare(right.agent) ||
218
- left.pane.localeCompare(right.pane) ||
219
- left.paneId.localeCompare(right.paneId),
220
- );
221
- return immutableSnapshot(rows);
222
- }
193
+ snapshot(): HerdrWidgetSnapshot | undefined {
194
+ if (!this.currentPaneId || !this.currentWorkspaceId || !this.workspace) return undefined;
195
+ const rows = [...this.panes.values()]
196
+ .filter(
197
+ (pane) =>
198
+ pane.workspaceId === this.currentWorkspaceId &&
199
+ pane.paneId !== this.currentPaneId &&
200
+ pane.agent !== undefined,
201
+ )
202
+ .map((pane) => rowForPane(pane, this.workspace as HerdrWorkspace));
203
+ rows.sort(
204
+ (left, right) =>
205
+ STATE_ORDER[left.state] - STATE_ORDER[right.state] ||
206
+ left.agent.localeCompare(right.agent) ||
207
+ left.pane.localeCompare(right.pane) ||
208
+ left.paneId.localeCompare(right.paneId),
209
+ );
210
+ return immutableSnapshot(rows);
211
+ }
223
212
  }
224
213
 
225
214
  function stateStyle(theme: Theme, state: HerdrAgentStatus, text: string): string {
226
- switch (state) {
227
- case "blocked":
228
- return theme.fg("error", text);
229
- case "done":
230
- return theme.fg("accent", text);
231
- case "working":
232
- return theme.fg("warning", text);
233
- case "idle":
234
- return theme.fg("success", text);
235
- case "unknown":
236
- return theme.fg("dim", text);
237
- }
215
+ switch (state) {
216
+ case "blocked":
217
+ return theme.fg("error", text);
218
+ case "done":
219
+ return theme.fg("accent", text);
220
+ case "working":
221
+ return theme.fg("warning", text);
222
+ case "idle":
223
+ return theme.fg("success", text);
224
+ case "unknown":
225
+ return theme.fg("dim", text);
226
+ }
238
227
  }
239
228
 
240
229
  function stateSymbol(state: HerdrAgentStatus): string {
241
- switch (state) {
242
- case "blocked":
243
- return "×";
244
- case "done":
245
- return "✓";
246
- case "working":
247
- return "◐";
248
- case "idle":
249
- return "○";
250
- case "unknown":
251
- return "·";
252
- }
230
+ switch (state) {
231
+ case "blocked":
232
+ return "×";
233
+ case "done":
234
+ return "✓";
235
+ case "working":
236
+ return "◐";
237
+ case "idle":
238
+ return "○";
239
+ case "unknown":
240
+ return "·";
241
+ }
253
242
  }
254
243
 
255
244
  export function createHerdrWidget(snapshot: HerdrWidgetSnapshot, theme: Theme): EditorStatusWidget {
256
- return new EditorStatusWidget({
257
- theme,
258
- renderBody() {
259
- const noun = snapshot.totalAgents === 1 ? "agent" : "agents";
260
- const lines = [theme.fg("muted", `Herdr · ${snapshot.totalAgents} sibling ${noun}`)];
261
- const separator = theme.fg("dim", " · ");
262
- for (const row of snapshot.rows) {
263
- const state = stateStyle(theme, row.state, `${stateSymbol(row.state)} ${row.stateLabel}`);
264
- const agent = theme.bold(theme.fg("text", row.agent));
265
- const pane = theme.fg("muted", row.pane);
266
- const space = theme.fg("dim", row.space);
267
- lines.push(`${state} ${agent}${separator}${pane}${separator}${space}`);
268
- }
269
- if (snapshot.hiddenAgents > 0) {
270
- lines.push(theme.fg("dim", `+${snapshot.hiddenAgents} more`));
271
- }
272
- return lines;
273
- },
274
- });
245
+ return new EditorStatusWidget({
246
+ theme,
247
+ renderBody() {
248
+ const noun = snapshot.totalAgents === 1 ? "agent" : "agents";
249
+ const lines = [theme.fg("muted", `Herdr · ${snapshot.totalAgents} sibling ${noun}`)];
250
+ const separator = theme.fg("dim", " · ");
251
+ for (const row of snapshot.rows) {
252
+ const state = stateStyle(theme, row.state, `${stateSymbol(row.state)} ${row.stateLabel}`);
253
+ const agent = theme.bold(theme.fg("text", row.agent));
254
+ const pane = theme.fg("muted", row.pane);
255
+ const space = theme.fg("dim", row.space);
256
+ lines.push(`${state} ${agent}${separator}${pane}${separator}${space}`);
257
+ }
258
+ if (snapshot.hiddenAgents > 0) {
259
+ lines.push(theme.fg("dim", `+${snapshot.hiddenAgents} more`));
260
+ }
261
+ return lines;
262
+ },
263
+ });
275
264
  }
276
265
 
277
- export function herdrWidgetFingerprint(
278
- snapshot: HerdrWidgetSnapshot | undefined,
279
- ): string | undefined {
280
- return snapshot ? JSON.stringify(snapshot) : undefined;
266
+ export function herdrWidgetFingerprint(snapshot: HerdrWidgetSnapshot | undefined): string | undefined {
267
+ return snapshot ? JSON.stringify(snapshot) : undefined;
281
268
  }
@@ -0,0 +1,188 @@
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
+
7
+ export const HERDR_SETTINGS_FILE = "pi-herdr.json";
8
+ const MAX_SETTINGS_BYTES = 64 * 1024;
9
+
10
+ export interface HerdrSettings {
11
+ widget: boolean;
12
+ }
13
+
14
+ export type HerdrSettingsLoadResult =
15
+ | { kind: "missing"; settings: HerdrSettings }
16
+ | { kind: "invalid"; reason: string; settings: HerdrSettings }
17
+ | { kind: "loaded"; settings: HerdrSettings };
18
+
19
+ export interface UpdateHerdrSettingsOptions {
20
+ settingsPath?: string;
21
+ beforeRename?: (temporaryPath: string, settingsPath: string) => Promise<void>;
22
+ }
23
+
24
+ type SettingsDocument = Record<string, unknown>;
25
+ const DEFAULT_SETTINGS: HerdrSettings = { widget: true };
26
+ const queues = new Map<string, Promise<void>>();
27
+
28
+ export function herdrSettingsPath(): string {
29
+ return join(getAgentDir(), HERDR_SETTINGS_FILE);
30
+ }
31
+
32
+ export function normalizeHerdrSettings(value: unknown): HerdrSettings | undefined {
33
+ if (!isRecord(value)) return undefined;
34
+ if (Object.hasOwn(value, "widget") && typeof value.widget !== "boolean") {
35
+ return undefined;
36
+ }
37
+ return {
38
+ widget: typeof value.widget === "boolean" ? value.widget : DEFAULT_SETTINGS.widget,
39
+ };
40
+ }
41
+
42
+ export function readHerdrSettings(settingsPath = herdrSettingsPath()): Promise<HerdrSettingsLoadResult> {
43
+ return enqueue(settingsPath, async () => {
44
+ let document: SettingsDocument;
45
+ try {
46
+ document = await readSettingsDocument(settingsPath);
47
+ } catch (error) {
48
+ if (isNodeError(error) && error.code === "ENOENT") {
49
+ return { kind: "missing", settings: { ...DEFAULT_SETTINGS } };
50
+ }
51
+ return {
52
+ kind: "invalid",
53
+ reason: `${settingsPath}: ${safeError(error)}`,
54
+ settings: { ...DEFAULT_SETTINGS },
55
+ };
56
+ }
57
+ const settings = normalizeHerdrSettings(document);
58
+ return settings
59
+ ? { kind: "loaded", settings }
60
+ : {
61
+ kind: "invalid",
62
+ reason: `${settingsPath}: invalid settings shape`,
63
+ settings: { ...DEFAULT_SETTINGS },
64
+ };
65
+ });
66
+ }
67
+
68
+ export function updateHerdrSettings(
69
+ patch: Partial<HerdrSettings>,
70
+ options: UpdateHerdrSettingsOptions = {},
71
+ ): Promise<HerdrSettings> {
72
+ const settingsPath = options.settingsPath ?? herdrSettingsPath();
73
+ return enqueue(settingsPath, async () => {
74
+ const current = await readDocumentForUpdate(settingsPath);
75
+ const updated = { ...current, ...patch };
76
+ const settings = normalizeHerdrSettings(updated);
77
+ if (!settings) throw new Error(`Pi Herdr settings at ${settingsPath} have an invalid shape.`);
78
+ await publishSettings(settingsPath, updated, options);
79
+ return settings;
80
+ });
81
+ }
82
+
83
+ export async function awaitHerdrSettingsWrites(settingsPath = herdrSettingsPath()): Promise<void> {
84
+ await queues.get(settingsPath);
85
+ }
86
+
87
+ function enqueue<T>(path: string, operation: () => Promise<T>): Promise<T> {
88
+ const previous = queues.get(path) ?? Promise.resolve();
89
+ const result = previous.then(operation, operation);
90
+ const settled = result.then(
91
+ () => undefined,
92
+ () => undefined,
93
+ );
94
+ queues.set(path, settled);
95
+ void settled.finally(() => {
96
+ if (queues.get(path) === settled) queues.delete(path);
97
+ });
98
+ return result;
99
+ }
100
+
101
+ async function readDocumentForUpdate(path: string): Promise<SettingsDocument> {
102
+ try {
103
+ const document = await readSettingsDocument(path);
104
+ if (!normalizeHerdrSettings(document)) throw new Error("invalid settings shape");
105
+ return document;
106
+ } catch (error) {
107
+ if (isNodeError(error) && error.code === "ENOENT") return {};
108
+ throw new Error(`Pi Herdr settings at ${path} are invalid: ${safeError(error)}`);
109
+ }
110
+ }
111
+
112
+ async function readSettingsDocument(path: string): Promise<SettingsDocument> {
113
+ const pathStats = await lstat(path);
114
+ if (pathStats.isSymbolicLink() || !pathStats.isFile()) {
115
+ throw new Error("settings path is not a regular file");
116
+ }
117
+ if (pathStats.size > MAX_SETTINGS_BYTES) {
118
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
119
+ }
120
+ const noFollow = constants.O_NOFOLLOW ?? 0;
121
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | noFollow);
122
+ try {
123
+ const stats = await handle.stat();
124
+ if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
125
+ throw new Error("settings path changed while opening");
126
+ }
127
+ const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
128
+ let offset = 0;
129
+ while (offset < buffer.length) {
130
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
131
+ if (bytesRead === 0) break;
132
+ offset += bytesRead;
133
+ }
134
+ if (offset > MAX_SETTINGS_BYTES) {
135
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
136
+ }
137
+ let contents: string;
138
+ try {
139
+ contents = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));
140
+ } catch {
141
+ throw new Error("settings file is not valid UTF-8");
142
+ }
143
+ let parsed: unknown;
144
+ try {
145
+ parsed = JSON.parse(contents) as unknown;
146
+ } catch {
147
+ throw new Error("invalid JSON");
148
+ }
149
+ if (!isRecord(parsed)) throw new Error("settings document must be a JSON object");
150
+ return parsed;
151
+ } finally {
152
+ await handle.close();
153
+ }
154
+ }
155
+
156
+ async function publishSettings(
157
+ path: string,
158
+ document: SettingsDocument,
159
+ options: UpdateHerdrSettingsOptions,
160
+ ): Promise<void> {
161
+ const contents = `${JSON.stringify(document, null, 2)}\n`;
162
+ if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
163
+ throw new Error(`Pi Herdr settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
164
+ }
165
+ const directory = dirname(path);
166
+ await mkdir(directory, { recursive: true });
167
+ const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
168
+ try {
169
+ await writeFile(temporaryPath, contents, { encoding: "utf8", flag: "wx", mode: 0o600 });
170
+ await options.beforeRename?.(temporaryPath, path);
171
+ await rename(temporaryPath, path);
172
+ } catch (error) {
173
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
174
+ throw error;
175
+ }
176
+ }
177
+
178
+ function isRecord(value: unknown): value is SettingsDocument {
179
+ return typeof value === "object" && value !== null && !Array.isArray(value);
180
+ }
181
+
182
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
183
+ return error instanceof Error && "code" in error;
184
+ }
185
+
186
+ function safeError(error: unknown): string {
187
+ return error instanceof Error ? error.message : String(error);
188
+ }