@constal/sdk 3.0.0 → 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Constal SDK
2
+ Copyright 2026 Coresource AI, Inc.
3
+
4
+ This product includes software developed by Coresource AI, Inc.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@constal/sdk",
3
- "version": "3.0.0",
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",
@@ -9,7 +9,7 @@
9
9
  "typescript",
10
10
  "sdk"
11
11
  ],
12
- "license": "UNLICENSED",
12
+ "license": "Apache-2.0",
13
13
  "homepage": "https://constal.ai",
14
14
  "type": "module",
15
15
  "sideEffects": false,
@@ -22,7 +22,9 @@
22
22
  }
23
23
  },
24
24
  "files": [
25
- "publish"
25
+ "publish",
26
+ "LICENSE",
27
+ "NOTICE"
26
28
  ],
27
29
  "publishConfig": {
28
30
  "access": "public"
@@ -37,5 +39,6 @@
37
39
  "esbuild": "^0.28.2",
38
40
  "rollup": "^4.62.4",
39
41
  "rollup-plugin-dts": "^6.2.3"
40
- }
42
+ },
43
+ "author": "Coresource AI, Inc."
41
44
  }
package/publish/api.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "package": "@constal/sdk",
3
- "version": "3.0.0",
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));