@constal/sdk 5.3.0 → 6.1.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/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 record11 = value;
85
- return `{${Object.keys(record11).sort().filter((key) => record11[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(record11[key])}`).join(",")}}`;
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 record11 = value;
412
- for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in record11)) return `${path}.${key} is required`;
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(record11).length < rule.minProperties) return `${path} has too few properties`;
415
- if (typeof rule.maxProperties === "number" && Object.keys(record11).length > rule.maxProperties) return `${path} has too many properties`;
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(record11).find((key) => !(key in properties));
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 record11) {
421
- const error = validateJsonSchema(record11[key], child, `${path}.${key}`);
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(record11).filter((candidate) => !(candidate in properties))) {
425
- const error = validateJsonSchema(record11[key], rule.additionalProperties, `${path}.${key}`);
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,159 @@ 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", "history", "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, "history")) {
2385
+ const history = record5(source.history);
2386
+ if (source.history !== null && (!history || Object.keys(history).some((key) => key !== "since") || !Number.isSafeInteger(history.since) || history.since <= 0)) {
2387
+ throw new TypeError("Share history must be null or { since: a time in milliseconds }");
2388
+ }
2389
+ terms.history = history ? { since: history.since } : null;
2390
+ }
2391
+ if (Object.hasOwn(source, "expiresAt")) {
2392
+ if (source.expiresAt !== null && (!Number.isSafeInteger(source.expiresAt) || source.expiresAt <= 0)) {
2393
+ throw new TypeError("Share expiresAt must be null or a time in milliseconds");
2394
+ }
2395
+ terms.expiresAt = source.expiresAt;
2396
+ }
2397
+ return terms;
2398
+ }
2399
+ var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2400
+ var HASH2 = /^[a-f0-9]{64}$/u;
2401
+ var DECISIONS = ["accept", "request-changes", "reject"];
2402
+ function contributionNote(value) {
2403
+ if (typeof value !== "string" || new TextEncoder().encode(value).byteLength > 4096) throw new TypeError("note must be text of at most 4096 bytes");
2404
+ return value;
2405
+ }
2406
+ function datasetPin(value, index) {
2407
+ const pin = record5(value);
2408
+ let kind = null;
2409
+ try {
2410
+ kind = typeof pin?.crn === "string" ? parseResourceName(pin.crn).kind : null;
2411
+ } catch {
2412
+ kind = null;
2413
+ }
2414
+ 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`);
2415
+ return { crn: pin.crn, version: pin.version, hash: pin.hash };
2416
+ }
2417
+ function shareContributionRequest(value) {
2418
+ const source = record5(value);
2419
+ const unknown = source && Object.keys(source).find((key) => key !== "datasets" && key !== "evaluations" && key !== "note");
2420
+ if (!source || unknown) throw new TypeError(unknown ? `Contribution field ${unknown} is not supported` : "Contribution request is invalid");
2421
+ const terms = {};
2422
+ if (Object.hasOwn(source, "datasets")) {
2423
+ if (!Array.isArray(source.datasets) || source.datasets.length > 16) throw new TypeError("datasets must be a list of at most 16 Dataset versions");
2424
+ terms.datasets = source.datasets.map(datasetPin);
2425
+ }
2426
+ if (Object.hasOwn(source, "evaluations")) {
2427
+ const evaluations = source.evaluations;
2428
+ if (!Array.isArray(evaluations) || evaluations.length > 16 || evaluations.some((item) => typeof item !== "string" || !NAME3.test(item))) {
2429
+ throw new TypeError("evaluations must be a list of at most 16 evaluation ids");
2430
+ }
2431
+ terms.evaluations = evaluations;
2432
+ }
2433
+ if (Object.hasOwn(source, "note")) terms.note = contributionNote(source.note);
2434
+ return terms;
2435
+ }
2436
+ function shareContributionReview(value) {
2437
+ const source = record5(value);
2438
+ const unknown = source && Object.keys(source).find((key) => !["decision", "note", "namespace", "targets"].includes(key));
2439
+ if (!source || unknown) throw new TypeError(unknown ? `Review field ${unknown} is not supported` : "Review request is invalid");
2440
+ if (!DECISIONS.includes(source.decision)) throw new TypeError("Review decision must be accept, request-changes or reject");
2441
+ const review = { decision: source.decision };
2442
+ if (Object.hasOwn(source, "note")) review.note = contributionNote(source.note);
2443
+ if (review.decision !== "accept") {
2444
+ if (Object.hasOwn(source, "namespace") || Object.hasOwn(source, "targets")) throw new TypeError("Only an accepting review names a namespace or targets");
2445
+ return review;
2446
+ }
2447
+ if (Object.hasOwn(source, "namespace")) {
2448
+ if (typeof source.namespace !== "string" || !NAME3.test(source.namespace)) throw new TypeError("Review namespace is invalid");
2449
+ review.namespace = source.namespace;
2450
+ }
2451
+ if (Object.hasOwn(source, "targets")) {
2452
+ const targets = source.targets;
2453
+ if (!Array.isArray(targets) || targets.length > 16 || targets.some((item) => item !== null && (typeof item !== "string" || !NAME3.test(item)))) {
2454
+ throw new TypeError("Review targets must be at most 16 Dataset ids or nulls");
2455
+ }
2456
+ review.targets = targets;
2457
+ }
2458
+ return review;
2459
+ }
2460
+
2296
2461
  // packages/sdk/src/table.ts
2297
2462
  var identifier = { type: "string", pattern: "^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$", maxLength: 128 };
2298
2463
  var tableName = { type: "string", pattern: "^[a-z0-9][a-z0-9._-]{0,127}$", maxLength: 128 };
@@ -2407,10 +2572,10 @@ var tableQuery = {
2407
2572
  };
2408
2573
 
2409
2574
  // packages/sdk/src/tools.ts
2410
- var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2575
+ var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2411
2576
  var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
2412
2577
  function opTool(binding, op, override = {}) {
2413
- if (!NAME3.test(binding) || !OPERATION2.test(op)) throw new TypeError("opTool binding or operation is invalid");
2578
+ if (!NAME4.test(binding) || !OPERATION2.test(op)) throw new TypeError("opTool binding or operation is invalid");
2414
2579
  const name = override.name ?? op.replaceAll(".", "_");
2415
2580
  return {
2416
2581
  name,
@@ -2583,7 +2748,7 @@ var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 }
2583
2748
  var content = { type: "string", minLength: 1 };
2584
2749
  var metadata2 = { type: "object" };
2585
2750
  var scope = { type: "string", pattern: "^[a-f0-9]{64}$", maxLength: 64 };
2586
- var record5 = {
2751
+ var record6 = {
2587
2752
  type: "object",
2588
2753
  required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
2589
2754
  additionalProperties: false,
@@ -2601,7 +2766,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
2601
2766
  op: "remember",
2602
2767
  description: "Persist or replace one record in the invocation's authenticated Memory partition.",
2603
2768
  schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata: metadata2, scope } },
2604
- resultSchema: record5,
2769
+ resultSchema: record6,
2605
2770
  effect: "idempotent",
2606
2771
  recovery: { kind: "idempotency-key" },
2607
2772
  async: false,
@@ -2626,9 +2791,9 @@ var MEMORY_OPERATION_DECLARATIONS = [
2626
2791
  required: ["hits"],
2627
2792
  additionalProperties: false,
2628
2793
  properties: { hits: { type: "array", items: {
2629
- ...record5,
2630
- required: [...record5.required, "score"],
2631
- properties: { ...record5.properties, score: { type: "number", minimum: 0, maximum: 1 } }
2794
+ ...record6,
2795
+ required: [...record6.required, "score"],
2796
+ properties: { ...record6.properties, score: { type: "number", minimum: 0, maximum: 1 } }
2632
2797
  } } }
2633
2798
  },
2634
2799
  effect: "read-only",
@@ -2640,7 +2805,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
2640
2805
  op: "get",
2641
2806
  description: "Read one record from the invocation's authenticated Memory partition.",
2642
2807
  schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id, scope } },
2643
- resultSchema: { anyOf: [record5, { type: "null" }] },
2808
+ resultSchema: { anyOf: [record6, { type: "null" }] },
2644
2809
  effect: "read-only",
2645
2810
  recovery: { kind: "repeat" },
2646
2811
  async: false,
@@ -2729,780 +2894,950 @@ function integrationEgressPolicy(value) {
2729
2894
  return { rules };
2730
2895
  }
2731
2896
 
