@cydm/pie 4.11.0 → 4.12.1

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 (39) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +2 -2
  2. package/dist/builtin/extensions/cron/index.js +1 -1
  3. package/dist/builtin/extensions/im-forward/index.js +8724 -7393
  4. package/dist/builtin/extensions/mcp-adapter/index.js +1 -1
  5. package/dist/builtin/extensions/memory/index.js +171 -66
  6. package/dist/builtin/extensions/pie-ipc/index.js +1 -1
  7. package/dist/builtin/extensions/pie-proc/index.js +533 -50
  8. package/dist/builtin/extensions/plan-mode/index.js +2 -2
  9. package/dist/builtin/extensions/subagent/README.md +1 -1
  10. package/dist/builtin/extensions/subagent/index.js +3 -3
  11. package/dist/builtin/extensions/todo/index.js +2 -2
  12. package/dist/chunks/{auth-storage-C3FZMT7J.js → auth-storage-IJEJ2TGE.js} +1 -1
  13. package/dist/chunks/chunk-26ILLZKQ.js +400 -0
  14. package/dist/chunks/{chunk-OU33ROFD.js → chunk-3GG342QY.js} +78 -78
  15. package/dist/chunks/{chunk-IZKHSUNQ.js → chunk-CAPBTMLI.js} +18 -1
  16. package/dist/chunks/{chunk-B5GKDXVG.js → chunk-IZ4DYCJ7.js} +246 -80
  17. package/dist/chunks/{chunk-HK3FHIAH.js → chunk-KW46ND3S.js} +1999 -767
  18. package/dist/chunks/{chunk-SW2E33UL.js → chunk-LMDWWT43.js} +123 -4
  19. package/dist/chunks/{chunk-EWPPGYBU.js → chunk-OGGL6LUN.js} +55 -16
  20. package/dist/chunks/chunk-Q4NJEPIZ.js +210 -0
  21. package/dist/chunks/{chunk-KWK7KTSZ.js → chunk-Q5PSWX3B.js} +3 -3
  22. package/dist/chunks/{chunk-BTUMBUDU.js → chunk-QSXBPTOA.js} +1 -1
  23. package/dist/chunks/{chunk-5QMS6RQC.js → chunk-SXBX2P5R.js} +160 -5
  24. package/dist/chunks/{chunk-7LICWWUE.js → chunk-W37NAT3N.js} +2 -2
  25. package/dist/chunks/chunk-WTBLV6F5.js +476 -0
  26. package/dist/chunks/{chunk-BB7ETSJK.js → chunk-Y6AVNVOD.js} +150 -4
  27. package/dist/chunks/chunk-ZB5FVHI7.js +618 -0
  28. package/dist/chunks/{host-image-fallback-3TEMOQM5.js → host-image-fallback-NXY36VO2.js} +1 -1
  29. package/dist/chunks/{manager-cli-BXI4UFTJ.js → manager-cli-OTIMAWO6.js} +280 -299
  30. package/dist/chunks/{manager-upgrade-XPFXKO7A.js → manager-upgrade-DYRQ7YZ5.js} +101 -69
  31. package/dist/chunks/memory-git-C3S276QJ.js +19 -0
  32. package/dist/chunks/{model-registry-MGZO2RBN.js → model-registry-QNEPISBJ.js} +11 -3
  33. package/dist/chunks/{read-file-understanding-N2ZZQLTZ.js → read-file-understanding-ZCBNCQHG.js} +3 -3
  34. package/dist/chunks/{src-F5N6O2HR.js → src-7CU7OTQS.js} +36 -36
  35. package/dist/chunks/{src-3PSR2AAX.js → src-7MZZJVOG.js} +1 -1
  36. package/dist/cli.js +740 -512
  37. package/package.json +2 -2
  38. package/dist/chunks/chunk-L7XXKNZW.js +0 -386
  39. package/dist/chunks/chunk-ZPJ3BNQB.js +0 -126
