@narumitw/pi-herdr 0.1.1 → 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.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Connect Pi's interactive lifecycle to Herdr and bootstrap the operating guidance
8
8
 
9
9
  - Reports Pi session identity and `working`, `blocked`, and `idle` lifecycle states to the current Herdr pane.
10
10
  - Publishes bounded `model`, `provider`, `thinking`, `session`, and `context_usage` tokens for Herdr sidebar rows.
11
- - Shows recognized sibling agents from the current Herdr workspace in a passive widget above Pi's editor.
11
+ - Shows recognized sibling agents from the current Herdr workspace in a passive widget above Pi's editor, with a saved visibility toggle in `/herdr`.
12
12
  - Updates the widget from Herdr pane lifecycle and agent-status events without polling the CLI.
13
13
  - Coalesces rapid state changes and retries short-lived local socket failures without interrupting Pi.
14
14
  - Derives blocked state from Pi's public `ui_prompt_start` and `ui_prompt_end` lifecycle events.
@@ -56,6 +56,31 @@ rm -rf ~/.agents/skills/herdr
56
56
 
57
57
  Run `/reload` or restart Pi after changing the installed resources.
58
58
 
59
+ ## 💬 Commands
60
+
61
+ `/herdr` opens a menu to toggle the agent widget and view status or help, inspired by `/tool`.
62
+ It accepts no arguments and is available inside Herdr in TUI and RPC modes; print and JSON modes reject it.
63
+ RPC can save the preference but does not display the widget.
64
+ Changes apply immediately and closing the menu does not undo saved changes.
65
+
66
+ ## ⚙️ Settings
67
+
68
+ Toggle **Agent widget** in `/herdr`, or edit `<getAgentDir()>/pi-herdr.json` (normally `~/.pi/agent/pi-herdr.json`):
69
+
70
+ ```json
71
+ {
72
+ "widget": false
73
+ }
74
+ ```
75
+
76
+ `widget` accepts only `true` or `false` and defaults to `true` when absent.
77
+ Only user settings are supported; project files are not read.
78
+ Manual edits apply after `/reload` or the next session start.
79
+ Missing files are not created until an explicit save. Invalid files trigger a warning, use defaults, and block saves until repaired.
80
+ Saves preserve unknown fields and use atomic temporary-file-plus-rename publication, with reads and writes ordered within one Pi process, not across processes.
81
+ Failed saves restore the previous effective value and leave the existing file untouched.
82
+ Turning the widget off closes its subscription and pending requests without disabling lifecycle or metadata reporting.
83
+
59
84
  ## 🔄 Lifecycle reporting
60
85
 
61
86
  The extension reports only interactive TUI sessions because Herdr displays agents attached to terminal panes.
@@ -135,7 +160,7 @@ Command recipes, approval handling, and other operating safety rules come from t
135
160
  ## 🚧 Limitations
136
161
 
137
162
  - Lifecycle reporting, metadata reporting, and the agent widget are disabled in RPC, JSON, and print modes.
138
- - The widget has no settings for placement, workspace scope, visibility, or row count.
163
+ - The widget has no settings for placement, workspace scope, or row count.
139
164
  - The widget cannot show blocked prompt text because Herdr does not expose it through public pane responses.
140
165
  - Herdr exposes no rename event, so agent and pane renames appear after the next topology refresh, reconnect, Pi `/reload`, or session start rather than immediately.
141
166
  - Integration requires a running compatible Herdr session and valid injected environment variables.
@@ -147,27 +172,11 @@ Command recipes, approval handling, and other operating safety rules come from t
147
172
 
148
173
  ```text
149
174
  packages/pi-herdr/
150
- ├── skills/herdr/
151
- │ └── SKILL.md # Thin bootstrap for CLI-owned operating guidance
152
- ├── src/
153
- │ ├── index.ts # Thin Pi entrypoint
154
- │ ├── herdr-agent-state.ts # Pi lifecycle and integration ownership
155
- │ ├── herdr-client.ts # Bounded Herdr socket transport
156
- │ ├── herdr-metadata.ts # Token normalization and request helpers
157
- │ ├── herdr-observer.ts # Read-only event subscription lifecycle
158
- │ ├── herdr-protocol.ts # Narrow response and event validation
159
- │ └── herdr-widget.ts # Agent state model and presentation
160
- ├── test/
161
- │ ├── herdr-agent-state.test.ts
162
- │ ├── herdr-client.test.ts
163
- │ ├── herdr-metadata.test.ts
164
- │ ├── herdr-observer.test.ts
165
- │ ├── herdr-skill.test.ts
166
- │ └── herdr-widget.test.ts
167
- ├── package.json # Pi extension and skill declarations
168
- ├── tsconfig.json
169
- ├── README.md
170
- └── LICENSE
175
+ ├── src/ # Authoritative implementation and helpers
176
+ │ ├── index.ts # Thin Pi entrypoint
177
+ │ └── herdr-agent-state.ts # Herdr lifecycle integration
178
+ ├── skills/herdr/ # Published bootstrap for CLI-owned guidance
179
+ └── test/ # Behavior and lifecycle coverage
171
180
  ```