2732
- // packages/sdk/src/container-image.ts
2733
- var REPOSITORY = /^[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*$/u;
2734
- var TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u;
2735
- var DIGEST = /^[a-z][a-z0-9+._-]*:[A-Za-z0-9=_-]+$/u;
2736
- var SHA256 = /^sha256:[a-f0-9]{64}$/u;
2737
- function containerImageReference(value) {
2738
- if (typeof value !== "string" || !value || /[\s?#\\]/u.test(value) || value.includes("://")) throw new TypeError("container image reference is invalid");
2739
- const components = value.split("@");
2740
- if (components.length > 2) throw new TypeError("container image reference is invalid");
2741
- let name = components[0];
2742
- const digest = components[1] ?? null;
2743
- if (digest !== null && (!DIGEST.test(digest) || digest.startsWith("sha256:") && !SHA256.test(digest))) {
2744
- throw new TypeError("container image digest is invalid");
2897
+ // packages/sdk/src/model.ts
2898
+ var MODEL_COMPLETION_CAPABILITY = {
2899
+ id: "constal.model-completion",
2900
+ version: "1",
2901
+ hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
2902
+ };
2903
+ var MODEL_EVALUATION_CAPABILITY = {
2904
+ id: "constal.model-evaluation",
2905
+ version: "1",
2906
+ hash: "9c0cc09c17fd5a79be3e1a8f822379f74a5e290d5a12e72104ae7c7eb4be22ee"
2907
+ };
2908
+ function modelGenerationOptions(source) {
2909
+ const { maxOutputTokens, temperature, effort } = source;
2910
+ if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1)) {
2911
+ throw new TypeError("maxOutputTokens must be a positive safe integer");
2745
2912
  }
2746
- const separator = name.lastIndexOf(":"), slash = name.lastIndexOf("/");
2747
- const tag = separator > slash ? name.slice(separator + 1) : null;
2748
- if (tag !== null) {
2749
- if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
2750
- name = name.slice(0, separator);
2913
+ if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature))) {
2914
+ throw new TypeError("temperature must be a finite number");
2751
2915
  }
2752
- const parts = name.split("/"), explicit = parts.length > 1 && (/[.:]/u.test(parts[0]) || parts[0] === "localhost");
2753
- const registryInput = explicit ? parts.shift() : "docker.io";
2754
- let registryUrl;
2755
- try {
2756
- registryUrl = new URL(`https://${registryInput}`);
2757
- } catch {
2758
- throw new TypeError("container image registry is invalid");
2916
+ if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2917
+ throw new TypeError("effort must be a nonempty model-supported string");
2759
2918
  }
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
2919
  return {
2767
- registry,
2768
- repository,
2769
- tag: selectedTag,
2770
- digest,
2771
- reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
2920
+ ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2921
+ ...temperature === void 0 ? {} : { temperature },
2922
+ ...effort === void 0 ? {} : { effort }
2772
2923
  };
2773
2924
  }
2774
- function immutableContainerImageReference(value) {
2775
- const image = containerImageReference(value);
2776
- if (!image.digest || !SHA256.test(image.digest)) throw new TypeError("container image must be resolved to a SHA-256 digest");
2777
- return image;
2925
+ var NAME5 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2926
+ var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2927
+ var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2928
+ function record7(value) {
2929
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2778
2930
  }
2779
- function containerImageSource(value) {
2780
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2781
- const platform = source?.platform && typeof source.platform === "object" && !Array.isArray(source.platform) ? source.platform : null;
2782
- const image = typeof source?.reference === "string" ? immutableContainerImageReference(source.reference) : null;
2783
- 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)) {
2784
- throw new TypeError("container image source is invalid");
2785
- }
2786
- return structuredClone(source);
2931
+ function credentialHeader(value, name) {
2932
+ if (value === null || value === void 0) return null;
2933
+ const source = record7(value);
2934
+ 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`);
2935
+ return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2787
2936
  }
2788
- function containerImageSelection(value) {
2789
- const selection = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2790
- const platform = selection?.platform && typeof selection.platform === "object" && !Array.isArray(selection.platform) ? selection.platform : null;
2791
- const image = typeof selection?.reference === "string" ? immutableContainerImageReference(selection.reference) : null;
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");
2937
+ function normalizeModelGatewayConfig(value) {
2938
+ const source = record7(value);
2939
+ if (!source || typeof source.baseUrl !== "string" || source.protocol !== "anthropic" && source.protocol !== "openai" || typeof source.model !== "string" || source.model.length === 0) {
2940
+ throw new TypeError("model gateway config is invalid");
2794
2941
  }
2795
- return { reference: image.reference, platform: structuredClone(platform) };
2796
- }
2797
- var OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
2798
- var OCI_INDEX = "application/vnd.oci.image.index.v1+json";
2799
- var DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
2800
- var DOCKER_INDEX = "application/vnd.docker.distribution.manifest.list.v2+json";
2801
- var ACCEPT = [OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].join(", ");
2802
- var MANIFEST_BYTES = 4194304;
2803
- function object3(value) {
2804
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2942
+ const maxOutputTokens = source.maxOutputTokens === void 0 ? null : Number(source.maxOutputTokens);
2943
+ const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2944
+ if (maxOutputTokens !== null && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1) || temperature !== null && !Number.isFinite(temperature)) {
2945
+ throw new TypeError("model gateway generation limits are invalid");
2946
+ }
2947
+ const normalized = {
2948
+ baseUrl: source.baseUrl,
2949
+ protocol: source.protocol,
2950
+ model: source.model,
2951
+ maxOutputTokens,
2952
+ temperature,
2953
+ gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2954
+ providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2955
+ };
2956
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2957
+ throw new TypeError("gateway and provider credentials cannot share one header");
2958
+ }
2959
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2960
+ throw new TypeError("gateway and provider credentials cannot share one slot");
2961
+ }
2962
+ modelGatewayEndpoint(normalized);
2963
+ return normalized;
2805
2964
  }
2806
- async function manifest(image, reference, request, authorization) {
2807
- const response = await request({
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;
2965
+ function modelGatewayEndpoint(config) {
2966
+ let endpoint;
2816
2967
  try {
2817
- value = object3(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(response.body)));
2968
+ endpoint = new URL(config.baseUrl);
2818
2969
  } catch {
2819
- value = null;
2970
+ throw new TypeError("model gateway baseUrl is invalid");
2820
2971
  }
2821
- if (!value || value.schemaVersion !== 2) throw new TypeError("container registry manifest is invalid");
2822
- const declared = typeof value.mediaType === "string" ? value.mediaType : response.headers["content-type"]?.split(";", 1)[0];
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");
2972
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2973
+ throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
2846
2974
  }
2847
- if (selected.mediaType !== OCI_MANIFEST && selected.mediaType !== DOCKER_MANIFEST) throw new TypeError("container image did not resolve to an image manifest");
2848
- const config = object3(selected.value.config), layers = selected.value.layers;
2849
- 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)) {
2850
- throw new TypeError("container image manifest descriptors are invalid");
2975
+ const hostname = endpoint.hostname.toLowerCase();
2976
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2977
+ throw new TypeError("model gateway baseUrl must use a public hostname");
2851
2978
  }
2852
- const bytes = Number(config.size) + layers.reduce((sum, layer) => sum + Number(object3(layer).size), 0);
2853
- return containerImageSource({
2854
- reference: `${image.registry}/${image.repository}@${selected.digest}`,
2855
- digest: selected.digest,
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;
2979
+ const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2980
+ if (!suffix) throw new TypeError("model gateway protocol is invalid");
2981
+ endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2982
+ return endpoint;
2885
2983
  }
2886
- function host(value) {
2887
- const [normalized] = normalizeSandboxDomains([value]);
2888
- return normalized;
2984
+ var CACHE_HINT_FIELDS = ["key", "retention", "ttl"];
2985
+ function nonempty(value) {
2986
+ return typeof value === "string" && value.trim().length > 0;
2889
2987
  }
2890
- function normalizeSandboxEgressPolicy(value) {
2891
- const input = object4(value);
2892
- 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") {
2893
- throw new TypeError("sandbox egress policy is invalid");
2894
- }
2895
- const rules = input.rules.map((raw) => {
2896
- const rule = object4(raw);
2897
- if (!rule || Object.keys(rule).some((key) => key !== "action" && key !== "host") || rule.action !== "allow" && rule.action !== "deny") {
2898
- throw new TypeError("sandbox egress rule is invalid");
2899
- }
2900
- return { action: rule.action, host: host(rule.host) };
2901
- });
2902
- return { rules, default: input.default === "allow" ? "allow" : "deny" };
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}` };
2988
+ function modelCacheHint(value) {
2989
+ if (value === void 0) return void 0;
2990
+ const source = record7(value);
2991
+ if (!source) throw new TypeError("model cache hint must be an object");
2992
+ const unknown = Object.keys(source).find((key) => !CACHE_HINT_FIELDS.includes(key));
2993
+ if (unknown !== void 0) throw new TypeError(`model cache hint has an unknown field: ${unknown}`);
2994
+ const hint = {};
2995
+ for (const field2 of CACHE_HINT_FIELDS) {
2996
+ const candidate = source[field2];
2997
+ if (candidate === void 0) continue;
2998
+ if (!nonempty(candidate)) throw new TypeError(`model cache hint ${field2} must be a nonempty string`);
2999
+ hint[field2] = candidate;
3000
+ }
3001
+ return hint;
2909
3002
  }
2910
- function normalizeSandboxEgressCredentialRules(value, options = {}) {
3003
+ function modelHistoryMessages(value) {
2911
3004
  if (value === void 0) return [];
2912
- if (!Array.isArray(value) || value.length > SANDBOX_EGRESS_LIMITS.credentialRules) throw new TypeError("sandbox egress Credential rules are invalid");
2913
- return value.map((raw) => {
2914
- const rule = object4(raw);
2915
- const allowed = ["hosts", "slot", "header", "value", "basic", ...options.bindings ? ["binding"] : [], ...options.uses ? ["use"] : []];
2916
- 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");
2917
- const sources = [rule.slot, rule.binding, rule.use].filter((source) => source !== void 0);
2918
- 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))) {
2919
- throw new TypeError("sandbox egress Credential rule names exactly one slot or binding");
3005
+ if (!Array.isArray(value)) throw new TypeError("model history must be an array of messages");
3006
+ const ids = /* @__PURE__ */ new Set();
3007
+ const unanswered = /* @__PURE__ */ new Set();
3008
+ const messages = value.map((candidate, index) => {
3009
+ const at = `model history message ${index}`;
3010
+ const source = record7(candidate);
3011
+ if (!source || typeof source.content !== "string" || source.role !== "user" && source.role !== "assistant" && source.role !== "tool") {
3012
+ throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
2920
3013
  }
2921
- const header = rule.header === void 0 ? "authorization" : rule.header;
2922
- if (typeof header !== "string" || !HEADER.test(header.toLowerCase()) || RESERVED_HEADERS.has(header.toLowerCase()) || header.toLowerCase().startsWith("x-constal-")) throw new TypeError("sandbox egress Credential header is invalid");
2923
- if (rule.value !== void 0 && rule.basic !== void 0) throw new TypeError("sandbox egress Credential rule takes value or basic, not both");
2924
- 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");
2925
- const basic = rule.basic === void 0 ? void 0 : object4(rule.basic);
2926
- 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");
2927
- return {
2928
- hosts: normalizeSandboxDomains(rule.hosts),
2929
- ...rule.slot !== void 0 ? { slot: rule.slot } : {},
2930
- ...rule.binding !== void 0 ? { binding: resourceCredentialBinding(rule.binding) } : {},
2931
- ...rule.use !== void 0 ? { use: rule.use } : {},
2932
- header: header.toLowerCase(),
2933
- ...basic ? { basic: basic.username === void 0 ? {} : { username: basic.username } } : { value: rule.value ?? "Bearer {value}" }
2934
- };
3014
+ const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
3015
+ const misplaced = foreign.find((field2) => source[field2] !== void 0);
3016
+ if (misplaced !== void 0) throw new TypeError(`${at} has the ${source.role} role, which cannot carry ${misplaced}`);
3017
+ if (source.role === "tool") {
3018
+ if (!nonempty(source.toolCallId)) throw new TypeError(`${at} needs the toolCallId of the Tool call it answers`);
3019
+ if (!unanswered.delete(source.toolCallId)) {
3020
+ throw new TypeError(`${at} answers Tool call ${source.toolCallId}, which is not an unanswered call of the assistant message before it`);
3021
+ }
3022
+ if (source.isError !== void 0 && typeof source.isError !== "boolean") throw new TypeError(`${at} isError must be a boolean`);
3023
+ return {
3024
+ role: "tool",
3025
+ toolCallId: source.toolCallId,
3026
+ content: source.content,
3027
+ ...source.isError === void 0 ? {} : { isError: source.isError }
3028
+ };
3029
+ }
3030
+ const open2 = unanswered.values().next();
3031
+ if (!open2.done) throw new TypeError(`model history Tool call ${open2.value} has no tool message answering it before message ${index}`);
3032
+ if (source.role === "user" || source.toolCalls === void 0) return { role: source.role, content: source.content };
3033
+ if (!Array.isArray(source.toolCalls)) throw new TypeError(`${at} toolCalls must be an array`);
3034
+ const toolCalls = source.toolCalls.map((call, position) => {
3035
+ const entry2 = record7(call);
3036
+ if (!entry2 || !nonempty(entry2.id) || !nonempty(entry2.name)) throw new TypeError(`${at} Tool call ${position} needs an id and a name`);
3037
+ if (ids.has(entry2.id)) throw new TypeError(`${at} repeats Tool call id ${entry2.id}`);
3038
+ try {
3039
+ canonicalJson(entry2.args);
3040
+ } catch {
3041
+ throw new TypeError(`${at} Tool call ${entry2.id} args must be a JSON value`);
3042
+ }
3043
+ ids.add(entry2.id);
3044
+ unanswered.add(entry2.id);
3045
+ return { id: entry2.id, name: entry2.name, args: entry2.args };
3046
+ });
3047
+ return { role: "assistant", content: source.content, ...toolCalls.length ? { toolCalls } : {} };
2935
3048
  });
3049
+ const open = unanswered.values().next();
3050
+ if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
3051
+ return messages;
2936
3052
  }
2937
- function normalizeSandboxLabels(value) {
2938
- if (value === void 0) return {};
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;
3053
+ function modelPrompt(args) {
3054
+ return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2947
3055
  }
2948
-
2949
- // packages/sdk/src/sandbox-pool.ts
2950
- var WORKSPACE_ROOT = "/workspace";
2951
- function absoluteSandboxPath(value) {
2952
- const segments = [];
2953
- for (const segment of value.split("/")) {
2954
- if (!segment || segment === ".") continue;
2955
- if (segment === "..") segments.pop();
2956
- else segments.push(segment);
2957
- }
2958
- return `/${segments.join("/")}`;
3056
+ function turnMessages(args) {
3057
+ const history = modelHistoryMessages(args.history);
3058
+ if (!history.length) return { messages: [{ role: "user", content: modelPrompt(args) }], lastHistory: null };
3059
+ const feedback = args.feedback ?? [];
3060
+ const prompt = args.objective == null && args.context == null && history[0].role === "user" ? [] : [{ role: "user", content: canonicalJson({ objective: args.objective ?? null, context: args.context ?? null }) }];
3061
+ return {
3062
+ messages: [...prompt, ...history, ...feedback.length ? [{ role: "user", content: canonicalJson({ feedback }) }] : []],
3063
+ lastHistory: prompt.length + history.length - 1
3064
+ };
2959
3065
  }
2960
- function normalizeSandboxWorkspacePath(path, cwd = WORKSPACE_ROOT) {
2961
- if (typeof path !== "string" || !path || typeof cwd !== "string" || !cwd || /[\u0000-\u001f\u007f]/u.test(path) || /[\u0000-\u001f\u007f]/u.test(cwd)) {
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;
3066
+ function modelMessages(args) {
3067
+ return turnMessages(args).messages;
2973
3068
  }
2974
- var SANDBOX_PROCESS_IO_OPERATIONS = ["process.status", "process.read", "process.write", "process.close"];
2975
- var SANDBOX_PROCESS_OPERATIONS = ["process.resolve", ...SANDBOX_PROCESS_IO_OPERATIONS, "process.stop"];
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;
3069
+ function anthropicBlocks(content2) {
3070
+ return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
2990
3071
  }
2991
- function integer(value, field2, minimum) {
2992
- if (!Number.isSafeInteger(value) || Number(value) < minimum) {
2993
- throw new TypeError(`${field2} is invalid`);
2994
- }
2995
- return Number(value);
3072
+ function anthropicMessage(message2) {
3073
+ if (message2.role === "tool") return { role: "user", content: [{
3074
+ type: "tool_result",
3075
+ tool_use_id: message2.toolCallId,
3076
+ content: message2.content,
3077
+ ...message2.isError ? { is_error: true } : {}
3078
+ }] };
3079
+ if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
3080
+ ...anthropicBlocks(message2.content),
3081
+ ...message2.toolCalls.map((call) => {
3082
+ const args = JSON.parse(canonicalJson(call.args));
3083
+ return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
3084
+ })
3085
+ ] };
3086
+ return { role: message2.role, content: message2.content };
2996
3087
  }
2997
- function finite(value, field2, minimum) {
2998
- if (typeof value !== "number" || !Number.isFinite(value) || value < minimum) {
2999
- throw new TypeError(`${field2} is invalid`);
3088
+ function alternating(messages) {
3089
+ const merged = [];
3090
+ for (const message2 of messages) {
3091
+ const last = merged.at(-1);
3092
+ if (!last || last.role !== message2.role) merged.push({ ...message2 });
3093
+ else if (typeof last.content === "string" && typeof message2.content === "string") last.content = `${last.content}
3094
+
3095
+ ${message2.content}`;
3096
+ else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
3000
3097
  }
3001
- return value;
3098
+ return merged;
3002
3099
  }
3003
- function providerPin(value) {
3004
- const candidate = record6(value);
3005
- if (!candidate || typeof candidate.crn !== "string" || typeof candidate.hash !== "string" || !HASH2.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "hash"].includes(key))) throw new TypeError("training provider pin is invalid");
3006
- const parts = parseResourceName(candidate.crn);
3007
- if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
3008
- return candidate;
3100
+ function openAiMessage(message2, options = {}) {
3101
+ if (message2.role === "tool") return {
3102
+ role: "tool",
3103
+ tool_call_id: message2.toolCallId,
3104
+ content: message2.content,
3105
+ ...options.toolErrorName && message2.isError ? { name: "tool_error" } : {}
3106
+ };
3107
+ if (message2.role === "assistant" && message2.toolCalls) return {
3108
+ role: "assistant",
3109
+ content: message2.content || null,
3110
+ tool_calls: message2.toolCalls.map((call) => ({
3111
+ id: call.id,
3112
+ type: "function",
3113
+ function: { name: call.name, arguments: canonicalJson(call.args) }
3114
+ }))
3115
+ };
3116
+ return { role: message2.role, content: message2.content };
3009
3117
  }
3010
- function resumePoint(value) {
3011
- if (value === null) return null;
3012
- const candidate = record6(value);
3013
- if (!candidate || typeof candidate.job !== "string" || !JOB_ID.test(candidate.job) || !Number.isSafeInteger(candidate.step) || Number(candidate.step) < 0 || typeof candidate.ref !== "string" || !HASH2.test(candidate.ref) || Object.keys(candidate).some((key) => !["job", "step", "ref"].includes(key))) {
3014
- throw new TypeError("training resume point is invalid");
3118
+ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args, options = {}) {
3119
+ const { effort } = modelGenerationOptions(args);
3120
+ if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
3121
+ throw new TypeError("model Tool choice is invalid");
3015
3122
  }
3016
- return candidate;
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");
3123
+ if (args.toolChoice === "required" && !args.tools?.length) {
3124
+ throw new TypeError("required model Tool choice needs at least one offered Tool");
3023
3125
  }
3024
- const models = candidate.models.map((raw) => {
3025
- const model = record6(raw);
3026
- const pricing = record6(model?.pricing);
3027
- if (!model || typeof model.id !== "string" || !JOB_ID.test(model.id) || typeof model.name !== "string" || !model.name || model.name.length > 128 || typeof model.providerModel !== "string" || !PROVIDER_MODEL_ID.test(model.providerModel) || !Number.isSafeInteger(model.contextTokens) || Number(model.contextTokens) < 1 || !pricing || pricing.currency !== "USD" || pricing.unit !== "million_tokens" || ["prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].some((key) => !Number.isSafeInteger(pricing[key]) || Number(pricing[key]) < 0) || Object.keys(pricing).some((key) => !["currency", "unit", "prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].includes(key)) || Object.keys(model).some((key) => !["id", "name", "providerModel", "contextTokens", "pricing"].includes(key))) {
3028
- throw new TypeError("Training Provider model offer is invalid");
3126
+ const cache = modelCacheHint(args.cache);
3127
+ const { messages, lastHistory } = turnMessages(args);
3128
+ const breakpoint = cache ? { type: "ephemeral", ...cache.ttl === void 0 ? {} : { ttl: cache.ttl } } : null;
3129
+ if (protocol === "anthropic") {
3130
+ const anthropic = messages.map(anthropicMessage);
3131
+ const marked = breakpoint && lastHistory !== null ? anthropicBlocks(anthropic[lastHistory].content) : [];
3132
+ if (breakpoint && lastHistory !== null && marked.length) {
3133
+ anthropic[lastHistory] = { ...anthropic[lastHistory], content: [...marked.slice(0, -1), { ...marked.at(-1), cache_control: breakpoint }] };
3029
3134
  }
3030
- return raw;
3031
- });
3032
- if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
3033
- throw new TypeError("Training Provider model offers must be unique");
3135
+ const tools = args.tools ?? [];
3136
+ return {
3137
+ model,
3138
+ system: breakpoint && args.system ? [{ type: "text", text: args.system, cache_control: breakpoint }] : args.system ?? "",
3139
+ messages: alternating(anthropic),
3140
+ ...maxOutputTokens === null ? {} : { max_tokens: maxOutputTokens },
3141
+ ...effort === void 0 ? {} : { output_config: { effort } },
3142
+ ...temperature === null ? {} : { temperature },
3143
+ ...tools.length ? { tools: tools.map((tool, index) => ({
3144
+ name: tool.name,
3145
+ description: tool.description,
3146
+ input_schema: tool.schema,
3147
+ ...breakpoint && index === tools.length - 1 ? { cache_control: breakpoint } : {}
3148
+ })) } : {},
3149
+ ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
3150
+ };
3034
3151
  }
3035
- return {
3036
- lifecycleVersion: 1,
3037
- methods: candidate.methods,
3038
- models,
3039
- checkpoints
3040
- };
3041
- }
3042
- function datasetRef(value, field2) {
3043
- const candidate = record6(value);
3044
- if (!candidate || typeof candidate.crn !== "string" || parseResourceName(datasetName(candidate.crn)).kind !== "dataset" || 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))) {
3045
- throw new TypeError(`${field2} is invalid`);
3152
+ if (protocol === "openai") {
3153
+ const marks = options.contentCacheControl === true ? breakpoint : null;
3154
+ const marked = (text2) => marks && text2 ? [{ type: "text", text: text2, cache_control: marks }] : text2;
3155
+ const openai = messages.map((message2, index) => {
3156
+ const entry2 = openAiMessage(message2, options);
3157
+ return index === lastHistory && typeof entry2.content === "string" ? { ...entry2, content: marked(entry2.content) } : entry2;
3158
+ });
3159
+ return {
3160
+ model,
3161
+ messages: [
3162
+ ...args.system ? [{ role: "developer", content: marked(args.system) }] : [],
3163
+ ...openai
3164
+ ],
3165
+ ...maxOutputTokens === null ? {} : { max_completion_tokens: maxOutputTokens },
3166
+ ...effort === void 0 ? {} : { reasoning_effort: effort },
3167
+ ...temperature === null ? {} : { temperature },
3168
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({
3169
+ type: "function",
3170
+ function: { name: tool.name, description: tool.description, parameters: tool.schema }
3171
+ })) } : {},
3172
+ ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice },
3173
+ ...cache?.key === void 0 ? {} : { prompt_cache_key: cache.key },
3174
+ ...cache?.retention === void 0 ? {} : { prompt_cache_retention: cache.retention }
3175
+ };
3046
3176
  }
3047
- return candidate;
3177
+ throw new TypeError("model gateway protocol is invalid");
3048
3178
  }
3049
- function scorerRef(value, field2) {
3050
- const candidate = record6(value);
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;
3179
+ function integer(value) {
3180
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
3055
3181
  }
3056
- function trainingRecipe(value) {
3057
- const candidate = record6(value);
3058
- const allowed = [
3059
- "method",
3060
- "baseModel",
3061
- "dataset",
3062
- "validationDataset",
3063
- "scorers",
3064
- "loraRank",
3065
- "learningRate",
3066
- "epochs",
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)
3182
+ function cacheWrite(usage) {
3183
+ const value = usage.cache_creation_input_tokens ?? record7(usage.prompt_tokens_details)?.cache_write_tokens;
3184
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? { cacheWrite: value } : {};
3185
+ }
3186
+ function costMetadata(usage) {
3187
+ const cost = usage.cost;
3188
+ const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
3189
+ return {
3190
+ ...costUsd !== void 0 ? { costUsd } : {},
3191
+ ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
3192
+ ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
3096
3193
  };
3097
- if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
3098
- return recipe;
3099
3194
  }
3100
- function startTrainingRequest(value) {
3101
- const candidate = record6(value);
3102
- 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))) {
3103
- throw new TypeError("training request is invalid");
3104
- }
3195
+ function modelProtocolResult(protocol, raw, provider, model) {
3196
+ const source = record7(raw);
3197
+ if (!source) throw new TypeError("model gateway response is invalid");
3198
+ const toolCalls = [];
3199
+ let content2 = "";
3200
+ let refusal;
3201
+ let reasoningContent;
3202
+ let usage;
3203
+ if (protocol === "anthropic") {
3204
+ if (!Array.isArray(source.content)) throw new TypeError("Anthropic model response content is invalid");
3205
+ const blocks = source.content;
3206
+ content2 = blocks.map((candidate) => {
3207
+ const block = record7(candidate);
3208
+ if (block?.type === "text" && typeof block.text === "string") return block.text;
3209
+ if (block?.type === "tool_use") {
3210
+ if (typeof block.id !== "string" || typeof block.name !== "string") throw new TypeError("Anthropic tool use is invalid");
3211
+ toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
3212
+ }
3213
+ return "";
3214
+ }).join("");
3215
+ const values = record7(source.usage) ?? {};
3216
+ const cached = integer(values.cache_read_input_tokens);
3217
+ usage = {
3218
+ input: integer(values.input_tokens) + integer(values.cache_creation_input_tokens) + cached,
3219
+ output: integer(values.output_tokens),
3220
+ cached,
3221
+ ...cacheWrite(values),
3222
+ ...costMetadata(values)
3223
+ };
3224
+ } else if (protocol === "openai") {
3225
+ const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null);
3226
+ const message2 = record7(choice?.message);
3227
+ if (!message2) throw new TypeError("OpenAI-compatible model response message is invalid");
3228
+ content2 = typeof message2.content === "string" ? message2.content : "";
3229
+ refusal = typeof message2.refusal === "string" ? message2.refusal : void 0;
3230
+ reasoningContent = typeof message2.reasoning_content === "string" ? message2.reasoning_content : void 0;
3231
+ if (message2.tool_calls !== void 0 && !Array.isArray(message2.tool_calls)) throw new TypeError("OpenAI-compatible tool calls are invalid");
3232
+ for (const candidate of Array.isArray(message2.tool_calls) ? message2.tool_calls : []) {
3233
+ const call = record7(candidate);
3234
+ const fn = record7(call?.function);
3235
+ if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") {
3236
+ throw new TypeError("OpenAI-compatible tool call is invalid");
3237
+ }
3238
+ let args;
3239
+ try {
3240
+ args = JSON.parse(fn.arguments);
3241
+ } catch {
3242
+ throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
3243
+ }
3244
+ toolCalls.push({ id: call.id, name: fn.name, args });
3245
+ }
3246
+ const values = record7(source.usage) ?? {};
3247
+ usage = {
3248
+ input: integer(values.prompt_tokens),
3249
+ output: integer(values.completion_tokens),
3250
+ cached: integer(record7(values.prompt_tokens_details)?.cached_tokens),
3251
+ ...cacheWrite(values),
3252
+ ...costMetadata(values)
3253
+ };
3254
+ } else throw new TypeError("model gateway protocol is invalid");
3105
3255
  return {
3106
- ...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
3107
- ...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
3108
- ...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
3109
- recipe: trainingRecipe(candidate.recipe),
3110
- outputModelId: candidate.outputModelId
3256
+ content: content2,
3257
+ ...toolCalls.length ? { toolCalls } : {},
3258
+ ...refusal === void 0 ? {} : { refusal },
3259
+ ...reasoningContent === void 0 ? {} : { reasoningContent },
3260
+ usage,
3261
+ provider,
3262
+ model,
3263
+ completion: modelCompletionStatus(protocol, raw)
3111
3264
  };
3112
3265
  }