@@ -171,6 +171,12 @@ var AuthStorage = class _AuthStorage {
171
171
  providerApiKeys = /* @__PURE__ */ new Map();
172
172
  runtimeApiKeys = /* @__PURE__ */ new Map();
173
173
  providerEnvVars = /* @__PURE__ */ new Map();
174
+ runtimeEnvVars = /* @__PURE__ */ new Map();
175
+ runtimeCredentialOverrides = /* @__PURE__ */ new Map();
176
+ oauthMaskedProviders = /* @__PURE__ */ new Set();
177
+ oauthVersionByProvider = /* @__PURE__ */ new Map();
178
+ configOwnedKeyProviders = /* @__PURE__ */ new Set();
179
+ configOwnedEnvProviders = /* @__PURE__ */ new Set();
174
180
  legacyApiKey;
175
181
  oauthCredentials = /* @__PURE__ */ new Map();
176
182
  removedOauthProviders = /* @__PURE__ */ new Set();
@@ -218,8 +224,53 @@ var AuthStorage = class _AuthStorage {
218
224
  this.runtimeApiKeys.delete(provider);
219
225
  return;
220
226
  }
227
+ this.oauthMaskedProviders.delete(provider);
221
228
  this.runtimeApiKeys.set(provider, apiKey);
222
229
  }
