@narumitw/pi-sync 0.60.2 → 0.60.5

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 (45) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +10 -0
  3. package/dist/chunks/{chunk-FOMZEZER.ts → chunk-6KIWZ4AY.ts} +360 -60
  4. package/dist/chunks/chunk-6KIWZ4AY.ts.map +7 -0
  5. package/dist/chunks/{chunk-B53FS4RW.ts → chunk-F64YWRXG.ts} +2 -2
  6. package/dist/chunks/{chunk-ENFHHB5O.ts → chunk-H7VOTY5N.ts} +55 -6
  7. package/dist/chunks/chunk-H7VOTY5N.ts.map +7 -0
  8. package/dist/chunks/{chunk-E7UJHMNW.ts → chunk-V2QIMC3U.ts} +2 -2
  9. package/dist/chunks/{chunk-3YXBG7BQ.ts → chunk-YVH5VJR4.ts} +2 -2
  10. package/dist/chunks/{command-handler-RTBEFZUX.ts → command-handler-TNPWFIPG.ts} +10 -8
  11. package/dist/chunks/command-handler-TNPWFIPG.ts.map +7 -0
  12. package/dist/chunks/{conflict-review-YXROU42F.ts → conflict-review-ETCSYJTH.ts} +3 -3
  13. package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts → manager-result-dispatcher-2GFNWHDM.ts} +4 -4
  14. package/dist/chunks/{manager-ui-TNAMQNEU.ts → manager-ui-LFONXWQN.ts} +8 -8
  15. package/dist/chunks/{remote-selection-ui-47H7V62F.ts → remote-selection-ui-GFR6TDTX.ts} +3 -3
  16. package/dist/chunks/{sync-inspection-5GQEB62G.ts → sync-inspection-6VGR2UVZ.ts} +3 -3
  17. package/dist/chunks/{sync-operations-65HDA67O.ts → sync-operations-SAKAZL6Z.ts} +3 -3
  18. package/dist/index.ts +64 -41
  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 +88 -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 +302 -57
  30. package/src/daemon/queue-release-ui.ts +88 -0
  31. package/src/sync-extension.ts +68 -43
  32. package/src/ui/sync-status.ts +67 -4
  33. package/dist/chunks/chunk-ENFHHB5O.ts.map +0 -7
  34. package/dist/chunks/chunk-FOMZEZER.ts.map +0 -7
  35. package/dist/chunks/command-handler-RTBEFZUX.ts.map +0 -7
  36. package/docs/settings.md +0 -90
  37. /package/dist/chunks/{chunk-B53FS4RW.ts.map → chunk-F64YWRXG.ts.map} +0 -0
  38. /package/dist/chunks/{chunk-E7UJHMNW.ts.map → chunk-V2QIMC3U.ts.map} +0 -0
  39. /package/dist/chunks/{chunk-3YXBG7BQ.ts.map → chunk-YVH5VJR4.ts.map} +0 -0
  40. /package/dist/chunks/{conflict-review-YXROU42F.ts.map → conflict-review-ETCSYJTH.ts.map} +0 -0
  41. /package/dist/chunks/{manager-result-dispatcher-4PEUHK7F.ts.map → manager-result-dispatcher-2GFNWHDM.ts.map} +0 -0
  42. /package/dist/chunks/{manager-ui-TNAMQNEU.ts.map → manager-ui-LFONXWQN.ts.map} +0 -0
  43. /package/dist/chunks/{remote-selection-ui-47H7V62F.ts.map → remote-selection-ui-GFR6TDTX.ts.map} +0 -0
  44. /package/dist/chunks/{sync-inspection-5GQEB62G.ts.map → sync-inspection-6VGR2UVZ.ts.map} +0 -0
  45. /package/dist/chunks/{sync-operations-65HDA67O.ts.map → sync-operations-SAKAZL6Z.ts.map} +0 -0
