@howaboua/pi-shepherdr 0.2.15 → 0.2.16

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +40 -33
  3. package/index.ts +16 -26
  4. package/package.json +11 -11
  5. package/src/agents-contract.ts +11 -1
  6. package/src/agents-discovery.ts +21 -7
  7. package/src/agents-focus.ts +242 -0
  8. package/src/agents-spawn.ts +23 -0
  9. package/src/agents-tool.ts +34 -5
  10. package/src/attachment-protocol.ts +7 -3
  11. package/src/attachment-target.ts +3 -1
  12. package/src/attachment.ts +3 -1
  13. package/src/board/host.ts +98 -366
  14. package/src/board/membership.ts +14 -8
  15. package/src/command-config.ts +51 -0
  16. package/src/control-panel-actions.ts +0 -20
  17. package/src/control-panel-items.ts +8 -36
  18. package/src/control-panel-view.ts +2 -11
  19. package/src/control-panel.ts +2 -11
  20. package/src/controller.ts +5 -5
  21. package/src/delivery.ts +0 -33
  22. package/src/herdr-client.ts +39 -6
  23. package/src/messages.ts +61 -61
  24. package/src/monitor-events.ts +24 -2
  25. package/src/monitor-questions.ts +12 -3
  26. package/src/monitor.ts +2 -2
  27. package/src/peer-channel.ts +39 -0
  28. package/src/peer-commands.ts +173 -0
  29. package/src/peer-inbox.ts +218 -55
  30. package/src/remote/shepherdr-channel.mjs +225 -0
  31. package/src/remote/shepherdr-checkpoints.mjs +5 -3
  32. package/src/remote/shepherdr-peer.mjs +151 -22
  33. package/src/remote/shepherdr.mjs +56 -8
  34. package/src/remote-client.ts +115 -11
  35. package/src/settlement.ts +1 -0
  36. package/src/shared-context.ts +104 -1
  37. package/src/types.ts +23 -0
  38. package/src/voice-handoff.ts +177 -0
  39. package/src/board/archive.ts +0 -77
  40. package/src/board/awareness.ts +0 -115
  41. package/src/board/config.ts +0 -121
  42. package/src/board/contract.ts +0 -181
  43. package/src/board/identity.ts +0 -169
  44. package/src/board/paging.ts +0 -55
  45. package/src/board/protocol.ts +0 -73
  46. package/src/board/queries.ts +0 -176
  47. package/src/board/response.ts +0 -56
  48. package/src/board/store.ts +0 -327
  49. package/src/board/tool.ts +0 -23
  50. package/src/board/turns.ts +0 -100
  51. package/src/context-briefing.ts +0 -226