3113
- function renderTrainingCompletion(input, expected) {
3114
- const text2 = (value) => typeof value === "string" ? value : canonicalJson(value);
3115
- return { prompt: `Input:
3116
- ${text2(input)}
3117
-
3118
- Response:
3119
- `, completion: expected === void 0 || expected === null ? null : text2(expected) };
3266
+ function modelCompletionStatus(protocol, raw) {
3267
+ const source = record7(raw) ?? {};
3268
+ const value = protocol === "anthropic" ? source.stop_reason : record7(Array.isArray(source.choices) ? source.choices[0] : null)?.finish_reason;
3269
+ const reason = typeof value === "string" ? value : null;
3270
+ const complete = protocol === "anthropic" ? ["end_turn", "tool_use", "stop_sequence"] : ["stop", "tool_calls", "function_call"];
3271
+ const incomplete = protocol === "anthropic" ? ["max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"] : ["length", "content_filter", "error", "cancelled", "canceled"];
3272
+ return { status: reason !== null && complete.includes(reason) ? "complete" : reason !== null && incomplete.includes(reason) ? "incomplete" : "unknown", reason };
3120
3273
  }
3121
3274
 
3122
- // packages/sdk/src/model.ts
3123
- var MODEL_COMPLETION_CAPABILITY = {
3124
- id: "constal.model-completion",
3125
- version: "1",
3126
- hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
3127
- };
3128
- var MODEL_EVALUATION_CAPABILITY = {
3129
- id: "constal.model-evaluation",
3275
+ // packages/sdk/src/chat-format.ts
3276
+ var HASH3 = /^[a-f0-9]{64}$/u;
3277
+ var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
3278
+ var CHAT_FORMAT_CAPABILITY = {
3279
+ id: "constal.chat-format",
3130
3280
  version: "1",
3131
- hash: "9c0cc09c17fd5a79be3e1a8f822379f74a5e290d5a12e72104ae7c7eb4be22ee"
3281
+ hash: "effa7b0d199664f1f12cd2a6add4db67e5b23f3771c01947a507bb8c20447c27"
3132
3282
  };
3133
- function modelGenerationOptions(source) {
3134
- const { maxOutputTokens, temperature, effort } = source;
3135
- if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1)) {
3136
- throw new TypeError("maxOutputTokens must be a positive safe integer");
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");
3283
+ var NotAppendOnly = class extends Error {
3284
+ constructor(message2 = "chat rendering is not append-only") {
3285
+ super(message2);
3286
+ this.name = "NotAppendOnly";
3143
3287
  }
3144
- return {
3145
- ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
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) {
3288
+ };
3289
+ function record8(value) {
3154
3290
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3155
3291
  }
3156
- function credentialHeader(value, name) {
3157
- if (value === null || value === void 0) return null;
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 };
3292
+ function exactKeys3(value, required2, optional = []) {
3293
+ return required2.every((key) => Object.hasOwn(value, key)) && Object.keys(value).every((key) => required2.includes(key) || optional.includes(key));
3161
3294
  }
3162
- function normalizeModelGatewayConfig(value) {
3163
- const source = record7(value);
3164
- if (!source || typeof source.baseUrl !== "string" || source.protocol !== "anthropic" && source.protocol !== "openai" || typeof source.model !== "string" || source.model.length === 0) {
3165
- throw new TypeError("model gateway config is invalid");
3166
- }
3167
- const maxOutputTokens = source.maxOutputTokens === void 0 ? null : Number(source.maxOutputTokens);
3168
- const temperature = source.temperature === void 0 ? null : Number(source.temperature);
3169
- if (maxOutputTokens !== null && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1) || temperature !== null && !Number.isFinite(temperature)) {
3170
- throw new TypeError("model gateway generation limits are invalid");
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");
3295
+ function tokenList(value, field2) {
3296
+ if (!Array.isArray(value) || value.some((token) => !Number.isSafeInteger(token) || token < 0)) throw new TypeError(`${field2} is invalid`);
3297
+ return value;
3298
+ }
3299
+ function jsonValue(value) {
3300
+ try {
3301
+ canonicalJson(value);
3302
+ return true;
3303
+ } catch {
3304
+ return false;
3183
3305
  }
3184
- if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
3185
- throw new TypeError("gateway and provider credentials cannot share one slot");
3306
+ }
3307
+ function chatFormatMetadata(value) {
3308
+ const source = record8(value);
3309
+ 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"])) {
3310
+ throw new TypeError("chat format metadata is invalid");
3186
3311
  }
3187
- modelGatewayEndpoint(normalized);
3188
- return normalized;
3312
+ return { lifecycleVersion: 1, models: [...source.models] };
3189
3313
  }
3190
- function modelGatewayEndpoint(config) {
3191
- let endpoint;
3314
+ function chatFormatPin(value) {
3315
+ const source = record8(value);
3316
+ 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");
3317
+ let kind;
3192
3318
  try {
3193
- endpoint = new URL(config.baseUrl);
3319
+ kind = parseResourceName(source.crn).kind;
3194
3320
  } catch {
3195
- throw new TypeError("model gateway baseUrl is invalid");
3321
+ throw new TypeError("chat format pin is invalid");
3196
3322
  }
3197
- if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
3198
- throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
3323
+ if (kind === "model" || kind === "memory") throw new TypeError("chat format pin is invalid");
3324
+ return { crn: source.crn, hash: source.hash };
3325
+ }
3326
+ function toolCall(value, field2) {
3327
+ const source = record8(value);
3328
+ 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"])) {
3329
+ throw new TypeError(`${field2} is invalid`);
3199
3330
  }
3200
- const hostname = endpoint.hostname.toLowerCase();
3201
- if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
3202
- throw new TypeError("model gateway baseUrl must use a public hostname");
3331
+ return source;
3332
+ }
3333
+ function chatMessage(value, index) {
3334
+ const source = record8(value);
3335
+ const field2 = `chat message ${index}`;
3336
+ if (!source || typeof source.content !== "string") throw new TypeError(`${field2} is invalid`);
3337
+ if (source.role === "user" && exactKeys3(source, ["role", "content"])) return source;
3338
+ 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;
3339
+ 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))) {
3340
+ source.toolCalls?.forEach((call, position) => toolCall(call, `${field2} Tool call ${position}`));
3341
+ return source;
3203
3342
  }
3204
- const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
3205
- if (!suffix) throw new TypeError("model gateway protocol is invalid");
3206
- endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
3207
- return endpoint;
3343
+ throw new TypeError(`${field2} is invalid`);
3208
3344
  }
