@constal/sdk 5.1.0 → 6.0.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/NOTICE +4 -0
- package/package.json +7 -1
- package/publish/api.json +51 -2
- package/publish/chat-format.d.ts +172 -0
- package/publish/chat-format.js +5989 -0
- package/publish/index.d.ts +576 -167
- package/publish/index.js +1203 -759
package/publish/index.js
CHANGED
|
@@ -81,8 +81,8 @@ function canonicalJson(value) {
|
|
|
81
81
|
if (typeof value === "string") return JSON.stringify(value);
|
|
82
82
|
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
83
83
|
if (typeof value === "object") {
|
|
84
|
-
const
|
|
85
|
-
return `{${Object.keys(
|
|
84
|
+
const record13 = value;
|
|
85
|
+
return `{${Object.keys(record13).sort().filter((key) => record13[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(record13[key])}`).join(",")}}`;
|
|
86
86
|
}
|
|
87
87
|
throw new TypeError(`canonical JSON does not support ${typeof value}`);
|
|
88
88
|
}
|
|
@@ -408,21 +408,21 @@ function validateJsonSchema(value, schema, path = "$") {
|
|
|
408
408
|
if (typeof rule.multipleOf === "number" && Math.abs(value / rule.multipleOf - Math.round(value / rule.multipleOf)) > Number.EPSILON * 8) return `${path} is not a multiple`;
|
|
409
409
|
}
|
|
410
410
|
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
411
|
-
const
|
|
412
|
-
for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in
|
|
411
|
+
const record13 = value;
|
|
412
|
+
for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in record13)) return `${path}.${key} is required`;
|
|
413
413
|
const properties = rule.properties && typeof rule.properties === "object" && !Array.isArray(rule.properties) ? rule.properties : {};
|
|
414
|
-
if (typeof rule.minProperties === "number" && Object.keys(
|
|
415
|
-
if (typeof rule.maxProperties === "number" && Object.keys(
|
|
414
|
+
if (typeof rule.minProperties === "number" && Object.keys(record13).length < rule.minProperties) return `${path} has too few properties`;
|
|
415
|
+
if (typeof rule.maxProperties === "number" && Object.keys(record13).length > rule.maxProperties) return `${path} has too many properties`;
|
|
416
416
|
if (rule.additionalProperties === false) {
|
|
417
|
-
const extra = Object.keys(
|
|
417
|
+
const extra = Object.keys(record13).find((key) => !(key in properties));
|
|
418
418
|
if (extra) return `${path}.${extra} is not allowed`;
|
|
419
419
|
}
|
|
420
|
-
for (const [key, child] of Object.entries(properties)) if (key in
|
|
421
|
-
const error = validateJsonSchema(
|
|
420
|
+
for (const [key, child] of Object.entries(properties)) if (key in record13) {
|
|
421
|
+
const error = validateJsonSchema(record13[key], child, `${path}.${key}`);
|
|
422
422
|
if (error) return error;
|
|
423
423
|
}
|
|
424
|
-
if (rule.additionalProperties && typeof rule.additionalProperties === "object") for (const key of Object.keys(
|
|
425
|
-
const error = validateJsonSchema(
|
|
424
|
+
if (rule.additionalProperties && typeof rule.additionalProperties === "object") for (const key of Object.keys(record13).filter((candidate) => !(candidate in properties))) {
|
|
425
|
+
const error = validateJsonSchema(record13[key], rule.additionalProperties, `${path}.${key}`);
|
|
426
426
|
if (error) return error;
|
|
427
427
|
}
|
|
428
428
|
}
|
|
@@ -534,6 +534,18 @@ function selectableResourceLabels(input) {
|
|
|
534
534
|
};
|
|
535
535
|
return resourceLabelMap(labels, { allowProtected: true });
|
|
536
536
|
}
|
|
537
|
+
function runLabels(input) {
|
|
538
|
+
const labels = {
|
|
539
|
+
...selectableResourceLabels({ ...input.agent, kind: "agent" }),
|
|
540
|
+
"constal.ai/tenant": input.tenant,
|
|
541
|
+
"constal.ai/principal": input.principal,
|
|
542
|
+
"constal.ai/customer": input.customer ?? "none"
|
|
543
|
+
};
|
|
544
|
+
for (const [key, value] of Object.entries(input.tags ?? {})) {
|
|
545
|
+
if (labelKey(key) && !key.startsWith(PROTECTED_RESOURCE_LABEL_PREFIX) && labelValue(value) && !Object.hasOwn(labels, key)) labels[key] = value;
|
|
546
|
+
}
|
|
547
|
+
return resourceLabelMap(labels, { allowProtected: true });
|
|
548
|
+
}
|
|
537
549
|
|
|
538
550
|
// packages/sdk/src/resources.ts
|
|
539
551
|
var RESOURCE_KINDS = [
|
|
@@ -891,7 +903,7 @@ function invocationCredentialUses(value) {
|
|
|
891
903
|
const result = {};
|
|
892
904
|
for (const [slot, raw] of Object.entries(source).sort(([left], [right]) => left.localeCompare(right))) {
|
|
893
905
|
const use = record2(raw), consumer = record2(use?.consumer);
|
|
894
|
-
if (!NAME2.test(slot) || !use || Object.keys(use).some((key) => key !== "binding" && key !== "consumer") || !consumer || Object.keys(consumer).some((key) => !["kind", "delivery", "name"].includes(key)) || !(consumer.kind === "process" && (consumer.delivery === "env" || consumer.delivery === "file") || consumer.kind === "egress" && consumer.delivery === "header") || typeof consumer.name !== "string" || !consumer.name || consumer.name.includes("=") || /[\u0000-\u001f\u007f]/u.test(consumer.name)) throw new TypeError("invocation Credential selection is invalid");
|
|
906
|
+
if (!NAME2.test(slot) || !use || Object.keys(use).some((key) => key !== "binding" && key !== "consumer") || !consumer || (consumer.kind === "resource" ? Object.keys(consumer).length !== 1 || typeof use.binding === "string" : Object.keys(consumer).some((key) => !["kind", "delivery", "name"].includes(key)) || !(consumer.kind === "process" && (consumer.delivery === "env" || consumer.delivery === "file") || consumer.kind === "egress" && consumer.delivery === "header") || typeof consumer.name !== "string" || !consumer.name || consumer.name.includes("=") || /[\u0000-\u001f\u007f]/u.test(consumer.name))) throw new TypeError("invocation Credential selection is invalid");
|
|
895
907
|
result[slot] = { binding: resourceCredentialBinding(use.binding), consumer };
|
|
896
908
|
}
|
|
897
909
|
return result;
|
|
@@ -2293,6 +2305,152 @@ async function evaluatePolicyDefinition(definition, input) {
|
|
|
2293
2305
|
return policyOutcome(await definition.evaluate(input));
|
|
2294
2306
|
}
|
|
2295
2307
|
|
|
2308
|
+
// packages/sdk/src/data-sharing.ts
|
|
2309
|
+
var ACTIONS = ["read", "evaluate", "contribute"];
|
|
2310
|
+
var TERMS = /* @__PURE__ */ new Set(["displayName", "selector", "actions", "prices", "evaluation", "expiresAt"]);
|
|
2311
|
+
var EVALUATION = ["namespace", "agent", "dataset", "scorers", "concurrency", "budgetMicroUsd"];
|
|
2312
|
+
function record5(value) {
|
|
2313
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2314
|
+
}
|
|
2315
|
+
function evaluationPin(value, namespace, kind, name) {
|
|
2316
|
+
const pin = record5(value);
|
|
2317
|
+
let named = false;
|
|
2318
|
+
try {
|
|
2319
|
+
named = typeof pin?.id === "string" && !!resourceName({ environment: "local", tenant: "local", namespace, kind, path: pin.id });
|
|
2320
|
+
} catch {
|
|
2321
|
+
named = false;
|
|
2322
|
+
}
|
|
2323
|
+
if (!pin || !named || Object.keys(pin).length !== 3 || typeof pin.version !== "string" || !pin.version || typeof pin.hash !== "string" || !/^[a-f0-9]{64}$/u.test(pin.hash)) throw new TypeError(`Share evaluation ${name} is invalid`);
|
|
2324
|
+
return { id: pin.id, version: pin.version, hash: pin.hash };
|
|
2325
|
+
}
|
|
2326
|
+
function shareEvaluation(value) {
|
|
2327
|
+
const source = record5(value);
|
|
2328
|
+
if (!source || Object.keys(source).length !== EVALUATION.length || EVALUATION.some((key) => !Object.hasOwn(source, key)) || typeof source.namespace !== "string" || typeof source.agent !== "string") throw new TypeError("Share evaluation is invalid");
|
|
2329
|
+
const namespace = source.namespace;
|
|
2330
|
+
try {
|
|
2331
|
+
resourceName({ environment: "local", tenant: "local", namespace, kind: "agent", path: source.agent });
|
|
2332
|
+
} catch {
|
|
2333
|
+
throw new TypeError("Share evaluation namespace or agent is invalid");
|
|
2334
|
+
}
|
|
2335
|
+
if (!Array.isArray(source.scorers) || source.scorers.length > 32) throw new TypeError("Share evaluation scorers must be at most 32 Scorers");
|
|
2336
|
+
if (!Number.isSafeInteger(source.concurrency) || source.concurrency < 1 || source.concurrency > 32) {
|
|
2337
|
+
throw new TypeError("Share evaluation concurrency must be from 1 to 32");
|
|
2338
|
+
}
|
|
2339
|
+
if (!Number.isSafeInteger(source.budgetMicroUsd) || source.budgetMicroUsd < 1) {
|
|
2340
|
+
throw new TypeError("Share evaluation budgetMicroUsd must be a positive whole microUsd");
|
|
2341
|
+
}
|
|
2342
|
+
return {
|
|
2343
|
+
namespace,
|
|
2344
|
+
agent: source.agent,
|
|
2345
|
+
dataset: evaluationPin(source.dataset, namespace, "dataset", "dataset"),
|
|
2346
|
+
scorers: source.scorers.map((scorer, index) => evaluationPin(scorer, namespace, "scorer", `scorer ${index}`)),
|
|
2347
|
+
concurrency: source.concurrency,
|
|
2348
|
+
budgetMicroUsd: source.budgetMicroUsd
|
|
2349
|
+
};
|
|
2350
|
+
}
|
|
2351
|
+
function sharePrices(value) {
|
|
2352
|
+
if (!Array.isArray(value) || value.length > 32) throw new TypeError("Share prices must be a list of at most 32 rules");
|
|
2353
|
+
return value.map((raw, index) => {
|
|
2354
|
+
const rule = record5(raw);
|
|
2355
|
+
if (!rule || Object.keys(rule).some((key) => key !== "selector" && key !== "microUsd") || !Object.hasOwn(rule, "selector") || !Number.isSafeInteger(rule.microUsd) || rule.microUsd < 0) throw new TypeError(`Share price ${index} is invalid`);
|
|
2356
|
+
return { selector: rule.selector === null ? null : labelSelector(rule.selector), microUsd: rule.microUsd };
|
|
2357
|
+
});
|
|
2358
|
+
}
|
|
2359
|
+
var DATA_SHARE_FEE_BPS = 3e3;
|
|
2360
|
+
function dataShareEarningMicroUsd(priceMicroUsd) {
|
|
2361
|
+
if (!Number.isSafeInteger(priceMicroUsd) || priceMicroUsd < 0) throw new TypeError("a trace's price must be a whole non-negative microUsd");
|
|
2362
|
+
const kept = 1e4 - DATA_SHARE_FEE_BPS;
|
|
2363
|
+
return Math.floor(priceMicroUsd / 1e4) * kept + Math.floor(priceMicroUsd % 1e4 * kept / 1e4);
|
|
2364
|
+
}
|
|
2365
|
+
function shareRequest(value) {
|
|
2366
|
+
const source = record5(value);
|
|
2367
|
+
const unknown = source && Object.keys(source).find((key) => !TERMS.has(key));
|
|
2368
|
+
if (!source || unknown) throw new TypeError(unknown ? `Share field ${unknown} is not supported` : "Share request is invalid");
|
|
2369
|
+
const terms = {};
|
|
2370
|
+
if (Object.hasOwn(source, "displayName")) {
|
|
2371
|
+
if (typeof source.displayName !== "string" || !source.displayName.trim()) throw new TypeError("Share displayName is invalid");
|
|
2372
|
+
terms.displayName = source.displayName;
|
|
2373
|
+
}
|
|
2374
|
+
if (Object.hasOwn(source, "selector")) terms.selector = source.selector === null ? null : labelSelector(source.selector);
|
|
2375
|
+
if (Object.hasOwn(source, "actions")) {
|
|
2376
|
+
const actions2 = source.actions;
|
|
2377
|
+
if (!Array.isArray(actions2) || actions2.length === 0 || actions2.some((item) => !ACTIONS.includes(item))) {
|
|
2378
|
+
throw new TypeError("Share actions must name read, evaluate or contribute");
|
|
2379
|
+
}
|
|
2380
|
+
terms.actions = ACTIONS.filter((item) => actions2.includes(item));
|
|
2381
|
+
}
|
|
2382
|
+
if (Object.hasOwn(source, "prices")) terms.prices = sharePrices(source.prices);
|
|
2383
|
+
if (Object.hasOwn(source, "evaluation")) terms.evaluation = source.evaluation === null ? null : shareEvaluation(source.evaluation);
|
|
2384
|
+
if (Object.hasOwn(source, "expiresAt")) {
|
|
2385
|
+
if (source.expiresAt !== null && (!Number.isSafeInteger(source.expiresAt) || source.expiresAt <= 0)) {
|
|
2386
|
+
throw new TypeError("Share expiresAt must be null or a time in milliseconds");
|
|
2387
|
+
}
|
|
2388
|
+
terms.expiresAt = source.expiresAt;
|
|
2389
|
+
}
|
|
2390
|
+
return terms;
|
|
2391
|
+
}
|
|
2392
|
+
var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
2393
|
+
var HASH2 = /^[a-f0-9]{64}$/u;
|
|
2394
|
+
var DECISIONS = ["accept", "request-changes", "reject"];
|
|
2395
|
+
function contributionNote(value) {
|
|
2396
|
+
if (typeof value !== "string" || new TextEncoder().encode(value).byteLength > 4096) throw new TypeError("note must be text of at most 4096 bytes");
|
|
2397
|
+
return value;
|
|
2398
|
+
}
|
|
2399
|
+
function datasetPin(value, index) {
|
|
2400
|
+
const pin = record5(value);
|
|
2401
|
+
let kind = null;
|
|
2402
|
+
try {
|
|
2403
|
+
kind = typeof pin?.crn === "string" ? parseResourceName(pin.crn).kind : null;
|
|
2404
|
+
} catch {
|
|
2405
|
+
kind = null;
|
|
2406
|
+
}
|
|
2407
|
+
if (!pin || Object.keys(pin).length !== 3 || kind !== "dataset" || typeof pin.version !== "string" || !pin.version || typeof pin.hash !== "string" || !HASH2.test(pin.hash)) throw new TypeError(`Contribution dataset ${index} is invalid`);
|
|
2408
|
+
return { crn: pin.crn, version: pin.version, hash: pin.hash };
|
|
2409
|
+
}
|
|
2410
|
+
function shareContributionRequest(value) {
|
|
2411
|
+
const source = record5(value);
|
|
2412
|
+
const unknown = source && Object.keys(source).find((key) => key !== "datasets" && key !== "evaluations" && key !== "note");
|
|
2413
|
+
if (!source || unknown) throw new TypeError(unknown ? `Contribution field ${unknown} is not supported` : "Contribution request is invalid");
|
|
2414
|
+
const terms = {};
|
|
2415
|
+
if (Object.hasOwn(source, "datasets")) {
|
|
2416
|
+
if (!Array.isArray(source.datasets) || source.datasets.length > 16) throw new TypeError("datasets must be a list of at most 16 Dataset versions");
|
|
2417
|
+
terms.datasets = source.datasets.map(datasetPin);
|
|
2418
|
+
}
|
|
2419
|
+
if (Object.hasOwn(source, "evaluations")) {
|
|
2420
|
+
const evaluations = source.evaluations;
|
|
2421
|
+
if (!Array.isArray(evaluations) || evaluations.length > 16 || evaluations.some((item) => typeof item !== "string" || !NAME3.test(item))) {
|
|
2422
|
+
throw new TypeError("evaluations must be a list of at most 16 evaluation ids");
|
|
2423
|
+
}
|
|
2424
|
+
terms.evaluations = evaluations;
|
|
2425
|
+
}
|
|
2426
|
+
if (Object.hasOwn(source, "note")) terms.note = contributionNote(source.note);
|
|
2427
|
+
return terms;
|
|
2428
|
+
}
|
|
2429
|
+
function shareContributionReview(value) {
|
|
2430
|
+
const source = record5(value);
|
|
2431
|
+
const unknown = source && Object.keys(source).find((key) => !["decision", "note", "namespace", "targets"].includes(key));
|
|
2432
|
+
if (!source || unknown) throw new TypeError(unknown ? `Review field ${unknown} is not supported` : "Review request is invalid");
|
|
2433
|
+
if (!DECISIONS.includes(source.decision)) throw new TypeError("Review decision must be accept, request-changes or reject");
|
|
2434
|
+
const review = { decision: source.decision };
|
|
2435
|
+
if (Object.hasOwn(source, "note")) review.note = contributionNote(source.note);
|
|
2436
|
+
if (review.decision !== "accept") {
|
|
2437
|
+
if (Object.hasOwn(source, "namespace") || Object.hasOwn(source, "targets")) throw new TypeError("Only an accepting review names a namespace or targets");
|
|
2438
|
+
return review;
|
|
2439
|
+
}
|
|
2440
|
+
if (Object.hasOwn(source, "namespace")) {
|
|
2441
|
+
if (typeof source.namespace !== "string" || !NAME3.test(source.namespace)) throw new TypeError("Review namespace is invalid");
|
|
2442
|
+
review.namespace = source.namespace;
|
|
2443
|
+
}
|
|
2444
|
+
if (Object.hasOwn(source, "targets")) {
|
|
2445
|
+
const targets = source.targets;
|
|
2446
|
+
if (!Array.isArray(targets) || targets.length > 16 || targets.some((item) => item !== null && (typeof item !== "string" || !NAME3.test(item)))) {
|
|
2447
|
+
throw new TypeError("Review targets must be at most 16 Dataset ids or nulls");
|
|
2448
|
+
}
|
|
2449
|
+
review.targets = targets;
|
|
2450
|
+
}
|
|
2451
|
+
return review;
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2296
2454
|
// packages/sdk/src/table.ts
|
|
2297
2455
|
var identifier = { type: "string", pattern: "^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$", maxLength: 128 };
|
|
2298
2456
|
var tableName = { type: "string", pattern: "^[a-z0-9][a-z0-9._-]{0,127}$", maxLength: 128 };
|
|
@@ -2407,10 +2565,10 @@ var tableQuery = {
|
|
|
2407
2565
|
};
|
|
2408
2566
|
|
|
2409
2567
|
// packages/sdk/src/tools.ts
|
|
2410
|
-
var
|
|
2568
|
+
var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
2411
2569
|
var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
|
|
2412
2570
|
function opTool(binding, op, override = {}) {
|
|
2413
|
-
if (!
|
|
2571
|
+
if (!NAME4.test(binding) || !OPERATION2.test(op)) throw new TypeError("opTool binding or operation is invalid");
|
|
2414
2572
|
const name = override.name ?? op.replaceAll(".", "_");
|
|
2415
2573
|
return {
|
|
2416
2574
|
name,
|
|
@@ -2583,7 +2741,7 @@ var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 }
|
|
|
2583
2741
|
var content = { type: "string", minLength: 1 };
|
|
2584
2742
|
var metadata2 = { type: "object" };
|
|
2585
2743
|
var scope = { type: "string", pattern: "^[a-f0-9]{64}$", maxLength: 64 };
|
|
2586
|
-
var
|
|
2744
|
+
var record6 = {
|
|
2587
2745
|
type: "object",
|
|
2588
2746
|
required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
|
|
2589
2747
|
additionalProperties: false,
|
|
@@ -2601,7 +2759,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
|
|
|
2601
2759
|
op: "remember",
|
|
2602
2760
|
description: "Persist or replace one record in the invocation's authenticated Memory partition.",
|
|
2603
2761
|
schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata: metadata2, scope } },
|
|
2604
|
-
resultSchema:
|
|
2762
|
+
resultSchema: record6,
|
|
2605
2763
|
effect: "idempotent",
|
|
2606
2764
|
recovery: { kind: "idempotency-key" },
|
|
2607
2765
|
async: false,
|
|
@@ -2614,16 +2772,21 @@ var MEMORY_OPERATION_DECLARATIONS = [
|
|
|
2614
2772
|
type: "object",
|
|
2615
2773
|
required: ["query"],
|
|
2616
2774
|
additionalProperties: false,
|
|
2617
|
-
properties: {
|
|
2775
|
+
properties: {
|
|
2776
|
+
query: { type: "string", minLength: 1 },
|
|
2777
|
+
limit: { type: "integer", minimum: 1 },
|
|
2778
|
+
scope,
|
|
2779
|
+
filter: { type: "object", additionalProperties: { anyOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }] } }
|
|
2780
|
+
}
|
|
2618
2781
|
},
|
|
2619
2782
|
resultSchema: {
|
|
2620
2783
|
type: "object",
|
|
2621
2784
|
required: ["hits"],
|
|
2622
2785
|
additionalProperties: false,
|
|
2623
2786
|
properties: { hits: { type: "array", items: {
|
|
2624
|
-
...
|
|
2625
|
-
required: [...
|
|
2626
|
-
properties: { ...
|
|
2787
|
+
...record6,
|
|
2788
|
+
required: [...record6.required, "score"],
|
|
2789
|
+
properties: { ...record6.properties, score: { type: "number", minimum: 0, maximum: 1 } }
|
|
2627
2790
|
} } }
|
|
2628
2791
|
},
|
|
2629
2792
|
effect: "read-only",
|
|
@@ -2634,8 +2797,8 @@ var MEMORY_OPERATION_DECLARATIONS = [
|
|
|
2634
2797
|
{
|
|
2635
2798
|
op: "get",
|
|
2636
2799
|
description: "Read one record from the invocation's authenticated Memory partition.",
|
|
2637
|
-
schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
|
|
2638
|
-
resultSchema: { anyOf: [
|
|
2800
|
+
schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id, scope } },
|
|
2801
|
+
resultSchema: { anyOf: [record6, { type: "null" }] },
|
|
2639
2802
|
effect: "read-only",
|
|
2640
2803
|
recovery: { kind: "repeat" },
|
|
2641
2804
|
async: false,
|
|
@@ -2644,7 +2807,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
|
|
|
2644
2807
|
{
|
|
2645
2808
|
op: "delete",
|
|
2646
2809
|
description: "Delete one record from the invocation's authenticated Memory partition.",
|
|
2647
|
-
schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
|
|
2810
|
+
schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id, scope } },
|
|
2648
2811
|
resultSchema: { type: "object", required: ["deleted"], additionalProperties: false, properties: { deleted: { type: "boolean" } } },
|
|
2649
2812
|
effect: "idempotent",
|
|
2650
2813
|
recovery: { kind: "idempotency-key" },
|
|
@@ -2724,780 +2887,950 @@ function integrationEgressPolicy(value) {
|
|
|
2724
2887
|
return { rules };
|
|
2725
2888
|
}
|
|
2726
2889
|
|
|
2727
|
-
// packages/sdk/src/
|
|
2728
|
-
var
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2890
|
+
// packages/sdk/src/model.ts
|
|
2891
|
+
var MODEL_COMPLETION_CAPABILITY = {
|
|
2892
|
+
id: "constal.model-completion",
|
|
2893
|
+
version: "1",
|
|
2894
|
+
hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
|
|
2895
|
+
};
|
|
2896
|
+
var MODEL_EVALUATION_CAPABILITY = {
|
|
2897
|
+
id: "constal.model-evaluation",
|
|
2898
|
+
version: "1",
|
|
2899
|
+
hash: "9c0cc09c17fd5a79be3e1a8f822379f74a5e290d5a12e72104ae7c7eb4be22ee"
|
|
2900
|
+
};
|
|
2901
|
+
function modelGenerationOptions(source) {
|
|
2902
|
+
const { maxOutputTokens, temperature, effort } = source;
|
|
2903
|
+
if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1)) {
|
|
2904
|
+
throw new TypeError("maxOutputTokens must be a positive safe integer");
|
|
2740
2905
|
}
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
if (tag !== null) {
|
|
2744
|
-
if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
|
|
2745
|
-
name = name.slice(0, separator);
|
|
2906
|
+
if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature))) {
|
|
2907
|
+
throw new TypeError("temperature must be a finite number");
|
|
2746
2908
|
}
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
let registryUrl;
|
|
2750
|
-
try {
|
|
2751
|
-
registryUrl = new URL(`https://${registryInput}`);
|
|
2752
|
-
} catch {
|
|
2753
|
-
throw new TypeError("container image registry is invalid");
|
|
2909
|
+
if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
|
|
2910
|
+
throw new TypeError("effort must be a nonempty model-supported string");
|
|
2754
2911
|
}
|
|
2755
|
-
if (registryUrl.username || registryUrl.password || registryUrl.pathname !== "/" || !registryUrl.hostname) throw new TypeError("container image registry is invalid");
|
|
2756
|
-
const registry = registryUrl.host === "index.docker.io" ? "docker.io" : registryUrl.host;
|
|
2757
|
-
if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
|
|
2758
|
-
const repository = parts.join("/");
|
|
2759
|
-
if (!REPOSITORY.test(repository)) throw new TypeError("container image repository is invalid");
|
|
2760
|
-
const selectedTag = tag ?? (digest === null ? "latest" : null);
|
|
2761
2912
|
return {
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
digest,
|
|
2766
|
-
reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
|
|
2913
|
+
...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
|
|
2914
|
+
...temperature === void 0 ? {} : { temperature },
|
|
2915
|
+
...effort === void 0 ? {} : { effort }
|
|
2767
2916
|
};
|
|
2768
2917
|
}
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2918
|
+
var NAME5 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
2919
|
+
var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
|
|
2920
|
+
var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
|
|
2921
|
+
function record7(value) {
|
|
2922
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2773
2923
|
}
|
|
2774
|
-
function
|
|
2775
|
-
|
|
2776
|
-
const
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
throw new TypeError("container image source is invalid");
|
|
2780
|
-
}
|
|
2781
|
-
return structuredClone(source);
|
|
2924
|
+
function credentialHeader(value, name) {
|
|
2925
|
+
if (value === null || value === void 0) return null;
|
|
2926
|
+
const source = record7(value);
|
|
2927
|
+
if (!source || typeof source.slot !== "string" || !NAME5.test(source.slot) || typeof source.header !== "string" || !HEADER.test(source.header.toLowerCase()) || RESERVED_HEADERS.has(source.header.toLowerCase()) || source.header.toLowerCase().startsWith("cf-") || source.scheme !== "bearer" && source.scheme !== "raw") throw new TypeError(`${name} is invalid`);
|
|
2928
|
+
return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
|
|
2782
2929
|
}
|
|
2783
|
-
function
|
|
2784
|
-
const
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
if (!selection || !image || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant) || Object.keys(selection).some((key) => key !== "reference" && key !== "platform") || Object.keys(platform).some((key) => key !== "os" && key !== "architecture" && key !== "variant")) {
|
|
2788
|
-
throw new TypeError("container image selection is invalid");
|
|
2930
|
+
function normalizeModelGatewayConfig(value) {
|
|
2931
|
+
const source = record7(value);
|
|
2932
|
+
if (!source || typeof source.baseUrl !== "string" || source.protocol !== "anthropic" && source.protocol !== "openai" || typeof source.model !== "string" || source.model.length === 0) {
|
|
2933
|
+
throw new TypeError("model gateway config is invalid");
|
|
2789
2934
|
}
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2935
|
+
const maxOutputTokens = source.maxOutputTokens === void 0 ? null : Number(source.maxOutputTokens);
|
|
2936
|
+
const temperature = source.temperature === void 0 ? null : Number(source.temperature);
|
|
2937
|
+
if (maxOutputTokens !== null && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1) || temperature !== null && !Number.isFinite(temperature)) {
|
|
2938
|
+
throw new TypeError("model gateway generation limits are invalid");
|
|
2939
|
+
}
|
|
2940
|
+
const normalized = {
|
|
2941
|
+
baseUrl: source.baseUrl,
|
|
2942
|
+
protocol: source.protocol,
|
|
2943
|
+
model: source.model,
|
|
2944
|
+
maxOutputTokens,
|
|
2945
|
+
temperature,
|
|
2946
|
+
gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
|
|
2947
|
+
providerAuth: credentialHeader(source.providerAuth, "providerAuth")
|
|
2948
|
+
};
|
|
2949
|
+
if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
|
|
2950
|
+
throw new TypeError("gateway and provider credentials cannot share one header");
|
|
2951
|
+
}
|
|
2952
|
+
if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
|
|
2953
|
+
throw new TypeError("gateway and provider credentials cannot share one slot");
|
|
2954
|
+
}
|
|
2955
|
+
modelGatewayEndpoint(normalized);
|
|
2956
|
+
return normalized;
|
|
2800
2957
|
}
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
url: `https://${image.registry}/v2/${image.repository}/manifests/${encodeURIComponent(reference)}`,
|
|
2804
|
-
method: "GET",
|
|
2805
|
-
headers: { accept: ACCEPT, ...authorization ? { authorization } : {} },
|
|
2806
|
-
maximumBytes: MANIFEST_BYTES
|
|
2807
|
-
});
|
|
2808
|
-
if (response.status < 200 || response.status >= 300) throw Object.assign(new Error(`container registry manifest request returned ${response.status}`), { status: response.status });
|
|
2809
|
-
if (response.body.byteLength === 0 || response.body.byteLength > MANIFEST_BYTES) throw new TypeError("container registry manifest size is invalid");
|
|
2810
|
-
let value;
|
|
2958
|
+
function modelGatewayEndpoint(config) {
|
|
2959
|
+
let endpoint;
|
|
2811
2960
|
try {
|
|
2812
|
-
|
|
2961
|
+
endpoint = new URL(config.baseUrl);
|
|
2813
2962
|
} catch {
|
|
2814
|
-
|
|
2963
|
+
throw new TypeError("model gateway baseUrl is invalid");
|
|
2815
2964
|
}
|
|
2816
|
-
if (
|
|
2817
|
-
|
|
2818
|
-
if (![OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].includes(String(declared))) throw new TypeError("container registry manifest media type is unsupported");
|
|
2819
|
-
const digest = `sha256:${await sha256Hex(response.body)}`;
|
|
2820
|
-
const header = response.headers["docker-content-digest"];
|
|
2821
|
-
if (header !== void 0 && header !== digest) throw new TypeError("container registry digest header differs from manifest bytes");
|
|
2822
|
-
return { value, mediaType: declared, digest };
|
|
2823
|
-
}
|
|
2824
|
-
async function resolveContainerImageSource(reference, platform, request, authorization) {
|
|
2825
|
-
const image = containerImageReference(reference);
|
|
2826
|
-
if (!platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && !platform.variant) throw new TypeError("container image platform is invalid");
|
|
2827
|
-
const requested = image.digest ?? image.tag;
|
|
2828
|
-
let selected = await manifest(image, requested, request, authorization);
|
|
2829
|
-
if (image.digest && selected.digest !== image.digest) throw new TypeError("container image digest does not match its manifest");
|
|
2830
|
-
if (selected.mediaType === OCI_INDEX || selected.mediaType === DOCKER_INDEX) {
|
|
2831
|
-
if (!Array.isArray(selected.value.manifests)) throw new TypeError("container image index has no manifests");
|
|
2832
|
-
const matches = selected.value.manifests.filter((raw) => {
|
|
2833
|
-
const item = object3(raw), target = object3(item?.platform);
|
|
2834
|
-
return item && target && target.os === platform.os && target.architecture === platform.architecture && (platform.variant === void 0 ? target.variant === void 0 : target.variant === platform.variant);
|
|
2835
|
-
}).map((item) => object3(item));
|
|
2836
|
-
if (matches.length !== 1 || typeof matches[0].digest !== "string" || !SHA256.test(matches[0].digest)) {
|
|
2837
|
-
throw new TypeError("container image index does not contain one exact requested platform");
|
|
2838
|
-
}
|
|
2839
|
-
selected = await manifest(image, matches[0].digest, request, authorization);
|
|
2840
|
-
if (selected.digest !== matches[0].digest) throw new TypeError("container image platform descriptor differs from its manifest");
|
|
2965
|
+
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
|
|
2966
|
+
throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
|
|
2841
2967
|
}
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
throw new TypeError("container image manifest descriptors are invalid");
|
|
2968
|
+
const hostname = endpoint.hostname.toLowerCase();
|
|
2969
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
|
|
2970
|
+
throw new TypeError("model gateway baseUrl must use a public hostname");
|
|
2846
2971
|
}
|
|
2847
|
-
const
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
mediaType: selected.mediaType,
|
|
2852
|
-
bytes,
|
|
2853
|
-
platform
|
|
2854
|
-
});
|
|
2855
|
-
}
|
|
2856
|
-
|
|
2857
|
-
// packages/sdk/src/sandbox-egress.ts
|
|
2858
|
-
var SANDBOX_EGRESS_LIMITS = { rules: 64, credentialRules: 16, hostsPerRule: 32, labels: 16, labelValueLength: 256 };
|
|
2859
|
-
var HEADER = /^[a-z0-9!#$%&'*+.^_`|~-]{1,64}$/u;
|
|
2860
|
-
var RESERVED_HEADERS = /* @__PURE__ */ new Set([
|
|
2861
|
-
"connection",
|
|
2862
|
-
"content-length",
|
|
2863
|
-
"host",
|
|
2864
|
-
"keep-alive",
|
|
2865
|
-
"proxy-connection",
|
|
2866
|
-
"te",
|
|
2867
|
-
"trailer",
|
|
2868
|
-
"transfer-encoding",
|
|
2869
|
-
"upgrade"
|
|
2870
|
-
]);
|
|
2871
|
-
var SLOT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
2872
|
-
var USE = /^egress-(?:0|[1-9][0-9]?)$/u;
|
|
2873
|
-
var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
|
|
2874
|
-
function object4(value) {
|
|
2875
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2876
|
-
}
|
|
2877
|
-
function sandboxEgressHostMatches(pattern, hostname) {
|
|
2878
|
-
const host2 = hostname.toLowerCase().replace(/\.$/u, "");
|
|
2879
|
-
return pattern.startsWith("*.") ? host2 === pattern.slice(2) || host2.endsWith(pattern.slice(1)) : host2 === pattern;
|
|
2972
|
+
const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
|
|
2973
|
+
if (!suffix) throw new TypeError("model gateway protocol is invalid");
|
|
2974
|
+
endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
|
|
2975
|
+
return endpoint;
|
|
2880
2976
|
}
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
return
|
|
2977
|
+
var CACHE_HINT_FIELDS = ["key", "retention", "ttl"];
|
|
2978
|
+
function nonempty(value) {
|
|
2979
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
2884
2980
|
}
|
|
2885
|
-
function
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
function sandboxEgressDecision(policy2, hostname) {
|
|
2900
|
-
if (!policy2) return { allowed: true, rule: "pool" };
|
|
2901
|
-
const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
|
|
2902
|
-
if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
|
|
2903
|
-
return { allowed: policy2.rules[index].action === "allow", rule: `sandbox:${index}` };
|
|
2981
|
+
function modelCacheHint(value) {
|
|
2982
|
+
if (value === void 0) return void 0;
|
|
2983
|
+
const source = record7(value);
|
|
2984
|
+
if (!source) throw new TypeError("model cache hint must be an object");
|
|
2985
|
+
const unknown = Object.keys(source).find((key) => !CACHE_HINT_FIELDS.includes(key));
|
|
2986
|
+
if (unknown !== void 0) throw new TypeError(`model cache hint has an unknown field: ${unknown}`);
|
|
2987
|
+
const hint = {};
|
|
2988
|
+
for (const field2 of CACHE_HINT_FIELDS) {
|
|
2989
|
+
const candidate = source[field2];
|
|
2990
|
+
if (candidate === void 0) continue;
|
|
2991
|
+
if (!nonempty(candidate)) throw new TypeError(`model cache hint ${field2} must be a nonempty string`);
|
|
2992
|
+
hint[field2] = candidate;
|
|
2993
|
+
}
|
|
2994
|
+
return hint;
|
|
2904
2995
|
}
|
|
2905
|
-
function
|
|
2996
|
+
function modelHistoryMessages(value) {
|
|
2906
2997
|
if (value === void 0) return [];
|
|
2907
|
-
if (!Array.isArray(value)
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
2911
|
-
|
|
2912
|
-
const
|
|
2913
|
-
if (
|
|
2914
|
-
throw new TypeError(
|
|
2998
|
+
if (!Array.isArray(value)) throw new TypeError("model history must be an array of messages");
|
|
2999
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3000
|
+
const unanswered = /* @__PURE__ */ new Set();
|
|
3001
|
+
const messages = value.map((candidate, index) => {
|
|
3002
|
+
const at = `model history message ${index}`;
|
|
3003
|
+
const source = record7(candidate);
|
|
3004
|
+
if (!source || typeof source.content !== "string" || source.role !== "user" && source.role !== "assistant" && source.role !== "tool") {
|
|
3005
|
+
throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
|
|
2915
3006
|
}
|
|
2916
|
-
const
|
|
2917
|
-
|
|
2918
|
-
if (
|
|
2919
|
-
if (
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
3007
|
+
const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
|
|
3008
|
+
const misplaced = foreign.find((field2) => source[field2] !== void 0);
|
|
3009
|
+
if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
|
|
3010
|
+
if (source.role === "tool") {
|
|
3011
|
+
if (!nonempty(source.toolCallId)) throw new TypeError(`${at} needs the toolCallId of the Tool call it answers`);
|
|
3012
|
+
if (!unanswered.delete(source.toolCallId)) {
|
|
3013
|
+
throw new TypeError(`${at} answers Tool call ${source.toolCallId}, which is not an unanswered call of the assistant message before it`);
|
|
3014
|
+
}
|
|
3015
|
+
if (source.isError !== void 0 && typeof source.isError !== "boolean") throw new TypeError(`${at} isError must be a boolean`);
|
|
3016
|
+
return {
|
|
3017
|
+
role: "tool",
|
|
3018
|
+
toolCallId: source.toolCallId,
|
|
3019
|
+
content: source.content,
|
|
3020
|
+
...source.isError === void 0 ? {} : { isError: source.isError }
|
|
3021
|
+
};
|
|
3022
|
+
}
|
|
3023
|
+
const open2 = unanswered.values().next();
|
|
3024
|
+
if (!open2.done) throw new TypeError(`model history Tool call ${open2.value} has no tool message answering it before message ${index}`);
|
|
3025
|
+
if (source.role === "user" || source.toolCalls === void 0) return { role: source.role, content: source.content };
|
|
3026
|
+
if (!Array.isArray(source.toolCalls)) throw new TypeError(`${at} toolCalls must be an array`);
|
|
3027
|
+
const toolCalls = source.toolCalls.map((call, position) => {
|
|
3028
|
+
const entry2 = record7(call);
|
|
3029
|
+
if (!entry2 || !nonempty(entry2.id) || !nonempty(entry2.name)) throw new TypeError(`${at} Tool call ${position} needs an id and a name`);
|
|
3030
|
+
if (ids.has(entry2.id)) throw new TypeError(`${at} repeats Tool call id ${entry2.id}`);
|
|
3031
|
+
try {
|
|
3032
|
+
canonicalJson(entry2.args);
|
|
3033
|
+
} catch {
|
|
3034
|
+
throw new TypeError(`${at} Tool call ${entry2.id} args must be a JSON value`);
|
|
3035
|
+
}
|
|
3036
|
+
ids.add(entry2.id);
|
|
3037
|
+
unanswered.add(entry2.id);
|
|
3038
|
+
return { id: entry2.id, name: entry2.name, args: entry2.args };
|
|
3039
|
+
});
|
|
3040
|
+
return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
|
|
2930
3041
|
});
|
|
3042
|
+
const open = unanswered.values().next();
|
|
3043
|
+
if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
|
|
3044
|
+
return messages;
|
|
2931
3045
|
}
|
|
2932
|
-
function
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
const
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
3046
|
+
function modelPrompt(args) {
|
|
3047
|
+
return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
|
|
3048
|
+
}
|
|
3049
|
+
function turnMessages(args) {
|
|
3050
|
+
const history = modelHistoryMessages(args.history);
|
|
3051
|
+
if (!history.length) return { messages: [{ role: "user", content: modelPrompt(args) }], lastHistory: null };
|
|
3052
|
+
const feedback = args.feedback ?? [];
|
|
3053
|
+
const prompt = args.objective == null && args.context == null && history[0].role === "user" ? [] : [{ role: "user", content: canonicalJson({ objective: args.objective ?? null, context: args.context ?? null }) }];
|
|
3054
|
+
return {
|
|
3055
|
+
messages: [...prompt, ...history, ...feedback.length ? [{ role: "user", content: canonicalJson({ feedback }) }] : []],
|
|
3056
|
+
lastHistory: prompt.length + history.length - 1
|
|
3057
|
+
};
|
|
2942
3058
|
}
|
|
3059
|
+
function modelMessages(args) {
|
|
3060
|
+
return turnMessages(args).messages;
|
|
3061
|
+
}
|
|
3062
|
+
function anthropicBlocks(content2) {
|
|
3063
|
+
return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
|
|
3064
|
+
}
|
|
3065
|
+
function anthropicMessage(message2) {
|
|
3066
|
+
if (message2.role === "tool") return { role: "user", content: [{
|
|
3067
|
+
type: "tool_result",
|
|
3068
|
+
tool_use_id: message2.toolCallId,
|
|
3069
|
+
content: message2.content,
|
|
3070
|
+
...message2.isError ? { is_error: true } : {}
|
|
3071
|
+
}] };
|
|
3072
|
+
if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
|
|
3073
|
+
...anthropicBlocks(message2.content),
|
|
3074
|
+
...message2.toolCalls.map((call) => {
|
|
3075
|
+
const args = JSON.parse(canonicalJson(call.args));
|
|
3076
|
+
return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
|
|
3077
|
+
})
|
|
3078
|
+
] };
|
|
3079
|
+
return { role: message2.role, content: message2.content };
|
|
3080
|
+
}
|
|
3081
|
+
function alternating(messages) {
|
|
3082
|
+
const merged = [];
|
|
3083
|
+
for (const message2 of messages) {
|
|
3084
|
+
const last = merged.at(-1);
|
|
3085
|
+
if (!last || last.role !== message2.role) merged.push({ ...message2 });
|
|
3086
|
+
else if (typeof last.content === "string" && typeof message2.content === "string") last.content = `${last.content}
|
|
2943
3087
|
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
function absoluteSandboxPath(value) {
|
|
2947
|
-
const segments = [];
|
|
2948
|
-
for (const segment of value.split("/")) {
|
|
2949
|
-
if (!segment || segment === ".") continue;
|
|
2950
|
-
if (segment === "..") segments.pop();
|
|
2951
|
-
else segments.push(segment);
|
|
3088
|
+
${message2.content}`;
|
|
3089
|
+
else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
|
|
2952
3090
|
}
|
|
2953
|
-
return
|
|
3091
|
+
return merged;
|
|
2954
3092
|
}
|
|
2955
|
-
function
|
|
2956
|
-
if (
|
|
2957
|
-
|
|
3093
|
+
function openAiMessage(message2, options) {
|
|
3094
|
+
if (message2.role === "tool") return {
|
|
3095
|
+
role: "tool",
|
|
3096
|
+
tool_call_id: message2.toolCallId,
|
|
3097
|
+
content: message2.content,
|
|
3098
|
+
...options.toolErrorName && message2.isError ? { name: "tool_error" } : {}
|
|
3099
|
+
};
|
|
3100
|
+
if (message2.role === "assistant" && message2.toolCalls) return {
|
|
3101
|
+
role: "assistant",
|
|
3102
|
+
content: message2.content || null,
|
|
3103
|
+
tool_calls: message2.toolCalls.map((call) => ({
|
|
3104
|
+
id: call.id,
|
|
3105
|
+
type: "function",
|
|
3106
|
+
function: { name: call.name, arguments: canonicalJson(call.args) }
|
|
3107
|
+
}))
|
|
3108
|
+
};
|
|
3109
|
+
return { role: message2.role, content: message2.content };
|
|
3110
|
+
}
|
|
3111
|
+
function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args, options = {}) {
|
|
3112
|
+
const { effort } = modelGenerationOptions(args);
|
|
3113
|
+
if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
|
|
3114
|
+
throw new TypeError("model Tool choice is invalid");
|
|
2958
3115
|
}
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
throw new TypeError("sandbox working directory is outside /workspace");
|
|
3116
|
+
if (args.toolChoice === "required" && !args.tools?.length) {
|
|
3117
|
+
throw new TypeError("required model Tool choice needs at least one offered Tool");
|
|
2962
3118
|
}
|
|
2963
|
-
const
|
|
2964
|
-
|
|
2965
|
-
|
|
3119
|
+
const cache = modelCacheHint(args.cache);
|
|
3120
|
+
const { messages, lastHistory } = turnMessages(args);
|
|
3121
|
+
const breakpoint = cache ? { type: "ephemeral", ...cache.ttl === void 0 ? {} : { ttl: cache.ttl } } : null;
|
|
3122
|
+
if (protocol === "anthropic") {
|
|
3123
|
+
const anthropic = messages.map(anthropicMessage);
|
|
3124
|
+
const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
|
|
3125
|
+
if (breakpoint && lastHistory !== null && marked.length) {
|
|
3126
|
+
anthropic[lastHistory] = { ...anthropic[lastHistory], content: [...marked.slice(0, -1), { ...marked.at(-1), cache_control: breakpoint }] };
|
|
3127
|
+
}
|
|
3128
|
+
const tools = args.tools ?? [];
|
|
3129
|
+
return {
|
|
3130
|
+
model,
|
|
3131
|
+
system: breakpoint && args.system ? [{ type: "text", text: args.system, cache_control: breakpoint }] : args.system ?? "",
|
|
3132
|
+
messages: alternating(anthropic),
|
|
3133
|
+
...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
|
|
3134
|
+
...effort === void 0 ? {} : { output_config: { effort } },
|
|
3135
|
+
...temperature === null ? {} : { temperature },
|
|
3136
|
+
...tools.length ? { tools: tools.map((tool, index) => ({
|
|
3137
|
+
name: tool.name,
|
|
3138
|
+
description: tool.description,
|
|
3139
|
+
input_schema: tool.schema,
|
|
3140
|
+
...breakpoint && index === tools.length - 1 ? { cache_control: breakpoint } : {}
|
|
3141
|
+
})) } : {},
|
|
3142
|
+
...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
|
|
3143
|
+
};
|
|
2966
3144
|
}
|
|
2967
|
-
|
|
3145
|
+
if (protocol === "openai") {
|
|
3146
|
+
const marks = options.contentCacheControl === true ? breakpoint : null;
|
|
3147
|
+
const marked = (text2) => marks && text2 ? [{ type: "text", text: text2, cache_control: marks }] : text2;
|
|
3148
|
+
const openai = messages.map((message2, index) => {
|
|
3149
|
+
const entry2 = openAiMessage(message2, options);
|
|
3150
|
+
return index === lastHistory && typeof entry2.content === "string" ? { ...entry2, content: marked(entry2.content) } : entry2;
|
|
3151
|
+
});
|
|
3152
|
+
return {
|
|
3153
|
+
model,
|
|
3154
|
+
messages: [
|
|
3155
|
+
...args.system ? [{ role: "developer", content: marked(args.system) }] : [],
|
|
3156
|
+
...openai
|
|
3157
|
+
],
|
|
3158
|
+
...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
|
|
3159
|
+
...effort === void 0 ? {} : { reasoning_effort: effort },
|
|
3160
|
+
...temperature === null ? {} : { temperature },
|
|
3161
|
+
...args.tools?.length ? { tools: args.tools.map((tool) => ({
|
|
3162
|
+
type: "function",
|
|
3163
|
+
function: { name: tool.name, description: tool.description, parameters: tool.schema }
|
|
3164
|
+
})) } : {},
|
|
3165
|
+
...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice },
|
|
3166
|
+
...cache?.key === void 0 ? {} : { prompt_cache_key: cache.key },
|
|
3167
|
+
...cache?.retention === void 0 ? {} : { prompt_cache_retention: cache.retention }
|
|
3168
|
+
};
|
|
3169
|
+
}
|
|
3170
|
+
throw new TypeError("model gateway protocol is invalid");
|
|
3171
|
+
}
|
|
3172
|
+
function integer(value) {
|
|
3173
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
3174
|
+
}
|
|
3175
|
+
function cacheWrite(usage) {
|
|
3176
|
+
const value = usage.cache_creation_input_tokens ?? record7(usage.prompt_tokens_details)?.cache_write_tokens;
|
|
3177
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? { cacheWrite: value } : {};
|
|
3178
|
+
}
|
|
3179
|
+
function costMetadata(usage) {
|
|
3180
|
+
const cost = usage.cost;
|
|
3181
|
+
const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
|
|
3182
|
+
return {
|
|
3183
|
+
...costUsd !== void 0 ? { costUsd } : {},
|
|
3184
|
+
...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
|
|
3185
|
+
...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
|
|
3186
|
+
};
|
|
3187
|
+
}
|
|
3188
|
+
function modelProtocolResult(protocol, raw, provider, model) {
|
|
3189
|
+
const source = record7(raw);
|
|
3190
|
+
if (!source) throw new TypeError("model gateway response is invalid");
|
|
3191
|
+
const toolCalls = [];
|
|
3192
|
+
let content2 = "";
|
|
3193
|
+
let refusal;
|
|
3194
|
+
let reasoningContent;
|
|
3195
|
+
let usage;
|
|
3196
|
+
if (protocol === "anthropic") {
|
|
3197
|
+
if (!Array.isArray(source.content)) throw new TypeError("Anthropic model response content is invalid");
|
|
3198
|
+
const blocks = source.content;
|
|
3199
|
+
content2 = blocks.map((candidate) => {
|
|
3200
|
+
const block = record7(candidate);
|
|
3201
|
+
if (block?.type === "text" && typeof block.text === "string") return block.text;
|
|
3202
|
+
if (block?.type === "tool_use") {
|
|
3203
|
+
if (typeof block.id !== "string" || typeof block.name !== "string") throw new TypeError("Anthropic tool use is invalid");
|
|
3204
|
+
toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
|
|
3205
|
+
}
|
|
3206
|
+
return "";
|
|
3207
|
+
}).join("");
|
|
3208
|
+
const values = record7(source.usage) ?? {};
|
|
3209
|
+
const cached = integer(values.cache_read_input_tokens);
|
|
3210
|
+
usage = {
|
|
3211
|
+
input: integer(values.input_tokens) + integer(values.cache_creation_input_tokens) + cached,
|
|
3212
|
+
output: integer(values.output_tokens),
|
|
3213
|
+
cached,
|
|
3214
|
+
...cacheWrite(values),
|
|
3215
|
+
...costMetadata(values)
|
|
3216
|
+
};
|
|
3217
|
+
} else if (protocol === "openai") {
|
|
3218
|
+
const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null);
|
|
3219
|
+
const message2 = record7(choice?.message);
|
|
3220
|
+
if (!message2) throw new TypeError("OpenAI-compatible model response message is invalid");
|
|
3221
|
+
content2 = typeof message2.content === "string" ? message2.content : "";
|
|
3222
|
+
refusal = typeof message2.refusal === "string" ? message2.refusal : void 0;
|
|
3223
|
+
reasoningContent = typeof message2.reasoning_content === "string" ? message2.reasoning_content : void 0;
|
|
3224
|
+
if (message2.tool_calls !== void 0 && !Array.isArray(message2.tool_calls)) throw new TypeError("OpenAI-compatible tool calls are invalid");
|
|
3225
|
+
for (const candidate of Array.isArray(message2.tool_calls) ? message2.tool_calls : []) {
|
|
3226
|
+
const call = record7(candidate);
|
|
3227
|
+
const fn = record7(call?.function);
|
|
3228
|
+
if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") {
|
|
3229
|
+
throw new TypeError("OpenAI-compatible tool call is invalid");
|
|
3230
|
+
}
|
|
3231
|
+
let args;
|
|
3232
|
+
try {
|
|
3233
|
+
args = JSON.parse(fn.arguments);
|
|
3234
|
+
} catch {
|
|
3235
|
+
throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
|
|
3236
|
+
}
|
|
3237
|
+
toolCalls.push({ id: call.id, name: fn.name, args });
|
|
3238
|
+
}
|
|
3239
|
+
const values = record7(source.usage) ?? {};
|
|
3240
|
+
usage = {
|
|
3241
|
+
input: integer(values.prompt_tokens),
|
|
3242
|
+
output: integer(values.completion_tokens),
|
|
3243
|
+
cached: integer(record7(values.prompt_tokens_details)?.cached_tokens),
|
|
3244
|
+
...cacheWrite(values),
|
|
3245
|
+
...costMetadata(values)
|
|
3246
|
+
};
|
|
3247
|
+
} else throw new TypeError("model gateway protocol is invalid");
|
|
3248
|
+
return {
|
|
3249
|
+
content: content2,
|
|
3250
|
+
...toolCalls.length ? { toolCalls } : {},
|
|
3251
|
+
...refusal === void 0 ? {} : { refusal },
|
|
3252
|
+
...reasoningContent === void 0 ? {} : { reasoningContent },
|
|
3253
|
+
usage,
|
|
3254
|
+
provider,
|
|
3255
|
+
model,
|
|
3256
|
+
completion: modelCompletionStatus(protocol, raw)
|
|
3257
|
+
};
|
|
3258
|
+
}
|
|
3259
|
+
function modelCompletionStatus(protocol, raw) {
|
|
3260
|
+
const source = record7(raw) ?? {};
|
|
3261
|
+
const value = protocol === "anthropic" ? source.stop_reason : record7(Array.isArray(source.choices) ? source.choices[0] : null)?.finish_reason;
|
|
3262
|
+
const reason = typeof value === "string" ? value : null;
|
|
3263
|
+
const complete = protocol === "anthropic" ? ["end_turn", "tool_use", "stop_sequence"] : ["stop", "tool_calls", "function_call"];
|
|
3264
|
+
const incomplete = protocol === "anthropic" ? ["max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"] : ["length", "content_filter", "error", "cancelled", "canceled"];
|
|
3265
|
+
return { status: reason !== null && complete.includes(reason) ? "complete" : reason !== null && incomplete.includes(reason) ? "incomplete" : "unknown", reason };
|
|
2968
3266
|
}
|
|
2969
|
-
var SANDBOX_PROCESS_IO_OPERATIONS = ["process.status", "process.read", "process.write", "process.close"];
|
|
2970
|
-
var SANDBOX_PROCESS_OPERATIONS = ["process.resolve", ...SANDBOX_PROCESS_IO_OPERATIONS, "process.stop"];
|
|
2971
3267
|
|
|
2972
|
-
// packages/sdk/src/
|
|
2973
|
-
var
|
|
2974
|
-
var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
|
|
2975
|
-
var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
2976
|
-
var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3268
|
+
// packages/sdk/src/chat-format.ts
|
|
3269
|
+
var HASH3 = /^[a-f0-9]{64}$/u;
|
|
2977
3270
|
var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
|
|
2978
|
-
var
|
|
2979
|
-
id: "constal.
|
|
3271
|
+
var CHAT_FORMAT_CAPABILITY = {
|
|
3272
|
+
id: "constal.chat-format",
|
|
2980
3273
|
version: "1",
|
|
2981
|
-
hash: "
|
|
3274
|
+
hash: "effa7b0d199664f1f12cd2a6add4db67e5b23f3771c01947a507bb8c20447c27"
|
|
2982
3275
|
};
|
|
2983
|
-
|
|
3276
|
+
var NotAppendOnly = class extends Error {
|
|
3277
|
+
constructor(message2 = "chat rendering is not append-only") {
|
|
3278
|
+
super(message2);
|
|
3279
|
+
this.name = "NotAppendOnly";
|
|
3280
|
+
}
|
|
3281
|
+
};
|
|
3282
|
+
function record8(value) {
|
|
2984
3283
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2985
3284
|
}
|
|
2986
|
-
function
|
|
2987
|
-
|
|
2988
|
-
throw new TypeError(`${field2} is invalid`);
|
|
2989
|
-
}
|
|
2990
|
-
return Number(value);
|
|
3285
|
+
function exactKeys3(value, required2, optional = []) {
|
|
3286
|
+
return required2.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required2.includes(key) || optional.includes(key));
|
|
2991
3287
|
}
|
|
2992
|
-
function
|
|
2993
|
-
if (
|
|
2994
|
-
throw new TypeError(`${field2} is invalid`);
|
|
2995
|
-
}
|
|
3288
|
+
function tokenList(value, field2) {
|
|
3289
|
+
if (!Array.isArray(value) || value.some((token) => !Number.isSafeInteger(token) || token < 0)) throw new TypeError(`${field2} is invalid`);
|
|
2996
3290
|
return value;
|
|
2997
3291
|
}
|
|
2998
|
-
function
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
}
|
|
3005
|
-
function resumePoint(value) {
|
|
3006
|
-
if (value === null) return null;
|
|
3007
|
-
const candidate = record6(value);
|
|
3008
|
-
if (!candidate || typeof candidate.job !== "string" || !JOB_ID.test(candidate.job) || !Number.isSafeInteger(candidate.step) || Number(candidate.step) < 0 || typeof candidate.ref !== "string" || !HASH2.test(candidate.ref) || Object.keys(candidate).some((key) => !["job", "step", "ref"].includes(key))) {
|
|
3009
|
-
throw new TypeError("training resume point is invalid");
|
|
3010
|
-
}
|
|
3011
|
-
return candidate;
|
|
3012
|
-
}
|
|
3013
|
-
function trainingProviderMetadata(value) {
|
|
3014
|
-
const candidate = record6(value);
|
|
3015
|
-
const checkpoints = record6(candidate?.checkpoints);
|
|
3016
|
-
if (!candidate || candidate.lifecycleVersion !== 1 || !Array.isArray(candidate.methods) || candidate.methods.length === 0 || candidate.methods.length > 2 || candidate.methods.some((method) => method !== "sft" && method !== "rl") || new Set(candidate.methods).size !== candidate.methods.length || !Array.isArray(candidate.models) || !checkpoints || !Array.isArray(checkpoints.formats) || checkpoints.formats.length === 0 || checkpoints.formats.some((format) => typeof format !== "string" || !/^[a-z0-9][a-z0-9._+-]{0,63}$/u.test(format)) || new Set(checkpoints.formats).size !== checkpoints.formats.length || typeof checkpoints.resume !== "boolean" || typeof checkpoints.fork !== "boolean" || Object.keys(checkpoints).some((key) => !["formats", "resume", "fork"].includes(key)) || Object.keys(candidate).some((key) => !["lifecycleVersion", "methods", "models", "checkpoints"].includes(key))) {
|
|
3017
|
-
throw new TypeError("Training Provider metadata is invalid");
|
|
3018
|
-
}
|
|
3019
|
-
const models = candidate.models.map((raw) => {
|
|
3020
|
-
const model = record6(raw);
|
|
3021
|
-
const pricing = record6(model?.pricing);
|
|
3022
|
-
if (!model || typeof model.id !== "string" || !JOB_ID.test(model.id) || typeof model.name !== "string" || !model.name || model.name.length > 128 || typeof model.providerModel !== "string" || !PROVIDER_MODEL_ID.test(model.providerModel) || !Number.isSafeInteger(model.contextTokens) || Number(model.contextTokens) < 1 || !pricing || pricing.currency !== "USD" || pricing.unit !== "million_tokens" || ["prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].some((key) => !Number.isSafeInteger(pricing[key]) || Number(pricing[key]) < 0) || Object.keys(pricing).some((key) => !["currency", "unit", "prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].includes(key)) || Object.keys(model).some((key) => !["id", "name", "providerModel", "contextTokens", "pricing"].includes(key))) {
|
|
3023
|
-
throw new TypeError("Training Provider model offer is invalid");
|
|
3024
|
-
}
|
|
3025
|
-
return raw;
|
|
3026
|
-
});
|
|
3027
|
-
if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
|
|
3028
|
-
throw new TypeError("Training Provider model offers must be unique");
|
|
3292
|
+
function jsonValue(value) {
|
|
3293
|
+
try {
|
|
3294
|
+
canonicalJson(value);
|
|
3295
|
+
return true;
|
|
3296
|
+
} catch {
|
|
3297
|
+
return false;
|
|
3029
3298
|
}
|
|
3030
|
-
return {
|
|
3031
|
-
lifecycleVersion: 1,
|
|
3032
|
-
methods: candidate.methods,
|
|
3033
|
-
models,
|
|
3034
|
-
checkpoints
|
|
3035
|
-
};
|
|
3036
3299
|
}
|
|
3037
|
-
function
|
|
3038
|
-
const
|
|
3039
|
-
if (!
|
|
3040
|
-
throw new TypeError(
|
|
3300
|
+
function chatFormatMetadata(value) {
|
|
3301
|
+
const source = record8(value);
|
|
3302
|
+
if (!source || source.lifecycleVersion !== 1 || !Array.isArray(source.models) || source.models.length === 0 || source.models.some((model) => typeof model !== "string" || !PROVIDER_MODEL_ID.test(model)) || new Set(source.models).size !== source.models.length || !exactKeys3(source, ["lifecycleVersion", "models"])) {
|
|
3303
|
+
throw new TypeError("chat format metadata is invalid");
|
|
3041
3304
|
}
|
|
3042
|
-
return
|
|
3305
|
+
return { lifecycleVersion: 1, models: [...source.models] };
|
|
3043
3306
|
}
|
|
3044
|
-
function
|
|
3045
|
-
const
|
|
3046
|
-
if (!
|
|
3307
|
+
function chatFormatPin(value) {
|
|
3308
|
+
const source = record8(value);
|
|
3309
|
+
if (!source || typeof source.crn !== "string" || typeof source.hash !== "string" || !HASH3.test(source.hash) || !exactKeys3(source, ["crn", "hash"])) throw new TypeError("chat format pin is invalid");
|
|
3310
|
+
let kind;
|
|
3311
|
+
try {
|
|
3312
|
+
kind = parseResourceName(source.crn).kind;
|
|
3313
|
+
} catch {
|
|
3314
|
+
throw new TypeError("chat format pin is invalid");
|
|
3315
|
+
}
|
|
3316
|
+
if (kind === "model" || kind === "memory") throw new TypeError("chat format pin is invalid");
|
|
3317
|
+
return { crn: source.crn, hash: source.hash };
|
|
3318
|
+
}
|
|
3319
|
+
function toolCall(value, field2) {
|
|
3320
|
+
const source = record8(value);
|
|
3321
|
+
if (!source || typeof source.id !== "string" || !source.id || typeof source.name !== "string" || !source.name || !Object.hasOwn(source, "args") || !jsonValue(source.args) || !exactKeys3(source, ["id", "name", "args"])) {
|
|
3047
3322
|
throw new TypeError(`${field2} is invalid`);
|
|
3048
3323
|
}
|
|
3049
|
-
return
|
|
3324
|
+
return source;
|
|
3050
3325
|
}
|
|
3051
|
-
function
|
|
3052
|
-
const
|
|
3053
|
-
const
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
"batchSize",
|
|
3063
|
-
"groupSize",
|
|
3064
|
-
"temperature",
|
|
3065
|
-
"seed",
|
|
3066
|
-
"checkpointEvery",
|
|
3067
|
-
"evalEvery",
|
|
3068
|
-
"maxTrainTokens",
|
|
3069
|
-
"maxSampleTokens",
|
|
3070
|
-
"budgetMicroUsd"
|
|
3071
|
-
];
|
|
3072
|
-
if (!candidate || candidate.method !== "sft" && candidate.method !== "rl" || typeof candidate.baseModel !== "string" || !PROVIDER_MODEL_ID.test(candidate.baseModel) || !Array.isArray(candidate.scorers) || candidate.method === "rl" && candidate.scorers.length === 0 || Object.keys(candidate).some((key) => !allowed.includes(key))) throw new TypeError("training recipe is invalid");
|
|
3073
|
-
const recipe = {
|
|
3074
|
-
method: candidate.method,
|
|
3075
|
-
baseModel: candidate.baseModel,
|
|
3076
|
-
dataset: datasetRef(candidate.dataset, "training dataset"),
|
|
3077
|
-
validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
|
|
3078
|
-
scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
|
|
3079
|
-
loraRank: integer(candidate.loraRank, "LoRA rank", 1),
|
|
3080
|
-
learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE),
|
|
3081
|
-
epochs: integer(candidate.epochs, "epochs", 1),
|
|
3082
|
-
batchSize: integer(candidate.batchSize, "batch size", 1),
|
|
3083
|
-
groupSize: integer(candidate.groupSize, "group size", 1),
|
|
3084
|
-
temperature: finite(candidate.temperature, "temperature", 0),
|
|
3085
|
-
seed: integer(candidate.seed, "seed", 0),
|
|
3086
|
-
checkpointEvery: integer(candidate.checkpointEvery, "checkpoint interval", 1),
|
|
3087
|
-
evalEvery: integer(candidate.evalEvery, "evaluation interval", 1),
|
|
3088
|
-
maxTrainTokens: integer(candidate.maxTrainTokens, "training token limit", 1),
|
|
3089
|
-
maxSampleTokens: integer(candidate.maxSampleTokens, "sample token limit", 1),
|
|
3090
|
-
budgetMicroUsd: integer(candidate.budgetMicroUsd, "training budget", 1)
|
|
3091
|
-
};
|
|
3092
|
-
if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
|
|
3093
|
-
return recipe;
|
|
3326
|
+
function chatMessage(value, index) {
|
|
3327
|
+
const source = record8(value);
|
|
3328
|
+
const field2 = `chat message ${index}`;
|
|
3329
|
+
if (!source || typeof source.content !== "string") throw new TypeError(`${field2} is invalid`);
|
|
3330
|
+
if (source.role === "user" && exactKeys3(source, ["role", "content"])) return source;
|
|
3331
|
+
if (source.role === "tool" && typeof source.toolCallId === "string" && source.toolCallId && (source.isError === void 0 || typeof source.isError === "boolean") && exactKeys3(source, ["role", "toolCallId", "content"], ["isError"])) return source;
|
|
3332
|
+
if (source.role === "assistant" && exactKeys3(source, ["role", "content"], ["toolCalls", "reasoning"]) && (source.reasoning === void 0 || typeof source.reasoning === "string") && (source.toolCalls === void 0 || Array.isArray(source.toolCalls))) {
|
|
3333
|
+
source.toolCalls?.forEach((call, position) => toolCall(call, `${field2} Tool call ${position}`));
|
|
3334
|
+
return source;
|
|
3335
|
+
}
|
|
3336
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3094
3337
|
}
|
|
3095
|
-
function
|
|
3096
|
-
const
|
|
3097
|
-
if (!
|
|
3098
|
-
throw new TypeError("
|
|
3338
|
+
function chatRenderInput(value) {
|
|
3339
|
+
const source = record8(value);
|
|
3340
|
+
if (!source || !exactKeys3(source, ["system", "messages", "tools", "toolChoice", "effort", "train"]) || source.system !== null && typeof source.system !== "string" || !Array.isArray(source.messages) || !Array.isArray(source.tools) || source.toolChoice !== null && source.toolChoice !== "auto" && source.toolChoice !== "required" || source.effort !== null && (typeof source.effort !== "string" || !source.effort.trim()) || !Array.isArray(source.train)) {
|
|
3341
|
+
throw new TypeError("chat render request is invalid");
|
|
3099
3342
|
}
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3343
|
+
const messages = source.messages.map(chatMessage);
|
|
3344
|
+
source.tools.forEach((raw, index) => {
|
|
3345
|
+
const tool = record8(raw);
|
|
3346
|
+
if (!tool || typeof tool.name !== "string" || !tool.name || typeof tool.description !== "string" || !record8(tool.schema) || !jsonValue(tool.schema) || !exactKeys3(tool, ["name", "description", "schema"])) throw new TypeError(`chat Tool ${index} is invalid`);
|
|
3347
|
+
});
|
|
3348
|
+
if (source.toolChoice === "required" && source.tools.length === 0) throw new TypeError("required Tool choice needs at least one offered Tool");
|
|
3349
|
+
source.train.forEach((index, position) => {
|
|
3350
|
+
if (!Number.isSafeInteger(index) || index < 0 || index >= messages.length || messages[index].role !== "assistant" || position > 0 && index <= source.train[position - 1]) {
|
|
3351
|
+
throw new TypeError("chat render request trains only assistant messages, in ascending order");
|
|
3352
|
+
}
|
|
3353
|
+
});
|
|
3354
|
+
return source;
|
|
3107
3355
|
}
|
|
3108
|
-
function
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3356
|
+
function chatRenderRequest(args, train = []) {
|
|
3357
|
+
if (args.rawProtocol !== void 0) throw new TypeError("a raw protocol model request has no chat rendering");
|
|
3358
|
+
const { effort } = modelGenerationOptions(args);
|
|
3359
|
+
if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
|
|
3360
|
+
throw new TypeError("model Tool choice is invalid");
|
|
3361
|
+
}
|
|
3362
|
+
return chatRenderInput(JSON.parse(canonicalJson({
|
|
3363
|
+
system: args.system ? args.system : null,
|
|
3364
|
+
messages: modelMessages(args),
|
|
3365
|
+
tools: (args.tools ?? []).map((tool) => ({ name: tool.name, description: tool.description, schema: tool.schema })),
|
|
3366
|
+
toolChoice: args.toolChoice ?? null,
|
|
3367
|
+
effort: effort ?? null,
|
|
3368
|
+
train
|
|
3369
|
+
})));
|
|
3370
|
+
}
|
|
3371
|
+
function chatRendering(value, request) {
|
|
3372
|
+
const source = record8(value);
|
|
3373
|
+
if (!source || !exactKeys3(source, ["tokens", "spans", "stop"]) || !Array.isArray(source.spans)) throw new TypeError("chat rendering is invalid");
|
|
3374
|
+
const tokens = tokenList(source.tokens, "chat rendering tokens");
|
|
3375
|
+
const stop = tokenList(source.stop, "chat rendering stop tokens");
|
|
3376
|
+
if (stop.length === 0) throw new TypeError("chat rendering stop tokens are invalid");
|
|
3377
|
+
if (source.spans.length !== request.train.length) throw new TypeError("chat rendering spans do not match the trained messages");
|
|
3378
|
+
let previous = 0;
|
|
3379
|
+
const spans = source.spans.map((raw, index) => {
|
|
3380
|
+
const span = record8(raw);
|
|
3381
|
+
if (!span || !exactKeys3(span, ["message", "start", "end"]) || span.message !== request.train[index] || !Number.isSafeInteger(span.start) || !Number.isSafeInteger(span.end) || Number(span.start) < previous || Number(span.end) <= Number(span.start) || Number(span.end) > tokens.length) throw new TypeError("chat rendering spans are invalid");
|
|
3382
|
+
previous = Number(span.end);
|
|
3383
|
+
return span;
|
|
3384
|
+
});
|
|
3385
|
+
return { tokens, spans, stop };
|
|
3386
|
+
}
|
|
3387
|
+
function chatParseInput(value) {
|
|
3388
|
+
const source = record8(value);
|
|
3389
|
+
if (!source || !exactKeys3(source, ["tokens"])) throw new TypeError("chat parse request is invalid");
|
|
3390
|
+
return { tokens: tokenList(source.tokens, "chat parse tokens") };
|
|
3391
|
+
}
|
|
3392
|
+
function chatParsed(value) {
|
|
3393
|
+
const source = record8(value);
|
|
3394
|
+
if (!source || !exactKeys3(source, ["content", "toolCalls", "reasoningContent", "stopped"]) || typeof source.content !== "string" || !Array.isArray(source.toolCalls) || source.reasoningContent !== null && typeof source.reasoningContent !== "string" || typeof source.stopped !== "boolean") throw new TypeError("parsed chat turn is invalid");
|
|
3395
|
+
const toolCalls = source.toolCalls.map((call, index) => toolCall(call, `parsed Tool call ${index}`));
|
|
3396
|
+
if (new Set(toolCalls.map((call) => call.id)).size !== toolCalls.length) throw new TypeError("parsed Tool call ids must be unique");
|
|
3397
|
+
return source;
|
|
3115
3398
|
}
|
|
3116
3399
|
|
|
3117
|
-
// packages/sdk/src/
|
|
3118
|
-
var
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1)) {
|
|
3131
|
-
throw new TypeError("maxOutputTokens must be a positive safe integer");
|
|
3400
|
+
// packages/sdk/src/container-image.ts
|
|
3401
|
+
var REPOSITORY = /^[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*$/u;
|
|
3402
|
+
var TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u;
|
|
3403
|
+
var DIGEST = /^[a-z][a-z0-9+._-]*:[A-Za-z0-9=_-]+$/u;
|
|
3404
|
+
var SHA256 = /^sha256:[a-f0-9]{64}$/u;
|
|
3405
|
+
function containerImageReference(value) {
|
|
3406
|
+
if (typeof value !== "string" || !value || /[\s?#\\]/u.test(value) || value.includes("://")) throw new TypeError("container image reference is invalid");
|
|
3407
|
+
const components = value.split("@");
|
|
3408
|
+
if (components.length > 2) throw new TypeError("container image reference is invalid");
|
|
3409
|
+
let name = components[0];
|
|
3410
|
+
const digest = components[1] ?? null;
|
|
3411
|
+
if (digest !== null && (!DIGEST.test(digest) || digest.startsWith("sha256:") && !SHA256.test(digest))) {
|
|
3412
|
+
throw new TypeError("container image digest is invalid");
|
|
3132
3413
|
}
|
|
3133
|
-
|
|
3134
|
-
|
|
3414
|
+
const separator = name.lastIndexOf(":"), slash = name.lastIndexOf("/");
|
|
3415
|
+
const tag = separator > slash ? name.slice(separator + 1) : null;
|
|
3416
|
+
if (tag !== null) {
|
|
3417
|
+
if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
|
|
3418
|
+
name = name.slice(0, separator);
|
|
3135
3419
|
}
|
|
3136
|
-
|
|
3137
|
-
|
|
3420
|
+
const parts = name.split("/"), explicit = parts.length > 1 && (/[.:]/u.test(parts[0]) || parts[0] === "localhost");
|
|
3421
|
+
const registryInput = explicit ? parts.shift() : "docker.io";
|
|
3422
|
+
let registryUrl;
|
|
3423
|
+
try {
|
|
3424
|
+
registryUrl = new URL(`https://${registryInput}`);
|
|
3425
|
+
} catch {
|
|
3426
|
+
throw new TypeError("container image registry is invalid");
|
|
3138
3427
|
}
|
|
3428
|
+
if (registryUrl.username || registryUrl.password || registryUrl.pathname !== "/" || !registryUrl.hostname) throw new TypeError("container image registry is invalid");
|
|
3429
|
+
const registry = registryUrl.host === "index.docker.io" ? "docker.io" : registryUrl.host;
|
|
3430
|
+
if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
|
|
3431
|
+
const repository = parts.join("/");
|
|
3432
|
+
if (!REPOSITORY.test(repository)) throw new TypeError("container image repository is invalid");
|
|
3433
|
+
const selectedTag = tag ?? (digest === null ? "latest" : null);
|
|
3139
3434
|
return {
|
|
3140
|
-
|
|
3141
|
-
|
|
3142
|
-
|
|
3435
|
+
registry,
|
|
3436
|
+
repository,
|
|
3437
|
+
tag: selectedTag,
|
|
3438
|
+
digest,
|
|
3439
|
+
reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
|
|
3143
3440
|
};
|
|
3144
3441
|
}
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3442
|
+
function immutableContainerImageReference(value) {
|
|
3443
|
+
const image = containerImageReference(value);
|
|
3444
|
+
if (!image.digest || !SHA256.test(image.digest)) throw new TypeError("container image must be resolved to a SHA-256 digest");
|
|
3445
|
+
return image;
|
|
3150
3446
|
}
|
|
3151
|
-
function
|
|
3152
|
-
|
|
3153
|
-
const
|
|
3154
|
-
|
|
3155
|
-
|
|
3447
|
+
function containerImageSource(value) {
|
|
3448
|
+
const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3449
|
+
const platform = source?.platform && typeof source.platform === "object" && !Array.isArray(source.platform) ? source.platform : null;
|
|
3450
|
+
const image = typeof source?.reference === "string" ? immutableContainerImageReference(source.reference) : null;
|
|
3451
|
+
if (!source || !image || source.digest !== image.digest || typeof source.mediaType !== "string" || !source.mediaType || !Number.isSafeInteger(source.bytes) || Number(source.bytes) < 1 || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant)) {
|
|
3452
|
+
throw new TypeError("container image source is invalid");
|
|
3453
|
+
}
|
|
3454
|
+
return structuredClone(source);
|
|
3156
3455
|
}
|
|
3157
|
-
function
|
|
3158
|
-
const
|
|
3159
|
-
|
|
3160
|
-
|
|
3456
|
+
function containerImageSelection(value) {
|
|
3457
|
+
const selection = value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3458
|
+
const platform = selection?.platform && typeof selection.platform === "object" && !Array.isArray(selection.platform) ? selection.platform : null;
|
|
3459
|
+
const image = typeof selection?.reference === "string" ? immutableContainerImageReference(selection.reference) : null;
|
|
3460
|
+
if (!selection || !image || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant) || Object.keys(selection).some((key) => key !== "reference" && key !== "platform") || Object.keys(platform).some((key) => key !== "os" && key !== "architecture" && key !== "variant")) {
|
|
3461
|
+
throw new TypeError("container image selection is invalid");
|
|
3161
3462
|
}
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3463
|
+
return { reference: image.reference, platform: structuredClone(platform) };
|
|
3464
|
+
}
|
|
3465
|
+
var OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
|
|
3466
|
+
var OCI_INDEX = "application/vnd.oci.image.index.v1+json";
|
|
3467
|
+
var DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
|
|
3468
|
+
var DOCKER_INDEX = "application/vnd.docker.distribution.manifest.list.v2+json";
|
|
3469
|
+
var ACCEPT = [OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].join(", ");
|
|
3470
|
+
var MANIFEST_BYTES = 4194304;
|
|
3471
|
+
function object3(value) {
|
|
3472
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3473
|
+
}
|
|
3474
|
+
async function manifest(image, reference, request, authorization) {
|
|
3475
|
+
const response = await request({
|
|
3476
|
+
url: `https://${image.registry}/v2/${image.repository}/manifests/${encodeURIComponent(reference)}`,
|
|
3477
|
+
method: "GET",
|
|
3478
|
+
headers: { accept: ACCEPT, ...authorization ? { authorization } : {} },
|
|
3479
|
+
maximumBytes: MANIFEST_BYTES
|
|
3480
|
+
});
|
|
3481
|
+
if (response.status < 200 || response.status >= 300) throw Object.assign(new Error(`container registry manifest request returned ${response.status}`), { status: response.status });
|
|
3482
|
+
if (response.body.byteLength === 0 || response.body.byteLength > MANIFEST_BYTES) throw new TypeError("container registry manifest size is invalid");
|
|
3483
|
+
let value;
|
|
3484
|
+
try {
|
|
3485
|
+
value = object3(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(response.body)));
|
|
3486
|
+
} catch {
|
|
3487
|
+
value = null;
|
|
3166
3488
|
}
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3489
|
+
if (!value || value.schemaVersion !== 2) throw new TypeError("container registry manifest is invalid");
|
|
3490
|
+
const declared = typeof value.mediaType === "string" ? value.mediaType : response.headers["content-type"]?.split(";", 1)[0];
|
|
3491
|
+
if (![OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].includes(String(declared))) throw new TypeError("container registry manifest media type is unsupported");
|
|
3492
|
+
const digest = `sha256:${await sha256Hex(response.body)}`;
|
|
3493
|
+
const header = response.headers["docker-content-digest"];
|
|
3494
|
+
if (header !== void 0 && header !== digest) throw new TypeError("container registry digest header differs from manifest bytes");
|
|
3495
|
+
return { value, mediaType: declared, digest };
|
|
3496
|
+
}
|
|
3497
|
+
async function resolveContainerImageSource(reference, platform, request, authorization) {
|
|
3498
|
+
const image = containerImageReference(reference);
|
|
3499
|
+
if (!platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && !platform.variant) throw new TypeError("container image platform is invalid");
|
|
3500
|
+
const requested = image.digest ?? image.tag;
|
|
3501
|
+
let selected = await manifest(image, requested, request, authorization);
|
|
3502
|
+
if (image.digest && selected.digest !== image.digest) throw new TypeError("container image digest does not match its manifest");
|
|
3503
|
+
if (selected.mediaType === OCI_INDEX || selected.mediaType === DOCKER_INDEX) {
|
|
3504
|
+
if (!Array.isArray(selected.value.manifests)) throw new TypeError("container image index has no manifests");
|
|
3505
|
+
const matches = selected.value.manifests.filter((raw) => {
|
|
3506
|
+
const item = object3(raw), target = object3(item?.platform);
|
|
3507
|
+
return item && target && target.os === platform.os && target.architecture === platform.architecture && (platform.variant === void 0 ? target.variant === void 0 : target.variant === platform.variant);
|
|
3508
|
+
}).map((item) => object3(item));
|
|
3509
|
+
if (matches.length !== 1 || typeof matches[0].digest !== "string" || !SHA256.test(matches[0].digest)) {
|
|
3510
|
+
throw new TypeError("container image index does not contain one exact requested platform");
|
|
3511
|
+
}
|
|
3512
|
+
selected = await manifest(image, matches[0].digest, request, authorization);
|
|
3513
|
+
if (selected.digest !== matches[0].digest) throw new TypeError("container image platform descriptor differs from its manifest");
|
|
3178
3514
|
}
|
|
3179
|
-
if (
|
|
3180
|
-
|
|
3515
|
+
if (selected.mediaType !== OCI_MANIFEST && selected.mediaType !== DOCKER_MANIFEST) throw new TypeError("container image did not resolve to an image manifest");
|
|
3516
|
+
const config = object3(selected.value.config), layers = selected.value.layers;
|
|
3517
|
+
if (!config || !Number.isSafeInteger(config.size) || Number(config.size) < 0 || !Array.isArray(layers) || layers.some((layer) => !object3(layer) || !Number.isSafeInteger(object3(layer).size) || Number(object3(layer).size) < 0)) {
|
|
3518
|
+
throw new TypeError("container image manifest descriptors are invalid");
|
|
3181
3519
|
}
|
|
3182
|
-
|
|
3183
|
-
return
|
|
3520
|
+
const bytes = Number(config.size) + layers.reduce((sum, layer) => sum + Number(object3(layer).size), 0);
|
|
3521
|
+
return containerImageSource({
|
|
3522
|
+
reference: `${image.registry}/${image.repository}@${selected.digest}`,
|
|
3523
|
+
digest: selected.digest,
|
|
3524
|
+
mediaType: selected.mediaType,
|
|
3525
|
+
bytes,
|
|
3526
|
+
platform
|
|
3527
|
+
});
|
|
3528
|
+
}
|
|
3529
|
+
|
|
3530
|
+
// packages/sdk/src/sandbox-egress.ts
|
|
3531
|
+
var SANDBOX_EGRESS_LIMITS = { rules: 64, credentialRules: 16, hostsPerRule: 32, labels: 16, labelValueLength: 256 };
|
|
3532
|
+
var HEADER2 = /^[a-z0-9!#$%&'*+.^_`|~-]{1,64}$/u;
|
|
3533
|
+
var RESERVED_HEADERS2 = /* @__PURE__ */ new Set([
|
|
3534
|
+
"connection",
|
|
3535
|
+
"content-length",
|
|
3536
|
+
"host",
|
|
3537
|
+
"keep-alive",
|
|
3538
|
+
"proxy-connection",
|
|
3539
|
+
"te",
|
|
3540
|
+
"trailer",
|
|
3541
|
+
"transfer-encoding",
|
|
3542
|
+
"upgrade"
|
|
3543
|
+
]);
|
|
3544
|
+
var SLOT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
3545
|
+
var USE = /^egress-(?:0|[1-9][0-9]?)$/u;
|
|
3546
|
+
var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
|
|
3547
|
+
function object4(value) {
|
|
3548
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3184
3549
|
}
|
|
3185
|
-
function
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
endpoint = new URL(config.baseUrl);
|
|
3189
|
-
} catch {
|
|
3190
|
-
throw new TypeError("model gateway baseUrl is invalid");
|
|
3191
|
-
}
|
|
3192
|
-
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
|
|
3193
|
-
throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
|
|
3194
|
-
}
|
|
3195
|
-
const hostname = endpoint.hostname.toLowerCase();
|
|
3196
|
-
if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
|
|
3197
|
-
throw new TypeError("model gateway baseUrl must use a public hostname");
|
|
3198
|
-
}
|
|
3199
|
-
const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
|
|
3200
|
-
if (!suffix) throw new TypeError("model gateway protocol is invalid");
|
|
3201
|
-
endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
|
|
3202
|
-
return endpoint;
|
|
3550
|
+
function sandboxEgressHostMatches(pattern, hostname) {
|
|
3551
|
+
const host2 = hostname.toLowerCase().replace(/\.$/u, "");
|
|
3552
|
+
return pattern.startsWith("*.") ? host2 === pattern.slice(2) || host2.endsWith(pattern.slice(1)) : host2 === pattern;
|
|
3203
3553
|
}
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
return
|
|
3554
|
+
function host(value) {
|
|
3555
|
+
const [normalized] = normalizeSandboxDomains([value]);
|
|
3556
|
+
return normalized;
|
|
3207
3557
|
}
|
|
3208
|
-
function
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
const unknown = Object.keys(source).find((key) => !CACHE_HINT_FIELDS.includes(key));
|
|
3213
|
-
if (unknown !== void 0) throw new TypeError(`model cache hint has an unknown field: ${unknown}`);
|
|
3214
|
-
const hint = {};
|
|
3215
|
-
for (const field2 of CACHE_HINT_FIELDS) {
|
|
3216
|
-
const candidate = source[field2];
|
|
3217
|
-
if (candidate === void 0) continue;
|
|
3218
|
-
if (!nonempty(candidate)) throw new TypeError(`model cache hint ${field2} must be a nonempty string`);
|
|
3219
|
-
hint[field2] = candidate;
|
|
3558
|
+
function normalizeSandboxEgressPolicy(value) {
|
|
3559
|
+
const input = object4(value);
|
|
3560
|
+
if (!input || Object.keys(input).some((key) => key !== "rules" && key !== "default") || !Array.isArray(input.rules) || input.rules.length > SANDBOX_EGRESS_LIMITS.rules || input.default !== void 0 && input.default !== "allow" && input.default !== "deny") {
|
|
3561
|
+
throw new TypeError("sandbox egress policy is invalid");
|
|
3220
3562
|
}
|
|
3221
|
-
|
|
3563
|
+
const rules = input.rules.map((raw) => {
|
|
3564
|
+
const rule = object4(raw);
|
|
3565
|
+
if (!rule || Object.keys(rule).some((key) => key !== "action" && key !== "host") || rule.action !== "allow" && rule.action !== "deny") {
|
|
3566
|
+
throw new TypeError("sandbox egress rule is invalid");
|
|
3567
|
+
}
|
|
3568
|
+
return { action: rule.action, host: host(rule.host) };
|
|
3569
|
+
});
|
|
3570
|
+
return { rules, default: input.default === "allow" ? "allow" : "deny" };
|
|
3222
3571
|
}
|
|
3223
|
-
function
|
|
3572
|
+
function sandboxEgressDecision(policy2, hostname) {
|
|
3573
|
+
if (!policy2) return { allowed: true, rule: "pool" };
|
|
3574
|
+
const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
|
|
3575
|
+
if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
|
|
3576
|
+
return { allowed: policy2.rules[index].action === "allow", rule: `sandbox:${index}` };
|
|
3577
|
+
}
|
|
3578
|
+
function normalizeSandboxEgressCredentialRules(value, options = {}) {
|
|
3224
3579
|
if (value === void 0) return [];
|
|
3225
|
-
if (!Array.isArray(value)) throw new TypeError("
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3230
|
-
const
|
|
3231
|
-
if (
|
|
3232
|
-
throw new TypeError(
|
|
3233
|
-
}
|
|
3234
|
-
const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
|
|
3235
|
-
const misplaced = foreign.find((field2) => source[field2] !== void 0);
|
|
3236
|
-
if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
|
|
3237
|
-
if (source.role === "tool") {
|
|
3238
|
-
if (!nonempty(source.toolCallId)) throw new TypeError(`${at} needs the toolCallId of the Tool call it answers`);
|
|
3239
|
-
if (!unanswered.delete(source.toolCallId)) {
|
|
3240
|
-
throw new TypeError(`${at} answers Tool call ${source.toolCallId}, which is not an unanswered call of the assistant message before it`);
|
|
3241
|
-
}
|
|
3242
|
-
if (source.isError !== void 0 && typeof source.isError !== "boolean") throw new TypeError(`${at} isError must be a boolean`);
|
|
3243
|
-
return {
|
|
3244
|
-
role: "tool",
|
|
3245
|
-
toolCallId: source.toolCallId,
|
|
3246
|
-
content: source.content,
|
|
3247
|
-
...source.isError === void 0 ? {} : { isError: source.isError }
|
|
3248
|
-
};
|
|
3580
|
+
if (!Array.isArray(value) || value.length > SANDBOX_EGRESS_LIMITS.credentialRules) throw new TypeError("sandbox egress Credential rules are invalid");
|
|
3581
|
+
return value.map((raw) => {
|
|
3582
|
+
const rule = object4(raw);
|
|
3583
|
+
const allowed = ["hosts", "slot", "header", "value", "basic", ...options.bindings ? ["binding"] : [], ...options.uses ? ["use"] : []];
|
|
3584
|
+
if (!rule || Object.keys(rule).some((key) => !allowed.includes(key)) || !Array.isArray(rule.hosts) || rule.hosts.length === 0 || rule.hosts.length > SANDBOX_EGRESS_LIMITS.hostsPerRule) throw new TypeError("sandbox egress Credential rule is invalid");
|
|
3585
|
+
const sources = [rule.slot, rule.binding, rule.use].filter((source) => source !== void 0);
|
|
3586
|
+
if (sources.length !== 1 || rule.slot !== void 0 && (typeof rule.slot !== "string" || !SLOT.test(rule.slot)) || rule.use !== void 0 && (typeof rule.use !== "string" || !USE.test(rule.use))) {
|
|
3587
|
+
throw new TypeError("sandbox egress Credential rule names exactly one slot or binding");
|
|
3249
3588
|
}
|
|
3250
|
-
const
|
|
3251
|
-
if (!
|
|
3252
|
-
if (
|
|
3253
|
-
if (
|
|
3254
|
-
const
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
}
|
|
3261
|
-
|
|
3262
|
-
}
|
|
3263
|
-
|
|
3264
|
-
unanswered.add(entry2.id);
|
|
3265
|
-
return { id: entry2.id, name: entry2.name, args: entry2.args };
|
|
3266
|
-
});
|
|
3267
|
-
return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
|
|
3589
|
+
const header = rule.header === void 0 ? "authorization" : rule.header;
|
|
3590
|
+
if (typeof header !== "string" || !HEADER2.test(header.toLowerCase()) || RESERVED_HEADERS2.has(header.toLowerCase()) || header.toLowerCase().startsWith("x-constal-")) throw new TypeError("sandbox egress Credential header is invalid");
|
|
3591
|
+
if (rule.value !== void 0 && rule.basic !== void 0) throw new TypeError("sandbox egress Credential rule takes value or basic, not both");
|
|
3592
|
+
if (rule.value !== void 0 && (typeof rule.value !== "string" || rule.value.length > 256 || /[\r\n\0]/u.test(rule.value) || rule.value.split("{value}").length !== 2)) throw new TypeError("sandbox egress Credential value must contain {value} exactly once");
|
|
3593
|
+
const basic = rule.basic === void 0 ? void 0 : object4(rule.basic);
|
|
3594
|
+
if (rule.basic !== void 0 && (!basic || Object.keys(basic).some((key) => key !== "username") || basic.username !== void 0 && (typeof basic.username !== "string" || !basic.username || basic.username.length > 128 || /[:\r\n\0]/u.test(basic.username)))) throw new TypeError("sandbox egress Credential basic auth is invalid");
|
|
3595
|
+
return {
|
|
3596
|
+
hosts: normalizeSandboxDomains(rule.hosts),
|
|
3597
|
+
...rule.slot !== void 0 ? { slot: rule.slot } : {},
|
|
3598
|
+
...rule.binding !== void 0 ? { binding: resourceCredentialBinding(rule.binding) } : {},
|
|
3599
|
+
...rule.use !== void 0 ? { use: rule.use } : {},
|
|
3600
|
+
header: header.toLowerCase(),
|
|
3601
|
+
...basic ? { basic: basic.username === void 0 ? {} : { username: basic.username } } : { value: rule.value ?? "Bearer {value}" }
|
|
3602
|
+
};
|
|
3268
3603
|
});
|
|
3269
|
-
const open = unanswered.values().next();
|
|
3270
|
-
if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
|
|
3271
|
-
return messages;
|
|
3272
3604
|
}
|
|
3273
|
-
function
|
|
3274
|
-
|
|
3605
|
+
function normalizeSandboxLabels(value) {
|
|
3606
|
+
if (value === void 0) return {};
|
|
3607
|
+
const input = object4(value);
|
|
3608
|
+
if (!input || Object.keys(input).length > SANDBOX_EGRESS_LIMITS.labels) throw new TypeError("sandbox labels are invalid");
|
|
3609
|
+
const labels = {};
|
|
3610
|
+
for (const [key, label] of Object.entries(input).sort(([left], [right]) => left.localeCompare(right))) {
|
|
3611
|
+
if (!LABEL.test(key) || typeof label !== "string" || label.length > SANDBOX_EGRESS_LIMITS.labelValueLength || /[\u0000-\u001f\u007f]/u.test(label)) throw new TypeError("sandbox label is invalid");
|
|
3612
|
+
labels[key] = label;
|
|
3613
|
+
}
|
|
3614
|
+
return labels;
|
|
3275
3615
|
}
|
|
3276
|
-
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
const
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3284
|
-
|
|
3616
|
+
|
|
3617
|
+
// packages/sdk/src/sandbox-pool.ts
|
|
3618
|
+
var WORKSPACE_ROOT = "/workspace";
|
|
3619
|
+
function absoluteSandboxPath(value) {
|
|
3620
|
+
const segments = [];
|
|
3621
|
+
for (const segment of value.split("/")) {
|
|
3622
|
+
if (!segment || segment === ".") continue;
|
|
3623
|
+
if (segment === "..") segments.pop();
|
|
3624
|
+
else segments.push(segment);
|
|
3625
|
+
}
|
|
3626
|
+
return `/${segments.join("/")}`;
|
|
3285
3627
|
}
|
|
3286
|
-
function
|
|
3287
|
-
|
|
3628
|
+
function normalizeSandboxWorkspacePath(path, cwd = WORKSPACE_ROOT) {
|
|
3629
|
+
if (typeof path !== "string" || !path || typeof cwd !== "string" || !cwd || /[\u0000-\u001f\u007f]/u.test(path) || /[\u0000-\u001f\u007f]/u.test(cwd)) {
|
|
3630
|
+
throw new TypeError("sandbox workspace path is invalid");
|
|
3631
|
+
}
|
|
3632
|
+
const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
|
|
3633
|
+
if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
|
|
3634
|
+
throw new TypeError("sandbox working directory is outside /workspace");
|
|
3635
|
+
}
|
|
3636
|
+
const normalized = absoluteSandboxPath(path.startsWith("/") ? path : `${base}/${path}`);
|
|
3637
|
+
if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
|
|
3638
|
+
throw new TypeError("sandbox path is outside /workspace");
|
|
3639
|
+
}
|
|
3640
|
+
return normalized;
|
|
3288
3641
|
}
|
|
3289
|
-
|
|
3290
|
-
|
|
3642
|
+
var SANDBOX_PROCESS_IO_OPERATIONS = ["process.status", "process.read", "process.write", "process.close"];
|
|
3643
|
+
var SANDBOX_PROCESS_OPERATIONS = ["process.resolve", ...SANDBOX_PROCESS_IO_OPERATIONS, "process.stop"];
|
|
3644
|
+
|
|
3645
|
+
// packages/sdk/src/training.ts
|
|
3646
|
+
var HASH4 = /^[a-f0-9]{64}$/u;
|
|
3647
|
+
var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
|
|
3648
|
+
var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3649
|
+
var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3650
|
+
var PROVIDER_MODEL_ID2 = /^[^\s]{1,512}$/u;
|
|
3651
|
+
var TRAINING_PROVIDER_CAPABILITY = {
|
|
3652
|
+
id: "constal.training-provider",
|
|
3653
|
+
version: "1",
|
|
3654
|
+
hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
|
|
3655
|
+
};
|
|
3656
|
+
var TRAINING_RECIPE_DEFAULTS = {
|
|
3657
|
+
epochs: 1,
|
|
3658
|
+
batchSize: 4,
|
|
3659
|
+
loraRank: 32,
|
|
3660
|
+
learningRate: 1e-4,
|
|
3661
|
+
groupSize: 4,
|
|
3662
|
+
checkpointEvery: 25,
|
|
3663
|
+
evalEvery: 25,
|
|
3664
|
+
maxTrainTokens: 1e6,
|
|
3665
|
+
maxSampleTokens: 5e5
|
|
3666
|
+
};
|
|
3667
|
+
function record9(value) {
|
|
3668
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3291
3669
|
}
|
|
3292
|
-
function
|
|
3293
|
-
if (
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
|
|
3297
|
-
...message2.isError ? { is_error: true } : {}
|
|
3298
|
-
}] };
|
|
3299
|
-
if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
|
|
3300
|
-
...anthropicBlocks(message2.content),
|
|
3301
|
-
...message2.toolCalls.map((call) => {
|
|
3302
|
-
const args = JSON.parse(canonicalJson(call.args));
|
|
3303
|
-
return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
|
|
3304
|
-
})
|
|
3305
|
-
] };
|
|
3306
|
-
return { role: message2.role, content: message2.content };
|
|
3670
|
+
function integer2(value, field2, minimum) {
|
|
3671
|
+
if (!Number.isSafeInteger(value) || Number(value) < minimum) {
|
|
3672
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3673
|
+
}
|
|
3674
|
+
return Number(value);
|
|
3307
3675
|
}
|
|
3308
|
-
function
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
const last = merged.at(-1);
|
|
3312
|
-
if (!last || last.role !== message2.role) merged.push({ ...message2 });
|
|
3313
|
-
else if (typeof last.content === "string" && typeof message2.content === "string") last.content = `${last.content}
|
|
3314
|
-
|
|
3315
|
-
${message2.content}`;
|
|
3316
|
-
else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
|
|
3676
|
+
function finite(value, field2, minimum) {
|
|
3677
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < minimum) {
|
|
3678
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3317
3679
|
}
|
|
3318
|
-
return
|
|
3680
|
+
return value;
|
|
3319
3681
|
}
|
|
3320
|
-
function
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
};
|
|
3327
|
-
if (message2.role === "assistant" && message2.toolCalls) return {
|
|
3328
|
-
role: "assistant",
|
|
3329
|
-
content: message2.content || null,
|
|
3330
|
-
tool_calls: message2.toolCalls.map((call) => ({
|
|
3331
|
-
id: call.id,
|
|
3332
|
-
type: "function",
|
|
3333
|
-
function: { name: call.name, arguments: canonicalJson(call.args) }
|
|
3334
|
-
}))
|
|
3335
|
-
};
|
|
3336
|
-
return { role: message2.role, content: message2.content };
|
|
3682
|
+
function providerPin(value) {
|
|
3683
|
+
const candidate = record9(value);
|
|
3684
|
+
if (!candidate || typeof candidate.crn !== "string" || typeof candidate.hash !== "string" || !HASH4.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "hash"].includes(key))) throw new TypeError("training provider pin is invalid");
|
|
3685
|
+
const parts = parseResourceName(candidate.crn);
|
|
3686
|
+
if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
|
|
3687
|
+
return candidate;
|
|
3337
3688
|
}
|
|
3338
|
-
function
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3689
|
+
function resumePoint(value) {
|
|
3690
|
+
if (value === null) return null;
|
|
3691
|
+
const candidate = record9(value);
|
|
3692
|
+
if (!candidate || typeof candidate.job !== "string" || !JOB_ID.test(candidate.job) || !Number.isSafeInteger(candidate.step) || Number(candidate.step) < 0 || typeof candidate.ref !== "string" || !HASH4.test(candidate.ref) || Object.keys(candidate).some((key) => !["job", "step", "ref"].includes(key))) {
|
|
3693
|
+
throw new TypeError("training resume point is invalid");
|
|
3342
3694
|
}
|
|
3343
|
-
|
|
3344
|
-
|
|
3695
|
+
return candidate;
|
|
3696
|
+
}
|
|
3697
|
+
function trainingProviderMetadata(value) {
|
|
3698
|
+
const candidate = record9(value);
|
|
3699
|
+
const checkpoints = record9(candidate?.checkpoints);
|
|
3700
|
+
if (!candidate || candidate.lifecycleVersion !== 1 || !Array.isArray(candidate.methods) || candidate.methods.length === 0 || candidate.methods.length > 2 || candidate.methods.some((method) => method !== "sft" && method !== "rl") || new Set(candidate.methods).size !== candidate.methods.length || !Array.isArray(candidate.models) || !checkpoints || !Array.isArray(checkpoints.formats) || checkpoints.formats.length === 0 || checkpoints.formats.some((format) => typeof format !== "string" || !/^[a-z0-9][a-z0-9._+-]{0,63}$/u.test(format)) || new Set(checkpoints.formats).size !== checkpoints.formats.length || typeof checkpoints.resume !== "boolean" || typeof checkpoints.fork !== "boolean" || Object.keys(checkpoints).some((key) => !["formats", "resume", "fork"].includes(key)) || Object.keys(candidate).some((key) => !["lifecycleVersion", "methods", "models", "checkpoints"].includes(key))) {
|
|
3701
|
+
throw new TypeError("Training Provider metadata is invalid");
|
|
3345
3702
|
}
|
|
3346
|
-
const
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
|
|
3352
|
-
if (breakpoint && lastHistory !== null && marked.length) {
|
|
3353
|
-
anthropic[lastHistory] = { ...anthropic[lastHistory], content: [...marked.slice(0, -1), { ...marked.at(-1), cache_control: breakpoint }] };
|
|
3703
|
+
const models = candidate.models.map((raw) => {
|
|
3704
|
+
const model = record9(raw);
|
|
3705
|
+
const pricing = record9(model?.pricing);
|
|
3706
|
+
if (!model || typeof model.id !== "string" || !JOB_ID.test(model.id) || typeof model.name !== "string" || !model.name || model.name.length > 128 || typeof model.providerModel !== "string" || !PROVIDER_MODEL_ID2.test(model.providerModel) || !Number.isSafeInteger(model.contextTokens) || Number(model.contextTokens) < 1 || !pricing || pricing.currency !== "USD" || pricing.unit !== "million_tokens" || ["prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].some((key) => !Number.isSafeInteger(pricing[key]) || Number(pricing[key]) < 0) || Object.keys(pricing).some((key) => !["currency", "unit", "prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].includes(key)) || Object.keys(model).some((key) => !["id", "name", "providerModel", "contextTokens", "pricing"].includes(key))) {
|
|
3707
|
+
throw new TypeError("Training Provider model offer is invalid");
|
|
3354
3708
|
}
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
messages: alternating(anthropic),
|
|
3360
|
-
...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
|
|
3361
|
-
...effort === void 0 ? {} : { output_config: { effort } },
|
|
3362
|
-
...temperature === null ? {} : { temperature },
|
|
3363
|
-
...tools.length ? { tools: tools.map((tool, index) => ({
|
|
3364
|
-
name: tool.name,
|
|
3365
|
-
description: tool.description,
|
|
3366
|
-
input_schema: tool.schema,
|
|
3367
|
-
...breakpoint && index === tools.length - 1 ? { cache_control: breakpoint } : {}
|
|
3368
|
-
})) } : {},
|
|
3369
|
-
...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
|
|
3370
|
-
};
|
|
3709
|
+
return raw;
|
|
3710
|
+
});
|
|
3711
|
+
if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
|
|
3712
|
+
throw new TypeError("Training Provider model offers must be unique");
|
|
3371
3713
|
}
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
...openai
|
|
3384
|
-
],
|
|
3385
|
-
...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
|
|
3386
|
-
...effort === void 0 ? {} : { reasoning_effort: effort },
|
|
3387
|
-
...temperature === null ? {} : { temperature },
|
|
3388
|
-
...args.tools?.length ? { tools: args.tools.map((tool) => ({
|
|
3389
|
-
type: "function",
|
|
3390
|
-
function: { name: tool.name, description: tool.description, parameters: tool.schema }
|
|
3391
|
-
})) } : {},
|
|
3392
|
-
...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice },
|
|
3393
|
-
...cache?.key === void 0 ? {} : { prompt_cache_key: cache.key },
|
|
3394
|
-
...cache?.retention === void 0 ? {} : { prompt_cache_retention: cache.retention }
|
|
3395
|
-
};
|
|
3714
|
+
return {
|
|
3715
|
+
lifecycleVersion: 1,
|
|
3716
|
+
methods: candidate.methods,
|
|
3717
|
+
models,
|
|
3718
|
+
checkpoints
|
|
3719
|
+
};
|
|
3720
|
+
}
|
|
3721
|
+
function datasetRef(value, field2) {
|
|
3722
|
+
const candidate = record9(value);
|
|
3723
|
+
if (!candidate || typeof candidate.crn !== "string" || parseResourceName(datasetName(candidate.crn)).kind !== "dataset" || typeof candidate.version !== "string" || !VERSION4.test(candidate.version) || typeof candidate.hash !== "string" || !HASH4.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "version", "hash"].includes(key))) {
|
|
3724
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3396
3725
|
}
|
|
3397
|
-
|
|
3726
|
+
return candidate;
|
|
3398
3727
|
}
|
|
3399
|
-
function
|
|
3400
|
-
|
|
3728
|
+
function scorerRef(value, field2) {
|
|
3729
|
+
const candidate = record9(value);
|
|
3730
|
+
if (!candidate || typeof candidate.crn !== "string" || parseResourceName(scorerName(candidate.crn)).kind !== "scorer" || typeof candidate.version !== "string" || !VERSION4.test(candidate.version) || typeof candidate.hash !== "string" || !HASH4.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "version", "hash"].includes(key))) {
|
|
3731
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3732
|
+
}
|
|
3733
|
+
return candidate;
|
|
3401
3734
|
}
|
|
3402
|
-
function
|
|
3403
|
-
|
|
3404
|
-
|
|
3735
|
+
function trainingSteps(value) {
|
|
3736
|
+
if (!Array.isArray(value) || value.length === 0) throw new TypeError("training steps are invalid");
|
|
3737
|
+
const steps = value.map((raw) => {
|
|
3738
|
+
const step = record9(raw);
|
|
3739
|
+
if (!step || step.kind !== "tool" && step.kind !== "turn" || typeof step.name !== "string" || !step.name || step.name.length > 256 || Object.keys(step).some((key) => key !== "kind" && key !== "name")) throw new TypeError("training step is invalid");
|
|
3740
|
+
return { kind: step.kind, name: step.name };
|
|
3741
|
+
});
|
|
3742
|
+
if (new Set(steps.map((step) => canonicalJson(step))).size !== steps.length) throw new TypeError("training steps must be unique");
|
|
3743
|
+
return steps;
|
|
3744
|
+
}
|
|
3745
|
+
function trainingCorrection(value) {
|
|
3746
|
+
const candidate = record9(value);
|
|
3747
|
+
const message2 = record9(candidate?.message);
|
|
3748
|
+
if (!candidate || typeof candidate.turn !== "string" || !HASH4.test(candidate.turn) || !message2 || typeof message2.content !== "string" || message2.reasoning !== void 0 && typeof message2.reasoning !== "string" || message2.toolCalls !== void 0 && !Array.isArray(message2.toolCalls) || Object.keys(candidate).some((key) => key !== "turn" && key !== "message") || Object.keys(message2).some((key) => !["content", "toolCalls", "reasoning"].includes(key))) {
|
|
3749
|
+
throw new TypeError("training correction is invalid");
|
|
3750
|
+
}
|
|
3751
|
+
const toolCalls = message2.toolCalls?.map((raw) => {
|
|
3752
|
+
const call = record9(raw);
|
|
3753
|
+
if (!call || typeof call.id !== "string" || !call.id || typeof call.name !== "string" || !call.name || !Object.hasOwn(call, "args") || Object.keys(call).some((key) => !["id", "name", "args"].includes(key))) throw new TypeError("training correction Tool call is invalid");
|
|
3754
|
+
canonicalJson(call.args);
|
|
3755
|
+
return { id: call.id, name: call.name, args: call.args };
|
|
3756
|
+
});
|
|
3757
|
+
if (toolCalls && new Set(toolCalls.map((call) => call.id)).size !== toolCalls.length) {
|
|
3758
|
+
throw new TypeError("training correction Tool call ids must be unique");
|
|
3759
|
+
}
|
|
3760
|
+
return { turn: candidate.turn, message: {
|
|
3761
|
+
content: message2.content,
|
|
3762
|
+
...toolCalls?.length ? { toolCalls } : {},
|
|
3763
|
+
...message2.reasoning ? { reasoning: message2.reasoning } : {}
|
|
3764
|
+
} };
|
|
3405
3765
|
}
|
|
3406
|
-
function
|
|
3407
|
-
const
|
|
3408
|
-
const
|
|
3409
|
-
|
|
3410
|
-
|
|
3411
|
-
|
|
3412
|
-
|
|
3766
|
+
function trainingRecipe(value) {
|
|
3767
|
+
const candidate = record9(value);
|
|
3768
|
+
const allowed = [
|
|
3769
|
+
"method",
|
|
3770
|
+
"baseModel",
|
|
3771
|
+
"chatFormat",
|
|
3772
|
+
"steps",
|
|
3773
|
+
"dataset",
|
|
3774
|
+
"validationDataset",
|
|
3775
|
+
"scorers",
|
|
3776
|
+
"loraRank",
|
|
3777
|
+
"learningRate",
|
|
3778
|
+
"epochs",
|
|
3779
|
+
"batchSize",
|
|
3780
|
+
"groupSize",
|
|
3781
|
+
"temperature",
|
|
3782
|
+
"seed",
|
|
3783
|
+
"checkpointEvery",
|
|
3784
|
+
"evalEvery",
|
|
3785
|
+
"maxTrainTokens",
|
|
3786
|
+
"maxSampleTokens",
|
|
3787
|
+
"budgetMicroUsd"
|
|
3788
|
+
];
|
|
3789
|
+
if (!candidate || candidate.method !== "sft" && candidate.method !== "rl" || typeof candidate.baseModel !== "string" || !PROVIDER_MODEL_ID2.test(candidate.baseModel) || !Array.isArray(candidate.scorers) || candidate.method === "rl" && candidate.scorers.length === 0 || Object.keys(candidate).some((key) => !allowed.includes(key))) throw new TypeError("training recipe is invalid");
|
|
3790
|
+
const recipe = {
|
|
3791
|
+
method: candidate.method,
|
|
3792
|
+
baseModel: candidate.baseModel,
|
|
3793
|
+
chatFormat: chatFormatPin(candidate.chatFormat),
|
|
3794
|
+
...candidate.steps === void 0 ? {} : { steps: trainingSteps(candidate.steps) },
|
|
3795
|
+
dataset: datasetRef(candidate.dataset, "training dataset"),
|
|
3796
|
+
validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
|
|
3797
|
+
scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
|
|
3798
|
+
loraRank: integer2(candidate.loraRank, "LoRA rank", 1),
|
|
3799
|
+
learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE),
|
|
3800
|
+
epochs: integer2(candidate.epochs, "epochs", 1),
|
|
3801
|
+
batchSize: integer2(candidate.batchSize, "batch size", 1),
|
|
3802
|
+
groupSize: integer2(candidate.groupSize, "group size", 1),
|
|
3803
|
+
temperature: finite(candidate.temperature, "temperature", 0),
|
|
3804
|
+
seed: integer2(candidate.seed, "seed", 0),
|
|
3805
|
+
checkpointEvery: integer2(candidate.checkpointEvery, "checkpoint interval", 1),
|
|
3806
|
+
evalEvery: integer2(candidate.evalEvery, "evaluation interval", 1),
|
|
3807
|
+
maxTrainTokens: integer2(candidate.maxTrainTokens, "training token limit", 1),
|
|
3808
|
+
maxSampleTokens: integer2(candidate.maxSampleTokens, "sample token limit", 1),
|
|
3809
|
+
budgetMicroUsd: integer2(candidate.budgetMicroUsd, "training budget", 1)
|
|
3413
3810
|
};
|
|
3811
|
+
if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
|
|
3812
|
+
return recipe;
|
|
3414
3813
|
}
|
|
3415
|
-
function
|
|
3416
|
-
const
|
|
3417
|
-
if (!
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
let refusal;
|
|
3421
|
-
let reasoningContent;
|
|
3422
|
-
let usage;
|
|
3423
|
-
if (protocol === "anthropic") {
|
|
3424
|
-
if (!Array.isArray(source.content)) throw new TypeError("Anthropic model response content is invalid");
|
|
3425
|
-
const blocks = source.content;
|
|
3426
|
-
content2 = blocks.map((candidate) => {
|
|
3427
|
-
const block = record7(candidate);
|
|
3428
|
-
if (block?.type === "text" && typeof block.text === "string") return block.text;
|
|
3429
|
-
if (block?.type === "tool_use") {
|
|
3430
|
-
if (typeof block.id !== "string" || typeof block.name !== "string") throw new TypeError("Anthropic tool use is invalid");
|
|
3431
|
-
toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
|
|
3432
|
-
}
|
|
3433
|
-
return "";
|
|
3434
|
-
}).join("");
|
|
3435
|
-
const values = record7(source.usage) ?? {};
|
|
3436
|
-
const cached = integer2(values.cache_read_input_tokens);
|
|
3437
|
-
usage = {
|
|
3438
|
-
input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
|
|
3439
|
-
output: integer2(values.output_tokens),
|
|
3440
|
-
cached,
|
|
3441
|
-
...cacheWrite(values),
|
|
3442
|
-
...costMetadata(values)
|
|
3443
|
-
};
|
|
3444
|
-
} else if (protocol === "openai") {
|
|
3445
|
-
const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null);
|
|
3446
|
-
const message2 = record7(choice?.message);
|
|
3447
|
-
if (!message2) throw new TypeError("OpenAI-compatible model response message is invalid");
|
|
3448
|
-
content2 = typeof message2.content === "string" ? message2.content : "";
|
|
3449
|
-
refusal = typeof message2.refusal === "string" ? message2.refusal : void 0;
|
|
3450
|
-
reasoningContent = typeof message2.reasoning_content === "string" ? message2.reasoning_content : void 0;
|
|
3451
|
-
if (message2.tool_calls !== void 0 && !Array.isArray(message2.tool_calls)) throw new TypeError("OpenAI-compatible tool calls are invalid");
|
|
3452
|
-
for (const candidate of Array.isArray(message2.tool_calls) ? message2.tool_calls : []) {
|
|
3453
|
-
const call = record7(candidate);
|
|
3454
|
-
const fn = record7(call?.function);
|
|
3455
|
-
if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") {
|
|
3456
|
-
throw new TypeError("OpenAI-compatible tool call is invalid");
|
|
3457
|
-
}
|
|
3458
|
-
let args;
|
|
3459
|
-
try {
|
|
3460
|
-
args = JSON.parse(fn.arguments);
|
|
3461
|
-
} catch {
|
|
3462
|
-
throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
|
|
3463
|
-
}
|
|
3464
|
-
toolCalls.push({ id: call.id, name: fn.name, args });
|
|
3465
|
-
}
|
|
3466
|
-
const values = record7(source.usage) ?? {};
|
|
3467
|
-
usage = {
|
|
3468
|
-
input: integer2(values.prompt_tokens),
|
|
3469
|
-
output: integer2(values.completion_tokens),
|
|
3470
|
-
cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
|
|
3471
|
-
...cacheWrite(values),
|
|
3472
|
-
...costMetadata(values)
|
|
3473
|
-
};
|
|
3474
|
-
} else throw new TypeError("model gateway protocol is invalid");
|
|
3814
|
+
function startTrainingRequest(value) {
|
|
3815
|
+
const candidate = record9(value);
|
|
3816
|
+
if (!candidate || candidate.jobId !== void 0 && (typeof candidate.jobId !== "string" || !JOB_ID.test(candidate.jobId)) || typeof candidate.outputModelId !== "string" || !MODEL_ID.test(candidate.outputModelId) || Object.keys(candidate).some((key) => !["jobId", "provider", "resumeFrom", "recipe", "outputModelId"].includes(key))) {
|
|
3817
|
+
throw new TypeError("training request is invalid");
|
|
3818
|
+
}
|
|
3475
3819
|
return {
|
|
3476
|
-
|
|
3477
|
-
...
|
|
3478
|
-
...
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
provider,
|
|
3482
|
-
model,
|
|
3483
|
-
completion: modelCompletionStatus(protocol, raw)
|
|
3820
|
+
...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
|
|
3821
|
+
...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
|
|
3822
|
+
...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
|
|
3823
|
+
recipe: trainingRecipe(candidate.recipe),
|
|
3824
|
+
outputModelId: candidate.outputModelId
|
|
3484
3825
|
};
|
|
3485
3826
|
}
|
|
3486
|
-
function modelCompletionStatus(protocol, raw) {
|
|
3487
|
-
const source = record7(raw) ?? {};
|
|
3488
|
-
const value = protocol === "anthropic" ? source.stop_reason : record7(Array.isArray(source.choices) ? source.choices[0] : null)?.finish_reason;
|
|
3489
|
-
const reason = typeof value === "string" ? value : null;
|
|
3490
|
-
const complete = protocol === "anthropic" ? ["end_turn", "tool_use", "stop_sequence"] : ["stop", "tool_calls", "function_call"];
|
|
3491
|
-
const incomplete = protocol === "anthropic" ? ["max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"] : ["length", "content_filter", "error", "cancelled", "canceled"];
|
|
3492
|
-
return { status: reason !== null && complete.includes(reason) ? "complete" : reason !== null && incomplete.includes(reason) ? "incomplete" : "unknown", reason };
|
|
3493
|
-
}
|
|
3494
3827
|
|
|
3495
3828
|
// packages/sdk/src/gateway.ts
|
|
3496
3829
|
async function checkpointArtifactRef(value) {
|
|
3497
3830
|
return await sha256Hex(canonicalJson(value));
|
|
3498
3831
|
}
|
|
3499
3832
|
var SLOT2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3500
|
-
var
|
|
3833
|
+
var HASH5 = /^[a-f0-9]{64}$/u;
|
|
3501
3834
|
var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
|
|
3502
3835
|
function httpsUrl(value, field2) {
|
|
3503
3836
|
if (value === void 0) return;
|
|
@@ -3562,7 +3895,7 @@ function checkpointImportRequest(value) {
|
|
|
3562
3895
|
const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
|
|
3563
3896
|
const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
|
|
3564
3897
|
const model = source?.model && typeof source.model === "object" && !Array.isArray(source.model) ? source.model : null;
|
|
3565
|
-
if (!source || typeof source.deploymentId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(source.deploymentId) || !provenance || !provider || typeof provider.crn !== "string" || typeof provider.hash !== "string" || !
|
|
3898
|
+
if (!source || typeof source.deploymentId !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(source.deploymentId) || !provenance || !provider || typeof provider.crn !== "string" || typeof provider.hash !== "string" || !HASH5.test(provider.hash) || Object.keys(provider).some((key) => !["crn", "hash"].includes(key)) || typeof provenance.job !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(provenance.job) || typeof provenance.baseModel !== "string" || !provenance.baseModel || provenance.baseModel.length > 512 || !checkpoint || !Number.isSafeInteger(checkpoint.step) || Number(checkpoint.step) < 0 || typeof checkpoint.ref !== "string" || !HASH5.test(checkpoint.ref) || typeof checkpoint.format !== "string" || !/^[a-z0-9][a-z0-9._+-]{0,63}$/u.test(checkpoint.format) || checkpoint.createdAt !== null && (!Number.isSafeInteger(checkpoint.createdAt) || Number(checkpoint.createdAt) < 0) || Object.keys(checkpoint).some((key) => !["step", "ref", "format", "createdAt"].includes(key)) || Object.keys(provenance).some((key) => !["provider", "job", "baseModel", "checkpoint"].includes(key)) || !artifact || artifact.ref !== checkpoint.ref || !artifactValue || Object.keys(artifact).some((key) => !["ref", "value"].includes(key)) || !model || typeof model.id !== "string" || !MODEL_RESOURCE_ID.test(model.id) || typeof model.displayName !== "string" || !model.displayName || typeof model.temperature !== "number" || !Number.isFinite(model.temperature) || model.temperature < 0 || model.temperature > 2 || Object.keys(model).some((key) => !["id", "displayName", "temperature"].includes(key)) || Object.keys(source).some((key) => !["deploymentId", "source", "artifact", "model"].includes(key))) {
|
|
3566
3899
|
throw new TypeError("checkpoint import request is invalid");
|
|
3567
3900
|
}
|
|
3568
3901
|
try {
|
|
@@ -3580,7 +3913,7 @@ function checkpointImportRequest(value) {
|
|
|
3580
3913
|
function checkpointDeploymentRequest(value) {
|
|
3581
3914
|
const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3582
3915
|
const gateway2 = source?.gateway && typeof source.gateway === "object" && !Array.isArray(source.gateway) ? source.gateway : null;
|
|
3583
|
-
if (!source || !gateway2 || typeof gateway2.crn !== "string" || typeof gateway2.hash !== "string" || !
|
|
3916
|
+
if (!source || !gateway2 || typeof gateway2.crn !== "string" || typeof gateway2.hash !== "string" || !HASH5.test(gateway2.hash) || Object.keys(gateway2).some((key) => !["crn", "hash"].includes(key)) || Object.keys(source).some((key) => !["gateway", "import"].includes(key))) {
|
|
3584
3917
|
throw new TypeError("checkpoint deployment request is invalid");
|
|
3585
3918
|
}
|
|
3586
3919
|
try {
|
|
@@ -3660,12 +3993,16 @@ function gatewayPackageMetadata(value) {
|
|
|
3660
3993
|
const discovery = discoverySetup(source.discovery);
|
|
3661
3994
|
const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
|
|
3662
3995
|
const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
|
|
3996
|
+
const chatFormat2 = source.chatFormat === void 0 ? void 0 : chatFormatMetadata(source.chatFormat);
|
|
3663
3997
|
if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
|
|
3664
3998
|
throw new TypeError("Training Provider packages must implement the exact Training Provider capability");
|
|
3665
3999
|
}
|
|
3666
4000
|
if (checkpointImport && (!capabilities.some((contract) => contract.id === MODEL_COMPLETION_CAPABILITY.id && contract.version === MODEL_COMPLETION_CAPABILITY.version && contract.hash === MODEL_COMPLETION_CAPABILITY.hash) || !capabilities.some((contract) => contract.id === MODEL_CHECKPOINT_IMPORT_CAPABILITY.id && contract.version === MODEL_CHECKPOINT_IMPORT_CAPABILITY.version && contract.hash === MODEL_CHECKPOINT_IMPORT_CAPABILITY.hash))) {
|
|
3667
4001
|
throw new TypeError("Checkpoint import Gateways must implement exact completion and checkpoint import capabilities");
|
|
3668
4002
|
}
|
|
4003
|
+
if (chatFormat2 && !capabilities.some((contract) => contract.id === CHAT_FORMAT_CAPABILITY.id && contract.version === CHAT_FORMAT_CAPABILITY.version && contract.hash === CHAT_FORMAT_CAPABILITY.hash)) {
|
|
4004
|
+
throw new TypeError("Chat format packages must implement the exact chat format capability");
|
|
4005
|
+
}
|
|
3669
4006
|
return {
|
|
3670
4007
|
lifecycleVersion: 1,
|
|
3671
4008
|
displayName: source.displayName,
|
|
@@ -3680,7 +4017,8 @@ function gatewayPackageMetadata(value) {
|
|
|
3680
4017
|
...configEgress.length ? { configEgress } : {},
|
|
3681
4018
|
...discovery ? { discovery } : {},
|
|
3682
4019
|
...training ? { training } : {},
|
|
3683
|
-
...checkpointImport ? { checkpointImport } : {}
|
|
4020
|
+
...checkpointImport ? { checkpointImport } : {},
|
|
4021
|
+
...chatFormat2 ? { chatFormat: chatFormat2 } : {}
|
|
3684
4022
|
};
|
|
3685
4023
|
}
|
|
3686
4024
|
function resolveGatewayEgress(metadata3, config) {
|
|
@@ -3722,7 +4060,8 @@ function gateway(definition) {
|
|
|
3722
4060
|
configEgress: definition.configEgress,
|
|
3723
4061
|
discovery: definition.discovery,
|
|
3724
4062
|
training: definition.training,
|
|
3725
|
-
checkpointImport: definition.checkpointImport
|
|
4063
|
+
checkpointImport: definition.checkpointImport,
|
|
4064
|
+
chatFormat: definition.chatFormat
|
|
3726
4065
|
});
|
|
3727
4066
|
const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
|
|
3728
4067
|
for (const binding of gateway2.configEgress ?? []) {
|
|
@@ -3749,6 +4088,10 @@ function gateway(definition) {
|
|
|
3749
4088
|
throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
|
|
3750
4089
|
}
|
|
3751
4090
|
}
|
|
4091
|
+
if (gateway2.chatFormat && ["render", "parse"].some((op) => {
|
|
4092
|
+
const operation = declarations.find((candidate) => candidate.op === op);
|
|
4093
|
+
return !operation || operation.async || operation.effect !== "read-only" || operation.recovery.kind !== "repeat";
|
|
4094
|
+
})) throw new TypeError("Chat format render and parse must be synchronous, read-only, and repeatable");
|
|
3752
4095
|
return declarations;
|
|
3753
4096
|
} };
|
|
3754
4097
|
return Object.freeze(wrapped);
|
|
@@ -3768,6 +4111,88 @@ function trainingProvider(definition) {
|
|
|
3768
4111
|
}
|
|
3769
4112
|
});
|
|
3770
4113
|
}
|
|
4114
|
+
var chatRenderRequestSchema = {
|
|
4115
|
+
type: "object",
|
|
4116
|
+
required: ["system", "messages", "tools", "toolChoice", "effort", "train"],
|
|
4117
|
+
additionalProperties: false,
|
|
4118
|
+
properties: {
|
|
4119
|
+
system: { type: ["string", "null"] },
|
|
4120
|
+
messages: { type: "array", items: { type: "object" } },
|
|
4121
|
+
tools: { type: "array", items: {
|
|
4122
|
+
type: "object",
|
|
4123
|
+
required: ["name", "description", "schema"],
|
|
4124
|
+
additionalProperties: false,
|
|
4125
|
+
properties: { name: { type: "string" }, description: { type: "string" }, schema: { type: "object" } }
|
|
4126
|
+
} },
|
|
4127
|
+
toolChoice: { enum: ["auto", "required", null] },
|
|
4128
|
+
effort: { type: ["string", "null"] },
|
|
4129
|
+
train: { type: "array", items: { type: "integer", minimum: 0 } }
|
|
4130
|
+
}
|
|
4131
|
+
};
|
|
4132
|
+
var tokensSchema = { type: "array", items: { type: "integer", minimum: 0 } };
|
|
4133
|
+
var chatFormatOperations = [
|
|
4134
|
+
{
|
|
4135
|
+
op: "render",
|
|
4136
|
+
description: "Render a conversation to tokens, with the spans of its trained assistant turns.",
|
|
4137
|
+
schema: chatRenderRequestSchema,
|
|
4138
|
+
resultSchema: { type: "object", required: ["tokens", "spans", "stop"], additionalProperties: false, properties: {
|
|
4139
|
+
tokens: tokensSchema,
|
|
4140
|
+
stop: tokensSchema,
|
|
4141
|
+
spans: { type: "array", items: {
|
|
4142
|
+
type: "object",
|
|
4143
|
+
required: ["message", "start", "end"],
|
|
4144
|
+
additionalProperties: false,
|
|
4145
|
+
properties: {
|
|
4146
|
+
message: { type: "integer", minimum: 0 },
|
|
4147
|
+
start: { type: "integer", minimum: 0 },
|
|
4148
|
+
end: { type: "integer", minimum: 1 }
|
|
4149
|
+
}
|
|
4150
|
+
} }
|
|
4151
|
+
} },
|
|
4152
|
+
effect: "read-only",
|
|
4153
|
+
recovery: { kind: "repeat" },
|
|
4154
|
+
async: false,
|
|
4155
|
+
usage: { meter: "none", priceTable: null }
|
|
4156
|
+
},
|
|
4157
|
+
{
|
|
4158
|
+
op: "parse",
|
|
4159
|
+
description: "Parse sampled tokens into an assistant turn.",
|
|
4160
|
+
schema: { type: "object", required: ["tokens"], additionalProperties: false, properties: { tokens: tokensSchema } },
|
|
4161
|
+
resultSchema: {
|
|
4162
|
+
type: "object",
|
|
4163
|
+
required: ["content", "toolCalls", "reasoningContent", "stopped"],
|
|
4164
|
+
additionalProperties: false,
|
|
4165
|
+
properties: {
|
|
4166
|
+
content: { type: "string" },
|
|
4167
|
+
toolCalls: { type: "array", items: { type: "object" } },
|
|
4168
|
+
reasoningContent: { type: ["string", "null"] },
|
|
4169
|
+
stopped: { type: "boolean" }
|
|
4170
|
+
}
|
|
4171
|
+
},
|
|
4172
|
+
effect: "read-only",
|
|
4173
|
+
recovery: { kind: "repeat" },
|
|
4174
|
+
async: false,
|
|
4175
|
+
usage: { meter: "none", priceTable: null }
|
|
4176
|
+
}
|
|
4177
|
+
];
|
|
4178
|
+
function chatFormat(definition) {
|
|
4179
|
+
const { render, parse, ...connection } = definition;
|
|
4180
|
+
if (typeof render !== "function" || typeof parse !== "function") throw new TypeError("chat format definition is invalid");
|
|
4181
|
+
return gateway({
|
|
4182
|
+
...connection,
|
|
4183
|
+
kind: "service",
|
|
4184
|
+
capabilities: [CHAT_FORMAT_CAPABILITY],
|
|
4185
|
+
catalog: () => chatFormatOperations.map((operation) => ({ ...operation })),
|
|
4186
|
+
async invoke(request, context) {
|
|
4187
|
+
if (request.op === "render") {
|
|
4188
|
+
const input = chatRenderInput(request.args);
|
|
4189
|
+
return chatRendering(await render(input, context), input);
|
|
4190
|
+
}
|
|
4191
|
+
if (request.op === "parse") return chatParsed(await parse(chatParseInput(request.args), context));
|
|
4192
|
+
throw new TypeError(`chat format operation is unknown: ${request.op}`);
|
|
4193
|
+
}
|
|
4194
|
+
});
|
|
4195
|
+
}
|
|
3771
4196
|
var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
|
|
3772
4197
|
id: "constal.model-checkpoint-import",
|
|
3773
4198
|
version: "1",
|
|
@@ -3803,7 +4228,7 @@ function credentialProviderConfigSchema(value) {
|
|
|
3803
4228
|
function interactionRecord(value) {
|
|
3804
4229
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3805
4230
|
}
|
|
3806
|
-
function
|
|
4231
|
+
function exactKeys4(value, allowed) {
|
|
3807
4232
|
return Object.keys(value).every((key) => allowed.includes(key));
|
|
3808
4233
|
}
|
|
3809
4234
|
function nonemptyText(value) {
|
|
@@ -3821,27 +4246,27 @@ function credentialInteractionEvent(value) {
|
|
|
3821
4246
|
if (event.kind === "callback") {
|
|
3822
4247
|
const parameters = interactionRecord(event.parameters);
|
|
3823
4248
|
const headers = interactionRecord(event.headers);
|
|
3824
|
-
if (!
|
|
4249
|
+
if (!exactKeys4(event, ["kind", "method", "parameters", "headers", "bodyBase64"]) || !["GET", "POST"].includes(String(event.method ?? "")) || !parameters || Object.entries(parameters).some(([key, item]) => typeof item !== "string") || !headers || Object.entries(headers).some(([key, item]) => typeof item !== "string") || event.bodyBase64 !== null && (typeof event.bodyBase64 !== "string" || !/^[A-Za-z0-9+/]*={0,2}$/u.test(event.bodyBase64))) {
|
|
3825
4250
|
throw new TypeError("credential interaction callback is invalid");
|
|
3826
4251
|
}
|
|
3827
4252
|
} else if (event.kind === "submit") {
|
|
3828
|
-
if (!
|
|
4253
|
+
if (!exactKeys4(event, ["kind", "value"])) {
|
|
3829
4254
|
throw new TypeError("credential interaction submission is invalid");
|
|
3830
4255
|
}
|
|
3831
4256
|
canonicalJson(event.value);
|
|
3832
|
-
} else if (!
|
|
4257
|
+
} else if (!exactKeys4(event, ["kind"])) throw new TypeError("credential interaction event is invalid");
|
|
3833
4258
|
return event;
|
|
3834
4259
|
}
|
|
3835
4260
|
function credentialInteractionPrimaryAction(value, origins) {
|
|
3836
4261
|
const action3 = interactionRecord(value);
|
|
3837
4262
|
const event = interactionRecord(action3?.event);
|
|
3838
|
-
if (!action3 || !event || !nonemptyText(action3.label) || !
|
|
4263
|
+
if (!action3 || !event || !nonemptyText(action3.label) || !exactKeys4(event, ["kind"]) || event.kind !== "continue") {
|
|
3839
4264
|
throw new TypeError("credential interaction primary action is invalid");
|
|
3840
4265
|
}
|
|
3841
4266
|
if (action3.kind === "continue") {
|
|
3842
|
-
if (!
|
|
4267
|
+
if (!exactKeys4(action3, ["kind", "label", "event"])) throw new TypeError("credential interaction primary action is invalid");
|
|
3843
4268
|
} else if (action3.kind === "open-url") {
|
|
3844
|
-
if (!
|
|
4269
|
+
if (!exactKeys4(action3, ["kind", "label", "url", "event"]) || !nonemptyText(action3.url)) {
|
|
3845
4270
|
throw new TypeError("credential interaction primary action is invalid");
|
|
3846
4271
|
}
|
|
3847
4272
|
let url;
|
|
@@ -3864,7 +4289,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3864
4289
|
const expiresAt = action3.kind === "complete" ? null : interactionExpiry(action3.expiresAt, sessionExpiresAt);
|
|
3865
4290
|
if (Number.isNaN(expiresAt)) throw new TypeError("credential interaction action expiry is invalid");
|
|
3866
4291
|
if (action3.kind === "redirect") {
|
|
3867
|
-
if (!
|
|
4292
|
+
if (!exactKeys4(action3, ["kind", "url", "expiresAt"]) || !nonemptyText(action3.url)) {
|
|
3868
4293
|
throw new TypeError("credential interaction redirect is invalid");
|
|
3869
4294
|
}
|
|
3870
4295
|
let url;
|
|
@@ -3877,7 +4302,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3877
4302
|
throw new TypeError("credential interaction redirect is not authorized");
|
|
3878
4303
|
}
|
|
3879
4304
|
} else if (action3.kind === "form") {
|
|
3880
|
-
if (!
|
|
4305
|
+
if (!exactKeys4(action3, ["kind", "schema", "title", "description", "submitLabel", "expiresAt"]) || action3.title !== void 0 && !nonemptyText(action3.title) || action3.description !== void 0 && !nonemptyText(action3.description) || action3.submitLabel !== void 0 && !nonemptyText(action3.submitLabel)) {
|
|
3881
4306
|
throw new TypeError("credential interaction form is invalid");
|
|
3882
4307
|
}
|
|
3883
4308
|
const schemaError = validateJsonSchemaDefinition(action3.schema, "$interaction.form.schema");
|
|
@@ -3886,16 +4311,16 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3886
4311
|
throw new TypeError(`credential interaction form schema is invalid${schemaError ? `: ${schemaError}` : ""}`);
|
|
3887
4312
|
}
|
|
3888
4313
|
} else if (action3.kind === "display") {
|
|
3889
|
-
if (!
|
|
4314
|
+
if (!exactKeys4(action3, ["kind", "instructions", "title", "userCode", "primaryAction", "expiresAt"]) || !nonemptyText(action3.instructions) || action3.title !== void 0 && !nonemptyText(action3.title) || action3.userCode !== void 0 && !nonemptyText(action3.userCode)) {
|
|
3890
4315
|
throw new TypeError("credential interaction display is invalid");
|
|
3891
4316
|
}
|
|
3892
4317
|
credentialInteractionPrimaryAction(action3.primaryAction, origins);
|
|
3893
4318
|
} else if (action3.kind === "wait") {
|
|
3894
|
-
if (!
|
|
4319
|
+
if (!exactKeys4(action3, ["kind", "resume", "expiresAt", "pollAfterMs"]) || !["callback", "poll"].includes(String(action3.resume ?? "")) || expiresAt === null || action3.pollAfterMs !== void 0 && (!Number.isSafeInteger(action3.pollAfterMs) || Number(action3.pollAfterMs) < 1e3 || Number(action3.pollAfterMs) > 3e5) || action3.resume === "poll" && action3.pollAfterMs === void 0 || action3.resume === "callback" && action3.pollAfterMs !== void 0) {
|
|
3895
4320
|
throw new TypeError("credential interaction wait action is invalid");
|
|
3896
4321
|
}
|
|
3897
4322
|
} else {
|
|
3898
|
-
if (!
|
|
4323
|
+
if (!exactKeys4(action3, ["kind", "material", "expiresAt"]) || !nonemptyText(action3.material) || action3.expiresAt !== void 0 && action3.expiresAt !== null && (!Number.isSafeInteger(action3.expiresAt) || Number(action3.expiresAt) <= Date.now())) {
|
|
3899
4324
|
throw new TypeError("credential interaction completion is invalid");
|
|
3900
4325
|
}
|
|
3901
4326
|
}
|
|
@@ -3903,7 +4328,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3903
4328
|
}
|
|
3904
4329
|
function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
|
|
3905
4330
|
const result = interactionRecord(value);
|
|
3906
|
-
if (!result || !
|
|
4331
|
+
if (!result || !exactKeys4(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
|
|
3907
4332
|
const privateState = result.privateState;
|
|
3908
4333
|
if (privateState !== void 0 && privateState !== null && typeof privateState !== "string") throw new TypeError("credential interaction private state is invalid");
|
|
3909
4334
|
return {
|
|
@@ -4018,7 +4443,7 @@ var EVALUATION_LIMITS = {
|
|
|
4018
4443
|
};
|
|
4019
4444
|
var QUESTION_ID = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/u;
|
|
4020
4445
|
var MODEL = /^[a-z0-9][a-z0-9._\/-]{0,255}$/u;
|
|
4021
|
-
function
|
|
4446
|
+
function record10(value) {
|
|
4022
4447
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
4023
4448
|
}
|
|
4024
4449
|
function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
|
|
@@ -4028,7 +4453,7 @@ function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
|
|
|
4028
4453
|
return value;
|
|
4029
4454
|
}
|
|
4030
4455
|
const array = Array.isArray(value);
|
|
4031
|
-
const source = array ? value :
|
|
4456
|
+
const source = array ? value : record10(value);
|
|
4032
4457
|
const prototype = source ? Object.getPrototypeOf(source) : void 0;
|
|
4033
4458
|
if (!source || !array && prototype !== Object.prototype && prototype !== null) throw new TypeError(`${field2} must be JSON text or structure`);
|
|
4034
4459
|
if (ancestors.has(source)) throw new TypeError(`${field2} contains a JSON cycle`);
|
|
@@ -4041,7 +4466,7 @@ function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
|
|
|
4041
4466
|
}
|
|
4042
4467
|
}
|
|
4043
4468
|
function question(id2, value) {
|
|
4044
|
-
const source =
|
|
4469
|
+
const source = record10(value);
|
|
4045
4470
|
if (!source) throw new TypeError(`question ${id2} must be an object`);
|
|
4046
4471
|
const type = source.type;
|
|
4047
4472
|
if (type !== "choice" && type !== "score" && type !== "noul") throw new TypeError(`question ${id2} type must be choice, score, or noul`);
|
|
@@ -4050,7 +4475,7 @@ function question(id2, value) {
|
|
|
4050
4475
|
const unknown = Object.keys(source).find((key) => !["type", "instructions", "criteria"].includes(key));
|
|
4051
4476
|
if (unknown) throw new TypeError(`question ${id2} has an unknown field ${unknown}`);
|
|
4052
4477
|
if (type === "choice") {
|
|
4053
|
-
const criteria2 =
|
|
4478
|
+
const criteria2 = record10(source.criteria);
|
|
4054
4479
|
const options = criteria2 ? Object.keys(criteria2) : [];
|
|
4055
4480
|
if (!criteria2 || options.length < 2) throw new TypeError(`choice question ${id2} needs at least two options`);
|
|
4056
4481
|
if (options.some((option) => !option.trim())) throw new TypeError(`choice question ${id2} has an invalid option key`);
|
|
@@ -4062,7 +4487,7 @@ function question(id2, value) {
|
|
|
4062
4487
|
return { type, instructions, criteria: criteria2.map((level, index) => entry(level, `score question ${id2} level ${index}`)) };
|
|
4063
4488
|
}
|
|
4064
4489
|
if (source.criteria === void 0) return { type, instructions };
|
|
4065
|
-
const criteria =
|
|
4490
|
+
const criteria = record10(source.criteria);
|
|
4066
4491
|
if (!criteria || Object.keys(criteria).some((key) => key !== "true" && key !== "false")) {
|
|
4067
4492
|
throw new TypeError(`noul question ${id2} criteria may only describe true and false`);
|
|
4068
4493
|
}
|
|
@@ -4072,11 +4497,11 @@ function question(id2, value) {
|
|
|
4072
4497
|
} };
|
|
4073
4498
|
}
|
|
4074
4499
|
function evaluationArguments(value) {
|
|
4075
|
-
const source =
|
|
4500
|
+
const source = record10(value);
|
|
4076
4501
|
if (!source) throw new TypeError("evaluation arguments must be an object");
|
|
4077
4502
|
if (source.state === void 0) throw new TypeError("evaluation requires a state");
|
|
4078
4503
|
const state = entry(source.state, "evaluation state");
|
|
4079
|
-
const questionSource =
|
|
4504
|
+
const questionSource = record10(source.questions);
|
|
4080
4505
|
const ids = questionSource ? Object.keys(questionSource) : [];
|
|
4081
4506
|
if (!questionSource || ids.length === 0) throw new TypeError("evaluation requires at least one question");
|
|
4082
4507
|
const questions = /* @__PURE__ */ Object.create(null);
|
|
@@ -4103,14 +4528,14 @@ function probability(value, field2) {
|
|
|
4103
4528
|
return value;
|
|
4104
4529
|
}
|
|
4105
4530
|
function distribution(value, keys, field2) {
|
|
4106
|
-
const source =
|
|
4531
|
+
const source = record10(value);
|
|
4107
4532
|
if (!source) throw new TypeError(`${field2} must map every option to a probability`);
|
|
4108
4533
|
const output = {};
|
|
4109
4534
|
for (const key of keys) output[key] = probability(source[key], `${field2}.${key}`);
|
|
4110
4535
|
return output;
|
|
4111
4536
|
}
|
|
4112
4537
|
function answer(id2, asked, value) {
|
|
4113
|
-
const source =
|
|
4538
|
+
const source = record10(value);
|
|
4114
4539
|
if (!source || source.type !== asked.type) throw new TypeError(`answer ${id2} does not match its ${asked.type} question`);
|
|
4115
4540
|
if (asked.type === "noul") return { type: "noul", noul: probability(source.noul, `answer ${id2} noul`) };
|
|
4116
4541
|
const confidence = probability(source.confidence, `answer ${id2} confidence`);
|
|
@@ -4123,7 +4548,7 @@ function answer(id2, asked, value) {
|
|
|
4123
4548
|
if (typeof source.score !== "number" || !Number.isFinite(source.score) || source.score < 0 || source.score > levels.length - 1) {
|
|
4124
4549
|
throw new TypeError(`answer ${id2} score is outside its levels`);
|
|
4125
4550
|
}
|
|
4126
|
-
const legend =
|
|
4551
|
+
const legend = record10(source.legend);
|
|
4127
4552
|
return {
|
|
4128
4553
|
type: "score",
|
|
4129
4554
|
score: source.score,
|
|
@@ -4137,15 +4562,15 @@ function integer3(value) {
|
|
|
4137
4562
|
}
|
|
4138
4563
|
function evaluationProtocolResult(protocol, raw, provider, model, questions) {
|
|
4139
4564
|
if (protocol !== "typesafe") throw new TypeError("evaluation protocol is invalid");
|
|
4140
|
-
const source =
|
|
4141
|
-
const answers =
|
|
4565
|
+
const source = record10(raw) ?? {};
|
|
4566
|
+
const answers = record10(source.answers);
|
|
4142
4567
|
if (!answers) throw new TypeError("evaluation response has no answers");
|
|
4143
4568
|
const output = {};
|
|
4144
4569
|
for (const [id2, asked] of Object.entries(questions)) {
|
|
4145
4570
|
if (answers[id2] === void 0) throw new TypeError(`evaluation response is missing answer ${id2}`);
|
|
4146
4571
|
output[id2] = answer(id2, asked, answers[id2]);
|
|
4147
4572
|
}
|
|
4148
|
-
const usage =
|
|
4573
|
+
const usage = record10(source.usage) ?? {};
|
|
4149
4574
|
const cost = usage.cost;
|
|
4150
4575
|
const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
|
|
4151
4576
|
return {
|
|
@@ -4172,30 +4597,30 @@ function scoreLevel(answer2) {
|
|
|
4172
4597
|
|
|
4173
4598
|
// packages/sdk/src/mcp.ts
|
|
4174
4599
|
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
4175
|
-
function
|
|
4600
|
+
function record11(value) {
|
|
4176
4601
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
4177
4602
|
}
|
|
4178
4603
|
function mcpToolDescription(value) {
|
|
4179
|
-
const tool =
|
|
4180
|
-
const outputSchema = tool?.outputSchema === void 0 ? {} :
|
|
4604
|
+
const tool = record11(value), inputSchema = record11(tool?.inputSchema);
|
|
4605
|
+
const outputSchema = tool?.outputSchema === void 0 ? {} : record11(tool.outputSchema);
|
|
4181
4606
|
if (!tool || typeof tool.name !== "string" || !tool.name || tool.description !== void 0 && typeof tool.description !== "string" || !inputSchema || outputSchema === null) throw new TerminalIntegrationFailure("MCP server advertised an invalid tool");
|
|
4182
4607
|
return {
|
|
4183
4608
|
name: tool.name,
|
|
4184
4609
|
description: typeof tool.description === "string" ? tool.description : "",
|
|
4185
4610
|
inputSchema,
|
|
4186
4611
|
outputSchema,
|
|
4187
|
-
annotations:
|
|
4612
|
+
annotations: record11(tool.annotations) ?? {}
|
|
4188
4613
|
};
|
|
4189
4614
|
}
|
|
4190
4615
|
function mcpToolResult(value) {
|
|
4191
|
-
const result =
|
|
4192
|
-
if (!result || result.isError !== void 0 && typeof result.isError !== "boolean" || result?.content !== void 0 && !Array.isArray(result.content) || result?.structuredContent !== void 0 && !
|
|
4616
|
+
const result = record11(value);
|
|
4617
|
+
if (!result || result.isError !== void 0 && typeof result.isError !== "boolean" || result?.content !== void 0 && !Array.isArray(result.content) || result?.structuredContent !== void 0 && !record11(result.structuredContent) || result && result.content === void 0 && result.structuredContent === void 0) {
|
|
4193
4618
|
throw new TerminalIntegrationFailure("MCP tools/call result is invalid");
|
|
4194
4619
|
}
|
|
4195
4620
|
return result;
|
|
4196
4621
|
}
|
|
4197
4622
|
function message(value) {
|
|
4198
|
-
const item =
|
|
4623
|
+
const item = record11(value);
|
|
4199
4624
|
if (!item || item.jsonrpc !== "2.0") throw new TerminalIntegrationFailure("MCP transport returned an invalid JSON-RPC message");
|
|
4200
4625
|
return item;
|
|
4201
4626
|
}
|
|
@@ -4235,7 +4660,7 @@ var McpClient = class {
|
|
|
4235
4660
|
for (; ; ) {
|
|
4236
4661
|
const received = message(await this.transport.receive());
|
|
4237
4662
|
if (received.id === id2) {
|
|
4238
|
-
if (
|
|
4663
|
+
if (record11(received.error)) {
|
|
4239
4664
|
const error = received.error;
|
|
4240
4665
|
throw new TerminalIntegrationFailure(`MCP ${typeof error.code === "number" || typeof error.code === "string" ? error.code : "unknown"}: ${typeof error.message === "string" ? error.message : "request failed"}`);
|
|
4241
4666
|
}
|
|
@@ -4260,7 +4685,7 @@ var McpClient = class {
|
|
|
4260
4685
|
}
|
|
4261
4686
|
async initialize() {
|
|
4262
4687
|
if (this.#protocol) return { protocolVersion: this.#protocol, server: {} };
|
|
4263
|
-
const result =
|
|
4688
|
+
const result = record11(await this.#request("initialize", {
|
|
4264
4689
|
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
4265
4690
|
capabilities: {},
|
|
4266
4691
|
clientInfo: this.options.client ?? { name: "Constal", version: "1.0.0" }
|
|
@@ -4271,7 +4696,7 @@ var McpClient = class {
|
|
|
4271
4696
|
this.#protocol = result.protocolVersion;
|
|
4272
4697
|
await this.transport.negotiated?.(this.#protocol);
|
|
4273
4698
|
await this.#serialized(() => this.transport.send({ jsonrpc: "2.0", method: "notifications/initialized" }));
|
|
4274
|
-
return { protocolVersion: this.#protocol, server:
|
|
4699
|
+
return { protocolVersion: this.#protocol, server: record11(result.serverInfo) ?? {} };
|
|
4275
4700
|
}
|
|
4276
4701
|
async request(method, params) {
|
|
4277
4702
|
if (!this.#protocol) throw new TerminalIntegrationFailure("MCP session is not initialized");
|
|
@@ -4281,8 +4706,8 @@ var McpClient = class {
|
|
|
4281
4706
|
const tools = [], cursors = /* @__PURE__ */ new Set();
|
|
4282
4707
|
let cursor;
|
|
4283
4708
|
do {
|
|
4284
|
-
const result =
|
|
4285
|
-
if (!result || !Array.isArray(result.tools) || result.tools.some((item) => !
|
|
4709
|
+
const result = record11(await this.request("tools/list", cursor ? { cursor } : {}));
|
|
4710
|
+
if (!result || !Array.isArray(result.tools) || result.tools.some((item) => !record11(item))) {
|
|
4286
4711
|
throw new TerminalIntegrationFailure("MCP tools/list result is invalid");
|
|
4287
4712
|
}
|
|
4288
4713
|
tools.push(...result.tools);
|
|
@@ -4312,31 +4737,31 @@ var McpClient = class {
|
|
|
4312
4737
|
function validPointer(value) {
|
|
4313
4738
|
return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));
|
|
4314
4739
|
}
|
|
4315
|
-
function
|
|
4740
|
+
function record12(value) {
|
|
4316
4741
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
4317
4742
|
}
|
|
4318
|
-
function
|
|
4743
|
+
function exactKeys5(value, allowed) {
|
|
4319
4744
|
return Object.keys(value).every((key) => allowed.includes(key));
|
|
4320
4745
|
}
|
|
4321
4746
|
function scorerRule(value, depth, state) {
|
|
4322
|
-
const rule =
|
|
4747
|
+
const rule = record12(value);
|
|
4323
4748
|
if (!rule || typeof rule.op !== "string") throw new TypeError("Code Scorer IR is invalid");
|
|
4324
4749
|
if (rule.op === "all" || rule.op === "any") {
|
|
4325
|
-
if (!
|
|
4750
|
+
if (!exactKeys5(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1) {
|
|
4326
4751
|
throw new TypeError("Code Scorer logical rule is invalid");
|
|
4327
4752
|
}
|
|
4328
4753
|
return { op: rule.op, rules: rule.rules.map((child) => scorerRule(child, depth + 1, state)) };
|
|
4329
4754
|
}
|
|
4330
4755
|
if (rule.op === "not") {
|
|
4331
|
-
if (!
|
|
4756
|
+
if (!exactKeys5(rule, ["op", "rule"])) throw new TypeError("Code Scorer not rule is invalid");
|
|
4332
4757
|
return { op: "not", rule: scorerRule(rule.rule, depth + 1, state) };
|
|
4333
4758
|
}
|
|
4334
4759
|
if (rule.op === "schema") {
|
|
4335
|
-
if (!
|
|
4760
|
+
if (!exactKeys5(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record12(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
|
|
4336
4761
|
return rule;
|
|
4337
4762
|
}
|
|
4338
4763
|
if (rule.op === "regex") {
|
|
4339
|
-
if (!
|
|
4764
|
+
if (!exactKeys5(rule, ["op", "path", "pattern", "flags"]) || !validPointer(rule.path) || typeof rule.pattern !== "string" || rule.pattern.length > 4096 || ![void 0, "", "i", "m", "im"].includes(rule.flags)) {
|
|
4340
4765
|
throw new TypeError("Code Scorer regex rule is invalid");
|
|
4341
4766
|
}
|
|
4342
4767
|
try {
|
|
@@ -4347,28 +4772,28 @@ function scorerRule(value, depth, state) {
|
|
|
4347
4772
|
return rule;
|
|
4348
4773
|
}
|
|
4349
4774
|
if (rule.op === "range") {
|
|
4350
|
-
if (!
|
|
4775
|
+
if (!exactKeys5(rule, ["op", "path", "min", "max"]) || !validPointer(rule.path) || rule.min === void 0 && rule.max === void 0 || rule.min !== void 0 && (typeof rule.min !== "number" || !Number.isFinite(rule.min)) || rule.max !== void 0 && (typeof rule.max !== "number" || !Number.isFinite(rule.max)) || typeof rule.min === "number" && typeof rule.max === "number" && rule.min > rule.max) throw new TypeError("Code Scorer range rule is invalid");
|
|
4351
4776
|
return rule;
|
|
4352
4777
|
}
|
|
4353
4778
|
if (rule.op === "equals" || rule.op === "contains") {
|
|
4354
|
-
if (!
|
|
4779
|
+
if (!exactKeys5(rule, ["op", "path", "value"]) || !validPointer(rule.path) || !Object.hasOwn(rule, "value") || new TextEncoder().encode(canonicalJson(rule.value)).byteLength > 65536) {
|
|
4355
4780
|
throw new TypeError(`Code Scorer ${rule.op} rule is invalid`);
|
|
4356
4781
|
}
|
|
4357
4782
|
return rule;
|
|
4358
4783
|
}
|
|
4359
4784
|
if (rule.op === "tool-sequence") {
|
|
4360
|
-
if (!
|
|
4785
|
+
if (!exactKeys5(rule, ["op", "path", "expected", "mode"]) || !validPointer(rule.path) || !Array.isArray(rule.expected) || rule.expected.some((item) => typeof item !== "string" || !/^[A-Za-z0-9._-]{1,128}$/u.test(item)) || rule.mode !== "exact" && rule.mode !== "ordered-subsequence") throw new TypeError("Code Scorer tool sequence rule is invalid");
|
|
4361
4786
|
return rule;
|
|
4362
4787
|
}
|
|
4363
4788
|
if (rule.op === "citations-in-source") {
|
|
4364
|
-
if (!
|
|
4789
|
+
if (!exactKeys5(rule, ["op", "textPath", "sourcesPath"]) || !validPointer(rule.textPath) || !validPointer(rule.sourcesPath)) throw new TypeError("Code Scorer citation rule is invalid");
|
|
4365
4790
|
return rule;
|
|
4366
4791
|
}
|
|
4367
4792
|
throw new TypeError("Code Scorer operation is invalid");
|
|
4368
4793
|
}
|
|
4369
4794
|
function codeScorerIR(value) {
|
|
4370
|
-
const ir =
|
|
4371
|
-
if (!ir || ir.v !== 1 || !
|
|
4795
|
+
const ir = record12(value);
|
|
4796
|
+
if (!ir || ir.v !== 1 || !exactKeys5(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
|
|
4372
4797
|
return { v: 1, rule: scorerRule(ir.rule, 0, { rules: 0 }) };
|
|
4373
4798
|
}
|
|
4374
4799
|
function pointer(value, path) {
|
|
@@ -4380,7 +4805,7 @@ function pointer(value, path) {
|
|
|
4380
4805
|
if (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length) return { found: false, value: void 0 };
|
|
4381
4806
|
current = current[Number(key)];
|
|
4382
4807
|
} else {
|
|
4383
|
-
const source =
|
|
4808
|
+
const source = record12(current);
|
|
4384
4809
|
if (!source || !Object.hasOwn(source, key)) return { found: false, value: void 0 };
|
|
4385
4810
|
current = source[key];
|
|
4386
4811
|
}
|
|
@@ -4414,7 +4839,7 @@ function evaluate(rule, subject) {
|
|
|
4414
4839
|
if (!sources.found || !Array.isArray(sources.value)) return fail(rule.sourcesPath, "citation sources are missing");
|
|
4415
4840
|
const available = new Set(sources.value.flatMap((source, index) => {
|
|
4416
4841
|
if (typeof source === "string") return [source, String(index + 1)];
|
|
4417
|
-
const item =
|
|
4842
|
+
const item = record12(source);
|
|
4418
4843
|
return item ? [String(item.id ?? ""), String(index + 1)].filter(Boolean) : [String(index + 1)];
|
|
4419
4844
|
}));
|
|
4420
4845
|
const citations = [...text2.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
|
|
@@ -4433,7 +4858,7 @@ function evaluate(rule, subject) {
|
|
|
4433
4858
|
const contains = typeof selected.value === "string" && typeof rule.value === "string" ? selected.value.includes(rule.value) : Array.isArray(selected.value) && selected.value.some((value) => canonicalJson(value) === canonicalJson(rule.value));
|
|
4434
4859
|
return contains ? pass() : fail(rule.path, "value is not contained");
|
|
4435
4860
|
}
|
|
4436
|
-
const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(
|
|
4861
|
+
const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record12(item)?.name ?? "")) : [];
|
|
4437
4862
|
const sequence = rule.mode === "exact" ? names.length === rule.expected.length && names.every((name, index) => name === rule.expected[index]) : rule.expected.reduce((cursor, expected) => {
|
|
4438
4863
|
const index = names.indexOf(expected, cursor);
|
|
4439
4864
|
return index < 0 ? Number.POSITIVE_INFINITY : index + 1;
|
|
@@ -4453,9 +4878,9 @@ function evaluateCodeScorer(raw, subject) {
|
|
|
4453
4878
|
|
|
4454
4879
|
// packages/sdk/src/errors.ts
|
|
4455
4880
|
var GateExhausted = class extends Error {
|
|
4456
|
-
constructor(
|
|
4881
|
+
constructor(record13) {
|
|
4457
4882
|
super("turn gate exhausted");
|
|
4458
|
-
this.record =
|
|
4883
|
+
this.record = record13;
|
|
4459
4884
|
this.name = "GateExhausted";
|
|
4460
4885
|
}
|
|
4461
4886
|
record;
|
|
@@ -4666,6 +5091,7 @@ export {
|
|
|
4666
5091
|
AGENT_UI_DEFAULTS,
|
|
4667
5092
|
AfterYield,
|
|
4668
5093
|
ApiError,
|
|
5094
|
+
CHAT_FORMAT_CAPABILITY,
|
|
4669
5095
|
CONSTAL_API_CAPABILITY,
|
|
4670
5096
|
CONSTAL_API_GET_KINDS,
|
|
4671
5097
|
CONSTAL_API_MODEL_TOOL_DESCRIPTIONS,
|
|
@@ -4677,6 +5103,7 @@ export {
|
|
|
4677
5103
|
CommitGateRejected,
|
|
4678
5104
|
CredentialRevoked,
|
|
4679
5105
|
CredentialUnavailable,
|
|
5106
|
+
DATA_SHARE_FEE_BPS,
|
|
4680
5107
|
DirectNetworkDenied,
|
|
4681
5108
|
EVALUATION_LIMITS,
|
|
4682
5109
|
EffectCeilingExceeded,
|
|
@@ -4692,6 +5119,7 @@ export {
|
|
|
4692
5119
|
MODEL_EVALUATION_CAPABILITY,
|
|
4693
5120
|
McpClient,
|
|
4694
5121
|
NondeterministicReplay,
|
|
5122
|
+
NotAppendOnly,
|
|
4695
5123
|
OutcomeUnknown,
|
|
4696
5124
|
PolicyConstraintFailed,
|
|
4697
5125
|
PolicyDecisionFailed,
|
|
@@ -4706,6 +5134,7 @@ export {
|
|
|
4706
5134
|
SpawnCardinality,
|
|
4707
5135
|
SwallowedYield,
|
|
4708
5136
|
TRAINING_PROVIDER_CAPABILITY,
|
|
5137
|
+
TRAINING_RECIPE_DEFAULTS,
|
|
4709
5138
|
TerminalIntegrationFailure,
|
|
4710
5139
|
ToolUnavailable,
|
|
4711
5140
|
UI_ASSET_CONTENT_TYPES,
|
|
@@ -4738,6 +5167,14 @@ export {
|
|
|
4738
5167
|
channelSourceEvidence,
|
|
4739
5168
|
channelSubscriptionRequest,
|
|
4740
5169
|
channelTarget,
|
|
5170
|
+
chatFormat,
|
|
5171
|
+
chatFormatMetadata,
|
|
5172
|
+
chatFormatPin,
|
|
5173
|
+
chatParseInput,
|
|
5174
|
+
chatParsed,
|
|
5175
|
+
chatRenderInput,
|
|
5176
|
+
chatRenderRequest,
|
|
5177
|
+
chatRendering,
|
|
4741
5178
|
checkpointArtifactRef,
|
|
4742
5179
|
checkpointDeploymentRequest,
|
|
4743
5180
|
checkpointImportMetadata,
|
|
@@ -4760,6 +5197,7 @@ export {
|
|
|
4760
5197
|
customerTenantName,
|
|
4761
5198
|
cutBatches,
|
|
4762
5199
|
cutPartitions,
|
|
5200
|
+
dataShareEarningMicroUsd,
|
|
4763
5201
|
datasetName,
|
|
4764
5202
|
evaluateCodeScorer,
|
|
4765
5203
|
evaluatePolicyDefinition,
|
|
@@ -4807,7 +5245,6 @@ export {
|
|
|
4807
5245
|
policy,
|
|
4808
5246
|
policyName,
|
|
4809
5247
|
race,
|
|
4810
|
-
renderTrainingCompletion,
|
|
4811
5248
|
resolveBindingOwner,
|
|
4812
5249
|
resolveContainerImageSource,
|
|
4813
5250
|
resolveGatewayEgress,
|
|
@@ -4821,6 +5258,7 @@ export {
|
|
|
4821
5258
|
resourcePattern,
|
|
4822
5259
|
resourceSelector,
|
|
4823
5260
|
resourceTools,
|
|
5261
|
+
runLabels,
|
|
4824
5262
|
sandboxControls,
|
|
4825
5263
|
sandboxEgressDecision,
|
|
4826
5264
|
sandboxEgressHostMatches,
|
|
@@ -4839,12 +5277,18 @@ export {
|
|
|
4839
5277
|
setupScreenView,
|
|
4840
5278
|
setupSubmission,
|
|
4841
5279
|
sha256Hex,
|
|
5280
|
+
shareContributionRequest,
|
|
5281
|
+
shareContributionReview,
|
|
5282
|
+
shareEvaluation,
|
|
5283
|
+
sharePrices,
|
|
5284
|
+
shareRequest,
|
|
4842
5285
|
skills,
|
|
4843
5286
|
stageOutput,
|
|
4844
5287
|
startTrainingRequest,
|
|
4845
5288
|
subtask,
|
|
4846
5289
|
tableDescribe,
|
|
4847
5290
|
tableQuery,
|
|
5291
|
+
trainingCorrection,
|
|
4848
5292
|
trainingProvider,
|
|
4849
5293
|
trainingProviderMetadata,
|
|
4850
5294
|
trainingRecipe,
|