172
181
 
173
182
  ## 🔎 Keywords
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-herdr",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Herdr agent-state integration and operating skill for Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,9 +41,9 @@
41
41
  },
42
42
  "devDependencies": {
43
43
  "@biomejs/biome": "2.5.11",
44
- "@earendil-works/pi-coding-agent": "0.84.4",
45
- "@earendil-works/pi-tui": "0.84.4",
46
- "@types/node": "26.4.0",
44
+ "@earendil-works/pi-coding-agent": "0.85.0",
45
+ "@earendil-works/pi-tui": "0.85.0",
46
+ "@types/node": "26.4.1",
47
47
  "typescript": "7.0.2"
48
48
  },
49
49
  "repository": {
@@ -11,6 +11,11 @@ import {
11
11
  } from "./herdr-metadata.js";
12
12
  import { createHerdrWidgetObserver, type HerdrWidgetObserver } from "./herdr-observer.js";
13
13
 
14
+ import {
15
+ createHerdrSettingsController,
16
+ type HerdrSettingsOptions,
17
+ } from "./herdr-settings-controller.js";
18
+
14
19
  const SOURCE = "herdr:pi";
15
20
 
16
21
  export type AgentState = "working" | "blocked" | "idle";
@@ -35,7 +40,7 @@ interface QueuedMetadata {
35
40
  generation: number;
36
41
  }
37
42
 
38
- export interface HerdrAgentStateOptions {
43
+ export interface HerdrAgentStateOptions extends HerdrSettingsOptions {
39
44
  environment?: HerdrEnvironment;
40
45
  now?: () => number;
41
46
  random?: () => number;
@@ -89,6 +94,7 @@ export function createHerdrAgentStateExtension(
89
94
 
90
95
  return function herdrAgentState(pi: ExtensionAPI): void {
91
96
  if (!environment.enabled) return;
97
+ const widget = createHerdrSettingsController(pi, widgetObserver, options);
92
98
 
93
99
  let sessionGeneration = 0;
94
100
  let sessionController = new AbortController();
@@ -340,18 +346,21 @@ export function createHerdrAgentStateExtension(
340
346
  sessionController = new AbortController();
341
347
  activeSession = ctx.sessionManager;
342
348
  rootSession = ctx.mode === "tui";
343
- if (rootSession) widgetObserver.start(ctx);
349
+ const widgetStart = widget.start(ctx);
344
350
  agentActive = false;
345
351
  blockedCount = 0;
346
352
  blockedMessage = undefined;
347
353
  lastState = undefined;
348
354
  lastMessage = undefined;
349
- if (!rootSession) return;
355
+ if (!rootSession) {
356
+ await widgetStart;
357
+ return;
358
+ }
350
359
 
351
360
  updateSessionRef(ctx);
352
361
  const sessionReport = reportSession(event.reason);
353
362
  publishMetadata(ctx);
354
- await sessionReport;
363
+ await Promise.all([sessionReport, widgetStart]);
355
364
  if (generation !== sessionGeneration || sessionController.signal.aborted || !rootSession) {
356
365
  return;
357
366
  }
@@ -382,7 +391,7 @@ export function createHerdrAgentStateExtension(
382
391
 
383
392
  pi.on("session_shutdown", async (_event, ctx) => {
384
393
  if (ctx.sessionManager !== activeSession) {
385
- await Promise.allSettled([widgetObserver.shutdown(ctx)]);
394
+ await Promise.allSettled([widget.shutdown(ctx)]);
386
395
  return;
387
396
  }
388
397
  if (shutdownTask && shutdownSession === ctx.sessionManager) {
@@ -400,7 +409,7 @@ export function createHerdrAgentStateExtension(
400
409
  sessionController.abort(new DOMException("Herdr session shut down", "AbortError"));
401
410
  queuedState = undefined;
402
411
  queuedMetadata = undefined;
403
- await Promise.allSettled([drainTask, metadataDrainTask, widgetObserver.shutdown(ctx)]);
412
+ await Promise.allSettled([drainTask, metadataDrainTask, widget.shutdown(ctx)]);
404
413
  const stillOwnsShutdown =
405
414
  shutdownGeneration === sessionGeneration && activeSession === session && !rootSession;
406
415
  if (shouldClearMetadata && stillOwnsShutdown) {
@@ -0,0 +1,55 @@
1
+ import type { MenuDefinition } from "@narumitw/pi-tui-kit";
2
+
3
+ export function createHerdrMenu(options: {
4
+ settingsPath: string;
5
+ isEnabled(): boolean;
6
+ toggle(signal: AbortSignal): Promise<boolean>;
7
+ }): MenuDefinition<undefined, "main" | "status" | "help", "toggle"> {
8
+ return {
9
+ start: "main",
10
+ screens: {
11
+ // One setting stays on the main menu, matching /tool rather than adding a submenu.
12
+ main: () => ({
13
+ kind: "actions",
14
+ title: "Herdr",
15
+ items: [
16
+ {
17
+ id: "widget",
18
+ label: `Agent widget: ${options.isEnabled() ? "On" : "Off"}`,
19
+ description: "Show or hide sibling agents above the editor",
20
+ action: "toggle",
21
+ },
22
+ { id: "status", label: "Status", to: "status" },
23
+ { id: "help", label: "Help", to: "help" },
24
+ { id: "close", label: "Close", close: true },
25
+ ],
26
+ hint: "close",
27
+ }),
28
+ status: () => ({
29
+ kind: "detail",
30
+ title: "Herdr Status",
31
+ lines: [
32
+ `Agent widget setting: ${options.isEnabled() ? "on" : "off"}`,
33
+ "The widget appears only in TUI mode with recognized sibling agents.",
34
+ "Lifecycle and metadata reporting are independent of this setting.",
35
+ `User settings file: ${options.settingsPath}`,
36
+ ],
37
+ hint: "back",
38
+ }),
39
+ help: () => ({
40
+ kind: "detail",
41
+ title: "Herdr Help",
42
+ lines: [
43
+ "Toggle Agent widget from /herdr. Changes are saved immediately; closing does not undo them.",
44
+ "Manual pi-herdr.json changes apply after /reload or the next session start.",
45
+ "The widget defaults to on. Project overrides are not read.",
46
+ ],
47
+ hint: "back",
48
+ }),
49
+ },
50
+ actions: {
51
+ toggle: async ({ signal }) =>
52
+ (await options.toggle(signal)) ? { kind: "stay" } : { kind: "rejected" },
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,135 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { HerdrWidgetObserver } from "./herdr-observer.js";
3
+ import {
4
+ awaitHerdrSettingsWrites,
5
+ herdrSettingsPath,
6
+ readHerdrSettings,
7
+ updateHerdrSettings,
8
+ } from "./settings.js";
9
+
10
+ export interface HerdrSettingsOptions {
11
+ settingsPath?: string;
12
+ }
13
+
14
+ export function createHerdrSettingsController(
15
+ pi: ExtensionAPI,
16
+ observer: HerdrWidgetObserver,
17
+ options: HerdrSettingsOptions = {},
18
+ ) {
19
+ const settingsPath = options.settingsPath ?? herdrSettingsPath();
20
+ let generation = 0;
21
+ let owner: ExtensionContext | undefined;
22
+ let controller = new AbortController();
23
+ let enabled = true;
24
+ let changes = Promise.resolve();
25
+ let menuOpen = false;
26
+ const current = (expected: number) => expected === generation && !controller.signal.aborted;
27
+
28
+ pi.registerCommand("herdr", {
29
+ description: "Configure the Herdr agent widget",
30
+ handler: async (args, ctx) => {
31
+ if (args.trim()) throw new Error("/herdr does not accept arguments.");
32
+ if (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc")) {
33
+ throw new Error("/herdr requires TUI or RPC mode.");
34
+ }
35
+ if (!owner || ctx.sessionManager !== owner.sessionManager || menuOpen) return;
36
+ const expected = generation;
37
+ const signal = controller.signal;
38
+ menuOpen = true;
39
+ try {
40
+ const [{ runMenu }, { createHerdrMenu }] = await Promise.all([
41
+ import("@narumitw/pi-tui-kit"),
42
+ import("./herdr-menu.js"),
43
+ ]);
44
+ if (!current(expected)) return;
45
+ await runMenu(
46
+ ctx,
47
+ createHerdrMenu({
48
+ settingsPath,
49
+ isEnabled: () => enabled,
50
+ toggle: (actionSignal) => {
51
+ const result = changes.then(async () => {
52
+ if (actionSignal.aborted || !current(expected) || !owner) return false;
53
+ // Once accepted, finish the explicit save even if the menu closes.
54
+ // Session replacement still prevents stale runtime publication.
55
+ const previous = enabled;
56
+ const actionOwner = owner;
57
+ try {
58
+ enabled = !previous;
59
+ if (enabled && actionOwner.mode === "tui") observer.start(actionOwner);
60
+ else await observer.shutdown(actionOwner);
61
+ if (!current(expected)) return false;
62
+ await updateHerdrSettings({ widget: enabled }, { settingsPath });
63
+ return current(expected);
64
+ } catch {
65
+ if (!current(expected)) return false;
66
+ enabled = previous;
67
+ try {
68
+ if (previous && actionOwner.mode === "tui") observer.start(actionOwner);
69
+ else await observer.shutdown(actionOwner);
70
+ } finally {
71
+ if (current(expected))
72
+ ctx.ui.notify(
73
+ "Herdr settings were not saved; the previous widget setting was restored. Check pi-herdr.json and its permissions.",
74
+ "warning",
75
+ );
76
+ }
77
+ return false;
78
+ }
79
+ });
80
+ changes = result.then(
81
+ () => undefined,
82
+ () => undefined,
83
+ );
84
+ return result;
85
+ },
86
+ }),
87
+ {
88
+ getState: () => undefined,
89
+ signal,
90
+ isCurrent: () => current(expected),
91
+ onError: () => {
92
+ if (current(expected))
93
+ ctx.ui.notify("The Herdr menu could not be displayed.", "error");
94
+ },
95
+ },
96
+ );
97
+ } finally {
98
+ if (expected === generation) menuOpen = false;
99
+ }
100
+ },
101
+ });
102
+
103
+ return {
104
+ async start(ctx: ExtensionContext) {
105
+ const expected = ++generation;
106
+ controller.abort();
107
+ controller = new AbortController();
108
+ menuOpen = false;
109
+ const previous = owner;
110
+ owner = ctx;
111
+ if (previous) await observer.shutdown(previous);
112
+ if (!current(expected)) return;
113
+ await changes;
114
+ if (!current(expected)) return;
115
+ const loaded = await readHerdrSettings(settingsPath);
116
+ if (!current(expected)) return;
117
+ enabled = loaded.settings.widget;
118
+ if (loaded.kind === "invalid" && ctx.hasUI)
119
+ ctx.ui.notify(
120
+ "Herdr ignored invalid pi-herdr.json settings and kept the widget enabled. Fix the file before saving.",
121
+ "warning",
122
+ );
123
+ if (enabled && ctx.mode === "tui") observer.start(ctx);
124
+ },
125
+ async shutdown(ctx: ExtensionContext) {
126
+ if (ctx.sessionManager !== owner?.sessionManager) return;
127
+ generation += 1;
128
+ controller.abort();
129
+ owner = undefined;
130
+ menuOpen = false;
131
+ await Promise.all([observer.shutdown(ctx), changes]);
132
+ await awaitHerdrSettingsWrites(settingsPath);
133
+ },
134
+ };
135
+ }
@@ -0,0 +1,192 @@
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(
43
+ settingsPath = herdrSettingsPath(),
44
+ ): Promise<HerdrSettingsLoadResult> {
45
+ return enqueue(settingsPath, async () => {
46
+ let document: SettingsDocument;
47
+ try {
48
+ document = await readSettingsDocument(settingsPath);
49
+ } catch (error) {
50
+ if (isNodeError(error) && error.code === "ENOENT") {
51
+ return { kind: "missing", settings: { ...DEFAULT_SETTINGS } };
52
+ }
53
+ return {
54
+ kind: "invalid",
55
+ reason: `${settingsPath}: ${safeError(error)}`,
56
+ settings: { ...DEFAULT_SETTINGS },
57
+ };
58
+ }
59
+ const settings = normalizeHerdrSettings(document);
60
+ return settings
61
+ ? { kind: "loaded", settings }
62
+ : {
63
+ kind: "invalid",
64
+ reason: `${settingsPath}: invalid settings shape`,
65
+ settings: { ...DEFAULT_SETTINGS },
66
+ };
67
+ });
68
+ }
69
+
70
+ export function updateHerdrSettings(
71
+ patch: Partial<HerdrSettings>,
72
+ options: UpdateHerdrSettingsOptions = {},
73
+ ): Promise<HerdrSettings> {
74
+ const settingsPath = options.settingsPath ?? herdrSettingsPath();
75
+ return enqueue(settingsPath, async () => {
76
+ const current = await readDocumentForUpdate(settingsPath);
77
+ const updated = { ...current, ...patch };
78
+ const settings = normalizeHerdrSettings(updated);
79
+ if (!settings) throw new Error(`Pi Herdr settings at ${settingsPath} have an invalid shape.`);
80
+ await publishSettings(settingsPath, updated, options);
81
+ return settings;
82
+ });
83
+ }
84
+
85
+ export async function awaitHerdrSettingsWrites(settingsPath = herdrSettingsPath()): Promise<void> {
86
+ await queues.get(settingsPath);
87
+ }
88
+
89
+ function enqueue<T>(path: string, operation: () => Promise<T>): Promise<T> {
90
+ const previous = queues.get(path) ?? Promise.resolve();
91
+ const result = previous.then(operation, operation);
92
+ const settled = result.then(
93
+ () => undefined,
94
+ () => undefined,
95
+ );
96
+ queues.set(path, settled);
97
+ void settled.finally(() => {
98
+ if (queues.get(path) === settled) queues.delete(path);
99
+ });
100
+ return result;
101
+ }
102
+
103
+ async function readDocumentForUpdate(path: string): Promise<SettingsDocument> {
104
+ try {
105
+ const document = await readSettingsDocument(path);
106
+ if (!normalizeHerdrSettings(document)) throw new Error("invalid settings shape");
107
+ return document;
108
+ } catch (error) {
109
+ if (isNodeError(error) && error.code === "ENOENT") return {};
110
+ throw new Error(`Pi Herdr settings at ${path} are invalid: ${safeError(error)}`);
111
+ }
112
+ }
113
+
114
+ async function readSettingsDocument(path: string): Promise<SettingsDocument> {
115
+ const pathStats = await lstat(path);
116
+ if (pathStats.isSymbolicLink() || !pathStats.isFile()) {
117
+ throw new Error("settings path is not a regular file");
118
+ }
119
+ if (pathStats.size > MAX_SETTINGS_BYTES) {
120
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
121
+ }
122
+ const noFollow = constants.O_NOFOLLOW ?? 0;
123
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | noFollow);
124
+ try {
125
+ const stats = await handle.stat();
126
+ if (!stats.isFile() || stats.dev !== pathStats.dev || stats.ino !== pathStats.ino) {
127
+ throw new Error("settings path changed while opening");
128
+ }
129
+ const buffer = Buffer.alloc(MAX_SETTINGS_BYTES + 1);
130
+ let offset = 0;
131
+ while (offset < buffer.length) {
132
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
133
+ if (bytesRead === 0) break;
134
+ offset += bytesRead;
135
+ }
136
+ if (offset > MAX_SETTINGS_BYTES) {
137
+ throw new Error(`settings file exceeds ${MAX_SETTINGS_BYTES} bytes`);
138
+ }
139
+ let contents: string;
140
+ try {
141
+ contents = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
142
+ buffer.subarray(0, offset),
143
+ );
144
+ } catch {
145
+ throw new Error("settings file is not valid UTF-8");
146
+ }
147
+ let parsed: unknown;
148
+ try {
149
+ parsed = JSON.parse(contents) as unknown;
150
+ } catch {
151
+ throw new Error("invalid JSON");
152
+ }
153
+ if (!isRecord(parsed)) throw new Error("settings document must be a JSON object");
154
+ return parsed;
155
+ } finally {
156
+ await handle.close();
157
+ }
158
+ }
159
+
160
+ async function publishSettings(
161
+ path: string,
162
+ document: SettingsDocument,
163
+ options: UpdateHerdrSettingsOptions,
164
+ ): Promise<void> {
165
+ const contents = `${JSON.stringify(document, null, 2)}\n`;
166
+ if (Buffer.byteLength(contents) > MAX_SETTINGS_BYTES) {
167
+ throw new Error(`Pi Herdr settings document exceeds ${MAX_SETTINGS_BYTES} bytes.`);
168
+ }
169
+ const directory = dirname(path);
170
+ await mkdir(directory, { recursive: true });
171
+ const temporaryPath = join(directory, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
172
+ try {
173
+ await writeFile(temporaryPath, contents, { encoding: "utf8", flag: "wx", mode: 0o600 });
174
+ await options.beforeRename?.(temporaryPath, path);
175
+ await rename(temporaryPath, path);
176
+ } catch (error) {
177
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
178
+ throw error;
179
+ }
180
+ }
181
+
182
+ function isRecord(value: unknown): value is SettingsDocument {
183
+ return typeof value === "object" && value !== null && !Array.isArray(value);
184
+ }
185
+
186
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
187
+ return error instanceof Error && "code" in error;
188
+ }
189
+
190
+ function safeError(error: unknown): string {
191
+ return error instanceof Error ? error.message : String(error);
192
+ }