3209
- var CACHE_HINT_FIELDS = ["key", "retention", "ttl"];
3210
- function nonempty(value) {
3211
- return typeof value === "string" && value.trim().length > 0;
3345
+ function chatRenderInput(value) {
3346
+ const source = record8(value);
3347
+ 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)) {
3348
+ throw new TypeError("chat render request is invalid");
3349
+ }
3350
+ const messages = source.messages.map(chatMessage);
3351
+ source.tools.forEach((raw, index) => {
3352
+ const tool = record8(raw);
3353
+ 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`);
3354
+ });
3355
+ if (source.toolChoice === "required" && source.tools.length === 0) throw new TypeError("required Tool choice needs at least one offered Tool");
3356
+ source.train.forEach((index, position) => {
3357
+ if (!Number.isSafeInteger(index) || index < 0 || index >= messages.length || messages[index].role !== "assistant" || position > 0 && index <= source.train[position - 1]) {
3358
+ throw new TypeError("chat render request trains only assistant messages, in ascending order");
3359
+ }
3360
+ });
3361
+ return source;
3212
3362
  }
3213
- function modelCacheHint(value) {
3214
- if (value === void 0) return void 0;
3215
- const source = record7(value);
3216
- if (!source) throw new TypeError("model cache hint must be an object");
3217
- const unknown = Object.keys(source).find((key) => !CACHE_HINT_FIELDS.includes(key));
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;
3363
+ function chatRenderRequest(args, train = []) {
3364
+ if (args.rawProtocol !== void 0) throw new TypeError("a raw protocol model request has no chat rendering");
3365
+ const { effort } = modelGenerationOptions(args);
3366
+ if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
3367
+ throw new TypeError("model Tool choice is invalid");
3225
3368
  }
3226
- return hint;
3369
+ return chatRenderInput(JSON.parse(canonicalJson({
3370
+ system: args.system ? args.system : null,
3371
+ messages: modelMessages(args),
3372
+ tools: (args.tools ?? []).map((tool) => ({ name: tool.name, description: tool.description, schema: tool.schema })),
3373
+ toolChoice: args.toolChoice ?? null,
3374
+ effort: effort ?? null,
3375
+ train
3376
+ })));
3227
3377
  }
3228
- function modelHistoryMessages(value) {
3229
- if (value === void 0) return [];
3230
- if (!Array.isArray(value)) throw new TypeError("model history must be an array of messages");
3231
- const ids = /* @__PURE__ */ new Set();
3232
- const unanswered = /* @__PURE__ */ new Set();
3233
- const messages = value.map((candidate, index) => {
3234
- const at = `model history message ${index}`;
3235
- const source = record7(candidate);
3236
- if (!source || typeof source.content !== "string" || source.role !== "user" && source.role !== "assistant" && source.role !== "tool") {
3237
- throw new TypeError(`${at} needs a user, assistant or tool role and text content`);
3238
- }
3239
- const foreign = source.role === "tool" ? ["toolCalls"] : source.role === "user" ? ["toolCalls", "toolCallId", "isError"] : ["toolCallId", "isError"];
3240
- const misplaced = foreign.find((field2) => source[field2] !== void 0);
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 } : {} };
3378
+ function chatRendering(value, request) {
3379
+ const source = record8(value);
3380
+ if (!source || !exactKeys3(source, ["tokens", "spans", "stop"]) || !Array.isArray(source.spans)) throw new TypeError("chat rendering is invalid");
3381
+ const tokens = tokenList(source.tokens, "chat rendering tokens");
3382
+ const stop = tokenList(source.stop, "chat rendering stop tokens");
3383
+ if (stop.length === 0) throw new TypeError("chat rendering stop tokens are invalid");
3384
+ if (source.spans.length !== request.train.length) throw new TypeError("chat rendering spans do not match the trained messages");
3385
+ let previous = 0;
3386
+ const spans = source.spans.map((raw, index) => {
3387
+ const span = record8(raw);
3388
+ 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");
3389
+ previous = Number(span.end);
3390
+ return span;
3273
3391
  });
3274
- const open = unanswered.values().next();
3275
- if (!open.done) throw new TypeError(`model history Tool call ${open.value} has no tool message answering it`);
3276
- return messages;
3392
+ return { tokens, spans, stop };
3277
3393
  }
3278
- function modelPrompt(args) {
3279
- return canonicalJson({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
3394
+ function chatParseInput(value) {
3395
+ const source = record8(value);
3396
+ if (!source || !exactKeys3(source, ["tokens"])) throw new TypeError("chat parse request is invalid");
3397
+ return { tokens: tokenList(source.tokens, "chat parse tokens") };
3280
3398
  }
3281
- function turnMessages(args) {
3282
- const history = modelHistoryMessages(args.history);
3283
- if (!history.length) return { messages: [{ role: "user", content: modelPrompt(args) }], lastHistory: null };
3284
- const feedback = args.feedback ?? [];
3285
- const prompt = args.objective == null && args.context == null && history[0].role === "user" ? [] : [{ role: "user", content: canonicalJson({ objective: args.objective ?? null, context: args.context ?? null }) }];
3399
+ function chatParsed(value) {
3400
+ const source = record8(value);
3401
+ 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");
3402
+ const toolCalls = source.toolCalls.map((call, index) => toolCall(call, `parsed Tool call ${index}`));
3403
+ if (new Set(toolCalls.map((call) => call.id)).size !== toolCalls.length) throw new TypeError("parsed Tool call ids must be unique");
3404
+ return source;
3405
+ }
3406
+
3407
+ // packages/sdk/src/container-image.ts
3408
+ var REPOSITORY = /^[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*$/u;
3409
+ var TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u;
3410
+ var DIGEST = /^[a-z][a-z0-9+._-]*:[A-Za-z0-9=_-]+$/u;
3411
+ var SHA256 = /^sha256:[a-f0-9]{64}$/u;
3412
+ function containerImageReference(value) {
3413
+ if (typeof value !== "string" || !value || /[\s?#\\]/u.test(value) || value.includes("://")) throw new TypeError("container image reference is invalid");
3414
+ const components = value.split("@");
3415
+ if (components.length > 2) throw new TypeError("container image reference is invalid");
3416
+ let name = components[0];
3417
+ const digest = components[1] ?? null;
3418
+ if (digest !== null && (!DIGEST.test(digest) || digest.startsWith("sha256:") && !SHA256.test(digest))) {
3419
+ throw new TypeError("container image digest is invalid");
3420
+ }
3421
+ const separator = name.lastIndexOf(":"), slash = name.lastIndexOf("/");
3422
+ const tag = separator > slash ? name.slice(separator + 1) : null;
3423
+ if (tag !== null) {
3424
+ if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
3425
+ name = name.slice(0, separator);
3426
+ }
3427
+ const parts = name.split("/"), explicit = parts.length > 1 && (/[.:]/u.test(parts[0]) || parts[0] === "localhost");
3428
+ const registryInput = explicit ? parts.shift() : "docker.io";
3429
+ let registryUrl;
3430
+ try {
3431
+ registryUrl = new URL(`https://${registryInput}`);
3432
+ } catch {
3433
+ throw new TypeError("container image registry is invalid");
3434
+ }
3435
+ if (registryUrl.username || registryUrl.password || registryUrl.pathname !== "/" || !registryUrl.hostname) throw new TypeError("container image registry is invalid");
3436
+ const registry = registryUrl.host === "index.docker.io" ? "docker.io" : registryUrl.host;
3437
+ if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
3438
+ const repository = parts.join("/");
3439
+ if (!REPOSITORY.test(repository)) throw new TypeError("container image repository is invalid");
3440
+ const selectedTag = tag ?? (digest === null ? "latest" : null);
3286
3441
  return {
3287
- messages: [...prompt, ...history, ...feedback.length ? [{ role: "user", content: canonicalJson({ feedback }) }] : []],
3288
- lastHistory: prompt.length + history.length - 1
3442
+ registry,
3443
+ repository,
3444
+ tag: selectedTag,
3445
+ digest,
3446
+ reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
3289
3447
  };
3290
3448
  }
3291
- function modelMessages(args) {
3292
- return turnMessages(args).messages;
3449
+ function immutableContainerImageReference(value) {
3450
+ const image = containerImageReference(value);
3451
+ if (!image.digest || !SHA256.test(image.digest)) throw new TypeError("container image must be resolved to a SHA-256 digest");
3452
+ return image;
3293
3453
  }
3294
- function anthropicBlocks(content2) {
3295
- return typeof content2 !== "string" ? content2 : content2 ? [{ type: "text", text: content2 }] : [];
3454
+ function containerImageSource(value) {
3455
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3456
+ const platform = source?.platform && typeof source.platform === "object" && !Array.isArray(source.platform) ? source.platform : null;
3457
+ const image = typeof source?.reference === "string" ? immutableContainerImageReference(source.reference) : null;
3458
+ 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)) {
3459
+ throw new TypeError("container image source is invalid");
3460
+ }
3461
+ return structuredClone(source);
3296
3462
  }
