@narumitw/pi-sync-daemon 0.3.0 → 0.5.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/dist/client.js CHANGED
@@ -4,7 +4,9 @@ import { request as httpRequest } from "node:http";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import lockfile from "proper-lockfile";
7
- import { daemonPaths, privateDirectory, processExists, readIdentity, readJsonBody, runtimePaths, } from "./identity.js";
7
+ import { lt, valid } from "semver";
8
+ import { DAEMON_BUILD_VERSION } from "./build-version.js";
9
+ import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readJsonBody, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
8
10
  import { withCleanup } from "./lifecycle.js";
9
11
  import { MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, REVIEW_PAGE_CHARS, record, } from "./protocol.js";
10
12
  export class DaemonError extends Error {
@@ -47,9 +49,9 @@ export async function requestDaemon(paths, identity, method, params, signal) {
47
49
  })
48
50
  .catch(reject);
49
51
  });
50
- // Attach can wait behind a complete apply. Its connection-owned signal/dispose
51
- // cancels that wait; an idle timeout must not let startup escape the admission fence.
52
- request.setTimeout(method === "attach" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
52
+ // Admission can wait behind a complete apply. The request owner's signal
53
+ // cancels that wait; an idle timeout must not let admission escape the fence.
54
+ request.setTimeout(method === "attach" || method === "resume-contact" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
53
55
  request.once("error", reject);
54
56
  request.end(body);
55
57
  });
@@ -62,35 +64,119 @@ async function hello(paths, identity, signal) {
62
64
  value.instance !== identity.instance ||
63
65
  value.pid !== identity.pid)
64
66
  throw new Error("Daemon handshake mismatch.");
67
+ const version = value.buildVersion;
68
+ if (Object.hasOwn(value, "buildVersion") && (typeof version !== "string" || valid(version) !== version))
69
+ throw new Error("Invalid daemon build version.");
70
+ // The old @narumitw/sync-daemon used the same wire protocol without a build version.
71
+ return { needsUpgrade: typeof version !== "string" || lt(version, DAEMON_BUILD_VERSION) };
72
+ }
73
+ async function checkUpgradeConsent(paths, assertRoot, signal) {
74
+ const { readConsent } = await import("./consent.js");
75
+ const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
76
+ signal?.throwIfAborted();
77
+ await withStateDirectoryGuardForRoot(paths.root, () => {
78
+ signal?.throwIfAborted();
79
+ assertRoot();
80
+ // An older owner cannot report an in-memory revocation failure.
81
+ const consent = readConsent(paths.root);
82
+ if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
83
+ throw new Error("Review or revoke unattended Pi Sync permission before restarting the older daemon.");
84
+ });
85
+ signal?.throwIfAborted();
86
+ assertRoot();
87
+ }
88
+ async function finishUpgrade(paths, owner, assertRoot, signal) {
89
+ await waitForProcessExit(owner, signal);
90
+ if ((await readIdentity(paths))?.instance === owner.instance)
91
+ throw new Error("The daemon exited without releasing its identity.");
92
+ await checkUpgradeConsent(paths, assertRoot, signal);
93
+ await clearUpgradeOwner(paths);
94
+ signal?.throwIfAborted();
95
+ assertRoot();
96
+ }
97
+ async function drainForUpgrade(paths, owner, { recorded, birth }, assertRoot, signal) {
98
+ await checkUpgradeConsent(paths, assertRoot, signal);
99
+ const barrier = recorded ?? { ...owner, birth };
100
+ try {
101
+ // Publish this before stop can remove the identity. A retry keeps the original evidence.
102
+ if (!recorded)
103
+ await recordUpgradeOwner(paths, barrier);
104
+ assertRoot();
105
+ const reply = await requestDaemon(paths, owner, "stop", {}, signal);
106
+ if (!record(reply) || reply.stopping !== true)
107
+ throw new Error("Daemon did not acknowledge stop.");
108
+ }
109
+ catch (error) {
110
+ signal?.throwIfAborted();
111
+ throw new Error("Pi Sync could not upgrade the older daemon safely. Check `pi-sync-daemon status --root <agent-directory>`. Do not force a second owner or remove recovery files.", { cause: error });
112
+ }
113
+ await finishUpgrade(paths, barrier, assertRoot, signal);
114
+ }
115
+ export async function acquireStartupLock(paths, signal) {
116
+ // Include the handshake, stop, exit wait, boot, and final handshake budgets.
117
+ const deadline = performance.now() + 150_000;
118
+ for (;;) {
119
+ signal?.throwIfAborted();
120
+ try {
121
+ return await lockfile.lock(paths.directory, {
122
+ realpath: false,
123
+ lockfilePath: paths.startup,
124
+ stale: 30_000,
125
+ update: 5_000,
126
+ });
127
+ }
128
+ catch (error) {
129
+ signal?.throwIfAborted();
130
+ if (error.code !== "ELOCKED")
131
+ throw error;
132
+ if (performance.now() >= deadline)
133
+ throw new Error("Timed out waiting to start the Pi Sync daemon.", { cause: error });
134
+ await delay(50, undefined, { signal });
135
+ }
136
+ }
65
137
  }
