@narumitw/pi-sync 0.70.5 → 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.
Files changed (68) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +2 -0
  3. package/dist/chunks/{chunk-3XN4FR72.ts → chunk-4A34OGXY.ts} +9 -9
  4. package/dist/chunks/{chunk-7NQ7SFZK.ts → chunk-5BE6LBDC.ts} +15 -15
  5. package/dist/chunks/chunk-A43CJYG4.ts +26 -0
  6. package/dist/chunks/chunk-A43CJYG4.ts.map +7 -0
  7. package/dist/chunks/{chunk-JPTI4HFC.ts → chunk-AXN3B5KC.ts} +22 -22
  8. package/dist/chunks/{chunk-SPXEDJ2G.ts → chunk-HCXPNKPU.ts} +61 -59
  9. package/dist/chunks/chunk-HCXPNKPU.ts.map +7 -0
  10. package/dist/chunks/{chunk-N24HEZSA.ts → chunk-VERMBZGL.ts} +7 -7
  11. package/dist/chunks/{chunk-LSIUAXE4.ts → chunk-WE3KJ7JS.ts} +8 -8
  12. package/dist/chunks/{chunk-5T4ZOHYF.ts → chunk-WRS3SUNZ.ts} +4 -18
  13. package/dist/chunks/chunk-WRS3SUNZ.ts.map +7 -0
  14. package/dist/chunks/client-debug-F4WFP2YJ.ts +40 -0
  15. package/dist/chunks/client-debug-F4WFP2YJ.ts.map +7 -0
  16. package/dist/chunks/{command-handler-PT2KVTLD.ts → command-handler-DWWFIXSC.ts} +34 -32
  17. package/dist/chunks/{command-handler-PT2KVTLD.ts.map → command-handler-DWWFIXSC.ts.map} +1 -1
  18. package/dist/chunks/{conflict-review-QI77P7KL.ts → conflict-review-HSERM245.ts} +3 -3
  19. package/dist/chunks/debug-tool-execution-7N4H6K3X.ts +67 -0
  20. package/dist/chunks/debug-tool-execution-7N4H6K3X.ts.map +7 -0
  21. package/dist/chunks/{diff-review-SOLP33TQ.ts → diff-review-6IUIOYST.ts} +3 -3
  22. package/dist/chunks/{diff-review-ILRZDQ4S.ts → diff-review-GB4NO53B.ts} +4 -4
  23. package/dist/chunks/{file-selection-2H3J2HTX.ts → file-selection-DGC5UJVI.ts} +9 -9
  24. package/dist/chunks/{manager-result-dispatcher-75FS46JP.ts → manager-result-dispatcher-6MOJPLIS.ts} +7 -7
  25. package/dist/chunks/{manager-ui-HW3ZAEVK.ts → manager-ui-3CQU37XY.ts} +52 -50
  26. package/dist/chunks/{manager-ui-HW3ZAEVK.ts.map → manager-ui-3CQU37XY.ts.map} +1 -1
  27. package/dist/chunks/{remote-selection-ui-AE6FOEXH.ts → remote-selection-ui-2V53UBHM.ts} +6 -6
  28. package/dist/chunks/{setup-switch-LJPEZONY.ts → setup-switch-WSKVGW7L.ts} +4 -4
  29. package/dist/chunks/{setup-wizard-FBX7RTZ6.ts → setup-wizard-FRIR2EOR.ts} +9 -9
  30. package/dist/chunks/{sync-inspection-TZ4EMSBN.ts → sync-inspection-CQDNC542.ts} +6 -6
  31. package/dist/chunks/{sync-operations-QIQ3G66S.ts → sync-operations-IF7LMWK6.ts} +4 -4
  32. package/dist/chunks/sync-state-store-TZE7XDV5.ts +23 -0
  33. package/dist/chunks/sync-state-store-TZE7XDV5.ts.map +7 -0
  34. package/dist/daemon/dist/build-id.json +1 -1
  35. package/dist/daemon/dist/cli.js +3 -2
  36. package/dist/daemon/dist/client.js +55 -14
  37. package/dist/daemon/dist/daemon-startup.js +2 -14
  38. package/dist/daemon/dist/daemon-upgrade-error.js +14 -0
  39. package/dist/daemon/dist/index.js +20 -3
  40. package/dist/daemon/package.json +1 -1
  41. package/dist/index.ts +278 -248
  42. package/dist/index.ts.map +2 -2
  43. package/docs/daemon-migration.md +2 -0
  44. package/package.json +2 -2
  45. package/src/daemon/client-debug.ts +2 -0
  46. package/src/daemon/pi-client.ts +60 -22
  47. package/src/sync/automatic-sync.ts +5 -3
  48. package/src/sync/debug-tool-execution.ts +66 -0
  49. package/src/sync/debug-tool.ts +8 -56
  50. package/src/sync/startup-check.ts +3 -1
  51. package/src/sync-extension.ts +252 -166
  52. package/dist/chunks/chunk-5T4ZOHYF.ts.map +0 -7
  53. package/dist/chunks/chunk-SPXEDJ2G.ts.map +0 -7
  54. /package/dist/chunks/{chunk-3XN4FR72.ts.map → chunk-4A34OGXY.ts.map} +0 -0
  55. /package/dist/chunks/{chunk-7NQ7SFZK.ts.map → chunk-5BE6LBDC.ts.map} +0 -0
  56. /package/dist/chunks/{chunk-JPTI4HFC.ts.map → chunk-AXN3B5KC.ts.map} +0 -0
  57. /package/dist/chunks/{chunk-N24HEZSA.ts.map → chunk-VERMBZGL.ts.map} +0 -0
  58. /package/dist/chunks/{chunk-LSIUAXE4.ts.map → chunk-WE3KJ7JS.ts.map} +0 -0
  59. /package/dist/chunks/{conflict-review-QI77P7KL.ts.map → conflict-review-HSERM245.ts.map} +0 -0
  60. /package/dist/chunks/{diff-review-SOLP33TQ.ts.map → diff-review-6IUIOYST.ts.map} +0 -0
  61. /package/dist/chunks/{diff-review-ILRZDQ4S.ts.map → diff-review-GB4NO53B.ts.map} +0 -0
  62. /package/dist/chunks/{file-selection-2H3J2HTX.ts.map → file-selection-DGC5UJVI.ts.map} +0 -0
  63. /package/dist/chunks/{manager-result-dispatcher-75FS46JP.ts.map → manager-result-dispatcher-6MOJPLIS.ts.map} +0 -0
  64. /package/dist/chunks/{remote-selection-ui-AE6FOEXH.ts.map → remote-selection-ui-2V53UBHM.ts.map} +0 -0
  65. /package/dist/chunks/{setup-switch-LJPEZONY.ts.map → setup-switch-WSKVGW7L.ts.map} +0 -0
  66. /package/dist/chunks/{setup-wizard-FBX7RTZ6.ts.map → setup-wizard-FRIR2EOR.ts.map} +0 -0
  67. /package/dist/chunks/{sync-inspection-TZ4EMSBN.ts.map → sync-inspection-CQDNC542.ts.map} +0 -0
  68. /package/dist/chunks/{sync-operations-QIQ3G66S.ts.map → sync-operations-IF7LMWK6.ts.map} +0 -0