@@ -1,10 +1,13 @@
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
+ showSyncQueueReleaseRecovery
7
+ } from "./chunk-H7VOTY5N.ts";
6
8
  import {
7
- SyncDecisionRequiredError
9
+ SyncDecisionRequiredError,
10
+ errorMessage
8
11
  } from "./chunk-ZIL6PW5L.ts";
9
12
  import {
10
13
  safeTerminalText
@@ -164,6 +167,86 @@ var PiApplyGate = class {
164
167
  }
165
168
  };
166
169
 
170
+ // src/daemon/queue-release-ui.ts
171
+ function createQueueReleaseUI(show, warn) {
172
+ const retries = /* @__PURE__ */ new Map();
173
+ const handledJobs = /* @__PURE__ */ new Set();
174
+ const deferredWarnings = /* @__PURE__ */ new Set();
175
+ let timer;
176
+ let clearStatus;
177
+ function remember(job) {
178
+ deferredWarnings.delete(job);
179
+ if (handledJobs.has(job)) return false;
180
+ if (handledJobs.size >= 128) {
181
+ const oldest = handledJobs.values().next();
182
+ if (!oldest.done) handledJobs.delete(oldest.value);
183
+ }
184
+ handledJobs.add(job);
185
+ return true;
186
+ }
187
+ function clearPresentation(redraw) {
188
+ clearTimeout(timer);
189
+ timer = void 0;
190
+ const release = clearStatus;
191
+ clearStatus = void 0;
192
+ release?.(redraw);
193
+ }
194
+ return {
195
+ get retrying() {
196
+ return retries.size > 0;
197
+ },
198
+ observe({ id, job, state, foreground }, commandBusy, cancelled) {
199
+ if (state === "retrying") {
200
+ if (foreground && cancelled) {
201
+ remember(job);
202
+ return;
203
+ }
204
+ if (retries.has(id)) return;
205
+ retries.set(id, { job, foreground });
206
+ if (retries.size !== 1) return;
207
+ timer = setTimeout(() => {
208
+ timer = void 0;
209
+ const release = show();
210
+ if (retries.size) clearStatus = release;
211
+ else release?.(false);
212
+ }, 2e3);
213
+ timer.unref?.();
214
+ return;
215
+ }
216
+ const retry = retries.get(id);
217
+ retries.delete(id);
218
+ if (!retries.size) clearPresentation(true);
219
+ if (state !== "unconfirmed") return;
220
+ const background = !foreground && !retry?.foreground;
221
+ if (background && commandBusy) {
222
+ if (!handledJobs.has(job)) deferredWarnings.add(job);
223
+ } else if (remember(job) && background) warn();
224
+ },
225
+ flushWarnings() {
226
+ if (!deferredWarnings.size) return;
227
+ for (const job of deferredWarnings) remember(job);
228
+ try {
229
+ warn();
230
+ } catch {
231
+ }
232
+ },
233
+ finishForeground(redraw) {
234
+ for (const [id, { job, foreground }] of retries) {
235
+ if (!foreground) continue;
236
+ retries.delete(id);
237
+ remember(job);
238
+ }
239
+ if (!retries.size) clearPresentation(redraw);
240
+ },
241
+ clear(redraw) {
242
+ retries.clear();
243
+ handledJobs.clear();
244
+ deferredWarnings.clear();
245
+ clearPresentation(redraw);
246
+ }
247
+ };
248
+ }
249
+
167
250
  // src/daemon/recovery.ts
168
251
  import { DaemonConnection, findDaemon } from "@narumitw/pi-sync-daemon";
169
252
  var recoveries = /* @__PURE__ */ new Set();
@@ -249,13 +332,13 @@ function currentPiDaemonClient() {
249
332
  return current();
250
333
  }
251
334
  function current() {
252
- const client = scope.getStore();
335
+ const client = scope.getStore()?.client;
253
336
  if (!client) throw new Error("Pi synchronization requires a current session-bound daemon client.");
254
337
  client.validate();
255
338
  return client;
256
339
  }