3297
- function anthropicMessage(message2) {
3298
- if (message2.role === "tool") return { role: "user", content: [{
3299
- type: "tool_result",
3300
- tool_use_id: message2.toolCallId,
3301
- content: message2.content,
3302
- ...message2.isError ? { is_error: true } : {}
3303
- }] };
3304
- if (message2.role === "assistant" && message2.toolCalls) return { role: "assistant", content: [
3305
- ...anthropicBlocks(message2.content),
3306
- ...message2.toolCalls.map((call) => {
3307
- const args = JSON.parse(canonicalJson(call.args));
3308
- return { type: "tool_use", id: call.id, name: call.name, input: record7(args) ?? { value: args } };
3309
- })
3310
- ] };
3311
- return { role: message2.role, content: message2.content };
3463
+ function containerImageSelection(value) {
3464
+ const selection = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3465
+ const platform = selection?.platform && typeof selection.platform === "object" && !Array.isArray(selection.platform) ? selection.platform : null;
3466
+ const image = typeof selection?.reference === "string" ? immutableContainerImageReference(selection.reference) : null;
3467
+ 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")) {
3468
+ throw new TypeError("container image selection is invalid");
3469
+ }
3470
+ return { reference: image.reference, platform: structuredClone(platform) };
3471
+ }
3472
+ var OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
3473
+ var OCI_INDEX = "application/vnd.oci.image.index.v1+json";
3474
+ var DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
3475
+ var DOCKER_INDEX = "application/vnd.docker.distribution.manifest.list.v2+json";
3476
+ var ACCEPT = [OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].join(", ");
3477
+ var MANIFEST_BYTES = 4194304;
3478
+ function object3(value) {
3479
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3480
+ }
3481
+ async function manifest(image, reference, request, authorization) {
3482
+ const response = await request({
3483
+ url: `https://${image.registry}/v2/${image.repository}/manifests/${encodeURIComponent(reference)}`,
3484
+ method: "GET",
3485
+ headers: { accept: ACCEPT, ...authorization ? { authorization } : {} },
3486
+ maximumBytes: MANIFEST_BYTES
3487
+ });
3488
+ if (response.status < 200 || response.status >= 300) throw Object.assign(new Error(`container registry manifest request returned ${response.status}`), { status: response.status });
3489
+ if (response.body.byteLength === 0 || response.body.byteLength > MANIFEST_BYTES) throw new TypeError("container registry manifest size is invalid");
3490
+ let value;
3491
+ try {
3492
+ value = object3(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(response.body)));
3493
+ } catch {
3494
+ value = null;
3495
+ }
3496
+ if (!value || value.schemaVersion !== 2) throw new TypeError("container registry manifest is invalid");
3497
+ const declared = typeof value.mediaType === "string" ? value.mediaType : response.headers["content-type"]?.split(";", 1)[0];
3498
+ if (![OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].includes(String(declared))) throw new TypeError("container registry manifest media type is unsupported");
3499
+ const digest = `sha256:${await sha256Hex(response.body)}`;
3500
+ const header = response.headers["docker-content-digest"];
3501
+ if (header !== void 0 && header !== digest) throw new TypeError("container registry digest header differs from manifest bytes");
3502
+ return { value, mediaType: declared, digest };
3503
+ }
3504
+ async function resolveContainerImageSource(reference, platform, request, authorization) {
3505
+ const image = containerImageReference(reference);
3506
+ 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");
3507
+ const requested = image.digest ?? image.tag;
3508
+ let selected = await manifest(image, requested, request, authorization);
3509
+ if (image.digest && selected.digest !== image.digest) throw new TypeError("container image digest does not match its manifest");
3510
+ if (selected.mediaType === OCI_INDEX || selected.mediaType === DOCKER_INDEX) {
3511
+ if (!Array.isArray(selected.value.manifests)) throw new TypeError("container image index has no manifests");
3512
+ const matches = selected.value.manifests.filter((raw) => {
3513
+ const item = object3(raw), target = object3(item?.platform);
3514
+ return item && target && target.os === platform.os && target.architecture === platform.architecture && (platform.variant === void 0 ? target.variant === void 0 : target.variant === platform.variant);
3515
+ }).map((item) => object3(item));
3516
+ if (matches.length !== 1 || typeof matches[0].digest !== "string" || !SHA256.test(matches[0].digest)) {
3517
+ throw new TypeError("container image index does not contain one exact requested platform");
3518
+ }
3519
+ selected = await manifest(image, matches[0].digest, request, authorization);
3520
+ if (selected.digest !== matches[0].digest) throw new TypeError("container image platform descriptor differs from its manifest");
3521
+ }
3522
+ if (selected.mediaType !== OCI_MANIFEST && selected.mediaType !== DOCKER_MANIFEST) throw new TypeError("container image did not resolve to an image manifest");
3523
+ const config = object3(selected.value.config), layers = selected.value.layers;
3524
+ 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)) {
3525
+ throw new TypeError("container image manifest descriptors are invalid");
3526
+ }
3527
+ const bytes = Number(config.size) + layers.reduce((sum, layer) => sum + Number(object3(layer).size), 0);
3528
+ return containerImageSource({
3529
+ reference: `${image.registry}/${image.repository}@${selected.digest}`,
3530
+ digest: selected.digest,
3531
+ mediaType: selected.mediaType,
3532
+ bytes,
3533
+ platform
3534
+ });
3312
3535
  }
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
3536
 
3320
- ${message2.content}`;
3321
- else last.content = [...anthropicBlocks(last.content), ...anthropicBlocks(message2.content)];
3537
+ // packages/sdk/src/sandbox-egress.ts
3538
+ var SANDBOX_EGRESS_LIMITS = { rules: 64, credentialRules: 16, hostsPerRule: 32, labels: 16, labelValueLength: 256 };
3539
+ var HEADER2 = /^[a-z0-9!#$%&'*+.^_`|~-]{1,64}$/u;
3540
+ var RESERVED_HEADERS2 = /* @__PURE__ */ new Set([
3541
+ "connection",
3542
+ "content-length",
3543
+ "host",
3544
+ "keep-alive",
3545
+ "proxy-connection",
3546
+ "te",
3547
+ "trailer",
3548
+ "transfer-encoding",
3549
+ "upgrade"
3550
+ ]);
3551
+ var SLOT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
3552
+ var USE = /^egress-(?:0|[1-9][0-9]?)$/u;
3553
+ var LABEL = /^[a-z0-9][a-z0-9._-]{0,62}$/u;
3554
+ function object4(value) {
3555
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3556
+ }
3557
+ function sandboxEgressHostMatches(pattern, hostname) {
3558
+ const host2 = hostname.toLowerCase().replace(/\.$/u, "");
3559
+ return pattern.startsWith("*.") ? host2 === pattern.slice(2) || host2.endsWith(pattern.slice(1)) : host2 === pattern;
3560
+ }
3561
+ function host(value) {
3562
+ const [normalized] = normalizeSandboxDomains([value]);
3563
+ return normalized;
3564
+ }
3565
+ function normalizeSandboxEgressPolicy(value) {
3566
+ const input = object4(value);
3567
+ 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") {
3568
+ throw new TypeError("sandbox egress policy is invalid");
3322
3569
  }
3323
- return merged;
3570
+ const rules = input.rules.map((raw) => {
3571
+ const rule = object4(raw);
3572
+ if (!rule || Object.keys(rule).some((key) => key !== "action" && key !== "host") || rule.action !== "allow" && rule.action !== "deny") {
3573
+ throw new TypeError("sandbox egress rule is invalid");
3574
+ }
3575
+ return { action: rule.action, host: host(rule.host) };
3576
+ });
3577
+ return { rules, default: input.default === "allow" ? "allow" : "deny" };
3324
3578
  }
3325
- function openAiMessage(message2, options) {
3326
- if (message2.role === "tool") return {
3327
- role: "tool",
3328
- tool_call_id: message2.toolCallId,
3329
- content: message2.content,
3330
- ...options.toolErrorName && message2.isError ? { name: "tool_error" } : {}
3331
- };
3332
- if (message2.role === "assistant" && message2.toolCalls) return {
3333
- role: "assistant",
3334
- content: message2.content || null,
3335
- tool_calls: message2.toolCalls.map((call) => ({
3336
- id: call.id,
3337
- type: "function",
3338
- function: { name: call.name, arguments: canonicalJson(call.args) }
3339
- }))
3340
- };
3341
- return { role: message2.role, content: message2.content };
3579
+ function sandboxEgressDecision(policy2, hostname) {
3580
+ if (!policy2) return { allowed: true, rule: "pool" };
3581
+ const index = policy2.rules.findIndex((rule) => sandboxEgressHostMatches(rule.host, hostname));
3582
+ if (index < 0) return { allowed: policy2.default === "allow", rule: "sandbox:default" };
3583
+ return { allowed: policy2.rules[index].action === "allow", rule: `sandbox:${index}` };
3584
+ }
3585
+ function normalizeSandboxEgressCredentialRules(value, options = {}) {
3586
+ if (value === void 0) return [];
3587
+ if (!Array.isArray(value) || value.length > SANDBOX_EGRESS_LIMITS.credentialRules) throw new TypeError("sandbox egress Credential rules are invalid");
3588
+ return value.map((raw) => {
3589
+ const rule = object4(raw);
3590
+ const allowed = ["hosts", "slot", "header", "value", "basic", ...options.bindings ? ["binding"] : [], ...options.uses ? ["use"] : []];
3591
+ 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");
3592
+ const sources = [rule.slot, rule.binding, rule.use].filter((source) => source !== void 0);
3593
+ 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))) {
3594
+ throw new TypeError("sandbox egress Credential rule names exactly one slot or binding");
3595
+ }
3596
+ const header = rule.header === void 0 ? "authorization" : rule.header;
3597
+ 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");
3598
+ if (rule.value !== void 0 && rule.basic !== void 0) throw new TypeError("sandbox egress Credential rule takes value or basic, not both");
3599
+ 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");
3600
+ const basic = rule.basic === void 0 ? void 0 : object4(rule.basic);
3601
+ 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");
3602
+ return {
3603
+ hosts: normalizeSandboxDomains(rule.hosts),
3604
+ ...rule.slot !== void 0 ? { slot: rule.slot } : {},
3605
+ ...rule.binding !== void 0 ? { binding: resourceCredentialBinding(rule.binding) } : {},
3606
+ ...rule.use !== void 0 ? { use: rule.use } : {},
3607
+ header: header.toLowerCase(),
3608
+ ...basic ? { basic: basic.username === void 0 ? {} : { username: basic.username } } : { value: rule.value ?? "Bearer {value}" }
3609
+ };
3610
+ });
3611
+ }
3612
+ function normalizeSandboxLabels(value) {
3613
+ if (value === void 0) return {};
3614
+ const input = object4(value);
3615
+ if (!input || Object.keys(input).length > SANDBOX_EGRESS_LIMITS.labels) throw new TypeError("sandbox labels are invalid");
3616
+ const labels = {};
3617
+ for (const [key, label] of Object.entries(input).sort(([left], [right]) => left.localeCompare(right))) {
3618
+ 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");
3619
+ labels[key] = label;
3620
+ }
3621
+ return labels;
3622
+ }
3623
+
3624
+ // packages/sdk/src/sandbox-pool.ts
3625
+ var WORKSPACE_ROOT = "/workspace";
3626
+ function absoluteSandboxPath(value) {
3627
+ const segments = [];
3628
+ for (const segment of value.split("/")) {
3629
+ if (!segment || segment === ".") continue;
3630
+ if (segment === "..") segments.pop();
3631
+ else segments.push(segment);
3632
+ }
3633
+ return `/${segments.join("/")}`;
3634
+ }
3635
+ function normalizeSandboxWorkspacePath(path, cwd = WORKSPACE_ROOT) {
3636
+ if (typeof path !== "string" || !path || typeof cwd !== "string" || !cwd || /[\u0000-\u001f\u007f]/u.test(path) || /[\u0000-\u001f\u007f]/u.test(cwd)) {
3637
+ throw new TypeError("sandbox workspace path is invalid");
3638
+ }
3639
+ const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
3640
+ if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
3641
+ throw new TypeError("sandbox working directory is outside /workspace");
3642
+ }
3643
+ const normalized = absoluteSandboxPath(path.startsWith("/") ? path : `${base}/${path}`);
3644
+ if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
3645
+ throw new TypeError("sandbox path is outside /workspace");
3646
+ }
3647
+ return normalized;
3648
+ }
3649
+ var SANDBOX_PROCESS_IO_OPERATIONS = ["process.status", "process.read", "process.write", "process.close"];
3650
+ var SANDBOX_PROCESS_OPERATIONS = ["process.resolve", ...SANDBOX_PROCESS_IO_OPERATIONS, "process.stop"];
3651
+
3652
+ // packages/sdk/src/training.ts
3653
+ var HASH4 = /^[a-f0-9]{64}$/u;
3654
+ var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
3655
+ var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3656
+ var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3657
+ var PROVIDER_MODEL_ID2 = /^[^\s]{1,512}$/u;
3658
+ var TRAINING_PROVIDER_CAPABILITY = {
3659
+ id: "constal.training-provider",
3660
+ version: "1",
3661
+ hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
3662
+ };
3663
+ var TRAINING_RECIPE_DEFAULTS = {
3664
+ epochs: 1,
3665
+ batchSize: 4,
3666
+ loraRank: 32,
3667
+ learningRate: 1e-4,
3668
+ groupSize: 4,
3669
+ checkpointEvery: 25,
3670
+ evalEvery: 25,
3671
+ maxTrainTokens: 1e6,
3672
+ maxSampleTokens: 5e5
3673
+ };
3674
+ function record9(value) {
3675
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3676
+ }
3677
+ function integer2(value, field2, minimum) {
3678
+ if (!Number.isSafeInteger(value) || Number(value) < minimum) {
3679
+ throw new TypeError(`${field2} is invalid`);
3680
+ }
3681
+ return Number(value);
3682
+ }
3683
+ function finite(value, field2, minimum) {
3684
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum) {
3685
+ throw new TypeError(`${field2} is invalid`);
3686
+ }
3687
+ return value;
3688
+ }
3689
+ function providerPin(value) {
3690
+ const candidate = record9(value);
3691
+ 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");
3692
+ const parts = parseResourceName(candidate.crn);
3693
+ if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
3694
+ return candidate;
3342
3695
  }
3343
- function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args, options = {}) {
3344
- const { effort } = modelGenerationOptions(args);
3345
- if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
3346
- throw new TypeError("model Tool choice is invalid");
3696
+ function resumePoint(value) {
3697
+ if (value === null) return null;
3698
+ const candidate = record9(value);
3699
+ 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))) {
3700
+ throw new TypeError("training resume point is invalid");
3347
3701
  }
3348
- if (args.toolChoice === "required" && !args.tools?.length) {
3349
- throw new TypeError("required model Tool choice needs at least one offered Tool");
3702
+ return candidate;
3703
+ }
3704
+ function trainingProviderMetadata(value) {
3705
+ const candidate = record9(value);
3706
+ const checkpoints = record9(candidate?.checkpoints);
3707
+ 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))) {
3708
+ throw new TypeError("Training Provider metadata is invalid");
3350
3709
  }
3351
- const cache = modelCacheHint(args.cache);
3352
- const { messages, lastHistory } = turnMessages(args);
3353
- const breakpoint = cache ? { type: "ephemeral", ...cache.ttl === void 0 ? {} : { ttl: cache.ttl } } : null;
3354
- if (protocol === "anthropic") {
3355
- const anthropic = messages.map(anthropicMessage);
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 }] };
3710
+ const models = candidate.models.map((raw) => {
3711
+ const model = record9(raw);
3712
+ const pricing = record9(model?.pricing);
3713
+ 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))) {
3714
+ throw new TypeError("Training Provider model offer is invalid");
3359
3715
  }
3360
- const tools = args.tools ?? [];
3361
- return {
3362
- model,
3363
- system: breakpoint && args.system ? [{ type: "text", text: args.system, cache_control: breakpoint }] : args.system ?? "",
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
- };
3716
+ return raw;
3717
+ });
3718
+ if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
3719
+ throw new TypeError("Training Provider model offers must be unique");
3376
3720
  }