package/dist/index.ts CHANGED
@@ -1,53 +1,51 @@
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
- import {
4
- createSyncAttentionController,
5
- readStateForConfig,
6
- syncStateFingerprint
7
- } from "./chunks/chunk-5T4ZOHYF.ts";
8
- import {
9
- combineSignals,
10
- throwIfAborted
11
- } from "./chunks/chunk-UMPA5S7X.ts";
12
- import {
13
- completeSyncArguments,
14
- retiredSyncCommandGuidance,
15
- setSyncSetupCompletions,
16
- splitArgs
17
- } from "./chunks/chunk-VQTYTUBU.ts";
18
- import {
19
- withStateDirectoryAccess
20
- } from "./chunks/chunk-T3LABNHF.ts";
21
3
  import {
22
4
  snapshotOptionsForContext
23
5
  } from "./chunks/chunk-P4GI7LTT.ts";
24
- import "./chunks/chunk-ZO52JM4H.ts";
25
- import {
26
- configFromSettings,
27
- loadConfigForCheck,
28
- syncCheckConfigFingerprint,
29
- syncConfigReviewFingerprint
30
- } from "./chunks/chunk-LNZRNXNQ.ts";
31
6
  import {
7
+ PI_SYNC_BINDING_UNAVAILABLE,
32
8
  bindPiDaemonClient,
33
9
  installPiDaemonHost,
34
10
  piDaemonClient,
35
11
  withPiDaemonClient
36
- } from "./chunks/chunk-SPXEDJ2G.ts";
12
+ } from "./chunks/chunk-HCXPNKPU.ts";
13
+ import {
14
+ createSyncAttentionController
15
+ } from "./chunks/chunk-WRS3SUNZ.ts";
16
+ import "./chunks/chunk-ZO52JM4H.ts";
37
17
  import {
38
18
  configureSyncStatus,
39
19
  createSyncStatusPublisher,
40
20
  setSyncStatus
41
21
  } from "./chunks/chunk-H7VOTY5N.ts";
