@cydm/pie 4.10.1 → 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.
- package/dist/builtin/extensions/im-forward/index.js +1093 -361
- package/dist/builtin/extensions/mcp-adapter/index.js +216 -7
- package/dist/builtin/extensions/memory/index.js +1 -1
- package/dist/builtin/extensions/pie-proc/index.js +187 -150
- package/dist/chunks/{chunk-FC5AN5QP.js → chunk-B5GKDXVG.js} +43 -48
- package/dist/chunks/chunk-EWPPGYBU.js +292 -0
- package/dist/chunks/{chunk-XMTRKMBG.js → chunk-L7XXKNZW.js} +1 -1
- package/dist/chunks/chunk-Z2RT3P4F.js +251 -0
- package/dist/chunks/manager-allow-SF5ROGDM.js +21 -0
- package/dist/chunks/{manager-cli-UU6SDS3F.js → manager-cli-BXI4UFTJ.js} +11 -54
- package/dist/chunks/{model-registry-QKJ3YVDS.js → model-registry-MGZO2RBN.js} +1 -1
- package/dist/cli.js +305 -41
- package/package.json +1 -1
- package/dist/chunks/chunk-6WKBQZWM.js +0 -19
|
@@ -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
|
-
|
|
1986
|
-
|
|
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
|
-
|
|
2049
|
-
|
|
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
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
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-
|
|
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");
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
getConfigDir
|
|
4
|
+
} from "./chunk-CBDQJMUI.js";
|
|
5
|
+
|
|
6
|
+
// src/commands/manager-allow.ts
|
|
7
|
+
import * as fs from "node:fs";
|
|
8
|
+
import * as os from "node:os";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { randomBytes } from "node:crypto";
|
|
11
|
+
function expandTilde(p) {
|
|
12
|
+
return p === "~" ? os.homedir() : p.startsWith("~/") || p.startsWith("~\\") ? path.join(os.homedir(), p.slice(2)) : p;
|
|
13
|
+
}
|
|
14
|
+
function resolveProcConfigCandidates() {
|
|
15
|
+
const root = getConfigDir();
|
|
16
|
+
const candidates = [path.join(root, "pie-proc.json")];
|
|
17
|
+
const pinnedRoot = process.env.PIE_PROC_REGISTRY_ROOT;
|
|
18
|
+
if (pinnedRoot) {
|
|
19
|
+
const pinDerived = path.join(path.dirname(path.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
|
|
20
|
+
if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
|
|
21
|
+
} else {
|
|
22
|
+
const homeFile = path.join(os.homedir(), ".pie", "pie-proc.json");
|
|
23
|
+
if (!candidates.includes(homeFile)) candidates.push(homeFile);
|
|
24
|
+
}
|
|
25
|
+
return candidates;
|
|
26
|
+
}
|
|
27
|
+
function resolveEffectiveProcConfigFile() {
|
|
28
|
+
const candidates = resolveProcConfigCandidates();
|
|
29
|
+
for (const candidate of candidates) {
|
|
30
|
+
try {
|
|
31
|
+
if (fs.existsSync(candidate)) return { file: candidate, exists: true };
|
|
32
|
+
} catch {
|
|
33
|
+
return { file: candidate, exists: true };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return { file: candidates[0], exists: false };
|
|
37
|
+
}
|
|
38
|
+
function resolveWritableProcConfigFile() {
|
|
39
|
+
return path.join(getConfigDir(), "pie-proc.json");
|
|
40
|
+
}
|
|
41
|
+
function isTooBroadForWorkerSandbox(input) {
|
|
42
|
+
let resolved;
|
|
43
|
+
try {
|
|
44
|
+
resolved = fs.realpathSync(input);
|
|
45
|
+
} catch {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
const root = path.parse(resolved).root;
|
|
49
|
+
if (resolved === root || resolved === os.homedir()) return true;
|
|
50
|
+
const forbidden = [os.homedir(), os.tmpdir(), "/tmp", "/var/tmp", "/private/tmp", "/private/var/tmp"];
|
|
51
|
+
for (const candidate of forbidden) {
|
|
52
|
+
try {
|
|
53
|
+
if (resolved === fs.realpathSync(candidate)) return true;
|
|
54
|
+
} catch {
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const stat = fs.statSync(resolved);
|
|
59
|
+
if ((stat.mode & 2) !== 0 && (stat.mode & 512) === 0) return true;
|
|
60
|
+
} catch {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
function seedProcConfig(launchCwd) {
|
|
66
|
+
const root = getConfigDir();
|
|
67
|
+
const file = path.join(root, "pie-proc.json");
|
|
68
|
+
const resolved = path.resolve(launchCwd);
|
|
69
|
+
try {
|
|
70
|
+
if (fs.existsSync(file)) return { state: "exists", file, root };
|
|
71
|
+
} catch {
|
|
72
|
+
return { state: "exists", file, root };
|
|
73
|
+
}
|
|
74
|
+
const userLayer = path.join(os.homedir(), ".pie", "pie-proc.json");
|
|
75
|
+
try {
|
|
76
|
+
if (fs.existsSync(userLayer)) return { state: "user-layer", file: userLayer, root };
|
|
77
|
+
} catch {
|
|
78
|
+
}
|
|
79
|
+
if (isTooBroadForWorkerSandbox(resolved)) {
|
|
80
|
+
return { state: "too-broad", file, root };
|
|
81
|
+
}
|
|
82
|
+
fs.mkdirSync(root, { recursive: true });
|
|
83
|
+
fs.writeFileSync(file, `${JSON.stringify({ allowCwd: [resolved] }, null, " ")}
|
|
84
|
+
`);
|
|
85
|
+
return { state: "seeded", file, root };
|
|
86
|
+
}
|
|
87
|
+
function isTooBroadDir(canonical) {
|
|
88
|
+
return isTooBroadForWorkerSandbox(canonical);
|
|
89
|
+
}
|
|
90
|
+
function addAllowedWorkerCwd(rawDir, opts = {}) {
|
|
91
|
+
const resolved = path.resolve(expandTilde(rawDir));
|
|
92
|
+
let canonical;
|
|
93
|
+
try {
|
|
94
|
+
canonical = fs.realpathSync(resolved);
|
|
95
|
+
if (!fs.statSync(canonical).isDirectory()) {
|
|
96
|
+
throw new Error(`"${rawDir}" is not a directory.`);
|
|
97
|
+
}
|
|
98
|
+
} catch (error) {
|
|
99
|
+
throw new Error(
|
|
100
|
+
error instanceof Error && error.message.includes("not a directory") ? error.message : `Directory does not exist or is unreadable: "${rawDir}" (${resolved}).`
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
if (isTooBroadDir(canonical) && !opts.force) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
`Refusing to authorize broad root "${canonical}" without --force. Pass a narrower project root (e.g. ~/Projects), or re-run with --force if you intentionally want this root.`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
const target = opts.file ? path.resolve(expandTilde(opts.file)) : resolveWritableProcConfigFile();
|
|
109
|
+
const shadowedFallback = !opts.file && !fs.existsSync(target) ? resolveProcConfigCandidates().slice(1).find((c) => {
|
|
110
|
+
try {
|
|
111
|
+
return fs.existsSync(c);
|
|
112
|
+
} catch {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}) : void 0;
|
|
116
|
+
let doc = {};
|
|
117
|
+
let backedUpTo;
|
|
118
|
+
if (fs.existsSync(target)) {
|
|
119
|
+
const rawText = fs.readFileSync(target, "utf8");
|
|
120
|
+
try {
|
|
121
|
+
const parsed = JSON.parse(rawText);
|
|
122
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
123
|
+
throw new Error("top-level JSON value must be an object");
|
|
124
|
+
}
|
|
125
|
+
doc = { ...parsed };
|
|
126
|
+
} catch (error) {
|
|
127
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
128
|
+
if (!opts.backupCorrupt) {
|
|
129
|
+
throw new Error(
|
|
130
|
+
`Cannot update ${target}: invalid JSON (${detail}). Re-run with --backup-corrupt to back up the broken file and recreate it.`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
backedUpTo = `${target}.corrupt-${Date.now()}-${randomBytes(3).toString("hex")}`;
|
|
134
|
+
fs.renameSync(target, backedUpTo);
|
|
135
|
+
doc = {};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const existing = Array.isArray(doc.allowCwd) ? doc.allowCwd.filter((v) => typeof v === "string" && v.trim().length > 0) : [];
|
|
139
|
+
const alreadyCovered = existing.some((entry) => {
|
|
140
|
+
try {
|
|
141
|
+
return fs.realpathSync(path.resolve(expandTilde(entry))) === canonical;
|
|
142
|
+
} catch {
|
|
143
|
+
return path.resolve(expandTilde(entry)) === canonical;
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
const nextAllowCwd = alreadyCovered ? existing : [...existing, canonical];
|
|
147
|
+
if (!alreadyCovered || backedUpTo) {
|
|
148
|
+
doc.allowCwd = nextAllowCwd;
|
|
149
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
150
|
+
const tmp = path.join(path.dirname(target), `.pie-proc-${process.pid}-${randomBytes(4).toString("hex")}.tmp`);
|
|
151
|
+
try {
|
|
152
|
+
fs.writeFileSync(tmp, `${JSON.stringify(doc, null, " ")}
|
|
153
|
+
`, { encoding: "utf8", mode: 384 });
|
|
154
|
+
fs.renameSync(tmp, target);
|
|
155
|
+
} finally {
|
|
156
|
+
try {
|
|
157
|
+
fs.rmSync(tmp, { force: true });
|
|
158
|
+
} catch {
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
file: target,
|
|
164
|
+
canonicalDir: canonical,
|
|
165
|
+
added: !alreadyCovered,
|
|
166
|
+
allowCwd: nextAllowCwd,
|
|
167
|
+
...backedUpTo ? { backedUpTo } : {},
|
|
168
|
+
...shadowedFallback ? { shadowedFallback } : {}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function runManagerAllowCommand(args) {
|
|
172
|
+
const json = args.includes("--json");
|
|
173
|
+
const force = args.includes("--force");
|
|
174
|
+
const backupCorrupt = args.includes("--backup-corrupt");
|
|
175
|
+
const list = args.includes("--list");
|
|
176
|
+
const help = args.includes("--help") || args.includes("-h");
|
|
177
|
+
const fileIdx = args.indexOf("--file");
|
|
178
|
+
const explicitFile = fileIdx >= 0 ? args[fileIdx + 1] : void 0;
|
|
179
|
+
if (fileIdx >= 0 && (!explicitFile || explicitFile.startsWith("-"))) {
|
|
180
|
+
console.error("--file expects a pie-proc.json path.");
|
|
181
|
+
process.exitCode = 2;
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (help) {
|
|
185
|
+
console.log(
|
|
186
|
+
"Usage:\n pie manager allow <dir> [--file <path>] [--force] [--backup-corrupt] [--json]\n pie manager allow --list [--json]\n\nAdds a canonical project root to the active pie-proc.json allowCwd list.\nRe-read on every worker spawn; no manager restart required."
|
|
187
|
+
);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (list) {
|
|
191
|
+
const { file, exists } = resolveEffectiveProcConfigFile();
|
|
192
|
+
if (!exists) {
|
|
193
|
+
if (json) console.log(JSON.stringify({ ok: true, file, exists: false, allowCwd: [] }));
|
|
194
|
+
else console.log(`No pie-proc.json found yet (next write target: ${file}).`);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
199
|
+
const allowCwd = Array.isArray(parsed.allowCwd) ? parsed.allowCwd.filter((v) => typeof v === "string") : [];
|
|
200
|
+
if (json) console.log(JSON.stringify({ ok: true, file, exists: true, allowCwd, maxWorkers: parsed.maxWorkers ?? 50 }));
|
|
201
|
+
else {
|
|
202
|
+
console.log(`Policy file: ${file}`);
|
|
203
|
+
console.log(`maxWorkers: ${typeof parsed.maxWorkers === "number" ? parsed.maxWorkers : "50 (default)"}`);
|
|
204
|
+
console.log(allowCwd.length ? `allowCwd:
|
|
205
|
+
${allowCwd.map((d) => ` - ${d}`).join("\n")}` : "allowCwd: (empty)");
|
|
206
|
+
}
|
|
207
|
+
} catch (error) {
|
|
208
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
209
|
+
if (json) console.log(JSON.stringify({ ok: false, file, error: detail }));
|
|
210
|
+
else console.error(`Invalid pie-proc.json at ${file}: ${detail}`);
|
|
211
|
+
process.exitCode = 1;
|
|
212
|
+
}
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
const positional = [];
|
|
216
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
217
|
+
if (args[i] === "--file") {
|
|
218
|
+
i += 1;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (!args[i].startsWith("-")) positional.push(args[i]);
|
|
222
|
+
}
|
|
223
|
+
const targetDir = positional[0];
|
|
224
|
+
if (!targetDir) {
|
|
225
|
+
console.error("Usage: pie manager allow <dir> [--file <path>] [--force] [--backup-corrupt] [--json] | pie manager allow --list");
|
|
226
|
+
process.exitCode = 2;
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const result = addAllowedWorkerCwd(targetDir, { file: explicitFile, force, backupCorrupt });
|
|
230
|
+
if (json) {
|
|
231
|
+
console.log(JSON.stringify({ ok: true, ...result }));
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (result.backedUpTo) console.log(`Backed up corrupt config to: ${result.backedUpTo}`);
|
|
235
|
+
if (result.shadowedFallback) {
|
|
236
|
+
console.log(`Note: created ${result.file}, which takes precedence over ${result.shadowedFallback}. Pass --file ${result.shadowedFallback} to update the shared policy instead.`);
|
|
237
|
+
}
|
|
238
|
+
console.log(
|
|
239
|
+
result.added ? `Authorized worker root "${result.canonicalDir}" in ${result.file} (effective immediately; no restart needed).` : `Worker root "${result.canonicalDir}" is already authorized in ${result.file}.`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export {
|
|
244
|
+
resolveProcConfigCandidates,
|
|
245
|
+
resolveEffectiveProcConfigFile,
|
|
246
|
+
resolveWritableProcConfigFile,
|
|
247
|
+
isTooBroadForWorkerSandbox,
|
|
248
|
+
seedProcConfig,
|
|
249
|
+
addAllowedWorkerCwd,
|
|
250
|
+
runManagerAllowCommand
|
|
251
|
+
};
|