66
138
  /** Explicit startup only: callers decide whether configuration or a user action authorizes it. */
67
139
  export async function ensureDaemon(root, signal) {
68
140
  const paths = await runtimePaths(root);
141
+ const assertRoot = canonicalRootGuard(paths.root);
69
142
  signal?.throwIfAborted();
70
143
  await privateDirectory(paths.directory);
71
144
  signal?.throwIfAborted();
72
- const release = await lockfile.lock(paths.directory, {
73
- realpath: false,
74
- lockfilePath: paths.startup,
75
- stale: 30_000,
76
- update: 5_000,
77
- retries: { retries: 100, factor: 1, minTimeout: 50, maxTimeout: 50 },
78
- });
145
+ const release = await acquireStartupLock(paths, signal);
79
146
  try {
80
147
  signal?.throwIfAborted();
81
148
  let waited = false;
149
+ let upgraded = false;
82
150
  for (;;) {
151
+ signal?.throwIfAborted();
152
+ const upgrade = await readUpgradeOwner(paths);
153
+ if (upgrade && (await upgradeRepairStarted(paths, upgrade)))
154
+ throw new Error("A daemon upgrade repair is incomplete. Run `pi-sync-daemon repair-upgrade` for this root.");
83
155
  const existing = await readIdentity(paths);
156
+ if (upgrade && existing?.instance === upgrade.instance && existing.pid !== upgrade.pid)
157
+ throw new Error("The recorded upgrade owner changed; private state was retained.");
158
+ if (upgrade && (existing?.instance !== upgrade.instance || (await processExited(upgrade)))) {
159
+ await finishUpgrade(paths, upgrade, assertRoot, signal);
160
+ upgraded = true;
161
+ continue;
162
+ }
84
163
  if (!existing)
85
164
  break;
165
+ // A sample taken only after hello could describe an unrelated process reusing the PID.
166
+ const beforeHello = upgrade ? undefined : await readProcessBirth(existing.pid);
167
+ let status;
86
168
  try {
87
- await hello(paths, existing, signal);
88
- signal?.throwIfAborted();
89
- return { paths: daemonPaths(paths, existing.instance), identity: existing };
169
+ status = await hello(paths, existing, signal);
90
170
  }
91
171
  catch (error) {
92
172
  if (signal?.aborted)
93
173
  throw signal.reason;
174
+ if (upgrade) {
175
+ // The stop may have been accepted even if the old endpoint no longer replies.
176
+ await finishUpgrade(paths, upgrade, assertRoot, signal);
177
+ upgraded = true;
178
+ continue;
179
+ }
94
180
  if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
95
181
  waited = true;
96
182
  await waitForDaemonExit(existing, signal);
@@ -100,7 +186,23 @@ export async function ensureDaemon(root, signal) {
100
186
  throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
101
187
  break;
102
188
  }
189
+ signal?.throwIfAborted();
190
+ assertRoot();
191
+ if (!status.needsUpgrade) {
192
+ if (upgrade)
193
+ throw new Error("The recorded upgrade owner changed; private state was retained.");
194
+ return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status };
195
+ }
196
+ if (upgraded)
197
+ throw new Error("An older Pi Sync daemon started again. Close or upgrade other Pi sessions, then use /reload.");
198
+ const birth = beforeHello === undefined ? undefined : await readProcessBirth(existing.pid);
199
+ if (birth !== undefined && birth !== beforeHello)
200
+ throw new Error("The daemon process changed during authentication; private state was retained.");
201
+ await drainForUpgrade(paths, existing, { recorded: upgrade, birth }, assertRoot, signal);
202
+ upgraded = true;
103
203
  }
204
+ signal?.throwIfAborted();
205
+ assertRoot();
104
206
  const executable = process.versions.bun ? "node" : process.execPath;
105
207
  const child = spawn(executable, [fileURLToPath(new URL("./cli.js", import.meta.url)), "serve", "--root", paths.root], {
106
208
  detached: true,
@@ -152,26 +254,33 @@ export async function ensureDaemon(root, signal) {
152
254
  child.unref();
153
255
  });
154
256
  // Never kill a published shared daemon on caller cancellation.
155
- await hello(paths, ready, signal);
257
+ const status = await hello(paths, ready, signal);
156
258
  signal?.throwIfAborted();
157
- return { paths: daemonPaths(paths, ready.instance), identity: ready };
259
+ assertRoot();
260
+ if (status.needsUpgrade)
261
+ throw new Error("The daemon installation changed during startup. Use /reload to retry.");
262
+ return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status };
158
263
  }
159
264
  finally {
160
265
  await release();
161
266
  }
162
267
  }
