@narumitw/pi-sync 0.70.2 → 0.70.3

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.
@@ -0,0 +1,207 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { canonicalRootGuard, privateDirectory, processExited, publishPrivateRecord, readPrivateRecord, readProcessBirth, runtimePaths, validBirth, } from "./identity.js";
7
+ import { withCleanup } from "./lifecycle.js";
8
+ import { record } from "./protocol.js";
9
+ const invalid = () => new Error("Cannot verify Pi session presence; keep the private records and retry after closing or reloading the other Pi sessions.");
10
+ const recordName = /^presence-[\da-f-]{36}\.json$/u;
11
+ const markerName = "session-write.json";
12
+ function owner(value, root) {
13
+ return (record(value) &&
14
+ value.version === 1 &&
15
+ value.root === root &&
16
+ typeof value.id === "string" &&
17
+ /^[\da-f-]{36}$/u.test(value.id) &&
18
+ typeof value.pid === "number" &&
19
+ Number.isSafeInteger(value.pid) &&
20
+ value.pid > 0 &&
21
+ value.pid <= 2_147_483_647 &&
22
+ (value.birth === undefined || validBirth(value.birth)));
23
+ }
24
+ function validPath(value) {
25
+ return typeof value === "string" && value.length <= 4096 && !value.includes("\0") && path.isAbsolute(value);
26
+ }
27
+ async function readMarker(paths) {
28
+ const value = await readPrivateRecord(path.join(paths.directory, markerName), "Pi session write marker");
29
+ if (value === undefined)
30
+ return;
31
+ if (!owner(value, paths.root))
32
+ throw invalid();
33
+ return value;
34
+ }
35
+ async function newOwner(paths) {
36
+ return {
37
+ version: 1,
38
+ root: paths.root,
39
+ id: randomUUID(),
40
+ pid: process.pid,
41
+ birth: await readProcessBirth(process.pid),
42
+ };
43
+ }
44
+ async function canonicalPath(file) {
45
+ if (!validPath(file))
46
+ throw invalid();
47
+ const missing = [];
48
+ for (let current = path.resolve(file);; current = path.dirname(current)) {
49
+ try {
50
+ return path.join(await fs.realpath(current), ...missing.reverse());
51
+ }
52
+ catch (error) {
53
+ if (error.code !== "ENOENT" || current === path.dirname(current))
54
+ throw error;
55
+ missing.push(path.basename(current));
56
+ }
57
+ }
58
+ }
59
+ function directoryGuard(paths) {
60
+ const assertRoot = canonicalRootGuard(paths.root);
61
+ const canonicalDirectory = realpathSync(paths.directory);
62
+ const assertDirectory = canonicalRootGuard(canonicalDirectory);
63
+ return () => {
64
+ assertRoot();
65
+ assertDirectory();
66
+ const stat = lstatSync(paths.directory);
67
+ if (!stat.isDirectory() ||
68
+ realpathSync(paths.directory) !== canonicalDirectory ||
69
+ (process.getuid && stat.uid !== process.getuid()) ||
70
+ (process.platform !== "win32" && stat.mode & 0o077))
71
+ throw invalid();
72
+ };
73
+ }
74
+ export async function createSessionPresence(root) {
75
+ const paths = await runtimePaths(root);
76
+ await privateDirectory(paths.directory);
77
+ const assertLocation = directoryGuard(paths);
78
+ await readPresence(paths);
79
+ assertLocation();
80
+ const identity = await newOwner(paths);
81
+ const file = path.join(paths.directory, `presence-${identity.id}.json`);
82
+ let tail = Promise.resolve();
83
+ return {
84
+ publish(files, pending, signal) {
85
+ const publish = tail.then(async () => {
86
+ signal?.throwIfAborted();
87
+ const targets = [...new Set(await Promise.all(files.map(canonicalPath)))];
88
+ const pendingRoot = pending === undefined ? undefined : await canonicalPath(pending);
89
+ const value = { ...identity, files: targets, pending: pendingRoot };
90
+ if (targets.length > 2 || Buffer.byteLength(JSON.stringify(value)) > 8192)
91
+ throw invalid();
92
+ assertLocation();
93
+ signal?.throwIfAborted();
94
+ await publishPrivateRecord(paths, file, value);
95
+ while (true) {
96
+ assertLocation();
97
+ signal?.throwIfAborted();
98
+ const writer = await readMarker(paths);
99
+ if (!writer || (await processExited(writer))) {
100
+ assertLocation();
101
+ signal?.throwIfAborted();
102
+ return;
103
+ }
104
+ await delay(25, undefined, { signal });
105
+ }
106
+ });
107
+ tail = publish.catch(() => { });
108
+ return publish;
109
+ },
110
+ };
111
+ }
112
+ export function sessionPathsOverlap(left, right) {
113
+ const a = path.resolve(left).normalize("NFC").toLowerCase();
114
+ const b = path.resolve(right).normalize("NFC").toLowerCase();
115
+ return (a === b ||
116
+ a.startsWith(b.endsWith(path.sep) ? b : b + path.sep) ||
117
+ b.startsWith(a.endsWith(path.sep) ? a : a + path.sep));
118
+ }
119
+ async function readPresence(paths) {
120
+ const records = (await fs.readdir(paths.directory)).filter((name) => name.startsWith("presence-"));
121
+ if (records.some((name) => !recordName.test(name)))
122
+ throw invalid();
123
+ let live = 0;
124
+ const files = new Set();
125
+ const pending = new Set();
126
+ for (const name of records) {
127
+ const file = path.join(paths.directory, name);
128
+ const value = await readPrivateRecord(file, "Pi session presence").catch((cause) => {
129
+ throw new Error(invalid().message, { cause });
130
+ });
131
+ if (value === undefined)
132
+ continue;
133
+ if (!owner(value, paths.root) ||
134
+ name !== `presence-${value.id}.json` ||
135
+ !Array.isArray(value.files) ||
136
+ value.files.length > 2 ||
137
+ !value.files.every(validPath) ||
138
+ (value.pending !== undefined && !validPath(value.pending)))
139
+ throw invalid();
140
+ if (await processExited(value)) {
141
+ await fs.rm(file, { force: true });
142
+ continue;
143
+ }
144
+ if (++live > 1024)
145
+ throw invalid();
146
+ for (const target of value.files)
147
+ files.add(target);
148
+ if (value.pending !== undefined)
149
+ pending.add(value.pending);
150
+ }
151
+ return { files: [...files], pending: [...pending] };
152
+ }
153
+ export function sessionPresenceReader(root) {
154
+ let tail = Promise.resolve();
155
+ const initialize = async () => {
156
+ const paths = await runtimePaths(root);
157
+ if (paths.root !== root)
158
+ throw invalid();
159
+ const assertLocation = directoryGuard(paths);
160
+ const owner = await newOwner(paths);
161
+ assertLocation();
162
+ return { paths, assertLocation, owner };
163
+ };
164
+ let location;
165
+ const locate = () => (location ??= initialize());
166
+ return {
167
+ async files() {
168
+ const { paths, assertLocation } = await locate();
169
+ assertLocation();
170
+ const { files } = await readPresence(paths);
171
+ assertLocation();
172
+ return files;
173
+ },
174
+ protect(targets, action, validate) {
175
+ const protectedWrite = tail.then(async () => {
176
+ const { paths, assertLocation, owner } = await locate();
177
+ assertLocation();
178
+ const previous = await readMarker(paths);
179
+ if (previous && !(await processExited(previous)))
180
+ throw invalid();
181
+ const identity = { ...owner, id: randomUUID() };
182
+ const file = path.join(paths.directory, markerName);
183
+ assertLocation();
184
+ validate();
185
+ await publishPrivateRecord(paths, file, identity);
186
+ return withCleanup(async () => {
187
+ assertLocation();
188
+ const { files, pending } = await readPresence(paths);
189
+ if (targets.some((target) => files.some((file) => sessionPathsOverlap(target, file)) ||
190
+ pending.some((dir) => sessionPathsOverlap(target, dir))))
191
+ throw new Error("A live Pi session or session transition protects this path. Wait or reload the other Pi before retrying.");
192
+ assertLocation();
193
+ validate();
194
+ return action();
195
+ }, async () => {
196
+ assertLocation();
197
+ if ((await readMarker(paths))?.id !== identity.id)
198
+ throw invalid();
199
+ assertLocation();
200
+ await fs.rm(file);
201
+ });
202
+ });
203
+ tail = protectedWrite.catch(() => { });
204
+ return protectedWrite;
205
+ },
206
+ };
207
+ }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.16.1"
2
+ "version": "0.16.2"
3
3
  }