257
340
  function canonicalPath(value) {
258
- if (value === void 0) return void 0;
341
+ if (value === void 0 || value === "") return void 0;
259
342
  if (!path2.isAbsolute(value)) throw new Error("Pi session paths must be absolute.");
260
343
  const parts = [];
261
344
  let cursor = path2.resolve(value);
@@ -319,7 +402,7 @@ var authority = {
319
402
  };
320
403
  function installPiDaemonHost() {
321
404
  configureEngineHost({
322
- root: () => scope.getStore()?.root ?? path2.resolve(getAgentDir()),
405
+ root: () => scope.getStore()?.client.root ?? path2.resolve(getAgentDir()),
323
406
  config: authority,
324
407
  mutate: async () => {
325
408
  throw new Error("File mutation belongs to pi-sync-daemon; no in-process fallback is permitted.");
@@ -340,8 +423,8 @@ function piDaemonClient(ctx) {
340
423
  client.validate();
341
424
  return client;
342
425
  }
343
- function withPiDaemonClient(ctx, action) {
344
- const client = piDaemonClient(ctx);
426
+ function withPiDaemonClient(ctx, action, reload) {
427
+ const owner = { client: piDaemonClient(ctx), reload };
345
428
  const ui = new Proxy(ctx.ui, {
346
429
  get(target, property) {
347
430
  if (property !== "custom") return Reflect.get(target, property, target);
@@ -355,14 +438,14 @@ function withPiDaemonClient(ctx, action) {
355
438
  if (typeof value !== "function") return value;
356
439
  const saved = methods.get(key);
357
440
  if (saved?.source === value) return saved.bound;
358
- const bound = (...values) => scope.run(client, () => Reflect.apply(value, original, values));
441
+ const bound = (...values) => scope.run(owner, () => Reflect.apply(value, original, values));
359
442
  methods.set(key, { source: value, bound });
360
443
  return bound;
361
444
  }
362
445
  });
363
446
  };
364
447
  const invoke = (...provided) => {
365
- const component = scope.run(client, () => factory(...provided));
448
+ const component = scope.run(owner, () => factory(...provided));
366
449
  return component instanceof Promise ? component.then(wrap) : wrap(component);
367
450
  };
368
451
  return target.custom(
@@ -377,11 +460,14 @@ function withPiDaemonClient(ctx, action) {
377
460
  return key === "ui" ? ui : Reflect.get(target, key, target);
378
461
  }
379
462
  });
380
- return scope.run(client, () => action(owned));
463
+ return scope.run(owner, () => action(owned));
381
464
  }
382
465
  async function remoteOperation(ctx, operation, options) {
383
466
  const client = piDaemonClient(ctx);
384
467
  const { signal, onCommit, args, setup } = options;
468
+ const owner = scope.getStore();
469
+ const reload = options.reload && owner?.client === client ? owner.reload : void 0;
470
+ reload?.signal.throwIfAborted();
385
471
  const payload = {
386
472
  args,
387
473
  ...setup === void 0 ? {} : { setup },
@@ -389,10 +475,13 @@ async function remoteOperation(ctx, operation, options) {
389
475
  force: options.force,
390
476
  stale: options.stale,
391
477
  silent: options.silent,
392
- reload: options.reload,
478
+ reload: reload !== void 0,
393
479
  ...options.agentRetryRefusal ? { agentRetryRefusal: true } : {}
394
480
  };
395
- return client.run(operation, payload, signal, ctx, onCommit);
481
+ return client.run(operation, payload, signal, ctx, onCommit, reload);
482
+ }
483
+ function remoteErrorNamed(error, name) {
484
+ return error instanceof DaemonError && error.remote.name === name;
396
485
  }
397
486
  var PiDaemonClient = class {
398
487
  constructor(ctx, signal, publish) {
@@ -406,21 +495,44 @@ var PiDaemonClient = class {
406
495
  if (!root) throw new Error("Agent directory is unavailable.");
407
496
  this.root = root;
408
497
  this.gate = new PiApplyGate(() => this.validate());
498
+ this.signal.addEventListener("abort", this.stopReleaseUI, { once: true });
409
499
  }
410
500
  ctx;
411
501
  signal;
412
502
  publish;
413
503
  connection;
504
+ protectionOnly = false;
414
505
  partialConnection;
415
506
  work = Promise.resolve();
416
507
  closing = false;
417
508
  paused = false;
418
509
  pausing;
419
510
  connecting;
511
+ contactRepair;
512
+ contactAttempt;
513
+ contactFactsUnpublished = false;
514
+ contactStatus;
515
+ releaseUIEnabled = true;
516
+ runSignal;
517
+ releaseUI = createQueueReleaseUI(
518
+ () => {
519
+ const ctx = this.releaseContext();
520
+ if (ctx) return showSyncQueueReleaseRecovery(ctx);
521
+ },
522
+ () => this.releaseContext()?.ui.notify(
523
+ "Pi Sync could not confirm the file write queue release. Sync may be paused; check /sync daemon status before retrying.",
524
+ "warning"
525
+ )
526
+ );
527
+ stopReleaseUI = () => {
528
+ this.releaseUIEnabled = false;
529
+ this.releaseUI.clear(Boolean(this.releaseContext(true)));
530
+ };
420
531
  disposed = false;
421
532
  disposing;
422
533
  uiContext;
423
- reloadRequested = false;
534
+ reloadRequest;
535
+ pendingReload;
424
536
  busy = /* @__PURE__ */ new Set();
425
537
  initialized = false;
426
538
  startupDebug = false;
@@ -453,7 +565,7 @@ var PiDaemonClient = class {
453
565
  return void 0;
454
566
  return { provider: model.provider, id: model.id, signature: modelSignature(model), authSource: source };
455
567
  }
456
- facts() {
568
+ facts(protectionOnly = this.protectionOnly) {
457
569
  const manager = this.ctx.sessionManager;
458
570
  return {
459
571
  id: this.id,
@@ -461,14 +573,14 @@ var PiDaemonClient = class {
461
573
  pid: process.pid,
462
574
  cwd: this.ctx.cwd,
463
575
  mode: this.ctx.mode,
464
- hasUI: this.ctx.hasUI,
465
- idle: !this.paused && !this.busy.size && this.ctx.isIdle(),
466
- ready: this.initialized,
576
+ hasUI: !protectionOnly && this.ctx.hasUI,
577
+ idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
578
+ ready: !protectionOnly && this.initialized,
467
579
  startupDebug: this.startupDebug,
468
580
  sessionFile: canonicalPath(manager.getSessionFile?.()),
469
581
  sessionId: manager.getSessionId?.(),
470
582
  sessionDir: canonicalPath(sessionDirFromContext(this.ctx)),
471
- model: this.modelBinding()
583
+ model: protectionOnly ? void 0 : this.modelBinding()
472
584
  };
473
585
  }
474
586
  async configured() {
@@ -482,6 +594,8 @@ var PiDaemonClient = class {
482
594
  async pauseForSessionChange() {
483
595
  this.validate();
484
596
  this.paused = true;
597
+ this.stopReleaseUI();
598
+ this.stopContactRepair(true);
485
599
  this.gate.cancelPending();
486
600
  this.pausing ??= (async () => {
487
601
  const connection = this.connection ?? this.partialConnection ?? await this.connecting?.catch(() => void 0);
@@ -492,21 +606,38 @@ var PiDaemonClient = class {
492
606
  })();
493
607
  return this.pausing;
494
608
  }
495
- async attachExisting() {
609
+ async attachExisting({ allowUpgrade = false } = {}) {
496
610
  this.validate();
497
611
  const address = await findDaemon2(this.root);
498
612
  this.validate();
499
- if (address) {
613
+ if (!address) return false;
614
+ const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
615
+ let upgradeFailure;
616
+ if (upgrade) {
500
617
  try {
501
- await this.connect(address);
618
+ await this.connect();
619
+ this.validate();
620
+ return true;
502
621
  } catch (error) {
503
622
  this.validate();
504
- if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError") return false;
505
- throw error;
623
+ if (this.paused) throw error;
624
+ upgradeFailure = safeTerminalText(errorMessage(error));
625
+ }
626
+ }
627
+ try {
628
+ await this.connect(address);
629
+ } catch (error) {
630
+ this.validate();
631
+ if (remoteErrorNamed(error, "DaemonStoppingError")) return false;
632
+ throw error;
633
+ } finally {
634
+ if (upgradeFailure !== void 0) {
635
+ this.validate();
636
+ this.ctx.ui.notify(`pi-sync daemon upgrade failed: ${upgradeFailure}`, "error");
506
637
  }
507
638
  }
508
639
  this.validate();
509
- return Boolean(address);
640
+ return !this.protectionOnly;
510
641
  }
511
642
  async finishReattachment() {
512
643
  this.validate();
@@ -524,7 +655,13 @@ var PiDaemonClient = class {
524
655
  startupSignal.throwIfAborted();
525
656
  };
526
657
  validateStartup();
527
- if (this.connection) return this.connection;
658
+ if (this.connection) {
659
+ if (!existing && this.protectionOnly)
660
+ throw new Error(
661
+ "This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade."
662
+ );
663
+ return this.connection;
664
+ }
528
665
  this.connecting ??= (async () => {
529
666
  if (this.partialConnection) {
530
667
  await this.partialConnection.dispose();
@@ -541,16 +678,17 @@ var PiDaemonClient = class {
541
678
  const daemon = existing ?? await ensureDaemon(this.root, startupSignal);
542
679
  validateStartup();
543
680
  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),
681
+ const protectionOnly = daemon.needsUpgrade === true;
682
+ const connection2 = new DaemonConnection2(daemon.paths, daemon.identity, this.facts(protectionOnly), {
683
+ callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
546
684
  event: (event) => {
547
685
  if (event.kind === "commit") return;
548
686
  if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
549
687
  const payload = event.payload;
550
688
  if (event.kind === "notify" && typeof payload?.message === "string")
551
689
  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));
690
+ if (event.kind === "timings" && typeof payload?.report === "string") {
691
+ this.publish?.(this.ctx, payload.report.split("\n").map(safeTerminalText).join("\n"));
554
692
  }
555
693
  if (event.kind === "status")
556
694
  setSyncStatus(
@@ -559,17 +697,19 @@ var PiDaemonClient = class {
559
697
  payload.presentation
560
698
  );
561
699
  },
700
+ contact: (state) => this.observeContact(connection2, state),
701
+ queueRelease: (event) => this.observeQueueRelease(connection2, event),
562
702
  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" });
703
+ if (this.ownsContactUI() && connection2.facts.hasUI && !this.releaseUI.retrying)
704
+ this.showContactStatus("sync service unavailable", "blocked", true);
565
705
  }
566
706
  });
567
- this.partialConnection = connection;
707
+ this.partialConnection = connection2;
568
708
  try {
569
- await connection.attach(startupSignal);
709
+ await connection2.attach(startupSignal);
570
710
  } catch (error) {
571
711
  if (!(error instanceof DaemonError) || error.remote.name !== "DaemonStoppingError") throw error;
572
- await connection.dispose().catch(() => {
712
+ await connection2.dispose().catch(() => {
573
713
  });
574
714
  this.partialConnection = void 0;
575
715
  validateStartup();
@@ -582,19 +722,152 @@ var PiDaemonClient = class {
582
722
  this.validate();
583
723
  await recoverDetachedClients(daemon);
584
724
  if (this.signal.aborted || this.disposed || this.closing) {
585
- await connection.dispose();
725
+ await connection2.dispose();
586
726
  this.validate();
587
727
  }
588
728
  this.validate();
589
- this.connection = connection;
729
+ this.connection = connection2;
730
+ this.protectionOnly = protectionOnly;
590
731
  this.partialConnection = void 0;
591
- return connection;
732
+ return connection2;
592
733
  }
593
734
  })().catch((error) => {
594
735
  this.connecting = void 0;
595
736
  throw error;
596
737
  });
597
- return this.connecting;
738
+ const connection = await this.connecting;
739
+ validateStartup();
740
+ if (!existing && this.protectionOnly)
741
+ throw new Error("This session is only protecting its files on an older Pi Sync daemon. Use /reload to upgrade.");
742
+ return connection;
743
+ }
744
+ ownsContactUI() {
745
+ return !this.signal.aborted && !this.disposed && !this.closing && !this.paused && clients.get(this.manager) === this;
746
+ }
747
+ releaseContext(cleanup = false) {
748
+ if (clients.get(this.manager) !== this) return;
749
+ if (!cleanup && (!this.releaseUIEnabled || !this.ownsContactUI() || this.busy.has("shutdown"))) return;
750
+ try {
751
+ this.ctx.isIdle();
752
+ if (this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc")) return this.ctx;
753
+ } catch {
754
+ }
755
+ }
756
+ disableQueueReleaseUI() {
757
+ this.stopReleaseUI();
758
+ }
759
+ observeQueueRelease(connection, event) {
760
+ if (connection !== this.connection || !connection.facts.hasUI || !this.releaseContext()) return;
761
+ if (event.state === "retrying" && this.contactStatus?.unavailable) this.clearConnectionStatus();
762
+ this.releaseUI.observe(event, this.busy.has("command"), !this.runSignal || this.runSignal.aborted);
763
+ }
764
+ showContactStatus(text, activity, unavailable = false) {
765
+ const previous = this.contactStatus;
766
+ this.contactStatus = {
767
+ clear: showSyncConnectionStatus(this.ctx, text, { activity, reason: activity === "retry" ? "temp" : "repair" }),
768
+ unavailable
769
+ };
770
+ previous?.clear();
771
+ }
772
+ clearConnectionStatus(redraw = true) {
773
+ const status = this.contactStatus;
774
+ this.contactStatus = void 0;
775
+ status?.clear(redraw);
776
+ }
777
+ stopContactRepair(redraw) {
778
+ this.contactRepair?.controller.abort(new DOMException("Pi session is changing", "AbortError"));
779
+ this.clearConnectionStatus(redraw);
780
+ }
781
+ observeContact(connection, state) {
782
+ if (connection !== this.connection || !this.ownsContactUI()) return;
783
+ if (state === "active") {
784
+ if (this.contactRepair || this.contactFactsUnpublished || connection.contactResumeState === "uncertain") return;
785
+ this.clearRestoredContact();
786
+ } else if (state === "expired" && connection.facts.hasUI && !this.contactAttempt && !this.contactRepair) {
787
+ if (this.gate.size || connection.hasPendingWork || this.releaseUI.retrying) return;
788
+ void this.resumeContact(connection).catch(() => {
789
+ });
790
+ }
791
+ }
792
+ clearRestoredContact() {
793
+ this.contactAttempt = void 0;
794
+ this.contactFactsUnpublished = false;
795
+ this.clearConnectionStatus();
796
+ }
797
+ async resumeContact(connection) {
798
+ this.validate();
799
+ if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
800
+ if (this.contactRepair) return this.contactRepair.done;
801
+ if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
802
+ if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
803
+ throw new Error(
804
+ "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying."
805
+ );
806
+ }
807
+ const earlier = this.contactAttempt;
808
+ if (connection.contactState !== "expired" || earlier) {
809
+ throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
810
+ cause: earlier?.error
811
+ });
812
+ }
813
+ const controller = new AbortController();
814
+ const signal = AbortSignal.any([this.signal, controller.signal]);
815
+ const attempt2 = {};
816
+ this.contactAttempt = attempt2;
817
+ const done = Promise.resolve().then(async () => {
818
+ try {
819
+ this.validate();
820
+ signal.throwIfAborted();
821
+ this.showContactStatus("sync reconnecting", "retry");
822
+ await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
823
+ this.validate();
824
+ signal.throwIfAborted();
825
+ this.contactFactsUnpublished = true;
826
+ this.contactAttempt = void 0;
827
+ await connection.update(this.facts());
828
+ this.validate();
829
+ signal.throwIfAborted();
830
+ this.confirmContact(connection);
831
+ } catch (error) {
832
+ attempt2.error = error;
833
+ if (this.ownsContactUI() && !signal.aborted)
834
+ this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
835
+ throw error;
836
+ } finally {
837
+ if (this.contactRepair?.controller === controller) this.contactRepair = void 0;
838
+ }
839
+ });
840
+ this.contactRepair = { controller, done };
841
+ return done;
842
+ }
843
+ async publishFacts(connection) {
844
+ if (this.contactRepair) await this.contactRepair.done;
845
+ this.validate();
846
+ if (this.paused) throw new Error("Pi Sync is paused for a session change.");
847
+ if (connection.contactResumeState === "uncertain")
848
+ throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
849
+ try {
850
+ await connection.update(this.facts());
851
+ } catch (error) {
852
+ if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
853
+ await this.resumeContact(connection);
854
+ this.validate();
855
+ await connection.update(this.facts());
856
+ }
857
+ this.validate();
858
+ this.confirmContact(connection);
859
+ }
860
+ confirmContact(connection) {
861
+ if (connection.contactState === "expired" || connection.contactState === "inactive")
862
+ throw new Error("Pi Sync did not confirm active participation in the daemon.");
863
+ this.clearRestoredContact();
864
+ }
865
+ async verifyConnection(signal) {
866
+ const connection = await this.connect(void 0, signal);
867
+ signal?.throwIfAborted();
868
+ await this.publishFacts(connection);
869
+ signal?.throwIfAborted();
870
+ return connection;
598
871
  }
599
872
  async readSettings(repair = false) {
600
873
  this.validate();
@@ -608,8 +881,8 @@ var PiDaemonClient = class {
608
881
  }
609
882
  return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
610
883
  }
611
- run(operation, payload, signal, ctx = this.ctx, onCommit) {
612
- const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit));
884
+ run(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
885
+ const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
613
886
  this.work = result.then(
614
887
  () => {
615
888
  },
@@ -618,9 +891,11 @@ var PiDaemonClient = class {
618
891
  );
619
892
  return result;
620
893
  }
621
- async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit) {
894
+ async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
622
895
  this.validate();
623
896
  signal?.throwIfAborted();
897
+ reload?.signal.throwIfAborted();
898
+ if (this.pendingReload) throw new Error("Pi resources are about to reload.");
624
899
  if (this.paused && operation !== "shutdown")
625
900
  throw new Error("Synchronization is paused for a session change; if it was cancelled, use /reload to reattach.");
626
901
  const connection = await this.connect(void 0, signal);
@@ -631,17 +906,26 @@ var PiDaemonClient = class {
631
906
  }
632
907
  this.validate();
633
908
  signal?.throwIfAborted();
634
- await connection.update(this.facts());
909
+ if (this.paused)
910
+ await connection.update(this.facts());
911
+ else await this.publishFacts(connection);
635
912
  this.validate();
636
913
  signal?.throwIfAborted();
637
914
  this.uiContext = ctx;
915
+ const request = reload ? { received: false } : void 0;
916
+ this.reloadRequest = request;
917
+ const runSignal = signal ? AbortSignal.any([signal, this.signal]) : this.signal;
918
+ this.runSignal = runSignal;
919
+ const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
920
+ runSignal.addEventListener("abort", clearForeground, { once: true });
638
921
  try {
639
- return await connection.run(
640
- operation,
641
- payload,
642
- signal ? AbortSignal.any([signal, this.signal]) : this.signal,
643
- onCommit
644
- );
922
+ const result = await connection.run(operation, payload, runSignal, onCommit);
923
+ if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
924
+ this.validate();
925
+ this.pendingReload = reload;
926
+ reload.abort(new DOMException("Pi resource reload requested", "AbortError"));
927
+ }
928
+ return result;
645
929
  } catch (error) {
646
930
  if (error instanceof DaemonError) {
647
931
  const prototype = error.name === "RemoteSelectionMismatchError" ? RemoteSelectionMismatchError.prototype : error.name === "SyncDecisionRequiredError" ? SyncDecisionRequiredError.prototype : void 0;
@@ -654,13 +938,21 @@ var PiDaemonClient = class {
654
938
  }
655
939
  throw error;
656
940
  } finally {
941
+ runSignal.removeEventListener("abort", clearForeground);
942
+ clearForeground();
943
+ this.runSignal = void 0;
657
944
  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
- }
945
+ this.reloadRequest = void 0;
662
946
  }
663
947
  }
948
+ canReload(owner) {
949
+ if (this.pendingReload !== owner || this.paused) return false;
950
+ this.validate();
951
+ return true;
952
+ }
953
+ releaseReload(owner) {
954
+ if (this.pendingReload === owner) this.pendingReload = void 0;
955
+ }
664
956
  async markReady(debug) {
665
957
  this.validate();
666
958
  this.startupDebug = debug;
@@ -668,18 +960,20 @@ var PiDaemonClient = class {
668
960
  await this.update();
669
961
  this.validate();
670
962
  }
671
- async setBusy(reason, busy) {
963
+ async setBusy(reason, busy, publish = true) {
672
964
  this.validate();
673
965
  if (busy) this.busy.add(reason);
674
- else this.busy.delete(reason);
675
- await this.update();
966
+ else if (this.busy.delete(reason) && reason === "command") {
967
+ this.releaseUI.flushWarnings();
968
+ }
969
+ if (publish) await this.update();
676
970
  this.validate();
677
971
  }
678
972
  async update() {
679
973
  if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
680
- await this.connection.update(this.facts());
974
+ await this.publishFacts(this.connection);
681
975
  }
682
- async callback(callback, signal) {
976
+ async callback(callback, signal, protectionOnly) {
683
977
  const payload = callback.payload;
684
978
  if (callback.kind === "queue-release") {
685
979
  if (typeof payload?.reservation !== "string") throw new Error("Invalid queue release.");
@@ -690,6 +984,7 @@ var PiDaemonClient = class {
690
984
  signal.throwIfAborted();
691
985
  if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
692
986
  if (callback.kind === "queue-acquire") {
987
+ if (this.pendingReload) throw new Error("Pi resources are about to reload.");
693
988
  if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
694
989
  if (payload.generation !== this.generation || typeof payload.reservation !== "string" || !Array.isArray(payload.targets))
695
990
  throw new Error("Stale file-queue request.");
@@ -698,6 +993,7 @@ var PiDaemonClient = class {
698
993
  const ctx = this.uiContext;
699
994
  const combined = AbortSignal.any([signal, this.signal]);
700
995
  if (callback.kind === "model-binding") {
996
+ if (protectionOnly) return null;
701
997
  const facts = this.facts();
702
998
  const connection = this.connection ?? this.partialConnection;
703
999
  if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
@@ -707,7 +1003,8 @@ var PiDaemonClient = class {
707
1003
  return payload.background && !facts.idle ? null : facts.model ?? null;
708
1004
  }
709
1005
  if (callback.kind === "reload") {
710
- this.reloadRequested = true;
1006
+ if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
1007
+ this.reloadRequest.received = true;
711
1008
  return true;
712
1009
  }
713
1010
  if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
@@ -751,6 +1048,9 @@ var PiDaemonClient = class {
751
1048
  async dispose(handoff) {
752
1049
  if (this.disposing) return this.disposing;
753
1050
  this.closing = true;
1051
+ this.signal.removeEventListener("abort", this.stopReleaseUI);
1052
+ this.stopReleaseUI();
1053
+ this.stopContactRepair(false);
754
1054
  this.disposing = (async () => {
755
1055
  const connection = this.connection ?? this.partialConnection ?? await this.connecting?.catch(() => void 0);
756
1056
  let confirmed = false;
@@ -781,4 +1081,4 @@ export {
781
1081
  withPiDaemonClient,
782
1082
  remoteOperation
783
1083
  };
784
- //# sourceMappingURL=chunk-FOMZEZER.ts.map
1084
+ //# sourceMappingURL=chunk-6KIWZ4AY.ts.map