@narumitw/pi-sync 0.60.2 → 0.60.4

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 (44) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +4 -0
  3. package/dist/chunks/{chunk-B53FS4RW.ts → chunk-IGDI5CIH.ts} +2 -2
  4. package/dist/chunks/{chunk-ENFHHB5O.ts → chunk-OVCP2SOB.ts} +42 -6
  5. package/dist/chunks/chunk-OVCP2SOB.ts.map +7 -0
  6. package/dist/chunks/{chunk-E7UJHMNW.ts → chunk-RJZIKZI3.ts} +2 -2
  7. package/dist/chunks/{chunk-3YXBG7BQ.ts → chunk-SE7HHBKH.ts} +2 -2
  8. package/dist/chunks/{chunk-FOMZEZER.ts → chunk-VQRDL3SY.ts} +227 -54
  9. package/dist/chunks/chunk-VQRDL3SY.ts.map +7 -0
  10. package/dist/chunks/{command-handler-RTBEFZUX.ts → command-handler-TMH4US44.ts} +10 -8
  11. package/dist/chunks/command-handler-TMH4US44.ts.map +7 -0
  12. package/dist/chunks/{conflict-review-YXROU42F.ts → conflict-review-QGUCODDH.ts} +3 -3
  13. package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts → manager-result-dispatcher-YVVD44QD.ts} +4 -4
  14. package/dist/chunks/{manager-ui-TNAMQNEU.ts → manager-ui-Q54OHOPR.ts} +8 -8
  15. package/dist/chunks/{remote-selection-ui-47H7V62F.ts → remote-selection-ui-ODSUHX5N.ts} +3 -3
  16. package/dist/chunks/{sync-inspection-5GQEB62G.ts → sync-inspection-ECUTWISE.ts} +3 -3
  17. package/dist/chunks/{sync-operations-65HDA67O.ts → sync-operations-REXODWZB.ts} +3 -3
  18. package/dist/index.ts +58 -39
  19. package/dist/index.ts.map +3 -3
  20. package/docs/agent-mode-verification.md +1 -1
  21. package/docs/agent-quality-verification.md +1 -1
  22. package/docs/continuous-sync-verification.md +1 -1
  23. package/docs/daemon-migration.md +82 -6
  24. package/docs/tui-contract.md +7 -1
  25. package/package.json +3 -3
  26. package/skills/configure-pi-sync/references/configuration.md +1 -0
  27. package/src/commands/command-execution.ts +1 -1
  28. package/src/commands/command-handler.ts +2 -0
  29. package/src/daemon/pi-client.ts +240 -51
  30. package/src/sync-extension.ts +62 -41
  31. package/src/ui/sync-status.ts +47 -4
  32. package/dist/chunks/chunk-ENFHHB5O.ts.map +0 -7
  33. package/dist/chunks/chunk-FOMZEZER.ts.map +0 -7
  34. package/dist/chunks/command-handler-RTBEFZUX.ts.map +0 -7
  35. package/docs/settings.md +0 -90
  36. /package/dist/chunks/{chunk-B53FS4RW.ts.map → chunk-IGDI5CIH.ts.map} +0 -0
  37. /package/dist/chunks/{chunk-E7UJHMNW.ts.map → chunk-RJZIKZI3.ts.map} +0 -0
  38. /package/dist/chunks/{chunk-3YXBG7BQ.ts.map → chunk-SE7HHBKH.ts.map} +0 -0
  39. /package/dist/chunks/{conflict-review-YXROU42F.ts.map → conflict-review-QGUCODDH.ts.map} +0 -0
  40. /package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts.map → manager-result-dispatcher-YVVD44QD.ts.map} +0 -0
  41. /package/dist/chunks/{manager-ui-TNAMQNEU.ts.map → manager-ui-Q54OHOPR.ts.map} +0 -0
  42. /package/dist/chunks/{remote-selection-ui-47H7V62F.ts.map → remote-selection-ui-ODSUHX5N.ts.map} +0 -0
  43. /package/dist/chunks/{sync-inspection-5GQEB62G.ts.map → sync-inspection-ECUTWISE.ts.map} +0 -0
  44. /package/dist/chunks/{sync-operations-65HDA67O.ts.map → sync-operations-REXODWZB.ts.map} +0 -0