@@ -0,0 +1,39 @@
1
+ import type {
2
+ ExtensionAPI,
3
+ ExtensionContext,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import type { FocusRequest, PaneInfo, PeerChannel } from "./types.js";
6
+
7
+ type Receiver = (
8
+ channel: PeerChannel,
9
+ request: FocusRequest,
10
+ ctx: ExtensionContext,
11
+ pane: PaneInfo,
12
+ ) => Promise<void>;
13
+ const receivers = new WeakMap<ExtensionAPI, Receiver>();
14
+
15
+ /** Resolve after admission; the receiver owns the channel through call shutdown. */
16
+ export function registerFocusChannelReceiver(
17
+ pi: ExtensionAPI,
18
+ receiver: Receiver,
19
+ ): () => void {
20
+ if (receivers.has(pi))
21
+ throw new Error("Focus channel receiver already registered");
22
+ receivers.set(pi, receiver);
23
+ return () => {
24
+ if (receivers.get(pi) === receiver) receivers.delete(pi);
25
+ };
26
+ }
27
+
28
+ export async function acceptFocusChannel(
29
+ pi: ExtensionAPI,
30
+ channel: PeerChannel,
31
+ request: FocusRequest,
32
+ ctx: ExtensionContext,
33
+ pane: PaneInfo,
34
+ ): Promise<void> {
35
+ const receiver = receivers.get(pi);
36
+ if (!receiver)
37
+ throw new Error("Voice transfer is unavailable in the destination session");
38
+ await receiver(channel, request, ctx, pane);
39
+ }
@@ -0,0 +1,173 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionCommandContext,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { readExtensionCommands } from "./command-config.js";
8
+
9
+ const builtins = {
10
+ quit: "Shut down Pi and close its pane",
11
+ model: "Set model: /model provider/model-id",
12
+ thinking: "Set thinking: /thinking off|minimal|low|medium|high|xhigh",
13
+ name: "Set session name: /name name",
14
+ new: "Start a new session",
15
+ reload: "Reload extensions and resources",
16
+ resume: "Resume a session: /resume session-path",
17
+ compact: "Compact context: /compact [instructions]",
18
+ };
19
+
20
+ export function createPeerCommands(pi: ExtensionAPI) {
21
+ const pending = new Map<
22
+ string,
23
+ {
24
+ session: string | undefined;
25
+ run: (ctx: ExtensionCommandContext) => Promise<void>;
26
+ }
27
+ >();
28
+ pi.on("session_shutdown", () => pending.clear());
29
+ return {
30
+ async handle(args: string, ctx: ExtensionCommandContext): Promise<boolean> {
31
+ const intent = pending.get(args);
32
+ if (!intent) return false;
33
+ pending.delete(args);
34
+ if (ctx.sessionManager.getSessionFile() !== intent.session)
35
+ throw new Error("Target session changed; resolve the target again");
36
+ await intent.run(ctx);
37
+ return true;
38
+ },
39
+ prepare(
40
+ text: string,
41
+ ctx: ExtensionContext,
42
+ ): { command: boolean; submit: () => void } {
43
+ const space = text.indexOf(" ");
44
+ const name = text.slice(1, space < 0 ? undefined : space);
45
+ const args = space < 0 ? "" : text.slice(space + 1).trim();
46
+ if (Object.hasOwn(builtins, name)) {
47
+ if (name !== "quit" && !ctx.isIdle())
48
+ throw new Error("Target is busy; retry after it settles");
49
+ const run = prepareBuiltin(pi, name, args, ctx);
50
+ return {
51
+ command: true,
52
+ submit: () => {
53
+ const token = randomUUID();
54
+ pending.set(token, {
55
+ session: ctx.sessionManager.getSessionFile(),
56
+ run,
57
+ });
58
+ pi.sendUserMessage(`/herdr ${token}`, {
59
+ expandPromptTemplates: true,
60
+ });
61
+ },
62
+ };
63
+ }
64
+ const commands = pi.getCommands();
65
+ const entry = commands.find((entry) => entry.name === name);
66
+ let allowed: Record<string, string> = {};
67
+ try {
68
+ allowed = readExtensionCommands();
69
+ } catch (error) {
70
+ ctx.ui.notify(`Extension commands disabled: ${String(error)}`, "error");
71
+ }
72
+ if (
73
+ !entry ||
74
+ (entry.source === "extension" && !Object.hasOwn(allowed, name))
75
+ ) {
76
+ const available = Object.entries(builtins).concat(
77
+ commands
78
+ .filter(
79
+ (entry) =>
80
+ entry.source === "extension" &&
81
+ Object.hasOwn(allowed, entry.name),
82
+ )
83
+ .flatMap((entry): [string, string][] => {
84
+ const description = allowed[entry.name];
85
+ return description === undefined
86
+ ? []
87
+ : [[entry.name, description]];
88
+ }),
89
+ );
90
+ throw new Error(
91
+ `Command /${name} is unavailable. Available commands:\n${available.map(([name, description]) => `/${name}: ${description}`).join("\n")}`,
92
+ );
93
+ }
94
+ return {
95
+ command: entry.source === "extension",
96
+ submit: () =>
97
+ pi.sendUserMessage(text, {
98
+ expandPromptTemplates: true,
99
+ deliverAs: "steer",
100
+ }),
101
+ };
102
+ },
103
+ };
104
+ }
105
+
106
+ function prepareBuiltin(
107
+ pi: ExtensionAPI,
108
+ name: string,
109
+ args: string,
110
+ ctx: ExtensionContext,
111
+ ): (ctx: ExtensionCommandContext) => Promise<void> {
112
+ if (["quit", "new", "reload"].includes(name) && args)
113
+ throw new Error(`/${name} takes no arguments`);
114
+ switch (name) {
115
+ case "quit":
116
+ return async (ctx) => ctx.shutdown();
117
+ case "new":
118
+ return async (ctx) => {
119
+ if ((await ctx.newSession()).cancelled)
120
+ throw new Error("New session cancelled");
121
+ };
122
+ case "reload":
123
+ return async (ctx) => {
124
+ await ctx.reload();
125
+ };
126
+ case "resume":
127
+ if (!args) throw new Error("Use /resume session-path");
128
+ return async (ctx) => {
129
+ if ((await ctx.switchSession(args)).cancelled)
130
+ throw new Error("Session switch cancelled");
131
+ };
132
+ case "name":
133
+ if (!args) throw new Error("Use /name name");
134
+ return async () => pi.setSessionName(args);
135
+ case "thinking": {
136
+ if (
137
+ args !== "off" &&
138
+ args !== "minimal" &&
139
+ args !== "low" &&
140
+ args !== "medium" &&
141
+ args !== "high" &&
142
+ args !== "xhigh"
143
+ )
144
+ throw new Error(builtins.thinking);
145
+ return async () => pi.setThinkingLevel(args);
146
+ }
147
+ case "model": {
148
+ const model = ctx.modelRegistry
149
+ .getAvailable()
150
+ .find((model) => `${model.provider}/${model.id}` === args);
151
+ if (!model)
152
+ throw new Error(
153
+ `Use /model provider/model-id. Available: ${ctx.modelRegistry
154
+ .getAvailable()
155
+ .map((model) => `${model.provider}/${model.id}`)
156
+ .join(", ")}`,
157
+ );
158
+ return async () => {
159
+ if (!(await pi.setModel(model)))
160
+ throw new Error("Model unavailable; choose another model");
161
+ };
162
+ }
163
+ case "compact":
164
+ return async (ctx) =>
165
+ ctx.compact({
166
+ ...(args ? { customInstructions: args } : {}),
167
+ onError: (error) =>
168
+ ctx.ui.notify(`Compaction failed: ${error.message}`, "error"),
169
+ });
170
+ default:
171
+ throw new Error(`Unsupported command /${name}`);
172
+ }
173
+ }
package/src/peer-inbox.ts CHANGED
@@ -5,16 +5,32 @@ import type {
5
5
  ExtensionAPI,
6
6
  ExtensionContext,
7
7
  } from "@earendil-works/pi-coding-agent";
8
+ import { acceptFocus, readFocus } from "./agents-focus.js";
8
9
  import { sendPolicyMessage, startPreparedIdleTurn } from "./delivery.js";
10
+ import type { AgentFleet } from "./fleet.js";
9
11
  import { getCurrentPane } from "./herdr.js";
10
12
  import { HerdrClient } from "./herdr-client.js";
11
13
  import { announcePeerMessage } from "./messages.js";
14
+ import { acceptFocusChannel } from "./peer-channel.js";
15
+ import type { createPeerCommands } from "./peer-commands.js";
16
+ import {
17
+ MAX_CHANNEL_FRAME_BYTES,
18
+ socketChannel,
19
+ } from "./remote/shepherdr-channel.mjs";
12
20
  import {
13
21
  MAX_PEER_FRAME_BYTES,
22
+ PEER_PROTOCOL,
14
23
  peerInboxPath,
15
24
  } from "./remote/shepherdr-peer.mjs";
16
25
 
17
- export function registerPeerInbox(pi: ExtensionAPI): void {
26
+ export function registerPeerInbox(
27
+ pi: ExtensionAPI,
28
+ commands: ReturnType<typeof createPeerCommands>,
29
+ fleet: AgentFleet,
30
+ catchup: (
31
+ ctx: ExtensionContext,
32
+ ) => Promise<{ content: string; accepted: () => void }>,
33
+ ): void {
18
34
  let close: (() => Promise<void>) | undefined;
19
35
  let running = false;
20
36
  pi.on("agent_start", () => {
@@ -29,7 +45,7 @@ export function registerPeerInbox(pi: ExtensionAPI): void {
29
45
  running = false;
30
46
  if (process.env["HERDR_ENV"] !== "1" || !process.env["HERDR_SOCKET_PATH"])
31
47
  return;
32
- close = await openInbox(pi, ctx, () => running);
48
+ close = await openInbox(pi, ctx, () => running, commands, fleet, catchup);
33
49
  });
34
50
  pi.on("session_shutdown", async () => {
35
51
  await close?.();
@@ -42,6 +58,11 @@ async function openInbox(
42
58
  pi: ExtensionAPI,
43
59
  ctx: ExtensionContext,
44
60
  isRunning: () => boolean,
61
+ commands: ReturnType<typeof createPeerCommands>,
62
+ fleet: AgentFleet,
63
+ catchup: (
64
+ ctx: ExtensionContext,
65
+ ) => Promise<{ content: string; accepted: () => void }>,
45
66
  ): Promise<() => Promise<void>> {
46
67
  const sessionFile = ctx.sessionManager.getSessionFile();
47
68
  if (!sessionFile)
@@ -51,7 +72,8 @@ async function openInbox(
51
72
  const path = peerInboxPath(sessionFile, pane.terminal_id);
52
73
  const temporary = `${path}.${token}.tmp`;
53
74
  const sockets = new Set<Socket>();
54
- let active = true;
75
+ let state: "open" | "quitting" | "closed" = "open";
76
+ let promptDelivery = Promise.resolve();
55
77
  const server = createServer((socket) => {
56
78
  sockets.add(socket);
57
79
  socket.setEncoding("utf8");
@@ -60,7 +82,7 @@ async function openInbox(
60
82
  socket.on("close", () => sockets.delete(socket));
61
83
  let buffer = "";
62
84
  let received = false;
63
- socket.on("data", (chunk: string) => {
85
+ socket.on("data", async (chunk: string) => {
64
86
  if (received) return;
65
87
  buffer += chunk;
66
88
  if (Buffer.byteLength(buffer) > MAX_PEER_FRAME_BYTES) {
@@ -80,24 +102,30 @@ async function openInbox(
80
102
  socket.destroy();
81
103
  return;
82
104
  }
83
- const reply = (value: object) =>
105
+ const reply = (value: object, flushed?: () => void) =>
84
106
  socket.end(
85
- `${JSON.stringify({ protocol: 1, id: request["id"], ...value })}\n`,
107
+ `${JSON.stringify({ protocol: PEER_PROTOCOL, id: request["id"], ...value })}\n`,
108
+ flushed,
86
109
  );
87
110
  if (
88
- !active ||
89
- request["protocol"] !== 1 ||
111
+ state !== "open" ||
112
+ request["protocol"] !== PEER_PROTOCOL ||
90
113
  request["token"] !== token ||
91
114
  request["sessionFile"] !== sessionFile ||
92
115
  request["terminalId"] !== pane.terminal_id ||
93
116
  ctx.sessionManager.getSessionFile() !== sessionFile ||
94
117
  typeof request["id"] !== "string" ||
95
- typeof request["text"] !== "string" ||
96
- !request["text"].trim() ||
97
- typeof request["sender"] !== "string" ||
98
- !/^<herdr_sender [^\n]+ \/>$/.test(request["sender"]) ||
99
- (request["context"] !== undefined &&
100
- typeof request["context"] !== "string")
118
+ (request["kind"] !== "focus" &&
119
+ request["kind"] !== "message" &&
120
+ request["kind"] !== "channel") ||
121
+ (request["kind"] !== "focus" &&
122
+ request["kind"] !== "channel" &&
123
+ (typeof request["text"] !== "string" ||
124
+ !request["text"].trim() ||
125
+ typeof request["sender"] !== "string" ||
126
+ !/^<herdr_sender [^\n]+ \/>$/.test(request["sender"]) ||
127
+ (request["context"] !== undefined &&
128
+ typeof request["context"] !== "string")))
101
129
  ) {
102
130
  reply({
103
131
  ok: false,
@@ -106,6 +134,92 @@ async function openInbox(
106
134
  });
107
135
  return;
108
136
  }
137
+ if (request["kind"] === "channel") {
138
+ let focus;
139
+ try {
140
+ focus = readFocus(request["focus"]);
141
+ } catch (error) {
142
+ reply({ ok: false, rejected: true, error: String(error) });
143
+ return;
144
+ }
145
+ // Hold outbound frames until the admission reply precedes them.
146
+ const pending: unknown[] = [];
147
+ let admitted = false;
148
+ const channel = socketChannel(socket, buffer.slice(newline + 1));
149
+ const receiverChannel = {
150
+ ...channel,
151
+ send(message: unknown) {
152
+ const json = JSON.stringify(message);
153
+ if (
154
+ json === undefined ||
155
+ Buffer.byteLength(json) > MAX_CHANNEL_FRAME_BYTES
156
+ ) {
157
+ channel.close();
158
+ throw new Error("Focus channel frame is too large or not JSON");
159
+ }
160
+ if (admitted) channel.send(message);
161
+ else {
162
+ pending.push(message);
163
+ if (
164
+ pending.length > 64 ||
165
+ Buffer.byteLength(JSON.stringify(pending)) > 1024 * 1024
166
+ ) {
167
+ channel.close();
168
+ throw new Error(
169
+ "Focus channel admission output exceeded its buffer",
170
+ );
171
+ }
172
+ }
173
+ },
174
+ };
175
+ void acceptFocusChannel(pi, receiverChannel, focus, ctx, pane).then(
176
+ () => {
177
+ try {
178
+ socket.write(
179
+ `${JSON.stringify({ protocol: PEER_PROTOCOL, id: request["id"], ok: true })}\n`,
180
+ );
181
+ admitted = true;
182
+ for (const message of pending) channel.send(message);
183
+ pending.length = 0;
184
+ } catch {
185
+ channel.close();
186
+ }
187
+ },
188
+ (error: unknown) => {
189
+ reply(
190
+ {
191
+ ok: false,
192
+ rejected: true,
193
+ error: error instanceof Error ? error.message : String(error),
194
+ },
195
+ () => channel.close(),
196
+ );
197
+ },
198
+ );
199
+ return;
200
+ }
201
+ if (request["kind"] === "focus") {
202
+ try {
203
+ if (readFocus(request["focus"]).voice === true)
204
+ throw new Error(
205
+ "Voice transfer was not admitted; retry using agents focus with voice:true",
206
+ );
207
+ } catch (error) {
208
+ reply({ ok: false, rejected: true, error: String(error) });
209
+ return;
210
+ }
211
+ socket.setTimeout(60_000, () => socket.destroy());
212
+ void acceptFocus(pi, ctx, fleet, pane, request["focus"]).then(
213
+ () => reply({ ok: true, command: false }),
214
+ (error: unknown) =>
215
+ reply({
216
+ ok: false,
217
+ rejected: !(error instanceof Error && "focusChanged" in error),
218
+ error: error instanceof Error ? error.message : String(error),
219
+ }),
220
+ );
221
+ return;
222
+ }
109
223
  let submitted = false;
110
224
  try {
111
225
  const idle = ctx.isIdle();
@@ -119,20 +233,13 @@ async function openInbox(
119
233
  });
120
234
  return;
121
235
  }
122
- const text = request["text"];
236
+ const text = request["text"] as string;
123
237
  const sender = request["context"]
124
238
  ? `${request["sender"]}\n${request["context"]}`
125
- : request["sender"];
239
+ : (request["sender"] as string);
126
240
  if (text.startsWith("/")) {
127
- // Match only Pi's extension-command boundary, not its argument or
128
- // skill/template parsers. Extension commands may never start a turn.
129
- const space = text.indexOf(" ");
130
- const name = text.slice(1, space < 0 ? undefined : space);
131
- const command = pi
132
- .getCommands()
133
- .some(
134
- (entry) => entry.source === "extension" && entry.name === name,
135
- );
241
+ const route = commands.prepare(text, ctx);
242
+ const { command } = route;
136
243
  const submit = () => {
137
244
  submitted = true;
138
245
  sendPolicyMessage(
@@ -147,41 +254,93 @@ async function openInbox(
147
254
  deliverAs: idle && !command ? "nextTurn" : "steer",
148
255
  },
149
256
  );
150
- pi.sendUserMessage(text, {
151
- expandPromptTemplates: true,
152
- deliverAs: "steer",
153
- });
257
+ route.submit();
154
258
  };
259
+ if (command) {
260
+ // Lifecycle commands can tear down this inbox. Flush acceptance first.
261
+ const execute = () => {
262
+ try {
263
+ submit();
264
+ } catch (error) {
265
+ ctx.ui.notify(
266
+ `Command submission failed: ${String(error)}`,
267
+ "error",
268
+ );
269
+ }
270
+ };
271
+ if (text.trim() === "/quit") {
272
+ // Hold this authenticated connection until process exit, not
273
+ // session_shutdown (which precedes Pi's runtime teardown).
274
+ state = "quitting";
275
+ sockets.delete(socket);
276
+ socket.setTimeout(0);
277
+ socket.write(
278
+ `${JSON.stringify({ protocol: PEER_PROTOCOL, id: request["id"], ok: true, command, closing: true })}\n`,
279
+ execute,
280
+ );
281
+ } else reply({ ok: true, command }, execute);
282
+ return;
283
+ }
155
284
  if (idle && !command) startPreparedIdleTurn(pi, ctx, submit);
156
285
  else submit();
157
286
  reply({ ok: true, command });
158
287
  return;
159
288
  }
160
- submitted = true;
161
- sendPolicyMessage(
162
- pi,
163
- {
164
- customType: "herdr-agent-message",
165
- content: `${sender}\n${text}`,
166
- display: true,
167
- },
168
- idle
169
- ? { triggerTurn: false, deliverAs: "nextTurn" }
170
- : { deliverAs: "steer" },
171
- );
172
- // Keep arrivals out of history until idle rollover and preparation
173
- // finish. The shared kickoff coalesces arrivals during preparation.
174
- if (idle) startPreparedIdleTurn(pi, ctx);
175
- // Voice failure must not turn accepted delivery into a retry.
289
+ // Catch-up sampling and acceptance form one prompt boundary, including
290
+ // bursts arriving on separate authenticated sockets.
291
+ const previous = promptDelivery;
292
+ let release!: () => void;
293
+ promptDelivery = new Promise<void>((resolve) => {
294
+ release = resolve;
295
+ });
296
+ await previous;
176
297
  try {
177
- announcePeerMessage(pi, { sender: request["sender"], text });
178
- } catch (error) {
179
- ctx.ui.notify(
180
- `Peer voice update failed: ${String(error)}`,
181
- "warning",
298
+ const notice = await catchup(ctx);
299
+ if (
300
+ state !== "open" ||
301
+ ctx.sessionManager.getSessionFile() !== sessionFile ||
302
+ (!ctx.isIdle() && !isRunning())
303
+ ) {
304
+ reply({
305
+ ok: false,
306
+ rejected: true,
307
+ error: "Target changed context; retry after it settles",
308
+ });
309
+ return;
310
+ }
311
+ const promptIdle = ctx.isIdle();
312
+ submitted = true;
313
+ sendPolicyMessage(
314
+ pi,
315
+ {
316
+ customType: "herdr-agent-message",
317
+ content: `${sender}\n${text}${notice.content}`,
318
+ display: true,
319
+ },
320
+ promptIdle
321
+ ? { triggerTurn: false, deliverAs: "nextTurn" }
322
+ : { deliverAs: "steer" },
182
323
  );
324
+ notice.accepted();
325
+ // Keep arrivals out of history until idle rollover and preparation
326
+ // finish. The shared kickoff coalesces arrivals during preparation.
327
+ if (promptIdle) startPreparedIdleTurn(pi, ctx);
328
+ // Voice failure must not turn accepted delivery into a retry.
329
+ try {
330
+ announcePeerMessage(pi, {
331
+ sender: request["sender"] as string,
332
+ text,
333
+ });
334
+ } catch (error) {
335
+ ctx.ui.notify(
336
+ `Peer voice update failed: ${String(error)}`,
337
+ "warning",
338
+ );
339
+ }
340
+ reply({ ok: true, command: false });
341
+ } finally {
342
+ release();
183
343
  }
184
- reply({ ok: true, command: false });
185
344
  } catch (error) {
186
345
  reply({
187
346
  ok: false,
@@ -193,10 +352,14 @@ async function openInbox(
193
352
  });
194
353
  server.maxConnections = 16;
195
354
  const stop = async () => {
196
- if (!active) return;
197
- active = false;
355
+ if (state === "closed") return;
356
+ const quitting = state === "quitting";
357
+ state = "closed";
198
358
  for (const socket of sockets) socket.destroy();
199
- await new Promise<void>((resolve) => server.close(() => resolve()));
359
+ const closed = new Promise<void>((resolve) =>
360
+ server.close(() => resolve()),
361
+ );
362
+ if (!quitting) await closed;
200
363
  try {
201
364
  const current: unknown = JSON.parse(await readFile(path, "utf8"));
202
365
  if (
@@ -232,7 +395,7 @@ async function openInbox(
232
395
  throw new Error("Shepherdr peer receiver has no address");
233
396
  await writeFile(
234
397
  temporary,
235
- JSON.stringify({ protocol: 1, port: address.port, token }),
398
+ JSON.stringify({ protocol: PEER_PROTOCOL, port: address.port, token }),
236
399
  { mode: 0o600, flag: "wx" },
237
400
  );
238
401
  await rename(temporary, path);