@forg3t/sdk 0.1.3 → 0.1.4
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/README.md +407 -63
- package/dist/index.d.mts +528 -12
- package/dist/index.d.ts +528 -12
- package/dist/index.js +1105 -34
- package/dist/index.mjs +1077 -40
- package/package.json +54 -49
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
-
}) : x)(function(x) {
|
|
4
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
-
});
|
|
7
|
-
|
|
8
1
|
// src/errors.ts
|
|
9
2
|
var Forg3tError = class extends Error {
|
|
10
3
|
constructor(message, status, code, requestId, details) {
|
|
@@ -40,18 +33,39 @@ var Forg3tApiConnectionError = class extends Forg3tError {
|
|
|
40
33
|
this.name = "Forg3tApiConnectionError";
|
|
41
34
|
}
|
|
42
35
|
};
|
|
36
|
+
var Forg3tNotImplementedError = class extends Forg3tError {
|
|
37
|
+
constructor(message, endpoint, requestId) {
|
|
38
|
+
super(
|
|
39
|
+
`Endpoint not implemented: ${endpoint || "unknown"}`,
|
|
40
|
+
501,
|
|
41
|
+
"NOT_IMPLEMENTED",
|
|
42
|
+
requestId,
|
|
43
|
+
{ endpoint }
|
|
44
|
+
);
|
|
45
|
+
this.name = "Forg3tNotImplementedError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
43
48
|
|
|
44
49
|
// src/transport.ts
|
|
45
50
|
var Transport = class {
|
|
46
51
|
constructor(config) {
|
|
47
|
-
|
|
52
|
+
const rawBaseUrl = config.baseUrl || typeof process !== "undefined" && process.env.FORG3T_API_URL || "";
|
|
53
|
+
this.baseUrl = String(rawBaseUrl).trim();
|
|
48
54
|
if (!this.baseUrl) {
|
|
49
55
|
throw new Error("Forg3tClient: apiUrl option or FORG3T_API_URL environment variable is required");
|
|
50
56
|
}
|
|
57
|
+
if (!/^https?:\/\//i.test(this.baseUrl)) {
|
|
58
|
+
throw new Error("Forg3tClient: apiUrl must be an absolute http(s) URL");
|
|
59
|
+
}
|
|
51
60
|
if (this.baseUrl.endsWith("/")) {
|
|
52
61
|
this.baseUrl = this.baseUrl.slice(0, -1);
|
|
53
62
|
}
|
|
54
|
-
|
|
63
|
+
const rawApiKey = config.apiKey || (typeof process !== "undefined" ? process.env.FORG3T_API_KEY : void 0);
|
|
64
|
+
const apiKey = typeof rawApiKey === "string" ? rawApiKey.trim() : rawApiKey;
|
|
65
|
+
this.apiKey = apiKey || void 0;
|
|
66
|
+
const rawBearerToken = config.bearerToken || (typeof process !== "undefined" ? process.env.FORG3T_BEARER_TOKEN : void 0);
|
|
67
|
+
const bearerToken = typeof rawBearerToken === "string" ? rawBearerToken.trim() : rawBearerToken;
|
|
68
|
+
this.bearerToken = bearerToken || void 0;
|
|
55
69
|
this.timeoutMs = config.timeoutMs || 3e4;
|
|
56
70
|
}
|
|
57
71
|
getBaseUrl() {
|
|
@@ -67,8 +81,11 @@ var Transport = class {
|
|
|
67
81
|
if (this.apiKey) {
|
|
68
82
|
headers["x-api-key"] = this.apiKey;
|
|
69
83
|
}
|
|
84
|
+
if (this.bearerToken && !headers.Authorization) {
|
|
85
|
+
headers.Authorization = `Bearer ${this.bearerToken}`;
|
|
86
|
+
}
|
|
70
87
|
if (requestId) {
|
|
71
|
-
headers["x-
|
|
88
|
+
headers["x-correlation-id"] = requestId;
|
|
72
89
|
}
|
|
73
90
|
const controller = new AbortController();
|
|
74
91
|
const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
@@ -81,7 +98,7 @@ var Transport = class {
|
|
|
81
98
|
// Add the abort signal
|
|
82
99
|
});
|
|
83
100
|
clearTimeout(timeoutId);
|
|
84
|
-
const responseRequestId = response.headers.get("x-request-id") || requestId;
|
|
101
|
+
const responseRequestId = response.headers.get("x-correlation-id") || response.headers.get("x-request-id") || requestId;
|
|
85
102
|
if (!response.ok) {
|
|
86
103
|
let errorData = {};
|
|
87
104
|
try {
|
|
@@ -119,7 +136,8 @@ var Transport = class {
|
|
|
119
136
|
if (error instanceof Error && error.name === "AbortError") {
|
|
120
137
|
throw new Forg3tApiConnectionError(`Request timeout after ${this.timeoutMs}ms`);
|
|
121
138
|
}
|
|
122
|
-
|
|
139
|
+
const detail = error instanceof Error ? error.message : "Network error";
|
|
140
|
+
throw new Forg3tApiConnectionError(`Request failed for ${url}: ${detail}`);
|
|
123
141
|
}
|
|
124
142
|
}
|
|
125
143
|
async download(url, requestId) {
|
|
@@ -130,6 +148,9 @@ var Transport = class {
|
|
|
130
148
|
if (this.apiKey) {
|
|
131
149
|
headers["x-api-key"] = this.apiKey;
|
|
132
150
|
}
|
|
151
|
+
if (this.bearerToken && !headers.Authorization) {
|
|
152
|
+
headers.Authorization = `Bearer ${this.bearerToken}`;
|
|
153
|
+
}
|
|
133
154
|
if (requestId) {
|
|
134
155
|
headers["x-request-id"] = requestId;
|
|
135
156
|
}
|
|
@@ -178,7 +199,8 @@ var Transport = class {
|
|
|
178
199
|
if (error instanceof Error && error.name === "AbortError") {
|
|
179
200
|
throw new Forg3tApiConnectionError(`Download timeout after ${this.timeoutMs}ms`);
|
|
180
201
|
}
|
|
181
|
-
|
|
202
|
+
const detail = error instanceof Error ? error.message : "Network error";
|
|
203
|
+
throw new Forg3tApiConnectionError(`Download failed for ${url}: ${detail}`);
|
|
182
204
|
}
|
|
183
205
|
}
|
|
184
206
|
async requestRaw(path, options = {}, requestId) {
|
|
@@ -191,6 +213,9 @@ var Transport = class {
|
|
|
191
213
|
if (this.apiKey) {
|
|
192
214
|
headers["x-api-key"] = this.apiKey;
|
|
193
215
|
}
|
|
216
|
+
if (this.bearerToken && !headers.Authorization) {
|
|
217
|
+
headers.Authorization = `Bearer ${this.bearerToken}`;
|
|
218
|
+
}
|
|
194
219
|
if (requestId) {
|
|
195
220
|
headers["x-request-id"] = requestId;
|
|
196
221
|
}
|
|
@@ -214,7 +239,8 @@ var Transport = class {
|
|
|
214
239
|
if (error instanceof Error && error.name === "AbortError") {
|
|
215
240
|
throw new Forg3tApiConnectionError(`Request timeout after ${this.timeoutMs}ms`);
|
|
216
241
|
}
|
|
217
|
-
|
|
242
|
+
const detail = error instanceof Error ? error.message : "Network error";
|
|
243
|
+
throw new Forg3tApiConnectionError(`Raw request failed for ${url}: ${detail}`);
|
|
218
244
|
}
|
|
219
245
|
}
|
|
220
246
|
};
|
|
@@ -225,9 +251,31 @@ var Forg3tClient = class {
|
|
|
225
251
|
this.transport = new Transport({
|
|
226
252
|
baseUrl: options.apiUrl,
|
|
227
253
|
apiKey: options.apiKey,
|
|
254
|
+
bearerToken: options.bearerToken,
|
|
228
255
|
timeoutMs: options.timeoutMs
|
|
229
256
|
});
|
|
230
257
|
}
|
|
258
|
+
// --- Authentication ---
|
|
259
|
+
/**
|
|
260
|
+
* Get the current user context and their default project.
|
|
261
|
+
* Used by the Admin Dashboard for bootstrap and session verification.
|
|
262
|
+
*/
|
|
263
|
+
async getCurrentUser(requestId) {
|
|
264
|
+
return this.transport.request("/v1/me", { method: "GET" }, requestId);
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Bootstraps a tenant for an authenticated dashboard user.
|
|
268
|
+
* Requires a bearer token from the user's session instead of an API key.
|
|
269
|
+
*/
|
|
270
|
+
async bootstrapTenant(data, requestId) {
|
|
271
|
+
if (!data?.tenantName || typeof data.tenantName !== "string" || !data.tenantName.trim()) {
|
|
272
|
+
throw new Error("bootstrapTenant requires a non-empty tenantName.");
|
|
273
|
+
}
|
|
274
|
+
return this.transport.request("/v1/bootstrap/tenant", {
|
|
275
|
+
method: "POST",
|
|
276
|
+
body: JSON.stringify(data)
|
|
277
|
+
}, requestId);
|
|
278
|
+
}
|
|
231
279
|
// --- Projects ---
|
|
232
280
|
async getProjectOverview(projectId, requestId) {
|
|
233
281
|
return this.transport.request(`/v1/projects/${projectId}/overview`, { method: "GET" }, requestId);
|
|
@@ -243,6 +291,42 @@ var Forg3tClient = class {
|
|
|
243
291
|
if (filters.cursor) params.append("cursor", filters.cursor);
|
|
244
292
|
return this.transport.request(`/v1/projects/${projectId}/audit?${params.toString()}`, { method: "GET" }, requestId);
|
|
245
293
|
}
|
|
294
|
+
// --- Integrations ---
|
|
295
|
+
async listIntegrations(projectId, requestId) {
|
|
296
|
+
return this.transport.request(`/v1/projects/${projectId}/integrations`, { method: "GET" }, requestId);
|
|
297
|
+
}
|
|
298
|
+
async createIntegration(projectId, data, requestId) {
|
|
299
|
+
return this.transport.request(`/v1/projects/${projectId}/integrations`, {
|
|
300
|
+
method: "POST",
|
|
301
|
+
body: JSON.stringify(data)
|
|
302
|
+
}, requestId);
|
|
303
|
+
}
|
|
304
|
+
async testIntegration(projectId, integrationId, requestId) {
|
|
305
|
+
void projectId;
|
|
306
|
+
return this.transport.request(
|
|
307
|
+
`/v1/integrations/${integrationId}/test`,
|
|
308
|
+
{ method: "POST" },
|
|
309
|
+
requestId
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
// --- Unlearning Requests ---
|
|
313
|
+
async createUnlearningRequest(projectId, data, requestId) {
|
|
314
|
+
this.assertCreateUnlearningRequest(data);
|
|
315
|
+
return this.transport.request(`/v1/projects/${projectId}/unlearning-requests`, {
|
|
316
|
+
method: "POST",
|
|
317
|
+
body: JSON.stringify(data)
|
|
318
|
+
}, requestId);
|
|
319
|
+
}
|
|
320
|
+
async listUnlearningRequests(projectId, requestId) {
|
|
321
|
+
return this.transport.request(`/v1/projects/${projectId}/unlearning-requests`, { method: "GET" }, requestId);
|
|
322
|
+
}
|
|
323
|
+
async getUnlearningRequest(projectId, unlearningRequestId, requestId) {
|
|
324
|
+
return this.transport.request(
|
|
325
|
+
`/v1/projects/${projectId}/unlearning-requests/${unlearningRequestId}`,
|
|
326
|
+
{ method: "GET" },
|
|
327
|
+
requestId
|
|
328
|
+
);
|
|
329
|
+
}
|
|
246
330
|
// --- API Keys ---
|
|
247
331
|
async listApiKeys(projectId, requestId) {
|
|
248
332
|
return this.transport.request(`/v1/projects/${projectId}/api-keys`, { method: "GET" }, requestId);
|
|
@@ -261,15 +345,48 @@ var Forg3tClient = class {
|
|
|
261
345
|
}
|
|
262
346
|
// --- Jobs ---
|
|
263
347
|
async submitJob(projectId, data, requestId) {
|
|
348
|
+
const normalizedPayload = "payload" in data ? data.payload : {
|
|
349
|
+
claim: data.claim,
|
|
350
|
+
config: data.config
|
|
351
|
+
};
|
|
352
|
+
if (data.type === "MODEL_UNLEARN") {
|
|
353
|
+
this.assertModelUnlearnPreflight(normalizedPayload);
|
|
354
|
+
}
|
|
264
355
|
const res = await this.transport.request(`/v1/projects/${projectId}/jobs`, {
|
|
265
356
|
method: "POST",
|
|
266
|
-
body: JSON.stringify(
|
|
357
|
+
body: JSON.stringify({
|
|
358
|
+
type: data.type,
|
|
359
|
+
payload: normalizedPayload,
|
|
360
|
+
idempotencyKey: data.idempotencyKey
|
|
361
|
+
})
|
|
267
362
|
}, requestId);
|
|
268
363
|
return res;
|
|
269
364
|
}
|
|
365
|
+
/**
|
|
366
|
+
* Creates a new job with deduplication support via an optional idempotency key.
|
|
367
|
+
* This wrapper cleanly exposes the core parameters for the production job queue.
|
|
368
|
+
*/
|
|
369
|
+
async createJob(projectId, type, claim, config, idempotencyKey, requestId) {
|
|
370
|
+
return this.submitJob(projectId, { type, claim, config, idempotencyKey }, requestId);
|
|
371
|
+
}
|
|
270
372
|
async getJob(projectId, jobId, requestId) {
|
|
271
373
|
return this.transport.request(`/v1/projects/${projectId}/jobs/${jobId}`, { method: "GET" }, requestId);
|
|
272
374
|
}
|
|
375
|
+
/**
|
|
376
|
+
* Polls the job status continuously until a terminal state (succeeded, failed, canceled) is reached,
|
|
377
|
+
* or the specified timeout limits are exceeded.
|
|
378
|
+
*/
|
|
379
|
+
async pollJobStatus(projectId, jobId, timeoutMs = 3e5, pollIntervalMs = 2e3, requestId) {
|
|
380
|
+
const startTime = Date.now();
|
|
381
|
+
while (Date.now() - startTime < timeoutMs) {
|
|
382
|
+
const job = await this.getJob(projectId, jobId, requestId);
|
|
383
|
+
if (job.status === "succeeded" || job.status === "failed" || job.status === "canceled") {
|
|
384
|
+
return job;
|
|
385
|
+
}
|
|
386
|
+
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
387
|
+
}
|
|
388
|
+
throw new Error(`pollJobStatus timed out after ${timeoutMs}ms waiting for job ${jobId} to reach a terminal state.`);
|
|
389
|
+
}
|
|
273
390
|
async listJobs(projectId, query, requestId) {
|
|
274
391
|
const params = new URLSearchParams();
|
|
275
392
|
if (query?.status) params.append("status", query.status);
|
|
@@ -283,20 +400,37 @@ var Forg3tClient = class {
|
|
|
283
400
|
body: JSON.stringify(data)
|
|
284
401
|
}, requestId);
|
|
285
402
|
}
|
|
286
|
-
async heartbeatJob(projectId, jobId, requestId) {
|
|
287
|
-
|
|
403
|
+
async heartbeatJob(projectId, jobId, optionsOrRequestId, requestId) {
|
|
404
|
+
const options = typeof optionsOrRequestId === "string" ? {} : optionsOrRequestId || {};
|
|
405
|
+
const resolvedRequestId = typeof optionsOrRequestId === "string" ? optionsOrRequestId : requestId;
|
|
406
|
+
return this.transport.request(`/v1/projects/${projectId}/jobs/${jobId}/heartbeat`, {
|
|
407
|
+
method: "POST",
|
|
408
|
+
body: JSON.stringify({
|
|
409
|
+
claimId: options.claimId
|
|
410
|
+
})
|
|
411
|
+
}, resolvedRequestId);
|
|
288
412
|
}
|
|
289
|
-
async completeJob(projectId, jobId, result, requestId) {
|
|
413
|
+
async completeJob(projectId, jobId, result, optionsOrRequestId, requestId) {
|
|
414
|
+
const options = typeof optionsOrRequestId === "string" ? {} : optionsOrRequestId || {};
|
|
415
|
+
const resolvedRequestId = typeof optionsOrRequestId === "string" ? optionsOrRequestId : requestId;
|
|
290
416
|
return this.transport.request(`/v1/projects/${projectId}/jobs/${jobId}/complete`, {
|
|
291
417
|
method: "POST",
|
|
292
|
-
body: JSON.stringify(
|
|
293
|
-
|
|
418
|
+
body: JSON.stringify({
|
|
419
|
+
...result,
|
|
420
|
+
claimId: options.claimId || result.claimId
|
|
421
|
+
})
|
|
422
|
+
}, resolvedRequestId);
|
|
294
423
|
}
|
|
295
|
-
async failJob(projectId, jobId, error, requestId) {
|
|
424
|
+
async failJob(projectId, jobId, error, optionsOrRequestId, requestId) {
|
|
425
|
+
const options = typeof optionsOrRequestId === "string" ? {} : optionsOrRequestId || {};
|
|
426
|
+
const resolvedRequestId = typeof optionsOrRequestId === "string" ? optionsOrRequestId : requestId;
|
|
296
427
|
return this.transport.request(`/v1/projects/${projectId}/jobs/${jobId}/fail`, {
|
|
297
428
|
method: "POST",
|
|
298
|
-
body: JSON.stringify(
|
|
299
|
-
|
|
429
|
+
body: JSON.stringify({
|
|
430
|
+
...error,
|
|
431
|
+
claimId: options.claimId || error.claimId
|
|
432
|
+
})
|
|
433
|
+
}, resolvedRequestId);
|
|
300
434
|
}
|
|
301
435
|
async listDeadJobs(projectId, requestId) {
|
|
302
436
|
return this.transport.request(`/v1/projects/${projectId}/jobs/dead`, { method: "GET" }, requestId);
|
|
@@ -306,7 +440,20 @@ var Forg3tClient = class {
|
|
|
306
440
|
}
|
|
307
441
|
// --- Evidence ---
|
|
308
442
|
async getEvidence(jobId, requestId) {
|
|
309
|
-
|
|
443
|
+
try {
|
|
444
|
+
return await this.transport.request(`/v1/jobs/${jobId}/evidence`, { method: "GET" }, requestId);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
if (error instanceof Forg3tNotFoundError) {
|
|
447
|
+
return this.transport.request(`/v1/jobs/evidence/${jobId}`, { method: "GET" }, requestId);
|
|
448
|
+
}
|
|
449
|
+
throw error;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
async getEvidenceJson(jobId, requestId) {
|
|
453
|
+
return this.transport.request(`/v1/jobs/${jobId}/evidence.json`, { method: "GET" }, requestId);
|
|
454
|
+
}
|
|
455
|
+
async getArtifactDownloadUrl(projectId, jobId, filename, requestId) {
|
|
456
|
+
return this.transport.request(`/v1/projects/${projectId}/jobs/${jobId}/artifacts/${filename}/download`, { method: "GET" }, requestId);
|
|
310
457
|
}
|
|
311
458
|
async getEvidencePdf(jobId, options) {
|
|
312
459
|
const response = await this.transport.requestRaw(`/v1/jobs/${jobId}/evidence.pdf`, { method: "GET" });
|
|
@@ -330,26 +477,24 @@ var Forg3tClient = class {
|
|
|
330
477
|
return result;
|
|
331
478
|
}
|
|
332
479
|
async savePdfToFile(data, filePath) {
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
const fs = __require("fs");
|
|
336
|
-
const path = __require("path");
|
|
337
|
-
const dir = path.dirname(filePath);
|
|
338
|
-
if (!fs.existsSync(dir)) {
|
|
339
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
340
|
-
}
|
|
341
|
-
fs.writeFileSync(filePath, Buffer.from(data));
|
|
342
|
-
} catch (error) {
|
|
343
|
-
console.error("Failed to save PDF to file:", error);
|
|
344
|
-
throw error;
|
|
345
|
-
}
|
|
346
|
-
} else {
|
|
480
|
+
const isNode = typeof process !== "undefined" && typeof process.versions?.node === "string";
|
|
481
|
+
if (!isNode) {
|
|
347
482
|
throw new Error("File saving is only supported in Node.js environment");
|
|
348
483
|
}
|
|
484
|
+
try {
|
|
485
|
+
const fs = await import("fs/promises");
|
|
486
|
+
const path = await import("path");
|
|
487
|
+
const dir = path.dirname(filePath);
|
|
488
|
+
await fs.mkdir(dir, { recursive: true });
|
|
489
|
+
await fs.writeFile(filePath, data);
|
|
490
|
+
} catch (error) {
|
|
491
|
+
console.error("Failed to save PDF to file:", error);
|
|
492
|
+
throw error;
|
|
493
|
+
}
|
|
349
494
|
}
|
|
350
495
|
/**
|
|
351
496
|
* @deprecated The current Control Plane version does not support direct artifact downloads.
|
|
352
|
-
* Please use
|
|
497
|
+
* Please use getArtifactDownloadUrl(), getEvidencePdf(), or getEvidenceJson().
|
|
353
498
|
*/
|
|
354
499
|
async downloadEvidenceArtifact(_jobId, _requestId) {
|
|
355
500
|
throw new Error("Artifact download not supported by current API version. Use getEvidence() to retrieve content.");
|
|
@@ -420,12 +565,904 @@ var Forg3tClient = class {
|
|
|
420
565
|
body: JSON.stringify(result)
|
|
421
566
|
}, requestId);
|
|
422
567
|
}
|
|
568
|
+
assertCreateUnlearningRequest(data) {
|
|
569
|
+
if (!data.target?.value?.trim()) {
|
|
570
|
+
throw new Error("createUnlearningRequest: target.value is required.");
|
|
571
|
+
}
|
|
572
|
+
if (typeof data.target.aliases !== "undefined") {
|
|
573
|
+
if (!Array.isArray(data.target.aliases) || data.target.aliases.some((alias) => typeof alias !== "string" || !alias.trim())) {
|
|
574
|
+
throw new Error("createUnlearningRequest: target.aliases must be an array of non-empty strings when provided.");
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
if (data.accessLevel === "layer_a_only") {
|
|
578
|
+
const target = data.execution?.target;
|
|
579
|
+
if (!target) {
|
|
580
|
+
throw new Error("createUnlearningRequest: execution.target is required for layer_a_only.");
|
|
581
|
+
}
|
|
582
|
+
if ((target.provider === "openai" || target.provider === "groq") && !target.model?.trim()) {
|
|
583
|
+
throw new Error(`createUnlearningRequest: execution.target.model is required when provider=${target.provider}.`);
|
|
584
|
+
}
|
|
585
|
+
if ((target.provider === "http_generic" || target.provider === "custom") && !target.endpoint?.trim()) {
|
|
586
|
+
throw new Error(`createUnlearningRequest: execution.target.endpoint is required when provider=${target.provider}.`);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
if (data.accessLevel === "layer_a_and_b") {
|
|
590
|
+
if (!data.execution?.model?.uri?.trim()) {
|
|
591
|
+
throw new Error("createUnlearningRequest: execution.model.uri is required for layer_a_and_b.");
|
|
592
|
+
}
|
|
593
|
+
const targetTokenIds = data.execution?.plan?.hyperparameters?.target_token_ids;
|
|
594
|
+
const tokenizerUri = data.execution?.model?.metadata?.tokenizer_uri;
|
|
595
|
+
const localizationMode = String(
|
|
596
|
+
data.execution?.plan?.hyperparameters?.localization_mode || data.execution?.plan?.hyperparameters?.localizationMode || ""
|
|
597
|
+
).trim().toLowerCase();
|
|
598
|
+
const allowMissingLocalization = String(process.env.FORG3T_ALLOW_MODEL_UNLEARN_WITHOUT_LOCALIZATION_INPUT || "").toLowerCase() === "true";
|
|
599
|
+
const hasTokenIds = Array.isArray(targetTokenIds) && targetTokenIds.some((value) => Number.isInteger(value) && Number(value) >= 0);
|
|
600
|
+
const hasTokenizer = typeof tokenizerUri === "string" && tokenizerUri.trim().length > 0;
|
|
601
|
+
if (localizationMode === "explicit_token_ids" && !hasTokenIds) {
|
|
602
|
+
throw new Error("createUnlearningRequest: localization_mode=explicit_token_ids requires target token IDs.");
|
|
603
|
+
}
|
|
604
|
+
if (localizationMode === "tokenizer_auto" && !hasTokenizer) {
|
|
605
|
+
throw new Error("createUnlearningRequest: localization_mode=tokenizer_auto requires execution.model.metadata.tokenizer_uri.");
|
|
606
|
+
}
|
|
607
|
+
if (localizationMode === "hybrid") {
|
|
608
|
+
if (!hasTokenIds) {
|
|
609
|
+
throw new Error("createUnlearningRequest: localization_mode=hybrid requires target token IDs.");
|
|
610
|
+
}
|
|
611
|
+
if (!hasTokenizer) {
|
|
612
|
+
throw new Error("createUnlearningRequest: localization_mode=hybrid requires execution.model.metadata.tokenizer_uri.");
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
if (!allowMissingLocalization && !hasTokenIds && !hasTokenizer) {
|
|
616
|
+
throw new Error(
|
|
617
|
+
"createUnlearningRequest: layer_a_and_b requires localization input. Provide target token IDs (execution.plan.hyperparameters.target_token_ids) or tokenizer URI (execution.model.metadata.tokenizer_uri)."
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
assertModelUnlearnPreflight(payload) {
|
|
623
|
+
if (!payload || typeof payload !== "object") {
|
|
624
|
+
throw new Error("MODEL_UNLEARN preflight failed: payload must be an object.");
|
|
625
|
+
}
|
|
626
|
+
const asRecord = payload;
|
|
627
|
+
const config = asRecord.config && typeof asRecord.config === "object" && !Array.isArray(asRecord.config) ? asRecord.config : null;
|
|
628
|
+
if (!config) {
|
|
629
|
+
throw new Error("MODEL_UNLEARN preflight failed: payload.config is required.");
|
|
630
|
+
}
|
|
631
|
+
const targetConfig = config.target_config && typeof config.target_config === "object" && !Array.isArray(config.target_config) ? config.target_config : null;
|
|
632
|
+
const parameters = config.parameters && typeof config.parameters === "object" && !Array.isArray(config.parameters) ? config.parameters : null;
|
|
633
|
+
const modelFromTargetConfig = targetConfig?.model && typeof targetConfig.model === "object" && !Array.isArray(targetConfig.model) ? targetConfig.model : null;
|
|
634
|
+
const modelFromParameters = parameters?.model && typeof parameters.model === "object" && !Array.isArray(parameters.model) ? parameters.model : null;
|
|
635
|
+
const model = modelFromParameters || modelFromTargetConfig;
|
|
636
|
+
const modelUri = typeof model?.uri === "string" ? model.uri.trim() : "";
|
|
637
|
+
if (!modelUri) {
|
|
638
|
+
throw new Error("MODEL_UNLEARN preflight failed: config.target_config.model.uri (or config.parameters.model.uri) is required.");
|
|
639
|
+
}
|
|
640
|
+
const target = parameters?.target && typeof parameters.target === "object" && !Array.isArray(parameters.target) ? parameters.target : null;
|
|
641
|
+
const tokenIds = target?.tokenIds;
|
|
642
|
+
const hasTokenIds = Array.isArray(tokenIds) && tokenIds.some((value) => Number.isInteger(value) && Number(value) >= 0);
|
|
643
|
+
const tokenizerFromTargetConfig = targetConfig?.tokenizer && typeof targetConfig.tokenizer === "object" && !Array.isArray(targetConfig.tokenizer) ? targetConfig.tokenizer : null;
|
|
644
|
+
const tokenizerFromParameters = parameters?.tokenizer && typeof parameters.tokenizer === "object" && !Array.isArray(parameters.tokenizer) ? parameters.tokenizer : null;
|
|
645
|
+
const tokenizerFromModel = model?.tokenizer && typeof model.tokenizer === "object" && !Array.isArray(model.tokenizer) ? model.tokenizer : null;
|
|
646
|
+
const tokenizerCandidates = [
|
|
647
|
+
tokenizerFromTargetConfig?.uri,
|
|
648
|
+
tokenizerFromParameters?.uri,
|
|
649
|
+
parameters?.tokenizer_uri,
|
|
650
|
+
model?.tokenizer_uri,
|
|
651
|
+
tokenizerFromModel?.uri
|
|
652
|
+
];
|
|
653
|
+
const hasTokenizerUri = tokenizerCandidates.some((candidate) => typeof candidate === "string" && candidate.trim().length > 0);
|
|
654
|
+
const allowMissingLocalization = String(process.env.FORG3T_ALLOW_MODEL_UNLEARN_WITHOUT_LOCALIZATION_INPUT || "").toLowerCase() === "true";
|
|
655
|
+
if (!allowMissingLocalization && !hasTokenIds && !hasTokenizerUri) {
|
|
656
|
+
throw new Error(
|
|
657
|
+
"MODEL_UNLEARN preflight failed: missing localization input. Provide config.parameters.target.tokenIds or a tokenizer URI in config.target_config.tokenizer.uri / config.parameters.tokenizer.uri / config.parameters.tokenizer_uri / model.tokenizer_uri."
|
|
658
|
+
);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
};
|
|
662
|
+
|
|
663
|
+
// src/types.ts
|
|
664
|
+
var IntegrationType = /* @__PURE__ */ ((IntegrationType2) => {
|
|
665
|
+
IntegrationType2["SLACK"] = "slack";
|
|
666
|
+
IntegrationType2["CONFLUENCE"] = "confluence";
|
|
667
|
+
IntegrationType2["GOOGLE_DRIVE"] = "google_drive";
|
|
668
|
+
IntegrationType2["ZENDESK"] = "zendesk";
|
|
669
|
+
IntegrationType2["NOTION"] = "notion";
|
|
670
|
+
IntegrationType2["LANGCHAIN"] = "langchain";
|
|
671
|
+
IntegrationType2["OPENROUTER"] = "openrouter";
|
|
672
|
+
IntegrationType2["OPENAI"] = "openai";
|
|
673
|
+
IntegrationType2["CUSTOM"] = "custom";
|
|
674
|
+
return IntegrationType2;
|
|
675
|
+
})(IntegrationType || {});
|
|
676
|
+
var IntegrationMode = /* @__PURE__ */ ((IntegrationMode2) => {
|
|
677
|
+
IntegrationMode2["MODE_A_BLACKBOX"] = "mode_a_blackbox";
|
|
678
|
+
IntegrationMode2["MODE_B_WHITEBOX"] = "mode_b_whitebox";
|
|
679
|
+
return IntegrationMode2;
|
|
680
|
+
})(IntegrationMode || {});
|
|
681
|
+
var AccessLevel = /* @__PURE__ */ ((AccessLevel2) => {
|
|
682
|
+
AccessLevel2["LAYER_A_ONLY"] = "layer_a_only";
|
|
683
|
+
AccessLevel2["LAYER_A_AND_B"] = "layer_a_and_b";
|
|
684
|
+
return AccessLevel2;
|
|
685
|
+
})(AccessLevel || {});
|
|
686
|
+
|
|
687
|
+
// src/whitebox.ts
|
|
688
|
+
import * as crypto from "crypto";
|
|
689
|
+
|
|
690
|
+
// src/quality-gate.ts
|
|
691
|
+
var WHITEBOX_QUALITY_GATE_PRESETS = {
|
|
692
|
+
balanced: {
|
|
693
|
+
requireEvaluation: false,
|
|
694
|
+
maxLeakScore: 0.05,
|
|
695
|
+
allowedVerdicts: ["PASS", "REVIEW"],
|
|
696
|
+
minChangedTensorCount: 1,
|
|
697
|
+
minChangedParamCount: 1,
|
|
698
|
+
requireModelHashTransition: true,
|
|
699
|
+
requireLocalization: false,
|
|
700
|
+
minLocalizationTokenCoverage: 0.5,
|
|
701
|
+
minLocalizedParamCount: 1,
|
|
702
|
+
minLocalizationConfidence: 0.6
|
|
703
|
+
},
|
|
704
|
+
strict: {
|
|
705
|
+
requireEvaluation: true,
|
|
706
|
+
maxLeakScore: 0.03,
|
|
707
|
+
allowedVerdicts: ["PASS"],
|
|
708
|
+
minChangedTensorCount: 1,
|
|
709
|
+
minChangedParamCount: 1,
|
|
710
|
+
requireModelHashTransition: true,
|
|
711
|
+
requireLocalization: true,
|
|
712
|
+
minLocalizationTokenCoverage: 0.5,
|
|
713
|
+
minLocalizedParamCount: 1,
|
|
714
|
+
minLocalizationConfidence: 0.6
|
|
715
|
+
}
|
|
716
|
+
};
|
|
717
|
+
var WHITEBOX_QUALITY_GATE_PRESET_EXPLANATIONS = {
|
|
718
|
+
balanced: "Balanced gate for faster rollout. Allows PASS/REVIEW and can run without evaluator output.",
|
|
719
|
+
strict: "Strict gate for production. Requires evaluator output, localization evidence, and PASS verdict only."
|
|
720
|
+
};
|
|
721
|
+
var DEFAULT_WHITEBOX_QUALITY_GATE_POLICY = {
|
|
722
|
+
requireEvaluation: false,
|
|
723
|
+
maxLeakScore: 0.05,
|
|
724
|
+
allowedVerdicts: ["PASS", "REVIEW"],
|
|
725
|
+
minChangedTensorCount: 1,
|
|
726
|
+
minChangedParamCount: 1,
|
|
727
|
+
requireModelHashTransition: true,
|
|
728
|
+
requireLocalization: false,
|
|
729
|
+
minLocalizationTokenCoverage: 0.5,
|
|
730
|
+
minLocalizedParamCount: 1,
|
|
731
|
+
minLocalizationConfidence: 0.6
|
|
732
|
+
};
|
|
733
|
+
var resolveWhiteboxQualityGatePolicy = (preset = "balanced", overrides) => {
|
|
734
|
+
return {
|
|
735
|
+
...WHITEBOX_QUALITY_GATE_PRESETS[preset],
|
|
736
|
+
...overrides || {}
|
|
737
|
+
};
|
|
423
738
|
};
|
|
739
|
+
var evaluateWhiteboxQualityGate = (unlearning, evaluation, policyOverrides) => {
|
|
740
|
+
const policy = {
|
|
741
|
+
...resolveWhiteboxQualityGatePolicy("balanced"),
|
|
742
|
+
...policyOverrides || {}
|
|
743
|
+
};
|
|
744
|
+
const reasons = [];
|
|
745
|
+
const changedTensors = Number(unlearning.changedTensorCount || 0);
|
|
746
|
+
const changedParams = Number(unlearning.changedParamCount || 0);
|
|
747
|
+
const minChangedTensors = Number(policy.minChangedTensorCount || 0);
|
|
748
|
+
const minChangedParams = Number(policy.minChangedParamCount || 0);
|
|
749
|
+
if (changedTensors < minChangedTensors) {
|
|
750
|
+
reasons.push(`Changed tensor count ${changedTensors} is below minimum ${minChangedTensors}.`);
|
|
751
|
+
}
|
|
752
|
+
if (minChangedParams > 0 && changedParams < minChangedParams) {
|
|
753
|
+
reasons.push(`Changed parameter count ${changedParams} is below minimum ${minChangedParams}.`);
|
|
754
|
+
}
|
|
755
|
+
if (policy.requireModelHashTransition) {
|
|
756
|
+
const before = (unlearning.modelBeforeSha256 || "").trim();
|
|
757
|
+
const after = (unlearning.modelAfterSha256 || "").trim();
|
|
758
|
+
if (!before || !after) {
|
|
759
|
+
reasons.push("Model hash transition is required but before/after hash is missing.");
|
|
760
|
+
} else if (before === after) {
|
|
761
|
+
reasons.push("Model hash did not change after unlearning.");
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
if (policy.requireEvaluation && !evaluation) {
|
|
765
|
+
reasons.push("Evaluation output is required but missing.");
|
|
766
|
+
}
|
|
767
|
+
if (policy.requireLocalization) {
|
|
768
|
+
const localization = unlearning.localization;
|
|
769
|
+
if (!localization) {
|
|
770
|
+
reasons.push("Localization output is required but missing.");
|
|
771
|
+
} else {
|
|
772
|
+
const tokenCoverage = Number(localization.tokenCoverage);
|
|
773
|
+
if (!Number.isFinite(tokenCoverage) || tokenCoverage < 0 || tokenCoverage > 1) {
|
|
774
|
+
reasons.push("Localization tokenCoverage must be a finite number in [0, 1].");
|
|
775
|
+
} else if (tokenCoverage < Number(policy.minLocalizationTokenCoverage)) {
|
|
776
|
+
reasons.push(
|
|
777
|
+
`Localization tokenCoverage ${tokenCoverage} is below minimum ${policy.minLocalizationTokenCoverage}.`
|
|
778
|
+
);
|
|
779
|
+
}
|
|
780
|
+
const localizedParamCount = Number(localization.localizedParamCount || 0);
|
|
781
|
+
if (localizedParamCount < Number(policy.minLocalizedParamCount)) {
|
|
782
|
+
reasons.push(
|
|
783
|
+
`Localization localizedParamCount ${localizedParamCount} is below minimum ${policy.minLocalizedParamCount}.`
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
const confidence = Number(localization.confidence);
|
|
787
|
+
if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) {
|
|
788
|
+
reasons.push("Localization confidence must be a finite number in [0, 1].");
|
|
789
|
+
} else if (confidence < Number(policy.minLocalizationConfidence)) {
|
|
790
|
+
reasons.push(
|
|
791
|
+
`Localization confidence ${confidence} is below minimum ${policy.minLocalizationConfidence}.`
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
if (evaluation) {
|
|
797
|
+
const maxLeak = Number(policy.maxLeakScore);
|
|
798
|
+
if (!Number.isNaN(maxLeak) && evaluation.leakScore > maxLeak) {
|
|
799
|
+
reasons.push(`Leak score ${evaluation.leakScore} is above max ${maxLeak}.`);
|
|
800
|
+
}
|
|
801
|
+
const allowedVerdicts = policy.allowedVerdicts || [];
|
|
802
|
+
if (allowedVerdicts.length > 0 && !allowedVerdicts.includes(evaluation.finalVerdict)) {
|
|
803
|
+
reasons.push(`Final verdict ${evaluation.finalVerdict} is not allowed by policy.`);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
pass: reasons.length === 0,
|
|
808
|
+
reasons,
|
|
809
|
+
policy
|
|
810
|
+
};
|
|
811
|
+
};
|
|
812
|
+
|
|
813
|
+
// src/whitebox.ts
|
|
814
|
+
var buildModelUnlearningPayload = (input) => {
|
|
815
|
+
return {
|
|
816
|
+
claim: input.claim,
|
|
817
|
+
config: {
|
|
818
|
+
target_adapter: input.targetAdapter || "CUSTOM_WHITEBOX_BACKEND",
|
|
819
|
+
target_config: {
|
|
820
|
+
model: input.model
|
|
821
|
+
},
|
|
822
|
+
sensitivity: input.sensitivity || "high",
|
|
823
|
+
parameters: {
|
|
824
|
+
target: input.target,
|
|
825
|
+
plan: input.plan,
|
|
826
|
+
...input.extraParameters
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
};
|
|
831
|
+
var defaultLogger = {
|
|
832
|
+
info(message, meta) {
|
|
833
|
+
console.log(`[whitebox-worker] ${message}`, meta || {});
|
|
834
|
+
},
|
|
835
|
+
warn(message, meta) {
|
|
836
|
+
console.warn(`[whitebox-worker] ${message}`, meta || {});
|
|
837
|
+
},
|
|
838
|
+
error(message, meta) {
|
|
839
|
+
console.error(`[whitebox-worker] ${message}`, meta || {});
|
|
840
|
+
}
|
|
841
|
+
};
|
|
842
|
+
var safeErrorMessage = (error) => {
|
|
843
|
+
if (error instanceof Error) {
|
|
844
|
+
return error.message.slice(0, 500);
|
|
845
|
+
}
|
|
846
|
+
return String(error).slice(0, 500);
|
|
847
|
+
};
|
|
848
|
+
var toJobError = (error) => {
|
|
849
|
+
const message = safeErrorMessage(error);
|
|
850
|
+
const isValidationFailure = message.startsWith("VALIDATION_ERROR:") || message.startsWith("QUALITY_GATE_FAILED:") || message.startsWith("ADAPTER_OUTPUT_INVALID:");
|
|
851
|
+
return {
|
|
852
|
+
error: {
|
|
853
|
+
code: isValidationFailure ? "VALIDATION_ERROR" : "WORKER_ERROR",
|
|
854
|
+
message
|
|
855
|
+
}
|
|
856
|
+
};
|
|
857
|
+
};
|
|
858
|
+
var toClaim = (job) => {
|
|
859
|
+
const claim = job.payload?.claim;
|
|
860
|
+
if (!claim) {
|
|
861
|
+
throw new Error("VALIDATION_ERROR: job payload.claim is required.");
|
|
862
|
+
}
|
|
863
|
+
if (typeof claim.claim_payload !== "string" || !claim.claim_payload.trim()) {
|
|
864
|
+
throw new Error("VALIDATION_ERROR: job payload.claim.claim_payload must be a non-empty string.");
|
|
865
|
+
}
|
|
866
|
+
return {
|
|
867
|
+
claim_type: claim.claim_type || "CONCEPT",
|
|
868
|
+
claim_payload: claim.claim_payload,
|
|
869
|
+
scope: claim.scope || "global",
|
|
870
|
+
assertion: claim.assertion || "must_not_be_recalled"
|
|
871
|
+
};
|
|
872
|
+
};
|
|
873
|
+
var toConfig = (job) => {
|
|
874
|
+
const config = job.payload?.config;
|
|
875
|
+
if (!config) {
|
|
876
|
+
throw new Error("VALIDATION_ERROR: job payload.config is required.");
|
|
877
|
+
}
|
|
878
|
+
return {
|
|
879
|
+
target_adapter: config.target_adapter || "CUSTOM_WHITEBOX_BACKEND",
|
|
880
|
+
target_config: config.target_config || {},
|
|
881
|
+
sensitivity: config.sensitivity || "high",
|
|
882
|
+
parameters: config.parameters || {}
|
|
883
|
+
};
|
|
884
|
+
};
|
|
885
|
+
var resolveModel = (config) => {
|
|
886
|
+
const modelFromTargetConfig = config.target_config?.model;
|
|
887
|
+
const modelFromParameters = config.parameters?.model;
|
|
888
|
+
const model = modelFromParameters || modelFromTargetConfig;
|
|
889
|
+
if (!model || !model.uri) {
|
|
890
|
+
throw new Error("MODEL_UNLEARN job missing model URI in config.target_config.model or config.parameters.model");
|
|
891
|
+
}
|
|
892
|
+
return model;
|
|
893
|
+
};
|
|
894
|
+
var resolveTarget = (claim, config) => {
|
|
895
|
+
const targetFromParameters = config.parameters?.target;
|
|
896
|
+
if (targetFromParameters) {
|
|
897
|
+
return targetFromParameters;
|
|
898
|
+
}
|
|
899
|
+
return {
|
|
900
|
+
text: claim.claim_payload,
|
|
901
|
+
selector: {
|
|
902
|
+
claim_type: claim.claim_type,
|
|
903
|
+
scope: claim.scope
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
};
|
|
907
|
+
var resolvePlan = (config) => {
|
|
908
|
+
const planFromParameters = config.parameters?.plan;
|
|
909
|
+
if (planFromParameters?.method) {
|
|
910
|
+
return planFromParameters;
|
|
911
|
+
}
|
|
912
|
+
const fallbackMethod = typeof config.parameters?.method === "string" ? config.parameters.method : "gradient_surgery";
|
|
913
|
+
const fallbackHyperparams = config.parameters?.hyperparameters || {};
|
|
914
|
+
return {
|
|
915
|
+
method: fallbackMethod,
|
|
916
|
+
hyperparameters: fallbackHyperparams
|
|
917
|
+
};
|
|
918
|
+
};
|
|
919
|
+
var isNonArrayRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
920
|
+
var resolveQualityGatePresetCandidate = (value) => {
|
|
921
|
+
if (typeof value !== "string") {
|
|
922
|
+
return void 0;
|
|
923
|
+
}
|
|
924
|
+
const normalized = value.trim().toLowerCase();
|
|
925
|
+
if (normalized === "strict" || normalized === "balanced") {
|
|
926
|
+
return normalized;
|
|
927
|
+
}
|
|
928
|
+
return void 0;
|
|
929
|
+
};
|
|
930
|
+
var resolvePerJobQualityGatePolicy = (workerPolicy, config, plan) => {
|
|
931
|
+
const configParams = isNonArrayRecord(config.parameters) ? config.parameters : {};
|
|
932
|
+
const planHyperparameters = isNonArrayRecord(plan.hyperparameters) ? plan.hyperparameters : {};
|
|
933
|
+
const preset = resolveQualityGatePresetCandidate(
|
|
934
|
+
planHyperparameters.quality_gate_preset || planHyperparameters.qualityGatePreset || configParams.quality_gate_preset || configParams.qualityGatePreset
|
|
935
|
+
);
|
|
936
|
+
const overrideFromPlan = isNonArrayRecord(planHyperparameters.quality_gate_policy) ? planHyperparameters.quality_gate_policy : isNonArrayRecord(planHyperparameters.qualityGatePolicy) ? planHyperparameters.qualityGatePolicy : {};
|
|
937
|
+
const overrideFromConfig = isNonArrayRecord(configParams.quality_gate_policy) ? configParams.quality_gate_policy : isNonArrayRecord(configParams.qualityGatePolicy) ? configParams.qualityGatePolicy : {};
|
|
938
|
+
const hasOverrides = Object.keys(overrideFromPlan).length > 0 || Object.keys(overrideFromConfig).length > 0;
|
|
939
|
+
if (!preset && !hasOverrides) {
|
|
940
|
+
return {
|
|
941
|
+
policy: workerPolicy,
|
|
942
|
+
preset: null
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
const presetPolicy = preset ? resolveWhiteboxQualityGatePolicy(preset) : workerPolicy;
|
|
946
|
+
return {
|
|
947
|
+
policy: {
|
|
948
|
+
...presetPolicy,
|
|
949
|
+
...overrideFromConfig,
|
|
950
|
+
...overrideFromPlan
|
|
951
|
+
},
|
|
952
|
+
preset: preset || null
|
|
953
|
+
};
|
|
954
|
+
};
|
|
955
|
+
var assertUnlearningOutput = (value) => {
|
|
956
|
+
const updatedModel = value?.updatedModel;
|
|
957
|
+
if (!updatedModel || typeof updatedModel.uri !== "string" || !updatedModel.uri.trim()) {
|
|
958
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: updatedModel.uri must be a non-empty string.");
|
|
959
|
+
}
|
|
960
|
+
if (!Number.isFinite(value.changedTensorCount) || value.changedTensorCount < 0) {
|
|
961
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: changedTensorCount must be a finite number >= 0.");
|
|
962
|
+
}
|
|
963
|
+
if (typeof value.changedParamCount !== "undefined" && (!Number.isFinite(value.changedParamCount) || value.changedParamCount < 0)) {
|
|
964
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: changedParamCount must be a finite number >= 0 when provided.");
|
|
965
|
+
}
|
|
966
|
+
if (typeof value.metrics !== "undefined" && !isNonArrayRecord(value.metrics)) {
|
|
967
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: metrics must be an object when provided.");
|
|
968
|
+
}
|
|
969
|
+
if (typeof value.artifacts !== "undefined") {
|
|
970
|
+
if (!Array.isArray(value.artifacts)) {
|
|
971
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: artifacts must be an array when provided.");
|
|
972
|
+
}
|
|
973
|
+
for (const artifact of value.artifacts) {
|
|
974
|
+
if (!artifact || typeof artifact.name !== "string" || typeof artifact.uri !== "string") {
|
|
975
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: each artifact requires string name and uri.");
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
var assertEvaluationOutput = (value) => {
|
|
981
|
+
if (!value || !["PASS", "FAIL", "REVIEW"].includes(value.finalVerdict)) {
|
|
982
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: evaluation.finalVerdict must be PASS | FAIL | REVIEW.");
|
|
983
|
+
}
|
|
984
|
+
if (!Number.isFinite(value.leakScore) || value.leakScore < 0) {
|
|
985
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: evaluation.leakScore must be a finite number >= 0.");
|
|
986
|
+
}
|
|
987
|
+
if (typeof value.details !== "undefined" && !isNonArrayRecord(value.details)) {
|
|
988
|
+
throw new Error("ADAPTER_OUTPUT_INVALID: evaluation.details must be an object when provided.");
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
var sha256Hex = (value) => {
|
|
992
|
+
return crypto.createHash("sha256").update(value, "utf8").digest("hex");
|
|
993
|
+
};
|
|
994
|
+
var buildResultClaim = (claim, mode) => {
|
|
995
|
+
if (mode === "raw") {
|
|
996
|
+
return claim;
|
|
997
|
+
}
|
|
998
|
+
const base = {
|
|
999
|
+
claim_type: claim.claim_type,
|
|
1000
|
+
scope: claim.scope,
|
|
1001
|
+
assertion: claim.assertion
|
|
1002
|
+
};
|
|
1003
|
+
if (mode === "omit") {
|
|
1004
|
+
return base;
|
|
1005
|
+
}
|
|
1006
|
+
const payload = typeof claim.claim_payload === "string" ? claim.claim_payload : "";
|
|
1007
|
+
return {
|
|
1008
|
+
...base,
|
|
1009
|
+
payload_hash: sha256Hex(payload),
|
|
1010
|
+
claim_payload_sha256: sha256Hex(payload),
|
|
1011
|
+
claim_payload_length: payload.length
|
|
1012
|
+
};
|
|
1013
|
+
};
|
|
1014
|
+
var WhiteboxWorker = class {
|
|
1015
|
+
constructor(client, adapter, options) {
|
|
1016
|
+
this.client = client;
|
|
1017
|
+
this.adapter = adapter;
|
|
1018
|
+
this.options = options;
|
|
1019
|
+
this.running = false;
|
|
1020
|
+
this.loopPromise = null;
|
|
1021
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 2e3;
|
|
1022
|
+
this.claimBatchSize = options.claimBatchSize ?? 1;
|
|
1023
|
+
this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 2e4;
|
|
1024
|
+
this.supportedJobTypes = options.supportedJobTypes ?? ["MODEL_UNLEARN"];
|
|
1025
|
+
this.qualityGatePolicy = {
|
|
1026
|
+
...DEFAULT_WHITEBOX_QUALITY_GATE_POLICY,
|
|
1027
|
+
...options.qualityGatePolicy || {}
|
|
1028
|
+
};
|
|
1029
|
+
this.qualityGateOnFailure = options.qualityGateOnFailure || "fail_job";
|
|
1030
|
+
this.resultClaimMode = options.resultClaimMode || "hash";
|
|
1031
|
+
this.logger = options.logger ?? defaultLogger;
|
|
1032
|
+
}
|
|
1033
|
+
async start() {
|
|
1034
|
+
if (this.running) {
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
this.running = true;
|
|
1038
|
+
this.logger.info("worker started", {
|
|
1039
|
+
projectId: this.options.projectId,
|
|
1040
|
+
adapter: this.adapter.name,
|
|
1041
|
+
claimBatchSize: this.claimBatchSize
|
|
1042
|
+
});
|
|
1043
|
+
this.loopPromise = this.runLoop();
|
|
1044
|
+
}
|
|
1045
|
+
async stop() {
|
|
1046
|
+
this.running = false;
|
|
1047
|
+
if (this.loopPromise) {
|
|
1048
|
+
await this.loopPromise;
|
|
1049
|
+
this.loopPromise = null;
|
|
1050
|
+
}
|
|
1051
|
+
this.logger.info("worker stopped", { projectId: this.options.projectId });
|
|
1052
|
+
}
|
|
1053
|
+
async runOnce() {
|
|
1054
|
+
const jobs = await this.client.claimJobs(this.options.projectId, {
|
|
1055
|
+
limit: this.claimBatchSize,
|
|
1056
|
+
types: this.supportedJobTypes
|
|
1057
|
+
});
|
|
1058
|
+
if (!jobs.length) {
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
for (const job of jobs) {
|
|
1062
|
+
await this.processClaimedJob(job);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
async runLoop() {
|
|
1066
|
+
while (this.running) {
|
|
1067
|
+
try {
|
|
1068
|
+
await this.runOnce();
|
|
1069
|
+
} catch (error) {
|
|
1070
|
+
this.logger.error("worker loop error", {
|
|
1071
|
+
projectId: this.options.projectId,
|
|
1072
|
+
error: safeErrorMessage(error)
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
await new Promise((resolve) => setTimeout(resolve, this.pollIntervalMs));
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
async processClaimedJob(job) {
|
|
1079
|
+
const claimId = typeof job.lastClaimId === "string" ? job.lastClaimId : void 0;
|
|
1080
|
+
if (!this.supportedJobTypes.includes(job.type)) {
|
|
1081
|
+
this.logger.warn("unsupported job type claimed", {
|
|
1082
|
+
jobId: job.id,
|
|
1083
|
+
type: job.type
|
|
1084
|
+
});
|
|
1085
|
+
await this.client.failJob(this.options.projectId, job.id, {
|
|
1086
|
+
error: {
|
|
1087
|
+
code: "VALIDATION_ERROR",
|
|
1088
|
+
message: `Unsupported job type: ${job.type}`
|
|
1089
|
+
}
|
|
1090
|
+
}, { claimId });
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
const context = {
|
|
1094
|
+
projectId: this.options.projectId,
|
|
1095
|
+
jobId: job.id,
|
|
1096
|
+
correlationId: claimId
|
|
1097
|
+
};
|
|
1098
|
+
let heartbeatTimer = null;
|
|
1099
|
+
const heartbeat = async () => {
|
|
1100
|
+
try {
|
|
1101
|
+
await this.client.heartbeatJob(this.options.projectId, job.id, { claimId });
|
|
1102
|
+
} catch (error) {
|
|
1103
|
+
this.logger.warn("heartbeat failed", {
|
|
1104
|
+
jobId: job.id,
|
|
1105
|
+
error: safeErrorMessage(error)
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
try {
|
|
1110
|
+
const claim = toClaim(job);
|
|
1111
|
+
const config = toConfig(job);
|
|
1112
|
+
const model = resolveModel(config);
|
|
1113
|
+
const target = resolveTarget(claim, config);
|
|
1114
|
+
const plan = resolvePlan(config);
|
|
1115
|
+
const perJobQualityGate = resolvePerJobQualityGatePolicy(this.qualityGatePolicy, config, plan);
|
|
1116
|
+
heartbeatTimer = setInterval(heartbeat, this.heartbeatIntervalMs);
|
|
1117
|
+
await heartbeat();
|
|
1118
|
+
const unlearningOutput = await this.adapter.runUnlearning(
|
|
1119
|
+
{ model, target, plan, claim, config },
|
|
1120
|
+
context
|
|
1121
|
+
);
|
|
1122
|
+
assertUnlearningOutput(unlearningOutput);
|
|
1123
|
+
let evaluationOutput;
|
|
1124
|
+
if (this.adapter.runEvaluation) {
|
|
1125
|
+
evaluationOutput = await this.adapter.runEvaluation(
|
|
1126
|
+
{
|
|
1127
|
+
model: unlearningOutput.updatedModel,
|
|
1128
|
+
baselineModel: model,
|
|
1129
|
+
claim,
|
|
1130
|
+
config,
|
|
1131
|
+
probes: config.parameters?.probes || []
|
|
1132
|
+
},
|
|
1133
|
+
context
|
|
1134
|
+
);
|
|
1135
|
+
assertEvaluationOutput(evaluationOutput);
|
|
1136
|
+
}
|
|
1137
|
+
const qualityGate = evaluateWhiteboxQualityGate(
|
|
1138
|
+
unlearningOutput,
|
|
1139
|
+
evaluationOutput,
|
|
1140
|
+
perJobQualityGate.policy
|
|
1141
|
+
);
|
|
1142
|
+
if (!qualityGate.pass && this.qualityGateOnFailure === "fail_job") {
|
|
1143
|
+
throw new Error(`QUALITY_GATE_FAILED: ${qualityGate.reasons.join(" | ")}`);
|
|
1144
|
+
}
|
|
1145
|
+
const finalVerdict = qualityGate.pass ? evaluationOutput?.finalVerdict || "REVIEW" : "REVIEW";
|
|
1146
|
+
const result = {
|
|
1147
|
+
result: {
|
|
1148
|
+
worker: {
|
|
1149
|
+
adapter: this.adapter.name,
|
|
1150
|
+
mode: "whitebox"
|
|
1151
|
+
},
|
|
1152
|
+
claim: buildResultClaim(claim, this.resultClaimMode),
|
|
1153
|
+
plan,
|
|
1154
|
+
unlearning: unlearningOutput,
|
|
1155
|
+
evaluation: evaluationOutput || null,
|
|
1156
|
+
quality_gate: qualityGate,
|
|
1157
|
+
quality_gate_preset: perJobQualityGate.preset,
|
|
1158
|
+
final_verdict: finalVerdict,
|
|
1159
|
+
report_hash: unlearningOutput.modelAfterSha256 || null,
|
|
1160
|
+
privacy: {
|
|
1161
|
+
claim_mode: this.resultClaimMode
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
};
|
|
1165
|
+
await this.client.completeJob(this.options.projectId, job.id, result, { claimId });
|
|
1166
|
+
this.logger.info("job completed", {
|
|
1167
|
+
jobId: job.id,
|
|
1168
|
+
type: job.type,
|
|
1169
|
+
adapter: this.adapter.name
|
|
1170
|
+
});
|
|
1171
|
+
} catch (error) {
|
|
1172
|
+
this.logger.error("job failed", {
|
|
1173
|
+
jobId: job.id,
|
|
1174
|
+
type: job.type,
|
|
1175
|
+
error: safeErrorMessage(error)
|
|
1176
|
+
});
|
|
1177
|
+
await this.client.failJob(this.options.projectId, job.id, toJobError(error), { claimId });
|
|
1178
|
+
} finally {
|
|
1179
|
+
if (heartbeatTimer) {
|
|
1180
|
+
clearInterval(heartbeatTimer);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
};
|
|
1185
|
+
|
|
1186
|
+
// src/native-adapters.ts
|
|
1187
|
+
import { spawn } from "child_process";
|
|
1188
|
+
var DEFAULT_ADAPTER_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
1189
|
+
var LocalCommandTrainingAdapter = class {
|
|
1190
|
+
constructor(options) {
|
|
1191
|
+
this.options = options;
|
|
1192
|
+
this.name = options.name || "local-command-adapter";
|
|
1193
|
+
}
|
|
1194
|
+
async runUnlearning(input, context) {
|
|
1195
|
+
const spec = resolveCommandSpec(this.options.unlearning, input, context);
|
|
1196
|
+
const output = await runJsonCommand(
|
|
1197
|
+
spec,
|
|
1198
|
+
{
|
|
1199
|
+
mode: "unlearning",
|
|
1200
|
+
input,
|
|
1201
|
+
context
|
|
1202
|
+
},
|
|
1203
|
+
this.options.timeoutMs ?? DEFAULT_ADAPTER_TIMEOUT_MS
|
|
1204
|
+
);
|
|
1205
|
+
return output;
|
|
1206
|
+
}
|
|
1207
|
+
async runEvaluation(input, context) {
|
|
1208
|
+
if (!this.options.evaluation) {
|
|
1209
|
+
throw new Error("LocalCommandTrainingAdapter evaluation command is not configured.");
|
|
1210
|
+
}
|
|
1211
|
+
const spec = resolveCommandSpec(this.options.evaluation, input, context);
|
|
1212
|
+
const output = await runJsonCommand(
|
|
1213
|
+
spec,
|
|
1214
|
+
{
|
|
1215
|
+
mode: "evaluation",
|
|
1216
|
+
input,
|
|
1217
|
+
context
|
|
1218
|
+
},
|
|
1219
|
+
this.options.timeoutMs ?? DEFAULT_ADAPTER_TIMEOUT_MS
|
|
1220
|
+
);
|
|
1221
|
+
return output;
|
|
1222
|
+
}
|
|
1223
|
+
};
|
|
1224
|
+
var HttpTrainingAdapter = class {
|
|
1225
|
+
constructor(options) {
|
|
1226
|
+
this.options = options;
|
|
1227
|
+
this.name = options.name || "http-training-adapter";
|
|
1228
|
+
}
|
|
1229
|
+
async runUnlearning(input, context) {
|
|
1230
|
+
const output = await postJson(
|
|
1231
|
+
this.options.unlearningUrl,
|
|
1232
|
+
{
|
|
1233
|
+
mode: "unlearning",
|
|
1234
|
+
input,
|
|
1235
|
+
context
|
|
1236
|
+
},
|
|
1237
|
+
this.options.headers,
|
|
1238
|
+
this.options.timeoutMs ?? DEFAULT_ADAPTER_TIMEOUT_MS
|
|
1239
|
+
);
|
|
1240
|
+
return output;
|
|
1241
|
+
}
|
|
1242
|
+
async runEvaluation(input, context) {
|
|
1243
|
+
if (!this.options.evaluationUrl) {
|
|
1244
|
+
throw new Error("HttpTrainingAdapter evaluationUrl is not configured.");
|
|
1245
|
+
}
|
|
1246
|
+
const output = await postJson(
|
|
1247
|
+
this.options.evaluationUrl,
|
|
1248
|
+
{
|
|
1249
|
+
mode: "evaluation",
|
|
1250
|
+
input,
|
|
1251
|
+
context
|
|
1252
|
+
},
|
|
1253
|
+
this.options.headers,
|
|
1254
|
+
this.options.timeoutMs ?? DEFAULT_ADAPTER_TIMEOUT_MS
|
|
1255
|
+
);
|
|
1256
|
+
return output;
|
|
1257
|
+
}
|
|
1258
|
+
};
|
|
1259
|
+
var createNativeTrainingAdapter = (config) => {
|
|
1260
|
+
if (config.provider === "local_command") {
|
|
1261
|
+
const { provider: _provider2, ...rest2 } = config;
|
|
1262
|
+
return new LocalCommandTrainingAdapter(rest2);
|
|
1263
|
+
}
|
|
1264
|
+
const { provider: _provider, ...rest } = config;
|
|
1265
|
+
return new HttpTrainingAdapter(rest);
|
|
1266
|
+
};
|
|
1267
|
+
function resolveCommandSpec(resolver, input, context) {
|
|
1268
|
+
const resolved = typeof resolver === "function" ? resolver(input, context) : resolver;
|
|
1269
|
+
if (!resolved?.command) {
|
|
1270
|
+
throw new Error("Adapter command is missing.");
|
|
1271
|
+
}
|
|
1272
|
+
return resolved;
|
|
1273
|
+
}
|
|
1274
|
+
async function runJsonCommand(spec, payload, defaultTimeoutMs) {
|
|
1275
|
+
const timeoutMs = spec.timeoutMs ?? defaultTimeoutMs;
|
|
1276
|
+
return new Promise((resolve, reject) => {
|
|
1277
|
+
const child = spawn(spec.command, spec.args || [], {
|
|
1278
|
+
cwd: spec.cwd,
|
|
1279
|
+
env: { ...process.env, ...spec.env || {} },
|
|
1280
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
1281
|
+
});
|
|
1282
|
+
let stdout = "";
|
|
1283
|
+
let stderr = "";
|
|
1284
|
+
let timedOut = false;
|
|
1285
|
+
let hardKillTimer = null;
|
|
1286
|
+
const timer = setTimeout(() => {
|
|
1287
|
+
timedOut = true;
|
|
1288
|
+
child.kill("SIGTERM");
|
|
1289
|
+
hardKillTimer = setTimeout(() => child.kill("SIGKILL"), 1e3);
|
|
1290
|
+
}, timeoutMs);
|
|
1291
|
+
child.stdout.on("data", (chunk) => {
|
|
1292
|
+
stdout += chunk.toString();
|
|
1293
|
+
});
|
|
1294
|
+
child.stderr.on("data", (chunk) => {
|
|
1295
|
+
stderr += chunk.toString();
|
|
1296
|
+
});
|
|
1297
|
+
child.on("error", (error) => {
|
|
1298
|
+
clearTimeout(timer);
|
|
1299
|
+
if (hardKillTimer) clearTimeout(hardKillTimer);
|
|
1300
|
+
reject(error);
|
|
1301
|
+
});
|
|
1302
|
+
child.on("close", (code) => {
|
|
1303
|
+
clearTimeout(timer);
|
|
1304
|
+
if (hardKillTimer) clearTimeout(hardKillTimer);
|
|
1305
|
+
if (timedOut) {
|
|
1306
|
+
reject(new Error(`Adapter command timed out after ${timeoutMs}ms: ${spec.command}`));
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
if (code !== 0) {
|
|
1310
|
+
reject(
|
|
1311
|
+
new Error(
|
|
1312
|
+
`Adapter command failed (${code}): ${spec.command} ${(spec.args || []).join(" ")}; stderr=${stderr.trim()}`
|
|
1313
|
+
)
|
|
1314
|
+
);
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
const trimmed = stdout.trim();
|
|
1318
|
+
if (!trimmed) {
|
|
1319
|
+
reject(new Error(`Adapter command returned empty stdout: ${spec.command}`));
|
|
1320
|
+
return;
|
|
1321
|
+
}
|
|
1322
|
+
try {
|
|
1323
|
+
resolve(JSON.parse(trimmed));
|
|
1324
|
+
} catch {
|
|
1325
|
+
reject(new Error(`Adapter command output is not valid JSON: ${trimmed.slice(0, 800)}`));
|
|
1326
|
+
}
|
|
1327
|
+
});
|
|
1328
|
+
if (spec.stdinMode !== "none") {
|
|
1329
|
+
try {
|
|
1330
|
+
child.stdin.write(JSON.stringify(payload));
|
|
1331
|
+
} catch (error) {
|
|
1332
|
+
clearTimeout(timer);
|
|
1333
|
+
if (hardKillTimer) clearTimeout(hardKillTimer);
|
|
1334
|
+
reject(error);
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
child.stdin.end();
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
async function postJson(url, body, headers, timeoutMs) {
|
|
1342
|
+
const controller = new AbortController();
|
|
1343
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
1344
|
+
try {
|
|
1345
|
+
const response = await fetch(url, {
|
|
1346
|
+
method: "POST",
|
|
1347
|
+
headers: {
|
|
1348
|
+
"content-type": "application/json",
|
|
1349
|
+
...headers || {}
|
|
1350
|
+
},
|
|
1351
|
+
body: JSON.stringify(body),
|
|
1352
|
+
signal: controller.signal
|
|
1353
|
+
});
|
|
1354
|
+
const text = await response.text();
|
|
1355
|
+
if (!response.ok) {
|
|
1356
|
+
throw new Error(`HTTP adapter request failed (${response.status}): ${text.slice(0, 800)}`);
|
|
1357
|
+
}
|
|
1358
|
+
if (!text.trim()) {
|
|
1359
|
+
throw new Error(`HTTP adapter returned empty response: ${url}`);
|
|
1360
|
+
}
|
|
1361
|
+
try {
|
|
1362
|
+
return JSON.parse(text);
|
|
1363
|
+
} catch {
|
|
1364
|
+
throw new Error(`HTTP adapter returned non-JSON response: ${text.slice(0, 800)}`);
|
|
1365
|
+
}
|
|
1366
|
+
} finally {
|
|
1367
|
+
clearTimeout(timeout);
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
// src/deployment-profiles.ts
|
|
1372
|
+
var ENTERPRISE_STRICT_QUALITY_GATE_POLICY = {
|
|
1373
|
+
...WHITEBOX_QUALITY_GATE_PRESETS.strict
|
|
1374
|
+
};
|
|
1375
|
+
function assertDeploymentCompatibility(options) {
|
|
1376
|
+
const normalizedHost = parseHost(options.apiUrl);
|
|
1377
|
+
if (!normalizedHost) {
|
|
1378
|
+
throw new Error(`Invalid FORG3T_API_URL: ${options.apiUrl}`);
|
|
1379
|
+
}
|
|
1380
|
+
if (options.profile !== "customer_airgapped") {
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
if (options.adapterMode === "http" && !options.allowHttpInAirgapped) {
|
|
1384
|
+
throw new Error(
|
|
1385
|
+
"Air-gapped profile rejects adapterMode=http by default. Use local_command or explicitly set allowHttpInAirgapped=true for trusted internal gateways."
|
|
1386
|
+
);
|
|
1387
|
+
}
|
|
1388
|
+
if (!isHostAllowedForAirgapped(normalizedHost, options.allowedApiHosts || [])) {
|
|
1389
|
+
throw new Error(
|
|
1390
|
+
`Air-gapped profile requires a private/control-plane host. Received ${normalizedHost}. Set allowedApiHosts for private DNS hosts if needed.`
|
|
1391
|
+
);
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
function buildWhiteboxWorkerOptions(profile, baseOptions) {
|
|
1395
|
+
const strictMode = profile === "customer_airgapped" || profile === "customer_online";
|
|
1396
|
+
const defaultPolicy = strictMode ? ENTERPRISE_STRICT_QUALITY_GATE_POLICY : DEFAULT_WHITEBOX_QUALITY_GATE_POLICY;
|
|
1397
|
+
const defaultSupportedTypes = ["MODEL_UNLEARN"];
|
|
1398
|
+
return {
|
|
1399
|
+
projectId: baseOptions.projectId,
|
|
1400
|
+
pollIntervalMs: baseOptions.pollIntervalMs ?? 2e3,
|
|
1401
|
+
claimBatchSize: baseOptions.claimBatchSize ?? 1,
|
|
1402
|
+
heartbeatIntervalMs: baseOptions.heartbeatIntervalMs ?? 2e4,
|
|
1403
|
+
supportedJobTypes: baseOptions.supportedJobTypes ?? defaultSupportedTypes,
|
|
1404
|
+
qualityGatePolicy: baseOptions.qualityGatePolicy ?? defaultPolicy,
|
|
1405
|
+
qualityGateOnFailure: baseOptions.qualityGateOnFailure ?? "fail_job",
|
|
1406
|
+
resultClaimMode: baseOptions.resultClaimMode ?? "hash",
|
|
1407
|
+
logger: baseOptions.logger
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
function parseHost(apiUrl) {
|
|
1411
|
+
try {
|
|
1412
|
+
const parsed = new URL(apiUrl);
|
|
1413
|
+
return parsed.hostname.toLowerCase();
|
|
1414
|
+
} catch {
|
|
1415
|
+
return null;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
function isHostAllowedForAirgapped(host, allowedApiHosts) {
|
|
1419
|
+
if (isPrivateHost(host)) {
|
|
1420
|
+
return true;
|
|
1421
|
+
}
|
|
1422
|
+
const allowSet = new Set(allowedApiHosts.map((item) => item.trim().toLowerCase()).filter(Boolean));
|
|
1423
|
+
return allowSet.has(host);
|
|
1424
|
+
}
|
|
1425
|
+
function isPrivateHost(host) {
|
|
1426
|
+
if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
|
|
1427
|
+
return true;
|
|
1428
|
+
}
|
|
1429
|
+
if (host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan")) {
|
|
1430
|
+
return true;
|
|
1431
|
+
}
|
|
1432
|
+
const parts = host.split(".");
|
|
1433
|
+
if (parts.length !== 4 || parts.some((part) => Number.isNaN(Number(part)))) {
|
|
1434
|
+
return false;
|
|
1435
|
+
}
|
|
1436
|
+
const octets = parts.map((part) => Number(part));
|
|
1437
|
+
const [a, b] = octets;
|
|
1438
|
+
if (a === 10) return true;
|
|
1439
|
+
if (a === 127) return true;
|
|
1440
|
+
if (a === 192 && b === 168) return true;
|
|
1441
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
1442
|
+
return false;
|
|
1443
|
+
}
|
|
424
1444
|
export {
|
|
1445
|
+
AccessLevel,
|
|
1446
|
+
DEFAULT_WHITEBOX_QUALITY_GATE_POLICY,
|
|
1447
|
+
ENTERPRISE_STRICT_QUALITY_GATE_POLICY,
|
|
425
1448
|
Forg3tApiConnectionError,
|
|
426
1449
|
Forg3tAuthenticationError,
|
|
427
1450
|
Forg3tClient,
|
|
428
1451
|
Forg3tError,
|
|
429
1452
|
Forg3tNotFoundError,
|
|
430
|
-
|
|
1453
|
+
Forg3tNotImplementedError,
|
|
1454
|
+
Forg3tRateLimitError,
|
|
1455
|
+
HttpTrainingAdapter,
|
|
1456
|
+
IntegrationMode,
|
|
1457
|
+
IntegrationType,
|
|
1458
|
+
LocalCommandTrainingAdapter,
|
|
1459
|
+
WHITEBOX_QUALITY_GATE_PRESETS,
|
|
1460
|
+
WHITEBOX_QUALITY_GATE_PRESET_EXPLANATIONS,
|
|
1461
|
+
WhiteboxWorker,
|
|
1462
|
+
assertDeploymentCompatibility,
|
|
1463
|
+
buildModelUnlearningPayload,
|
|
1464
|
+
buildWhiteboxWorkerOptions,
|
|
1465
|
+
createNativeTrainingAdapter,
|
|
1466
|
+
evaluateWhiteboxQualityGate,
|
|
1467
|
+
resolveWhiteboxQualityGatePolicy
|
|
431
1468
|
};
|