@cydm/pie 4.10.2 → 4.11.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.
@@ -3,7 +3,7 @@ import {
3
3
  distillWorkerLogPath,
4
4
  readDistillWorkerLog,
5
5
  spawnDistillWorker
6
- } from "../../../chunks/chunk-XMTRKMBG.js";
6
+ } from "../../../chunks/chunk-L7XXKNZW.js";
7
7
  import {
8
8
  DEFAULT_MEMORY_INJECTION_BUDGET,
9
9
  MemoryStore,
@@ -3,15 +3,16 @@ import {
3
3
  liveSessionHolder
4
4
  } from "../../../chunks/chunk-KWK7KTSZ.js";
5
5
  import {
6
- registerWorkerLifecycleBridge
7
- } from "../../../chunks/chunk-6WKBQZWM.js";
6
+ registerWorkerLifecycleBridge,
7
+ syncInheritedWorkerModels
8
+ } from "../../../chunks/chunk-EWPPGYBU.js";
8
9
  import {
9
10
  readProcessCommandLine
10
11
  } from "../../../chunks/chunk-7RJXKN7N.js";
11
12
  import "../../../chunks/chunk-ZPJ3BNQB.js";
12
13
  import {
13
14
  loadResolvedModelsConfig
14
- } from "../../../chunks/chunk-FC5AN5QP.js";
15
+ } from "../../../chunks/chunk-B5GKDXVG.js";
15
16
  import "../../../chunks/chunk-CBDQJMUI.js";
16
17
  import "../../../chunks/chunk-G2K4GY6N.js";
17
18
  import {
@@ -435,7 +436,7 @@ async function waitForWorkerIpcReady(opts) {
435
436
  if (!isPidAlive(opts.pid)) return { exitedEarly: true };
436
437
  const remaining = deadline - Date.now();
437
438
  if (remaining <= 0) break;
438
- await new Promise((resolve3) => setTimeout(resolve3, Math.min(pollMs, remaining)));
439
+ await new Promise((resolve4) => setTimeout(resolve4, Math.min(pollMs, remaining)));
439
440
  }
440
441
  return { peer: readLiveWorkerPeer(opts.ipcRoot, opts.sessionId, opts.pid), exitedEarly: !isPidAlive(opts.pid) };
441
442
  }
@@ -463,7 +464,13 @@ async function buildSpawnReceipt(opts) {
463
464
  return { modelLabel, text };
464
465
  }