package/dist/index.ts CHANGED
@@ -49,6 +49,53 @@ import {
49
49
  safeTerminalText
50
50
  } from "./chunks/chunk-AMJRUXFT.ts";
51
51
 
52
+ // src/daemon/session-presence.ts
53
+ import { createSessionPresence } from "#pi-sync-daemon";
54
+ var stateKey = /* @__PURE__ */ Symbol.for("@narumitw/pi-sync/session-presence/v1");
55
+ var processState = globalThis;
56
+ function handoffKey(root, previous, target) {
57
+ return JSON.stringify([root, previous, target]);
58
+ }
59
+ function sessionPresence(root, manager, previous) {
60
+ processState[stateKey] ??= { managers: /* @__PURE__ */ new WeakMap(), handoffs: /* @__PURE__ */ new Map() };
61
+ const state = processState[stateKey];
62
+ const current = manager.getSessionFile?.();
63
+ const directory = current ? manager.getSessionDir?.() ?? void 0 : void 0;
64
+ const key = previous && current ? handoffKey(root, previous, current) : void 0;
65
+ const candidates = key ? state.handoffs.get(key) : void 0;
66
+ const sameManager = state.managers.get(manager);
67
+ const predecessor = candidates?.size === 1 ? [...candidates][0] : void 0;
68
+ const slot = sameManager?.root === root ? sameManager : predecessor ?? { root };
69
+ if (key && predecessor === slot) state.handoffs.delete(key);
70
+ state.managers.set(manager, slot);
71
+ async function publish(target, pending, signal) {
72
+ if (!current && !target && !slot.registration) return;
73
+ if (pending && current && !target && !directory)
74
+ throw new Error("Cannot determine the pending Pi session directory.");
75
+ signal.throwIfAborted();
76
+ slot.registration ??= createSessionPresence(root).catch((error) => {
77
+ slot.registration = void 0;
78
+ throw error;
79
+ });
80
+ const writer = await slot.registration;
81
+ signal.throwIfAborted();
82
+ const files = [current, target].filter((file) => file !== void 0);
83
+ await writer.publish(files, pending && !target ? directory : void 0, signal);
84
+ }
85
+ return {
86
+ start: (signal) => publish(void 0, false, signal),
87
+ publish,
88
+ async shutdown(target, signal) {
89
+ await publish(target, false, signal);
90
+ if (!current || !target || signal.aborted) return;
91
+ const key2 = handoffKey(root, current, target);
92
+ const candidates2 = state.handoffs.get(key2) ?? /* @__PURE__ */ new Set();
93
+ candidates2.add(slot);
94
+ state.handoffs.set(key2, candidates2);
95
+ }
96
+ };
97
+ }
98
+
52
99
  // src/sync/agent-policy.ts