42
22
  import {
43
- errorMessage
44
- } from "./chunks/chunk-6YKOHBSC.ts";
23
+ combineSignals,
24
+ throwIfAborted
25
+ } from "./chunks/chunk-UMPA5S7X.ts";
45
26
  import {
46
27
  syncSessionsSelected
47
28
  } from "./chunks/chunk-R3SAMXB6.ts";
29
+ import {
30
+ completeSyncArguments,
31
+ retiredSyncCommandGuidance,
32
+ setSyncSetupCompletions,
33
+ splitArgs
34
+ } from "./chunks/chunk-VQTYTUBU.ts";
35
+ import {
36
+ errorMessage
37
+ } from "./chunks/chunk-6YKOHBSC.ts";
48
38
  import {
49
39
  safeTerminalText
50
40
  } from "./chunks/chunk-AMJRUXFT.ts";
41
+ import {
42
+ withStateDirectoryAccess
43
+ } from "./chunks/chunk-T3LABNHF.ts";
44
+ import {
45
+ configFromSettings,
46
+ loadConfigForCheck,
47
+ syncCheckConfigFingerprint
48
+ } from "./chunks/chunk-LNZRNXNQ.ts";
51
49
 
52
50
  // src/daemon/session-presence.ts
53
51
  import { createSessionPresence } from "#pi-sync-daemon";
