@nones/agentflow-core 0.1.0 → 0.6.1

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/src/server.ts CHANGED
@@ -4,18 +4,24 @@ import {
4
4
  lstatSync,
5
5
  mkdirSync,
6
6
  readFileSync,
7
+ realpathSync,
7
8
  unlinkSync,
8
9
  writeFileSync,
9
10
  } from "node:fs";
10
11
  import type { Stats } from "node:fs";
11
- import { dirname, join } from "node:path";
12
+ import { dirname, join, resolve } from "node:path";
12
13
  import type { Socket, UnixSocketListener } from "bun";
13
14
  import { EngineImpl } from "./engine";
14
15
  import { AgentFlowError, asAgentFlowError } from "./errors";
15
16
  import { isPlainObject } from "./json";
16
17
  import { JsonLines, JsonLineWriter } from "./jsonl-socket";
17
18
  import {
19
+ isDrainReadOnlyAction,
18
20
  isRpcAction,
21
+ operatorOptions,
22
+ parseAmendRunArgs,
23
+ type DrainOptions,
24
+ type DrainReport,
19
25
  type RpcActionArgs,
20
26
  type RpcErrorPayload,
21
27
  type RpcRequest,
@@ -44,18 +50,132 @@ interface LockHandle {
44
50
  release(): void;
45
51
  }
46
52
 
53
+ /** Owner-private record of the custom socket a daemon bound for a state dir. */
54
+ interface SocketReceipt extends FileIdentity {
55
+ path: string;
56
+ }
57
+
47
58
  interface ServerConnection {
48
59
  lines: JsonLines;
49
60
  writer: JsonLineWriter<ServerConnection>;
50
61
  chain: Promise<void>;
51
62
  idleTimer?: ReturnType<typeof setTimeout>;
52
63
  closed: boolean;
64
+ /** In-flight request count; zero means the connection is idle. */
65
+ busy: number;
66
+ /** Set before any shutdown: close once the current reply is written. */
67
+ closeAfterChain: boolean;
53
68
  }
54
69
 
55
70
  const DEFAULT_MAX_REQUEST_BYTES = 1_000_000;
56
71
  const MAX_SOCKET_PATH_BYTES = 100;
57
72
  const LOCK_ATTEMPTS = 8;
58
73
  const SOCKET_PROBE_TIMEOUT_MS = 250;
74
+ const SOCKET_RECEIPT_FILE = "socket.receipt";
75
+
76
+ /**
77
+ * Shutdown supervisor shared by `close()`, the `drain` RPC and the host
78
+ * `ServeHandle.drain()`. Exactly one engine shutdown runs; concurrent
79
+ * requests join it. The caller's reply is flushed before the socket path and
80
+ * the state-directory lock are released, so a replacement daemon can never
81
+ * start against a live owner.
82
+ */
83
+ class ShutdownSupervisor {
84
+ private report: DrainReport | undefined;
85
+ private settled: Promise<void> | undefined;
86
+ /** True once the engine drain has settled. */
87
+ done = false;
88
+
89
+ constructor(
90
+ private readonly engine: Engine,
91
+ private readonly sockets: Set<Socket<ServerConnection>>,
92
+ private readonly defaultGraceMs: number | undefined,
93
+ ) {}
94
+
95
+ /**
96
+ * Starts or joins the drain. The grace deadline only bounds how long the
97
+ * engine may take to settle; the engine's own durable summary (including
98
+ * its recovery reasons) is the report either way.
99
+ */
100
+ async drain(graceMs?: number): Promise<DrainReport> {
101
+ if (this.settled === undefined) {
102
+ // Keep read-only requests available until the engine settles.
103
+ for (const live of this.sockets) {
104
+ const state = live.data;
105
+ if (state === undefined || state.closed) continue;
106
+ state.closeAfterChain = true;
107
+ }
108
+ // The drain caller's own request is still in flight; shutdown closes it
109
+ // right after its reply is flushed.
110
+ this.settled = this.run(graceMs ?? this.defaultGraceMs);
111
+ }
112
+ await this.settled;
113
+ const report = this.report;
114
+ if (report === undefined) {
115
+ throw new AgentFlowError("closed", "daemon drain did not settle");
116
+ }
117
+ return report;
118
+ }
119
+
120
+ private async run(graceMs: number | undefined): Promise<void> {
121
+ // The engine owns the durable summary and its grace handling. It is
122
+ // observed either way so a rejection can never surface as unhandled.
123
+ const closing = this.engine.drain(graceMs).then(
124
+ (summary) => summary,
125
+ () => undefined,
126
+ );
127
+ const summary = await closing;
128
+ if (summary === undefined) {
129
+ // The engine rejected; a joining caller sees the same failure.
130
+ throw new AgentFlowError("closed", "daemon drain failed");
131
+ }
132
+ this.report = summary;
133
+ this.done = true;
134
+ // Idle connections close now. The drain caller is still busy with its own
135
+ // reply and every other in-flight reply drains first; shutdown then
136
+ // closes the rest.
137
+ for (const live of this.sockets) {
138
+ const state = live.data;
139
+ if (state !== undefined && state.busy === 0 && state.closeAfterChain) {
140
+ closeConnection(live, true);
141
+ }
142
+ }
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Detect an engine generation that carries the lifecycle operator surface.
148
+ * Structural detection keeps the listener callable for older engines, which
149
+ * answer with a `capability` error instead of failing to start.
150
+ */
151
+ type OperatorKeys =
152
+ | "pauseRun"
153
+ | "continueRun"
154
+ | "limitRun"
155
+ | "retryRun"
156
+ | "amendRun"
157
+ | "operations"
158
+ | "recovery";
159
+
160
+ function requireRunOperator(engine: Engine): Engine {
161
+ const candidate = engine as Partial<Record<OperatorKeys, unknown>>;
162
+ const present: OperatorKeys[] = [
163
+ "pauseRun",
164
+ "continueRun",
165
+ "limitRun",
166
+ "retryRun",
167
+ "amendRun",
168
+ "operations",
169
+ "recovery",
170
+ ];
171
+ if (present.every((key) => typeof candidate[key] === "function")) {
172
+ return engine;
173
+ }
174
+ throw new AgentFlowError(
175
+ "capability",
176
+ "this daemon does not support lifecycle operator actions",
177
+ );
178
+ }
59
179
 
60
180
  /**
61
181
  * Starts the owner-only Unix socket daemon around a new engine.
@@ -64,6 +184,20 @@ const SOCKET_PROBE_TIMEOUT_MS = 250;
64
184
  * lock file for the lifetime of the process.
65
185
  */
66
186
  export async function serve(options: ServeOptions): Promise<ServeHandle> {
187
+ return serveWithEngine(options, (options) => new EngineImpl(options));
188
+ }
189
+
190
+ /**
191
+ * Binds the owner-only Unix socket listener to a caller-provided engine.
192
+ *
193
+ * This is the structural seam used by integration tests and by embedders
194
+ * that already own an engine. The listener, lock and drain semantics are
195
+ * identical to `serve`; only the engine is supplied.
196
+ */
197
+ export async function serveWithEngine(
198
+ options: ServeOptions,
199
+ engineFactory: (options: ServeOptions) => Engine | Promise<Engine>,
200
+ ): Promise<ServeHandle> {
67
201
  if (!isPlainObject(options)) {
68
202
  throw new AgentFlowError("validation", "serve options must be an object");
69
203
  }
@@ -73,6 +207,12 @@ export async function serve(options: ServeOptions): Promise<ServeHandle> {
73
207
  "stateDir must be a non-empty string",
74
208
  );
75
209
  }
210
+ if (graceIsInvalid(options.rpc?.drainGraceMs)) {
211
+ throw new AgentFlowError(
212
+ "validation",
213
+ "rpc.drainGraceMs must be a non-negative number",
214
+ );
215
+ }
76
216
 
77
217
  const socketPath =
78
218
  options.socketPath === undefined
@@ -104,25 +244,38 @@ export async function serve(options: ServeOptions): Promise<ServeHandle> {
104
244
  let server: UnixSocketListener<ServerConnection> | undefined;
105
245
  const sockets = new Set<Socket<ServerConnection>>();
106
246
  let closing = false;
247
+ let closePromise: Promise<void> | undefined;
248
+ let supervisor: ShutdownSupervisor | undefined;
107
249
  let ownedSocket: FileIdentity | undefined;
250
+ const defaultGraceMs = options.rpc?.drainGraceMs;
251
+
252
+ const hostDrain = (options?: DrainOptions): Promise<DrainReport> =>
253
+ drainWithGrace(options?.graceMs);
108
254
 
109
255
  const cleanup = async (): Promise<void> => {
110
256
  if (closing) return;
111
257
  closing = true;
112
- for (const socket of sockets) closeConnection(socket);
113
- sockets.clear();
114
258
  try {
115
259
  if (server !== undefined) {
116
260
  const current = server;
117
261
  server = undefined;
118
- current.stop(true);
262
+ current.stop(false);
119
263
  }
264
+ // In-flight replies are finished and written before the engine is
265
+ // drained: a request that was already admitted keeps its reply.
266
+ await flushInFlightReplies();
120
267
  if (engine !== undefined) {
121
- const current = engine;
122
- engine = undefined;
123
- await current.close();
268
+ // One supervisor: the engine drains once whether the host called
269
+ // `close()`, `drain()` or a client sent the `drain` RPC. A drain that
270
+ // was already requested is joined, never repeated.
271
+ await hostDrain();
124
272
  }
273
+ // The socket path and the lock are released only after every reply,
274
+ // including the drain report, has reached the wire.
275
+ await closeIdleConnections();
125
276
  } finally {
277
+ for (const socket of sockets) closeConnection(socket);
278
+ sockets.clear();
126
279
  if (ownedSocket !== undefined) {
127
280
  removeOwnedSocket(socketPath, ownedSocket);
128
281
  ownedSocket = undefined;
@@ -131,17 +284,35 @@ export async function serve(options: ServeOptions): Promise<ServeHandle> {
131
284
  }
132
285
  };
133
286
 
287
+ /** Waits until no connection has an admitted request in flight. */
288
+ async function flushInFlightReplies(): Promise<void> {
289
+ while (true) {
290
+ const busy = [...sockets].filter(
291
+ (socket) => !socket.data.closed && socket.data.busy > 0,
292
+ );
293
+ if (busy.length === 0) return;
294
+ await Promise.all(busy.map((socket) => socket.data.chain));
295
+ }
296
+ }
297
+
298
+ /** Closes every connection; all replies are already on the wire. */
299
+ async function closeIdleConnections(): Promise<void> {
300
+ await flushInFlightReplies();
301
+ for (const socket of [...sockets]) closeConnection(socket, true);
302
+ }
303
+
134
304
  try {
135
305
  if (customSocket) {
136
- // A custom path may be shared with a daemon that uses another stateDir,
137
- // so no existing path can be proven stale. Never unlink it.
138
- assertCustomSocketAvailable(socketPath);
306
+ // A custom path may be shared with a daemon that uses another stateDir.
307
+ // A path is reclaimed only when this state dir's receipt proves that
308
+ // this state's own daemon bound exactly that inode and it is now stale.
309
+ await reclaimStaleCustomSocket(options.stateDir, socketPath);
139
310
  } else {
140
311
  // Holding this state directory's lock is the proof that a default
141
312
  // socket left at this path belongs to no live daemon for this state.
142
313
  await removeStaleDefaultSocket(socketPath);
143
314
  }
144
- engine = new EngineImpl(options);
315
+ engine = await engineFactory(options);
145
316
  const runningEngine = engine;
146
317
  await runningEngine.ready();
147
318
 
@@ -168,6 +339,8 @@ export async function serve(options: ServeOptions): Promise<ServeHandle> {
168
339
  writer: new JsonLineWriter(socket),
169
340
  chain: Promise.resolve(),
170
341
  closed: false,
342
+ busy: 0,
343
+ closeAfterChain: isDraining(),
171
344
  };
172
345
  sockets.add(socket);
173
346
  resetIdleTimeout(socket);
@@ -177,16 +350,39 @@ export async function serve(options: ServeOptions): Promise<ServeHandle> {
177
350
  if (connection.closed) return;
178
351
  resetIdleTimeout(socket);
179
352
  const withinLimit = connection.lines.receive(chunk, (line) => {
353
+ connection.busy += 1;
180
354
  connection.chain = connection.chain
181
355
  .then(() =>
182
- handleLine(runningEngine, line, (response) => {
183
- if (connection.closed) return;
184
- resetIdleTimeout(socket);
185
- if (!connection.writer.send(response))
186
- closeConnection(socket);
187
- }),
356
+ handleLine(
357
+ runningEngine,
358
+ line,
359
+ (response) => {
360
+ if (connection.closed) return;
361
+ resetIdleTimeout(socket);
362
+ if (!connection.writer.send(response))
363
+ closeConnection(socket);
364
+ },
365
+ (graceMs) => drainWithGrace(graceMs),
366
+ isDraining,
367
+ ),
188
368
  )
189
- .catch(() => closeConnection(socket));
369
+ .then(
370
+ () => {
371
+ connection.busy -= 1;
372
+ if (connection.closeAfterChain && connection.busy === 0) {
373
+ // A read-only call admitted just before the drain still
374
+ // gets its reply; shutdown starts once it has settled.
375
+ if (supervisor?.done === true && engine !== undefined) {
376
+ closePromise ??= cleanup();
377
+ void closePromise.catch(() => {});
378
+ }
379
+ }
380
+ },
381
+ () => {
382
+ connection.busy -= 1;
383
+ closeConnection(socket);
384
+ },
385
+ );
190
386
  });
191
387
  if (!withinLimit) closeConnection(socket);
192
388
  },
@@ -207,6 +403,10 @@ export async function serve(options: ServeOptions): Promise<ServeHandle> {
207
403
  });
208
404
  ownedSocket = socketIdentity(socketPath);
209
405
  chmodSync(socketPath, 0o600);
406
+ if (customSocket) {
407
+ // Publish the reclaimable receipt while the state lock is still held.
408
+ writeSocketReceipt(options.stateDir, socketPath, ownedSocket);
409
+ }
210
410
  } catch (error) {
211
411
  try {
212
412
  await cleanup();
@@ -216,27 +416,62 @@ export async function serve(options: ServeOptions): Promise<ServeHandle> {
216
416
  throw error;
217
417
  }
218
418
 
219
- let closePromise: Promise<void> | undefined;
220
419
  return {
221
420
  socketPath,
421
+ // Host-facing graceful drain: the same single supervisor operation the
422
+ // `drain` RPC joins, so an embedded host shares the daemon contract.
423
+ async drain(options: DrainOptions = {}): Promise<DrainReport> {
424
+ const report = await drainWithGrace(options.graceMs);
425
+ closePromise ??= cleanup();
426
+ await closePromise;
427
+ return report;
428
+ },
222
429
  close(): Promise<void> {
223
430
  if (closePromise === undefined) closePromise = cleanup();
224
431
  return closePromise;
225
432
  },
226
433
  };
434
+
435
+ function drainWithGrace(graceMs?: number): Promise<DrainReport> {
436
+ if (supervisor === undefined) {
437
+ const runningEngine = engine;
438
+ if (runningEngine === undefined) {
439
+ return Promise.reject(
440
+ new AgentFlowError("closed", "daemon is already closed"),
441
+ );
442
+ }
443
+ supervisor = new ShutdownSupervisor(
444
+ runningEngine,
445
+ sockets,
446
+ defaultGraceMs,
447
+ );
448
+ }
449
+ return supervisor.drain(graceMs);
450
+ }
451
+
452
+ /** True once a host or client drain has started. */
453
+ function isDraining(): boolean {
454
+ return supervisor !== undefined;
455
+ }
227
456
  }
228
457
 
229
- function closeConnection(socket: Socket<ServerConnection>): void {
458
+ function closeConnection(
459
+ socket: Socket<ServerConnection>,
460
+ graceful = false,
461
+ ): void {
230
462
  if (socket.data.closed) return;
231
463
  socket.data.closed = true;
232
464
  clearTimeout(socket.data.idleTimer);
233
- socket.terminate();
465
+ if (graceful) socket.end();
466
+ else socket.terminate();
234
467
  }
235
468
 
236
469
  async function handleLine(
237
470
  engine: Engine,
238
471
  line: string,
239
472
  send: (response: RpcResponse) => void,
473
+ drain: (graceMs?: number) => Promise<DrainReport>,
474
+ isDraining: () => boolean,
240
475
  ): Promise<void> {
241
476
  let request: unknown;
242
477
  try {
@@ -257,6 +492,19 @@ async function handleLine(
257
492
  send(failure(id, "ipc", `unknown action ${String(request.action)}`));
258
493
  return;
259
494
  }
495
+ if (isDraining() && !isDrainReadOnlyAction(request.action)) {
496
+ // Mutations are refused before any argument validation or engine call;
497
+ // read-only progress still flows during the grace period.
498
+ send(
499
+ failure(
500
+ id,
501
+ "closed",
502
+ `daemon is draining; ${request.action} is not accepted`,
503
+ { action: request.action, draining: true },
504
+ ),
505
+ );
506
+ return;
507
+ }
260
508
  let args: unknown;
261
509
  try {
262
510
  args = validateActionArgs(request.action, request.args);
@@ -267,7 +515,7 @@ async function handleLine(
267
515
  }
268
516
 
269
517
  try {
270
- const result = await dispatch(engine, request.action, args);
518
+ const result = await dispatch(engine, request.action, args, drain);
271
519
  send({ id, ok: true, result });
272
520
  } catch (error) {
273
521
  const failureInfo = asAgentFlowError(error);
@@ -293,6 +541,7 @@ async function dispatch(
293
541
  engine: Engine,
294
542
  action: string,
295
543
  args: unknown,
544
+ drain: (graceMs?: number) => Promise<DrainReport>,
296
545
  ): Promise<unknown> {
297
546
  switch (action) {
298
547
  case "ping":
@@ -344,6 +593,42 @@ async function dispatch(
344
593
  const typed = args as RpcActionArgs["output"];
345
594
  return engine.output(typed.id, typed.artifactId);
346
595
  }
596
+ case "pauseRun": {
597
+ const typed = args as RpcActionArgs["pauseRun"];
598
+ const { id, ...options } = typed;
599
+ return requireRunOperator(engine).pauseRun(id, options);
600
+ }
601
+ case "continueRun": {
602
+ const typed = args as RpcActionArgs["continueRun"];
603
+ const { id, ...options } = typed;
604
+ return requireRunOperator(engine).continueRun(id, options);
605
+ }
606
+ case "limitRun": {
607
+ const typed = args as RpcActionArgs["limitRun"];
608
+ const { id, maxConcurrent, ...options } = typed;
609
+ return requireRunOperator(engine).limitRun(id, maxConcurrent, options);
610
+ }
611
+ case "retryRun": {
612
+ const typed = args as RpcActionArgs["retryRun"];
613
+ const { id, ...options } = typed;
614
+ return requireRunOperator(engine).retryRun(id, options);
615
+ }
616
+ case "amendRun": {
617
+ const typed = args as RpcActionArgs["amendRun"];
618
+ return requireRunOperator(engine).amendRun(typed.id, typed.amendment);
619
+ }
620
+ case "operations":
621
+ return requireRunOperator(engine).operations(
622
+ (args as RpcActionArgs["operations"]).id,
623
+ );
624
+ case "recovery":
625
+ return requireRunOperator(engine).recovery(
626
+ (args as RpcActionArgs["recovery"]).id,
627
+ );
628
+ case "drain": {
629
+ const typed = args as RpcActionArgs["drain"];
630
+ return drain(typed.graceMs);
631
+ }
347
632
  default:
348
633
  throw new AgentFlowError("ipc", `action ${action} is not allowed`);
349
634
  }
@@ -415,11 +700,62 @@ function validateActionArgs(action: string, args: unknown): unknown {
415
700
  id: requireString(object, "id"),
416
701
  artifactId: requireString(object, "artifactId"),
417
702
  };
703
+ case "pauseRun":
704
+ case "continueRun":
705
+ return {
706
+ id: requireString(object, "id"),
707
+ ...operatorOptions(object, action),
708
+ };
709
+ case "retryRun": {
710
+ const steps = object.steps;
711
+ if (
712
+ steps !== undefined &&
713
+ (!Array.isArray(steps) ||
714
+ steps.some((step) => typeof step !== "string" || step === ""))
715
+ ) {
716
+ throw new AgentFlowError(
717
+ "ipc",
718
+ "retryRun args.steps must be an array of non-empty strings",
719
+ );
720
+ }
721
+ return {
722
+ id: requireString(object, "id"),
723
+ ...operatorOptions(object, action),
724
+ ...(steps === undefined ? {} : { steps }),
725
+ };
726
+ }
727
+ case "limitRun": {
728
+ const maxConcurrent = object.maxConcurrent;
729
+ if (
730
+ typeof maxConcurrent !== "number" ||
731
+ !Number.isSafeInteger(maxConcurrent) ||
732
+ maxConcurrent < 1
733
+ ) {
734
+ throw new AgentFlowError(
735
+ "ipc",
736
+ "limitRun args.maxConcurrent must be a positive safe integer",
737
+ );
738
+ }
739
+ return {
740
+ id: requireString(object, "id"),
741
+ maxConcurrent,
742
+ ...operatorOptions(object, action),
743
+ };
744
+ }
745
+ case "amendRun":
746
+ return parseAmendRunArgs({
747
+ ...object,
748
+ id: requireString(object, "id"),
749
+ });
750
+ case "operations":
751
+ case "recovery":
752
+ return { id: requireString(object, "id") };
753
+ case "drain":
754
+ return optionalNumber(object, "graceMs");
418
755
  default:
419
756
  throw new AgentFlowError("ipc", `unknown action ${action}`);
420
757
  }
421
758
  }
422
-
423
759
  function requireString(object: Record<string, unknown>, key: string): string {
424
760
  const value = object[key];
425
761
  if (typeof value !== "string" || value === "") {
@@ -455,6 +791,13 @@ function optionalNumber(
455
791
  return { [key]: value };
456
792
  }
457
793
 
794
+ function graceIsInvalid(value: unknown): boolean {
795
+ return (
796
+ value !== undefined &&
797
+ (typeof value !== "number" || !Number.isFinite(value) || value < 0)
798
+ );
799
+ }
800
+
458
801
  function preparePrivateDirectory(directory: string, label: string): void {
459
802
  let stats: Stats | undefined;
460
803
  try {
@@ -507,20 +850,21 @@ function currentUid(): number | undefined {
507
850
  return typeof process.getuid === "function" ? process.getuid() : undefined;
508
851
  }
509
852
 
510
- function assertCustomSocketAvailable(socketPath: string): void {
511
- try {
512
- lstatSync(socketPath);
513
- } catch (error) {
514
- if ((error as { code?: string }).code === "ENOENT") return;
515
- throw error;
516
- }
517
- throw new AgentFlowError(
518
- "conflict",
519
- `custom socket path is already occupied: ${socketPath}`,
520
- );
521
- }
522
-
523
- async function removeStaleDefaultSocket(socketPath: string): Promise<void> {
853
+ /**
854
+ * Reclaims a custom socket only when this state directory's own receipt proves
855
+ * the path was bound by this daemon's predecessor for this state.
856
+ *
857
+ * Reclaim requires every proof: the receipt is a same-owner 0600 regular file,
858
+ * records exactly this state dir and this canonical path with the identity
859
+ * (device/inode) that is still present, the path is a same-owner socket that
860
+ * refuses connections, and the identity still matches right before unlink.
861
+ * Any other path — active, foreign, unrecorded, or replaced — is untouched and
862
+ * rejected exactly like before.
863
+ */
864
+ async function reclaimStaleCustomSocket(
865
+ stateDir: string,
866
+ socketPath: string,
867
+ ): Promise<void> {
524
868
  let stats: Stats;
525
869
  try {
526
870
  stats = lstatSync(socketPath);
@@ -528,26 +872,26 @@ async function removeStaleDefaultSocket(socketPath: string): Promise<void> {
528
872
  if ((error as { code?: string }).code === "ENOENT") return;
529
873
  throw error;
530
874
  }
531
- if (!stats.isSocket()) {
532
- throw new AgentFlowError(
533
- "conflict",
534
- `socket path exists and is not a socket: ${socketPath}`,
535
- );
536
- }
875
+
876
+ const realStateDir = realpathSync(stateDir);
877
+ const canonicalPath = resolve(socketPath);
537
878
  const uid = currentUid();
538
- if (uid !== undefined && stats.uid !== uid) {
539
- throw new AgentFlowError(
540
- "conflict",
541
- `socket path is owned by another user: ${socketPath}`,
542
- );
879
+ if (
880
+ !stats.isSocket() ||
881
+ (uid !== undefined && stats.uid !== uid) ||
882
+ !receiptMatches(
883
+ realStateDir,
884
+ canonicalPath,
885
+ { dev: stats.dev, ino: stats.ino },
886
+ uid,
887
+ )
888
+ ) {
889
+ throw occupiedCustomSocket(socketPath);
543
890
  }
544
891
 
545
892
  const identity: FileIdentity = { dev: stats.dev, ino: stats.ino };
546
893
  if (await socketAcceptsConnections(socketPath)) {
547
- throw new AgentFlowError(
548
- "conflict",
549
- `socket path is already in use: ${socketPath}`,
550
- );
894
+ throw occupiedCustomSocket(socketPath);
551
895
  }
552
896
 
553
897
  let current: Stats;
@@ -557,15 +901,15 @@ async function removeStaleDefaultSocket(socketPath: string): Promise<void> {
557
901
  if ((error as { code?: string }).code === "ENOENT") return;
558
902
  throw error;
559
903
  }
904
+ // Re-check the identity immediately before unlink so a socket that was
905
+ // replaced while probing is never removed.
560
906
  if (
561
907
  !current.isSocket() ||
908
+ (uid !== undefined && current.uid !== uid) ||
562
909
  current.dev !== identity.dev ||
563
910
  current.ino !== identity.ino
564
911
  ) {
565
- throw new AgentFlowError(
566
- "conflict",
567
- `socket path changed while checking it: ${socketPath}`,
568
- );
912
+ throw occupiedCustomSocket(socketPath);
569
913
  }
570
914
 
571
915
  try {
@@ -575,6 +919,91 @@ async function removeStaleDefaultSocket(socketPath: string): Promise<void> {
575
919
  }
576
920
  }
577
921
 
922
+ function occupiedCustomSocket(socketPath: string): AgentFlowError {
923
+ return new AgentFlowError(
924
+ "conflict",
925
+ `custom socket path is already occupied: ${socketPath}`,
926
+ );
927
+ }
928
+
929
+ function socketReceiptPath(stateDir: string): string {
930
+ return join(stateDir, SOCKET_RECEIPT_FILE);
931
+ }
932
+
933
+ /**
934
+ * True only when the receipt belongs to this state directory and records the
935
+ * exact canonical socket path and the exact device/inode observed now. The
936
+ * receipt must itself be a same-owner 0600 regular file.
937
+ */
938
+ function receiptMatches(
939
+ realStateDir: string,
940
+ canonicalPath: string,
941
+ identity: FileIdentity,
942
+ uid: number | undefined,
943
+ ): boolean {
944
+ const path = socketReceiptPath(realStateDir);
945
+ try {
946
+ const stats = lstatSync(path);
947
+ if (
948
+ !stats.isFile() ||
949
+ (stats.mode & 0o7777) !== 0o600 ||
950
+ (uid !== undefined && stats.uid !== uid)
951
+ ) {
952
+ return false;
953
+ }
954
+ const record: unknown = JSON.parse(readFileSync(path, "utf8"));
955
+ if (!isPlainObject(record)) return false;
956
+ return (
957
+ record.stateDir === realStateDir &&
958
+ record.socketPath === canonicalPath &&
959
+ record.dev === identity.dev &&
960
+ record.ino === identity.ino
961
+ );
962
+ } catch {
963
+ return false;
964
+ }
965
+ }
966
+
967
+ /** Atomically publishes this daemon's receipt for its custom socket. */
968
+ function writeSocketReceipt(
969
+ stateDir: string,
970
+ socketPath: string,
971
+ identity: FileIdentity,
972
+ ): void {
973
+ const path = socketReceiptPath(stateDir);
974
+ const tempPath = `${path}.${process.pid}.${crypto.randomUUID()}.tmp`;
975
+ let tempCreated = false;
976
+ try {
977
+ writeFileSync(
978
+ tempPath,
979
+ `${JSON.stringify({
980
+ stateDir: realpathSync(stateDir),
981
+ socketPath: resolve(socketPath),
982
+ dev: identity.dev,
983
+ ino: identity.ino,
984
+ })}\n`,
985
+ { encoding: "utf8", mode: 0o600, flag: "wx" },
986
+ );
987
+ tempCreated = true;
988
+ // A hard link never replaces an existing receipt; a leftover receipt from
989
+ // a predecessor is replaced only once startup proved it stale.
990
+ try {
991
+ unlinkSync(path);
992
+ } catch (error) {
993
+ if ((error as { code?: string }).code !== "ENOENT") throw error;
994
+ }
995
+ linkSync(tempPath, path);
996
+ } finally {
997
+ if (tempCreated) {
998
+ try {
999
+ unlinkSync(tempPath);
1000
+ } catch {
1001
+ // Another process may have removed our temporary name.
1002
+ }
1003
+ }
1004
+ }
1005
+ }
1006
+
578
1007
  function socketAcceptsConnections(socketPath: string): Promise<boolean> {
579
1008
  return new Promise((resolve) => {
580
1009
  const timer = setTimeout(() => resolve(true), SOCKET_PROBE_TIMEOUT_MS);
@@ -622,6 +1051,7 @@ function removeOwnedSocket(socketPath: string, identity: FileIdentity): void {
622
1051
  if (!stats.isSocket()) return;
623
1052
  const uid = currentUid();
624
1053
  if (uid !== undefined && stats.uid !== uid) return;
1054
+ // Only the socket this process bound is removed; a replaced path is left.
625
1055
  if (stats.dev !== identity.dev || stats.ino !== identity.ino) return;
626
1056
  unlinkSync(socketPath);
627
1057
  } catch {
@@ -629,6 +1059,64 @@ function removeOwnedSocket(socketPath: string, identity: FileIdentity): void {
629
1059
  }
630
1060
  }
631
1061
 
1062
+ async function removeStaleDefaultSocket(socketPath: string): Promise<void> {
1063
+ let stats: Stats;
1064
+ try {
1065
+ stats = lstatSync(socketPath);
1066
+ } catch (error) {
1067
+ if ((error as { code?: string }).code === "ENOENT") return;
1068
+ throw error;
1069
+ }
1070
+ if (!stats.isSocket()) {
1071
+ throw new AgentFlowError(
1072
+ "conflict",
1073
+ `socket path exists and is not a socket: ${socketPath}`,
1074
+ );
1075
+ }
1076
+ const uid = currentUid();
1077
+ if (uid !== undefined && stats.uid !== uid) {
1078
+ throw new AgentFlowError(
1079
+ "conflict",
1080
+ `socket path is owned by another user: ${socketPath}`,
1081
+ );
1082
+ }
1083
+
1084
+ // Holding this state directory's lock proves the socket belongs to no live
1085
+ // daemon, so an accepting socket here is a foreign process, not ours.
1086
+ if (await socketAcceptsConnections(socketPath)) {
1087
+ throw new AgentFlowError(
1088
+ "conflict",
1089
+ `socket path is already in use: ${socketPath}`,
1090
+ );
1091
+ }
1092
+
1093
+ const identity: FileIdentity = { dev: stats.dev, ino: stats.ino };
1094
+ let current: Stats;
1095
+ try {
1096
+ current = lstatSync(socketPath);
1097
+ } catch (error) {
1098
+ if ((error as { code?: string }).code === "ENOENT") return;
1099
+ throw error;
1100
+ }
1101
+ // Never unlink a socket that was replaced while it was being probed.
1102
+ if (
1103
+ !current.isSocket() ||
1104
+ current.dev !== identity.dev ||
1105
+ current.ino !== identity.ino
1106
+ ) {
1107
+ throw new AgentFlowError(
1108
+ "conflict",
1109
+ `socket path changed while checking it: ${socketPath}`,
1110
+ );
1111
+ }
1112
+
1113
+ try {
1114
+ unlinkSync(socketPath);
1115
+ } catch (error) {
1116
+ if ((error as { code?: string }).code !== "ENOENT") throw error;
1117
+ }
1118
+ }
1119
+
632
1120
  function acquireLock(stateDir: string): LockHandle {
633
1121
  const path = join(stateDir, "daemon.lock");
634
1122
  const content = `${process.pid}\n`;