@cydm/pie 4.10.2 → 4.12.0

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 (38) 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 +9128 -7189
  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 +542 -52
  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-KWK7KTSZ.js → chunk-322WLBDY.js} +1 -1
  15. package/dist/chunks/{chunk-OU33ROFD.js → chunk-3GG342QY.js} +78 -78
  16. package/dist/chunks/{chunk-BB7ETSJK.js → chunk-6U6UGM4C.js} +119 -3
  17. package/dist/chunks/{chunk-ZPJ3BNQB.js → chunk-BSITHT43.js} +1 -0
  18. package/dist/chunks/{chunk-IZKHSUNQ.js → chunk-CAPBTMLI.js} +18 -1
  19. package/dist/chunks/{chunk-FC5AN5QP.js → chunk-IZ4DYCJ7.js} +268 -107
  20. package/dist/chunks/{chunk-HK3FHIAH.js → chunk-KW46ND3S.js} +1999 -767
  21. package/dist/chunks/{chunk-SW2E33UL.js → chunk-LMDWWT43.js} +123 -4
  22. package/dist/chunks/chunk-OGGL6LUN.js +331 -0
  23. package/dist/chunks/{chunk-BTUMBUDU.js → chunk-QSXBPTOA.js} +1 -1
  24. package/dist/chunks/{chunk-5QMS6RQC.js → chunk-SXBX2P5R.js} +160 -5
  25. package/dist/chunks/{chunk-7LICWWUE.js → chunk-W37NAT3N.js} +2 -2
  26. package/dist/chunks/chunk-WTBLV6F5.js +476 -0
  27. package/dist/chunks/{host-image-fallback-3TEMOQM5.js → host-image-fallback-NXY36VO2.js} +1 -1
  28. package/dist/chunks/{manager-cli-BXI4UFTJ.js → manager-cli-B6GIYTI7.js} +35 -13
  29. package/dist/chunks/{manager-upgrade-XPFXKO7A.js → manager-upgrade-WHER3WTJ.js} +284 -109
  30. package/dist/chunks/memory-git-C3S276QJ.js +19 -0
  31. package/dist/chunks/{model-registry-QKJ3YVDS.js → model-registry-QNEPISBJ.js} +11 -3
  32. package/dist/chunks/{read-file-understanding-N2ZZQLTZ.js → read-file-understanding-ZCBNCQHG.js} +3 -3
  33. package/dist/chunks/{src-F5N6O2HR.js → src-7CU7OTQS.js} +36 -36
  34. package/dist/chunks/{src-3PSR2AAX.js → src-7MZZJVOG.js} +1 -1
  35. package/dist/cli.js +750 -516
  36. package/package.json +2 -2
  37. package/dist/chunks/chunk-6WKBQZWM.js +0 -19
  38. package/dist/chunks/chunk-XMTRKMBG.js +0 -386