465
466
  function inheritWorkerConfigFiles(pieDir, parentConfigDir) {
466
- for (const file of ["models.json", "config.json", "auth.json", "settings.json"]) {
467
+ const relToParent = path3.relative(path3.resolve(parentConfigDir), path3.resolve(pieDir));
468
+ const allowedDestRoot = relToParent && !relToParent.startsWith("..") && !path3.isAbsolute(relToParent) ? parentConfigDir : path3.dirname(pieDir);
469
+ syncInheritedWorkerModels(path3.join(pieDir, "models.json"), path3.join(parentConfigDir, "models.json"), {
470
+ allowedDestRoot,
471
+ allowedSrcRoot: parentConfigDir
472
+ });
473
+ for (const file of ["config.json", "auth.json", "settings.json"]) {
467
474
  const dst = path3.join(pieDir, file);
468
475
  const src = path3.join(parentConfigDir, file);
469
476
  if (!fs3.existsSync(dst) && fs3.existsSync(src)) {
@@ -1365,6 +1365,8 @@ var ModelRegistry = class {
1365
1365
  modelOrder = [];
1366
1366
  modelOverrides = {};
1367
1367
  extensionOAuthProviders = /* @__PURE__ */ new Map();
1368
+ runtimeRegistrations = [];
1369
+ runtimeReloadEpoch = 0;
1368
1370
  usingExternalProviders = false;
1369
1371
  localProfileIds = /* @__PURE__ */ new Set();
1370
1372
  remoteCredentialEnvByProvider = /* @__PURE__ */ new Map();
@@ -1981,29 +1983,9 @@ var ModelRegistry = class {
1981
1983
  if (remoteEnv) return typeof process !== "undefined" ? process.env?.[remoteEnv] : void 0;
1982
1984
  return this.authStorage.getApiKey(provider);
1983
1985
  }
1984
- /**
1985
- * Register a provider at runtime (extension API). Not persisted to
1986
- * models.json: runtime registrations live for the process unless the
1987
- * extension registers them again. Returns an unregister handle that
1988
- * restores the provider's previous state (models, order, env binding).
1989
- *
1990
- * When the provider already exists (local profile or remote catalog),
1991
- * models are merged by id: registered models upsert over existing entries
1992
- * with the same id; existing entries not named in `config.models` survive.
1993
- * baseUrl/api/headers patch every model of that provider (existing and
1994
- * new) when provided.
1995
- */
1996
- registerProvider(provider, config) {
1997
- validateExtensionProviderConfig(provider, config);
1998
- const previousModels = this.models.get(provider) ? new Map(this.models.get(provider)) : void 0;
1999
- const previousOrder = [...this.modelOrder];
2000
- const previousEnvVar = this.authStorage.getProviderEnvVar(provider);
2001
- if (config.apiKey) {
2002
- this.authStorage.setRuntimeApiKey(provider, config.apiKey);
2003
- }
2004
- if (config.apiKeyEnv) {
2005
- this.authStorage.setProviderEnvVar(provider, config.apiKeyEnv);
2006
- }
1986
+ applyRuntimeRegistration(provider, config) {
1987
+ if (config.apiKey) this.authStorage.setRuntimeApiKey(provider, config.apiKey);
1988
+ if (config.apiKeyEnv) this.authStorage.setProviderEnvVar(provider, config.apiKeyEnv);
2007
1989
  const existing = this.models.get(provider);
2008
1990
  if (existing && (config.baseUrl || config.api || config.headers || config.transport)) {
2009
1991
  for (const model of existing.values()) {
@@ -2043,17 +2025,32 @@ var ModelRegistry = class {
2043
2025
  fileCapabilities: customModel.fileCapabilities || baseModel?.fileCapabilities
2044
2026
  });
2045
2027
  }
2046
- this.applyModelOverrides();
2047
2028
  this.usingExternalProviders = true;
2048
- const registeredOAuth = config.oauth;
2049
- if (registeredOAuth) this.extensionOAuthProviders.set(provider, registeredOAuth);
2029
+ if (config.oauth) this.extensionOAuthProviders.set(provider, config.oauth);
2030
+ }
2031
+ /** Register a runtime provider (extension API; merged by id with existing providers) and return an unregister handle. */
2032
+ registerProvider(provider, config) {
2033
+ validateExtensionProviderConfig(provider, config);
2034
+ const previousModels = this.models.get(provider) ? new Map(this.models.get(provider)) : void 0;
2035
+ const previousOrder = [...this.modelOrder];
2036
+ const previousEnvVar = this.authStorage.getProviderEnvVar(provider);
2037
+ const regId = Symbol(provider);
2038
+ const regEpoch = this.runtimeReloadEpoch;
2039
+ this.runtimeRegistrations.push({ id: regId, provider, config });
2040
+ this.applyRuntimeRegistration(provider, config);
2041
+ this.applyModelOverrides();
2050
2042
  return () => {
2043
+ this.runtimeRegistrations = this.runtimeRegistrations.filter((r) => r.id !== regId);
2044
+ this.authStorage.setRuntimeApiKey(provider, void 0);
2045
+ this.authStorage.setProviderEnvVar(provider, previousEnvVar);
2046
+ if (config.oauth) this.extensionOAuthProviders.delete(provider);
2047
+ if (this.runtimeReloadEpoch !== regEpoch) {
2048
+ this.reloadFromDisk();
2049
+ return;
2050
+ }
2051
2051
  if (previousModels) this.models.set(provider, previousModels);
2052
2052
  else this.models.delete(provider);
2053
2053
  this.modelOrder = previousOrder;
2054
- this.authStorage.setRuntimeApiKey(provider, void 0);
2055
- this.authStorage.setProviderEnvVar(provider, previousEnvVar);
2056
- if (registeredOAuth) this.extensionOAuthProviders.delete(provider);
2057
2054
  this.applyModelOverrides();
2058
2055
  };
2059
2056
  }
@@ -2061,21 +2058,27 @@ var ModelRegistry = class {
2061
2058
  getExtensionOAuth(provider) {
2062
2059
  return this.extensionOAuthProviders.get(provider);
2063
2060
  }
2064
- /**
2065
- * Restore persisted OAuth credentials now that extensions have registered
2066
- * their providers: refresh expired tokens when the extension declares
2067
- * refreshToken, and drop the runtime binding when a token cannot be
2068
- * recovered (getApiKey then reports the provider as unauthenticated).
2069
- * Never throws; returns per-provider outcomes for the host to surface.
2070
- */
2061
+ /** Reload models.json + cached remote catalogs, replaying active runtime provider registrations. */
2062
+ reloadFromDisk() {
2063
+ const prevModels = new Map([...this.models].map(([p, m]) => [p, new Map(m)]));
2064
+ const prev = [this.modelOrder.slice(), { ...this.modelOverrides }, this.configDefaults, this.usingExternalProviders, new Set(this.localProfileIds), new Map(this.remoteCredentialEnvByProvider), new Map(this.remoteCatalogByProvider), new Map(this.remoteCredentialFingerprintByCatalog), this.loadError];
2065
+ this.load();
2066
+ if (this.loadError) {
2067
+ this.models = prevModels;
2068
+ [this.modelOrder, this.modelOverrides, this.configDefaults, this.usingExternalProviders, this.localProfileIds, this.remoteCredentialEnvByProvider, this.remoteCatalogByProvider, this.remoteCredentialFingerprintByCatalog, this.loadError] = prev;
2069
+ return false;
2070
+ }
2071
+ for (const reg of this.runtimeRegistrations) this.applyRuntimeRegistration(reg.provider, reg.config);
2072
+ this.applyModelOverrides();
2073
+ this.runtimeReloadEpoch++;
2074
+ return true;
2075
+ }
2071
2076
  async restorePersistedOAuth() {
2072
2077
  const authStorage = this.authStorage;
2073
2078
  const results = [];
2074
2079
  for (const provider of authStorage.getOAuthProviderNames()) {
2075
2080
  const credentials = authStorage.getOAuthCredentials(provider);
2076
- if (!credentials?.access) continue;
2077
- const expired = credentials.expires !== void 0 && credentials.expires <= Date.now() + OAUTH_RESTORE_LEEWAY_MS;
2078
- if (!expired) continue;
2081
+ if (!credentials?.access || credentials.expires !== void 0 && credentials.expires > Date.now() + OAUTH_RESTORE_LEEWAY_MS) continue;
2079
2082
  const oauth = this.extensionOAuthProviders.get(provider);
2080
2083
  if (!oauth?.refreshToken || !credentials.refresh) {
2081
2084
  authStorage.setRuntimeApiKey(provider, void 0);
@@ -2083,15 +2086,7 @@ var ModelRegistry = class {
2083
2086
  continue;
2084
2087
  }
2085
2088
  try {
2086
- const next = await withTimeout(
2087
- oauth.refreshToken({
2088
- access: credentials.access,
2089
- refresh: credentials.refresh,
2090
- expires: credentials.expires
2091
- }),
2092
- OAUTH_REFRESH_TIMEOUT_MS,
2093
- `${provider} refreshToken timed out after ${OAUTH_REFRESH_TIMEOUT_MS}ms`
2094
- );
2089
+ const next = await withTimeout(oauth.refreshToken({ access: credentials.access, refresh: credentials.refresh, expires: credentials.expires }), OAUTH_REFRESH_TIMEOUT_MS, `${provider} refreshToken timed out after ${OAUTH_REFRESH_TIMEOUT_MS}ms`);
2095
2090
  const merged = { ...credentials, ...next };
2096
2091
  authStorage.setOAuthCredentials(provider, merged);
2097
2092
  authStorage.setRuntimeApiKey(provider, merged.access);
@@ -0,0 +1,292 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+
3
+ // src/core/worker-models-sync.ts
4
+ import * as fs from "node:fs";
5
+ import * as path from "node:path";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ var INHERITED_HASH_FILENAME = ".models.inherited-sha256";
8
+ var SYNC_LOCK_FILENAME = ".models.sync.lock";
9
+ var LOCK_STALE_MS = 5e3;
10
+ var LOCK_MAX_ATTEMPTS = 12;
11
+ var LOCK_WAIT_MS = 10;
12
+ function sha256Utf8(text) {
13
+ return createHash("sha256").update(text, "utf8").digest("hex");
14
+ }
15
+ function isPlainObject(value) {
16
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17
+ }
18
+ function stableJson(value) {
19
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
20
+ if (isPlainObject(value)) {
21
+ const keys = Object.keys(value).sort();
22
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableJson(value[k])}`).join(",")}}`;
23
+ }
24
+ return JSON.stringify(value);
25
+ }
26
+ function indexModelsByKey(rawModels) {
27
+ if (rawModels === void 0) return /* @__PURE__ */ new Map();
28
+ if (!Array.isArray(rawModels)) return null;
29
+ const map = /* @__PURE__ */ new Map();
30
+ for (const entry of rawModels) {
31
+ if (typeof entry === "string") {
32
+ map.set(`s:${entry}`, stableJson(entry));
33
+ } else if (isPlainObject(entry) && typeof entry.id === "string") {
34
+ map.set(`o:${entry.id}`, stableJson(entry));
35
+ } else {
36
+ return null;
37
+ }
38
+ }
39
+ return map;
40
+ }
41
+ function isLegacyUnmodifiedModelsSnapshot(workerDoc, globalDoc) {
42
+ if (!isPlainObject(workerDoc) || !isPlainObject(globalDoc)) return false;
43
+ for (const key of Object.keys(workerDoc)) {
44
+ if (key === "profiles" || key === "modelOverrides" || key === "remoteCatalogs") continue;
45
+ if (stableJson(workerDoc[key]) !== stableJson(globalDoc[key])) return false;
46
+ }
47
+ const workerProfiles = isPlainObject(workerDoc.profiles) ? workerDoc.profiles : {};
48
+ const globalProfiles = isPlainObject(globalDoc.profiles) ? globalDoc.profiles : {};
49
+ if (workerDoc.profiles !== void 0 && !isPlainObject(workerDoc.profiles)) return false;
50
+ for (const [provider, rawWorkerProfile] of Object.entries(workerProfiles)) {
51
+ const rawGlobalProfile = globalProfiles[provider];
52
+ if (!isPlainObject(rawWorkerProfile) || !isPlainObject(rawGlobalProfile)) return false;
53
+ const profileKeys = /* @__PURE__ */ new Set([...Object.keys(rawWorkerProfile), ...Object.keys(rawGlobalProfile)]);
54
+ for (const field of profileKeys) {
55
+ if (field === "models") continue;
56
+ if (stableJson(rawWorkerProfile[field]) !== stableJson(rawGlobalProfile[field])) return false;
57
+ }
58
+ const workerModels = indexModelsByKey(rawWorkerProfile.models);
59
+ const globalModels = indexModelsByKey(rawGlobalProfile.models);
60
+ if (!workerModels || !globalModels) return false;
61
+ for (const [modelKey, serialized] of workerModels) {
62
+ if (globalModels.get(modelKey) !== serialized) return false;
63
+ }
64
+ }
65
+ if (workerDoc.modelOverrides !== void 0) {
66
+ if (!isPlainObject(workerDoc.modelOverrides) || !isPlainObject(globalDoc.modelOverrides)) return false;
67
+ for (const [key, val] of Object.entries(workerDoc.modelOverrides)) {
68
+ if (stableJson(val) !== stableJson(globalDoc.modelOverrides[key])) return false;
69
+ }
70
+ }
71
+ if (workerDoc.remoteCatalogs !== void 0) {
72
+ if (!Array.isArray(workerDoc.remoteCatalogs) || !Array.isArray(globalDoc.remoteCatalogs)) return false;
73
+ const globalRemotes = new Set(globalDoc.remoteCatalogs.map(stableJson));
74
+ for (const remote of workerDoc.remoteCatalogs) {
75
+ if (!globalRemotes.has(stableJson(remote))) return false;
76
+ }
77
+ }
78
+ return true;
79
+ }
80
+ function writeAtomicFile(targetPath, content, mode = 384) {
81
+ const dir = path.dirname(targetPath);
82
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
83
+ const tmp = path.join(dir, `.${path.basename(targetPath)}-${process.pid}-${randomUUID()}.tmp`);
84
+ try {
85
+ const fd = fs.openSync(tmp, "wx", mode);
86
+ try {
87
+ fs.writeFileSync(fd, content, "utf8");
88
+ } finally {
89
+ fs.closeSync(fd);
90
+ }
91
+ fs.renameSync(tmp, targetPath);
92
+ } catch (error) {
93
+ try {
94
+ fs.rmSync(tmp, { force: true });
95
+ } catch {
96
+ }
97
+ throw error;
98
+ }
99
+ }
100
+ function isSymlinkIfExists(targetPath) {
101
+ try {
102
+ return fs.lstatSync(targetPath).isSymbolicLink();
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+ function isRegularFileIfExists(targetPath) {
108
+ try {
109
+ const st = fs.lstatSync(targetPath);
110
+ return !st.isSymbolicLink() && st.isFile();
111
+ } catch (error) {
112
+ return error?.code === "ENOENT";
113
+ }
114
+ }
115
+ function isPathSafeWithinRoot(rootDir, targetPath) {
116
+ try {
117
+ if (!fs.existsSync(rootDir) || isSymlinkIfExists(rootDir)) return false;
118
+ const absRoot = path.resolve(rootDir);
119
+ const absTarget = path.resolve(targetPath);
120
+ const rel = path.relative(absRoot, absTarget);
121
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return false;
122
+ const segments = rel.split(path.sep).filter(Boolean);
123
+ let cursor = absRoot;
124
+ let deepestExisting = absRoot;
125
+ for (const seg of segments) {
126
+ cursor = path.join(cursor, seg);
127
+ try {
128
+ const st = fs.lstatSync(cursor);
129
+ if (st.isSymbolicLink()) return false;
130
+ deepestExisting = cursor;
131
+ } catch (error) {
132
+ if (error?.code === "ENOENT") break;
133
+ return false;
134
+ }
135
+ }
136
+ const canonicalRoot = fs.realpathSync(absRoot);
137
+ const canonicalDeepest = fs.realpathSync(deepestExisting);
138
+ const canonicalRel = path.relative(canonicalRoot, canonicalDeepest);
139
+ return canonicalRel === "" || !canonicalRel.startsWith("..") && !path.isAbsolute(canonicalRel);
140
+ } catch {
141
+ return false;
142
+ }
143
+ }
144
+ var SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
145
+ function sleepSyncMs(ms) {
146
+ try {
147
+ Atomics.wait(SLEEP_BUFFER, 0, 0, ms);
148
+ } catch {
149
+ const end = Date.now() + ms;
150
+ while (Date.now() < end) {
151
+ }
152
+ }
153
+ }
154
+ function isPidAlive(pid) {
155
+ if (!Number.isInteger(pid) || pid <= 0) return false;
156
+ try {
157
+ process.kill(pid, 0);
158
+ return true;
159
+ } catch (error) {
160
+ return error?.code === "EPERM";
161
+ }
162
+ }
163
+ function tryReclaimStaleLock(lockPath) {
164
+ try {
165
+ const st = fs.lstatSync(lockPath);
166
+ if (st.isSymbolicLink() || !st.isFile()) return false;
167
+ const ageMs = Date.now() - st.mtimeMs;
168
+ let ownerDead = false;
169
+ try {
170
+ const pid = Number.parseInt(fs.readFileSync(lockPath, "utf8").trim(), 10);
171
+ if (Number.isInteger(pid) && pid > 0 && !isPidAlive(pid)) ownerDead = true;
172
+ } catch {
173
+ }
174
+ if (ownerDead || ageMs > LOCK_STALE_MS) {
175
+ fs.unlinkSync(lockPath);
176
+ return true;
177
+ }
178
+ } catch (error) {
179
+ if (error?.code === "ENOENT") return true;
180
+ }
181
+ return false;
182
+ }
183
+ function acquireSyncLock(lockPath) {
184
+ if (isSymlinkIfExists(lockPath)) return void 0;
185
+ for (let attempt = 0; attempt < LOCK_MAX_ATTEMPTS; attempt++) {
186
+ try {
187
+ const fd = fs.openSync(lockPath, "wx", 384);
188
+ try {
189
+ fs.writeFileSync(fd, `${process.pid}
190
+ `, "utf8");
191
+ } finally {
192
+ fs.closeSync(fd);
193
+ }
194
+ return () => {
195
+ try {
196
+ fs.unlinkSync(lockPath);
197
+ } catch {
198
+ }
199
+ };
200
+ } catch (error) {
201
+ if (error?.code !== "EEXIST") return void 0;
202
+ if (tryReclaimStaleLock(lockPath)) continue;
203
+ sleepSyncMs(LOCK_WAIT_MS);
204
+ }
205
+ }
206
+ return void 0;
207
+ }
208
+ function syncInheritedWorkerModels(workerModelsPath, globalModelsPath, opts = {}) {
209
+ let releaseLock;
210
+ try {
211
+ if (!workerModelsPath || !globalModelsPath) return false;
212
+ if (path.resolve(workerModelsPath) === path.resolve(globalModelsPath)) return false;
213
+ if (opts.allowedSrcRoot && !isPathSafeWithinRoot(opts.allowedSrcRoot, globalModelsPath)) return false;
214
+ if (opts.allowedDestRoot && !isPathSafeWithinRoot(opts.allowedDestRoot, workerModelsPath)) return false;
215
+ if (!fs.existsSync(globalModelsPath) || !isRegularFileIfExists(globalModelsPath)) return false;
216
+ if (isSymlinkIfExists(path.dirname(globalModelsPath))) return false;
217
+ const workerDir = path.dirname(workerModelsPath);
218
+ if (isSymlinkIfExists(workerDir) || !isRegularFileIfExists(workerModelsPath)) return false;
219
+ const sidecarPath = path.join(workerDir, INHERITED_HASH_FILENAME);
220
+ const lockPath = path.join(workerDir, SYNC_LOCK_FILENAME);
221
+ if (!isRegularFileIfExists(sidecarPath) || isSymlinkIfExists(lockPath)) return false;
222
+ fs.mkdirSync(workerDir, { recursive: true, mode: 448 });
223
+ if (opts.allowedDestRoot && !isPathSafeWithinRoot(opts.allowedDestRoot, workerModelsPath)) return false;
224
+ releaseLock = acquireSyncLock(lockPath);
225
+ if (!releaseLock) return false;
226
+ if (!fs.existsSync(globalModelsPath) || !isRegularFileIfExists(globalModelsPath)) return false;
227
+ if (!isRegularFileIfExists(workerModelsPath) || !isRegularFileIfExists(sidecarPath)) return false;
228
+ const globalText = fs.readFileSync(globalModelsPath, "utf8");
229
+ const globalHash = sha256Utf8(globalText);
230
+ if (!fs.existsSync(workerModelsPath)) {
231
+ writeAtomicFile(workerModelsPath, globalText, 384);
232
+ writeAtomicFile(sidecarPath, `${globalHash}
233
+ `, 384);
234
+ return true;
235
+ }
236
+ const workerText = fs.readFileSync(workerModelsPath, "utf8");
237
+ const workerHash = sha256Utf8(workerText);
238
+ if (workerHash === globalHash) {
239
+ const existingSidecar = fs.existsSync(sidecarPath) ? fs.readFileSync(sidecarPath, "utf8").trim() : void 0;
240
+ if (existingSidecar !== globalHash) {
241
+ try {
242
+ writeAtomicFile(sidecarPath, `${globalHash}
243
+ `, 384);
244
+ } catch {
245
+ }
246
+ }
247
+ return false;
248
+ }
249
+ if (fs.existsSync(sidecarPath)) {
250
+ const recorded = fs.readFileSync(sidecarPath, "utf8").trim();
251
+ if (recorded !== workerHash) {
252
+ return false;
253
+ }
254
+ writeAtomicFile(workerModelsPath, globalText, 384);
255
+ writeAtomicFile(sidecarPath, `${globalHash}
256
+ `, 384);
257
+ return true;
258
+ }
259
+ const workerParsed = JSON.parse(workerText);
260
+ const globalParsed = JSON.parse(globalText);
261
+ if (!isLegacyUnmodifiedModelsSnapshot(workerParsed, globalParsed)) {
262
+ return false;
263
+ }
264
+ writeAtomicFile(workerModelsPath, globalText, 384);
265
+ writeAtomicFile(sidecarPath, `${globalHash}
266
+ `, 384);
267
+ return true;
268
+ } catch {
269
+ return false;
270
+ } finally {
271
+ releaseLock?.();
272
+ }
273
+ }
274
+
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
+ export {
289
+ syncInheritedWorkerModels,
290
+ registerWorkerLifecycleBridge,
291
+ currentWorkerLifecycleBridge
292
+ };
@@ -196,7 +196,7 @@ async function runDistillWorkerMain(memoryRoot, date, noExit = false, sessionsDi
196
196
  let result;
197
197
  let ledger;
198
198
  try {
199
- const { ModelRegistry } = await import("./model-registry-QKJ3YVDS.js");
199
+ const { ModelRegistry } = await import("./model-registry-MGZO2RBN.js");
200
200
  const { AuthStorage } = await import("./auth-storage-C3FZMT7J.js");
201
201
  const { getSessionsDir } = await import("./config-4EOI5NOU.js");
202
202
  const { FileSessionStore } = await import("./src-3PSR2AAX.js");
@@ -4,7 +4,7 @@ import {
4
4
  assertNoSecretSubstrings,
5
5
  configuredRemoteCredentialValues,
6
6
  loadResolvedModelsConfig
7
- } from "./chunk-FC5AN5QP.js";
7
+ } from "./chunk-B5GKDXVG.js";
8
8
  import "./chunk-CBDQJMUI.js";
9
9
  import "./chunk-G2K4GY6N.js";
10
10
  import "./chunk-XXGYUYXI.js";
package/dist/cli.js CHANGED
@@ -28,7 +28,7 @@ import {
28
28
  runDistillWorkerMain,
29
29
  spawnDistillAutoWorker,
30
30
  spawnDistillWorker
31
- } from "./chunks/chunk-XMTRKMBG.js";
31
+ } from "./chunks/chunk-L7XXKNZW.js";
32
32
  import {
33
33
  SessionOwnershipLifecycle,
34
34
  claimSessionOwnership,
@@ -125,7 +125,7 @@ import "./chunks/chunk-F7EBZTZO.js";
125
125
  import "./chunks/chunk-ZPJ3BNQB.js";
126
126
  import {
127
127
  ModelRegistry
128
- } from "./chunks/chunk-FC5AN5QP.js";
128
+ } from "./chunks/chunk-B5GKDXVG.js";
129
129
  import {
130
130
  VERSION,
131
131
  getAgentDir,
@@ -81384,10 +81384,13 @@ async function loadInteractiveExtensions(host) {
81384
81384
  if (control !== "model.set") return { ok: false, message: `unknown control: ${control}` };
81385
81385
  if (!host.switchModel) return { ok: false, message: "host does not expose a model switch path" };
81386
81386
  const ref = payload && typeof payload === "object" && "model" in payload ? String(payload.model) : void 0;
81387
- if (!ref || !/^[^/\s]+\/[^/\s]+$/.test(ref)) return { ok: false, message: "model.set requires payload.model as 'provider/modelId'" };
81387
+ if (!ref || !/^[^/\s]+\/\S+$/.test(ref)) return { ok: false, message: "model.set requires payload.model as 'provider/modelId'" };
81388
81388
  const provider = ref.slice(0, ref.indexOf("/"));
81389
81389
  const modelId = ref.slice(ref.indexOf("/") + 1);
81390
- const model = host.options.modelRegistry.find(provider, modelId);
81390
+ let model = host.options.modelRegistry.find(provider, modelId);
81391
+ if (!model && typeof host.options.modelRegistry.reloadFromDisk === "function" && host.options.modelRegistry.reloadFromDisk()) {
81392
+ model = host.options.modelRegistry.find(provider, modelId);
81393
+ }
81391
81394
  if (!model) return { ok: false, message: `model "${ref}" not found` };
81392
81395
  if (!host.options.modelRegistry.getApiKey(model)) return { ok: false, message: `model "${ref}" has no API key configured` };
81393
81396
  try {
@@ -84157,13 +84160,16 @@ async function loadJsonModeExtensions(params) {
84157
84160
  applyIpcControl: async (control, payload) => {
84158
84161
  if (control === "model.set") {
84159
84162
  const ref = payload && typeof payload === "object" && "model" in payload ? String(payload.model) : void 0;
84160
- if (!ref || !/^[^/\s]+\/[^/\s]+$/.test(ref))
84163
+ if (!ref || !/^[^/\s]+\/\S+$/.test(ref))
84161
84164
  return { ok: false, message: "model.set requires payload.model as 'provider/modelId'" };
84162
84165
  try {
84163
84166
  const { provider, modelId } = { provider: ref.slice(0, ref.indexOf("/")), modelId: ref.slice(ref.indexOf("/") + 1) };
84164
84167
  const liveAgent = params.getAgent();
84165
84168
  if (!liveAgent) return { ok: false, message: "runtime not composed" };
84166
- const model = params.runtime.modelRegistry.find(provider, modelId);
84169
+ let model = params.runtime.modelRegistry.find(provider, modelId);
84170
+ if (!model && typeof params.runtime.modelRegistry.reloadFromDisk === "function" && params.runtime.modelRegistry.reloadFromDisk()) {
84171
+ model = params.runtime.modelRegistry.find(provider, modelId);
84172
+ }
84167
84173
  if (!model) return { ok: false, message: `model "${ref}" not found` };
84168
84174
  const apiKey = params.runtime.modelRegistry.getApiKey(model);
84169
84175
  if (!apiKey) return { ok: false, message: `model "${ref}" has no API key configured` };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cydm/pie",
3
- "version": "4.10.2",
3
+ "version": "4.11.0",
4
4
  "description": "Pie AI Agent CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,19 +0,0 @@
1
- import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
-
3
- // src/core/worker-lifecycle-bridge.ts
4
- var activeBridge;
5
- function registerWorkerLifecycleBridge(bridge) {
6
- const token = /* @__PURE__ */ Symbol("worker-lifecycle-bridge");
7
- activeBridge = { token, bridge };
8
- return () => {
9
- if (activeBridge?.token === token) activeBridge = void 0;
10
- };
11
- }
12
- function currentWorkerLifecycleBridge() {
13
- return activeBridge?.bridge;
14
- }
15
-
16
- export {
17
- registerWorkerLifecycleBridge,
18
- currentWorkerLifecycleBridge
19
- };