163
268
  /** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
164
- export async function waitForDaemonExit(identity, signal) {
269
+ export async function waitForDaemonExit({ pid }, signal) {
270
+ await waitForProcessExit({ pid }, signal);
271
+ }
272
+ async function waitForProcessExit(owner, signal) {
165
273
  const deadline = Date.now() + 30_000;
166
274
  signal?.throwIfAborted();
167
- while (processExists(identity.pid)) {
275
+ while (!(await processExited(owner))) {
276
+ signal?.throwIfAborted();
168
277
  if (Date.now() >= deadline)
169
278
  throw new Error("Closing daemon is still alive; replacement was not attempted.");
170
279
  await delay(25, undefined, { signal });
171
280
  }
172
281
  signal?.throwIfAborted();
173
282
  }
174
- /** Inspect an existing compatible owner without starting one. */
283
+ /** Inspect an existing protocol-compatible owner without starting or replacing it. */
175
284
  export async function findDaemon(root) {
176
285
  let paths;
177
286
  try {
@@ -186,14 +295,14 @@ export async function findDaemon(root) {
186
295
  if (!identity || !processExists(identity.pid))
187
296
  return undefined;
188
297
  try {
189
- await hello(paths, identity);
298
+ const status = await hello(paths, identity);
299
+ return { paths: daemonPaths(paths, identity.instance), identity, ...status };
190
300
  }
191
301
  catch (error) {
192
302
  if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
193
303
  return undefined;
194
304
  throw error;
195
305
  }
196
- return { paths: daemonPaths(paths, identity.instance), identity };
197
306
  }
198
307
  /** Gracefully stop an existing compatible owner without creating a new service. */
199
308
  export async function stopDaemon(root) {
@@ -226,10 +335,18 @@ export class DaemonConnection {
226
335
  callbackTasks = new Set();
227
336
  updates = Promise.resolve();
228
337
  attached = false;
338
+ admitting = false;
339
+ observedContact;
340
+ contactRevision = 0;
341
+ lifecycleRevision = 0;
342
+ resuming;
343
+ resumeUncertain = false;
344
+ pendingJobs = 0;
229
345
  uncertain = false;
230
346
  reportedError = false;
231
347
  commits = new Map();
232
348
  completedCallbacks = new Set();
349
+ pausing;
233
350
  disposing;
234
351
  polling;
235
352
  closed = false;
@@ -239,9 +356,29 @@ export class DaemonConnection {
239
356
  this.facts = facts;
240
357
  this.options = options;
241
358
  }
359
+ /** Latest owner observation, or undefined if contact is unsupported or not observed. */
360
+ get contactState() {
361
+ return this.observedContact;
362
+ }
363
+ /** An uncertain attempt must not be retried or turned into a new attach. */
364
+ get contactResumeState() {
365
+ return this.resumeUncertain ? "uncertain" : this.resuming ? "running" : "idle";
366
+ }
367
+ /** Original submitted jobs must finish (or be reconciled) before repairing contact. */
368
+ get hasPendingWork() {
369
+ return this.pendingJobs > 0 || this.uncertain;
370
+ }
242
371
  async attach(signal) {
243
- if (this.closed || this.uncertain)
372
+ if (this.closed ||
373
+ this.hasPendingWork ||
374
+ this.contactResumeState !== "idle" ||
375
+ this.admitting ||
376
+ this.pausing ||
377
+ this.disposing)
244
378
  throw new Error("Daemon client is unavailable; reconnect after draining work.");
379
+ this.admitting = true;
380
+ this.lifecycleRevision++;
381
+ this.contactRevision++;
245
382
  const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal);
246
383
  // Poll during attach: stopping a previous controller may need release answers
247
384
  // from this reattached participant before the attach response can complete.
@@ -250,7 +387,7 @@ export class DaemonConnection {
250
387
  try {
251
388
  const result = await request;
252
389
  admitted = true;
253
- this.consume(result);
390
+ this.publishContact(this.consume(result));
254
391
  this.attached = true;
255
392
  return this;
256
393
  }
@@ -279,24 +416,111 @@ export class DaemonConnection {
279
416
  }
280
417
  });
281
418
  }
419
+ finally {
420
+ this.admitting = false;
421
+ }
282
422
  }
283
- update(facts) {
423
+ async update(facts) {
424
+ const lifecycle = this.lifecycleRevision;
425
+ if (this.admitting || this.pausing || this.disposing)
426
+ throw new Error("Daemon client is changing; wait before updating facts.");
284
427
  const update = this.updates.then(async () => {
285
- if (this.closed || this.uncertain)
428
+ if (this.closed || this.uncertain || this.resumeUncertain || lifecycle !== this.lifecycleRevision)
286
429
  throw new Error("Daemon client is unavailable; reconnect after draining work.");
287
- const result = await requestDaemon(this.paths, this.identity, "update", { facts }, this.controller.signal);
430
+ const revision = this.contactRevision;
431
+ let result;
432
+ try {
433
+ result = await requestDaemon(this.paths, this.identity, "update", { facts }, this.controller.signal);
434
+ }
435
+ catch (error) {
436
+ if (this.attached &&
437
+ revision === this.contactRevision &&
438
+ this.sameClient(facts) &&
439
+ error instanceof DaemonError &&
440
+ error.remote.name === "ClientContactExpiredError")
441
+ this.publishContact("expired");
442
+ throw error;
443
+ }
288
444
  if (this.closed)
289
445
  throw new Error("Daemon client closed during update.");
446
+ if (revision !== this.contactRevision)
447
+ throw new Error("Daemon client changed during update.");
448
+ const contact = this.consume(result);
449
+ if (revision !== this.contactRevision)
450
+ throw new Error("Daemon client changed during update.");
290
451
  Object.assign(this.facts, facts);
291
- this.consume(result);
452
+ this.publishContact(contact);
292
453
  });
293
454
  this.updates = update.catch(() => { });
294
455
  return update;
295
456
  }
457
+ /** Resume this participant without replacing its callbacks, jobs, or polling. */
458
+ async resumeContact(facts, signal) {
459
+ signal?.throwIfAborted();
460
+ if (this.contactResumeState !== "idle")
461
+ throw new Error("Daemon contact resume is running or uncertain.");
462
+ const check = () => {
463
+ if (!this.attached || this.admitting || this.pausing || this.disposing || this.closed || this.hasPendingWork)
464
+ throw new Error("Daemon client is unavailable; reconnect after draining work.");
465
+ if (!this.sameClient(facts) || this.contactState !== "expired")
466
+ throw new Error("No confirmed contact expiry for this daemon client.");
467
+ };
468
+ facts = structuredClone(facts);
469
+ check();
470
+ const resume = new AbortController();
471
+ this.resuming = resume;
472
+ const ownedSignal = signal ? AbortSignal.any([signal, resume.signal]) : resume.signal;
473
+ let sent = false;
474
+ const attempt = this.updates.then(async () => {
475
+ ownedSignal.throwIfAborted();
476
+ check();
477
+ sent = true;
478
+ const reply = await requestDaemon(this.paths, this.identity, "resume-contact", facts, ownedSignal);
479
+ ownedSignal.throwIfAborted();
480
+ const contact = this.consume(reply);
481
+ ownedSignal.throwIfAborted();
482
+ if (contact !== "active")
483
+ throw new Error("Daemon did not confirm resumed contact.");
484
+ Object.assign(this.facts, facts);
485
+ this.publishContact(contact);
486
+ });
487
+ this.updates = attempt.catch(() => { });
488
+ // Reject a queued repair on cancellation even if the earlier update has not finished.
489
+ const cancellation = Promise.withResolvers();
490
+ const abort = () => cancellation.reject(ownedSignal.reason);
491
+ ownedSignal.addEventListener("abort", abort, { once: true });
492
+ try {
493
+ await Promise.race([attempt, cancellation.promise]);
494
+ }
495
+ catch (error) {
496
+ if (sent) {
497
+ // The protocol does not distinguish definite pre-publication refusal from a lost acknowledgement.
498
+ this.resumeUncertain = true;
499
+ for (const { controller, kind } of this.callbacks.values())
500
+ if (kind !== "queue-release")
501
+ controller.abort();
502
+ }
503
+ throw error;
504
+ }
505
+ finally {
506
+ this.resuming = undefined;
507
+ ownedSignal.removeEventListener("abort", abort);
508
+ }
509
+ }
510
+ sameClient(facts) {
511
+ return facts.id === this.facts.id && facts.pid === this.facts.pid && facts.generation === this.facts.generation;
512
+ }
296
513
  async run(operation, payload, signal, onCommit) {
297
- if (this.closed || this.uncertain)
298
- throw new Error("Daemon client is unavailable; reconnect after draining work.");
514
+ if (this.closed ||
515
+ this.uncertain ||
516
+ this.contactResumeState !== "idle" ||
517
+ this.pausing ||
518
+ this.disposing ||
519
+ this.contactState === "expired" ||
520
+ this.contactState === "inactive")
521
+ throw new Error("Daemon client is unavailable; confirm contact and drain work before submitting.");
299
522
  signal?.throwIfAborted();
523
+ this.pendingJobs++;
300
524
  const id = `${operationPrefix(this.identity)}${randomUUID()}`;
301
525
  const abort = () => {
302
526
  void requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id }, this.controller.signal).catch(() => { });
@@ -313,11 +537,11 @@ export class DaemonConnection {
313
537
  const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor, job: id }, this.controller.signal);
314
538
  this.consume(reply);
315
539
  const job = record(reply) ? reply.job : undefined;
316
- if (job?.phase === "failed") {
540
+ if (job?.id === id && job.phase === "failed") {
317
541
  terminal = true;
318
542
  throw new DaemonError(job.error ?? { name: "Error", message: "Daemon operation failed." });
319
543
  }
320
- if (job?.phase === "done") {
544
+ if (job?.id === id && job.phase === "done") {
321
545
  terminal = true;
322
546
  signal?.throwIfAborted();
323
547
  return job.result;
@@ -343,7 +567,11 @@ export class DaemonConnection {
343
567
  throw new Error("Operation outcome is uncertain; reload to reconnect and reconcile, never replay the write.", { cause: error });
344
568
  }
345
569
  }
346
- });
570
+ }).finally(() => this.pendingJobs--);
571
+ }
572
+ publishContact(contact) {
573
+ this.contactRevision++;
574
+ this.observedContact = contact;
347
575
  }