@@ -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) {
@@ -0,0 +1,331 @@
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
+ }
22
+
23
+ // src/core/worker-models-sync.ts
24
+ import * as fs from "node:fs";
25
+ import * as path from "node:path";
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
+ }
51
+ var INHERITED_HASH_FILENAME = ".models.inherited-sha256";
52
+ var SYNC_LOCK_FILENAME = ".models.sync.lock";
53
+ var LOCK_STALE_MS = 5e3;
54
+ var LOCK_MAX_ATTEMPTS = 12;
55
+ var LOCK_WAIT_MS = 10;
56
+ function sha256Utf8(text) {
57
+ return createHash("sha256").update(text, "utf8").digest("hex");
58
+ }
59
+ function isPlainObject(value) {
60
+ return typeof value === "object" && value !== null && !Array.isArray(value);
61
+ }
62
+ function stableJson(value) {
63
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
64
+ if (isPlainObject(value)) {
65
+ const keys = Object.keys(value).sort();
66
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableJson(value[k])}`).join(",")}}`;
67
+ }
68
+ return JSON.stringify(value);
69
+ }
70
+ function indexModelsByKey(rawModels) {
71
+ if (rawModels === void 0) return /* @__PURE__ */ new Map();
72
+ if (!Array.isArray(rawModels)) return null;
73
+ const map = /* @__PURE__ */ new Map();
74
+ for (const entry of rawModels) {
75
+ if (typeof entry === "string") {
76
+ map.set(`s:${entry}`, stableJson(entry));
77
+ } else if (isPlainObject(entry) && typeof entry.id === "string") {
78
+ map.set(`o:${entry.id}`, stableJson(entry));
79
+ } else {
80
+ return null;
81
+ }
82
+ }
83
+ return map;
84
+ }
85
+ function isLegacyUnmodifiedModelsSnapshot(workerDoc, globalDoc) {
86
+ if (!isPlainObject(workerDoc) || !isPlainObject(globalDoc)) return false;
87
+ for (const key of Object.keys(workerDoc)) {
88
+ if (key === "profiles" || key === "modelOverrides" || key === "remoteCatalogs") continue;
89
+ if (stableJson(workerDoc[key]) !== stableJson(globalDoc[key])) return false;
90
+ }
91
+ const workerProfiles = isPlainObject(workerDoc.profiles) ? workerDoc.profiles : {};
92
+ const globalProfiles = isPlainObject(globalDoc.profiles) ? globalDoc.profiles : {};
93
+ if (workerDoc.profiles !== void 0 && !isPlainObject(workerDoc.profiles)) return false;
94
+ for (const [provider, rawWorkerProfile] of Object.entries(workerProfiles)) {
95
+ const rawGlobalProfile = globalProfiles[provider];
96
+ if (!isPlainObject(rawWorkerProfile) || !isPlainObject(rawGlobalProfile)) return false;
97
+ const profileKeys = /* @__PURE__ */ new Set([...Object.keys(rawWorkerProfile), ...Object.keys(rawGlobalProfile)]);
98
+ for (const field of profileKeys) {
99
+ if (field === "models") continue;
100
+ if (stableJson(rawWorkerProfile[field]) !== stableJson(rawGlobalProfile[field])) return false;
101
+ }
102
+ const workerModels = indexModelsByKey(rawWorkerProfile.models);
103
+ const globalModels = indexModelsByKey(rawGlobalProfile.models);
104
+ if (!workerModels || !globalModels) return false;
105
+ for (const [modelKey, serialized] of workerModels) {
106
+ if (globalModels.get(modelKey) !== serialized) return false;
107
+ }
108
+ }
109
+ if (workerDoc.modelOverrides !== void 0) {
110
+ if (!isPlainObject(workerDoc.modelOverrides) || !isPlainObject(globalDoc.modelOverrides)) return false;
111
+ for (const [key, val] of Object.entries(workerDoc.modelOverrides)) {
112
+ if (stableJson(val) !== stableJson(globalDoc.modelOverrides[key])) return false;
113
+ }
114
+ }
115
+ if (workerDoc.remoteCatalogs !== void 0) {
116
+ if (!Array.isArray(workerDoc.remoteCatalogs) || !Array.isArray(globalDoc.remoteCatalogs)) return false;
117
+ const globalRemotes = new Set(globalDoc.remoteCatalogs.map(stableJson));
118
+ for (const remote of workerDoc.remoteCatalogs) {
119
+ if (!globalRemotes.has(stableJson(remote))) return false;
120
+ }
121
+ }
122
+ return true;
123
+ }
124
+ function writeAtomicFile(targetPath, content, mode = 384) {
125
+ const dir = path.dirname(targetPath);
126
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
127
+ const tmp = path.join(dir, `.${path.basename(targetPath)}-${process.pid}-${randomUUID()}.tmp`);
128
+ try {
129
+ const fd = fs.openSync(tmp, "wx", mode);
130
+ try {
131
+ fs.writeFileSync(fd, content, "utf8");
132
+ } finally {
133
+ fs.closeSync(fd);
134
+ }
135
+ fs.renameSync(tmp, targetPath);
136
+ } catch (error) {
137
+ try {
138
+ fs.rmSync(tmp, { force: true });
139
+ } catch {
140
+ }
141
+ throw error;
142
+ }
143
+ }
144
+ function isSymlinkIfExists(targetPath) {
145
+ try {
146
+ return fs.lstatSync(targetPath).isSymbolicLink();
147
+ } catch {
148
+ return false;
149
+ }
150
+ }
151
+ function isRegularFileIfExists(targetPath) {
152
+ try {
153
+ const st = fs.lstatSync(targetPath);
154
+ return !st.isSymbolicLink() && st.isFile();
155
+ } catch (error) {
156
+ return error?.code === "ENOENT";
157
+ }
158
+ }
159
+ function isPathSafeWithinRoot(rootDir, targetPath) {
160
+ try {
161
+ if (!fs.existsSync(rootDir) || isSymlinkIfExists(rootDir)) return false;
162
+ const absRoot = path.resolve(rootDir);
163
+ const absTarget = path.resolve(targetPath);
164
+ const rel = path.relative(absRoot, absTarget);
165
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return false;
166
+ const segments = rel.split(path.sep).filter(Boolean);
167
+ let cursor = absRoot;
168
+ let deepestExisting = absRoot;
169
+ for (const seg of segments) {
170
+ cursor = path.join(cursor, seg);
171
+ try {
172
+ const st = fs.lstatSync(cursor);
173
+ if (st.isSymbolicLink()) return false;
174
+ deepestExisting = cursor;
175
+ } catch (error) {
176
+ if (error?.code === "ENOENT") break;
177
+ return false;
178
+ }
179
+ }
180
+ const canonicalRoot = fs.realpathSync(absRoot);
181
+ const canonicalDeepest = fs.realpathSync(deepestExisting);
182
+ const canonicalRel = path.relative(canonicalRoot, canonicalDeepest);
183
+ return canonicalRel === "" || !canonicalRel.startsWith("..") && !path.isAbsolute(canonicalRel);
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+ var SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
189
+ function sleepSyncMs(ms) {
190
+ try {
191
+ Atomics.wait(SLEEP_BUFFER, 0, 0, ms);
192
+ } catch {
193
+ const end = Date.now() + ms;
194
+ while (Date.now() < end) {
195
+ }
196
+ }
197
+ }
198
+ function isPidAlive(pid) {
199
+ if (!Number.isInteger(pid) || pid <= 0) return false;
200
+ try {
201
+ process.kill(pid, 0);
202
+ return true;
203
+ } catch (error) {
204
+ return error?.code === "EPERM";
205
+ }
206
+ }
207
+ function tryReclaimStaleLock(lockPath) {
208
+ try {
209
+ const st = fs.lstatSync(lockPath);
210
+ if (st.isSymbolicLink() || !st.isFile()) return false;
211
+ const ageMs = Date.now() - st.mtimeMs;
212
+ let ownerDead = false;
213
+ try {
214
+ const pid = Number.parseInt(fs.readFileSync(lockPath, "utf8").trim(), 10);
215
+ if (Number.isInteger(pid) && pid > 0 && !isPidAlive(pid)) ownerDead = true;
216
+ } catch {
217
+ }
218
+ if (ownerDead || ageMs > LOCK_STALE_MS) {
219
+ fs.unlinkSync(lockPath);
220
+ return true;
221
+ }
222
+ } catch (error) {
223
+ if (error?.code === "ENOENT") return true;
224
+ }
225
+ return false;
226
+ }
227
+ function acquireSyncLock(lockPath) {
228
+ if (isSymlinkIfExists(lockPath)) return void 0;
229
+ for (let attempt = 0; attempt < LOCK_MAX_ATTEMPTS; attempt++) {
230
+ try {
231
+ const fd = fs.openSync(lockPath, "wx", 384);
232
+ try {
233
+ fs.writeFileSync(fd, `${process.pid}
234
+ `, "utf8");
235
+ } finally {
236
+ fs.closeSync(fd);
237
+ }
238
+ return () => {
239
+ try {
240
+ fs.unlinkSync(lockPath);
241
+ } catch {
242
+ }
243
+ };
244
+ } catch (error) {
245
+ if (error?.code !== "EEXIST") return void 0;
246
+ if (tryReclaimStaleLock(lockPath)) continue;
247
+ sleepSyncMs(LOCK_WAIT_MS);
248
+ }
249
+ }
250
+ return void 0;
251
+ }
252
+ function syncInheritedWorkerModels(workerModelsPath, globalModelsPath, opts = {}) {
253
+ let releaseLock;
254
+ try {
255
+ if (!workerModelsPath || !globalModelsPath) return false;
256
+ if (path.resolve(workerModelsPath) === path.resolve(globalModelsPath)) return false;
257
+ if (opts.allowedSrcRoot && !isPathSafeWithinRoot(opts.allowedSrcRoot, globalModelsPath)) return false;
258
+ if (opts.allowedDestRoot && !isPathSafeWithinRoot(opts.allowedDestRoot, workerModelsPath)) return false;
259
+ if (!fs.existsSync(globalModelsPath) || !isRegularFileIfExists(globalModelsPath)) return false;
260
+ if (isSymlinkIfExists(path.dirname(globalModelsPath))) return false;
261
+ const workerDir = path.dirname(workerModelsPath);
262
+ if (isSymlinkIfExists(workerDir) || !isRegularFileIfExists(workerModelsPath)) return false;
263
+ const sidecarPath = path.join(workerDir, INHERITED_HASH_FILENAME);
264
+ const lockPath = path.join(workerDir, SYNC_LOCK_FILENAME);
265
+ if (!isRegularFileIfExists(sidecarPath) || isSymlinkIfExists(lockPath)) return false;
266
+ fs.mkdirSync(workerDir, { recursive: true, mode: 448 });
267
+ if (opts.allowedDestRoot && !isPathSafeWithinRoot(opts.allowedDestRoot, workerModelsPath)) return false;
268
+ releaseLock = acquireSyncLock(lockPath);
269
+ if (!releaseLock) return false;
270
+ if (!fs.existsSync(globalModelsPath) || !isRegularFileIfExists(globalModelsPath)) return false;
271
+ if (!isRegularFileIfExists(workerModelsPath) || !isRegularFileIfExists(sidecarPath)) return false;
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
+ }
282
+ const globalHash = sha256Utf8(globalText);
283
+ if (!fs.existsSync(workerModelsPath)) {
284
+ writeAtomicFile(workerModelsPath, globalText, 384);
285
+ writeAtomicFile(sidecarPath, `${globalHash}
286
+ `, 384);
287
+ return true;
288
+ }
289
+ const workerText = fs.readFileSync(workerModelsPath, "utf8");
290
+ const workerHash = sha256Utf8(workerText);
291
+ if (workerHash === globalHash) {
292
+ const existingSidecar = fs.existsSync(sidecarPath) ? fs.readFileSync(sidecarPath, "utf8").trim() : void 0;
293
+ if (existingSidecar !== globalHash) {
294
+ try {
295
+ writeAtomicFile(sidecarPath, `${globalHash}
296
+ `, 384);
297
+ } catch {
298
+ }
299
+ }
300
+ return false;
301
+ }
302
+ if (fs.existsSync(sidecarPath)) {
303
+ const recorded = fs.readFileSync(sidecarPath, "utf8").trim();
304
+ if (recorded !== workerHash) {
305
+ return false;
306
+ }
307
+ writeAtomicFile(workerModelsPath, globalText, 384);
308
+ writeAtomicFile(sidecarPath, `${globalHash}
309
+ `, 384);
310
+ return true;
311
+ }
312
+ const workerParsed = JSON.parse(workerText);
313
+ if (!isLegacyUnmodifiedModelsSnapshot(workerParsed, globalParsed)) {
314
+ return false;
315
+ }
316
+ writeAtomicFile(workerModelsPath, globalText, 384);
317
+ writeAtomicFile(sidecarPath, `${globalHash}
318
+ `, 384);
319
+ return true;
320
+ } catch {
321
+ return false;
322
+ } finally {
323
+ releaseLock?.();
324
+ }
325
+ }
326
+
327
+ export {
328
+ registerWorkerLifecycleBridge,
329
+ currentWorkerLifecycleBridge,
330
+ syncInheritedWorkerModels
331
+ };
@@ -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";