@constal/sdk 5.3.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 +551 -165
- package/publish/index.js +1200 -761
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,
|
|
@@ -2626,9 +2784,9 @@ var MEMORY_OPERATION_DECLARATIONS = [
|
|
|
2626
2784
|
required: ["hits"],
|
|
2627
2785
|
additionalProperties: false,
|
|
2628
2786
|
properties: { hits: { type: "array", items: {
|
|
2629
|
-
...
|
|
2630
|
-
required: [...
|
|
2631
|
-
properties: { ...
|
|
2787
|
+
...record6,
|
|
2788
|
+
required: [...record6.required, "score"],
|
|
2789
|
+
properties: { ...record6.properties, score: { type: "number", minimum: 0, maximum: 1 } }
|
|
2632
2790
|
} } }
|
|
2633
2791
|
},
|
|
2634
2792
|
effect: "read-only",
|
|
@@ -2640,7 +2798,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
|
|
|
2640
2798
|
op: "get",
|
|
2641
2799
|
description: "Read one record from the invocation's authenticated Memory partition.",
|
|
2642
2800
|
schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id, scope } },
|
|
2643
|
-
resultSchema: { anyOf: [
|
|
2801
|
+
resultSchema: { anyOf: [record6, { type: "null" }] },
|
|
2644
2802
|
effect: "read-only",
|
|
2645
2803
|
recovery: { kind: "repeat" },
|
|
2646
2804
|
async: false,
|
|
@@ -2729,780 +2887,950 @@ function integrationEgressPolicy(value) {
|
|
|
2729
2887
|
return { rules };
|
|
2730
2888
|
}
|
|
2731
2889
|
|
|
2732
|
-
// packages/sdk/src/
|
|
2733
|
-
var
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
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");
|
|
2745
2905
|
}
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
if (tag !== null) {
|
|
2749
|
-
if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
|
|
2750
|
-
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");
|
|
2751
2908
|
}
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
let registryUrl;
|
|
2755
|
-
try {
|
|
2756
|
-
registryUrl = new URL(`https://${registryInput}`);
|
|
2757
|
-
} catch {
|
|
2758
|
-
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");
|
|
2759
2911
|
}
|
|
2760
|
-
if (registryUrl.username || registryUrl.password || registryUrl.pathname !== "/" || !registryUrl.hostname) throw new TypeError("container image registry is invalid");
|
|
2761
|
-
const registry = registryUrl.host === "index.docker.io" ? "docker.io" : registryUrl.host;
|
|
2762
|
-
if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
|
|
2763
|
-
const repository = parts.join("/");
|
|
2764
|
-
if (!REPOSITORY.test(repository)) throw new TypeError("container image repository is invalid");
|
|
2765
|
-
const selectedTag = tag ?? (digest === null ? "latest" : null);
|
|
2766
2912
|
return {
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
digest,
|
|
2771
|
-
reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
|
|
2913
|
+
...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
|
|
2914
|
+
...temperature === void 0 ? {} : { temperature },
|
|
2915
|
+
...effort === void 0 ? {} : { effort }
|
|
2772
2916
|
};
|
|
2773
2917
|
}
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
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;
|
|
2778
2923
|
}
|
|
2779
|
-
function
|
|
2780
|
-
|
|
2781
|
-
const
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
throw new TypeError("container image source is invalid");
|
|
2785
|
-
}
|
|
2786
|
-
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 };
|
|
2787
2929
|
}
|
|
2788
|
-
function
|
|
2789
|
-
const
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
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")) {
|
|
2793
|
-
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");
|
|
2794
2934
|
}
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
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;
|
|
2805
2957
|
}
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
url: `https://${image.registry}/v2/${image.repository}/manifests/${encodeURIComponent(reference)}`,
|
|
2809
|
-
method: "GET",
|
|
2810
|
-
headers: { accept: ACCEPT, ...authorization ? { authorization } : {} },
|
|
2811
|
-
maximumBytes: MANIFEST_BYTES
|
|
2812
|
-
});
|
|
2813
|
-
if (response.status < 200 || response.status >= 300) throw Object.assign(new Error(`container registry manifest request returned ${response.status}`), { status: response.status });
|
|
2814
|
-
if (response.body.byteLength === 0 || response.body.byteLength > MANIFEST_BYTES) throw new TypeError("container registry manifest size is invalid");
|
|
2815
|
-
let value;
|
|
2958
|
+
function modelGatewayEndpoint(config) {
|
|
2959
|
+
let endpoint;
|
|
2816
2960
|
try {
|
|
2817
|
-
|
|
2961
|
+
endpoint = new URL(config.baseUrl);
|
|
2818
2962
|
} catch {
|
|
2819
|
-
|
|
2963
|
+
throw new TypeError("model gateway baseUrl is invalid");
|
|
2820
2964
|
}
|
|
2821
|
-
if (
|
|
2822
|
-
|
|
2823
|
-
if (![OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].includes(String(declared))) throw new TypeError("container registry manifest media type is unsupported");
|
|
2824
|
-
const digest = `sha256:${await sha256Hex(response.body)}`;
|
|
2825
|
-
const header = response.headers["docker-content-digest"];
|
|
2826
|
-
if (header !== void 0 && header !== digest) throw new TypeError("container registry digest header differs from manifest bytes");
|
|
2827
|
-
return { value, mediaType: declared, digest };
|
|
2828
|
-
}
|
|
2829
|
-
async function resolveContainerImageSource(reference, platform, request, authorization) {
|
|
2830
|
-
const image = containerImageReference(reference);
|
|
2831
|
-
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");
|
|
2832
|
-
const requested = image.digest ?? image.tag;
|
|
2833
|
-
let selected = await manifest(image, requested, request, authorization);
|
|
2834
|
-
if (image.digest && selected.digest !== image.digest) throw new TypeError("container image digest does not match its manifest");
|
|
2835
|
-
if (selected.mediaType === OCI_INDEX || selected.mediaType === DOCKER_INDEX) {
|
|
2836
|
-
if (!Array.isArray(selected.value.manifests)) throw new TypeError("container image index has no manifests");
|
|
2837
|
-
const matches = selected.value.manifests.filter((raw) => {
|
|
2838
|
-
const item = object3(raw), target = object3(item?.platform);
|
|
2839
|
-
return item && target && target.os === platform.os && target.architecture === platform.architecture && (platform.variant === void 0 ? target.variant === void 0 : target.variant === platform.variant);
|
|
2840
|
-
}).map((item) => object3(item));
|
|
2841
|
-
if (matches.length !== 1 || typeof matches[0].digest !== "string" || !SHA256.test(matches[0].digest)) {
|
|
2842
|
-
throw new TypeError("container image index does not contain one exact requested platform");
|
|
2843
|
-
}
|
|
2844
|
-
selected = await manifest(image, matches[0].digest, request, authorization);
|
|
2845
|
-
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");
|
|
2846
2967
|
}
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
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");
|
|
2851
2971
|
}
|
|
2852
|
-
const
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
mediaType: selected.mediaType,
|
|
2857
|
-
bytes,
|
|
2858
|
-
platform
|
|
2859
|
-
});
|
|
2860
|
-
}
|
|
2861
|
-
|
|
2862
|
-
// packages/sdk/src/sandbox-egress.ts
|
|
2863
|
-
var SANDBOX_EGRESS_LIMITS = { rules: 64, credentialRules: 16, hostsPerRule: 32, labels: 16, labelValueLength: 256 };
|
|
2864
|
-
var HEADER = /^[a-z0-9!#$%&'*+.^_`|~-]{1,64}$/u;
|
|
2865
|
-
var RESERVED_HEADERS = /* @__PURE__ */ new Set([
|
|
2866
|
-
"connection",
|
|
2867
|
-
"content-length",
|
|
2868
|
-
"host",
|
|
2869
|
-
"keep-alive",
|
|
2870
|
-
"proxy-connection",
|
|
2871
|
-
"te",
|
|
2872
|
-
"trailer",
|
|
2873
|
-
"transfer-encoding",
|
|
2874
|
-
"upgrade"
|
|
2875
|
-
]);
|
|
2876
|
-
var SLOT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
|
|
2877
|
-
var USE = /^egress-(?:0|[1-9][0-9]?)$/u;
|
|
2878
|
-
var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
|
|
2879
|
-
function object4(value) {
|
|
2880
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
2881
|
-
}
|
|
2882
|
-
function sandboxEgressHostMatches(pattern, hostname) {
|
|
2883
|
-
const host2 = hostname.toLowerCase().replace(/\.$/u, "");
|
|
2884
|
-
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;
|
|
2885
2976
|
}
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
return
|
|
2977
|
+
var CACHE_HINT_FIELDS = ["key", "retention", "ttl"];
|
|
2978
|
+
function nonempty(value) {
|
|
2979
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
2889
2980
|
}
|
|
2890
|
-
function
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
function sandboxEgressDecision(policy2, hostname) {
|
|
2905
|
-
if (!policy2) return { allowed: true, rule: "pool" };
|
|
2906
|
-
const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
|
|
2907
|
-
if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
|
|
2908
|
-
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;
|
|
2909
2995
|
}
|
|
2910
|
-
function
|
|
2996
|
+
function modelHistoryMessages(value) {
|
|
2911
2997
|
if (value === void 0) return [];
|
|
2912
|
-
if (!Array.isArray(value)
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
const
|
|
2918
|
-
if (
|
|
2919
|
-
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`);
|
|
2920
3006
|
}
|
|
2921
|
-
const
|
|
2922
|
-
|
|
2923
|
-
if (
|
|
2924
|
-
if (
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
|
|
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 } : {} };
|
|
2935
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;
|
|
2936
3045
|
}
|
|
2937
|
-
function
|
|
2938
|
-
|
|
2939
|
-
const input = object4(value);
|
|
2940
|
-
if (!input || Object.keys(input).length > SANDBOX_EGRESS_LIMITS.labels) throw new TypeError("sandbox labels are invalid");
|
|
2941
|
-
const labels = {};
|
|
2942
|
-
for (const [key, label] of Object.entries(input).sort(([left], [right]) => left.localeCompare(right))) {
|
|
2943
|
-
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");
|
|
2944
|
-
labels[key] = label;
|
|
2945
|
-
}
|
|
2946
|
-
return labels;
|
|
3046
|
+
function modelPrompt(args) {
|
|
3047
|
+
return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
|
|
2947
3048
|
}
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
const
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
}
|
|
2958
|
-
return `/${segments.join("/")}`;
|
|
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
|
+
};
|
|
2959
3058
|
}
|
|
2960
|
-
function
|
|
2961
|
-
|
|
2962
|
-
throw new TypeError("sandbox workspace path is invalid");
|
|
2963
|
-
}
|
|
2964
|
-
const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
|
|
2965
|
-
if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
|
|
2966
|
-
throw new TypeError("sandbox working directory is outside /workspace");
|
|
2967
|
-
}
|
|
2968
|
-
const normalized = absoluteSandboxPath(path.startsWith("/") ? path : `${base}/${path}`);
|
|
2969
|
-
if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
|
|
2970
|
-
throw new TypeError("sandbox path is outside /workspace");
|
|
2971
|
-
}
|
|
2972
|
-
return normalized;
|
|
3059
|
+
function modelMessages(args) {
|
|
3060
|
+
return turnMessages(args).messages;
|
|
2973
3061
|
}
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
// packages/sdk/src/training.ts
|
|
2978
|
-
var HASH2 = /^[a-f0-9]{64}$/u;
|
|
2979
|
-
var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
|
|
2980
|
-
var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
2981
|
-
var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
2982
|
-
var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
|
|
2983
|
-
var TRAINING_PROVIDER_CAPABILITY = {
|
|
2984
|
-
id: "constal.training-provider",
|
|
2985
|
-
version: "1",
|
|
2986
|
-
hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
|
|
2987
|
-
};
|
|
2988
|
-
function record6(value) {
|
|
2989
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3062
|
+
function anthropicBlocks(content2) {
|
|
3063
|
+
return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
|
|
2990
3064
|
}
|
|
2991
|
-
function
|
|
2992
|
-
if (
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
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 };
|
|
2996
3080
|
}
|
|
2997
|
-
function
|
|
2998
|
-
|
|
2999
|
-
|
|
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}
|
|
3087
|
+
|
|
3088
|
+
${message2.content}`;
|
|
3089
|
+
else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
|
|
3000
3090
|
}
|
|
3001
|
-
return
|
|
3091
|
+
return merged;
|
|
3002
3092
|
}
|
|
3003
|
-
function
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
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 };
|
|
3009
3110
|
}
|
|
3010
|
-
function
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
throw new TypeError("training resume point is invalid");
|
|
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");
|
|
3015
3115
|
}
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
function trainingProviderMetadata(value) {
|
|
3019
|
-
const candidate = record6(value);
|
|
3020
|
-
const checkpoints = record6(candidate?.checkpoints);
|
|
3021
|
-
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))) {
|
|
3022
|
-
throw new TypeError("Training Provider metadata is invalid");
|
|
3116
|
+
if (args.toolChoice === "required" && !args.tools?.length) {
|
|
3117
|
+
throw new TypeError("required model Tool choice needs at least one offered Tool");
|
|
3023
3118
|
}
|
|
3024
|
-
const
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
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 }] };
|
|
3029
3127
|
}
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
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
|
+
};
|
|
3034
3144
|
}
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
}
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
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
|
+
};
|
|
3046
3169
|
}
|
|
3047
|
-
|
|
3170
|
+
throw new TypeError("model gateway protocol is invalid");
|
|
3048
3171
|
}
|
|
3049
|
-
function
|
|
3050
|
-
|
|
3051
|
-
if (!candidate || typeof candidate.crn !== "string" || parseResourceName(scorerName(candidate.crn)).kind !== "scorer" || typeof candidate.version !== "string" || !VERSION4.test(candidate.version) || typeof candidate.hash !== "string" || !HASH2.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "version", "hash"].includes(key))) {
|
|
3052
|
-
throw new TypeError(`${field2} is invalid`);
|
|
3053
|
-
}
|
|
3054
|
-
return candidate;
|
|
3172
|
+
function integer(value) {
|
|
3173
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
3055
3174
|
}
|
|
3056
|
-
function
|
|
3057
|
-
const
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
"
|
|
3066
|
-
"
|
|
3067
|
-
"batchSize",
|
|
3068
|
-
"groupSize",
|
|
3069
|
-
"temperature",
|
|
3070
|
-
"seed",
|
|
3071
|
-
"checkpointEvery",
|
|
3072
|
-
"evalEvery",
|
|
3073
|
-
"maxTrainTokens",
|
|
3074
|
-
"maxSampleTokens",
|
|
3075
|
-
"budgetMicroUsd"
|
|
3076
|
-
];
|
|
3077
|
-
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");
|
|
3078
|
-
const recipe = {
|
|
3079
|
-
method: candidate.method,
|
|
3080
|
-
baseModel: candidate.baseModel,
|
|
3081
|
-
dataset: datasetRef(candidate.dataset, "training dataset"),
|
|
3082
|
-
validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
|
|
3083
|
-
scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
|
|
3084
|
-
loraRank: integer(candidate.loraRank, "LoRA rank", 1),
|
|
3085
|
-
learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE),
|
|
3086
|
-
epochs: integer(candidate.epochs, "epochs", 1),
|
|
3087
|
-
batchSize: integer(candidate.batchSize, "batch size", 1),
|
|
3088
|
-
groupSize: integer(candidate.groupSize, "group size", 1),
|
|
3089
|
-
temperature: finite(candidate.temperature, "temperature", 0),
|
|
3090
|
-
seed: integer(candidate.seed, "seed", 0),
|
|
3091
|
-
checkpointEvery: integer(candidate.checkpointEvery, "checkpoint interval", 1),
|
|
3092
|
-
evalEvery: integer(candidate.evalEvery, "evaluation interval", 1),
|
|
3093
|
-
maxTrainTokens: integer(candidate.maxTrainTokens, "training token limit", 1),
|
|
3094
|
-
maxSampleTokens: integer(candidate.maxSampleTokens, "sample token limit", 1),
|
|
3095
|
-
budgetMicroUsd: integer(candidate.budgetMicroUsd, "training budget", 1)
|
|
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 } : {}
|
|
3096
3186
|
};
|
|
3097
|
-
if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
|
|
3098
|
-
return recipe;
|
|
3099
3187
|
}
|
|
3100
|
-
function
|
|
3101
|
-
const
|
|
3102
|
-
if (!
|
|
3103
|
-
|
|
3104
|
-
|
|
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");
|
|
3105
3248
|
return {
|
|
3106
|
-
|
|
3107
|
-
...
|
|
3108
|
-
...
|
|
3109
|
-
|
|
3110
|
-
|
|
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)
|
|
3111
3257
|
};
|
|
3112
3258
|
}
|
|
3113
|
-
function
|
|
3114
|
-
const
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
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 };
|
|
3120
3266
|
}
|
|
3121
3267
|
|
|
3122
|
-
// packages/sdk/src/
|
|
3123
|
-
var
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
};
|
|
3128
|
-
var MODEL_EVALUATION_CAPABILITY = {
|
|
3129
|
-
id: "constal.model-evaluation",
|
|
3268
|
+
// packages/sdk/src/chat-format.ts
|
|
3269
|
+
var HASH3 = /^[a-f0-9]{64}$/u;
|
|
3270
|
+
var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
|
|
3271
|
+
var CHAT_FORMAT_CAPABILITY = {
|
|
3272
|
+
id: "constal.chat-format",
|
|
3130
3273
|
version: "1",
|
|
3131
|
-
hash: "
|
|
3274
|
+
hash: "effa7b0d199664f1f12cd2a6add4db67e5b23f3771c01947a507bb8c20447c27"
|
|
3132
3275
|
};
|
|
3133
|
-
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
}
|
|
3138
|
-
if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature))) {
|
|
3139
|
-
throw new TypeError("temperature must be a finite number");
|
|
3140
|
-
}
|
|
3141
|
-
if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
|
|
3142
|
-
throw new TypeError("effort must be a nonempty model-supported string");
|
|
3276
|
+
var NotAppendOnly = class extends Error {
|
|
3277
|
+
constructor(message2 = "chat rendering is not append-only") {
|
|
3278
|
+
super(message2);
|
|
3279
|
+
this.name = "NotAppendOnly";
|
|
3143
3280
|
}
|
|
3144
|
-
|
|
3145
|
-
|
|
3146
|
-
...temperature === void 0 ? {} : { temperature },
|
|
3147
|
-
...effort === void 0 ? {} : { effort }
|
|
3148
|
-
};
|
|
3149
|
-
}
|
|
3150
|
-
var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3151
|
-
var HEADER2 = /^[a-z0-9][a-z0-9-]{0,63}$/u;
|
|
3152
|
-
var RESERVED_HEADERS2 = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
|
|
3153
|
-
function record7(value) {
|
|
3281
|
+
};
|
|
3282
|
+
function record8(value) {
|
|
3154
3283
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3155
3284
|
}
|
|
3156
|
-
function
|
|
3157
|
-
|
|
3158
|
-
const source = record7(value);
|
|
3159
|
-
if (!source || typeof source.slot !== "string" || !NAME4.test(source.slot) || typeof source.header !== "string" || !HEADER2.test(source.header.toLowerCase()) || RESERVED_HEADERS2.has(source.header.toLowerCase()) || source.header.toLowerCase().startsWith("cf-") || source.scheme !== "bearer" && source.scheme !== "raw") throw new TypeError(`${name} is invalid`);
|
|
3160
|
-
return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
|
|
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));
|
|
3161
3287
|
}
|
|
3162
|
-
function
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
const normalized = {
|
|
3173
|
-
baseUrl: source.baseUrl,
|
|
3174
|
-
protocol: source.protocol,
|
|
3175
|
-
model: source.model,
|
|
3176
|
-
maxOutputTokens,
|
|
3177
|
-
temperature,
|
|
3178
|
-
gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
|
|
3179
|
-
providerAuth: credentialHeader(source.providerAuth, "providerAuth")
|
|
3180
|
-
};
|
|
3181
|
-
if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
|
|
3182
|
-
throw new TypeError("gateway and provider credentials cannot share one header");
|
|
3288
|
+
function tokenList(value, field2) {
|
|
3289
|
+
if (!Array.isArray(value) || value.some((token) => !Number.isSafeInteger(token) || token < 0)) throw new TypeError(`${field2} is invalid`);
|
|
3290
|
+
return value;
|
|
3291
|
+
}
|
|
3292
|
+
function jsonValue(value) {
|
|
3293
|
+
try {
|
|
3294
|
+
canonicalJson(value);
|
|
3295
|
+
return true;
|
|
3296
|
+
} catch {
|
|
3297
|
+
return false;
|
|
3183
3298
|
}
|
|
3184
|
-
|
|
3185
|
-
|
|
3299
|
+
}
|
|
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");
|
|
3186
3304
|
}
|
|
3187
|
-
|
|
3188
|
-
return normalized;
|
|
3305
|
+
return { lifecycleVersion: 1, models: [...source.models] };
|
|
3189
3306
|
}
|
|
3190
|
-
function
|
|
3191
|
-
|
|
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;
|
|
3192
3311
|
try {
|
|
3193
|
-
|
|
3312
|
+
kind = parseResourceName(source.crn).kind;
|
|
3194
3313
|
} catch {
|
|
3195
|
-
throw new TypeError("
|
|
3314
|
+
throw new TypeError("chat format pin is invalid");
|
|
3196
3315
|
}
|
|
3197
|
-
if (
|
|
3198
|
-
|
|
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"])) {
|
|
3322
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3199
3323
|
}
|
|
3200
|
-
|
|
3201
|
-
|
|
3202
|
-
|
|
3324
|
+
return source;
|
|
3325
|
+
}
|
|
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;
|
|
3203
3335
|
}
|
|
3204
|
-
|
|
3205
|
-
if (!suffix) throw new TypeError("model gateway protocol is invalid");
|
|
3206
|
-
endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
|
|
3207
|
-
return endpoint;
|
|
3336
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3208
3337
|
}
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
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");
|
|
3342
|
+
}
|
|
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;
|
|
3212
3355
|
}
|
|
3213
|
-
function
|
|
3214
|
-
if (
|
|
3215
|
-
const
|
|
3216
|
-
if (
|
|
3217
|
-
|
|
3218
|
-
if (unknown !== void 0) throw new TypeError(`model cache hint has an unknown field: ${unknown}`);
|
|
3219
|
-
const hint = {};
|
|
3220
|
-
for (const field2 of CACHE_HINT_FIELDS) {
|
|
3221
|
-
const candidate = source[field2];
|
|
3222
|
-
if (candidate === void 0) continue;
|
|
3223
|
-
if (!nonempty(candidate)) throw new TypeError(`model cache hint ${field2} must be a nonempty string`);
|
|
3224
|
-
hint[field2] = candidate;
|
|
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");
|
|
3225
3361
|
}
|
|
3226
|
-
return
|
|
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
|
+
})));
|
|
3227
3370
|
}
|
|
3228
|
-
function
|
|
3229
|
-
|
|
3230
|
-
if (!Array.isArray(
|
|
3231
|
-
const
|
|
3232
|
-
const
|
|
3233
|
-
|
|
3234
|
-
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
3241
|
-
if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
|
|
3242
|
-
if (source.role === "tool") {
|
|
3243
|
-
if (!nonempty(source.toolCallId)) throw new TypeError(`${at} needs the toolCallId of the Tool call it answers`);
|
|
3244
|
-
if (!unanswered.delete(source.toolCallId)) {
|
|
3245
|
-
throw new TypeError(`${at} answers Tool call ${source.toolCallId}, which is not an unanswered call of the assistant message before it`);
|
|
3246
|
-
}
|
|
3247
|
-
if (source.isError !== void 0 && typeof source.isError !== "boolean") throw new TypeError(`${at} isError must be a boolean`);
|
|
3248
|
-
return {
|
|
3249
|
-
role: "tool",
|
|
3250
|
-
toolCallId: source.toolCallId,
|
|
3251
|
-
content: source.content,
|
|
3252
|
-
...source.isError === void 0 ? {} : { isError: source.isError }
|
|
3253
|
-
};
|
|
3254
|
-
}
|
|
3255
|
-
const open2 = unanswered.values().next();
|
|
3256
|
-
if (!open2.done) throw new TypeError(`model history Tool call ${open2.value} has no tool message answering it before message ${index}`);
|
|
3257
|
-
if (source.role === "user" || source.toolCalls === void 0) return { role: source.role, content: source.content };
|
|
3258
|
-
if (!Array.isArray(source.toolCalls)) throw new TypeError(`${at} toolCalls must be an array`);
|
|
3259
|
-
const toolCalls = source.toolCalls.map((call, position) => {
|
|
3260
|
-
const entry2 = record7(call);
|
|
3261
|
-
if (!entry2 || !nonempty(entry2.id) || !nonempty(entry2.name)) throw new TypeError(`${at} Tool call ${position} needs an id and a name`);
|
|
3262
|
-
if (ids.has(entry2.id)) throw new TypeError(`${at} repeats Tool call id ${entry2.id}`);
|
|
3263
|
-
try {
|
|
3264
|
-
canonicalJson(entry2.args);
|
|
3265
|
-
} catch {
|
|
3266
|
-
throw new TypeError(`${at} Tool call ${entry2.id} args must be a JSON value`);
|
|
3267
|
-
}
|
|
3268
|
-
ids.add(entry2.id);
|
|
3269
|
-
unanswered.add(entry2.id);
|
|
3270
|
-
return { id: entry2.id, name: entry2.name, args: entry2.args };
|
|
3271
|
-
});
|
|
3272
|
-
return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
|
|
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;
|
|
3273
3384
|
});
|
|
3274
|
-
|
|
3275
|
-
if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
|
|
3276
|
-
return messages;
|
|
3385
|
+
return { tokens, spans, stop };
|
|
3277
3386
|
}
|
|
3278
|
-
function
|
|
3279
|
-
|
|
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") };
|
|
3280
3391
|
}
|
|
3281
|
-
function
|
|
3282
|
-
const
|
|
3283
|
-
if (!
|
|
3284
|
-
const
|
|
3285
|
-
|
|
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;
|
|
3398
|
+
}
|
|
3399
|
+
|
|
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");
|
|
3413
|
+
}
|
|
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);
|
|
3419
|
+
}
|
|
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");
|
|
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);
|
|
3286
3434
|
return {
|
|
3287
|
-
|
|
3288
|
-
|
|
3435
|
+
registry,
|
|
3436
|
+
repository,
|
|
3437
|
+
tag: selectedTag,
|
|
3438
|
+
digest,
|
|
3439
|
+
reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
|
|
3289
3440
|
};
|
|
3290
3441
|
}
|
|
3291
|
-
function
|
|
3292
|
-
|
|
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;
|
|
3293
3446
|
}
|
|
3294
|
-
function
|
|
3295
|
-
|
|
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);
|
|
3296
3455
|
}
|
|
3297
|
-
function
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
}
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
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");
|
|
3462
|
+
}
|
|
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;
|
|
3488
|
+
}
|
|
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");
|
|
3514
|
+
}
|
|
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");
|
|
3519
|
+
}
|
|
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
|
+
});
|
|
3312
3528
|
}
|
|
3313
|
-
function alternating(messages) {
|
|
3314
|
-
const merged = [];
|
|
3315
|
-
for (const message2 of messages) {
|
|
3316
|
-
const last = merged.at(-1);
|
|
3317
|
-
if (!last || last.role !== message2.role) merged.push({ ...message2 });
|
|
3318
|
-
else if (typeof last.content === "string" && typeof message2.content === "string") last.content = `${last.content}
|
|
3319
3529
|
|
|
3320
|
-
|
|
3321
|
-
|
|
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;
|
|
3549
|
+
}
|
|
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;
|
|
3553
|
+
}
|
|
3554
|
+
function host(value) {
|
|
3555
|
+
const [normalized] = normalizeSandboxDomains([value]);
|
|
3556
|
+
return normalized;
|
|
3557
|
+
}
|
|
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");
|
|
3322
3562
|
}
|
|
3323
|
-
|
|
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" };
|
|
3324
3571
|
}
|
|
3325
|
-
function
|
|
3326
|
-
if (
|
|
3327
|
-
|
|
3328
|
-
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
if (
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
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 = {}) {
|
|
3579
|
+
if (value === void 0) return [];
|
|
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");
|
|
3588
|
+
}
|
|
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
|
+
};
|
|
3603
|
+
});
|
|
3604
|
+
}
|
|
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;
|
|
3615
|
+
}
|
|
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("/")}`;
|
|
3627
|
+
}
|
|
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;
|
|
3641
|
+
}
|
|
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;
|
|
3669
|
+
}
|
|
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);
|
|
3675
|
+
}
|
|
3676
|
+
function finite(value, field2, minimum) {
|
|
3677
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < minimum) {
|
|
3678
|
+
throw new TypeError(`${field2} is invalid`);
|
|
3679
|
+
}
|
|
3680
|
+
return value;
|
|
3681
|
+
}
|
|
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;
|
|
3342
3688
|
}
|
|
3343
|
-
function
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
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");
|
|
3347
3694
|
}
|
|
3348
|
-
|
|
3349
|
-
|
|
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");
|
|
3350
3702
|
}
|
|
3351
|
-
const
|
|
3352
|
-
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
|
|
3357
|
-
if (breakpoint && lastHistory !== null && marked.length) {
|
|
3358
|
-
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");
|
|
3359
3708
|
}
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
messages: alternating(anthropic),
|
|
3365
|
-
...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
|
|
3366
|
-
...effort === void 0 ? {} : { output_config: { effort } },
|
|
3367
|
-
...temperature === null ? {} : { temperature },
|
|
3368
|
-
...tools.length ? { tools: tools.map((tool, index) => ({
|
|
3369
|
-
name: tool.name,
|
|
3370
|
-
description: tool.description,
|
|
3371
|
-
input_schema: tool.schema,
|
|
3372
|
-
...breakpoint && index === tools.length - 1 ? { cache_control: breakpoint } : {}
|
|
3373
|
-
})) } : {},
|
|
3374
|
-
...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
|
|
3375
|
-
};
|
|
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");
|
|
3376
3713
|
}
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
...openai
|
|
3389
|
-
],
|
|
3390
|
-
...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
|
|
3391
|
-
...effort === void 0 ? {} : { reasoning_effort: effort },
|
|
3392
|
-
...temperature === null ? {} : { temperature },
|
|
3393
|
-
...args.tools?.length ? { tools: args.tools.map((tool) => ({
|
|
3394
|
-
type: "function",
|
|
3395
|
-
function: { name: tool.name, description: tool.description, parameters: tool.schema }
|
|
3396
|
-
})) } : {},
|
|
3397
|
-
...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice },
|
|
3398
|
-
...cache?.key === void 0 ? {} : { prompt_cache_key: cache.key },
|
|
3399
|
-
...cache?.retention === void 0 ? {} : { prompt_cache_retention: cache.retention }
|
|
3400
|
-
};
|
|
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`);
|
|
3401
3725
|
}
|
|
3402
|
-
|
|
3726
|
+
return candidate;
|
|
3403
3727
|
}
|
|
3404
|
-
function
|
|
3405
|
-
|
|
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;
|
|
3406
3734
|
}
|
|
3407
|
-
function
|
|
3408
|
-
|
|
3409
|
-
|
|
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
|
+
} };
|
|
3410
3765
|
}
|
|
3411
|
-
function
|
|
3412
|
-
const
|
|
3413
|
-
const
|
|
3414
|
-
|
|
3415
|
-
|
|
3416
|
-
|
|
3417
|
-
|
|
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)
|
|
3418
3810
|
};
|
|
3811
|
+
if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
|
|
3812
|
+
return recipe;
|
|
3419
3813
|
}
|
|
3420
|
-
function
|
|
3421
|
-
const
|
|
3422
|
-
if (!
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
let refusal;
|
|
3426
|
-
let reasoningContent;
|
|
3427
|
-
let usage;
|
|
3428
|
-
if (protocol === "anthropic") {
|
|
3429
|
-
if (!Array.isArray(source.content)) throw new TypeError("Anthropic model response content is invalid");
|
|
3430
|
-
const blocks = source.content;
|
|
3431
|
-
content2 = blocks.map((candidate) => {
|
|
3432
|
-
const block = record7(candidate);
|
|
3433
|
-
if (block?.type === "text" && typeof block.text === "string") return block.text;
|
|
3434
|
-
if (block?.type === "tool_use") {
|
|
3435
|
-
if (typeof block.id !== "string" || typeof block.name !== "string") throw new TypeError("Anthropic tool use is invalid");
|
|
3436
|
-
toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
|
|
3437
|
-
}
|
|
3438
|
-
return "";
|
|
3439
|
-
}).join("");
|
|
3440
|
-
const values = record7(source.usage) ?? {};
|
|
3441
|
-
const cached = integer2(values.cache_read_input_tokens);
|
|
3442
|
-
usage = {
|
|
3443
|
-
input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
|
|
3444
|
-
output: integer2(values.output_tokens),
|
|
3445
|
-
cached,
|
|
3446
|
-
...cacheWrite(values),
|
|
3447
|
-
...costMetadata(values)
|
|
3448
|
-
};
|
|
3449
|
-
} else if (protocol === "openai") {
|
|
3450
|
-
const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null);
|
|
3451
|
-
const message2 = record7(choice?.message);
|
|
3452
|
-
if (!message2) throw new TypeError("OpenAI-compatible model response message is invalid");
|
|
3453
|
-
content2 = typeof message2.content === "string" ? message2.content : "";
|
|
3454
|
-
refusal = typeof message2.refusal === "string" ? message2.refusal : void 0;
|
|
3455
|
-
reasoningContent = typeof message2.reasoning_content === "string" ? message2.reasoning_content : void 0;
|
|
3456
|
-
if (message2.tool_calls !== void 0 && !Array.isArray(message2.tool_calls)) throw new TypeError("OpenAI-compatible tool calls are invalid");
|
|
3457
|
-
for (const candidate of Array.isArray(message2.tool_calls) ? message2.tool_calls : []) {
|
|
3458
|
-
const call = record7(candidate);
|
|
3459
|
-
const fn = record7(call?.function);
|
|
3460
|
-
if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") {
|
|
3461
|
-
throw new TypeError("OpenAI-compatible tool call is invalid");
|
|
3462
|
-
}
|
|
3463
|
-
let args;
|
|
3464
|
-
try {
|
|
3465
|
-
args = JSON.parse(fn.arguments);
|
|
3466
|
-
} catch {
|
|
3467
|
-
throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
|
|
3468
|
-
}
|
|
3469
|
-
toolCalls.push({ id: call.id, name: fn.name, args });
|
|
3470
|
-
}
|
|
3471
|
-
const values = record7(source.usage) ?? {};
|
|
3472
|
-
usage = {
|
|
3473
|
-
input: integer2(values.prompt_tokens),
|
|
3474
|
-
output: integer2(values.completion_tokens),
|
|
3475
|
-
cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
|
|
3476
|
-
...cacheWrite(values),
|
|
3477
|
-
...costMetadata(values)
|
|
3478
|
-
};
|
|
3479
|
-
} 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
|
+
}
|
|
3480
3819
|
return {
|
|
3481
|
-
|
|
3482
|
-
...
|
|
3483
|
-
...
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
provider,
|
|
3487
|
-
model,
|
|
3488
|
-
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
|
|
3489
3825
|
};
|
|
3490
3826
|
}
|
|
3491
|
-
function modelCompletionStatus(protocol, raw) {
|
|
3492
|
-
const source = record7(raw) ?? {};
|
|
3493
|
-
const value = protocol === "anthropic" ? source.stop_reason : record7(Array.isArray(source.choices) ? source.choices[0] : null)?.finish_reason;
|
|
3494
|
-
const reason = typeof value === "string" ? value : null;
|
|
3495
|
-
const complete = protocol === "anthropic" ? ["end_turn", "tool_use", "stop_sequence"] : ["stop", "tool_calls", "function_call"];
|
|
3496
|
-
const incomplete = protocol === "anthropic" ? ["max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"] : ["length", "content_filter", "error", "cancelled", "canceled"];
|
|
3497
|
-
return { status: reason !== null && complete.includes(reason) ? "complete" : reason !== null && incomplete.includes(reason) ? "incomplete" : "unknown", reason };
|
|
3498
|
-
}
|
|
3499
3827
|
|
|
3500
3828
|
// packages/sdk/src/gateway.ts
|
|
3501
3829
|
async function checkpointArtifactRef(value) {
|
|
3502
3830
|
return await sha256Hex(canonicalJson(value));
|
|
3503
3831
|
}
|
|
3504
3832
|
var SLOT2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
|
|
3505
|
-
var
|
|
3833
|
+
var HASH5 = /^[a-f0-9]{64}$/u;
|
|
3506
3834
|
var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
|
|
3507
3835
|
function httpsUrl(value, field2) {
|
|
3508
3836
|
if (value === void 0) return;
|
|
@@ -3567,7 +3895,7 @@ function checkpointImportRequest(value) {
|
|
|
3567
3895
|
const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
|
|
3568
3896
|
const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
|
|
3569
3897
|
const model = source?.model && typeof source.model === "object" && !Array.isArray(source.model) ? source.model : null;
|
|
3570
|
-
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))) {
|
|
3571
3899
|
throw new TypeError("checkpoint import request is invalid");
|
|
3572
3900
|
}
|
|
3573
3901
|
try {
|
|
@@ -3585,7 +3913,7 @@ function checkpointImportRequest(value) {
|
|
|
3585
3913
|
function checkpointDeploymentRequest(value) {
|
|
3586
3914
|
const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3587
3915
|
const gateway2 = source?.gateway && typeof source.gateway === "object" && !Array.isArray(source.gateway) ? source.gateway : null;
|
|
3588
|
-
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))) {
|
|
3589
3917
|
throw new TypeError("checkpoint deployment request is invalid");
|
|
3590
3918
|
}
|
|
3591
3919
|
try {
|
|
@@ -3665,12 +3993,16 @@ function gatewayPackageMetadata(value) {
|
|
|
3665
3993
|
const discovery = discoverySetup(source.discovery);
|
|
3666
3994
|
const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
|
|
3667
3995
|
const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
|
|
3996
|
+
const chatFormat2 = source.chatFormat === void 0 ? void 0 : chatFormatMetadata(source.chatFormat);
|
|
3668
3997
|
if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
|
|
3669
3998
|
throw new TypeError("Training Provider packages must implement the exact Training Provider capability");
|
|
3670
3999
|
}
|
|
3671
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))) {
|
|
3672
4001
|
throw new TypeError("Checkpoint import Gateways must implement exact completion and checkpoint import capabilities");
|
|
3673
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
|
+
}
|
|
3674
4006
|
return {
|
|
3675
4007
|
lifecycleVersion: 1,
|
|
3676
4008
|
displayName: source.displayName,
|
|
@@ -3685,7 +4017,8 @@ function gatewayPackageMetadata(value) {
|
|
|
3685
4017
|
...configEgress.length ? { configEgress } : {},
|
|
3686
4018
|
...discovery ? { discovery } : {},
|
|
3687
4019
|
...training ? { training } : {},
|
|
3688
|
-
...checkpointImport ? { checkpointImport } : {}
|
|
4020
|
+
...checkpointImport ? { checkpointImport } : {},
|
|
4021
|
+
...chatFormat2 ? { chatFormat: chatFormat2 } : {}
|
|
3689
4022
|
};
|
|
3690
4023
|
}
|
|
3691
4024
|
function resolveGatewayEgress(metadata3, config) {
|
|
@@ -3727,7 +4060,8 @@ function gateway(definition) {
|
|
|
3727
4060
|
configEgress: definition.configEgress,
|
|
3728
4061
|
discovery: definition.discovery,
|
|
3729
4062
|
training: definition.training,
|
|
3730
|
-
checkpointImport: definition.checkpointImport
|
|
4063
|
+
checkpointImport: definition.checkpointImport,
|
|
4064
|
+
chatFormat: definition.chatFormat
|
|
3731
4065
|
});
|
|
3732
4066
|
const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
|
|
3733
4067
|
for (const binding of gateway2.configEgress ?? []) {
|
|
@@ -3754,6 +4088,10 @@ function gateway(definition) {
|
|
|
3754
4088
|
throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
|
|
3755
4089
|
}
|
|
3756
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");
|
|
3757
4095
|
return declarations;
|
|
3758
4096
|
} };
|
|
3759
4097
|
return Object.freeze(wrapped);
|
|
@@ -3773,6 +4111,88 @@ function trainingProvider(definition) {
|
|
|
3773
4111
|
}
|
|
3774
4112
|
});
|
|
3775
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
|
+
}
|
|
3776
4196
|
var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
|
|
3777
4197
|
id: "constal.model-checkpoint-import",
|
|
3778
4198
|
version: "1",
|
|
@@ -3808,7 +4228,7 @@ function credentialProviderConfigSchema(value) {
|
|
|
3808
4228
|
function interactionRecord(value) {
|
|
3809
4229
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
3810
4230
|
}
|
|
3811
|
-
function
|
|
4231
|
+
function exactKeys4(value, allowed) {
|
|
3812
4232
|
return Object.keys(value).every((key) => allowed.includes(key));
|
|
3813
4233
|
}
|
|
3814
4234
|
function nonemptyText(value) {
|
|
@@ -3826,27 +4246,27 @@ function credentialInteractionEvent(value) {
|
|
|
3826
4246
|
if (event.kind === "callback") {
|
|
3827
4247
|
const parameters = interactionRecord(event.parameters);
|
|
3828
4248
|
const headers = interactionRecord(event.headers);
|
|
3829
|
-
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))) {
|
|
3830
4250
|
throw new TypeError("credential interaction callback is invalid");
|
|
3831
4251
|
}
|
|
3832
4252
|
} else if (event.kind === "submit") {
|
|
3833
|
-
if (!
|
|
4253
|
+
if (!exactKeys4(event, ["kind", "value"])) {
|
|
3834
4254
|
throw new TypeError("credential interaction submission is invalid");
|
|
3835
4255
|
}
|
|
3836
4256
|
canonicalJson(event.value);
|
|
3837
|
-
} else if (!
|
|
4257
|
+
} else if (!exactKeys4(event, ["kind"])) throw new TypeError("credential interaction event is invalid");
|
|
3838
4258
|
return event;
|
|
3839
4259
|
}
|
|
3840
4260
|
function credentialInteractionPrimaryAction(value, origins) {
|
|
3841
4261
|
const action3 = interactionRecord(value);
|
|
3842
4262
|
const event = interactionRecord(action3?.event);
|
|
3843
|
-
if (!action3 || !event || !nonemptyText(action3.label) || !
|
|
4263
|
+
if (!action3 || !event || !nonemptyText(action3.label) || !exactKeys4(event, ["kind"]) || event.kind !== "continue") {
|
|
3844
4264
|
throw new TypeError("credential interaction primary action is invalid");
|
|
3845
4265
|
}
|
|
3846
4266
|
if (action3.kind === "continue") {
|
|
3847
|
-
if (!
|
|
4267
|
+
if (!exactKeys4(action3, ["kind", "label", "event"])) throw new TypeError("credential interaction primary action is invalid");
|
|
3848
4268
|
} else if (action3.kind === "open-url") {
|
|
3849
|
-
if (!
|
|
4269
|
+
if (!exactKeys4(action3, ["kind", "label", "url", "event"]) || !nonemptyText(action3.url)) {
|
|
3850
4270
|
throw new TypeError("credential interaction primary action is invalid");
|
|
3851
4271
|
}
|
|
3852
4272
|
let url;
|
|
@@ -3869,7 +4289,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3869
4289
|
const expiresAt = action3.kind === "complete" ? null : interactionExpiry(action3.expiresAt, sessionExpiresAt);
|
|
3870
4290
|
if (Number.isNaN(expiresAt)) throw new TypeError("credential interaction action expiry is invalid");
|
|
3871
4291
|
if (action3.kind === "redirect") {
|
|
3872
|
-
if (!
|
|
4292
|
+
if (!exactKeys4(action3, ["kind", "url", "expiresAt"]) || !nonemptyText(action3.url)) {
|
|
3873
4293
|
throw new TypeError("credential interaction redirect is invalid");
|
|
3874
4294
|
}
|
|
3875
4295
|
let url;
|
|
@@ -3882,7 +4302,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3882
4302
|
throw new TypeError("credential interaction redirect is not authorized");
|
|
3883
4303
|
}
|
|
3884
4304
|
} else if (action3.kind === "form") {
|
|
3885
|
-
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)) {
|
|
3886
4306
|
throw new TypeError("credential interaction form is invalid");
|
|
3887
4307
|
}
|
|
3888
4308
|
const schemaError = validateJsonSchemaDefinition(action3.schema, "$interaction.form.schema");
|
|
@@ -3891,16 +4311,16 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3891
4311
|
throw new TypeError(`credential interaction form schema is invalid${schemaError ? `: ${schemaError}` : ""}`);
|
|
3892
4312
|
}
|
|
3893
4313
|
} else if (action3.kind === "display") {
|
|
3894
|
-
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)) {
|
|
3895
4315
|
throw new TypeError("credential interaction display is invalid");
|
|
3896
4316
|
}
|
|
3897
4317
|
credentialInteractionPrimaryAction(action3.primaryAction, origins);
|
|
3898
4318
|
} else if (action3.kind === "wait") {
|
|
3899
|
-
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) {
|
|
3900
4320
|
throw new TypeError("credential interaction wait action is invalid");
|
|
3901
4321
|
}
|
|
3902
4322
|
} else {
|
|
3903
|
-
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())) {
|
|
3904
4324
|
throw new TypeError("credential interaction completion is invalid");
|
|
3905
4325
|
}
|
|
3906
4326
|
}
|
|
@@ -3908,7 +4328,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
|
|
|
3908
4328
|
}
|
|
3909
4329
|
function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
|
|
3910
4330
|
const result = interactionRecord(value);
|
|
3911
|
-
if (!result || !
|
|
4331
|
+
if (!result || !exactKeys4(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
|
|
3912
4332
|
const privateState = result.privateState;
|
|
3913
4333
|
if (privateState !== void 0 && privateState !== null && typeof privateState !== "string") throw new TypeError("credential interaction private state is invalid");
|
|
3914
4334
|
return {
|
|
@@ -4023,7 +4443,7 @@ var EVALUATION_LIMITS = {
|
|
|
4023
4443
|
};
|
|
4024
4444
|
var QUESTION_ID = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/u;
|
|
4025
4445
|
var MODEL = /^[a-z0-9][a-z0-9._\/-]{0,255}$/u;
|
|
4026
|
-
function
|
|
4446
|
+
function record10(value) {
|
|
4027
4447
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
4028
4448
|
}
|
|
4029
4449
|
function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
|
|
@@ -4033,7 +4453,7 @@ function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
|
|
|
4033
4453
|
return value;
|
|
4034
4454
|
}
|
|
4035
4455
|
const array = Array.isArray(value);
|
|
4036
|
-
const source = array ? value :
|
|
4456
|
+
const source = array ? value : record10(value);
|
|
4037
4457
|
const prototype = source ? Object.getPrototypeOf(source) : void 0;
|
|
4038
4458
|
if (!source || !array && prototype !== Object.prototype && prototype !== null) throw new TypeError(`${field2} must be JSON text or structure`);
|
|
4039
4459
|
if (ancestors.has(source)) throw new TypeError(`${field2} contains a JSON cycle`);
|
|
@@ -4046,7 +4466,7 @@ function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
|
|
|
4046
4466
|
}
|
|
4047
4467
|
}
|
|
4048
4468
|
function question(id2, value) {
|
|
4049
|
-
const source =
|
|
4469
|
+
const source = record10(value);
|
|
4050
4470
|
if (!source) throw new TypeError(`question ${id2} must be an object`);
|
|
4051
4471
|
const type = source.type;
|
|
4052
4472
|
if (type !== "choice" && type !== "score" && type !== "noul") throw new TypeError(`question ${id2} type must be choice, score, or noul`);
|
|
@@ -4055,7 +4475,7 @@ function question(id2, value) {
|
|
|
4055
4475
|
const unknown = Object.keys(source).find((key) => !["type", "instructions", "criteria"].includes(key));
|
|
4056
4476
|
if (unknown) throw new TypeError(`question ${id2} has an unknown field ${unknown}`);
|
|
4057
4477
|
if (type === "choice") {
|
|
4058
|
-
const criteria2 =
|
|
4478
|
+
const criteria2 = record10(source.criteria);
|
|
4059
4479
|
const options = criteria2 ? Object.keys(criteria2) : [];
|
|
4060
4480
|
if (!criteria2 || options.length < 2) throw new TypeError(`choice question ${id2} needs at least two options`);
|
|
4061
4481
|
if (options.some((option) => !option.trim())) throw new TypeError(`choice question ${id2} has an invalid option key`);
|
|
@@ -4067,7 +4487,7 @@ function question(id2, value) {
|
|
|
4067
4487
|
return { type, instructions, criteria: criteria2.map((level, index) => entry(level, `score question ${id2} level ${index}`)) };
|
|
4068
4488
|
}
|
|
4069
4489
|
if (source.criteria === void 0) return { type, instructions };
|
|
4070
|
-
const criteria =
|
|
4490
|
+
const criteria = record10(source.criteria);
|
|
4071
4491
|
if (!criteria || Object.keys(criteria).some((key) => key !== "true" && key !== "false")) {
|
|
4072
4492
|
throw new TypeError(`noul question ${id2} criteria may only describe true and false`);
|
|
4073
4493
|
}
|
|
@@ -4077,11 +4497,11 @@ function question(id2, value) {
|
|
|
4077
4497
|
} };
|
|
4078
4498
|
}
|
|
4079
4499
|
function evaluationArguments(value) {
|
|
4080
|
-
const source =
|
|
4500
|
+
const source = record10(value);
|
|
4081
4501
|
if (!source) throw new TypeError("evaluation arguments must be an object");
|
|
4082
4502
|
if (source.state === void 0) throw new TypeError("evaluation requires a state");
|
|
4083
4503
|
const state = entry(source.state, "evaluation state");
|
|
4084
|
-
const questionSource =
|
|
4504
|
+
const questionSource = record10(source.questions);
|
|
4085
4505
|
const ids = questionSource ? Object.keys(questionSource) : [];
|
|
4086
4506
|
if (!questionSource || ids.length === 0) throw new TypeError("evaluation requires at least one question");
|
|
4087
4507
|
const questions = /* @__PURE__ */ Object.create(null);
|
|
@@ -4108,14 +4528,14 @@ function probability(value, field2) {
|
|
|
4108
4528
|
return value;
|
|
4109
4529
|
}
|
|
4110
4530
|
function distribution(value, keys, field2) {
|
|
4111
|
-
const source =
|
|
4531
|
+
const source = record10(value);
|
|
4112
4532
|
if (!source) throw new TypeError(`${field2} must map every option to a probability`);
|
|
4113
4533
|
const output = {};
|
|
4114
4534
|
for (const key of keys) output[key] = probability(source[key], `${field2}.${key}`);
|
|
4115
4535
|
return output;
|
|
4116
4536
|
}
|
|
4117
4537
|
function answer(id2, asked, value) {
|
|
4118
|
-
const source =
|
|
4538
|
+
const source = record10(value);
|
|
4119
4539
|
if (!source || source.type !== asked.type) throw new TypeError(`answer ${id2} does not match its ${asked.type} question`);
|
|
4120
4540
|
if (asked.type === "noul") return { type: "noul", noul: probability(source.noul, `answer ${id2} noul`) };
|
|
4121
4541
|
const confidence = probability(source.confidence, `answer ${id2} confidence`);
|
|
@@ -4128,7 +4548,7 @@ function answer(id2, asked, value) {
|
|
|
4128
4548
|
if (typeof source.score !== "number" || !Number.isFinite(source.score) || source.score < 0 || source.score > levels.length - 1) {
|
|
4129
4549
|
throw new TypeError(`answer ${id2} score is outside its levels`);
|
|
4130
4550
|
}
|
|
4131
|
-
const legend =
|
|
4551
|
+
const legend = record10(source.legend);
|
|
4132
4552
|
return {
|
|
4133
4553
|
type: "score",
|
|
4134
4554
|
score: source.score,
|
|
@@ -4142,15 +4562,15 @@ function integer3(value) {
|
|
|
4142
4562
|
}
|
|
4143
4563
|
function evaluationProtocolResult(protocol, raw, provider, model, questions) {
|
|
4144
4564
|
if (protocol !== "typesafe") throw new TypeError("evaluation protocol is invalid");
|
|
4145
|
-
const source =
|
|
4146
|
-
const answers =
|
|
4565
|
+
const source = record10(raw) ?? {};
|
|
4566
|
+
const answers = record10(source.answers);
|
|
4147
4567
|
if (!answers) throw new TypeError("evaluation response has no answers");
|
|
4148
4568
|
const output = {};
|
|
4149
4569
|
for (const [id2, asked] of Object.entries(questions)) {
|
|
4150
4570
|
if (answers[id2] === void 0) throw new TypeError(`evaluation response is missing answer ${id2}`);
|
|
4151
4571
|
output[id2] = answer(id2, asked, answers[id2]);
|
|
4152
4572
|
}
|
|
4153
|
-
const usage =
|
|
4573
|
+
const usage = record10(source.usage) ?? {};
|
|
4154
4574
|
const cost = usage.cost;
|
|
4155
4575
|
const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
|
|
4156
4576
|
return {
|
|
@@ -4177,30 +4597,30 @@ function scoreLevel(answer2) {
|
|
|
4177
4597
|
|
|
4178
4598
|
// packages/sdk/src/mcp.ts
|
|
4179
4599
|
var MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
4180
|
-
function
|
|
4600
|
+
function record11(value) {
|
|
4181
4601
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
4182
4602
|
}
|
|
4183
4603
|
function mcpToolDescription(value) {
|
|
4184
|
-
const tool =
|
|
4185
|
-
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);
|
|
4186
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");
|
|
4187
4607
|
return {
|
|
4188
4608
|
name: tool.name,
|
|
4189
4609
|
description: typeof tool.description === "string" ? tool.description : "",
|
|
4190
4610
|
inputSchema,
|
|
4191
4611
|
outputSchema,
|
|
4192
|
-
annotations:
|
|
4612
|
+
annotations: record11(tool.annotations) ?? {}
|
|
4193
4613
|
};
|
|
4194
4614
|
}
|
|
4195
4615
|
function mcpToolResult(value) {
|
|
4196
|
-
const result =
|
|
4197
|
-
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) {
|
|
4198
4618
|
throw new TerminalIntegrationFailure("MCP tools/call result is invalid");
|
|
4199
4619
|
}
|
|
4200
4620
|
return result;
|
|
4201
4621
|
}
|
|
4202
4622
|
function message(value) {
|
|
4203
|
-
const item =
|
|
4623
|
+
const item = record11(value);
|
|
4204
4624
|
if (!item || item.jsonrpc !== "2.0") throw new TerminalIntegrationFailure("MCP transport returned an invalid JSON-RPC message");
|
|
4205
4625
|
return item;
|
|
4206
4626
|
}
|
|
@@ -4240,7 +4660,7 @@ var McpClient = class {
|
|
|
4240
4660
|
for (; ; ) {
|
|
4241
4661
|
const received = message(await this.transport.receive());
|
|
4242
4662
|
if (received.id === id2) {
|
|
4243
|
-
if (
|
|
4663
|
+
if (record11(received.error)) {
|
|
4244
4664
|
const error = received.error;
|
|
4245
4665
|
throw new TerminalIntegrationFailure(`MCP ${typeof error.code === "number" || typeof error.code === "string" ? error.code : "unknown"}: ${typeof error.message === "string" ? error.message : "request failed"}`);
|
|
4246
4666
|
}
|
|
@@ -4265,7 +4685,7 @@ var McpClient = class {
|
|
|
4265
4685
|
}
|
|
4266
4686
|
async initialize() {
|
|
4267
4687
|
if (this.#protocol) return { protocolVersion: this.#protocol, server: {} };
|
|
4268
|
-
const result =
|
|
4688
|
+
const result = record11(await this.#request("initialize", {
|
|
4269
4689
|
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
4270
4690
|
capabilities: {},
|
|
4271
4691
|
clientInfo: this.options.client ?? { name: "Constal", version: "1.0.0" }
|
|
@@ -4276,7 +4696,7 @@ var McpClient = class {
|
|
|
4276
4696
|
this.#protocol = result.protocolVersion;
|
|
4277
4697
|
await this.transport.negotiated?.(this.#protocol);
|
|
4278
4698
|
await this.#serialized(() => this.transport.send({ jsonrpc: "2.0", method: "notifications/initialized" }));
|
|
4279
|
-
return { protocolVersion: this.#protocol, server:
|
|
4699
|
+
return { protocolVersion: this.#protocol, server: record11(result.serverInfo) ?? {} };
|
|
4280
4700
|
}
|
|
4281
4701
|
async request(method, params) {
|
|
4282
4702
|
if (!this.#protocol) throw new TerminalIntegrationFailure("MCP session is not initialized");
|
|
@@ -4286,8 +4706,8 @@ var McpClient = class {
|
|
|
4286
4706
|
const tools = [], cursors = /* @__PURE__ */ new Set();
|
|
4287
4707
|
let cursor;
|
|
4288
4708
|
do {
|
|
4289
|
-
const result =
|
|
4290
|
-
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))) {
|
|
4291
4711
|
throw new TerminalIntegrationFailure("MCP tools/list result is invalid");
|
|
4292
4712
|
}
|
|
4293
4713
|
tools.push(...result.tools);
|
|
@@ -4317,31 +4737,31 @@ var McpClient = class {
|
|
|
4317
4737
|
function validPointer(value) {
|
|
4318
4738
|
return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));
|
|
4319
4739
|
}
|
|
4320
|
-
function
|
|
4740
|
+
function record12(value) {
|
|
4321
4741
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
4322
4742
|
}
|
|
4323
|
-
function
|
|
4743
|
+
function exactKeys5(value, allowed) {
|
|
4324
4744
|
return Object.keys(value).every((key) => allowed.includes(key));
|
|
4325
4745
|
}
|
|
4326
4746
|
function scorerRule(value, depth, state) {
|
|
4327
|
-
const rule =
|
|
4747
|
+
const rule = record12(value);
|
|
4328
4748
|
if (!rule || typeof rule.op !== "string") throw new TypeError("Code Scorer IR is invalid");
|
|
4329
4749
|
if (rule.op === "all" || rule.op === "any") {
|
|
4330
|
-
if (!
|
|
4750
|
+
if (!exactKeys5(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1) {
|
|
4331
4751
|
throw new TypeError("Code Scorer logical rule is invalid");
|
|
4332
4752
|
}
|
|
4333
4753
|
return { op: rule.op, rules: rule.rules.map((child) => scorerRule(child, depth + 1, state)) };
|
|
4334
4754
|
}
|
|
4335
4755
|
if (rule.op === "not") {
|
|
4336
|
-
if (!
|
|
4756
|
+
if (!exactKeys5(rule, ["op", "rule"])) throw new TypeError("Code Scorer not rule is invalid");
|
|
4337
4757
|
return { op: "not", rule: scorerRule(rule.rule, depth + 1, state) };
|
|
4338
4758
|
}
|
|
4339
4759
|
if (rule.op === "schema") {
|
|
4340
|
-
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");
|
|
4341
4761
|
return rule;
|
|
4342
4762
|
}
|
|
4343
4763
|
if (rule.op === "regex") {
|
|
4344
|
-
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)) {
|
|
4345
4765
|
throw new TypeError("Code Scorer regex rule is invalid");
|
|
4346
4766
|
}
|
|
4347
4767
|
try {
|
|
@@ -4352,28 +4772,28 @@ function scorerRule(value, depth, state) {
|
|
|
4352
4772
|
return rule;
|
|
4353
4773
|
}
|
|
4354
4774
|
if (rule.op === "range") {
|
|
4355
|
-
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");
|
|
4356
4776
|
return rule;
|
|
4357
4777
|
}
|
|
4358
4778
|
if (rule.op === "equals" || rule.op === "contains") {
|
|
4359
|
-
if (!
|
|
4779
|
+
if (!exactKeys5(rule, ["op", "path", "value"]) || !validPointer(rule.path) || !Object.hasOwn(rule, "value") || new TextEncoder().encode(canonicalJson(rule.value)).byteLength > 65536) {
|
|
4360
4780
|
throw new TypeError(`Code Scorer ${rule.op} rule is invalid`);
|
|
4361
4781
|
}
|
|
4362
4782
|
return rule;
|
|
4363
4783
|
}
|
|
4364
4784
|
if (rule.op === "tool-sequence") {
|
|
4365
|
-
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");
|
|
4366
4786
|
return rule;
|
|
4367
4787
|
}
|
|
4368
4788
|
if (rule.op === "citations-in-source") {
|
|
4369
|
-
if (!
|
|
4789
|
+
if (!exactKeys5(rule, ["op", "textPath", "sourcesPath"]) || !validPointer(rule.textPath) || !validPointer(rule.sourcesPath)) throw new TypeError("Code Scorer citation rule is invalid");
|
|
4370
4790
|
return rule;
|
|
4371
4791
|
}
|
|
4372
4792
|
throw new TypeError("Code Scorer operation is invalid");
|
|
4373
4793
|
}
|
|
4374
4794
|
function codeScorerIR(value) {
|
|
4375
|
-
const ir =
|
|
4376
|
-
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");
|
|
4377
4797
|
return { v: 1, rule: scorerRule(ir.rule, 0, { rules: 0 }) };
|
|
4378
4798
|
}
|
|
4379
4799
|
function pointer(value, path) {
|
|
@@ -4385,7 +4805,7 @@ function pointer(value, path) {
|
|
|
4385
4805
|
if (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length) return { found: false, value: void 0 };
|
|
4386
4806
|
current = current[Number(key)];
|
|
4387
4807
|
} else {
|
|
4388
|
-
const source =
|
|
4808
|
+
const source = record12(current);
|
|
4389
4809
|
if (!source || !Object.hasOwn(source, key)) return { found: false, value: void 0 };
|
|
4390
4810
|
current = source[key];
|
|
4391
4811
|
}
|
|
@@ -4419,7 +4839,7 @@ function evaluate(rule, subject) {
|
|
|
4419
4839
|
if (!sources.found || !Array.isArray(sources.value)) return fail(rule.sourcesPath, "citation sources are missing");
|
|
4420
4840
|
const available = new Set(sources.value.flatMap((source, index) => {
|
|
4421
4841
|
if (typeof source === "string") return [source, String(index + 1)];
|
|
4422
|
-
const item =
|
|
4842
|
+
const item = record12(source);
|
|
4423
4843
|
return item ? [String(item.id ?? ""), String(index + 1)].filter(Boolean) : [String(index + 1)];
|
|
4424
4844
|
}));
|
|
4425
4845
|
const citations = [...text2.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
|
|
@@ -4438,7 +4858,7 @@ function evaluate(rule, subject) {
|
|
|
4438
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));
|
|
4439
4859
|
return contains ? pass() : fail(rule.path, "value is not contained");
|
|
4440
4860
|
}
|
|
4441
|
-
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 ?? "")) : [];
|
|
4442
4862
|
const sequence = rule.mode === "exact" ? names.length === rule.expected.length && names.every((name, index) => name === rule.expected[index]) : rule.expected.reduce((cursor, expected) => {
|
|
4443
4863
|
const index = names.indexOf(expected, cursor);
|
|
4444
4864
|
return index < 0 ? Number.POSITIVE_INFINITY : index + 1;
|
|
@@ -4458,9 +4878,9 @@ function evaluateCodeScorer(raw, subject) {
|
|
|
4458
4878
|
|
|
4459
4879
|
// packages/sdk/src/errors.ts
|
|
4460
4880
|
var GateExhausted = class extends Error {
|
|
4461
|
-
constructor(
|
|
4881
|
+
constructor(record13) {
|
|
4462
4882
|
super("turn gate exhausted");
|
|
4463
|
-
this.record =
|
|
4883
|
+
this.record = record13;
|
|
4464
4884
|
this.name = "GateExhausted";
|
|
4465
4885
|
}
|
|
4466
4886
|
record;
|
|
@@ -4671,6 +5091,7 @@ export {
|
|
|
4671
5091
|
AGENT_UI_DEFAULTS,
|
|
4672
5092
|
AfterYield,
|
|
4673
5093
|
ApiError,
|
|
5094
|
+
CHAT_FORMAT_CAPABILITY,
|
|
4674
5095
|
CONSTAL_API_CAPABILITY,
|
|
4675
5096
|
CONSTAL_API_GET_KINDS,
|
|
4676
5097
|
CONSTAL_API_MODEL_TOOL_DESCRIPTIONS,
|
|
@@ -4682,6 +5103,7 @@ export {
|
|
|
4682
5103
|
CommitGateRejected,
|
|
4683
5104
|
CredentialRevoked,
|
|
4684
5105
|
CredentialUnavailable,
|
|
5106
|
+
DATA_SHARE_FEE_BPS,
|
|
4685
5107
|
DirectNetworkDenied,
|
|
4686
5108
|
EVALUATION_LIMITS,
|
|
4687
5109
|
EffectCeilingExceeded,
|
|
@@ -4697,6 +5119,7 @@ export {
|
|
|
4697
5119
|
MODEL_EVALUATION_CAPABILITY,
|
|
4698
5120
|
McpClient,
|
|
4699
5121
|
NondeterministicReplay,
|
|
5122
|
+
NotAppendOnly,
|
|
4700
5123
|
OutcomeUnknown,
|
|
4701
5124
|
PolicyConstraintFailed,
|
|
4702
5125
|
PolicyDecisionFailed,
|
|
@@ -4711,6 +5134,7 @@ export {
|
|
|
4711
5134
|
SpawnCardinality,
|
|
4712
5135
|
SwallowedYield,
|
|
4713
5136
|
TRAINING_PROVIDER_CAPABILITY,
|
|
5137
|
+
TRAINING_RECIPE_DEFAULTS,
|
|
4714
5138
|
TerminalIntegrationFailure,
|
|
4715
5139
|
ToolUnavailable,
|
|
4716
5140
|
UI_ASSET_CONTENT_TYPES,
|
|
@@ -4743,6 +5167,14 @@ export {
|
|
|
4743
5167
|
channelSourceEvidence,
|
|
4744
5168
|
channelSubscriptionRequest,
|
|
4745
5169
|
channelTarget,
|
|
5170
|
+
chatFormat,
|
|
5171
|
+
chatFormatMetadata,
|
|
5172
|
+
chatFormatPin,
|
|
5173
|
+
chatParseInput,
|
|
5174
|
+
chatParsed,
|
|
5175
|
+
chatRenderInput,
|
|
5176
|
+
chatRenderRequest,
|
|
5177
|
+
chatRendering,
|
|
4746
5178
|
checkpointArtifactRef,
|
|
4747
5179
|
checkpointDeploymentRequest,
|
|
4748
5180
|
checkpointImportMetadata,
|
|
@@ -4765,6 +5197,7 @@ export {
|
|
|
4765
5197
|
customerTenantName,
|
|
4766
5198
|
cutBatches,
|
|
4767
5199
|
cutPartitions,
|
|
5200
|
+
dataShareEarningMicroUsd,
|
|
4768
5201
|
datasetName,
|
|
4769
5202
|
evaluateCodeScorer,
|
|
4770
5203
|
evaluatePolicyDefinition,
|
|
@@ -4812,7 +5245,6 @@ export {
|
|
|
4812
5245
|
policy,
|
|
4813
5246
|
policyName,
|
|
4814
5247
|
race,
|
|
4815
|
-
renderTrainingCompletion,
|
|
4816
5248
|
resolveBindingOwner,
|
|
4817
5249
|
resolveContainerImageSource,
|
|
4818
5250
|
resolveGatewayEgress,
|
|
@@ -4826,6 +5258,7 @@ export {
|
|
|
4826
5258
|
resourcePattern,
|
|
4827
5259
|
resourceSelector,
|
|
4828
5260
|
resourceTools,
|
|
5261
|
+
runLabels,
|
|
4829
5262
|
sandboxControls,
|
|
4830
5263
|
sandboxEgressDecision,
|
|
4831
5264
|
sandboxEgressHostMatches,
|
|
@@ -4844,12 +5277,18 @@ export {
|
|
|
4844
5277
|
setupScreenView,
|
|
4845
5278
|
setupSubmission,
|
|
4846
5279
|
sha256Hex,
|
|
5280
|
+
shareContributionRequest,
|
|
5281
|
+
shareContributionReview,
|
|
5282
|
+
shareEvaluation,
|
|
5283
|
+
sharePrices,
|
|
5284
|
+
shareRequest,
|
|
4847
5285
|
skills,
|
|
4848
5286
|
stageOutput,
|
|
4849
5287
|
startTrainingRequest,
|
|
4850
5288
|
subtask,
|
|
4851
5289
|
tableDescribe,
|
|
4852
5290
|
tableQuery,
|
|
5291
|
+
trainingCorrection,
|
|
4853
5292
|
trainingProvider,
|
|
4854
5293
|
trainingProviderMetadata,
|
|
4855
5294
|
trainingRecipe,
|