348
576
  consume(reply) {
349
577
  if (!record(reply) ||
@@ -353,8 +581,11 @@ export class DaemonConnection {
353
581
  !Array.isArray(reply.callbacks) ||
354
582
  !Array.isArray(reply.events))
355
583
  throw new Error("Invalid daemon poll response.");
584
+ const { contact } = reply;
585
+ if (contact !== undefined && contact !== "active" && contact !== "expired" && contact !== "inactive")
586
+ throw new Error("Invalid daemon contact state.");
356
587
  if (reply.cursor < this.cursor)
357
- return;
588
+ return contact;
358
589
  for (const event of reply.events)
359
590
  if (event.id > this.cursor) {
360
591
  if (event.kind === "commit" && record(event.payload) && typeof event.payload.job === "string") {
@@ -381,7 +612,7 @@ export class DaemonConnection {
381
612
  let value;
382
613
  let failed = false;
383
614
  try {
384
- if (this.uncertain && callback.kind !== "queue-release")
615
+ if ((this.uncertain || this.resumeUncertain) && callback.kind !== "queue-release")
385
616
  throw new Error("Client is draining uncertain work.");
386
617
  value = await this.performCallback(callback, controller.signal);
387
618
  }
@@ -406,6 +637,7 @@ export class DaemonConnection {
406
637
  });
407
638
  this.callbackTasks.add(task);
408
639
  }
640
+ return contact;
409
641
  }
410
642
  async performCallback(callback, signal) {
411
643
  const reference = callback.review;
@@ -475,9 +707,25 @@ export class DaemonConnection {
475
707
  async poll() {
476
708
  while (!this.closed) {
477
709
  try {
710
+ const revision = this.contactRevision;
478
711
  const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor }, this.controller.signal);
479
- this.consume(reply);
480
- this.reportedError = false;
712
+ // An older poll must not undo typed update expiry or a successful resume.
713
+ if (revision === this.contactRevision) {
714
+ const contact = this.consume(reply);
715
+ this.reportedError = false;
716
+ if (revision === this.contactRevision &&
717
+ this.attached &&
718
+ !this.admitting &&
719
+ !this.pausing &&
720
+ !this.disposing &&
721
+ !this.closed) {
722
+ // A new observation fences older facts replies; identical polls do not.
723
+ if (contact !== this.observedContact)
724
+ this.publishContact(contact);
725
+ if (contact !== undefined)
726
+ this.options.contact?.(contact);
727
+ }
728
+ }
481
729
  await this.wait(100);
482
730
  }
483
731
  catch (error) {
@@ -495,16 +743,31 @@ export class DaemonConnection {
495
743
  }
496
744
  }
497
745
  async pause() {
498
- if (this.closed)
746
+ if (this.closed || this.disposing)
499
747
  throw new Error("Daemon client is closed.");
500
- const reply = await requestDaemon(this.paths, this.identity, "pause", { client: this.facts.id });
501
- this.consume(reply);
748
+ if (this.pausing)
749
+ return this.pausing;
750
+ this.resuming?.abort(new DOMException("Client paused", "AbortError"));
751
+ this.lifecycleRevision++;
752
+ this.contactRevision++;
753
+ this.pausing = (async () => {
754
+ const reply = await requestDaemon(this.paths, this.identity, "pause", { client: this.facts.id });
755
+ const contact = this.consume(reply);
756
+ if (!this.disposing)
757
+ this.publishContact(contact);
758
+ })().finally(() => {
759
+ this.pausing = undefined;
760
+ });
761
+ return this.pausing;
502
762
  }
503
763
  async dispose(handoff) {
504
764
  if (this.disposing)
505
765
  return this.disposing;
506
766
  if (this.closed)
507
767
  return;
768
+ this.resuming?.abort(new DOMException("Client disposed", "AbortError"));
769
+ this.lifecycleRevision++;
770
+ this.contactRevision++;
508
771
  this.disposing = (async () => {
509
772
  this.polling ??= this.poll();
510
773
  // Cancel UI before drain, but keep polling for acknowledged queue-release callbacks.
package/dist/consent.d.ts CHANGED
@@ -17,6 +17,8 @@ export declare class ConsentPublicationError extends Error {
17
17
  }
18
18
  /** A different interactive binding cannot silently resume an older unattended grant after exit/restart. */
19
19
  export declare function revokeChangedBindings(root: string, peers: readonly ClientFacts[]): void;
20
+ /** Explicit offline repair only. The caller must exclude daemon owners and state migration. */
21
+ export declare function revokeRetainedGrants(root: string): number;
20
22
  export declare function readConsent(root: string): Consent | undefined;
21
23
  export declare function consentFingerprint(root: string, config: AnySyncConfig): string;
22
24
  export declare function requireHandover(execution: Execution): Promise<void>;
package/dist/consent.js CHANGED
@@ -4,18 +4,40 @@ import path from "node:path";
4
4
  import { syncCheckConfigFingerprint } from "./engine/settings/config.js";
5
5
  import { stateDir } from "./engine/state/state-directory.js";
6
6
  import { record } from "./protocol.js";
7
- function file() {
8
- return path.join(stateDir(), "daemon.json");
7
+ function file(root) {
8
+ return path.join(stateDir(root), "daemon.json");
9
9
  }
10
10
  export class ConsentPublicationError extends Error {
11
11
  }
12
+ const FORMATTED_CONSENT_BYTES = 65_536;
13
+ // Each legacy grant already uses at least 64 bytes for its fingerprint. Reserving one byte per
14
+ // grant covers all legacy writes, including compact files, when `true` becomes `false`.
15
+ const MAX_CONSENT_BYTES = FORMATTED_CONSENT_BYTES + FORMATTED_CONSENT_BYTES / 64;
16
+ function compactConsentWithRevocationReserve(value) {
17
+ const compact = JSON.stringify(value);
18
+ const grantCount = Object.values(value.setups).filter((setup) => setup.afterExit).length;
19
+ if (Buffer.byteLength(compact) + grantCount > MAX_CONSENT_BYTES)
20
+ throw new Error("Daemon consent exceeds its storage bound; existing evidence retained.");
21
+ return compact;
22
+ }
23
+ function syncConsentDirectory(target) {
24
+ if (process.platform === "win32")
25
+ return;
26
+ const directory = openSync(path.dirname(target), "r");
27
+ try {
28
+ fsyncSync(directory);
29
+ }
30
+ finally {
31
+ closeSync(directory);
32
+ }
33
+ }
12
34
  /** A small synchronous publication keeps approval, metadata revocation, and rename in one event-loop turn. */
13
35
  function publishConsent(value) {
14
36
  try {
15
- const target = file();
16
- const content = `${JSON.stringify(value, null, "\t")}\n`;
17
- if (Buffer.byteLength(content) > 65_536)
18
- throw new Error("Daemon consent exceeds its storage bound; existing evidence retained.");
37
+ const target = file(value.root);
38
+ const compact = compactConsentWithRevocationReserve(value);
39
+ const formatted = `${JSON.stringify(value, null, "\t")}\n`;
40
+ const content = Buffer.byteLength(formatted) <= FORMATTED_CONSENT_BYTES ? formatted : compact;
19
41
  mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
20
42
  const temporary = `${target}.${process.pid}.${randomBytes(16).toString("hex")}.tmp`;
21
43
  const handle = openSync(temporary, "wx", 0o600);
@@ -28,15 +50,7 @@ function publishConsent(value) {
28
50
  closeSync(handle);
29
51
  }
30
52
  renameSync(temporary, target);
31
- if (process.platform !== "win32") {
32
- const directory = openSync(path.dirname(target), "r");
33
- try {
34
- fsyncSync(directory);
35
- }
36
- finally {
37
- closeSync(directory);
38
- }
39
- }
53
+ syncConsentDirectory(target);
40
54
  }
41
55
  finally {
42
56
  rmSync(temporary, { force: true });
@@ -67,14 +81,33 @@ export function revokeChangedBindings(root, peers) {
67
81
  if (changed)
68
82
  publishConsent(consent);
69
83
  }
84
+ /** Explicit offline repair only. The caller must exclude daemon owners and state migration. */
85
+ export function revokeRetainedGrants(root) {
86
+ const consent = readConsent(root);
87
+ if (!consent)
88
+ return 0;
89
+ let revoked = 0;
90
+ for (const saved of Object.values(consent.setups)) {
91
+ if (!saved.afterExit)
92
+ continue;
93
+ saved.afterExit = false;
94
+ revoked += 1;
95
+ }
96
+ if (revoked)
97
+ publishConsent(consent);
98
+ // A prior attempt may have renamed the synced file but failed to sync the directory.
99
+ else
100
+ syncConsentDirectory(file(root));
101
+ return revoked;
102
+ }
70
103
  export function readConsent(root) {
71
- const target = file();
104
+ const target = file(root);
72
105
  let handle;
73
106
  try {
74
107
  const before = lstatSync(target);
75
108
  if (!before.isFile() ||
76
109
  before.isSymbolicLink() ||
77
- before.size > 65_536 ||
110
+ before.size > MAX_CONSENT_BYTES ||
78
111
  (process.getuid && before.uid !== process.getuid()) ||
79
112
  (process.platform !== "win32" && before.mode & 0o077))
80
113
  throw new Error("Unsafe daemon consent document; evidence retained.");
@@ -109,7 +142,9 @@ export function readConsent(root) {
109
142
  !["stored", "environment", "models_json_key", "models_json_command"].includes(String(entry.model.authSource)))))
110
143
  throw new Error("Invalid daemon setup consent.");
111
144
  }
112
- return value;
145
+ const consent = value;
146
+ compactConsentWithRevocationReserve(consent);
147
+ return consent;
113
148
  }
114
149
  catch (error) {
115
150
  if (error.code === "ENOENT")
@@ -7,8 +7,10 @@ export type StateDirectoryPreparation = {
7
7
  status: "deferred";
8
8
  message: string;
9
9
  };
10
- export declare function stateDir(): string;
11
- export declare function legacyStateDir(): string;
10
+ export declare function stateDir(root?: string): string;
11
+ export declare function legacyStateDir(root?: string): string;
12
12
  export declare function stateDirectoryMigrationNotice(): "Legacy pi-sync state is still stored in .pisync. Close other Pi sessions, then run /sync migrate-state to move it to pi-sync/." | undefined;
13
13
  export declare function withStateDirectoryAccess<T>(fn: () => Promise<T>): Promise<T>;
14
14
  export declare function migrateLegacyStateDirectory(): Promise<StateDirectoryPreparation>;
15
+ /** Protect path selection and a synchronous access outside the engine host. */
16
+ export declare function withStateDirectoryGuardForRoot<T>(root: string, access: () => T): Promise<T>;