53
100
  import {
54
101
  AGENT_INPUT_BYTES,
@@ -491,6 +538,7 @@ function sync(pi, dependencies = {}) {
491
538
  let initialization = Promise.resolve(void 0);
492
539
  let owner;
493
540
  let ownerManager;
541
+ let presence;
494
542
  const exposeDebugTool = registerPiSyncDebug(
495
543
  pi,
496
544
  (ctx) => owner?.debugEnabled && !sessionAbort.signal.aborted && ownerManager === ctx.sessionManager ? { client: owner, signal: sessionAbort.signal } : void 0
@@ -600,7 +648,7 @@ function sync(pi, dependencies = {}) {
600
648
  }
601
649
  }
602
650
  });
603
- pi.on("session_start", async (_event, ctx) => {
651
+ pi.on("session_start", async (event, ctx) => {
604
652
  const previousClient = owner;
605
653
  shutdownAbort?.abort(new DOMException("Session replaced", "AbortError"));
606
654
  shutdownAbort = void 0;
@@ -611,6 +659,8 @@ function sync(pi, dependencies = {}) {
611
659
  const client = bindPiDaemonClient(ctx, signal, publishTimings);
612
660
  owner = client;
613
661
  ownerManager = ctx.sessionManager;
662
+ const registration = sessionPresence(client.root, ctx.sessionManager, event?.previousSessionFile);
663
+ presence = registration;
614
664
  const replacementFile = ctx.sessionManager.getSessionFile?.();
615
665
  attention.reset(ctx);
616
666
  const previous = initialization;
@@ -619,7 +669,10 @@ function sync(pi, dependencies = {}) {
619
669
  });
620
670
  if (signal.aborted || owner !== client) return false;
621
671
  try {
672
+ await registration.start(signal);
673
+ if (signal.aborted || owner !== client) return false;
622
674
  await check.stop();
675
+ if (signal.aborted || owner !== client) return false;
623
676
  if (previousClient) {
624
677
  try {
625
678
  await client.attachExisting({ allowUpgrade: true });
@@ -689,24 +742,36 @@ function sync(pi, dependencies = {}) {
689
742
  pi.on("model_select", async (_event, ctx) => {
690
743
  if (owner && ownerManager === ctx.sessionManager && !sessionAbort.signal.aborted) await owner.update();
691
744
  });
692
- const pauseForReplacement = async (_event, ctx) => {
745
+ const pauseForReplacement = async (event, ctx) => {
693
746
  const client = owner;
694
- if (!client || ownerManager !== ctx.sessionManager || sessionAbort.signal.aborted) return;
747
+ const registration = presence;
748
+ const signal = sessionAbort.signal;
749
+ if (!client || ownerManager !== ctx.sessionManager || signal.aborted) return;
695
750
  const results = await Promise.allSettled([client.pauseForSessionChange(), check.stop()]);
751
+ if (owner !== client || signal.aborted) return { cancel: true };
696
752
  if (results.some((result) => result.status === "rejected")) {
697
- if (owner === client && !sessionAbort.signal.aborted)
753
+ if (owner === client && !signal.aborted)
698
754
  ctx.ui.notify(
699
755
  "pi-sync could not drain its writer. Repair or stop the existing daemon before changing sessions.",
700
756
  "error"
701
757
  );
702
758
  return { cancel: true };
703
759
  }
760
+ try {
761
+ await registration?.publish(event.targetSessionFile, !event.targetSessionFile, signal);
762
+ if (owner !== client || signal.aborted) return { cancel: true };
763
+ } catch (error) {
764
+ if (owner === client && !signal.aborted && ctx.hasUI)
765
+ ctx.ui.notify(`pi-sync could not protect the next session: ${safeTerminalText(errorMessage(error))}`, "error");
766
+ return { cancel: true };
767
+ }
704
768
  };
705
769
  pi.on("session_before_switch", pauseForReplacement);
706
770
  pi.on("session_before_fork", pauseForReplacement);
707
771
  pi.on("session_shutdown", async (event, ctx) => {
708
772
  const releaseStatus = status.cleanupFor(ctx);
709
773
  const client = owner;
774
+ const registration = presence;
710
775
  if (!client || ownerManager !== ctx.sessionManager) {
711
776
  releaseStatus();
712
777
  return;
@@ -724,6 +789,8 @@ function sync(pi, dependencies = {}) {
724
789
  });
725
790
  await check.stop();
726
791
  if (signal.aborted || owner !== client) return;
792
+ await registration?.shutdown(target, signal);
793
+ if (signal.aborted || owner !== client) return;
727
794
  if (reason !== "reload") {
728
795
  shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);
729
796
  shutdownClient.setDebugPreference(client.debugEnabled);
@@ -743,6 +810,7 @@ function sync(pi, dependencies = {}) {
743
810
  if (owner === client) {
744
811
  owner = void 0;
745
812
  ownerManager = void 0;
813
+ presence = void 0;
746
814
  try {
747
815
  attention.reset(ctx);
748
816
  } catch {