@constal/sdk 3.0.1 → 3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constal/sdk",
3
- "version": "3.0.1",
3
+ "version": "3.1.0",
4
4
  "description": "Public TypeScript SDK for authoring Constal agents, integrations, policies, channels, and credential providers",
5
5
  "keywords": [
6
6
  "constal",
package/publish/api.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "package": "@constal/sdk",
3
- "version": "3.0.1",
3
+ "version": "3.1.0",
4
4
  "exports": [
5
5
  "Action",
6
6
  "ActionPattern",
@@ -586,6 +586,89 @@ declare function renderTrainingCompletion(input: unknown, expected?: unknown): {
586
586
  completion: string | null;
587
587
  };
588
588
 
589
+ /** Stable capability shared by configured Models and directly bound Gateways. */
590
+ declare const MODEL_COMPLETION_CAPABILITY: CapabilityContractRef;
591
+ type ModelGatewayProtocol = "anthropic" | "openai";
592
+ type RawModelProtocol = ModelGatewayProtocol | "bedrock";
593
+ /** Optional generation choices. Supported effort values are defined by the selected model. */
594
+ interface ModelGenerationOptions {
595
+ maxOutputTokens?: number;
596
+ temperature?: number;
597
+ effort?: string;
598
+ }
599
+ interface ModelTool {
600
+ name: string;
601
+ version?: string;
602
+ description: string;
603
+ schema: object;
604
+ }
605
+ interface ModelInvocationArgs extends ModelGenerationOptions {
606
+ /** Logical Model identity or a model selected through a bound Gateway, evaluated under Policy. */
607
+ model?: string;
608
+ system?: string;
609
+ objective?: unknown;
610
+ context?: unknown;
611
+ tools?: ModelTool[];
612
+ /** Constrain whether an offered Tool must be selected for this generation. */
613
+ toolChoice?: "auto" | "required";
614
+ feedback?: string[];
615
+ stream?: boolean;
616
+ /** Host-adapter escape hatch for a qualified upstream SDK wire request. Credentials and the selected model remain platform-owned. */
617
+ rawProtocol?: {
618
+ protocol: RawModelProtocol;
619
+ request: Record<string, unknown>;
620
+ };
621
+ }
622
+ interface ModelCredentialHeader {
623
+ slot: string;
624
+ header: string;
625
+ scheme: "bearer" | "raw";
626
+ }
627
+ interface ModelGatewayConfig {
628
+ baseUrl: string;
629
+ protocol: ModelGatewayProtocol;
630
+ model: string;
631
+ maxOutputTokens?: number;
632
+ temperature?: number;
633
+ gatewayAuth?: ModelCredentialHeader | null;
634
+ providerAuth?: ModelCredentialHeader | null;
635
+ }
636
+ type NormalizedModelGatewayConfig = Omit<ModelGatewayConfig, "maxOutputTokens" | "temperature" | "gatewayAuth" | "providerAuth"> & {
637
+ maxOutputTokens: number;
638
+ temperature: number | null;
639
+ gatewayAuth: ModelCredentialHeader | null;
640
+ providerAuth: ModelCredentialHeader | null;
641
+ };
642
+ interface ModelInvocationResult {
643
+ content: string;
644
+ toolCalls?: {
645
+ id: string;
646
+ name: string;
647
+ args: unknown;
648
+ }[];
649
+ /** Integration-observed timing for the complete upstream model request. */
650
+ timing?: {
651
+ upstreamMs: number;
652
+ };
653
+ usage: {
654
+ input: number;
655
+ output: number;
656
+ cached: number;
657
+ cacheWrite?: number;
658
+ /** Exact upstream inference cost when the Gateway can establish it; null means unavailable. */
659
+ costUsd?: number | null;
660
+ costSource?: string;
661
+ costEstimated?: boolean;
662
+ };
663
+ provider: string;
664
+ model: string;
665
+ }
666
+ declare function normalizeModelGatewayConfig(value: unknown): NormalizedModelGatewayConfig;
667
+ declare function modelGatewayEndpoint(config: Pick<ModelGatewayConfig, "baseUrl" | "protocol">): URL;
668
+ declare function modelPrompt(args: ModelInvocationArgs): string;
669
+ declare function modelProtocolRequest(protocol: ModelGatewayProtocol, model: string, maxOutputTokens: number, temperature: number | null, args: ModelInvocationArgs): Record<string, unknown>;
670
+ declare function modelProtocolResult(protocol: ModelGatewayProtocol, raw: unknown, provider: string, model: string): ModelInvocationResult;
671
+
589
672
  interface GatewayCredentialSlotSetup {
590
673
  title: string;
591
674
  description?: string;
@@ -716,8 +799,6 @@ declare function gateway<C>(definition: GatewayDefinition<C>): GatewayPackage<C>
716
799
  * other Resource.
717
800
  */
718
801
  declare function trainingProvider<C>(definition: TrainingProviderDefinition<C>): GatewayPackage<C>;
719
- /** Stable capability implemented by every model-completion Gateway. */
720
- declare const MODEL_COMPLETION_CAPABILITY: CapabilityContractRef;
721
802
  /** Stable capability implemented by Gateways that import immutable training checkpoints. */
722
803
  declare const MODEL_CHECKPOINT_IMPORT_CAPABILITY: CapabilityContractRef;
723
804
  /** Stable capability implemented by remote MCP client Gateways. */
@@ -1199,8 +1280,8 @@ type ModelGovernanceMeter = "cached_input_tokens" | "input_tokens" | "output_tok
1199
1280
  type UiGovernanceMeter = "requests";
1200
1281
  declare function sandboxControls(values: Partial<SandboxGovernanceControls>): ResourceControlsConstraint;
1201
1282
  declare function sandboxLimit(input: AdmissionLimitInput<SandboxGovernanceMeter>): AdmissionLimitConstraint;
1202
- declare function modelControls(values: Partial<ModelGovernanceControls>): ResourceControlsConstraint;
1203
- declare function modelLimit(input: AdmissionLimitInput<ModelGovernanceMeter>): AdmissionLimitConstraint;
1283
+ declare function modelControls(values: Partial<ModelGovernanceControls>, contract?: GovernanceContractRef): ResourceControlsConstraint;
1284
+ declare function modelLimit(input: AdmissionLimitInput<ModelGovernanceMeter>, contract?: GovernanceContractRef): AdmissionLimitConstraint;
1204
1285
  declare function uiLimit(input: AdmissionLimitInput<UiGovernanceMeter>): AdmissionLimitConstraint;
1205
1286
 
1206
1287
  type PrincipalKind = "user" | "service" | "channel" | "agent" | "anonymous";
@@ -1790,7 +1871,7 @@ interface TurnGate {
1790
1871
  feedback?(rec: TurnRecord | TurnDraft): string;
1791
1872
  onExhausted?: "fail" | "commit-with-verdict";
1792
1873
  }
1793
- interface TurnSpec {
1874
+ interface TurnSpec extends ModelGenerationOptions {
1794
1875
  system: string;
1795
1876
  objective?: unknown;
1796
1877
  context?: unknown;
@@ -1798,10 +1879,11 @@ interface TurnSpec {
1798
1879
  /** Require one of the offered Tools for this model generation. */
1799
1880
  toolChoice?: "auto" | "required";
1800
1881
  gate?: TurnGate;
1882
+ /** Model binding name; when gateway is supplied, the Gateway's model identifier instead. */
1801
1883
  model?: string;
1884
+ /** Bound Gateway to use with the explicitly selected model identifier. */
1885
+ gateway?: string;
1802
1886
  stream?: boolean;
1803
- /** Requested output ceiling for this turn. The bound Model and Policy may lower it. */
1804
- maxOutputTokens?: number;
1805
1887
  }
1806
1888
  interface ToolCallRecord {
1807
1889
  id: string;
@@ -2097,8 +2179,9 @@ declare function validateTool(tool: Tool, path?: string): Tool;
2097
2179
  declare function validateView<V extends ViewDef<any, any>>(view: V, path?: string): V;
2098
2180
  declare function validatePartitionFn<I, O, R>(fn: PartitionFn<I, O, R>): PartitionFn<I, O, R>;
2099
2181
  declare function validateFoldFn<I, O>(fn: FoldFn<I, O> | SqlFold): FoldFn<I, O> | SqlFold;
2100
- declare function agent<S>(input: Omit<AgentDef<S>, "version"> & {
2182
+ declare function agent<S>(input: Omit<AgentDef<S>, "version" | "model"> & {
2101
2183
  version?: string;
2184
+ model?: string;
2102
2185
  }): AgentDef<S>;
2103
2186
  declare function subtask<T>(def: Task<T>): Task<T>;
2104
2187
 
@@ -3600,83 +3683,6 @@ declare function credentialProviderSetupMetadata(value: unknown, slots: string[]
3600
3683
  /** Defines and validates a Credential Provider package. */
3601
3684
  declare function credentialProvider<C>(definition: CredentialProviderDefinition<C>): CredentialProviderPackage<C>;
3602
3685
 
3603
- type ModelGatewayProtocol = "anthropic" | "openai";
3604
- type RawModelProtocol = ModelGatewayProtocol | "bedrock";
3605
- interface ModelTool {
3606
- name: string;
3607
- version?: string;
3608
- description: string;
3609
- schema: object;
3610
- }
3611
- interface ModelInvocationArgs {
3612
- /** Admission-pinned logical model. Runtime code cannot override this value. */
3613
- model?: string;
3614
- system?: string;
3615
- objective?: unknown;
3616
- context?: unknown;
3617
- tools?: ModelTool[];
3618
- /** Constrain whether an offered Tool must be selected for this generation. */
3619
- toolChoice?: "auto" | "required";
3620
- feedback?: string[];
3621
- maxOutputTokens?: number;
3622
- temperature?: number;
3623
- stream?: boolean;
3624
- /** Host-adapter escape hatch for a qualified upstream SDK wire request. Credentials and the selected model remain platform-owned. */
3625
- rawProtocol?: {
3626
- protocol: RawModelProtocol;
3627
- request: Record<string, unknown>;
3628
- };
3629
- }
3630
- interface ModelCredentialHeader {
3631
- slot: string;
3632
- header: string;
3633
- scheme: "bearer" | "raw";
3634
- }
3635
- interface ModelGatewayConfig {
3636
- baseUrl: string;
3637
- protocol: ModelGatewayProtocol;
3638
- model: string;
3639
- maxOutputTokens?: number;
3640
- temperature?: number;
3641
- gatewayAuth?: ModelCredentialHeader | null;
3642
- providerAuth?: ModelCredentialHeader | null;
3643
- }
3644
- type NormalizedModelGatewayConfig = Omit<ModelGatewayConfig, "maxOutputTokens" | "temperature" | "gatewayAuth" | "providerAuth"> & {
3645
- maxOutputTokens: number;
3646
- temperature: number | null;
3647
- gatewayAuth: ModelCredentialHeader | null;
3648
- providerAuth: ModelCredentialHeader | null;
3649
- };
3650
- interface ModelInvocationResult {
3651
- content: string;
3652
- toolCalls?: {
3653
- id: string;
3654
- name: string;
3655
- args: unknown;
3656
- }[];
3657
- /** Integration-observed timing for the complete upstream model request. */
3658
- timing?: {
3659
- upstreamMs: number;
3660
- };
3661
- usage: {
3662
- input: number;
3663
- output: number;
3664
- cached: number;
3665
- cacheWrite?: number;
3666
- /** Exact upstream inference cost when the Gateway can establish it; null means unavailable. */
3667
- costUsd?: number | null;
3668
- costSource?: string;
3669
- costEstimated?: boolean;
3670
- };
3671
- provider: string;
3672
- model: string;
3673
- }
3674
- declare function normalizeModelGatewayConfig(value: unknown): NormalizedModelGatewayConfig;
3675
- declare function modelGatewayEndpoint(config: Pick<ModelGatewayConfig, "baseUrl" | "protocol">): URL;
3676
- declare function modelPrompt(args: ModelInvocationArgs): string;
3677
- declare function modelProtocolRequest(protocol: ModelGatewayProtocol, model: string, maxOutputTokens: number, temperature: number | null, args: ModelInvocationArgs): Record<string, unknown>;
3678
- declare function modelProtocolResult(protocol: ModelGatewayProtocol, raw: unknown, provider: string, model: string): ModelInvocationResult;
3679
-
3680
3686
  type CodeScorerRule = {
3681
3687
  op: "all";
3682
3688
  rules: CodeScorerRule[];
package/publish/index.js CHANGED
@@ -931,7 +931,11 @@ function validateFoldFn(fn) {
931
931
  return fn;
932
932
  }
933
933
  function agent(input) {
934
- const def = { ...input, version: input.version === void 0 ? "current" : input.version };
934
+ const def = {
935
+ ...input,
936
+ version: input.version === void 0 ? "current" : input.version,
937
+ model: input.model === void 0 ? "model" : input.model
938
+ };
935
939
  validateExecutable(def, "agent");
936
940
  requiredString(def.model, "agent.model");
937
941
  const mode = def.mode ?? "script";
@@ -1722,11 +1726,11 @@ function sandboxControls(values) {
1722
1726
  function sandboxLimit(input) {
1723
1727
  return limit(SANDBOX_CONTRACT, ["commands", "compute_ms", "file_bytes", "requests"], input);
1724
1728
  }
1725
- function modelControls(values) {
1726
- return controls(MODEL_CONTRACT, values, modelSchema);
1729
+ function modelControls(values, contract = MODEL_CONTRACT) {
1730
+ return controls(contract, values, modelSchema);
1727
1731
  }
1728
- function modelLimit(input) {
1729
- return limit(MODEL_CONTRACT, ["cached_input_tokens", "input_tokens", "output_tokens", "requests"], input);
1732
+ function modelLimit(input, contract = MODEL_CONTRACT) {
1733
+ return limit(contract, ["cached_input_tokens", "input_tokens", "output_tokens", "requests"], input);
1730
1734
  }
1731
1735
  function uiLimit(input) {
1732
1736
  return limit(UI_CONTRACT, ["requests"], input);
@@ -2378,6 +2382,190 @@ Response:
2378
2382
  `, completion: expected === void 0 || expected === null ? null : text2(expected) };
2379
2383
  }
2380
2384
 
2385
+ // src/model.ts
2386
+ var MODEL_COMPLETION_CAPABILITY = {
2387
+ id: "constal.model-completion",
2388
+ version: "1",
2389
+ hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
2390
+ };
2391
+ function modelGenerationOptions(source) {
2392
+ const { maxOutputTokens, temperature, effort } = source;
2393
+ if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 1048576)) {
2394
+ throw new TypeError("maxOutputTokens must be an integer from 1 to 1048576");
2395
+ }
2396
+ if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2397
+ throw new TypeError("temperature must be a finite number from 0 to 2");
2398
+ }
2399
+ if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2400
+ throw new TypeError("effort must be a nonempty model-supported string");
2401
+ }
2402
+ return {
2403
+ ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2404
+ ...temperature === void 0 ? {} : { temperature },
2405
+ ...effort === void 0 ? {} : { effort }
2406
+ };
2407
+ }
2408
+ var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2409
+ var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2410
+ var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2411
+ function record7(value) {
2412
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2413
+ }
2414
+ function credentialHeader(value, name) {
2415
+ if (value === null || value === void 0) return null;
2416
+ const source = record7(value);
2417
+ if (!source || typeof source.slot !== "string" || !NAME4.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`);
2418
+ return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2419
+ }
2420
+ function normalizeModelGatewayConfig(value) {
2421
+ const source = record7(value);
2422
+ if (!source || typeof source.baseUrl !== "string" || source.baseUrl.length > 2048 || source.protocol !== "anthropic" && source.protocol !== "openai" || typeof source.model !== "string" || source.model.length === 0 || source.model.length > 256) {
2423
+ throw new TypeError("model gateway config is invalid");
2424
+ }
2425
+ const maxOutputTokens = source.maxOutputTokens === void 0 ? 256 : Number(source.maxOutputTokens);
2426
+ const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2427
+ if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 8192 || temperature !== null && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2428
+ throw new TypeError("model gateway generation limits are invalid");
2429
+ }
2430
+ const normalized = {
2431
+ baseUrl: source.baseUrl,
2432
+ protocol: source.protocol,
2433
+ model: source.model,
2434
+ maxOutputTokens,
2435
+ temperature,
2436
+ gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2437
+ providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2438
+ };
2439
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2440
+ throw new TypeError("gateway and provider credentials cannot share one header");
2441
+ }
2442
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2443
+ throw new TypeError("gateway and provider credentials cannot share one slot");
2444
+ }
2445
+ modelGatewayEndpoint(normalized);
2446
+ return normalized;
2447
+ }
2448
+ function modelGatewayEndpoint(config) {
2449
+ let endpoint;
2450
+ try {
2451
+ endpoint = new URL(config.baseUrl);
2452
+ } catch {
2453
+ throw new TypeError("model gateway baseUrl is invalid");
2454
+ }
2455
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2456
+ throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
2457
+ }
2458
+ const hostname = endpoint.hostname.toLowerCase();
2459
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2460
+ throw new TypeError("model gateway baseUrl must use a public hostname");
2461
+ }
2462
+ const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2463
+ if (!suffix) throw new TypeError("model gateway protocol is invalid");
2464
+ endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2465
+ return endpoint;
2466
+ }
2467
+ function modelPrompt(args) {
2468
+ return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2469
+ }
2470
+ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2471
+ const { effort } = modelGenerationOptions(args);
2472
+ if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
2473
+ throw new TypeError("model Tool choice is invalid");
2474
+ }
2475
+ if (args.toolChoice === "required" && !args.tools?.length) {
2476
+ throw new TypeError("required model Tool choice needs at least one offered Tool");
2477
+ }
2478
+ const prompt = modelPrompt(args);
2479
+ if (protocol === "anthropic") return {
2480
+ model,
2481
+ system: args.system ?? "",
2482
+ messages: [{ role: "user", content: prompt }],
2483
+ max_tokens: maxOutputTokens,
2484
+ ...effort === void 0 ? {} : { output_config: { effort } },
2485
+ ...temperature === null ? {} : { temperature },
2486
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
2487
+ ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
2488
+ };
2489
+ if (protocol === "openai") return {
2490
+ model,
2491
+ messages: [
2492
+ ...args.system ? [{ role: "developer", content: args.system }] : [],
2493
+ { role: "user", content: prompt }
2494
+ ],
2495
+ max_completion_tokens: maxOutputTokens,
2496
+ ...effort === void 0 ? {} : { reasoning_effort: effort },
2497
+ ...temperature === null ? {} : { temperature },
2498
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({
2499
+ type: "function",
2500
+ function: { name: tool.name, description: tool.description, parameters: tool.schema }
2501
+ })) } : {},
2502
+ ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
2503
+ };
2504
+ throw new TypeError("model gateway protocol is invalid");
2505
+ }
2506
+ function integer2(value) {
2507
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
2508
+ }
2509
+ function costMetadata(usage) {
2510
+ const cost = usage.cost;
2511
+ const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
2512
+ return {
2513
+ ...costUsd !== void 0 ? { costUsd } : {},
2514
+ ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
2515
+ ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
2516
+ };
2517
+ }
2518
+ function modelProtocolResult(protocol, raw, provider, model) {
2519
+ const source = record7(raw) ?? {};
2520
+ const toolCalls = [];
2521
+ let content2 = "";
2522
+ let usage;
2523
+ if (protocol === "anthropic") {
2524
+ const blocks = Array.isArray(source.content) ? source.content : [];
2525
+ content2 = blocks.map((candidate) => {
2526
+ const block = record7(candidate);
2527
+ if (block?.type === "text" && typeof block.text === "string") return block.text;
2528
+ if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
2529
+ toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
2530
+ }
2531
+ return "";
2532
+ }).join("");
2533
+ const values = record7(source.usage) ?? {};
2534
+ const cached = integer2(values.cache_read_input_tokens);
2535
+ usage = {
2536
+ input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
2537
+ output: integer2(values.output_tokens),
2538
+ cached,
2539
+ ...costMetadata(values)
2540
+ };
2541
+ } else if (protocol === "openai") {
2542
+ const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2543
+ const message = record7(choice.message) ?? {};
2544
+ content2 = typeof message.content === "string" ? message.content : "";
2545
+ for (const candidate of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
2546
+ const call = record7(candidate);
2547
+ const fn = record7(call?.function);
2548
+ if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
2549
+ let args;
2550
+ try {
2551
+ args = JSON.parse(fn.arguments);
2552
+ } catch {
2553
+ throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
2554
+ }
2555
+ toolCalls.push({ id: call.id, name: fn.name, args });
2556
+ }
2557
+ const values = record7(source.usage) ?? {};
2558
+ usage = {
2559
+ input: integer2(values.prompt_tokens),
2560
+ output: integer2(values.completion_tokens),
2561
+ cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
2562
+ ...costMetadata(values)
2563
+ };
2564
+ } else throw new TypeError("model gateway protocol is invalid");
2565
+ if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
2566
+ return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model };
2567
+ }
2568
+
2381
2569
  // src/gateway.ts
2382
2570
  async function checkpointArtifactRef(value) {
2383
2571
  return await sha256Hex(canonicalJson(value));
@@ -2655,11 +2843,6 @@ function trainingProvider(definition) {
2655
2843
  }
2656
2844
  });
2657
2845
  }