3377
- if (protocol === "openai") {
3378
- const marks = options.contentCacheControl === true ? breakpoint : null;
3379
- const marked = (text2) => marks && text2 ? [{ type: "text", text: text2, cache_control: marks }] : text2;
3380
- const openai = messages.map((message2, index) => {
3381
- const entry2 = openAiMessage(message2, options);
3382
- return index === lastHistory && typeof entry2.content === "string" ? { ...entry2, content: marked(entry2.content) } : entry2;
3383
- });
3384
- return {
3385
- model,
3386
- messages: [
3387
- ...args.system ? [{ role: "developer", content: marked(args.system) }] : [],
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
- };
3721
+ return {
3722
+ lifecycleVersion: 1,
3723
+ methods: candidate.methods,
3724
+ models,
3725
+ checkpoints
3726
+ };
3727
+ }
3728
+ function datasetRef(value, field2) {
3729
+ const candidate = record9(value);
3730
+ 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))) {
3731
+ throw new TypeError(`${field2} is invalid`);
3401
3732
  }
3402
- throw new TypeError("model gateway protocol is invalid");
3733
+ return candidate;
3403
3734
  }
3404
- function integer2(value) {
3405
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
3735
+ function scorerRef(value, field2) {
3736
+ const candidate = record9(value);
3737
+ 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))) {
3738
+ throw new TypeError(`${field2} is invalid`);
3739
+ }
3740
+ return candidate;
3406
3741
  }
3407
- function cacheWrite(usage) {
3408
- const value = usage.cache_creation_input_tokens ?? record7(usage.prompt_tokens_details)?.cache_write_tokens;
3409
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? { cacheWrite: value } : {};
3742
+ function trainingSteps(value) {
3743
+ if (!Array.isArray(value) || value.length === 0) throw new TypeError("training steps are invalid");
3744
+ const steps = value.map((raw) => {
3745
+ const step = record9(raw);
3746
+ 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");
3747
+ return { kind: step.kind, name: step.name };
3748
+ });
3749
+ if (new Set(steps.map((step) => canonicalJson(step))).size !== steps.length) throw new TypeError("training steps must be unique");
3750
+ return steps;
3751
+ }
3752
+ function trainingCorrection(value) {
3753
+ const candidate = record9(value);
3754
+ const message2 = record9(candidate?.message);
3755
+ 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))) {
3756
+ throw new TypeError("training correction is invalid");
3757
+ }
3758
+ const toolCalls = message2.toolCalls?.map((raw) => {
3759
+ const call = record9(raw);
3760
+ 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");
3761
+ canonicalJson(call.args);
3762
+ return { id: call.id, name: call.name, args: call.args };
3763
+ });
3764
+ if (toolCalls && new Set(toolCalls.map((call) => call.id)).size !== toolCalls.length) {
3765
+ throw new TypeError("training correction Tool call ids must be unique");
3766
+ }
3767
+ return { turn: candidate.turn, message: {
3768
+ content: message2.content,
3769
+ ...toolCalls?.length ? { toolCalls } : {},
3770
+ ...message2.reasoning ? { reasoning: message2.reasoning } : {}
3771
+ } };
3410
3772
  }
3411
- function costMetadata(usage) {
3412
- const cost = usage.cost;
3413
- const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
3414
- return {
3415
- ...costUsd !== void 0 ? { costUsd } : {},
3416
- ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
3417
- ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
3773
+ function trainingRecipe(value) {
3774
+ const candidate = record9(value);
3775
+ const allowed = [
3776
+ "method",
3777
+ "baseModel",
3778
+ "chatFormat",
3779
+ "steps",
3780
+ "dataset",
3781
+ "validationDataset",
3782
+ "scorers",
3783
+ "loraRank",
3784
+ "learningRate",
3785
+ "epochs",
3786
+ "batchSize",
3787
+ "groupSize",
3788
+ "temperature",
3789
+ "seed",
3790
+ "checkpointEvery",
3791
+ "evalEvery",
3792
+ "maxTrainTokens",
3793
+ "maxSampleTokens",
3794
+ "budgetMicroUsd"
3795
+ ];
3796
+ 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");
3797
+ const recipe = {
3798
+ method: candidate.method,
3799
+ baseModel: candidate.baseModel,
3800
+ chatFormat: chatFormatPin(candidate.chatFormat),
3801
+ ...candidate.steps === void 0 ? {} : { steps: trainingSteps(candidate.steps) },
3802
+ dataset: datasetRef(candidate.dataset, "training dataset"),
3803
+ validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
3804
+ scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
3805
+ loraRank: integer2(candidate.loraRank, "LoRA rank", 1),
3806
+ learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE),
3807
+ epochs: integer2(candidate.epochs, "epochs", 1),
3808
+ batchSize: integer2(candidate.batchSize, "batch size", 1),
3809
+ groupSize: integer2(candidate.groupSize, "group size", 1),
3810
+ temperature: finite(candidate.temperature, "temperature", 0),
3811
+ seed: integer2(candidate.seed, "seed", 0),
3812
+ checkpointEvery: integer2(candidate.checkpointEvery, "checkpoint interval", 1),
3813
+ evalEvery: integer2(candidate.evalEvery, "evaluation interval", 1),
3814
+ maxTrainTokens: integer2(candidate.maxTrainTokens, "training token limit", 1),
3815
+ maxSampleTokens: integer2(candidate.maxSampleTokens, "sample token limit", 1),
3816
+ budgetMicroUsd: integer2(candidate.budgetMicroUsd, "training budget", 1)
3418
3817
  };
3818
+ if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
3819
+ return recipe;
3419
3820
  }
3420
- function modelProtocolResult(protocol, raw, provider, model) {
3421
- const source = record7(raw);
3422
- if (!source) throw new TypeError("model gateway response is invalid");
3423
- const toolCalls = [];
3424
- let content2 = "";
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");
3821
+ function startTrainingRequest(value) {
3822
+ const candidate = record9(value);
3823
+ 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))) {
3824
+ throw new TypeError("training request is invalid");
3825
+ }
3480
3826
  return {
3481
- content: content2,
3482
- ...toolCalls.length ? { toolCalls } : {},
3483
- ...refusal === void 0 ? {} : { refusal },
3484
- ...reasoningContent === void 0 ? {} : { reasoningContent },
3485
- usage,
3486
- provider,
3487
- model,
3488
- completion: modelCompletionStatus(protocol, raw)
3827
+ ...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
3828
+ ...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
3829
+ ...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
3830
+ recipe: trainingRecipe(candidate.recipe),
3831
+ outputModelId: candidate.outputModelId
3489
3832
  };
3490
3833
  }
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
3834
 
3500
3835
  // packages/sdk/src/gateway.ts
3501
3836
  async function checkpointArtifactRef(value) {
3502
3837
  return await sha256Hex(canonicalJson(value));
3503
3838
  }
3504
3839
  var SLOT2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3505
- var HASH3 = /^[a-f0-9]{64}$/u;
3840
+ var HASH5 = /^[a-f0-9]{64}$/u;
3506
3841
  var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
3507
3842
  function httpsUrl(value, field2) {
3508
3843
  if (value === void 0) return;
@@ -3567,7 +3902,7 @@ function checkpointImportRequest(value) {
3567
3902
  const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
3568
3903
  const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
3569
3904
  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" || !HASH3.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" || !HASH3.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))) {
3905
+ 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
3906
  throw new TypeError("checkpoint import request is invalid");
3572
3907
  }
3573
3908
  try {
@@ -3585,7 +3920,7 @@ function checkpointImportRequest(value) {
3585
3920
  function checkpointDeploymentRequest(value) {
3586
3921
  const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3587
3922
  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" || !HASH3.test(gateway2.hash) || Object.keys(gateway2).some((key) => !["crn", "hash"].includes(key)) || Object.keys(source).some((key) => !["gateway", "import"].includes(key))) {
3923
+ 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
3924
  throw new TypeError("checkpoint deployment request is invalid");
3590
3925
  }
3591
3926
  try {
@@ -3665,12 +4000,16 @@ function gatewayPackageMetadata(value) {
3665
4000
  const discovery = discoverySetup(source.discovery);
3666
4001
  const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
3667
4002
  const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
4003
+ const chatFormat2 = source.chatFormat === void 0 ? void 0 : chatFormatMetadata(source.chatFormat);
3668
4004
  if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
3669
4005
  throw new TypeError("Training Provider packages must implement the exact Training Provider capability");
3670
4006
  }
3671
4007
  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
4008
  throw new TypeError("Checkpoint import Gateways must implement exact completion and checkpoint import capabilities");
3673
4009
  }
4010
+ if (chatFormat2 && !capabilities.some((contract) => contract.id === CHAT_FORMAT_CAPABILITY.id && contract.version === CHAT_FORMAT_CAPABILITY.version && contract.hash === CHAT_FORMAT_CAPABILITY.hash)) {
4011
+ throw new TypeError("Chat format packages must implement the exact chat format capability");
4012
+ }
3674
4013
  return {
3675
4014
  lifecycleVersion: 1,
3676
4015
  displayName: source.displayName,
@@ -3685,7 +4024,8 @@ function gatewayPackageMetadata(value) {
3685
4024
  ...configEgress.length ? { configEgress } : {},
3686
4025
  ...discovery ? { discovery } : {},
3687
4026
  ...training ? { training } : {},
3688
- ...checkpointImport ? { checkpointImport } : {}
4027
+ ...checkpointImport ? { checkpointImport } : {},
4028
+ ...chatFormat2 ? { chatFormat: chatFormat2 } : {}
3689
4029
  };
3690
4030
  }
3691
4031
  function resolveGatewayEgress(metadata3, config) {
@@ -3727,7 +4067,8 @@ function gateway(definition) {
3727
4067
  configEgress: definition.configEgress,
3728
4068
  discovery: definition.discovery,
3729
4069
  training: definition.training,
3730
- checkpointImport: definition.checkpointImport
4070
+ checkpointImport: definition.checkpointImport,
4071
+ chatFormat: definition.chatFormat
3731
4072
  });
3732
4073
  const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
3733
4074
  for (const binding of gateway2.configEgress ?? []) {
@@ -3754,6 +4095,10 @@ function gateway(definition) {
3754
4095
  throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
3755
4096
  }
3756
4097
  }
4098
+ if (gateway2.chatFormat && ["render", "parse"].some((op) => {
4099
+ const operation = declarations.find((candidate) => candidate.op === op);
4100
+ return !operation || operation.async || operation.effect !== "read-only" || operation.recovery.kind !== "repeat";
4101
+ })) throw new TypeError("Chat format render and parse must be synchronous, read-only, and repeatable");
3757
4102
  return declarations;
3758
4103
  } };
3759
4104
  return Object.freeze(wrapped);
@@ -3773,6 +4118,88 @@ function trainingProvider(definition) {
3773
4118
  }
3774
4119
  });
3775
4120
  }
4121
+ var chatRenderRequestSchema = {
4122
+ type: "object",
4123
+ required: ["system", "messages", "tools", "toolChoice", "effort", "train"],
4124
+ additionalProperties: false,
4125
+ properties: {
4126
+ system: { type: ["string", "null"] },
4127
+ messages: { type: "array", items: { type: "object" } },
4128
+ tools: { type: "array", items: {
4129
+ type: "object",
4130
+ required: ["name", "description", "schema"],
4131
+ additionalProperties: false,
4132
+ properties: { name: { type: "string" }, description: { type: "string" }, schema: { type: "object" } }
4133
+ } },
4134
+ toolChoice: { enum: ["auto", "required", null] },
4135
+ effort: { type: ["string", "null"] },
4136
+ train: { type: "array", items: { type: "integer", minimum: 0 } }
4137
+ }
4138
+ };
4139
+ var tokensSchema = { type: "array", items: { type: "integer", minimum: 0 } };
4140
+ var chatFormatOperations = [
4141
+ {
4142
+ op: "render",
4143
+ description: "Render a conversation to tokens, with the spans of its trained assistant turns.",
4144
+ schema: chatRenderRequestSchema,
4145
+ resultSchema: { type: "object", required: ["tokens", "spans", "stop"], additionalProperties: false, properties: {
4146
+ tokens: tokensSchema,
4147
+ stop: tokensSchema,
4148
+ spans: { type: "array", items: {
4149
+ type: "object",
4150
+ required: ["message", "start", "end"],
4151
+ additionalProperties: false,
4152
+ properties: {
4153
+ message: { type: "integer", minimum: 0 },
4154
+ start: { type: "integer", minimum: 0 },
4155
+ end: { type: "integer", minimum: 1 }
4156
+ }
4157
+ } }
4158
+ } },
4159
+ effect: "read-only",
4160
+ recovery: { kind: "repeat" },
4161
+ async: false,
4162
+ usage: { meter: "none", priceTable: null }
4163
+ },
4164
+ {
4165
+ op: "parse",
4166
+ description: "Parse sampled tokens into an assistant turn.",
4167
+ schema: { type: "object", required: ["tokens"], additionalProperties: false, properties: { tokens: tokensSchema } },
4168
+ resultSchema: {
4169
+ type: "object",
4170
+ required: ["content", "toolCalls", "reasoningContent", "stopped"],
4171
+ additionalProperties: false,
4172
+ properties: {
4173
+ content: { type: "string" },
4174
+ toolCalls: { type: "array", items: { type: "object" } },
4175
+ reasoningContent: { type: ["string", "null"] },
4176
+ stopped: { type: "boolean" }
4177
+ }
4178
+ },
4179
+ effect: "read-only",
4180
+ recovery: { kind: "repeat" },
4181
+ async: false,
4182
+ usage: { meter: "none", priceTable: null }
4183
+ }
4184
+ ];
4185
+ function chatFormat(definition) {
4186
+ const { render, parse, ...connection } = definition;
4187
+ if (typeof render !== "function" || typeof parse !== "function") throw new TypeError("chat format definition is invalid");
4188
+ return gateway({
4189
+ ...connection,
4190
+ kind: "service",
4191
+ capabilities: [CHAT_FORMAT_CAPABILITY],
4192
+ catalog: () => chatFormatOperations.map((operation) => ({ ...operation })),
4193
+ async invoke(request, context) {
4194
+ if (request.op === "render") {
4195
+ const input = chatRenderInput(request.args);
4196
+ return chatRendering(await render(input, context), input);
4197
+ }
4198
+ if (request.op === "parse") return chatParsed(await parse(chatParseInput(request.args), context));
4199
+ throw new TypeError(`chat format operation is unknown: ${request.op}`);
4200
+ }
4201
+ });
4202
+ }
3776
4203
  var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