230
+ /** Drop any runtime token and mask persisted OAuth for `provider` until a
231
+ * fresh login/refresh binds a new token to the current endpoint. */
232
+ maskOAuthForProvider(provider) {
233
+ this.runtimeApiKeys.delete(provider);
234
+ this.oauthMaskedProviders.add(provider);
235
+ this.bumpOAuthVersion(provider);
236
+ }
237
+ isOAuthMasked(provider) {
238
+ return this.oauthMaskedProviders.has(provider);
239
+ }
240
+ getOAuthVersion(provider) {
241
+ return this.oauthVersionByProvider.get(provider) ?? 0;
242
+ }
243
+ bumpOAuthVersion(provider) {
244
+ const next = (this.oauthVersionByProvider.get(provider) ?? 0) + 1;
245
+ this.oauthVersionByProvider.set(provider, next);
246
+ return next;
247
+ }
248
+ setRuntimeEnvVar(provider, envVar) {
249
+ if (!envVar) {
250
+ this.runtimeEnvVars.delete(provider);
251
+ return;
252
+ }
253
+ this.runtimeEnvVars.set(provider, envVar);
254
+ }
255
+ setRuntimeCredentialOverride(provider, override) {
256
+ if (!override) {
257
+ this.runtimeCredentialOverrides.delete(provider);
258
+ return;
259
+ }
260
+ this.runtimeCredentialOverrides.set(provider, override);
261
+ }
262
+ /** Clear all extension-registered runtime env/override layers without touching config or OAuth layers. */
263
+ clearRuntimeEnvVars() {
264
+ this.runtimeEnvVars.clear();
265
+ this.runtimeCredentialOverrides.clear();
266
+ }
267
+ /** Restore ONLY the models.json/remote config credential layer (leaving runtime/OAuth untouched). */
268
+ restoreModelsConfigOnly(snapshot) {
269
+ this.providerApiKeys = new Map(snapshot.apiKeys);
270
+ this.providerEnvVars = new Map(snapshot.envVars);
271
+ this.configOwnedKeyProviders = new Set(snapshot.ownedKeys);
272
+ this.configOwnedEnvProviders = new Set(snapshot.ownedEnvs);
273
+ }
223
274
  setProviderEnvVar(provider, envVar) {
224
275
  if (!envVar) {
225
276
  this.providerEnvVars.delete(provider);
@@ -228,14 +279,69 @@ var AuthStorage = class _AuthStorage {
228
279
  this.providerEnvVars.set(provider, envVar);
229
280
  }
230
281
  getProviderEnvVar(provider) {
231
- return this.providerEnvVars.get(provider);
282
+ const rtOverride = this.runtimeCredentialOverrides.get(provider);
283
+ if (rtOverride) return rtOverride.kind === "env" ? rtOverride.envVar : void 0;
284
+ return this.runtimeEnvVars.get(provider) ?? this.providerEnvVars.get(provider);
285
+ }
286
+ /** Atomically replace models.json-owned provider keys/env vars, clearing
287
+ * entries removed from config while preserving runtime/OAuth layers. */
288
+ replaceModelsConfigCredentials(nextApiKeys, nextEnvVars) {
289
+ for (const p of this.configOwnedKeyProviders) {
290
+ if (!nextApiKeys.has(p)) this.providerApiKeys.delete(p);
291
+ }
292
+ for (const p of this.configOwnedEnvProviders) {
293
+ if (!nextEnvVars.has(p)) this.providerEnvVars.delete(p);
294
+ }
295
+ for (const [p, k] of nextApiKeys) this.providerApiKeys.set(p, k);
296
+ for (const [p, e] of nextEnvVars) this.providerEnvVars.set(p, e);
297
+ this.configOwnedKeyProviders = new Set(nextApiKeys.keys());
298
+ this.configOwnedEnvProviders = new Set(nextEnvVars.keys());
299
+ }
300
+ /** Mark a provider env var as config-owned (for async remote catalog refresh). */
301
+ setConfigProviderEnvVar(provider, envVar) {
302
+ this.providerEnvVars.set(provider, envVar);
303
+ this.configOwnedEnvProviders.add(provider);
304
+ }
305
+ /** Clear a config/remote-owned provider env var without disturbing runtime/OAuth layers. */
306
+ clearConfigProviderEnvVar(provider) {
307
+ if (!this.configOwnedEnvProviders.has(provider)) return;
308
+ this.providerEnvVars.delete(provider);
309
+ this.configOwnedEnvProviders.delete(provider);
310
+ }
311
+ /** Snapshot provider config & runtime key/env layers (leaving persisted OAuth untouched). */
312
+ snapshotProviderConfig() {
313
+ return {
314
+ apiKeys: new Map(this.providerApiKeys),
315
+ envVars: new Map(this.providerEnvVars),
316
+ runtimeKeys: new Map(this.runtimeApiKeys),
317
+ runtimeEnvs: new Map(this.runtimeEnvVars),
318
+ runtimeOverrides: new Map(this.runtimeCredentialOverrides),
319
+ oauthMasked: new Set(this.oauthMaskedProviders),
320
+ oauthVersions: new Map(this.oauthVersionByProvider),
321
+ ownedKeys: new Set(this.configOwnedKeyProviders),
322
+ ownedEnvs: new Set(this.configOwnedEnvProviders)
323
+ };
324
+ }
325
+ /** Restore a previously captured provider config snapshot on failed reload/replay. */
326
+ restoreProviderConfig(snapshot) {
327
+ this.providerApiKeys = new Map(snapshot.apiKeys);
328
+ this.providerEnvVars = new Map(snapshot.envVars);
329
+ this.runtimeApiKeys = new Map(snapshot.runtimeKeys);
330
+ this.runtimeEnvVars = new Map(snapshot.runtimeEnvs);
331
+ this.runtimeCredentialOverrides = new Map(snapshot.runtimeOverrides);
332
+ this.oauthMaskedProviders = new Set(snapshot.oauthMasked);
333
+ this.oauthVersionByProvider = new Map(snapshot.oauthVersions);
334
+ this.configOwnedKeyProviders = new Set(snapshot.ownedKeys);
335
+ this.configOwnedEnvProviders = new Set(snapshot.ownedEnvs);
232
336
  }
233
337
  setOAuthCredentials(provider, credentials) {
338
+ this.bumpOAuthVersion(provider);
234
339
  if (!credentials) {
235
340
  this.oauthCredentials.delete(provider);
236
341
  this.removedOauthProviders.add(provider);
237
342
  this.runtimeApiKeys.delete(provider);
238
343
  } else {
344
+ this.oauthMaskedProviders.delete(provider);
239
345
  this.oauthCredentials.set(provider, credentials);
240
346
  this.removedOauthProviders.delete(provider);
241
347
  }
@@ -255,13 +361,26 @@ var AuthStorage = class _AuthStorage {
255
361
  removedOauth: [...this.removedOauthProviders]
256
362
  });
257
363
  }
258
- getApiKey(provider, explicitEnvVar) {
364
+ getApiKey(provider, explicitEnvVar, opts) {
365
+ const rtOverride = this.runtimeCredentialOverrides.get(provider);
366
+ if (rtOverride) {
367
+ if (rtOverride.kind === "literal") return rtOverride.key;
368
+ if (rtOverride.kind === "env") {
369
+ return typeof process !== "undefined" ? process.env?.[rtOverride.envVar] || void 0 : void 0;
370
+ }
371
+ if (rtOverride.kind === "oauth") {
372
+ if (opts?.skipOAuth || this.oauthMaskedProviders.has(provider)) return void 0;
373
+ return this.runtimeApiKeys.get(provider) || this.usableOAuthAccessToken(provider);
374
+ }
375
+ return void 0;
376
+ }
259
377
  const envVar = explicitEnvVar || this.getProviderEnvVar(provider);
260
378
  const envApiKey = envVar && typeof process !== "undefined" ? process.env?.[envVar] : void 0;
261
- return this.runtimeApiKeys.get(provider) || this.providerApiKeys.get(provider) || envApiKey || this.usableOAuthAccessToken(provider) || this.legacyApiKey;
379
+ return this.runtimeApiKeys.get(provider) || this.providerApiKeys.get(provider) || envApiKey || (opts?.skipOAuth ? void 0 : this.usableOAuthAccessToken(provider)) || this.legacyApiKey;
262
380
  }
263
- /** Persisted OAuth access token, when it exists and has not expired. */
381
+ /** Persisted OAuth access token, when it exists, is unmasked, and has not expired. */
264
382
  usableOAuthAccessToken(provider) {
383
+ if (this.oauthMaskedProviders.has(provider)) return void 0;
265
384
  const credentials = this.oauthCredentials.get(provider);
266
385
  if (!credentials?.access) return void 0;
267
386
  if (credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_EXPIRY_SKEW_MS) {
@@ -1,9 +1,53 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ mergeThinkingCapability,
4
+ resolveProfileRoute,
5
+ validateModelsDocumentShape,
6
+ validateProfileConfig,
7
+ validatedRemoteCatalogs
8
+ } from "./chunk-IZ4DYCJ7.js";
9
+
10
+ // src/core/worker-lifecycle-bridge.ts
11
+ var activeBridge;
12
+ function registerWorkerLifecycleBridge(bridge) {
13
+ const token = /* @__PURE__ */ Symbol("worker-lifecycle-bridge");
14
+ activeBridge = { token, bridge };
15
+ return () => {
16
+ if (activeBridge?.token === token) activeBridge = void 0;
17
+ };
18
+ }
19
+ function currentWorkerLifecycleBridge() {
20
+ return activeBridge?.bridge;
21
+ }
2
22
 
3
23
  // src/core/worker-models-sync.ts
4
24
  import * as fs from "node:fs";
5
25
  import * as path from "node:path";
6
26
  import { createHash, randomUUID } from "node:crypto";
27
+ function validateModelsDocumentForSync(raw) {
28
+ try {
29
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || "providers" in raw) return false;
30
+ validateModelsDocumentShape(raw);
31
+ validatedRemoteCatalogs(raw.remoteCatalogs);
32
+ const modelApiMap = /* @__PURE__ */ new Map();
33
+ for (const [id, cfg] of Object.entries(raw.profiles || {})) {
34
+ validateProfileConfig(id, cfg);
35
+ for (const m of cfg.models || []) {
36
+ const route = resolveProfileRoute(cfg, m);
37
+ modelApiMap.set(`${id}/${m.id}`, { api: route.api, thinking: m.thinking ?? cfg.thinking });
38
+ }
39
+ }
40
+ for (const [key, ov] of Object.entries(raw.modelOverrides || {})) {
41
+ const target = modelApiMap.get(key);
42
+ if (target && ov?.thinking !== void 0) {
43
+ mergeThinkingCapability(target.thinking, ov.thinking, target.api, `models.json modelOverrides["${key}"].thinking`);
44
+ }
45
+ }
46
+ return true;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
7
51
  var INHERITED_HASH_FILENAME = ".models.inherited-sha256";
8
52
  var SYNC_LOCK_FILENAME = ".models.sync.lock";
9
53
  var LOCK_STALE_MS = 5e3;
@@ -226,6 +270,15 @@ function syncInheritedWorkerModels(workerModelsPath, globalModelsPath, opts = {}
226
270
  if (!fs.existsSync(globalModelsPath) || !isRegularFileIfExists(globalModelsPath)) return false;
227
271
  if (!isRegularFileIfExists(workerModelsPath) || !isRegularFileIfExists(sidecarPath)) return false;
228
272
  const globalText = fs.readFileSync(globalModelsPath, "utf8");
273
+ let globalParsed;
274
+ try {
275
+ globalParsed = JSON.parse(globalText);
276
+ } catch {
277
+ return false;
278
+ }
279
+ if (!validateModelsDocumentForSync(globalParsed)) {
280
+ return false;
281
+ }
229
282
  const globalHash = sha256Utf8(globalText);
230
283
  if (!fs.existsSync(workerModelsPath)) {
231
284
  writeAtomicFile(workerModelsPath, globalText, 384);
@@ -257,7 +310,6 @@ function syncInheritedWorkerModels(workerModelsPath, globalModelsPath, opts = {}
257
310
  return true;
258
311
  }
259
312
  const workerParsed = JSON.parse(workerText);
260
- const globalParsed = JSON.parse(globalText);
261
313
  if (!isLegacyUnmodifiedModelsSnapshot(workerParsed, globalParsed)) {
262
314
  return false;
263
315
  }
@@ -272,21 +324,8 @@ function syncInheritedWorkerModels(workerModelsPath, globalModelsPath, opts = {}
272
324
  }
273
325
  }
274
326
 
275
- // src/core/worker-lifecycle-bridge.ts
276
- var activeBridge;
277
- function registerWorkerLifecycleBridge(bridge) {
278
- const token = /* @__PURE__ */ Symbol("worker-lifecycle-bridge");
279
- activeBridge = { token, bridge };
280
- return () => {
281
- if (activeBridge?.token === token) activeBridge = void 0;
282
- };
283
- }
284
- function currentWorkerLifecycleBridge() {
285
- return activeBridge?.bridge;
286
- }
287
-
288
327
  export {
289
- syncInheritedWorkerModels,
290
328
  registerWorkerLifecycleBridge,
291
- currentWorkerLifecycleBridge
329
+ currentWorkerLifecycleBridge,
330
+ syncInheritedWorkerModels
292
331
  };
@@ -0,0 +1,210 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+
3
+ // src/core/node-ownership-lock.ts
4
+ import * as fs from "node:fs";
5
+ import * as os from "node:os";
6
+ import * as path from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+ import { randomUUID } from "node:crypto";
9
+ var REBOOT_CLOCK_SKEW_MARGIN_MS = 6e4;
10
+ var PROCESS_IDENTITY_PROBE_TIMEOUT_MS = 500;
11
+ var MUTEX_PROBE_THROTTLE_MS = 250;
12
+ var NODE_OR_PIE_IDENTITY_RE = /(?:^|[\s/\\"'=])(?:node(?:\.exe)?|pie(?:\.exe|\.cmd)?|bun(?:\.exe)?|deno(?:\.exe)?|tsx(?:\.cmd)?|service-launcher(?:\.exe)?|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh(?:\.exe)?|cli\.(?:js|ts|mjs|cjs))(?:$|[\s/\\"'=])/i;
13
+ function pidDefinitelyDead(pid) {
14
+ if (!Number.isInteger(pid) || pid <= 0) return false;
15
+ try {
16
+ process.kill(pid, 0);
17
+ return false;
18
+ } catch (error) {
19
+ return error.code === "ESRCH";
20
+ }
21
+ }
22
+ function isPreRebootTimestamp(timestampMs, nowMs = Date.now(), uptimeSec = os.uptime()) {
23
+ if (typeof timestampMs !== "number" || !Number.isFinite(timestampMs) || timestampMs <= 0) return false;
24
+ if (!Number.isFinite(nowMs) || !Number.isFinite(uptimeSec) || uptimeSec < 0) return false;
25
+ const hostBootMs = nowMs - Math.floor(uptimeSec * 1e3);
26
+ return timestampMs < hostBootMs - REBOOT_CLOCK_SKEW_MARGIN_MS;
27
+ }
28
+ function parseWindowsTasklistImageName(stdout, expectedPid) {
29
+ if (!Number.isInteger(expectedPid) || expectedPid <= 0) return void 0;
30
+ for (const rawLine of stdout.split(/\r?\n/)) {
31
+ const line = rawLine.trim();
32
+ if (!line) continue;
33
+ const match = /^"([^"]+)"\s*,\s*"(\d+)"\s*,/.exec(line);
34
+ if (!match) return void 0;
35
+ const imageName = match[1].trim();
36
+ const rowPid = Number.parseInt(match[2], 10);
37
+ if (!imageName || rowPid !== expectedPid) return void 0;
38
+ return imageName;
39
+ }
40
+ return void 0;
41
+ }
42
+ function parsePosixPsIdentity(stdout, expectedPid) {
43
+ if (!Number.isInteger(expectedPid) || expectedPid <= 0) return void 0;
44
+ for (const rawLine of stdout.split(/\r?\n/)) {
45
+ const line = rawLine.trim();
46
+ if (!line) continue;
47
+ const match = /^(\d+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
48
+ if (!match) return void 0;
49
+ const rowPid = Number.parseInt(match[1], 10);
50
+ const comm = match[2].trim();
51
+ const args = match[3]?.trim() ?? "";
52
+ if (!comm || rowPid !== expectedPid) return void 0;
53
+ return args ? `${comm} ${args}` : comm;
54
+ }
55
+ return void 0;
56
+ }
57
+ function probeProcessIdentity(pid) {
58
+ if (!Number.isInteger(pid) || pid <= 0) return void 0;
59
+ try {
60
+ if (process.platform === "win32") {
61
+ const out2 = execFileSync(
62
+ "tasklist",
63
+ ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"],
64
+ { encoding: "utf8", timeout: PROCESS_IDENTITY_PROBE_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
65
+ );
66
+ return parseWindowsTasklistImageName(out2, pid);
67
+ }
68
+ const out = execFileSync(
69
+ "ps",
70
+ ["-p", String(pid), "-o", "pid=,comm=,args="],
71
+ { encoding: "utf8", timeout: PROCESS_IDENTITY_PROBE_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] }
72
+ );
73
+ return parsePosixPsIdentity(out, pid);
74
+ } catch {
75
+ return void 0;
76
+ }
77
+ }
78
+ function isPositivelyDeadHolder(pid, timestampMs, options) {
79
+ if (!Number.isInteger(pid) || pid <= 0) return false;
80
+ const checkDead = options?.isDead ?? pidDefinitelyDead;
81
+ if (checkDead(pid)) return true;
82
+ const selfPid = options?.selfPid ?? process.pid;
83
+ if (pid === selfPid) return false;
84
+ if (!isPreRebootTimestamp(timestampMs, options?.nowMs, options?.uptimeSec)) return false;
85
+ const identity = (options?.probeIdentity ?? probeProcessIdentity)(pid);
86
+ if (identity === void 0 || identity.trim().length === 0) return false;
87
+ return !NODE_OR_PIE_IDENTITY_RE.test(identity);
88
+ }
89
+ function withOwnershipMutex(lock, fn) {
90
+ fs.mkdirSync(path.dirname(lock), { recursive: true, mode: 448 });
91
+ const token = randomUUID();
92
+ const candidate = `${lock}.acquire.${token}`;
93
+ fs.mkdirSync(candidate, { mode: 448 });
94
+ try {
95
+ fs.writeFileSync(path.join(candidate, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, at: Date.now() }), { flag: "wx", mode: 384 });
96
+ const deadline = process.hrtime.bigint() + 2000000000n;
97
+ const lastNegativeProbeAt = /* @__PURE__ */ new Map();
98
+ for (; ; ) {
99
+ try {
100
+ fs.renameSync(candidate, lock);
101
+ break;
102
+ } catch (error) {
103
+ if (!["EEXIST", "ENOTEMPTY", "EPERM", "ENOTDIR"].includes(error.code ?? "")) throw error;
104
+ if (process.hrtime.bigint() >= deadline) throw new Error(`Ownership mutex contention: ${lock}`);
105
+ try {
106
+ const entries = fs.readdirSync(lock);
107
+ if (entries.every((name) => {
108
+ if (!/^held\.[a-f0-9-]+$/.test(name)) return false;
109
+ const value = JSON.parse(fs.readFileSync(path.join(lock, name), "utf8"));
110
+ if (value?.version !== 1 || !Number.isInteger(value.pid) || value.pid <= 0) return false;
111
+ if (pidDefinitelyDead(value.pid)) return true;
112
+ const heldAt = typeof value.at === "number" ? value.at : void 0;
113
+ const cacheKey = `${name}:${value.pid}`;
114
+ const now = Date.now();
115
+ const lastProbed = lastNegativeProbeAt.get(cacheKey);
116
+ if (lastProbed !== void 0 && now - lastProbed < MUTEX_PROBE_THROTTLE_MS) return false;
117
+ const dead = isPositivelyDeadHolder(value.pid, heldAt);
118
+ if (!dead) lastNegativeProbeAt.set(cacheKey, now);
119
+ return dead;
120
+ })) {
121
+ for (const name of entries) {
122
+ try {
123
+ fs.unlinkSync(path.join(lock, name));
124
+ } catch (e) {
125
+ if (e.code !== "ENOENT") throw e;
126
+ }
127
+ }
128
+ fs.rmdirSync(lock);
129
+ }
130
+ } catch {
131
+ }
132
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3);
133
+ }
134
+ }
135
+ try {
136
+ return fn();
137
+ } finally {
138
+ try {
139
+ fs.unlinkSync(path.join(lock, `held.${token}`));
140
+ } catch {
141
+ }
142
+ try {
143
+ fs.rmdirSync(lock);
144
+ } catch {
145
+ }
146
+ }
147
+ } finally {
148
+ fs.rmSync(candidate, { recursive: true, force: true });
149
+ }
150
+ }
151
+ function readOwnership(target, valid) {
152
+ let raw;
153
+ try {
154
+ raw = fs.readFileSync(target, "utf8");
155
+ } catch (error) {
156
+ if (error.code === "ENOENT") return void 0;
157
+ throw error;
158
+ }
159
+ const value = JSON.parse(raw);
160
+ if (!value || !Number.isInteger(value.pid) || value.pid <= 0 || typeof value.holder !== "string" || !Number.isFinite(value.heartbeatAt) || value.generation !== void 0 && typeof value.generation !== "string" || !valid(value)) {
161
+ throw new Error(`Invalid ownership record: ${target}`);
162
+ }
163
+ return value;
164
+ }
165
+ function claimOwnership(target, mine, valid) {
166
+ const mutex = `${target}.mutex`;
167
+ const generation = randomUUID();
168
+ const publish = () => {
169
+ const tmp = `${target}.${randomUUID()}.tmp`;
170
+ try {
171
+ fs.writeFileSync(tmp, `${JSON.stringify({ ...mine, generation, heartbeatAt: Date.now() })}
172
+ `, { flag: "wx", mode: 384 });
173
+ fs.renameSync(tmp, target);
174
+ } finally {
175
+ fs.rmSync(tmp, { force: true });
176
+ }
177
+ };
178
+ const holder = withOwnershipMutex(mutex, () => {
179
+ const current = readOwnership(target, valid);
180
+ if (current && !isPositivelyDeadHolder(current.pid, current.heartbeatAt)) return current;
181
+ publish();
182
+ return void 0;
183
+ });
184
+ if (holder) return { holder };
185
+ let released = false;
186
+ return { handle: {
187
+ heartbeat: () => {
188
+ if (released) return false;
189
+ return withOwnershipMutex(mutex, () => {
190
+ if (readOwnership(target, valid)?.generation !== generation) return false;
191
+ publish();
192
+ return true;
193
+ });
194
+ },
195
+ release: () => {
196
+ if (released) return;
197
+ released = true;
198
+ withOwnershipMutex(mutex, () => {
199
+ if (readOwnership(target, valid)?.generation === generation) fs.unlinkSync(target);
200
+ });
201
+ }
202
+ } };
203
+ }
204
+
205
+ export {
206
+ isPositivelyDeadHolder,
207
+ withOwnershipMutex,
208
+ readOwnership,
209
+ claimOwnership
210
+ };
@@ -1,9 +1,9 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  claimOwnership,
4
- pidDefinitelyDead,
4
+ isPositivelyDeadHolder,
5
5
  readOwnership
6
- } from "./chunk-ZPJ3BNQB.js";
6
+ } from "./chunk-Q4NJEPIZ.js";
7
7
  import {
8
8
  getSessionsDir
9
9
  } from "./chunk-CBDQJMUI.js";
@@ -25,7 +25,7 @@ function unavailable(sessionId) {
25
25
  function sessionOwnerAlive(sessionId, _now = Date.now()) {
26
26
  try {
27
27
  const info = readOwnership(lockPath(sessionId), (v) => v.sessionId === sessionId);
28
- return info && !pidDefinitelyDead(info.pid) ? info : void 0;
28
+ return info && !isPositivelyDeadHolder(info.pid, info.heartbeatAt) ? info : void 0;
29
29
  } catch {
30
30
  return unavailable(sessionId);
31
31
  }
@@ -2,7 +2,7 @@ import { createRequire as __createRequire } from "node:module"; const require =
2
2
  import {
3
3
  createReadFileUnderstandingHandler,
4
4
  modalityForReadFileUnderstandingKind
5
- } from "./chunk-HK3FHIAH.js";
5
+ } from "./chunk-KW46ND3S.js";
6
6
  import {
7
7
  readImageFormat
8
8
  } from "./chunk-F7EBZTZO.js";