@@ -1,10 +1,12 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
- setSyncStatus
5
- } from "./chunk-ENFHHB5O.ts";
4
+ setSyncStatus,
5
+ showSyncConnectionStatus
6
+ } from "./chunk-OVCP2SOB.ts";
6
7
  import {
7
- SyncDecisionRequiredError
8
+ SyncDecisionRequiredError,
9
+ errorMessage
8
10
  } from "./chunk-ZIL6PW5L.ts";
9
11
  import {
10
12
  safeTerminalText
@@ -249,13 +251,13 @@ function currentPiDaemonClient() {
249
251
  return current();
250
252
  }
251
253
  function current() {
252
- const client = scope.getStore();
254
+ const client = scope.getStore()?.client;
253
255
  if (!client) throw new Error("Pi synchronization requires a current session-bound daemon client.");
254
256
  client.validate();
255
257
  return client;
256
258
  }
257
259
  function canonicalPath(value) {
258
- if (value === void 0) return void 0;
260
+ if (value === void 0 || value === "") return void 0;
259
261
  if (!path2.isAbsolute(value)) throw new Error("Pi session paths must be absolute.");
260
262
  const parts = [];
261
263
  let cursor = path2.resolve(value);
@@ -319,7 +321,7 @@ var authority = {
319
321
  };
320
322
  function installPiDaemonHost() {
321
323
  configureEngineHost({
322
- root: () => scope.getStore()?.root ?? path2.resolve(getAgentDir()),
324
+ root: () => scope.getStore()?.client.root ?? path2.resolve(getAgentDir()),
323
325
  config: authority,
324
326
  mutate: async () => {
325
327
  throw new Error("File mutation belongs to pi-sync-daemon; no in-process fallback is permitted.");
@@ -340,8 +342,8 @@ function piDaemonClient(ctx) {
340
342
  client.validate();
341
343
  return client;
342
344
  }
343
- function withPiDaemonClient(ctx, action) {
344
- const client = piDaemonClient(ctx);
345
+ function withPiDaemonClient(ctx, action, reload) {
346
+ const owner = { client: piDaemonClient(ctx), reload };
345
347
  const ui = new Proxy(ctx.ui, {
346
348
  get(target, property) {
347
349
  if (property !== "custom") return Reflect.get(target, property, target);
@@ -355,14 +357,14 @@ function withPiDaemonClient(ctx, action) {
355
357
  if (typeof value !== "function") return value;
356
358
  const saved = methods.get(key);
357
359
  if (saved?.source === value) return saved.bound;
358
- const bound = (...values) => scope.run(client, () => Reflect.apply(value, original, values));
360
+ const bound = (...values) => scope.run(owner, () => Reflect.apply(value, original, values));
359
361
  methods.set(key, { source: value, bound });
360
362
  return bound;
361
363
  }
362
364
  });
363
365
  };
364
366
  const invoke = (...provided) => {
365
- const component = scope.run(client, () => factory(...provided));
367
+ const component = scope.run(owner, () => factory(...provided));
366
368
  return component instanceof Promise ? component.then(wrap) : wrap(component);
367
369
  };
368
370
  return target.custom(
@@ -377,11 +379,14 @@ function withPiDaemonClient(ctx, action) {
377
379
  return key === "ui" ? ui : Reflect.get(target, key, target);
378
380
  }
379
381
  });
380
- return scope.run(client, () => action(owned));
382
+ return scope.run(owner, () => action(owned));
381
383
  }
382
384
  async function remoteOperation(ctx, operation, options) {
383
385
  const client = piDaemonClient(ctx);
384
386
  const { signal, onCommit, args, setup } = options;
387
+ const owner = scope.getStore();
388
+ const reload = options.reload && owner?.client === client ? owner.reload : void 0;
389
+ reload?.signal.throwIfAborted();
385
390
  const payload = {
386
391
  args,
387
392
  ...setup === void 0 ? {} : { setup },
@@ -389,10 +394,13 @@ async function remoteOperation(ctx, operation, options) {
389
394
  force: options.force,
390
395
  stale: options.stale,
391
396
  silent: options.silent,
392
- reload: options.reload,
397
+ reload: reload !== void 0,
393
398
  ...options.agentRetryRefusal ? { agentRetryRefusal: true } : {}
394
399
  };
395
- return client.run(operation, payload, signal, ctx, onCommit);
400
+ return client.run(operation, payload, signal, ctx, onCommit, reload);
401
+ }
402
+ function remoteErrorNamed(error, name) {
403
+ return error instanceof DaemonError && error.remote.name === name;
396
404
  }
397
405
  var PiDaemonClient = class {
398
406
  constructor(ctx, signal, publish) {
@@ -411,16 +419,22 @@ var PiDaemonClient = class {
411
419
  signal;
412
420
  publish;
413
421
  connection;
422
+ protectionOnly = false;
414
423
  partialConnection;
415
424
  work = Promise.resolve();
416
425
  closing = false;
417
426
  paused = false;
418
427
  pausing;
419
428
  connecting;
429
+ contactRepair;
430
+ contactAttempt;
431
+ contactFactsUnpublished = false;
432
+ clearContactStatus;
420
433
  disposed = false;
421
434
  disposing;
422
435
  uiContext;
423
- reloadRequested = false;
436
+ reloadRequest;
437
+ pendingReload;
424
438
  busy = /* @__PURE__ */ new Set();
425
439
  initialized = false;
426
440
  startupDebug = false;
@@ -453,7 +467,7 @@ var PiDaemonClient = class {
453
467
  return void 0;
454
468
  return { provider: model.provider, id: model.id, signature: modelSignature(model), authSource: source };
455
469
  }
456
- facts() {
470
+ facts(protectionOnly = this.protectionOnly) {
457
471
  const manager = this.ctx.sessionManager;
458
472
  return {
459
473
  id: this.id,
@@ -461,14 +475,14 @@ var PiDaemonClient = class {
461
475
  pid: process.pid,
462
476
  cwd: this.ctx.cwd,
463
477
  mode: this.ctx.mode,
464
- hasUI: this.ctx.hasUI,
465
- idle: !this.paused && !this.busy.size && this.ctx.isIdle(),
466
- ready: this.initialized,
478
+ hasUI: !protectionOnly && this.ctx.hasUI,
479
+ idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
480
+ ready: !protectionOnly && this.initialized,
467
481
  startupDebug: this.startupDebug,
468
482
  sessionFile: canonicalPath(manager.getSessionFile?.()),
469
483
  sessionId: manager.getSessionId?.(),
470
484
  sessionDir: canonicalPath(sessionDirFromContext(this.ctx)),
471
- model: this.modelBinding()
485
+ model: protectionOnly ? void 0 : this.modelBinding()
472
486
  };
473
487
  }
474
488
  async configured() {
@@ -482,6 +496,7 @@ var PiDaemonClient = class {
482
496
  async pauseForSessionChange() {
483
497
  this.validate();
484
498
  this.paused = true;
499
+ this.stopContactRepair(true);
485
500
  this.gate.cancelPending();
486
501
  this.pausing ??= (async () => {
487
502
  const connection = this.connection ?? this.partialConnection ?? await this.connecting?.catch(() => void 0);
@@ -492,21 +507,38 @@ var PiDaemonClient = class {
492
507
  })();
493
508
  return this.pausing;
494
509
  }
495
- async attachExisting() {
510
+ async attachExisting({ allowUpgrade = false } = {}) {
496
511
  this.validate();
497
512
  const address = await findDaemon2(this.root);
498
513
  this.validate();
499
- if (address) {
514
+ if (!address) return false;
515
+ const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
516
+ let upgradeFailure;
517
+ if (upgrade) {
500
518
  try {
501
- await this.connect(address);
519
+ await this.connect();
520
+ this.validate();
521
+ return true;
502
522
  } catch (error) {
503
523
  this.validate();
504
- if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError") return false;
505
- throw error;
524
+ if (this.paused) throw error;
525
+ upgradeFailure = safeTerminalText(errorMessage(error));
526
+ }
527
+ }
528
+ try {
529
+ await this.connect(address);
530
+ } catch (error) {
531
+ this.validate();
532
+ if (remoteErrorNamed(error, "DaemonStoppingError")) return false;
533
+ throw error;
534
+ } finally {
535
+ if (upgradeFailure !== void 0) {
536
+ this.validate();
537
+ this.ctx.ui.notify(`pi-sync daemon upgrade failed: ${upgradeFailure}`, "error");
506
538
  }
507
539
  }
508
540
  this.validate();
509
- return Boolean(address);
541
+ return !this.protectionOnly;
510
542
  }
511
543
  async finishReattachment() {
512
544
  this.validate();
@@ -524,7 +556,13 @@ var PiDaemonClient = class {
524
556
  startupSignal.throwIfAborted();
525
557
  };
526
558
  validateStartup();
527
- if (this.connection) return this.connection;
559
+ if (this.connection) {
560
+ if (!existing && this.protectionOnly)
561
+ throw new Error(
562
+ "This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade."
563
+ );
564
+ return this.connection;
565
+ }
528
566
  this.connecting ??= (async () => {
529
567
  if (this.partialConnection) {
530
568
  await this.partialConnection.dispose();
@@ -541,16 +579,17 @@ var PiDaemonClient = class {
541
579
  const daemon = existing ?? await ensureDaemon(this.root, startupSignal);
542
580
  validateStartup();
543
581
  if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
544
- const connection = new DaemonConnection2(daemon.paths, daemon.identity, this.facts(), {
545
- callback: (callback, signal) => this.callback(callback, signal),
582
+ const protectionOnly = daemon.needsUpgrade === true;
583
+ const connection2 = new DaemonConnection2(daemon.paths, daemon.identity, this.facts(protectionOnly), {
584
+ callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
546
585
  event: (event) => {
547
586
  if (event.kind === "commit") return;
548
587
  if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
549
588
  const payload = event.payload;
550
589
  if (event.kind === "notify" && typeof payload?.message === "string")
551
590
  this.uiContext.ui.notify(safeTerminalText(payload.message), payload.level ?? "info");
552
- if (event.kind === "timings" && typeof event.payload?.report === "string") {
553
- this.publish?.(this.ctx, safeTerminalText(event.payload.report));
591
+ if (event.kind === "timings" && typeof payload?.report === "string") {
592
+ this.publish?.(this.ctx, payload.report.split("\n").map(safeTerminalText).join("\n"));
554
593
  }
555
594
  if (event.kind === "status")
556
595
  setSyncStatus(
@@ -559,17 +598,17 @@ var PiDaemonClient = class {
559
598
  payload.presentation
560
599
  );
561
600
  },
601
+ contact: (state) => this.observeContact(connection2, state),
562
602
  error: () => {
563
- if (!this.signal.aborted && !this.disposed && !this.closing && clients.get(this.manager) === this)
564
- setSyncStatus(this.ctx, "sync service unavailable", { activity: "blocked", reason: "repair" });
603
+ if (this.ownsContactUI()) this.showContactStatus("sync service unavailable", "blocked");
565
604
  }
566
605
  });
567
- this.partialConnection = connection;
606
+ this.partialConnection = connection2;
568
607
  try {
569
- await connection.attach(startupSignal);
608
+ await connection2.attach(startupSignal);
570
609
  } catch (error) {
571
610
  if (!(error instanceof DaemonError) || error.remote.name !== "DaemonStoppingError") throw error;
572
- await connection.dispose().catch(() => {
611
+ await connection2.dispose().catch(() => {
573
612
  });
574
613
  this.partialConnection = void 0;
575
614
  validateStartup();
@@ -582,19 +621,132 @@ var PiDaemonClient = class {
582
621
  this.validate();
583
622
  await recoverDetachedClients(daemon);
584
623
  if (this.signal.aborted || this.disposed || this.closing) {
585
- await connection.dispose();
624
+ await connection2.dispose();
586
625
  this.validate();
587
626
  }
588
627
  this.validate();
589
- this.connection = connection;
628
+ this.connection = connection2;
629
+ this.protectionOnly = protectionOnly;
590
630
  this.partialConnection = void 0;
591
- return connection;
631
+ return connection2;
592
632
  }
593
633
  })().catch((error) => {
594
634
  this.connecting = void 0;
595
635
  throw error;
596
636
  });
597
- return this.connecting;
637
+ const connection = await this.connecting;
638
+ validateStartup();
639
+ if (!existing && this.protectionOnly)
640
+ throw new Error("This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.");
641
+ return connection;
642
+ }
643
+ ownsContactUI() {
644
+ return !this.signal.aborted && !this.disposed && !this.closing && !this.paused && clients.get(this.manager) === this;
645
+ }
646
+ showContactStatus(text, activity) {
647
+ const previous = this.clearContactStatus;
648
+ this.clearContactStatus = showSyncConnectionStatus(this.ctx, text, {
649
+ activity,
650
+ reason: activity === "retry" ? "temp" : "repair"
651
+ });
652
+ previous?.();
653
+ }
654
+ stopContactRepair(redraw) {
655
+ this.contactRepair?.controller.abort(new DOMException("Pi session is changing", "AbortError"));
656
+ this.clearContactStatus?.(redraw);
657
+ this.clearContactStatus = void 0;
658
+ }
659
+ observeContact(connection, state) {
660
+ if (connection !== this.connection || !this.ownsContactUI()) return;
661
+ if (state === "active") {
662
+ if (this.contactRepair || this.contactFactsUnpublished || connection.contactResumeState === "uncertain") return;
663
+ this.clearRestoredContact();
664
+ } else if (state === "expired" && connection.facts.hasUI && !this.contactAttempt && !this.contactRepair) {
665
+ if (this.gate.size || connection.hasPendingWork) return;
666
+ void this.resumeContact(connection).catch(() => {
667
+ });
668
+ }
669
+ }
670
+ clearRestoredContact() {
671
+ this.contactAttempt = void 0;
672
+ this.contactFactsUnpublished = false;
673
+ this.clearContactStatus?.();
674
+ this.clearContactStatus = void 0;
675
+ }
676
+ async resumeContact(connection) {
677
+ this.validate();
678
+ if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
679
+ if (this.contactRepair) return this.contactRepair.done;
680
+ if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
681
+ if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
682
+ throw new Error(
683
+ "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying."
684
+ );
685
+ }
686
+ const earlier = this.contactAttempt;
687
+ if (connection.contactState !== "expired" || earlier) {
688
+ throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
689
+ cause: earlier?.error
690
+ });
691
+ }
692
+ const controller = new AbortController();
693
+ const signal = AbortSignal.any([this.signal, controller.signal]);
694
+ const attempt2 = {};
695
+ this.contactAttempt = attempt2;
696
+ const done = Promise.resolve().then(async () => {
697
+ try {
698
+ this.validate();
699
+ signal.throwIfAborted();
700
+ this.showContactStatus("sync reconnecting", "retry");
701
+ await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
702
+ this.validate();
703
+ signal.throwIfAborted();
704
+ this.contactFactsUnpublished = true;
705
+ this.contactAttempt = void 0;
706
+ await connection.update(this.facts());
707
+ this.validate();
708
+ signal.throwIfAborted();
709
+ this.confirmContact(connection);
710
+ } catch (error) {
711
+ attempt2.error = error;
712
+ if (this.ownsContactUI() && !signal.aborted)
713
+ this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
714
+ throw error;
715
+ } finally {
716
+ if (this.contactRepair?.controller === controller) this.contactRepair = void 0;
717
+ }
718
+ });
719
+ this.contactRepair = { controller, done };
720
+ return done;
721
+ }
722
+ async publishFacts(connection) {
723
+ if (this.contactRepair) await this.contactRepair.done;
724
+ this.validate();
725
+ if (this.paused) throw new Error("Pi Sync is paused for a session change.");
726
+ if (connection.contactResumeState === "uncertain")
727
+ throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
728
+ try {
729
+ await connection.update(this.facts());
730
+ } catch (error) {
731
+ if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
732
+ await this.resumeContact(connection);
733
+ this.validate();
734
+ await connection.update(this.facts());
735
+ }
736
+ this.validate();
737
+ this.confirmContact(connection);
738
+ }
739
+ confirmContact(connection) {
740
+ if (connection.contactState === "expired" || connection.contactState === "inactive")
741
+ throw new Error("Pi Sync did not confirm active participation in the daemon.");
742
+ this.clearRestoredContact();
743
+ }
744
+ async verifyConnection(signal) {
745
+ const connection = await this.connect(void 0, signal);
746
+ signal?.throwIfAborted();
747
+ await this.publishFacts(connection);
748
+ signal?.throwIfAborted();
749
+ return connection;
598
750
  }
599
751
  async readSettings(repair = false) {
600
752
  this.validate();
@@ -608,8 +760,8 @@ var PiDaemonClient = class {
608
760
  }
609
761
  return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
610
762
  }
611
- run(operation, payload, signal, ctx = this.ctx, onCommit) {
612
- const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit));
763
+ run(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
764
+ const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
613
765
  this.work = result.then(
614
766
  () => {
615
767
  },
@@ -618,9 +770,11 @@ var PiDaemonClient = class {
618
770
  );
619
771
  return result;
620
772
  }
621
- async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit) {
773
+ async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
622
774
  this.validate();
623
775
  signal?.throwIfAborted();
776
+ reload?.signal.throwIfAborted();
777
+ if (this.pendingReload) throw new Error("Pi resources are about to reload.");
624
778
  if (this.paused && operation !== "shutdown")
625
779
  throw new Error("Synchronization is paused for a session change; if it was cancelled, use /reload to reattach.");
626
780
  const connection = await this.connect(void 0, signal);
@@ -631,17 +785,27 @@ var PiDaemonClient = class {
631
785
  }
632
786
  this.validate();
633
787
  signal?.throwIfAborted();
634
- await connection.update(this.facts());
788
+ if (this.paused)
789
+ await connection.update(this.facts());
790
+ else await this.publishFacts(connection);
635
791
  this.validate();
636
792
  signal?.throwIfAborted();
637
793
  this.uiContext = ctx;
794
+ const request = reload ? { received: false } : void 0;
795
+ this.reloadRequest = request;
638
796
  try {
639
- return await connection.run(
797
+ const result = await connection.run(
640
798
  operation,
641
799
  payload,
642
800
  signal ? AbortSignal.any([signal, this.signal]) : this.signal,
643
801
  onCommit
644
802
  );
803
+ if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
804
+ this.validate();
805
+ this.pendingReload = reload;
806
+ reload.abort(new DOMException("Pi resource reload requested", "AbortError"));
807
+ }
808
+ return result;
645
809
  } catch (error) {
646
810
  if (error instanceof DaemonError) {
647
811
  const prototype = error.name === "RemoteSelectionMismatchError" ? RemoteSelectionMismatchError.prototype : error.name === "SyncDecisionRequiredError" ? SyncDecisionRequiredError.prototype : void 0;
@@ -655,12 +819,17 @@ var PiDaemonClient = class {
655
819
  throw error;
656
820
  } finally {
657
821
  this.uiContext = this.ctx;
658
- if (this.reloadRequested && !this.signal.aborted && !this.disposed && !this.closing && clients.get(this.manager) === this) {
659
- this.reloadRequested = false;
660
- if ("reload" in ctx && typeof ctx.reload === "function") await ctx.reload();
661
- }
822
+ this.reloadRequest = void 0;
662
823
  }
663
824
  }
825
+ canReload(owner) {
826
+ if (this.pendingReload !== owner || this.paused) return false;
827
+ this.validate();
828
+ return true;
829
+ }
830
+ releaseReload(owner) {
831
+ if (this.pendingReload === owner) this.pendingReload = void 0;
832
+ }
664
833
  async markReady(debug) {
665
834
  this.validate();
666
835
  this.startupDebug = debug;
@@ -668,18 +837,18 @@ var PiDaemonClient = class {
668
837
  await this.update();
669
838
  this.validate();
670
839
  }
671
- async setBusy(reason, busy) {
840
+ async setBusy(reason, busy, publish = true) {
672
841
  this.validate();
673
842
  if (busy) this.busy.add(reason);
674
843
  else this.busy.delete(reason);
675
- await this.update();
844
+ if (publish) await this.update();
676
845
  this.validate();
677
846
  }
678
847
  async update() {
679
848
  if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
680
- await this.connection.update(this.facts());
849
+ await this.publishFacts(this.connection);
681
850
  }
682
- async callback(callback, signal) {
851
+ async callback(callback, signal, protectionOnly) {
683
852
  const payload = callback.payload;
684
853
  if (callback.kind === "queue-release") {
685
854
  if (typeof payload?.reservation !== "string") throw new Error("Invalid queue release.");
@@ -690,6 +859,7 @@ var PiDaemonClient = class {
690
859
  signal.throwIfAborted();
691
860
  if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
692
861
  if (callback.kind === "queue-acquire") {
862
+ if (this.pendingReload) throw new Error("Pi resources are about to reload.");
693
863
  if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
694
864
  if (payload.generation !== this.generation || typeof payload.reservation !== "string" || !Array.isArray(payload.targets))
695
865
  throw new Error("Stale file-queue request.");
@@ -698,6 +868,7 @@ var PiDaemonClient = class {
698
868
  const ctx = this.uiContext;
699
869
  const combined = AbortSignal.any([signal, this.signal]);
700
870
  if (callback.kind === "model-binding") {
871
+ if (protectionOnly) return null;
701
872
  const facts = this.facts();
702
873
  const connection = this.connection ?? this.partialConnection;
703
874
  if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
@@ -707,7 +878,8 @@ var PiDaemonClient = class {
707
878
  return payload.background && !facts.idle ? null : facts.model ?? null;
708
879
  }
709
880
  if (callback.kind === "reload") {
710
- this.reloadRequested = true;
881
+ if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
882
+ this.reloadRequest.received = true;
711
883
  return true;
712
884
  }
713
885
  if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
@@ -751,6 +923,7 @@ var PiDaemonClient = class {
751
923
  async dispose(handoff) {
752
924
  if (this.disposing) return this.disposing;
753
925
  this.closing = true;
926
+ this.stopContactRepair(false);
754
927
  this.disposing = (async () => {
755
928
  const connection = this.connection ?? this.partialConnection ?? await this.connecting?.catch(() => void 0);
756
929
  let confirmed = false;
@@ -781,4 +954,4 @@ export {
781
954
  withPiDaemonClient,
782
955
  remoteOperation
783
956
  };
784
- //# sourceMappingURL=chunk-FOMZEZER.ts.map
957
+ //# sourceMappingURL=chunk-VQRDL3SY.ts.map