3777
4204
  id: "constal.model-checkpoint-import",
3778
4205
  version: "1",
@@ -3808,7 +4235,7 @@ function credentialProviderConfigSchema(value) {
3808
4235
  function interactionRecord(value) {
3809
4236
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3810
4237
  }
3811
- function exactKeys3(value, allowed) {
4238
+ function exactKeys4(value, allowed) {
3812
4239
  return Object.keys(value).every((key) => allowed.includes(key));
3813
4240
  }
3814
4241
  function nonemptyText(value) {
@@ -3826,27 +4253,27 @@ function credentialInteractionEvent(value) {
3826
4253
  if (event.kind === "callback") {
3827
4254
  const parameters = interactionRecord(event.parameters);
3828
4255
  const headers = interactionRecord(event.headers);
3829
- if (!exactKeys3(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))) {
4256
+ 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
4257
  throw new TypeError("credential interaction callback is invalid");
3831
4258
  }
3832
4259
  } else if (event.kind === "submit") {
3833
- if (!exactKeys3(event, ["kind", "value"])) {
4260
+ if (!exactKeys4(event, ["kind", "value"])) {
3834
4261
  throw new TypeError("credential interaction submission is invalid");
3835
4262
  }
3836
4263
  canonicalJson(event.value);
3837
- } else if (!exactKeys3(event, ["kind"])) throw new TypeError("credential interaction event is invalid");
4264
+ } else if (!exactKeys4(event, ["kind"])) throw new TypeError("credential interaction event is invalid");
3838
4265
  return event;
3839
4266
  }
3840
4267
  function credentialInteractionPrimaryAction(value, origins) {
3841
4268
  const action3 = interactionRecord(value);
3842
4269
  const event = interactionRecord(action3?.event);
3843
- if (!action3 || !event || !nonemptyText(action3.label) || !exactKeys3(event, ["kind"]) || event.kind !== "continue") {
4270
+ if (!action3 || !event || !nonemptyText(action3.label) || !exactKeys4(event, ["kind"]) || event.kind !== "continue") {
3844
4271
  throw new TypeError("credential interaction primary action is invalid");
3845
4272
  }
3846
4273
  if (action3.kind === "continue") {
3847
- if (!exactKeys3(action3, ["kind", "label", "event"])) throw new TypeError("credential interaction primary action is invalid");
4274
+ if (!exactKeys4(action3, ["kind", "label", "event"])) throw new TypeError("credential interaction primary action is invalid");
3848
4275
  } else if (action3.kind === "open-url") {
3849
- if (!exactKeys3(action3, ["kind", "label", "url", "event"]) || !nonemptyText(action3.url)) {
4276
+ if (!exactKeys4(action3, ["kind", "label", "url", "event"]) || !nonemptyText(action3.url)) {
3850
4277
  throw new TypeError("credential interaction primary action is invalid");
3851
4278
  }
3852
4279
  let url;
@@ -3869,7 +4296,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
3869
4296
  const expiresAt = action3.kind === "complete" ? null : interactionExpiry(action3.expiresAt, sessionExpiresAt);
3870
4297
  if (Number.isNaN(expiresAt)) throw new TypeError("credential interaction action expiry is invalid");
3871
4298
  if (action3.kind === "redirect") {
3872
- if (!exactKeys3(action3, ["kind", "url", "expiresAt"]) || !nonemptyText(action3.url)) {
4299
+ if (!exactKeys4(action3, ["kind", "url", "expiresAt"]) || !nonemptyText(action3.url)) {
3873
4300
  throw new TypeError("credential interaction redirect is invalid");
3874
4301
  }
3875
4302
  let url;
@@ -3882,7 +4309,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
3882
4309
  throw new TypeError("credential interaction redirect is not authorized");
3883
4310
  }
3884
4311
  } else if (action3.kind === "form") {
3885
- if (!exactKeys3(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)) {
4312
+ 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
4313
  throw new TypeError("credential interaction form is invalid");
3887
4314
  }
3888
4315
  const schemaError = validateJsonSchemaDefinition(action3.schema, "$interaction.form.schema");
@@ -3891,16 +4318,16 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
3891
4318
  throw new TypeError(`credential interaction form schema is invalid${schemaError ? `: ${schemaError}` : ""}`);
3892
4319
  }
3893
4320
  } else if (action3.kind === "display") {
3894
- if (!exactKeys3(action3, ["kind", "instructions", "title", "userCode", "primaryAction", "expiresAt"]) || !nonemptyText(action3.instructions) || action3.title !== void 0 && !nonemptyText(action3.title) || action3.userCode !== void 0 && !nonemptyText(action3.userCode)) {
4321
+ 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
4322
  throw new TypeError("credential interaction display is invalid");
3896
4323
  }
3897
4324
  credentialInteractionPrimaryAction(action3.primaryAction, origins);
3898
4325
  } else if (action3.kind === "wait") {
3899
- if (!exactKeys3(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) {
4326
+ 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
4327
  throw new TypeError("credential interaction wait action is invalid");
3901
4328
  }
3902
4329
  } else {
3903
- if (!exactKeys3(action3, ["kind", "material", "expiresAt"]) || !nonemptyText(action3.material) || action3.expiresAt !== void 0 && action3.expiresAt !== null && (!Number.isSafeInteger(action3.expiresAt) || Number(action3.expiresAt) <= Date.now())) {
4330
+ 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
4331
  throw new TypeError("credential interaction completion is invalid");
3905
4332
  }
3906
4333
  }
@@ -3908,7 +4335,7 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
3908
4335
  }
3909
4336
  function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
3910
4337
  const result = interactionRecord(value);
3911
- if (!result || !exactKeys3(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
4338
+ if (!result || !exactKeys4(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
3912
4339
  const privateState = result.privateState;
3913
4340
  if (privateState !== void 0 && privateState !== null && typeof privateState !== "string") throw new TypeError("credential interaction private state is invalid");
3914
4341
  return {
@@ -4023,7 +4450,7 @@ var EVALUATION_LIMITS = {
4023
4450
  };
4024
4451
  var QUESTION_ID = /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/u;
4025
4452
  var MODEL = /^[a-z0-9][a-z0-9._\/-]{0,255}$/u;
4026
- function record8(value) {
4453
+ function record10(value) {
4027
4454
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
4028
4455
  }
4029
4456
  function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
@@ -4033,7 +4460,7 @@ function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
4033
4460
  return value;
4034
4461
  }
4035
4462
  const array = Array.isArray(value);
4036
- const source = array ? value : record8(value);
4463
+ const source = array ? value : record10(value);
4037
4464
  const prototype = source ? Object.getPrototypeOf(source) : void 0;
4038
4465
  if (!source || !array && prototype !== Object.prototype && prototype !== null) throw new TypeError(`${field2} must be JSON text or structure`);
4039
4466
  if (ancestors.has(source)) throw new TypeError(`${field2} contains a JSON cycle`);
@@ -4046,7 +4473,7 @@ function entry(value, field2, ancestors = /* @__PURE__ */ new WeakSet()) {
4046
4473
  }
4047
4474
  }
4048
4475
  function question(id2, value) {
4049
- const source = record8(value);
4476
+ const source = record10(value);
4050
4477
  if (!source) throw new TypeError(`question ${id2} must be an object`);
4051
4478
  const type = source.type;
4052
4479
  if (type !== "choice" && type !== "score" && type !== "noul") throw new TypeError(`question ${id2} type must be choice, score, or noul`);
@@ -4055,7 +4482,7 @@ function question(id2, value) {
4055
4482
  const unknown = Object.keys(source).find((key) => !["type", "instructions", "criteria"].includes(key));
4056
4483
  if (unknown) throw new TypeError(`question ${id2} has an unknown field ${unknown}`);
4057
4484
  if (type === "choice") {
4058
- const criteria2 = record8(source.criteria);
4485
+ const criteria2 = record10(source.criteria);
4059
4486
  const options = criteria2 ? Object.keys(criteria2) : [];
4060
4487
  if (!criteria2 || options.length < 2) throw new TypeError(`choice question ${id2} needs at least two options`);
4061
4488
  if (options.some((option) => !option.trim())) throw new TypeError(`choice question ${id2} has an invalid option key`);
@@ -4067,7 +4494,7 @@ function question(id2, value) {
4067
4494
  return { type, instructions, criteria: criteria2.map((level, index) => entry(level, `score question ${id2} level ${index}`)) };
4068
4495
  }
4069
4496
  if (source.criteria === void 0) return { type, instructions };
4070
- const criteria = record8(source.criteria);
4497
+ const criteria = record10(source.criteria);
4071
4498
  if (!criteria || Object.keys(criteria).some((key) => key !== "true" && key !== "false")) {
4072
4499
  throw new TypeError(`noul question ${id2} criteria may only describe true and false`);
4073
4500
  }
@@ -4077,11 +4504,11 @@ function question(id2, value) {
4077
4504
  } };
4078
4505
  }
4079
4506
  function evaluationArguments(value) {
4080
- const source = record8(value);
4507
+ const source = record10(value);
4081
4508
  if (!source) throw new TypeError("evaluation arguments must be an object");
4082
4509
  if (source.state === void 0) throw new TypeError("evaluation requires a state");
4083
4510
  const state = entry(source.state, "evaluation state");
4084
- const questionSource = record8(source.questions);
4511
+ const questionSource = record10(source.questions);
4085
4512
  const ids = questionSource ? Object.keys(questionSource) : [];
4086
4513
  if (!questionSource || ids.length === 0) throw new TypeError("evaluation requires at least one question");
4087
4514
  const questions = /* @__PURE__ */ Object.create(null);
@@ -4108,14 +4535,14 @@ function probability(value, field2) {
4108
4535
  return value;
4109
4536
  }
4110
4537
  function distribution(value, keys, field2) {
4111
- const source = record8(value);
4538
+ const source = record10(value);
4112
4539
  if (!source) throw new TypeError(`${field2} must map every option to a probability`);
4113
4540
  const output = {};
4114
4541
  for (const key of keys) output[key] = probability(source[key], `${field2}.${key}`);
4115
4542
  return output;
4116
4543
  }
4117
4544
  function answer(id2, asked, value) {
4118
- const source = record8(value);
4545
+ const source = record10(value);
4119
4546
  if (!source || source.type !== asked.type) throw new TypeError(`answer ${id2} does not match its ${asked.type} question`);
4120
4547
  if (asked.type === "noul") return { type: "noul", noul: probability(source.noul, `answer ${id2} noul`) };
4121
4548
  const confidence = probability(source.confidence, `answer ${id2} confidence`);
@@ -4128,7 +4555,7 @@ function answer(id2, asked, value) {
4128
4555
  if (typeof source.score !== "number" || !Number.isFinite(source.score) || source.score < 0 || source.score > levels.length - 1) {
4129
4556
  throw new TypeError(`answer ${id2} score is outside its levels`);
4130
4557
  }
4131
- const legend = record8(source.legend);
4558
+ const legend = record10(source.legend);
4132
4559
  return {
4133
4560
  type: "score",
4134
4561
  score: source.score,
@@ -4142,15 +4569,15 @@ function integer3(value) {
4142
4569
  }
4143
4570
  function evaluationProtocolResult(protocol, raw, provider, model, questions) {
4144
4571
  if (protocol !== "typesafe") throw new TypeError("evaluation protocol is invalid");
4145
- const source = record8(raw) ?? {};
4146
- const answers = record8(source.answers);
4572
+ const source = record10(raw) ?? {};
4573
+ const answers = record10(source.answers);
4147
4574
  if (!answers) throw new TypeError("evaluation response has no answers");
4148
4575
  const output = {};
4149
4576
  for (const [id2, asked] of Object.entries(questions)) {
4150
4577
  if (answers[id2] === void 0) throw new TypeError(`evaluation response is missing answer ${id2}`);
4151
4578
  output[id2] = answer(id2, asked, answers[id2]);
4152
4579
  }
4153
- const usage = record8(source.usage) ?? {};
4580
+ const usage = record10(source.usage) ?? {};
4154
4581
  const cost = usage.cost;
4155
4582
  const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
4156
4583
  return {
@@ -4177,30 +4604,30 @@ function scoreLevel(answer2) {
4177
4604
 
4178
4605
  // packages/sdk/src/mcp.ts
4179
4606
  var MCP_PROTOCOL_VERSION = "2025-06-18";
4180
- function record9(value) {
4607
+ function record11(value) {
4181
4608
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
4182
4609
  }
4183
4610
  function mcpToolDescription(value) {
4184
- const tool = record9(value), inputSchema = record9(tool?.inputSchema);
4185
- const outputSchema = tool?.outputSchema === void 0 ? {} : record9(tool.outputSchema);
4611
+ const tool = record11(value), inputSchema = record11(tool?.inputSchema);
4612
+ const outputSchema = tool?.outputSchema === void 0 ? {} : record11(tool.outputSchema);
4186
4613
  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
4614
  return {
4188
4615
  name: tool.name,
4189
4616
  description: typeof tool.description === "string" ? tool.description : "",
4190
4617
  inputSchema,
4191
4618
  outputSchema,
4192
- annotations: record9(tool.annotations) ?? {}
4619
+ annotations: record11(tool.annotations) ?? {}
4193
4620
  };
4194
4621
  }
4195
4622
  function mcpToolResult(value) {
4196
- const result = record9(value);
4197
- if (!result || result.isError !== void 0 && typeof result.isError !== "boolean" || result?.content !== void 0 && !Array.isArray(result.content) || result?.structuredContent !== void 0 && !record9(result.structuredContent) || result && result.content === void 0 && result.structuredContent === void 0) {
4623
+ const result = record11(value);
4624
+ 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
4625
  throw new TerminalIntegrationFailure("MCP tools/call result is invalid");
4199
4626
  }
4200
4627
  return result;
4201
4628
  }
4202
4629
  function message(value) {
4203
- const item = record9(value);
4630
+ const item = record11(value);
4204
4631
  if (!item || item.jsonrpc !== "2.0") throw new TerminalIntegrationFailure("MCP transport returned an invalid JSON-RPC message");
4205
4632
  return item;
4206
4633
  }
@@ -4240,7 +4667,7 @@ var McpClient = class {
4240
4667
  for (; ; ) {
4241
4668
  const received = message(await this.transport.receive());
4242
4669
  if (received.id === id2) {
4243
- if (record9(received.error)) {
4670
+ if (record11(received.error)) {
4244
4671
  const error = received.error;
4245
4672
  throw new TerminalIntegrationFailure(`MCP ${typeof error.code === "number" || typeof error.code === "string" ? error.code : "unknown"}: ${typeof error.message === "string" ? error.message : "request failed"}`);
4246
4673
  }
@@ -4265,7 +4692,7 @@ var McpClient = class {
4265
4692
  }
4266
4693
  async initialize() {
4267
4694
  if (this.#protocol) return { protocolVersion: this.#protocol, server: {} };
4268
- const result = record9(await this.#request("initialize", {
4695
+ const result = record11(await this.#request("initialize", {
4269
4696
  protocolVersion: MCP_PROTOCOL_VERSION,
4270
4697
  capabilities: {},
4271
4698
  clientInfo: this.options.client ?? { name: "Constal", version: "1.0.0" }
@@ -4276,7 +4703,7 @@ var McpClient = class {
4276
4703
  this.#protocol = result.protocolVersion;
4277
4704
  await this.transport.negotiated?.(this.#protocol);
4278
4705
  await this.#serialized(() => this.transport.send({ jsonrpc: "2.0", method: "notifications/initialized" }));
4279
- return { protocolVersion: this.#protocol, server: record9(result.serverInfo) ?? {} };
4706
+ return { protocolVersion: this.#protocol, server: record11(result.serverInfo) ?? {} };
4280
4707
  }
4281
4708
  async request(method, params) {
4282
4709
  if (!this.#protocol) throw new TerminalIntegrationFailure("MCP session is not initialized");
@@ -4286,8 +4713,8 @@ var McpClient = class {
4286
4713
  const tools = [], cursors = /* @__PURE__ */ new Set();
4287
4714
  let cursor;
4288
4715
  do {
4289
- const result = record9(await this.request("tools/list", cursor ? { cursor } : {}));
4290
- if (!result || !Array.isArray(result.tools) || result.tools.some((item) => !record9(item))) {
4716
+ const result = record11(await this.request("tools/list", cursor ? { cursor } : {}));
4717
+ if (!result || !Array.isArray(result.tools) || result.tools.some((item) => !record11(item))) {
4291
4718
  throw new TerminalIntegrationFailure("MCP tools/list result is invalid");
4292
4719
  }
4293
4720
  tools.push(...result.tools);
@@ -4317,31 +4744,31 @@ var McpClient = class {
4317
4744
  function validPointer(value) {
4318
4745
  return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));
4319
4746
  }
4320
- function record10(value) {
4747
+ function record12(value) {
4321
4748
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
4322
4749
  }
4323
- function exactKeys4(value, allowed) {
4750
+ function exactKeys5(value, allowed) {
4324
4751
  return Object.keys(value).every((key) => allowed.includes(key));
4325
4752
  }
4326
4753
  function scorerRule(value, depth, state) {
4327
- const rule = record10(value);
4754
+ const rule = record12(value);
4328
4755
  if (!rule || typeof rule.op !== "string") throw new TypeError("Code Scorer IR is invalid");
4329
4756
  if (rule.op === "all" || rule.op === "any") {
4330
- if (!exactKeys4(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1) {
4757
+ if (!exactKeys5(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1) {
4331
4758
  throw new TypeError("Code Scorer logical rule is invalid");
4332
4759
  }
4333
4760
  return { op: rule.op, rules: rule.rules.map((child) => scorerRule(child, depth + 1, state)) };
4334
4761
  }
4335
4762
  if (rule.op === "not") {
4336
- if (!exactKeys4(rule, ["op", "rule"])) throw new TypeError("Code Scorer not rule is invalid");
4763
+ if (!exactKeys5(rule, ["op", "rule"])) throw new TypeError("Code Scorer not rule is invalid");
4337
4764
  return { op: "not", rule: scorerRule(rule.rule, depth + 1, state) };
4338
4765
  }
4339
4766
  if (rule.op === "schema") {
4340
- if (!exactKeys4(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record10(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
4767
+ 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
4768
  return rule;
4342
4769
  }
4343
4770
  if (rule.op === "regex") {
4344
- if (!exactKeys4(rule, ["op", "path", "pattern", "flags"]) || !validPointer(rule.path) || typeof rule.pattern !== "string" || rule.pattern.length > 4096 || ![void 0, "", "i", "m", "im"].includes(rule.flags)) {
4771
+ 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
4772
  throw new TypeError("Code Scorer regex rule is invalid");
4346
4773
  }
4347
4774
  try {
@@ -4352,28 +4779,28 @@ function scorerRule(value, depth, state) {
4352
4779
  return rule;
4353
4780
  }
4354
4781
  if (rule.op === "range") {
4355
- if (!exactKeys4(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");
4782
+ 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
4783
  return rule;
4357
4784
  }
4358
4785
  if (rule.op === "equals" || rule.op === "contains") {
4359
- if (!exactKeys4(rule, ["op", "path", "value"]) || !validPointer(rule.path) || !Object.hasOwn(rule, "value") || new TextEncoder().encode(canonicalJson(rule.value)).byteLength > 65536) {
4786
+ if (!exactKeys5(rule, ["op", "path", "value"]) || !validPointer(rule.path) || !Object.hasOwn(rule, "value") || new TextEncoder().encode(canonicalJson(rule.value)).byteLength > 65536) {
4360
4787
  throw new TypeError(`Code Scorer ${rule.op} rule is invalid`);
4361
4788
  }
4362
4789
  return rule;
4363
4790
  }
4364
4791
  if (rule.op === "tool-sequence") {
4365
- if (!exactKeys4(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");
4792
+ 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
4793
  return rule;
4367
4794
  }
4368
4795
  if (rule.op === "citations-in-source") {
4369
- if (!exactKeys4(rule, ["op", "textPath", "sourcesPath"]) || !validPointer(rule.textPath) || !validPointer(rule.sourcesPath)) throw new TypeError("Code Scorer citation rule is invalid");
4796
+ if (!exactKeys5(rule, ["op", "textPath", "sourcesPath"]) || !validPointer(rule.textPath) || !validPointer(rule.sourcesPath)) throw new TypeError("Code Scorer citation rule is invalid");
4370
4797
  return rule;
4371
4798
  }
4372
4799
  throw new TypeError("Code Scorer operation is invalid");
4373
4800
  }
4374
4801
  function codeScorerIR(value) {
4375
- const ir = record10(value);
4376
- if (!ir || ir.v !== 1 || !exactKeys4(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
4802
+ const ir = record12(value);
4803
+ if (!ir || ir.v !== 1 || !exactKeys5(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
4377
4804
  return { v: 1, rule: scorerRule(ir.rule, 0, { rules: 0 }) };
4378
4805
  }
4379
4806
  function pointer(value, path) {
@@ -4385,7 +4812,7 @@ function pointer(value, path) {
4385
4812
  if (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length) return { found: false, value: void 0 };
4386
4813
  current = current[Number(key)];
4387
4814
  } else {
4388
- const source = record10(current);
4815
+ const source = record12(current);
4389
4816
  if (!source || !Object.hasOwn(source, key)) return { found: false, value: void 0 };
4390
4817
  current = source[key];
4391
4818
  }
@@ -4419,7 +4846,7 @@ function evaluate(rule, subject) {
4419
4846
  if (!sources.found || !Array.isArray(sources.value)) return fail(rule.sourcesPath, "citation sources are missing");
4420
4847
  const available = new Set(sources.value.flatMap((source, index) => {
4421
4848
  if (typeof source === "string") return [source, String(index + 1)];
4422
- const item = record10(source);
4849
+ const item = record12(source);
4423
4850
  return item ? [String(item.id ?? ""), String(index + 1)].filter(Boolean) : [String(index + 1)];
4424
4851
  }));
4425
4852
  const citations = [...text2.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
@@ -4438,7 +4865,7 @@ function evaluate(rule, subject) {
4438
4865
  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
4866
  return contains ? pass() : fail(rule.path, "value is not contained");
4440
4867
  }
4441
- const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record10(item)?.name ?? "")) : [];
4868
+ const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record12(item)?.name ?? "")) : [];
4442
4869
  const sequence = rule.mode === "exact" ? names.length === rule.expected.length && names.every((name, index) => name === rule.expected[index]) : rule.expected.reduce((cursor, expected) => {
4443
4870
  const index = names.indexOf(expected, cursor);
4444
4871
  return index < 0 ? Number.POSITIVE_INFINITY : index + 1;
@@ -4458,9 +4885,9 @@ function evaluateCodeScorer(raw, subject) {
4458
4885
 
4459
4886
  // packages/sdk/src/errors.ts
4460
4887
  var GateExhausted = class extends Error {
4461
- constructor(record11) {
4888
+ constructor(record13) {
4462
4889
  super("turn gate exhausted");
4463
- this.record = record11;
4890
+ this.record = record13;
4464
4891
  this.name = "GateExhausted";
4465
4892
  }
4466
4893
  record;
@@ -4671,6 +5098,7 @@ export {
4671
5098
  AGENT_UI_DEFAULTS,
4672
5099
  AfterYield,
4673
5100
  ApiError,
5101
+ CHAT_FORMAT_CAPABILITY,
4674
5102
  CONSTAL_API_CAPABILITY,
4675
5103
  CONSTAL_API_GET_KINDS,
4676
5104
  CONSTAL_API_MODEL_TOOL_DESCRIPTIONS,
@@ -4682,6 +5110,7 @@ export {
4682
5110
  CommitGateRejected,
4683
5111
  CredentialRevoked,
4684
5112
  CredentialUnavailable,
5113
+ DATA_SHARE_FEE_BPS,
4685
5114
  DirectNetworkDenied,
4686
5115
  EVALUATION_LIMITS,
4687
5116
  EffectCeilingExceeded,
@@ -4697,6 +5126,7 @@ export {
4697
5126
  MODEL_EVALUATION_CAPABILITY,
4698
5127
  McpClient,
4699
5128
  NondeterministicReplay,
5129
+ NotAppendOnly,
4700
5130
  OutcomeUnknown,
4701
5131
  PolicyConstraintFailed,
4702
5132
  PolicyDecisionFailed,
@@ -4711,6 +5141,7 @@ export {
4711
5141
  SpawnCardinality,
4712
5142
  SwallowedYield,
4713
5143
  TRAINING_PROVIDER_CAPABILITY,
5144
+ TRAINING_RECIPE_DEFAULTS,
4714
5145
  TerminalIntegrationFailure,
4715
5146
  ToolUnavailable,
4716
5147
  UI_ASSET_CONTENT_TYPES,
@@ -4743,6 +5174,14 @@ export {
4743
5174
  channelSourceEvidence,
4744
5175
  channelSubscriptionRequest,
4745
5176
  channelTarget,
5177
+ chatFormat,
5178
+ chatFormatMetadata,
5179
+ chatFormatPin,
5180
+ chatParseInput,
5181
+ chatParsed,
5182
+ chatRenderInput,
5183
+ chatRenderRequest,
5184
+ chatRendering,
4746
5185
  checkpointArtifactRef,
4747
5186
  checkpointDeploymentRequest,
4748
5187
  checkpointImportMetadata,
@@ -4765,6 +5204,7 @@ export {
4765
5204
  customerTenantName,
4766
5205
  cutBatches,
4767
5206
  cutPartitions,
5207
+ dataShareEarningMicroUsd,
4768
5208
  datasetName,
4769
5209
  evaluateCodeScorer,
4770
5210
  evaluatePolicyDefinition,
@@ -4812,7 +5252,6 @@ export {
4812
5252
  policy,
4813
5253
  policyName,
4814
5254
  race,
4815
- renderTrainingCompletion,
4816
5255
  resolveBindingOwner,
4817
5256
  resolveContainerImageSource,
4818
5257
  resolveGatewayEgress,
@@ -4826,6 +5265,7 @@ export {
4826
5265
  resourcePattern,
4827
5266
  resourceSelector,
4828
5267
  resourceTools,
5268
+ runLabels,
4829
5269
  sandboxControls,
4830
5270
  sandboxEgressDecision,
4831
5271
  sandboxEgressHostMatches,
@@ -4844,12 +5284,18 @@ export {
4844
5284
  setupScreenView,
4845
5285
  setupSubmission,
4846
5286
  sha256Hex,
5287
+ shareContributionRequest,
5288
+ shareContributionReview,
5289
+ shareEvaluation,
5290
+ sharePrices,
5291
+ shareRequest,
4847
5292
  skills,
4848
5293
  stageOutput,
4849
5294
  startTrainingRequest,
4850
5295
  subtask,
4851
5296
  tableDescribe,
4852
5297
  tableQuery,
5298
+ trainingCorrection,
4853
5299
  trainingProvider,
4854
5300
  trainingProviderMetadata,
4855
5301
  trainingRecipe,