@@ -130,7 +128,9 @@ async function startSession(ctx, signal, publish) {
130
128
  client.validate();
131
129
  throwIfAborted(signal);
132
130
  const debug = settings?.debug ?? false;
133
- client.setDebugPreference(debug);
131
+ await client.setDebugPreference(debug);
132
+ client.validate();
133
+ throwIfAborted(signal);
134
134
  configureSyncStatus(ctx, settings?.showStatus ?? true);
135
135
  const { stateDirectoryMigrationNotice } = await import("./chunks/state-directory-CMAIF34J.ts");
136
136
  client.validate();
@@ -191,8 +191,8 @@ async function startSession(ctx, signal, publish) {
191
191
  return { debug: result.debug, config: result.config };
192
192
  }
193
193
  async function autoPushSessions(ctx, signal, _loaders) {
194
+ const client = piDaemonClient(ctx);
194
195
  try {
195
- const client = piDaemonClient(ctx);
196
196
  const eligible = (config2) => config2.automatic && syncSessionsSelected(config2);
197
197
  if (!await client.configured((settings) => eligible(configFromSettings(settings)))) {
198
198
  client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
@@ -212,21 +212,15 @@ async function autoPushSessions(ctx, signal, _loaders) {
212
212
  signal
213
213
  );
214
214
  } catch (error) {
215
- if (signal.aborted || isMissingConfigError(error)) return;
215
+ if (signal.aborted || !client.isCurrent() || isMissingConfigError(error)) return;
216
216
  ctx.ui.notify(`pi-sync session push skipped: ${safeTerminalText(errorMessage(error))}`, "warning");
217
217
  }
218
218
  }
219
219
 
220
220
  // src/sync/debug-tool.ts
221
221
  import { StringEnum } from "@earendil-works/pi-ai";
222
- import { debugCheckFailure, summarizeDebugInspection } from "#pi-sync-daemon/engine/debug-check";
223
- import { readLatestDebugCheck } from "#pi-sync-daemon/engine/debug-log";
224
222
  import { Type } from "typebox";
225
223
  var TOOL_NAME = "pi_sync_debug";
226
- var RECHECK_TIMEOUT_MS = 3e4;
227
- function toolResult(value) {
228
- return { content: [{ type: "text", text: JSON.stringify(value) }], details: {} };
229
- }
230
224
  function registerPiSyncDebug(pi, getOwner) {
231
225
  pi.registerTool({
232
226
  name: TOOL_NAME,
@@ -237,9 +231,8 @@ function registerPiSyncDebug(pi, getOwner) {
237
231
  exposure: "direct",
238
232
  executionMode: "sequential",
239
233
  async execute(_id, { action }, toolSignal, _update, ctx) {
240
- const owner = getOwner(ctx);
241
- if (!owner || !ctx.hasUI || ctx.mode !== "tui" && ctx.mode !== "rpc")
242
- 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.");
243
236
  const { client } = owner;
244
237
  const signal = toolSignal ? AbortSignal.any([owner.signal, toolSignal]) : owner.signal;
245
238
  const validate = () => {
@@ -248,55 +241,16 @@ function registerPiSyncDebug(pi, getOwner) {
248
241
  try {
249
242
  client.validateDebugTool();
250
243
  } catch {
251
- throw new Error("The Pi Sync debug session is no longer available.");
244
+ throw new Error(PI_SYNC_BINDING_UNAVAILABLE);
252
245
  }
253
246
  };
254
- async function readSetup() {
255
- validate();
256
- try {
257
- const { settings } = await client.readStartupSettings(signal);
258
- validate();
259
- if (settings) return configFromSettings(settings);
260
- } catch {
261
- validate();
262
- }
263
- throw new Error("The current Pi Sync setup is not available. Review /sync \u2192 Settings.");
264
- }
265
- const setup = await readSetup();
266
247
  validate();
267
- if (action === "latest") {
268
- const last = readLatestDebugCheck(client.root, syncConfigReviewFingerprint(setup));
269
- if (last.kind === "unavailable") throw new Error("The private Pi Sync debug log is unavailable.");
270
- if (last.kind === "no-record") return toolResult({ kind: "no-record" });
271
- return toolResult({ kind: "historical", ...last.check });
272
- }
273
- if (action !== "recheck") throw new Error("Choose latest or recheck.");
274
- if (client.ownershipCleanupRequired) throw new Error("Pi Sync needs recovery. Open /sync daemon status.");
275
- const fingerprint = syncCheckConfigFingerprint(setup);
276
- const deadline = AbortSignal.timeout(RECHECK_TIMEOUT_MS);
277
- const recheckSignal = AbortSignal.any([signal, deadline]);
278
- let result;
279
- try {
280
- result = await client.run(
281
- "inspect",
282
- { setup: setup.setupName, fingerprint, origin: "recheck" },
283
- recheckSignal,
284
- ctx
285
- );
286
- } catch (error) {
248
+ const { executeDebugTool } = await import("./chunks/debug-tool-execution-7N4H6K3X.ts").catch(() => {
287
249
  validate();
288
- const { reason } = debugCheckFailure(deadline.aborted ? deadline.reason : error);
289
- throw new Error(`Pi Sync recheck failed: ${reason}.`);
290
- }
291
- validate();
292
- if (deadline.aborted) throw new Error("Pi Sync recheck failed: timeout.");
293
- const latest = await readSetup();
250
+ throw new Error("Pi Sync debug could not load.");
251
+ });
294
252
  validate();
295
- if (fingerprint !== syncCheckConfigFingerprint(latest))
296
- throw new Error("Pi Sync setup changed during recheck. Ask to recheck the new setup.");
297
- const summary = summarizeDebugInspection(result);
298
- if (!summary) throw new Error("Pi Sync did not return a valid check result.");
299
- return toolResult({ kind: "fresh", time: (/* @__PURE__ */ new Date()).toISOString(), origin: "recheck", summary });
253
+ return executeDebugTool(action, ctx, client, signal, validate);
300
254
  }
301
255
  });
302
256
  return (enabled) => {
@@ -370,6 +324,9 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
370
324
  () => inspectSync(captured, snapshotOptionsForContext(ctx, captured), signal, void 0, timings)
371
325
  );
372
326
  throwIfAborted(signal);
327
+ const { readStateForConfig, syncStateFingerprint } = await import("./chunks/sync-state-store-TZE7XDV5.ts");
328
+ throwIfAborted(signal);
329
+ if (!isCurrent()) return;
373
330
  const latest = await loadConfigForCheck(void 0, signal);
374
331
  throwIfAborted(signal);
375
332
  if (syncCheckConfigFingerprint(latest) !== identity) return;
@@ -480,12 +437,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
480
437
  // src/sync/sync-loaders.ts
481
438
  function createSyncLoaders(dependencies) {
482
439
  const loaders = {
483
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-PT2KVTLD.ts"))),
484
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-TZ4EMSBN.ts"))),
485
- setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-LJPEZONY.ts"))),
440
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-DWWFIXSC.ts"))),
441
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-CQDNC542.ts"))),
442
+ setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-WSKVGW7L.ts"))),
486
443
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
487
444
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-QIT64TKV.ts"))),
488
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-QIQ3G66S.ts")))
445
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-IF7LMWK6.ts")))
489
446
  };
490
447
  return loaders;
491
448
  }
@@ -532,38 +489,40 @@ function sync(pi, dependencies = {}) {
532
489
  const attention = createSyncAttentionController();
533
490
  const status = createSyncStatusPublisher(pi.events);
534
491
  const publishTimings = registerStartupTimings(pi);
535
- const check = createStartupCheck(loaders, attention, 3e4, publishTimings);
536
- let sessionAbort = new AbortController();
537
- let shutdownAbort;
538
- let initialization = Promise.resolve(void 0);
539
- let owner;
540
- let ownerManager;
541
- let presence;
542
- const exposeDebugTool = registerPiSyncDebug(
543
- pi,
544
- (ctx) => owner?.debugEnabled && !sessionAbort.signal.aborted && ownerManager === ctx.sessionManager ? { client: owner, signal: sessionAbort.signal } : void 0
545
- );
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
+ });
546
500
  pi.registerCommand("sync", {
547
501
  description: "Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage",
548
502
  getArgumentCompletions: completeSyncArguments,
549
503
  handler: async (args, ctx) => {
550
- 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.");
551
506
  const retired = retiredSyncCommandGuidance(splitArgs(args)[0]);
552
507
  if (retired) {
553
508
  ctx.ui.notify(retired, "warning");
554
509
  return;
555
510
  }
556
- status.bind(ctx);
557
- const signal = sessionAbort.signal;
558
- const client = owner;
559
- if (!client || ownerManager !== ctx.sessionManager) {
560
- 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);
561
518
  const commands = await loaders.commands();
562
- if (signal.aborted || owner) return;
519
+ if (beforeStart.signal.aborted) return;
563
520
  ctx.isIdle();
564
- await commands.handleCommand(args, ctx, signal, loaders, attention);
521
+ await commands.handleCommand(args, ctx, beforeStart.signal, loaders, attention);
565
522
  return;
566
523
  }
524
+ const { client, check, initialization } = current;
525
+ const { signal } = client;
567
526
  const reload = new AbortController();
568
527
  const commandSignal = combineSignals(signal, reload.signal);
569
528
  try {
@@ -573,7 +532,10 @@ function sync(pi, dependencies = {}) {
573
532
  const [command, action, ...extra] = splitArgs(args);
574
533
  const recover = command === "daemon" && action === "recover";
575
534
  const ready = recover ? void 0 : await initialization;
576
- 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
+ }
577
539
  const needsDaemonRecovery = () => client.ownershipCleanupRequired;
578
540
  if (recover || !command && needsDaemonRecovery()) {
579
541
  if (recover && extra.length) {
@@ -581,7 +543,7 @@ function sync(pi, dependencies = {}) {
581
543
  return;
582
544
  }
583
545
  const commands = await loaders.commands();
584
- if (signal.aborted || owner !== client) return;
546
+ if (!owns(current)) return;
585
547
  await commands.handleCommand(
586
548
  args,
587
549
  ctx2,
@@ -599,9 +561,9 @@ function sync(pi, dependencies = {}) {
599
561
  try {
600
562
  await client.setBusy("command", true, requiresContact);
601
563
  busyPublished = requiresContact;
602
- if (signal.aborted || owner !== client) return;
564
+ if (!owns(current)) return;
603
565
  if (!daemonStatus) await check.stop();
604
- if (signal.aborted || owner !== client) return;
566
+ if (!owns(current)) return;
605
567
  if (ready === false && command !== "help" && command !== "unlock" && command !== "migrate-state" && command !== "daemon") {
606
568
  ctx2.ui.notify(
607
569
  "pi-sync recovery required. Repair the startup error, then /reload before syncing. Use /sync help for recovery guidance.",
@@ -611,11 +573,11 @@ function sync(pi, dependencies = {}) {
611
573
  }
612
574
  if (command === "unlock" || command === "migrate-state") {
613
575
  const { stateDirectoryMigrationNotice } = await import("./chunks/state-directory-CMAIF34J.ts");
614
- if (signal.aborted || owner !== client) return;
576
+ if (!owns(current)) return;
615
577
  stateDirectoryMigrationNotice();
616
578
  }
617
579
  const commands = await loaders.commands();
618
- if (signal.aborted || owner !== client) return;
580
+ if (!owns(current)) return;
619
581
  await commands.handleCommand(
620
582
  args,
621
583
  ctx2,
@@ -627,21 +589,22 @@ function sync(pi, dependencies = {}) {
627
589
  );
628
590
  } catch (error) {
629
591
  client.recordOwnershipFailure(error);
630
- if (!commandSignal.aborted && owner === client) {
592
+ if (!commandSignal.aborted && owns(current)) {
631
593
  ctx2.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
632
594
  if (command === "unlock" || command === "migrate-state") throw error;
633
595
  }
634
596
  } finally {
635
- if (!signal.aborted && owner === client) {
597
+ if (owns(current)) {
636
598
  const publish = busyPublished || daemonStatus || command === "unlock" || command === "migrate-state";
637
599
  await client.setBusy("command", false, publish && !needsDaemonRecovery()).catch(() => {
638
600
  });
639
601
  }
640
602
  }
641
603
  },
642
- reload
604
+ reload,
605
+ client
643
606
  );
644
- if (!signal.aborted && owner === client && client.canReload(reload)) await ctx.reload();
607
+ if (owns(current) && client.canReload(reload)) await ctx.reload();
645
608
  } finally {
646
609
  client.releaseReload(reload);
647
610
  reload.abort();
@@ -649,50 +612,89 @@ function sync(pi, dependencies = {}) {
649
612
  }
650
613
  });
651
614
  pi.on("session_start", async (event, ctx) => {
652
- const previousClient = owner;
653
- shutdownAbort?.abort(new DOMException("Session replaced", "AbortError"));
654
- shutdownAbort = void 0;
655
- sessionAbort.abort(new DOMException("Session replaced", "AbortError"));
656
- const releaseStatus = status.start(ctx);
657
- sessionAbort = new AbortController();
658
- const signal = sessionAbort.signal;
659
- const client = bindPiDaemonClient(ctx, signal, publishTimings);
660
- owner = client;
661
- ownerManager = ctx.sessionManager;
662
- const registration = sessionPresence(client.root, ctx.sessionManager, event?.previousSessionFile);
663
- presence = registration;
664
- const replacementFile = ctx.sessionManager.getSessionFile?.();
665
- attention.reset(ctx);
666
- const previous = initialization;
667
- initialization = withPiDaemonClient(ctx, async () => {
668
- 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(() => {
669
625
  });
670
- if (signal.aborted || owner !== client) return false;
626
+ await previousCheck;
671
627
  try {
672
- await registration.start(signal);
673
- if (signal.aborted || owner !== client) return false;
674
- await check.stop();
675
- if (signal.aborted || owner !== client) return false;
676
- if (previousClient) {
677
- try {
678
- await client.attachExisting({ allowUpgrade: true });
679
- } catch {
680
- }
681
- try {
682
- await previousClient.disposeForShutdown("resume", replacementFile);
683
- } 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
+ }
684
683
  }
685
- await client.finishReattachment();
684
+ } finally {
685
+ await retirePrevious(replacementFile);
686
686
  }
687
- if (signal.aborted || owner !== client) return false;
688
- 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;
689
691
  } catch (error) {
690
- if (!signal.aborted && owner === client) {
692
+ if (session === current && !signal.aborted) {
691
693
  try {
692
694
  ctx.isIdle();
693
695
  client.recordOwnershipFailure(error);
694
696
  if (ctx.hasUI) {
695
- 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." : "";
696
698
  ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}${advice}`, "error");
697
699
  }
698
700
  } catch {
@@ -702,66 +704,90 @@ function sync(pi, dependencies = {}) {
702
704
  }
703
705
  });
704
706
  try {
705
- const ready = await initialization;
706
- if (!signal.aborted && owner === client) exposeDebugTool(client.debugEnabled);
707
+ const ready = await current.initialization;
708
+ if (session === current && !signal.aborted) exposeDebugTool(client.debugEnabled);
707
709
  if (ready === false) {
708
710
  client.disableQueueReleaseUI();
709
- releaseStatus();
711
+ current.releaseStatus();
710
712
  }
711
- if (ready && !signal.aborted && owner === client && (ready.automatic || startupTransferEnabled(ready)))
712
- await withPiDaemonClient(ctx, async () => {
713
- check.start(
714
- ctx,
715
- signal,
716
- ready,
717
- client.debugEnabled ? (report) => client.recordDebug({ event: "startup-timings", report }) : void 0
718
- );
719
- });
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
+ );
720
727
  } catch (error) {
721
728
  client.disableQueueReleaseUI();
722
- releaseStatus();
723
- throw error;
729
+ current.releaseStatus();
730
+ if (owns(current)) throw error;
724
731
  }
725
732
  });
726
- pi.on("agent_start", async (_event, ctx) => {
727
- const client = owner;
728
- if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;
729
- if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) await client.attachExisting();
730
- await client.setBusy("agent", true);
731
- if (owner === client && !sessionAbort.signal.aborted) await check.interrupt(ctx);
732
- });
733
- pi.on("agent_settled", async (_event, ctx) => {
734
- const client = owner;
735
- if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;
736
- await client.setBusy("agent", false);
737
- if (owner === client && !sessionAbort.signal.aborted)
738
- await withPiDaemonClient(ctx, async () => {
739
- check.settled(ctx);
740
- });
741
- });
742
- pi.on("model_select", async (_event, ctx) => {
743
- if (owner && ownerManager === ctx.sessionManager && !sessionAbort.signal.aborted) await owner.update();
744
- });
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()));
745
771
  const pauseForReplacement = async (event, ctx) => {
746
- const client = owner;
747
- const registration = presence;
748
- const signal = sessionAbort.signal;
749
- 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 };
750
777
  const results = await Promise.allSettled([client.pauseForSessionChange(), check.stop()]);
751
- if (owner !== client || signal.aborted) return { cancel: true };
778
+ if (!owns(current)) return { cancel: true };
752
779
  if (results.some((result) => result.status === "rejected")) {
753
- if (owner === client && !signal.aborted)
754
- ctx.ui.notify(
755
- "pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.",
756
- "error"
757
- );
780
+ ctx.ui.notify(
781
+ "pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.",
782
+ "error"
783
+ );
758
784
  return { cancel: true };
759
785
  }
760
786
  try {
761
- await registration?.publish(event.targetSessionFile, !event.targetSessionFile, signal);
762
- if (owner !== client || signal.aborted) return { cancel: true };
787
+ await presence.publish(event.targetSessionFile, !event.targetSessionFile, signal);
788
+ if (!owns(current)) return { cancel: true };
763
789
  } catch (error) {
764
- if (owner === client && !signal.aborted && ctx.hasUI)
790
+ if (owns(current) && ctx.hasUI)
765
791
  ctx.ui.notify(`pi-sync could not protect the next session: ${safeTerminalText(errorMessage(error))}`, "error");
766
792
  return { cancel: true };
767
793
  }
@@ -769,65 +795,69 @@ function sync(pi, dependencies = {}) {
769
795
  pi.on("session_before_switch", pauseForReplacement);
770
796
  pi.on("session_before_fork", pauseForReplacement);
771
797
  pi.on("session_shutdown", async (event, ctx) => {
772
- const releaseStatus = status.cleanupFor(ctx);
773
- const client = owner;
774
- const registration = presence;
775
- if (!client || ownerManager !== ctx.sessionManager) {
776
- releaseStatus();
798
+ const current = sessionFor(ctx);
799
+ if (!current) {
800
+ if (!session) status.cleanupFor(ctx)();
777
801
  return;
778
802
  }
803
+ if (current.shutdown) return current.shutdown.done;
804
+ const { client, check, initialization, releaseStatus } = current;
805
+ const canPush = owns(current);
779
806
  const controller = new AbortController();
780
- shutdownAbort?.abort(new DOMException("Session shut down again", "AbortError"));
781
- shutdownAbort = controller;
782
- const signal = combineSignals(controller.signal, AbortSignal.timeout(3e4));
783
- const reason = typeof event === "object" && event ? event.reason : void 0;
784
- const target = typeof event === "object" && event ? event.targetSessionFile : void 0;
785
- sessionAbort.abort(new DOMException("Session shutting down", "AbortError"));
786
- let shutdownClient;
787
- try {
788
- await initialization.catch(() => {
789
- });
790
- await check.stop();
791
- if (signal.aborted || owner !== client) return;
792
- await registration?.shutdown(target, signal);
793
- if (signal.aborted || owner !== client) return;
794
- if (reason !== "reload") {
795
- shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);
796
- shutdownClient.setDebugPreference(client.debugEnabled);
797
- await shutdownClient.setBusy("shutdown", true);
798
- const attached = await shutdownClient.attachExisting();
799
- if (!signal.aborted && owner === client && attached)
800
- await withPiDaemonClient(ctx, () => autoPushSessions(ctx, signal, loaders));
801
- }
802
- } catch (error) {
803
- if (!signal.aborted && owner === client) {
804
- try {
805
- ctx.ui.notify(`pi-sync shutdown skipped: ${safeTerminalText(errorMessage(error))}`, "warning");
806
- } catch {
807
- }
808
- }
809
- } finally {
810
- if (owner === client) {
811
- owner = void 0;
812
- ownerManager = void 0;
813
- presence = void 0;
814
- try {
815
- attention.reset(ctx);
816
- } catch {
817
- }
818
- }
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;
819
813
  try {
820
- 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
+ }
821
836
  } finally {
837
+ if (session === current) {
838
+ if (client.ownsBinding()) {
839
+ try {
840
+ attention.reset(ctx);
841
+ } catch {
842
+ }
843
+ }
844
+ }
822
845
  try {
823
- await shutdownClient?.disposeForShutdown(reason, target);
846
+ await client.disposeForShutdown(reason, target);
824
847
  } finally {
825
- controller.abort();
826
- releaseStatus();
848
+ try {
849
+ await shutdownClient?.disposeForShutdown(reason, target);
850
+ } finally {
851
+ controller.abort();
852
+ releaseStatus();
853
+ if (session === current) session = void 0;
854
+ }
827
855
  }
828
856
  }
829
- if (shutdownAbort === controller) shutdownAbort = void 0;
830
- }
857
+ });
858
+ current.shutdown = { abort: controller, done };
859
+ current.abort.abort(new DOMException("Session shutting down", "AbortError"));
860
+ await done;
831
861
  });
832
862
  }
833
863
  export {