2658
- var MODEL_COMPLETION_CAPABILITY = {
2659
- id: "constal.model-completion",
2660
- version: "1",
2661
- hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
2662
- };
2663
2846
  var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
2664
2847
  id: "constal.model-checkpoint-import",
2665
2848
  version: "1",
@@ -2898,165 +3081,6 @@ function credentialProvider(definition) {
2898
3081
  return Object.freeze({ ...definition, mintRecovery, metadata: metadata2 });
2899
3082
  }
2900
3083
 
2901
- // src/model.ts
2902
- var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2903
- var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2904
- var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2905
- function record7(value) {
2906
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2907
- }
2908
- function credentialHeader(value, name) {
2909
- if (value === null || value === void 0) return null;
2910
- const source = record7(value);
2911
- if (!source || typeof source.slot !== "string" || !NAME4.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`);
2912
- return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2913
- }
2914
- function normalizeModelGatewayConfig(value) {
2915
- const source = record7(value);
2916
- if (!source || typeof source.baseUrl !== "string" || source.baseUrl.length > 2048 || source.protocol !== "anthropic" && source.protocol !== "openai" || typeof source.model !== "string" || source.model.length === 0 || source.model.length > 256) {
2917
- throw new TypeError("model gateway config is invalid");
2918
- }
2919
- const maxOutputTokens = source.maxOutputTokens === void 0 ? 256 : Number(source.maxOutputTokens);
2920
- const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2921
- if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 8192 || temperature !== null && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2922
- throw new TypeError("model gateway generation limits are invalid");
2923
- }
2924
- const normalized = {
2925
- baseUrl: source.baseUrl,
2926
- protocol: source.protocol,
2927
- model: source.model,
2928
- maxOutputTokens,
2929
- temperature,
2930
- gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2931
- providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2932
- };
2933
- if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2934
- throw new TypeError("gateway and provider credentials cannot share one header");
2935
- }
2936
- if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2937
- throw new TypeError("gateway and provider credentials cannot share one slot");
2938
- }
2939
- modelGatewayEndpoint(normalized);
2940
- return normalized;
2941
- }
2942
- function modelGatewayEndpoint(config) {
2943
- let endpoint;
2944
- try {
2945
- endpoint = new URL(config.baseUrl);
2946
- } catch {
2947
- throw new TypeError("model gateway baseUrl is invalid");
2948
- }
2949
- if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2950
- throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
2951
- }
2952
- const hostname = endpoint.hostname.toLowerCase();
2953
- if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2954
- throw new TypeError("model gateway baseUrl must use a public hostname");
2955
- }
2956
- const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2957
- if (!suffix) throw new TypeError("model gateway protocol is invalid");
2958
- endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2959
- return endpoint;
2960
- }
2961
- function modelPrompt(args) {
2962
- return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2963
- }
2964
- function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2965
- if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
2966
- throw new TypeError("model Tool choice is invalid");
2967
- }
2968
- if (args.toolChoice === "required" && !args.tools?.length) {
2969
- throw new TypeError("required model Tool choice needs at least one offered Tool");
2970
- }
2971
- const prompt = modelPrompt(args);
2972
- if (protocol === "anthropic") return {
2973
- model,
2974
- system: args.system ?? "",
2975
- messages: [{ role: "user", content: prompt }],
2976
- max_tokens: maxOutputTokens,
2977
- ...temperature === null ? {} : { temperature },
2978
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
2979
- ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
2980
- };
2981
- if (protocol === "openai") return {
2982
- model,
2983
- messages: [
2984
- ...args.system ? [{ role: "developer", content: args.system }] : [],
2985
- { role: "user", content: prompt }
2986
- ],
2987
- max_completion_tokens: maxOutputTokens,
2988
- ...temperature === null ? {} : { temperature },
2989
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({
2990
- type: "function",
2991
- function: { name: tool.name, description: tool.description, parameters: tool.schema }
2992
- })) } : {},
2993
- ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
2994
- };
2995
- throw new TypeError("model gateway protocol is invalid");
2996
- }
2997
- function integer2(value) {
2998
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
2999
- }
3000
- function costMetadata(usage) {
3001
- const cost = usage.cost;
3002
- const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
3003
- return {
3004
- ...costUsd !== void 0 ? { costUsd } : {},
3005
- ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
3006
- ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
3007
- };
3008
- }
3009
- function modelProtocolResult(protocol, raw, provider, model) {
3010
- const source = record7(raw) ?? {};
3011
- const toolCalls = [];
3012
- let content2 = "";
3013
- let usage;
3014
- if (protocol === "anthropic") {
3015
- const blocks = Array.isArray(source.content) ? source.content : [];
3016
- content2 = blocks.map((candidate) => {
3017
- const block = record7(candidate);
3018
- if (block?.type === "text" && typeof block.text === "string") return block.text;
3019
- if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
3020
- toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
3021
- }
3022
- return "";
3023
- }).join("");
3024
- const values = record7(source.usage) ?? {};
3025
- const cached = integer2(values.cache_read_input_tokens);
3026
- usage = {
3027
- input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
3028
- output: integer2(values.output_tokens),
3029
- cached,
3030
- ...costMetadata(values)
3031
- };
3032
- } else if (protocol === "openai") {
3033
- const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
3034
- const message = record7(choice.message) ?? {};
3035
- content2 = typeof message.content === "string" ? message.content : "";
3036
- for (const candidate of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
3037
- const call = record7(candidate);
3038
- const fn = record7(call?.function);
3039
- if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
3040
- let args;
3041
- try {
3042
- args = JSON.parse(fn.arguments);
3043
- } catch {
3044
- throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
3045
- }
3046
- toolCalls.push({ id: call.id, name: fn.name, args });
3047
- }
3048
- const values = record7(source.usage) ?? {};
3049
- usage = {
3050
- input: integer2(values.prompt_tokens),
3051
- output: integer2(values.completion_tokens),
3052
- cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
3053
- ...costMetadata(values)
3054
- };
3055
- } else throw new TypeError("model gateway protocol is invalid");
3056
- if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
3057
- return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model };
3058
- }
3059
-
3060
3084
  // src/scorer.ts
3061
3085
  function validPointer(value) {
3062
3086
  return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));