@narumitw/pi-sync 0.70.6 → 0.70.7

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/index.ts CHANGED
@@ -4,11 +4,12 @@ import {
4
4
  snapshotOptionsForContext
5
5
  } from "./chunks/chunk-P4GI7LTT.ts";
6
6
  import {
7
+ PI_SYNC_BINDING_UNAVAILABLE,
7
8
  bindPiDaemonClient,
8
9
  installPiDaemonHost,
9
10
  piDaemonClient,
10
11
  withPiDaemonClient
11
- } from "./chunks/chunk-KN4NY2VV.ts";
12
+ } from "./chunks/chunk-HCXPNKPU.ts";
12
13
  import {
13
14
  createSyncAttentionController
14
15
  } from "./chunks/chunk-WRS3SUNZ.ts";
@@ -190,8 +191,8 @@ async function startSession(ctx, signal, publish) {
190
191
  return { debug: result.debug, config: result.config };
191
192
  }
192
193
  async function autoPushSessions(ctx, signal, _loaders) {
194
+ const client = piDaemonClient(ctx);
193
195
  try {
194
- const client = piDaemonClient(ctx);
195
196
  const eligible = (config2) => config2.automatic && syncSessionsSelected(config2);
196
197
  if (!await client.configured((settings) => eligible(configFromSettings(settings)))) {
197
198
  client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
@@ -211,7 +212,7 @@ async function autoPushSessions(ctx, signal, _loaders) {
211
212
  signal
212
213
  );
213
214
  } catch (error) {
214
- if (signal.aborted || isMissingConfigError(error)) return;
215
+ if (signal.aborted || !client.isCurrent() || isMissingConfigError(error)) return;
215
216
  ctx.ui.notify(`pi-sync session push skipped: ${safeTerminalText(errorMessage(error))}`, "warning");
216
217
  }
217
218
  }
@@ -230,9 +231,8 @@ function registerPiSyncDebug(pi, getOwner) {
230
231
  exposure: "direct",
231
232
  executionMode: "sequential",
232
233
  async execute(_id, { action }, toolSignal, _update, ctx) {
233
- const owner = getOwner(ctx);
234
- if (!owner || !ctx.hasUI || ctx.mode !== "tui" && ctx.mode !== "rpc")
235
- throw new Error("Pi Sync debug requires an interactive session started with Debug mode on.");
234
+ const owner = ctx.hasUI && (ctx.mode === "tui" || ctx.mode === "rpc") ? getOwner(ctx) : void 0;
235
+ if (!owner) throw new Error("Pi Sync debug requires an interactive session started with Debug mode on.");
236
236
  const { client } = owner;
237
237
  const signal = toolSignal ? AbortSignal.any([owner.signal, toolSignal]) : owner.signal;
238
238
  const validate = () => {
@@ -241,7 +241,7 @@ function registerPiSyncDebug(pi, getOwner) {
241
241
  try {
242
242
  client.validateDebugTool();
243
243
  } catch {
244
- throw new Error("The Pi Sync debug session is no longer available.");
244
+ throw new Error(PI_SYNC_BINDING_UNAVAILABLE);
245
245
  }
246
246
  };
247
247
  validate();
@@ -437,12 +437,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
437
437
  // src/sync/sync-loaders.ts
438
438
  function createSyncLoaders(dependencies) {
439
439
  const loaders = {
440
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-GERC7LOE.ts"))),
441
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-ECI4BY5N.ts"))),
440
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-DWWFIXSC.ts"))),
441
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-CQDNC542.ts"))),
442
442
  setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-WSKVGW7L.ts"))),
443
443
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
444
444
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-QIT64TKV.ts"))),
445
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-KWXZZEPT.ts")))
445
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-IF7LMWK6.ts")))
446
446
  };
447
447
  return loaders;
448
448
  }
@@ -489,38 +489,40 @@ function sync(pi, dependencies = {}) {
489
489
  const attention = createSyncAttentionController();
490
490
  const status = createSyncStatusPublisher(pi.events);
491
491
  const publishTimings = registerStartupTimings(pi);
492
- const check = createStartupCheck(loaders, attention, 3e4, publishTimings);
493
- let sessionAbort = new AbortController();
494
- let shutdownAbort;
495
- let initialization = Promise.resolve(void 0);
496
- let owner;
497
- let ownerManager;
498
- let presence;
499
- const exposeDebugTool = registerPiSyncDebug(
500
- pi,
501
- (ctx) => owner?.debugEnabled && !sessionAbort.signal.aborted && ownerManager === ctx.sessionManager ? { client: owner, signal: sessionAbort.signal } : void 0
502
- );
492
+ const beforeStart = new AbortController();
493
+ let session;
494
+ const sessionFor = (ctx) => session?.client.isFor(ctx.sessionManager) ? session : void 0;
495
+ const owns = (current) => session === current && current.client.isCurrent();
496
+ const exposeDebugTool = registerPiSyncDebug(pi, (ctx) => {
497
+ const current = sessionFor(ctx);
498
+ if (current?.client.debugEnabled) return { client: current.client, signal: current.client.signal };
499
+ });
503
500
  pi.registerCommand("sync", {
504
501
  description: "Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage",
505
502
  getArgumentCompletions: completeSyncArguments,
506
503
  handler: async (args, ctx) => {
507
- if (!ctx.hasUI) throw new Error("/sync requires TUI or RPC mode so results and safety prompts are observable.");
504
+ if (!ctx.hasUI || ctx.mode !== "tui" && ctx.mode !== "rpc")
505
+ throw new Error("/sync requires TUI or RPC mode so results and safety prompts are observable.");
508
506
  const retired = retiredSyncCommandGuidance(splitArgs(args)[0]);
509
507
  if (retired) {
510
508
  ctx.ui.notify(retired, "warning");
511
509
  return;
512
510
  }
513
- status.bind(ctx);
514
- const signal = sessionAbort.signal;
515
- const client = owner;
516
- if (!client || ownerManager !== ctx.sessionManager) {
517
- if (splitArgs(args)[0] !== "help") throw new Error("pi-sync session is not ready.");
511
+ const current = sessionFor(ctx);
512
+ if (!current || !owns(current)) {
513
+ if (beforeStart.signal.aborted || splitArgs(args)[0] !== "help") {
514
+ ctx.ui.notify(PI_SYNC_BINDING_UNAVAILABLE, "error");
515
+ return;
516
+ }
517
+ status.bind(ctx);
518
518
  const commands = await loaders.commands();
519
- if (signal.aborted || owner) return;
519
+ if (beforeStart.signal.aborted) return;
520
520
  ctx.isIdle();
521
- await commands.handleCommand(args, ctx, signal, loaders, attention);
521
+ await commands.handleCommand(args, ctx, beforeStart.signal, loaders, attention);
522
522
  return;
523
523
  }
524
+ const { client, check, initialization } = current;
525
+ const { signal } = client;
524
526
  const reload = new AbortController();
525
527
  const commandSignal = combineSignals(signal, reload.signal);
526
528
  try {
@@ -530,7 +532,10 @@ function sync(pi, dependencies = {}) {
530
532
  const [command, action, ...extra] = splitArgs(args);
531
533
  const recover = command === "daemon" && action === "recover";
532
534
  const ready = recover ? void 0 : await initialization;
533
- if (signal.aborted || owner !== client) return;
535
+ if (!owns(current)) {
536
+ if (session === current && !signal.aborted) ctx2.ui.notify(PI_SYNC_BINDING_UNAVAILABLE, "error");
537
+ return;
538
+ }
534
539
  const needsDaemonRecovery = () => client.ownershipCleanupRequired;
535
540
  if (recover || !command && needsDaemonRecovery()) {
536
541
  if (recover && extra.length) {
@@ -538,7 +543,7 @@ function sync(pi, dependencies = {}) {
538
543
  return;
539
544
  }
540
545
  const commands = await loaders.commands();
541
- if (signal.aborted || owner !== client) return;
546
+ if (!owns(current)) return;
542
547
  await commands.handleCommand(
543
548
  args,
544
549
  ctx2,
@@ -556,9 +561,9 @@ function sync(pi, dependencies = {}) {
556
561
  try {
557
562
  await client.setBusy("command", true, requiresContact);
558
563
  busyPublished = requiresContact;
559
- if (signal.aborted || owner !== client) return;
564
+ if (!owns(current)) return;
560
565
  if (!daemonStatus) await check.stop();
561
- if (signal.aborted || owner !== client) return;
566
+ if (!owns(current)) return;
562
567
  if (ready === false && command !== "help" && command !== "unlock" && command !== "migrate-state" && command !== "daemon") {
563
568
  ctx2.ui.notify(
564
569
  "pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.",
@@ -568,11 +573,11 @@ function sync(pi, dependencies = {}) {
568
573
  }
569
574
  if (command === "unlock" || command === "migrate-state") {
570
575
  const { stateDirectoryMigrationNotice } = await import("./chunks/state-directory-CMAIF34J.ts");
571
- if (signal.aborted || owner !== client) return;
576
+ if (!owns(current)) return;
572
577
  stateDirectoryMigrationNotice();
573
578
  }
574
579
  const commands = await loaders.commands();
575
- if (signal.aborted || owner !== client) return;
580
+ if (!owns(current)) return;
576
581
  await commands.handleCommand(
577
582
  args,
578
583
  ctx2,
@@ -584,21 +589,22 @@ function sync(pi, dependencies = {}) {
584
589
  );
585
590
  } catch (error) {
586
591
  client.recordOwnershipFailure(error);
587
- if (!commandSignal.aborted && owner === client) {
592
+ if (!commandSignal.aborted && owns(current)) {
588
593
  ctx2.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
589
594
  if (command === "unlock" || command === "migrate-state") throw error;
590
595
  }
591
596
  } finally {
592
- if (!signal.aborted && owner === client) {
597
+ if (owns(current)) {
593
598
  const publish = busyPublished || daemonStatus || command === "unlock" || command === "migrate-state";
594
599
  await client.setBusy("command", false, publish && !needsDaemonRecovery()).catch(() => {
595
600
  });
596
601
  }
597
602
  }
598
603
  },
599
- reload
604
+ reload,
605
+ client
600
606
  );
601
- if (!signal.aborted && owner === client && client.canReload(reload)) await ctx.reload();
607
+ if (owns(current) && client.canReload(reload)) await ctx.reload();
602
608
  } finally {
603
609
  client.releaseReload(reload);
604
610
  reload.abort();
@@ -606,50 +612,89 @@ function sync(pi, dependencies = {}) {
606
612
  }
607
613
  });
608
614
  pi.on("session_start", async (event, ctx) => {
609
- const previousClient = owner;
610
- shutdownAbort?.abort(new DOMException("Session replaced", "AbortError"));
611
- shutdownAbort = void 0;
612
- sessionAbort.abort(new DOMException("Session replaced", "AbortError"));
613
- const releaseStatus = status.start(ctx);
614
- sessionAbort = new AbortController();
615
- const signal = sessionAbort.signal;
616
- const client = bindPiDaemonClient(ctx, signal, publishTimings);
617
- owner = client;
618
- ownerManager = ctx.sessionManager;
619
- const registration = sessionPresence(client.root, ctx.sessionManager, event?.previousSessionFile);
620
- presence = registration;
621
- const replacementFile = ctx.sessionManager.getSessionFile?.();
622
- attention.reset(ctx);
623
- const previous = initialization;
624
- initialization = withPiDaemonClient(ctx, async () => {
625
- await previous.catch(() => {
615
+ const previous = session;
616
+ const replaced = new DOMException("Session replaced", "AbortError");
617
+ beforeStart.abort(replaced);
618
+ previous?.shutdown?.abort?.abort(replaced);
619
+ previous?.abort.abort(replaced);
620
+ const previousCheck = previous?.check.stop();
621
+ const retirePrevious = async (replacementFile) => {
622
+ if (!previous) return;
623
+ const shutdown = previous.shutdown?.done;
624
+ await previous.initialization.catch(() => {
626
625
  });
627
- if (signal.aborted || owner !== client) return false;
626
+ await previousCheck;
628
627
  try {
629
- await registration.start(signal);
630
- if (signal.aborted || owner !== client) return false;
631
- await check.stop();
632
- if (signal.aborted || owner !== client) return false;
633
- if (previousClient) {
634
- try {
635
- await client.attachExisting({ allowUpgrade: true });
636
- } catch {
637
- }
638
- try {
639
- await previousClient.disposeForShutdown("resume", replacementFile);
640
- } catch {
628
+ await (shutdown ?? previous.client.disposeForShutdown("resume", replacementFile));
629
+ } catch {
630
+ }
631
+ };
632
+ const abort = new AbortController();
633
+ let client;
634
+ let releaseStatus;
635
+ try {
636
+ client = bindPiDaemonClient(ctx, abort.signal, publishTimings);
637
+ releaseStatus = status.start(ctx);
638
+ } catch (error) {
639
+ const retirement = retirePrevious();
640
+ if (previous && !previous.shutdown) previous.shutdown = { done: retirement };
641
+ abort.abort(error);
642
+ if (session === previous) {
643
+ try {
644
+ attention.reset(ctx);
645
+ } catch {
646
+ }
647
+ }
648
+ await Promise.allSettled([retirement, client?.disposeForShutdown("resume")]);
649
+ previous?.releaseStatus();
650
+ if (session === previous) session = void 0;
651
+ throw error;
652
+ }
653
+ const { signal } = client;
654
+ const check = createStartupCheck(loaders, attention, 3e4, publishTimings);
655
+ const current = {
656
+ client,
657
+ abort,
658
+ check,
659
+ releaseStatus,
660
+ initialization: Promise.resolve(void 0)
661
+ };
662
+ session = current;
663
+ current.initialization = Promise.resolve().then(async () => {
664
+ try {
665
+ let replacementFile;
666
+ try {
667
+ if (previous) await previous.initialization.catch(() => {
668
+ });
669
+ if (!owns(current)) return false;
670
+ client.validate();
671
+ const manager = ctx.sessionManager;
672
+ replacementFile = manager.getSessionFile?.();
673
+ current.presence = sessionPresence(client.root, manager, event?.previousSessionFile);
674
+ attention.reset(ctx);
675
+ await current.presence.start(signal);
676
+ if (previous) {
677
+ await previousCheck;
678
+ if (!owns(current)) return false;
679
+ try {
680
+ await client.attachExisting({ allowUpgrade: true });
681
+ } catch {
682
+ }
641
683
  }
642
- await client.finishReattachment();
684
+ } finally {
685
+ await retirePrevious(replacementFile);
643
686
  }
644
- if (signal.aborted || owner !== client) return false;
645
- return (await startSession(ctx, signal, publishTimings))?.config;
687
+ if (!owns(current)) return false;
688
+ if (previous) await client.finishReattachment();
689
+ if (!owns(current)) return false;
690
+ return (await withPiDaemonClient(ctx, () => startSession(ctx, signal, publishTimings), void 0, client))?.config;
646
691
  } catch (error) {
647
- if (!signal.aborted && owner === client) {
692
+ if (session === current && !signal.aborted) {
648
693
  try {
649
694
  ctx.isIdle();
650
695
  client.recordOwnershipFailure(error);
651
696
  if (ctx.hasUI) {
652
- const advice = client.ownershipCleanupRequired ? " Open /sync to recover the daemon." : "";
697
+ const advice = !client.isCurrent() ? ` ${PI_SYNC_BINDING_UNAVAILABLE}` : client.ownershipCleanupRequired ? " Open /sync to recover the daemon." : "";
653
698
  ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}${advice}`, "error");
654
699
  }
655
700
  } catch {
@@ -659,66 +704,90 @@ function sync(pi, dependencies = {}) {
659
704
  }
660
705
  });
661
706
  try {
662
- const ready = await initialization;
663
- if (!signal.aborted && owner === client) exposeDebugTool(client.debugEnabled);
707
+ const ready = await current.initialization;
708
+ if (session === current && !signal.aborted) exposeDebugTool(client.debugEnabled);
664
709
  if (ready === false) {
665
710
  client.disableQueueReleaseUI();
666
- releaseStatus();
711
+ current.releaseStatus();
667
712
  }
668
- if (ready && !signal.aborted && owner === client && (ready.automatic || startupTransferEnabled(ready)))
669
- await withPiDaemonClient(ctx, async () => {
670
- check.start(
671
- ctx,
672
- signal,
673
- ready,
674
- client.debugEnabled ? (report) => client.recordDebug({ event: "startup-timings", report }) : void 0
675
- );
676
- });
713
+ if (ready && owns(current) && (ready.automatic || startupTransferEnabled(ready)))
714
+ await withPiDaemonClient(
715
+ ctx,
716
+ async () => {
717
+ check.start(
718
+ ctx,
719
+ signal,
720
+ ready,
721
+ client.debugEnabled ? (report) => client.recordDebug({ event: "startup-timings", report }) : void 0
722
+ );
723
+ },
724
+ void 0,
725
+ client
726
+ );
677
727
  } catch (error) {
678
728
  client.disableQueueReleaseUI();
679
- releaseStatus();
680
- throw error;
729
+ current.releaseStatus();
730
+ if (owns(current)) throw error;
681
731
  }
682
732
  });
683
- pi.on("agent_start", async (_event, ctx) => {
684
- const client = owner;
685
- if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;
686
- if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) await client.attachExisting();
687
- await client.setBusy("agent", true);
688
- if (owner === client && !sessionAbort.signal.aborted) await check.interrupt(ctx);
689
- });
690
- pi.on("agent_settled", async (_event, ctx) => {
691
- const client = owner;
692
- if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;
693
- await client.setBusy("agent", false);
694
- if (owner === client && !sessionAbort.signal.aborted)
695
- await withPiDaemonClient(ctx, async () => {
696
- check.settled(ctx);
697
- });
698
- });
699
- pi.on("model_select", async (_event, ctx) => {
700
- if (owner && ownerManager === ctx.sessionManager && !sessionAbort.signal.aborted) await owner.update();
701
- });
733
+ const whileOwned = async (ctx, action) => {
734
+ const current = sessionFor(ctx);
735
+ if (!current || !owns(current)) return;
736
+ try {
737
+ await action(current);
738
+ } catch (error) {
739
+ if (owns(current)) throw error;
740
+ }
741
+ };
742
+ pi.on(
743
+ "agent_start",
744
+ (_event, ctx) => whileOwned(ctx, async (current) => {
745
+ const { client, check } = current;
746
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) {
747
+ await client.attachExisting();
748
+ if (!owns(current)) return;
749
+ }
750
+ await client.setBusy("agent", true);
751
+ if (owns(current)) await check.interrupt(ctx);
752
+ })
753
+ );
754
+ pi.on(
755
+ "agent_settled",
756
+ (_event, ctx) => whileOwned(ctx, async (current) => {
757
+ const { client, check } = current;
758
+ await client.setBusy("agent", false);
759
+ if (owns(current))
760
+ await withPiDaemonClient(
761
+ ctx,
762
+ async () => {
763
+ check.settled(ctx);
764
+ },
765
+ void 0,
766
+ client
767
+ );
768
+ })
769
+ );
770
+ pi.on("model_select", (_event, ctx) => whileOwned(ctx, ({ client }) => client.update()));
702
771
  const pauseForReplacement = async (event, ctx) => {
703
- const client = owner;
704
- const registration = presence;
705
- const signal = sessionAbort.signal;
706
- if (!client || ownerManager !== ctx.sessionManager || signal.aborted) return;
772
+ const current = sessionFor(ctx);
773
+ if (!current || current.client.signal.aborted) return;
774
+ const { client, presence, check } = current;
775
+ const { signal } = client;
776
+ if (!owns(current) || !presence) return { cancel: true };
707
777
  const results = await Promise.allSettled([client.pauseForSessionChange(), check.stop()]);
708
- if (owner !== client || signal.aborted) return { cancel: true };
778
+ if (!owns(current)) return { cancel: true };
709
779
  if (results.some((result) => result.status === "rejected")) {
710
- if (owner === client && !signal.aborted)
711
- ctx.ui.notify(
712
- "pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.",
713
- "error"
714
- );
780
+ ctx.ui.notify(
781
+ "pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.",
782
+ "error"
783
+ );
715
784
  return { cancel: true };
716
785
  }
717
786
  try {
718
- await registration?.publish(event.targetSessionFile, !event.targetSessionFile, signal);
719
- if (owner !== client || signal.aborted) return { cancel: true };
787
+ await presence.publish(event.targetSessionFile, !event.targetSessionFile, signal);
788
+ if (!owns(current)) return { cancel: true };
720
789
  } catch (error) {
721
- if (owner === client && !signal.aborted && ctx.hasUI)
790
+ if (owns(current) && ctx.hasUI)
722
791
  ctx.ui.notify(`pi-sync could not protect the next session: ${safeTerminalText(errorMessage(error))}`, "error");
723
792
  return { cancel: true };
724
793
  }
@@ -726,66 +795,69 @@ function sync(pi, dependencies = {}) {
726
795
  pi.on("session_before_switch", pauseForReplacement);
727
796
  pi.on("session_before_fork", pauseForReplacement);
728
797
  pi.on("session_shutdown", async (event, ctx) => {
729
- const releaseStatus = status.cleanupFor(ctx);
730
- const client = owner;
731
- const registration = presence;
732
- if (!client || ownerManager !== ctx.sessionManager) {
733
- releaseStatus();
798
+ const current = sessionFor(ctx);
799
+ if (!current) {
800
+ if (!session) status.cleanupFor(ctx)();
734
801
  return;
735
802
  }
803
+ if (current.shutdown) return current.shutdown.done;
804
+ const { client, check, initialization, releaseStatus } = current;
805
+ const canPush = owns(current);
736
806
  const controller = new AbortController();
737
- shutdownAbort?.abort(new DOMException("Session shut down again", "AbortError"));
738
- shutdownAbort = controller;
739
- const signal = combineSignals(controller.signal, AbortSignal.timeout(3e4));
740
- const reason = typeof event === "object" && event ? event.reason : void 0;
741
- const target = typeof event === "object" && event ? event.targetSessionFile : void 0;
742
- sessionAbort.abort(new DOMException("Session shutting down", "AbortError"));
743
- let shutdownClient;
744
- try {
745
- await initialization.catch(() => {
746
- });
747
- await check.stop();
748
- if (signal.aborted || owner !== client) return;
749
- await registration?.shutdown(target, signal);
750
- if (signal.aborted || owner !== client) return;
751
- if (reason !== "reload") {
752
- shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);
753
- await shutdownClient.setDebugPreference(client.debugEnabled);
754
- if (signal.aborted || owner !== client) return;
755
- await shutdownClient.setBusy("shutdown", true);
756
- const attached = await shutdownClient.attachExisting();
757
- if (!signal.aborted && owner === client && attached)
758
- await withPiDaemonClient(ctx, () => autoPushSessions(ctx, signal, loaders));
759
- }
760
- } catch (error) {
761
- if (!signal.aborted && owner === client) {
762
- try {
763
- ctx.ui.notify(`pi-sync shutdown skipped: ${safeTerminalText(errorMessage(error))}`, "warning");
764
- } catch {
765
- }
766
- }
767
- } finally {
768
- if (owner === client) {
769
- owner = void 0;
770
- ownerManager = void 0;
771
- presence = void 0;
772
- try {
773
- attention.reset(ctx);
774
- } catch {
775
- }
776
- }
807
+ const signal = AbortSignal.any([controller.signal, client.replacementSignal, AbortSignal.timeout(3e4)]);
808
+ const isEnding = () => session === current && !signal.aborted;
809
+ const reason = event?.reason;
810
+ const target = event && "targetSessionFile" in event ? event.targetSessionFile : void 0;
811
+ const done = Promise.resolve().then(async () => {
812
+ let shutdownClient;
777
813
  try {
778
- await client.disposeForShutdown(reason, target);
814
+ await initialization.catch(() => {
815
+ });
816
+ await check.stop();
817
+ if (!isEnding()) return;
818
+ await current.presence?.shutdown(target, signal);
819
+ if (!isEnding() || !canPush || !client.ownsBinding() || reason === "reload") return;
820
+ const endingClient = client.createShutdownClient(ctx, signal);
821
+ shutdownClient = endingClient;
822
+ await endingClient.setDebugPreference(client.debugEnabled);
823
+ if (!isEnding() || !endingClient.isCurrent()) return;
824
+ await endingClient.setBusy("shutdown", true);
825
+ if (!isEnding() || !endingClient.isCurrent()) return;
826
+ const attached = await endingClient.attachExisting();
827
+ if (isEnding() && endingClient.isCurrent() && attached)
828
+ await withPiDaemonClient(ctx, (owned) => autoPushSessions(owned, signal, loaders), void 0, endingClient);
829
+ } catch (error) {
830
+ if (isEnding() && client.ownsBinding()) {
831
+ try {
832
+ ctx.ui.notify(`pi-sync shutdown skipped: ${safeTerminalText(errorMessage(error))}`, "warning");
833
+ } catch {
834
+ }
835
+ }
779
836
  } finally {
837
+ if (session === current) {
838
+ if (client.ownsBinding()) {
839
+ try {
840
+ attention.reset(ctx);
841
+ } catch {
842
+ }
843
+ }
844
+ }
780
845
  try {
781
- await shutdownClient?.disposeForShutdown(reason, target);
846
+ await client.disposeForShutdown(reason, target);
782
847
  } finally {
783
- controller.abort();
784
- releaseStatus();
848
+ try {
849
+ await shutdownClient?.disposeForShutdown(reason, target);
850
+ } finally {
851
+ controller.abort();
852
+ releaseStatus();
853
+ if (session === current) session = void 0;
854
+ }
785
855
  }
786
856
  }
787
- if (shutdownAbort === controller) shutdownAbort = void 0;
788
- }
857
+ });
858
+ current.shutdown = { abort: controller, done };
859
+ current.abort.abort(new DOMException("Session shutting down", "AbortError"));
860
+ await done;
789
861
  });
790
862
  }
791
863
  export {