@constal/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2625 @@
1
+ // src/hash.ts
2
+ var encoder = new TextEncoder();
3
+ function canonicalNumber(value) {
4
+ if (!Number.isFinite(value)) throw new TypeError("canonical JSON does not support non-finite numbers");
5
+ if (Object.is(value, -0)) return "0";
6
+ return JSON.stringify(value);
7
+ }
8
+ function canonicalJson(value) {
9
+ if (value === null) return "null";
10
+ if (typeof value === "boolean") return value ? "true" : "false";
11
+ if (typeof value === "number") return canonicalNumber(value);
12
+ if (typeof value === "string") return JSON.stringify(value);
13
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
14
+ if (typeof value === "object") {
15
+ const record8 = value;
16
+ return `{${Object.keys(record8).sort().filter((key) => record8[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(record8[key])}`).join(",")}}`;
17
+ }
18
+ throw new TypeError(`canonical JSON does not support ${typeof value}`);
19
+ }
20
+ async function sha256Hex(bytes) {
21
+ const input = typeof bytes === "string" ? encoder.encode(bytes) : bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
22
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(input).buffer);
23
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
24
+ }
25
+ async function hash(domain, ...values) {
26
+ return sha256Hex(canonicalJson([domain, ...values]));
27
+ }
28
+ async function hashValue(value) {
29
+ return hash("constal/value/v2", value);
30
+ }
31
+ function murmur3_32(value, seed = 0) {
32
+ const bytes = encoder.encode(value);
33
+ let state = seed >>> 0;
34
+ const blockEnd = bytes.length - bytes.length % 4;
35
+ for (let offset = 0; offset < blockEnd; offset += 4) {
36
+ let block = (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
37
+ block = Math.imul(block, 3432918353);
38
+ block = (block << 15 | block >>> 17) >>> 0;
39
+ block = Math.imul(block, 461845907);
40
+ state ^= block;
41
+ state = (state << 13 | state >>> 19) >>> 0;
42
+ state = Math.imul(state, 5) + 3864292196 >>> 0;
43
+ }
44
+ let tail = 0;
45
+ switch (bytes.length & 3) {
46
+ case 3:
47
+ tail ^= bytes[blockEnd + 2] << 16;
48
+ case 2:
49
+ tail ^= bytes[blockEnd + 1] << 8;
50
+ case 1:
51
+ tail ^= bytes[blockEnd];
52
+ tail = Math.imul(tail, 3432918353);
53
+ tail = (tail << 15 | tail >>> 17) >>> 0;
54
+ tail = Math.imul(tail, 461845907);
55
+ state ^= tail;
56
+ }
57
+ state ^= bytes.length;
58
+ state ^= state >>> 16;
59
+ state = Math.imul(state, 2246822507);
60
+ state ^= state >>> 13;
61
+ state = Math.imul(state, 3266489909);
62
+ state ^= state >>> 16;
63
+ return state >>> 0;
64
+ }
65
+ function bucketFor(value, buckets) {
66
+ if (!Number.isSafeInteger(buckets) || buckets < 1 || buckets > 1024) throw new RangeError("bucket count must be an integer from 1 to 1024");
67
+ return murmur3_32(canonicalJson(value)) % buckets;
68
+ }
69
+
70
+ // src/partition.ts
71
+ var encoder2 = new TextEncoder();
72
+ function positiveSafeInteger(value) {
73
+ return Number.isSafeInteger(value) && Number(value) > 0;
74
+ }
75
+ function validatePartitionSpec(spec) {
76
+ if (!spec || typeof spec !== "object") throw new TypeError("partition spec must be an object");
77
+ if ("rows" in spec) {
78
+ if (!positiveSafeInteger(spec.rows)) throw new TypeError("partition.rows must be a positive safe integer");
79
+ return;
80
+ }
81
+ if ("bytes" in spec) {
82
+ if (!positiveSafeInteger(spec.bytes)) throw new TypeError("partition.bytes must be a positive safe integer");
83
+ return;
84
+ }
85
+ if ("tokens" in spec) {
86
+ if (!positiveSafeInteger(spec.tokens) || typeof spec.of !== "string" || spec.of.length === 0) {
87
+ throw new TypeError("partition.tokens must be positive and partition.of must be a non-empty field");
88
+ }
89
+ return;
90
+ }
91
+ if ("key" in spec) {
92
+ if (typeof spec.key !== "string" || spec.key.length === 0 || !positiveSafeInteger(spec.buckets) || spec.buckets > 1024) {
93
+ throw new TypeError("partition.key requires a non-empty field and 1..1024 buckets");
94
+ }
95
+ return;
96
+ }
97
+ throw new TypeError("unsupported partition spec");
98
+ }
99
+ function validateBatchSpec(spec) {
100
+ validatePartitionSpec(spec);
101
+ if (!("rows" in spec) && !("tokens" in spec)) throw new TypeError("batch spec must use rows or tokens");
102
+ }
103
+ function field(row, name, purpose) {
104
+ if (!row || typeof row !== "object" || Array.isArray(row) || !Object.hasOwn(row, name)) {
105
+ throw new TypeError(`${purpose} row is missing field ${name}`);
106
+ }
107
+ return row[name];
108
+ }
109
+ function approximateTokens(value) {
110
+ const text = typeof value === "string" ? value : canonicalJson(value);
111
+ return Math.max(1, Math.ceil(encoder2.encode(text).byteLength / 4));
112
+ }
113
+ function cutByWeight(rows, limit2, weight, framing) {
114
+ const partitions = [];
115
+ let current = [];
116
+ let used = framing ? 2 : 0;
117
+ for (const row of rows) {
118
+ const rowWeight = weight(row);
119
+ const added = rowWeight + (framing && current.length > 0 ? 1 : 0);
120
+ if (current.length > 0 && used + added > limit2) {
121
+ partitions.push(current);
122
+ current = [];
123
+ used = framing ? 2 : 0;
124
+ }
125
+ used += rowWeight + (framing && current.length > 0 ? 1 : 0);
126
+ current.push(row);
127
+ }
128
+ if (current.length > 0) partitions.push(current);
129
+ return partitions;
130
+ }
131
+ function cutPartitions(rows, spec) {
132
+ validatePartitionSpec(spec);
133
+ if (rows.length === 0) return [];
134
+ if ("rows" in spec) {
135
+ return Array.from({ length: Math.ceil(rows.length / spec.rows) }, (_, index) => rows.slice(index * spec.rows, (index + 1) * spec.rows));
136
+ }
137
+ if ("bytes" in spec) {
138
+ return cutByWeight(rows, spec.bytes, (row) => encoder2.encode(canonicalJson(row)).byteLength, true);
139
+ }
140
+ if ("tokens" in spec) {
141
+ return cutByWeight(rows, spec.tokens, (row) => approximateTokens(field(row, spec.of, "token partition")), false);
142
+ }
143
+ const partitions = Array.from({ length: spec.buckets }, () => []);
144
+ for (const row of rows) partitions[bucketFor(field(row, spec.key, "key partition"), spec.buckets)].push(row);
145
+ return partitions;
146
+ }
147
+ function cutBatches(rows, spec) {
148
+ validateBatchSpec(spec);
149
+ return cutPartitions(rows, spec);
150
+ }
151
+
152
+ // src/analytics.ts
153
+ var EVENT_ID = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/u;
154
+ var FIELD_ID = /^[a-z][a-z0-9_]{0,63}$/u;
155
+ var VERSION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
156
+ var RESERVED = /* @__PURE__ */ new Set(["system", "platform", "constal", "billing", "security", "audit"]);
157
+ function analyticsEvent(definition) {
158
+ if (typeof definition.id !== "string" || definition.id.length > 128 || !EVENT_ID.test(definition.id)) throw new TypeError("analytics event id is invalid");
159
+ if (RESERVED.has(definition.id.split(/[.-]/u)[0])) throw new TypeError("analytics event id uses a reserved namespace");
160
+ if (typeof definition.version !== "string" || !VERSION.test(definition.version)) throw new TypeError("analytics event version is invalid");
161
+ for (const [kind, fields] of [["dimensions", definition.dimensions], ["metrics", definition.metrics]]) {
162
+ if (!Array.isArray(fields) || fields.length > 16 || fields.some((field2) => typeof field2 !== "string" || !FIELD_ID.test(field2))) throw new TypeError(`analytics event ${kind} are invalid`);
163
+ if (new Set(fields).size !== fields.length) throw new TypeError(`analytics event ${kind} must be unique`);
164
+ }
165
+ const metricNames = new Set(definition.metrics);
166
+ if (definition.dimensions.some((field2) => metricNames.has(field2))) throw new TypeError("analytics dimension and metric names must not overlap");
167
+ return Object.freeze({ ...definition, dimensions: Object.freeze([...definition.dimensions]), metrics: Object.freeze([...definition.metrics]) });
168
+ }
169
+
170
+ // src/schema.ts
171
+ var KEYWORDS = /* @__PURE__ */ new Set([
172
+ "$schema",
173
+ "$id",
174
+ "$comment",
175
+ "title",
176
+ "description",
177
+ "default",
178
+ "examples",
179
+ "readOnly",
180
+ "writeOnly",
181
+ "format",
182
+ "type",
183
+ "enum",
184
+ "const",
185
+ "minLength",
186
+ "maxLength",
187
+ "pattern",
188
+ "minimum",
189
+ "maximum",
190
+ "exclusiveMinimum",
191
+ "exclusiveMaximum",
192
+ "multipleOf",
193
+ "properties",
194
+ "required",
195
+ "additionalProperties",
196
+ "minProperties",
197
+ "maxProperties",
198
+ "items",
199
+ "minItems",
200
+ "maxItems",
201
+ "uniqueItems",
202
+ "anyOf"
203
+ ]);
204
+ var TYPES = /* @__PURE__ */ new Set(["null", "boolean", "object", "array", "number", "string", "integer"]);
205
+ function validateJsonSchemaDefinition(schema, path = "$schema", depth = 0) {
206
+ if (schema === true || schema === false) return null;
207
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return `${path} must be an object or boolean schema`;
208
+ if (depth > 32) return `${path} exceeds the schema depth limit`;
209
+ const rule = schema;
210
+ const unknown = Object.keys(rule).find((key) => !KEYWORDS.has(key) && !key.startsWith("x-"));
211
+ if (unknown) return `${path}.${unknown} is not supported`;
212
+ const types = typeof rule.type === "string" ? [rule.type] : Array.isArray(rule.type) ? rule.type : [];
213
+ if (rule.type !== void 0 && (types.length === 0 || types.some((type) => typeof type !== "string" || !TYPES.has(type)))) return `${path}.type is invalid`;
214
+ if (rule.enum !== void 0 && (!Array.isArray(rule.enum) || rule.enum.length === 0)) return `${path}.enum must be non-empty`;
215
+ for (const keyword of ["minLength", "maxLength", "minItems", "maxItems", "minProperties", "maxProperties"]) {
216
+ if (rule[keyword] !== void 0 && (!Number.isSafeInteger(rule[keyword]) || Number(rule[keyword]) < 0)) return `${path}.${keyword} is invalid`;
217
+ }
218
+ for (const keyword of ["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"]) {
219
+ if (rule[keyword] !== void 0 && (typeof rule[keyword] !== "number" || !Number.isFinite(rule[keyword]))) return `${path}.${keyword} is invalid`;
220
+ }
221
+ if (typeof rule.multipleOf === "number" && rule.multipleOf <= 0) return `${path}.multipleOf must be positive`;
222
+ if (rule.pattern !== void 0) {
223
+ try {
224
+ if (typeof rule.pattern !== "string") throw new Error();
225
+ new RegExp(rule.pattern, "u");
226
+ } catch {
227
+ return `${path}.pattern is invalid`;
228
+ }
229
+ }
230
+ if (rule.required !== void 0 && (!Array.isArray(rule.required) || rule.required.some((key) => typeof key !== "string") || new Set(rule.required).size !== rule.required.length)) return `${path}.required is invalid`;
231
+ if (rule.properties !== void 0 && (!rule.properties || typeof rule.properties !== "object" || Array.isArray(rule.properties))) return `${path}.properties is invalid`;
232
+ for (const [key, child] of Object.entries(rule.properties ?? {})) {
233
+ const error = validateJsonSchemaDefinition(child, `${path}.properties.${key}`, depth + 1);
234
+ if (error) return error;
235
+ }
236
+ if (rule.items !== void 0) {
237
+ const error = validateJsonSchemaDefinition(rule.items, `${path}.items`, depth + 1);
238
+ if (error) return error;
239
+ }
240
+ if (rule.anyOf !== void 0) {
241
+ if (!Array.isArray(rule.anyOf) || rule.anyOf.length === 0 || rule.anyOf.length > 32) return `${path}.anyOf is invalid`;
242
+ for (const [index, child] of rule.anyOf.entries()) {
243
+ const error = validateJsonSchemaDefinition(child, `${path}.anyOf[${index}]`, depth + 1);
244
+ if (error) return error;
245
+ }
246
+ }
247
+ if (rule.additionalProperties !== void 0 && typeof rule.additionalProperties !== "boolean") {
248
+ const error = validateJsonSchemaDefinition(rule.additionalProperties, `${path}.additionalProperties`, depth + 1);
249
+ if (error) return error;
250
+ }
251
+ if (rule.uniqueItems !== void 0 && typeof rule.uniqueItems !== "boolean") return `${path}.uniqueItems is invalid`;
252
+ return null;
253
+ }
254
+ function validateJsonSchema(value, schema, path = "$") {
255
+ if (schema === true) return null;
256
+ if (schema === false) return `${path} is rejected by the schema`;
257
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) return `${path} has an invalid schema`;
258
+ const rule = schema;
259
+ if (Array.isArray(rule.anyOf) && !rule.anyOf.some((child) => validateJsonSchema(value, child, path) === null)) {
260
+ return `${path} does not match any allowed schema`;
261
+ }
262
+ const types = typeof rule.type === "string" ? [rule.type] : Array.isArray(rule.type) ? rule.type : [];
263
+ if (types.length && !types.some((type) => type === "object" ? value !== null && typeof value === "object" && !Array.isArray(value) : type === "array" ? Array.isArray(value) : type === "null" ? value === null : type === "integer" ? typeof value === "number" && Number.isInteger(value) : typeof value === type)) return `${path} must be ${types.join(" or ")}`;
264
+ if (Array.isArray(rule.enum) && !rule.enum.some((candidate) => canonicalJson(candidate) === canonicalJson(value))) return `${path} is not allowed`;
265
+ if (Object.hasOwn(rule, "const") && canonicalJson(rule.const) !== canonicalJson(value)) return `${path} does not equal the required value`;
266
+ if (typeof value === "string") {
267
+ if (typeof rule.minLength === "number" && value.length < rule.minLength) return `${path} is too short`;
268
+ if (typeof rule.maxLength === "number" && value.length > rule.maxLength) return `${path} is too long`;
269
+ if (typeof rule.pattern === "string" && !new RegExp(rule.pattern, "u").test(value)) return `${path} does not match the required pattern`;
270
+ }
271
+ if (typeof value === "number") {
272
+ if (typeof rule.minimum === "number" && value < rule.minimum) return `${path} is below minimum`;
273
+ if (typeof rule.maximum === "number" && value > rule.maximum) return `${path} is above maximum`;
274
+ if (typeof rule.exclusiveMinimum === "number" && value <= rule.exclusiveMinimum) return `${path} is below exclusive minimum`;
275
+ if (typeof rule.exclusiveMaximum === "number" && value >= rule.exclusiveMaximum) return `${path} is above exclusive maximum`;
276
+ if (typeof rule.multipleOf === "number" && Math.abs(value / rule.multipleOf - Math.round(value / rule.multipleOf)) > Number.EPSILON * 8) return `${path} is not a multiple`;
277
+ }
278
+ if (value && typeof value === "object" && !Array.isArray(value)) {
279
+ const record8 = value;
280
+ for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in record8)) return `${path}.${key} is required`;
281
+ const properties = rule.properties && typeof rule.properties === "object" && !Array.isArray(rule.properties) ? rule.properties : {};
282
+ if (typeof rule.minProperties === "number" && Object.keys(record8).length < rule.minProperties) return `${path} has too few properties`;
283
+ if (typeof rule.maxProperties === "number" && Object.keys(record8).length > rule.maxProperties) return `${path} has too many properties`;
284
+ if (rule.additionalProperties === false) {
285
+ const extra = Object.keys(record8).find((key) => !(key in properties));
286
+ if (extra) return `${path}.${extra} is not allowed`;
287
+ }
288
+ for (const [key, child] of Object.entries(properties)) if (key in record8) {
289
+ const error = validateJsonSchema(record8[key], child, `${path}.${key}`);
290
+ if (error) return error;
291
+ }
292
+ if (rule.additionalProperties && typeof rule.additionalProperties === "object") for (const key of Object.keys(record8).filter((candidate) => !(candidate in properties))) {
293
+ const error = validateJsonSchema(record8[key], rule.additionalProperties, `${path}.${key}`);
294
+ if (error) return error;
295
+ }
296
+ }
297
+ if (Array.isArray(value)) {
298
+ if (typeof rule.minItems === "number" && value.length < rule.minItems) return `${path} has too few items`;
299
+ if (typeof rule.maxItems === "number" && value.length > rule.maxItems) return `${path} has too many items`;
300
+ if (rule.items) for (const [index, item] of value.entries()) {
301
+ const error = validateJsonSchema(item, rule.items, `${path}[${index}]`);
302
+ if (error) return error;
303
+ }
304
+ if (rule.uniqueItems === true) {
305
+ const values = value.map(canonicalJson);
306
+ if (new Set(values).size !== values.length) return `${path} must contain unique items`;
307
+ }
308
+ }
309
+ return null;
310
+ }
311
+
312
+ // src/selector.ts
313
+ var PROTECTED_RESOURCE_LABEL_PREFIX = "constal.ai/";
314
+ var MAX_LABELS = 64;
315
+ var MAX_EXPRESSIONS = 64;
316
+ var MAX_VALUES = 64;
317
+ var NAME = /^[A-Za-z0-9](?:[-_.A-Za-z0-9]{0,61}[A-Za-z0-9])?$/u;
318
+ var DNS_LABEL = /^[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?$/u;
319
+ function record(value) {
320
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
321
+ }
322
+ function labelKey(value) {
323
+ if (typeof value !== "string" || value.length > 317) return false;
324
+ const slash = value.indexOf("/");
325
+ if (slash < 0) return NAME.test(value);
326
+ if (slash === 0 || slash !== value.lastIndexOf("/")) return false;
327
+ const prefix = value.slice(0, slash);
328
+ const name = value.slice(slash + 1);
329
+ return prefix.length <= 253 && NAME.test(name) && prefix.split(".").every((part) => DNS_LABEL.test(part));
330
+ }
331
+ function labelValue(value) {
332
+ return typeof value === "string" && (value === "" || NAME.test(value));
333
+ }
334
+ function selectorValue(key, value) {
335
+ return key.startsWith(PROTECTED_RESOURCE_LABEL_PREFIX) ? typeof value === "string" && value.length > 0 && value.length <= 1024 : labelValue(value);
336
+ }
337
+ function resourceLabelMap(value, options = {}) {
338
+ const source = record(value);
339
+ if (!source || Object.keys(source).length > MAX_LABELS) throw new TypeError("Resource labels are invalid");
340
+ const entries = Object.entries(source);
341
+ for (const [key, candidate] of entries) {
342
+ if (!labelKey(key) || !(options.allowProtected ? selectorValue(key, candidate) : labelValue(candidate)) || !options.allowProtected && key.startsWith(PROTECTED_RESOURCE_LABEL_PREFIX)) throw new TypeError(`Resource label ${key || "<empty>"} is invalid`);
343
+ }
344
+ return Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right)));
345
+ }
346
+ function labelSelector(value) {
347
+ const source = record(value);
348
+ if (!source || Object.keys(source).some((key) => key !== "matchLabels" && key !== "matchExpressions")) {
349
+ throw new TypeError("Label selector is invalid");
350
+ }
351
+ const matchLabels = source.matchLabels === void 0 ? {} : resourceLabelMap(source.matchLabels, { allowProtected: true });
352
+ const rawExpressions = source.matchExpressions === void 0 ? [] : source.matchExpressions;
353
+ if (!Array.isArray(rawExpressions) || rawExpressions.length > MAX_EXPRESSIONS) throw new TypeError("Label selector expressions are invalid");
354
+ const matchExpressions = rawExpressions.map((raw, index) => {
355
+ const expression = record(raw);
356
+ const operator = expression?.operator;
357
+ const values = expression?.values;
358
+ if (!expression || !labelKey(expression.key) || !["In", "NotIn", "Exists", "DoesNotExist"].includes(String(operator)) || Object.keys(expression).some((key) => !["key", "operator", "values"].includes(key))) {
359
+ throw new TypeError(`Label selector expression ${index} is invalid`);
360
+ }
361
+ if (operator === "In" || operator === "NotIn") {
362
+ if (!Array.isArray(values) || values.length === 0 || values.length > MAX_VALUES || values.some((item) => !selectorValue(expression.key, item))) {
363
+ throw new TypeError(`Label selector expression ${index} values are invalid`);
364
+ }
365
+ return { key: expression.key, operator, values: [...new Set(values)].sort() };
366
+ }
367
+ if (values !== void 0) throw new TypeError(`Label selector expression ${index} must not define values`);
368
+ return { key: expression.key, operator };
369
+ }).sort((left, right) => left.key.localeCompare(right.key) || left.operator.localeCompare(right.operator) || JSON.stringify(left.values ?? []).localeCompare(JSON.stringify(right.values ?? [])));
370
+ const identities = matchExpressions.map((item) => JSON.stringify(item));
371
+ if (new Set(identities).size !== identities.length) throw new TypeError("Label selector contains duplicate expressions");
372
+ return { matchLabels, matchExpressions };
373
+ }
374
+ function resourceSelector(value, allowedKinds) {
375
+ const source = record(value);
376
+ if (!source || typeof source.resourceKind !== "string" || !allowedKinds.includes(source.resourceKind) || Object.keys(source).some((key) => key !== "resourceKind" && key !== "selector")) throw new TypeError("Resource selector is invalid");
377
+ return { resourceKind: source.resourceKind, selector: labelSelector(source.selector) };
378
+ }
379
+ function matchesLabelSelector(selector, labels) {
380
+ const normalized = labelSelector(selector);
381
+ for (const [key, expected] of Object.entries(normalized.matchLabels ?? {})) if (labels[key] !== expected) return false;
382
+ for (const requirement of normalized.matchExpressions ?? []) {
383
+ const present = Object.hasOwn(labels, requirement.key);
384
+ if (requirement.operator === "Exists" && !present || requirement.operator === "DoesNotExist" && present) return false;
385
+ if (requirement.operator === "In" && (!present || !requirement.values.includes(labels[requirement.key]))) return false;
386
+ if (requirement.operator === "NotIn" && (!present || requirement.values.includes(labels[requirement.key]))) return false;
387
+ }
388
+ return true;
389
+ }
390
+
391
+ // src/resources.ts
392
+ var RESOURCE_KINDS = [
393
+ "agent",
394
+ "channel",
395
+ "auth-provider",
396
+ "policy",
397
+ "credential-provider",
398
+ "credential",
399
+ "tool",
400
+ "scorer",
401
+ "dataset",
402
+ "model",
403
+ "memory",
404
+ "cas",
405
+ "web",
406
+ "service",
407
+ "mcp",
408
+ "db",
409
+ "browser",
410
+ "sandbox-pool",
411
+ "vault"
412
+ ];
413
+ var PLATFORM_ADDRESS_KINDS = [
414
+ "analytics",
415
+ "role",
416
+ "principal",
417
+ "customer",
418
+ "binding",
419
+ "session",
420
+ "run",
421
+ "ledger",
422
+ "table",
423
+ "artifact",
424
+ "deployment"
425
+ ];
426
+ var INVOKABLE_KINDS = ["model", "memory", "cas", "web", "service", "mcp", "db", "browser", "sandbox-pool", "vault"];
427
+ var POLICY_TARGET_KINDS = [...RESOURCE_KINDS, ...PLATFORM_ADDRESS_KINDS];
428
+ var SEGMENT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
429
+ var PATH = /^[A-Za-z0-9._~/%-]{1,512}$/u;
430
+ var NAME2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
431
+ var OPERATION = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
432
+ var VERSION2 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
433
+ var HASH = /^[a-f0-9]{64}$/u;
434
+ var KINDS = /* @__PURE__ */ new Set([...RESOURCE_KINDS, ...PLATFORM_ADDRESS_KINDS]);
435
+ var RESOURCE_KIND_SET = new Set(RESOURCE_KINDS);
436
+ var INVOKABLE_KIND_SET = new Set(INVOKABLE_KINDS);
437
+ function record2(value) {
438
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
439
+ }
440
+ function scopedBindingKey(value) {
441
+ if (typeof value !== "string" || !NAME2.test(value)) throw new TypeError("scoped binding key is invalid");
442
+ return value;
443
+ }
444
+ function resourceContractRef(value) {
445
+ const candidate = record2(value);
446
+ if (!candidate || typeof candidate.id !== "string" || !NAME2.test(candidate.id) || typeof candidate.version !== "string" || !VERSION2.test(candidate.version) || typeof candidate.hash !== "string" || !HASH.test(candidate.hash)) throw new TypeError("Resource contract reference is invalid");
447
+ return candidate;
448
+ }
449
+ function capabilityContractRef(value) {
450
+ const candidate = record2(value);
451
+ if (!candidate || typeof candidate.id !== "string" || !NAME2.test(candidate.id) || typeof candidate.version !== "string" || !VERSION2.test(candidate.version) || typeof candidate.hash !== "string" || !HASH.test(candidate.hash) || Object.keys(candidate).some((key) => !["id", "version", "hash"].includes(key))) {
452
+ throw new TypeError("capability contract reference is invalid");
453
+ }
454
+ return candidate;
455
+ }
456
+ function bindingOwnerScope(value) {
457
+ if (value !== "tenant" && value !== "customer" && value !== "principal") throw new TypeError("scoped binding owner is invalid");
458
+ return value;
459
+ }
460
+ function scopedResourceRef(value) {
461
+ const candidate = record2(value);
462
+ if (!candidate || candidate.kind !== "scoped" || typeof candidate.required !== "boolean") {
463
+ throw new TypeError("scoped Resource reference is invalid");
464
+ }
465
+ scopedBindingKey(candidate.key);
466
+ bindingOwnerScope(candidate.owner);
467
+ resourceContractRef(candidate.contract);
468
+ if (Object.keys(candidate).some((key) => !["kind", "key", "owner", "required", "contract"].includes(key))) {
469
+ throw new TypeError("scoped Resource reference is invalid");
470
+ }
471
+ return candidate;
472
+ }
473
+ function modelGatewayBinding(value) {
474
+ const candidate = record2(value);
475
+ if (!candidate) throw new TypeError("Model Gateway binding is invalid");
476
+ if (candidate.kind === "fixed") {
477
+ const resource = record2(candidate.resource);
478
+ if (!resource || typeof resource.crn !== "string" || typeof resource.hash !== "string" || !HASH.test(resource.hash) || Object.keys(resource).some((key) => !["crn", "hash"].includes(key)) || Object.keys(candidate).some((key) => !["kind", "resource", "contract"].includes(key))) {
479
+ throw new TypeError("fixed Model Gateway binding is invalid");
480
+ }
481
+ const parts = parseResourceName(resource.crn);
482
+ if (!INVOKABLE_KIND_SET.has(parts.kind) || parts.kind === "model" || parts.kind === "memory") {
483
+ throw new TypeError("Model Gateway must reference a Connection Resource");
484
+ }
485
+ capabilityContractRef(candidate.contract);
486
+ return candidate;
487
+ }
488
+ if (candidate.kind === "scoped") {
489
+ if (candidate.required !== true || Object.keys(candidate).some((key) => !["kind", "key", "owner", "required", "contract"].includes(key))) {
490
+ throw new TypeError("scoped Model Gateway binding is invalid");
491
+ }
492
+ scopedBindingKey(candidate.key);
493
+ bindingOwnerScope(candidate.owner);
494
+ capabilityContractRef(candidate.contract);
495
+ return candidate;
496
+ }
497
+ throw new TypeError("Model Gateway binding is invalid");
498
+ }
499
+ function memoryStoreBinding(value) {
500
+ const candidate = record2(value);
501
+ if (!candidate) throw new TypeError("Memory Store binding is invalid");
502
+ if (candidate.kind === "fixed") {
503
+ const resource = record2(candidate.resource);
504
+ if (!resource || typeof resource.crn !== "string" || typeof resource.hash !== "string" || !HASH.test(resource.hash) || Object.keys(resource).some((key) => !["crn", "hash"].includes(key)) || Object.keys(candidate).some((key) => !["kind", "resource", "contract"].includes(key))) {
505
+ throw new TypeError("fixed Memory Store binding is invalid");
506
+ }
507
+ const parts = parseResourceName(resource.crn);
508
+ if (!INVOKABLE_KIND_SET.has(parts.kind) || parts.kind === "model" || parts.kind === "memory") {
509
+ throw new TypeError("Memory Store must reference a Connection Resource");
510
+ }
511
+ capabilityContractRef(candidate.contract);
512
+ return candidate;
513
+ }
514
+ if (candidate.kind === "scoped") {
515
+ if (candidate.required !== true || Object.keys(candidate).some((key) => !["kind", "key", "owner", "required", "contract"].includes(key))) {
516
+ throw new TypeError("scoped Memory Store binding is invalid");
517
+ }
518
+ scopedBindingKey(candidate.key);
519
+ bindingOwnerScope(candidate.owner);
520
+ capabilityContractRef(candidate.contract);
521
+ return candidate;
522
+ }
523
+ throw new TypeError("Memory Store binding is invalid");
524
+ }
525
+ function scopedCredentialRef(value) {
526
+ const candidate = record2(value);
527
+ if (!candidate || candidate.kind !== "scoped" || typeof candidate.required !== "boolean") {
528
+ throw new TypeError("scoped Credential reference is invalid");
529
+ }
530
+ scopedBindingKey(candidate.key);
531
+ bindingOwnerScope(candidate.owner);
532
+ if (Object.keys(candidate).some((key) => !["kind", "key", "owner", "required"].includes(key))) {
533
+ throw new TypeError("scoped Credential reference is invalid");
534
+ }
535
+ return candidate;
536
+ }
537
+ function agentResourceBinding(value) {
538
+ if (typeof value === "string") {
539
+ parseResourceName(value);
540
+ return value;
541
+ }
542
+ return scopedResourceRef(value);
543
+ }
544
+ function resourceCredentialBinding(value) {
545
+ if (typeof value === "string") return credentialName(value);
546
+ return scopedCredentialRef(value);
547
+ }
548
+ function validateRotationDefaults(value) {
549
+ const candidate = record2(value);
550
+ if (!candidate || !["manual", "scheduled", "auto"].includes(String(candidate.mode ?? "")) || candidate.intervalMs !== null && (!Number.isSafeInteger(candidate.intervalMs) || Number(candidate.intervalMs) < 6e4) || !Number.isSafeInteger(candidate.overlapMs) || Number(candidate.overlapMs) < 0 || candidate.maxAgeMs !== null && (!Number.isSafeInteger(candidate.maxAgeMs) || Number(candidate.maxAgeMs) < 6e4) || !Number.isSafeInteger(candidate.refreshBeforeMs) || Number(candidate.refreshBeforeMs) < 0) throw new TypeError("credential rotation policy is invalid");
551
+ if (Object.hasOwn(candidate, "producer")) throw new TypeError("credential provider rotation defaults cannot select a producer");
552
+ return candidate;
553
+ }
554
+ function credentialRotationDefaults(value) {
555
+ return validateRotationDefaults(value);
556
+ }
557
+ function validateParts(parts) {
558
+ if (!SEGMENT.test(parts.environment)) throw new TypeError("resource environment is invalid");
559
+ if (!SEGMENT.test(parts.tenant)) throw new TypeError("resource tenant is invalid");
560
+ if (!SEGMENT.test(parts.namespace)) throw new TypeError("resource namespace is invalid");
561
+ if (!KINDS.has(parts.kind)) throw new TypeError("resource kind is invalid");
562
+ if (!PATH.test(parts.path) || parts.path.startsWith("/") || parts.path.endsWith("/") || parts.path.split("/").some((part) => part === "" || part === "." || part === "..")) {
563
+ throw new TypeError("resource path is invalid");
564
+ }
565
+ }
566
+ function resourceName(parts) {
567
+ validateParts(parts);
568
+ return `crn:constal:${parts.environment}:${parts.tenant}:${parts.namespace}:${parts.kind}/${parts.path}`;
569
+ }
570
+ function parseResourceName(value) {
571
+ const match = value.match(/^crn:constal:([^:]+):([^:]+):([^:]+):([^/]+)\/(.+)$/u);
572
+ if (!match) throw new TypeError("resource name is invalid");
573
+ const parts = { environment: match[1], tenant: match[2], namespace: match[3], kind: match[4], path: match[5] };
574
+ validateParts(parts);
575
+ if (resourceName(parts) !== value) throw new TypeError("resource name is not canonical");
576
+ return parts;
577
+ }
578
+ function credentialName(value) {
579
+ if (parseResourceName(value).kind !== "credential") throw new TypeError("credential CRN is invalid");
580
+ return value;
581
+ }
582
+ function credentialProviderName(value) {
583
+ if (parseResourceName(value).kind !== "credential-provider") throw new TypeError("credential provider CRN is invalid");
584
+ return value;
585
+ }
586
+ function authProviderName(value) {
587
+ if (parseResourceName(value).kind !== "auth-provider") throw new TypeError("AuthProvider CRN is invalid");
588
+ return value;
589
+ }
590
+ function policyName(value) {
591
+ if (parseResourceName(value).kind !== "policy") throw new TypeError("Policy CRN is invalid");
592
+ return value;
593
+ }
594
+ function scorerName(value) {
595
+ if (parseResourceName(value).kind !== "scorer") throw new TypeError("Scorer CRN is invalid");
596
+ return value;
597
+ }
598
+ function datasetName(value) {
599
+ if (parseResourceName(value).kind !== "dataset") throw new TypeError("Dataset CRN is invalid");
600
+ return value;
601
+ }
602
+ function customerTenantName(value) {
603
+ const parts = parseResourceName(value);
604
+ if (parts.kind !== "customer" || parts.namespace !== "identity" || !SEGMENT.test(parts.path)) throw new TypeError("Customer tenant CRN is invalid");
605
+ return value;
606
+ }
607
+ function bindingName(value) {
608
+ if (parseResourceName(value).kind !== "binding") throw new TypeError("binding CRN is invalid");
609
+ return value;
610
+ }
611
+ function resourcePattern(value) {
612
+ if (value === "*") return value;
613
+ if (!/^crn:constal:[a-z0-9*][a-z0-9._*-]*:[a-z0-9*][a-z0-9._*-]*:[a-z0-9*][a-z0-9._*-]*:[a-z0-9*][a-z0-9._*-]*\/[A-Za-z0-9._~/%*-]+$/u.test(value)) {
614
+ throw new TypeError("resource pattern is invalid");
615
+ }
616
+ return value;
617
+ }
618
+ function wildcard(pattern, value) {
619
+ if (pattern === "*") return true;
620
+ const expression = pattern.replace(/[.+?^${}()|[\]\\]/gu, "\\$&").replaceAll("*", "[^:]*");
621
+ return new RegExp(`^${expression}$`, "u").test(value);
622
+ }
623
+ function matchesResource(pattern, value) {
624
+ return wildcard(pattern, value);
625
+ }
626
+ function action(value) {
627
+ if (!/^[a-z][a-z0-9-]{0,63}:[a-z][a-z0-9-]{0,63}$/u.test(value)) throw new TypeError("action is invalid");
628
+ return value;
629
+ }
630
+ function actionPattern(value) {
631
+ if (value !== "*" && !/^[a-z][a-z0-9-]{0,63}:(?:[a-z][a-z0-9-]{0,63}|\*)$/u.test(value)) {
632
+ throw new TypeError("action pattern is invalid");
633
+ }
634
+ return value;
635
+ }
636
+ function matchesAction(pattern, value) {
637
+ return wildcard(pattern, value);
638
+ }
639
+ function modelAdvertisedPricing(value) {
640
+ const candidate = record2(value);
641
+ if (!candidate || candidate.currency !== "USD" || candidate.unit !== "million_tokens" || typeof candidate.version !== "string" || !VERSION2.test(candidate.version) || Object.keys(candidate).some((key) => ![
642
+ "currency",
643
+ "unit",
644
+ "inputMicroUsd",
645
+ "outputMicroUsd",
646
+ "cachedInputMicroUsd",
647
+ "cacheWriteMicroUsd",
648
+ "version"
649
+ ].includes(key))) {
650
+ throw new TypeError("Model advertised pricing is invalid");
651
+ }
652
+ for (const field2 of ["inputMicroUsd", "outputMicroUsd"]) {
653
+ if (!Number.isSafeInteger(candidate[field2]) || Number(candidate[field2]) < 0) throw new TypeError("Model advertised pricing is invalid");
654
+ }
655
+ for (const field2 of ["cachedInputMicroUsd", "cacheWriteMicroUsd"]) {
656
+ if (candidate[field2] !== null && (!Number.isSafeInteger(candidate[field2]) || Number(candidate[field2]) < 0)) {
657
+ throw new TypeError("Model advertised pricing is invalid");
658
+ }
659
+ }
660
+ return candidate;
661
+ }
662
+ function resourceNeed(need) {
663
+ if (!NAME2.test(need.binding) || !RESOURCE_KIND_SET.has(need.kind) || need.ops !== void 0 && (!Array.isArray(need.ops) || need.ops.length === 0 || need.ops.length > 256 || need.ops.some((op) => !OPERATION.test(op)))) throw new TypeError("resource need is invalid");
664
+ return need;
665
+ }
666
+ function ipv4(value) {
667
+ const parts = value.split(".");
668
+ if (parts.length !== 4 || parts.some((part) => !/^(?:0|[1-9][0-9]{0,2})$/u.test(part) || Number(part) > 255)) {
669
+ throw new TypeError("sandbox network CIDR is invalid");
670
+ }
671
+ return parts.reduce((total, part) => total * 256 + Number(part) >>> 0, 0);
672
+ }
673
+ function ipv4Text(value) {
674
+ return [value >>> 24, value >>> 16 & 255, value >>> 8 & 255, value & 255].join(".");
675
+ }
676
+ var RESERVED_IPV4 = [
677
+ [ipv4("0.0.0.0"), 8],
678
+ [ipv4("10.0.0.0"), 8],
679
+ [ipv4("100.64.0.0"), 10],
680
+ [ipv4("127.0.0.0"), 8],
681
+ [ipv4("169.254.0.0"), 16],
682
+ [ipv4("172.16.0.0"), 12],
683
+ [ipv4("192.0.0.0"), 24],
684
+ [ipv4("192.168.0.0"), 16],
685
+ [ipv4("198.18.0.0"), 15],
686
+ [ipv4("224.0.0.0"), 4],
687
+ [ipv4("240.0.0.0"), 4]
688
+ ];
689
+ function normalizeCidrs(values, allowPrivate) {
690
+ if (!Array.isArray(values) || values.length === 0 || values.length > 10) throw new TypeError("sandbox network CIDRs must contain 1 to 10 entries");
691
+ const entries = values.map((raw) => {
692
+ if (typeof raw !== "string") throw new TypeError("sandbox network CIDR is invalid");
693
+ const match = raw.trim().match(/^([^/]+)\/(0|[1-9]|[12][0-9]|3[0-2])$/u);
694
+ if (!match) throw new TypeError("sandbox network CIDR is invalid");
695
+ const address = ipv4(match[1]);
696
+ const prefix = Number(match[2]);
697
+ const mask = prefix === 0 ? 0 : 4294967295 << 32 - prefix >>> 0;
698
+ const network = (address & mask) >>> 0;
699
+ if (network !== address) throw new TypeError("sandbox network CIDR must use its canonical network address");
700
+ const last = (network | ~mask) >>> 0;
701
+ if (!allowPrivate && RESERVED_IPV4.some(([reserved, bits]) => {
702
+ const reservedMask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
703
+ const reservedLast = (reserved | ~reservedMask) >>> 0;
704
+ return network <= reservedLast && last >= reserved;
705
+ })) throw new TypeError("sandbox network CIDR intersects a reserved range");
706
+ return { network, prefix, last, text: `${ipv4Text(network)}/${prefix}` };
707
+ }).sort((left, right) => left.network - right.network || left.prefix - right.prefix);
708
+ const result = [];
709
+ for (const entry of entries) {
710
+ if (result.some((prior) => entry.network >= prior.network && entry.last <= prior.last)) continue;
711
+ result.push(entry);
712
+ }
713
+ return result.map((entry) => entry.text);
714
+ }
715
+ function normalizeDomains(values) {
716
+ if (!Array.isArray(values) || values.length === 0 || values.length > 20) throw new TypeError("sandbox network domains must contain 1 to 20 entries");
717
+ const domains = values.map((raw) => {
718
+ if (typeof raw !== "string" || raw !== raw.trim() || /[:/?#@]/u.test(raw)) throw new TypeError("sandbox network domain is invalid");
719
+ const wildcard2 = raw.startsWith("*.");
720
+ const candidate = wildcard2 ? raw.slice(2) : raw;
721
+ let hostname;
722
+ try {
723
+ hostname = new URL(`https://${candidate}`).hostname.toLowerCase();
724
+ } catch {
725
+ throw new TypeError("sandbox network domain is invalid");
726
+ }
727
+ const labels = hostname.split(".");
728
+ if (!hostname || hostname.length > 253 || hostname !== new URL(`https://${hostname}`).hostname || hostname.includes(":") || labels.some((label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(label)) || hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname === "metadata.google.internal" || /^\d+(?:\.\d+){3}$/u.test(hostname)) {
729
+ throw new TypeError("sandbox network domain is invalid or reserved");
730
+ }
731
+ return `${wildcard2 ? "*." : ""}${hostname}`;
732
+ }).sort();
733
+ return [...new Set(domains)].filter((domain, index, all) => {
734
+ const bare = domain.startsWith("*.") ? domain.slice(2) : domain;
735
+ return !all.some((candidate, candidateIndex) => candidateIndex !== index && candidate.startsWith("*.") && (bare === candidate.slice(2) || bare.endsWith(`.${candidate.slice(2)}`)));
736
+ });
737
+ }
738
+ function normalizeSandboxNetworkPolicy(value, options = {}) {
739
+ if (value === void 0 || value === null) return { mode: "block-all" };
740
+ const input = record2(value);
741
+ if (!input || typeof input.mode !== "string") throw new TypeError("sandbox network policy is invalid");
742
+ if (input.mode === "block-all" || input.mode === "unrestricted") {
743
+ if (Object.keys(input).length !== 1) throw new TypeError("sandbox network policy has unexpected fields");
744
+ return { mode: input.mode };
745
+ }
746
+ if (input.mode === "cidr-allow") {
747
+ if (Object.keys(input).some((key) => key !== "mode" && key !== "cidrs")) throw new TypeError("sandbox network policy has unexpected fields");
748
+ return { mode: "cidr-allow", cidrs: normalizeCidrs(input.cidrs, options.allowPrivate === true) };
749
+ }
750
+ if (input.mode === "domain-allow") {
751
+ if (Object.keys(input).some((key) => key !== "mode" && key !== "domains")) throw new TypeError("sandbox network policy has unexpected fields");
752
+ return { mode: "domain-allow", domains: normalizeDomains(input.domains) };
753
+ }
754
+ if (input.mode === "managed-http") {
755
+ if (input.transport !== "bridge" && input.transport !== "proxy") throw new TypeError("sandbox managed HTTP transport is invalid");
756
+ if (typeof input.egress !== "string" || parseResourceName(input.egress).kind !== "service") throw new TypeError("sandbox managed HTTP egress must be a Service CRN");
757
+ if (input.transport === "bridge") {
758
+ if (Object.keys(input).some((key) => !["mode", "transport", "egress"].includes(key))) throw new TypeError("sandbox network policy has unexpected fields");
759
+ return { mode: "managed-http", transport: "bridge", egress: input.egress };
760
+ }
761
+ if (Object.keys(input).some((key) => !["mode", "transport", "egress", "domains"].includes(key))) throw new TypeError("sandbox network policy has unexpected fields");
762
+ return { mode: "managed-http", transport: "proxy", egress: input.egress, domains: normalizeDomains(input.domains) };
763
+ }
764
+ throw new TypeError("sandbox network policy mode is invalid");
765
+ }
766
+
767
+ // src/definitions.ts
768
+ function requiredString(value, path) {
769
+ if (typeof value !== "string" || value.trim() === "") throw new TypeError(`${path} must be a non-empty string`);
770
+ }
771
+ function validateExecutable(value, path) {
772
+ requiredString(value.id, `${path}.id`);
773
+ requiredString(value.version, `${path}.version`);
774
+ }
775
+ function validateTool(tool, path = "tool") {
776
+ requiredString(tool.name, `${path}.name`);
777
+ requiredString(tool.version, `${path}.version`);
778
+ if (!["read-only", "idempotent", "reconcilable", "non-idempotent"].includes(tool.maxEffect)) throw new TypeError(`${path}.maxEffect is invalid`);
779
+ tool.needs?.forEach(resourceNeed);
780
+ if (typeof tool.run !== "function") throw new TypeError(`${path}.run must be a function`);
781
+ return tool;
782
+ }
783
+ function validateView(view, path = "view") {
784
+ validateExecutable(view, path);
785
+ if (typeof view.init !== "function" || typeof view.apply !== "function") throw new TypeError(`${path} must define init and apply`);
786
+ return view;
787
+ }
788
+ function validatePartitionFn(fn) {
789
+ validateExecutable(fn, "partitionFn");
790
+ if (!(/* @__PURE__ */ new Set(["pure", "read-only", "idempotent"])).has(fn.effects)) throw new TypeError("partitionFn.effects must declare pure, read-only, or idempotent");
791
+ validateBatchSpec(fn.batch);
792
+ if (typeof fn.run !== "function") throw new TypeError("partitionFn.run must be a function");
793
+ return fn;
794
+ }
795
+ function validateFoldFn(fn) {
796
+ requiredString(fn.version, "fold.version");
797
+ if ("sql" in fn) {
798
+ requiredString(fn.sql, "fold.sql");
799
+ if (fn.deterministic !== true || fn.associative !== true) throw new TypeError("SQL folds must be deterministic and associative");
800
+ } else validateExecutable(fn, "fold");
801
+ if (fn.associative !== true && fn.associative.orderBy !== "partition") throw new TypeError("fold.associative is required");
802
+ return fn;
803
+ }
804
+ function agent(def) {
805
+ validateExecutable(def, "agent");
806
+ requiredString(def.model, "agent.model");
807
+ const mode = def.mode ?? "script";
808
+ if (mode === "script" && typeof def.onMessage !== "function") throw new TypeError("script agents require onMessage");
809
+ if (mode === "durable" && (typeof def.init !== "function" || typeof def.step !== "function" || typeof def.output !== "function")) {
810
+ throw new TypeError("durable agents require init, step, and output");
811
+ }
812
+ def.subtasks?.forEach((task, index) => validateExecutable(task, `agent.subtasks[${index}]`));
813
+ def.views?.forEach((view, index) => validateView(view, `agent.views[${index}]`));
814
+ def.partitionFns?.forEach((fn) => validatePartitionFn(fn));
815
+ def.foldFns?.forEach((fn) => validateFoldFn(fn));
816
+ def.analytics?.forEach((event) => analyticsEvent(event));
817
+ for (const [localName, tool] of Object.entries(def.tools ?? {})) {
818
+ if (localName !== tool.name) throw new TypeError(`agent.tools.${localName} must match Tool.name`);
819
+ validateTool(tool, `agent.tools.${localName}`);
820
+ }
821
+ if (new Set(Object.values(def.tools ?? {}).map((tool) => tool.name)).size !== Object.keys(def.tools ?? {}).length) {
822
+ throw new TypeError("agent Tool names must be unique");
823
+ }
824
+ if ((def.analytics?.length ?? 0) > 64 || new Set((def.analytics ?? []).map((event) => `${event.id}@${event.version}`)).size !== (def.analytics?.length ?? 0)) throw new TypeError("agent analytics definitions must be unique and contain at most 64 events");
825
+ const registered = [
826
+ ...(def.partitionFns ?? []).map((fn) => `map:${fn.id}@${fn.version}`),
827
+ ...(def.foldFns ?? []).map((fn) => `reduce:${"sql" in fn ? fn.sql : fn.id}@${fn.version}`)
828
+ ];
829
+ if (new Set(registered).size !== registered.length) throw new TypeError("agent stage function identities must be unique");
830
+ return def;
831
+ }
832
+ function subtask(def) {
833
+ validateExecutable(def, "task");
834
+ if (typeof def.run !== "function") throw new TypeError("task.run must be a function");
835
+ return def;
836
+ }
837
+
838
+ // src/auth-provider.ts
839
+ function authProvider(definition) {
840
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition.id)) throw new TypeError("authProvider.id is invalid");
841
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition.version)) throw new TypeError("authProvider.version is invalid");
842
+ if (typeof definition.authenticate !== "function") throw new TypeError("authProvider.authenticate must be a function");
843
+ definition.needs?.forEach(resourceNeed);
844
+ return definition;
845
+ }
846
+
847
+ // src/channel.ts
848
+ function required(value, path) {
849
+ if (typeof value !== "string" || value.trim() === "") throw new TypeError(`${path} must be a non-empty string`);
850
+ }
851
+ function executable(value, path) {
852
+ required(value.id, `${path}.id`);
853
+ required(value.version, `${path}.version`);
854
+ }
855
+ function channel(definition) {
856
+ executable(definition, "channel");
857
+ executable(definition.protocol, "channel.protocol");
858
+ if (typeof definition.protocol.receive !== "function" || typeof definition.protocol.respond !== "function" || definition.protocol.send !== void 0 && typeof definition.protocol.send !== "function" || definition.protocol.alarm !== void 0 && typeof definition.protocol.alarm !== "function") {
859
+ throw new TypeError("channel.protocol must define receive and respond, with optional send and alarm handlers");
860
+ }
861
+ authProviderName(definition.authProvider);
862
+ definition.needs?.forEach(resourceNeed);
863
+ const analytics = definition.analytics ?? [];
864
+ analytics.forEach((event) => analyticsEvent(event));
865
+ if (analytics.length > 64 || new Set(analytics.map((event) => `${event.id}@${event.version}`)).size !== analytics.length) throw new TypeError("channel analytics definitions must be unique and contain at most 64 events");
866
+ return definition;
867
+ }
868
+
869
+ // src/policy-governance.ts
870
+ var SANDBOX_CONTRACT = {
871
+ id: "constal.sandbox-pool",
872
+ version: "1",
873
+ hash: "566d919e8bc85fc657c691baab034524ad71e5bd01d9ff8a50d336874423362c"
874
+ };
875
+ var MODEL_CONTRACT = {
876
+ id: "constal.model",
877
+ version: "1",
878
+ hash: "76dd0da40da46adabb6837f911b25ed6f675c965e5d4d919077ee9c3945fbca7"
879
+ };
880
+ var sandboxSchema = {
881
+ type: "object",
882
+ additionalProperties: false,
883
+ properties: {
884
+ command_timeout_ms: { type: "integer", minimum: 1e3, maximum: 216e5 },
885
+ cpu: { type: "number", exclusiveMinimum: 0, maximum: 64 },
886
+ disk_gib: { type: "number", minimum: 0, maximum: 1024 },
887
+ idle_stop_ms: { type: "integer", minimum: 1e3, maximum: 864e5 },
888
+ max_concurrent_commands: { type: "integer", minimum: 1, maximum: 1024 },
889
+ max_file_bytes: { type: "integer", minimum: 1, maximum: 16777216 },
890
+ memory_gib: { type: "number", exclusiveMinimum: 0, maximum: 1024 },
891
+ network_cidrs: { type: "array", minItems: 1, maxItems: 1024, items: { type: "string" } },
892
+ network_domains: { type: "array", minItems: 1, maxItems: 1024, items: { type: "string" } },
893
+ network_egress: { type: ["string", "null"] },
894
+ network_mode: { enum: ["block-all", "cidr-allow", "domain-allow", "managed-http", "unrestricted"] },
895
+ network_transport: { enum: [null, "bridge", "proxy"] },
896
+ permitted_paths: { type: "array", minItems: 1, maxItems: 1024, items: { type: "string" } }
897
+ }
898
+ };
899
+ var modelSchema = { type: "object", additionalProperties: false, properties: {
900
+ max_input_tokens: { type: "integer", minimum: 1, maximum: 1048576 },
901
+ max_output_tokens: { type: "integer", minimum: 1, maximum: 1048576 },
902
+ temperature_max: { type: "number", minimum: 0, maximum: 2 }
903
+ } };
904
+ function controls(contract, values, schema) {
905
+ const error = validateJsonSchema(values, schema);
906
+ if (error) throw new TypeError(`governance controls are invalid: ${error}`);
907
+ return { kind: "resource-controls", contract, values };
908
+ }
909
+ function limit(contract, meters, input) {
910
+ if (!input || typeof input !== "object" || !/^[a-z][a-z0-9._-]{0,127}$/u.test(input.id) || !meters.includes(input.meter) || !["run", "session", "subject", "customer", "tenant", "binding", "resource"].includes(input.scope) || !input.window || !["concurrency", "fixed", "lifetime"].includes(input.window.kind) || input.window.kind === "fixed" && (!Number.isSafeInteger(input.window.milliseconds) || input.window.milliseconds < 1) || !Number.isFinite(input.maximum) || input.maximum < 0 || !["target", "target-version"].includes(input.continuity)) throw new TypeError("governance limit is invalid");
911
+ return { kind: "admission-limit", contract, ...input };
912
+ }
913
+ function sandboxControls(values) {
914
+ return controls(SANDBOX_CONTRACT, values, sandboxSchema);
915
+ }
916
+ function sandboxLimit(input) {
917
+ return limit(SANDBOX_CONTRACT, ["commands", "compute_ms", "file_bytes", "requests"], input);
918
+ }
919
+ function modelControls(values) {
920
+ return controls(MODEL_CONTRACT, values, modelSchema);
921
+ }
922
+ function modelLimit(input) {
923
+ return limit(MODEL_CONTRACT, ["cached_input_tokens", "input_tokens", "output_tokens", "requests"], input);
924
+ }
925
+ function validatePolicyGovernanceConstraint(value) {
926
+ if (value.kind === "resource-controls") {
927
+ if (!value.contract || typeof value.contract.id !== "string" || typeof value.contract.version !== "string" || !/^[a-f0-9]{64}$/u.test(value.contract.hash) || !value.values || typeof value.values !== "object" || Array.isArray(value.values)) {
928
+ throw new TypeError("resource controls constraint is invalid");
929
+ }
930
+ return;
931
+ }
932
+ limit(value.contract, [value.meter], value);
933
+ }
934
+
935
+ // src/authorization.ts
936
+ var MAX_CONSTRAINTS = 64;
937
+ var MAX_OUTCOME_BYTES = 65536;
938
+ var MAX_REASON_BYTES = 1024;
939
+ var DENIAL_CODE = /^[a-z][a-z0-9._-]{0,127}$/u;
940
+ var encoder3 = new TextEncoder();
941
+ function record3(value) {
942
+ return !!value && typeof value === "object" && !Array.isArray(value);
943
+ }
944
+ function requiredString2(value, path, maximum = 1024) {
945
+ if (typeof value !== "string" || value.length === 0 || encoder3.encode(value).byteLength > maximum) {
946
+ throw new TypeError(`${path} must be a bounded non-empty string`);
947
+ }
948
+ }
949
+ function exactKeys(value, allowed, required2, path) {
950
+ if (Object.keys(value).some((key) => !allowed.includes(key)) || required2.some((key) => !Object.hasOwn(value, key))) {
951
+ throw new TypeError(`${path} has invalid keys`);
952
+ }
953
+ }
954
+ function scalar(value) {
955
+ return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
956
+ }
957
+ function validateGrant(grant, path) {
958
+ if (!record3(grant) || !Array.isArray(grant.actions) || grant.actions.length === 0 || grant.actions.length > 256 || !Array.isArray(grant.resources) || grant.resources.length === 0 || grant.resources.length > 256 || !Number.isSafeInteger(grant.ttlMs) || grant.ttlMs < 1 || grant.ttlMs > 864e5) {
959
+ throw new TypeError(`${path} is invalid`);
960
+ }
961
+ exactKeys(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
962
+ grant.actions.forEach(actionPattern);
963
+ grant.resources.forEach(resourcePattern);
964
+ }
965
+ function validatePolicyConstraint(constraint, path = "constraint") {
966
+ if (!constraint || typeof constraint !== "object" || Array.isArray(constraint) || typeof constraint.kind !== "string") {
967
+ throw new TypeError(`${path} is invalid`);
968
+ }
969
+ const source = constraint;
970
+ if (constraint.kind === "resource-controls" || constraint.kind === "admission-limit") {
971
+ try {
972
+ validatePolicyGovernanceConstraint(constraint);
973
+ } catch (error) {
974
+ throw new TypeError(`${path} is invalid: ${error instanceof Error ? error.message : String(error)}`);
975
+ }
976
+ return;
977
+ }
978
+ if (constraint.kind === "arguments") {
979
+ exactKeys(source, ["kind", "schema"], ["kind", "schema"], path);
980
+ if (!record3(constraint.schema) || validateJsonSchemaDefinition(constraint.schema)) throw new TypeError(`${path}.schema is invalid`);
981
+ return;
982
+ }
983
+ if (constraint.kind === "context") {
984
+ exactKeys(source, ["kind", "equals"], ["kind", "equals"], path);
985
+ if (!record3(constraint.equals) || Object.keys(constraint.equals).length === 0 || Object.keys(constraint.equals).length > 64 || Object.entries(constraint.equals).some(([key, value]) => !key || key.length > 256 || !scalar(value))) {
986
+ throw new TypeError(`${path}.equals is invalid`);
987
+ }
988
+ return;
989
+ }
990
+ if (constraint.kind === "credential-binding") {
991
+ exactKeys(source, ["kind", "source", "consumer"], ["kind", "source", "consumer"], path);
992
+ credentialName(constraint.source);
993
+ parseResourceName(constraint.consumer);
994
+ return;
995
+ }
996
+ throw new TypeError(`${path}.kind is invalid`);
997
+ }
998
+ function validateConstraints(value, path, required2) {
999
+ if (value === void 0 && !required2) return [];
1000
+ if (!Array.isArray(value) || required2 && value.length === 0 || value.length > MAX_CONSTRAINTS) {
1001
+ throw new TypeError(`${path} is invalid`);
1002
+ }
1003
+ value.forEach((constraint, index) => validatePolicyConstraint(constraint, `${path}[${index}]`));
1004
+ return value;
1005
+ }
1006
+ function policyOutcome(value) {
1007
+ if (!record3(value) || typeof value.kind !== "string") throw new TypeError("Policy outcome is invalid");
1008
+ if (value.kind === "allow") exactKeys(value, ["kind"], ["kind"], "Policy allow outcome");
1009
+ else if (value.kind === "deny") {
1010
+ exactKeys(value, ["kind", "code", "reason"], ["kind", "code"], "Policy deny outcome");
1011
+ if (typeof value.code !== "string" || !DENIAL_CODE.test(value.code)) throw new TypeError("Policy denial code is invalid");
1012
+ if (value.reason !== void 0) requiredString2(value.reason, "Policy denial reason", MAX_REASON_BYTES);
1013
+ } else if (value.kind === "constrain") {
1014
+ exactKeys(value, ["kind", "constraints"], ["kind", "constraints"], "Policy constrain outcome");
1015
+ validateConstraints(value.constraints, "Policy constraints", true);
1016
+ } else if (value.kind === "substitute") {
1017
+ exactKeys(value, ["kind", "value", "constraints"], ["kind", "value"], "Policy substitute outcome");
1018
+ canonicalJson(value.value);
1019
+ validateConstraints(value.constraints, "Policy constraints", false);
1020
+ } else if (value.kind === "require-approval") {
1021
+ exactKeys(value, ["kind", "reason", "constraints"], ["kind"], "Policy approval outcome");
1022
+ if (value.reason !== void 0) requiredString2(value.reason, "Policy approval reason", MAX_REASON_BYTES);
1023
+ validateConstraints(value.constraints, "Policy constraints", false);
1024
+ } else if (value.kind === "grant") {
1025
+ exactKeys(value, ["kind", "grant"], ["kind", "grant"], "Policy grant outcome");
1026
+ validateGrant(value.grant, "Policy grant");
1027
+ } else throw new TypeError("Policy outcome kind is invalid");
1028
+ if (encoder3.encode(canonicalJson(value)).byteLength > MAX_OUTCOME_BYTES) throw new TypeError("Policy outcome is oversized");
1029
+ return value;
1030
+ }
1031
+
1032
+ // src/policy.ts
1033
+ var ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1034
+ var VERSION3 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
1035
+ function policy(definition) {
1036
+ if (!definition || typeof definition !== "object" || Array.isArray(definition) || Object.keys(definition).some((key) => !["id", "version", "evaluate"].includes(key)) || !ID.test(definition.id) || !VERSION3.test(definition.version) || typeof definition.evaluate !== "function") throw new TypeError("Policy definition is invalid");
1037
+ return Object.freeze(definition);
1038
+ }
1039
+ async function evaluatePolicyDefinition(definition, input) {
1040
+ return policyOutcome(await definition.evaluate(input));
1041
+ }
1042
+
1043
+ // src/table.ts
1044
+ var identifier = { type: "string", pattern: "^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$", maxLength: 128 };
1045
+ var tableName = { type: "string", pattern: "^[a-z0-9][a-z0-9._-]{0,127}$", maxLength: 128 };
1046
+ var branchName = { type: "string", pattern: "^[a-z0-9][a-z0-9._/-]{0,127}$", maxLength: 128 };
1047
+ var hash2 = { type: "string", pattern: "^[a-f0-9]{64}$" };
1048
+ var scalar2 = { type: ["string", "number", "integer", "boolean", "null"], maxLength: 4096 };
1049
+ var TABLE_DESCRIBE_SCHEMA = {
1050
+ type: "object",
1051
+ required: ["table"],
1052
+ additionalProperties: false,
1053
+ properties: {
1054
+ table: tableName,
1055
+ branch: branchName,
1056
+ snapshot: hash2,
1057
+ stageId: hash2,
1058
+ waitMs: { type: "integer", minimum: 0, maximum: 25e3 }
1059
+ }
1060
+ };
1061
+ var filterSchema = {
1062
+ type: "object",
1063
+ required: ["field", "op", "value"],
1064
+ additionalProperties: false,
1065
+ properties: {
1066
+ field: identifier,
1067
+ op: { type: "string", enum: ["eq", "ne", "gt", "gte", "lt", "lte", "in", "between"] },
1068
+ value: { anyOf: [scalar2, { type: "array", minItems: 1, maxItems: 100, items: scalar2 }] }
1069
+ }
1070
+ };
1071
+ var TABLE_QUERY_SCHEMA = {
1072
+ type: "object",
1073
+ required: ["table", "snapshot", "query"],
1074
+ additionalProperties: false,
1075
+ properties: {
1076
+ table: tableName,
1077
+ branch: branchName,
1078
+ snapshot: hash2,
1079
+ query: {
1080
+ type: "object",
1081
+ additionalProperties: false,
1082
+ properties: {
1083
+ select: { type: "array", maxItems: 64, uniqueItems: true, items: identifier },
1084
+ where: { type: "array", maxItems: 32, items: filterSchema },
1085
+ groupBy: { type: "array", maxItems: 16, uniqueItems: true, items: identifier },
1086
+ aggregates: { type: "array", maxItems: 32, items: {
1087
+ type: "object",
1088
+ required: ["fn", "as"],
1089
+ additionalProperties: false,
1090
+ properties: {
1091
+ fn: { type: "string", enum: ["count", "sum", "avg", "min", "max"] },
1092
+ field: identifier,
1093
+ as: identifier
1094
+ }
1095
+ } },
1096
+ orderBy: { type: "array", maxItems: 8, items: {
1097
+ type: "object",
1098
+ required: ["field", "direction"],
1099
+ additionalProperties: false,
1100
+ properties: { field: identifier, direction: { type: "string", enum: ["asc", "desc"] } }
1101
+ } },
1102
+ limit: { type: "integer", minimum: 1, maximum: 1e3 }
1103
+ }
1104
+ }
1105
+ }
1106
+ };
1107
+ function validateStageOutputSpec(value, path = "$.output") {
1108
+ if (!value || typeof value !== "object" || Array.isArray(value)) return `${path} must be an object`;
1109
+ const output = value;
1110
+ const extra = Object.keys(output).find((key) => key !== "schema" && key !== "sortOrder");
1111
+ if (extra) return `${path}.${extra} is not allowed`;
1112
+ if (!Object.hasOwn(output, "schema")) return `${path}.schema is required`;
1113
+ const schemaError = validateJsonSchemaDefinition(output.schema, `${path}.schema`);
1114
+ if (schemaError) return schemaError;
1115
+ const sortOrder = output.sortOrder ?? [];
1116
+ if (!Array.isArray(sortOrder) || sortOrder.length > 64) return `${path}.sortOrder is invalid`;
1117
+ const keys = /* @__PURE__ */ new Set();
1118
+ for (const [index, raw] of sortOrder.entries()) {
1119
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${path}.sortOrder[${index}] is invalid`;
1120
+ const field2 = raw;
1121
+ if (Object.keys(field2).some((key) => key !== "key" && key !== "direction") || typeof field2.key !== "string" || !/^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$/u.test(field2.key) || field2.direction !== "asc" && field2.direction !== "desc" || keys.has(field2.key)) {
1122
+ return `${path}.sortOrder[${index}] is invalid`;
1123
+ }
1124
+ keys.add(field2.key);
1125
+ }
1126
+ return null;
1127
+ }
1128
+ function stageOutput(value) {
1129
+ const error = validateStageOutputSpec(value);
1130
+ if (error) throw new TypeError(error);
1131
+ return value;
1132
+ }
1133
+ var tableDescribe = {
1134
+ name: "table_describe",
1135
+ version: "1",
1136
+ description: "Inspect the schema and identity of one exact, queryable Table snapshot before querying it.",
1137
+ schema: TABLE_DESCRIBE_SCHEMA,
1138
+ maxEffect: "read-only",
1139
+ needs: [{ binding: "table_catalog", kind: "service", ops: ["describe"] }],
1140
+ async run(args, ctx) {
1141
+ return ctx.invoke(ctx.resources.table_catalog, "describe", args);
1142
+ }
1143
+ };
1144
+ var tableQuery = {
1145
+ name: "table_query",
1146
+ version: "1",
1147
+ description: "Query one exact Table snapshot with bounded fields, filters, grouping, aggregates, ordering, and limit.",
1148
+ schema: TABLE_QUERY_SCHEMA,
1149
+ maxEffect: "read-only",
1150
+ needs: [{ binding: "table_catalog", kind: "service", ops: ["query"] }],
1151
+ async run(args, ctx) {
1152
+ return ctx.invoke(ctx.resources.table_catalog, "query", args);
1153
+ }
1154
+ };
1155
+
1156
+ // src/tools.ts
1157
+ var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
1158
+ var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
1159
+ function opTool(binding, op, override = {}) {
1160
+ if (!NAME3.test(binding) || !OPERATION2.test(op)) throw new TypeError("opTool binding or operation is invalid");
1161
+ const name = override.name ?? op.replaceAll(".", "_");
1162
+ return {
1163
+ name,
1164
+ version: "catalog",
1165
+ description: override.description ?? `Invoke ${op} on the bound ${binding} resource.`,
1166
+ schema: { type: "object", additionalProperties: false },
1167
+ maxEffect: "read-only",
1168
+ needs: [],
1169
+ ...override.tier ? { tier: override.tier } : {},
1170
+ ...override.once ? { once: override.once } : {},
1171
+ ...override.guard ? { guard: override.guard } : {},
1172
+ catalog: { binding, op },
1173
+ async run() {
1174
+ throw new TypeError(`catalog Tool ${binding}#${op} was not resolved by deployment`);
1175
+ }
1176
+ };
1177
+ }
1178
+ function opTools(binding, ops = []) {
1179
+ if (ops.length === 0) throw new TypeError("opTools requires pinned operation names at bundle construction");
1180
+ return ops.map((op) => opTool(binding, op));
1181
+ }
1182
+ var webFetch = opTool("web", "get", {
1183
+ name: "web_fetch",
1184
+ description: "Fetch an HTTPS resource through the bound governed web Resource."
1185
+ });
1186
+ var webSearch = opTool("search", "search", {
1187
+ name: "web_search",
1188
+ description: "Search the public web through the bound governed search Resource."
1189
+ });
1190
+ var casTool = {
1191
+ name: "cas",
1192
+ version: "1",
1193
+ description: "Store or load one content-addressed Agent artifact.",
1194
+ schema: {
1195
+ type: "object",
1196
+ required: ["action"],
1197
+ additionalProperties: false,
1198
+ properties: {
1199
+ action: { type: "string", enum: ["put", "get"] },
1200
+ value: {},
1201
+ ref: { type: "string", pattern: "^[a-f0-9]{64}$" }
1202
+ }
1203
+ },
1204
+ maxEffect: "idempotent",
1205
+ needs: [{ binding: "cas", kind: "cas", ops: ["put", "get"] }],
1206
+ async run(args, ctx) {
1207
+ const input = args && typeof args === "object" && !Array.isArray(args) ? args : {};
1208
+ if (input.action === "put") {
1209
+ if (!Object.hasOwn(input, "value")) throw new TypeError("cas put requires value");
1210
+ return ctx.invoke(ctx.resources.cas, "put", { value: input.value });
1211
+ }
1212
+ if (input.action === "get") {
1213
+ if (typeof input.ref !== "string") throw new TypeError("cas get requires ref");
1214
+ return ctx.invoke(ctx.resources.cas, "get", { ref: input.ref });
1215
+ }
1216
+ throw new TypeError("cas action must be put or get");
1217
+ }
1218
+ };
1219
+
1220
+ // src/memory.ts
1221
+ var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 };
1222
+ var content = { type: "string", minLength: 1, maxLength: 65536 };
1223
+ var metadata = { type: "object", maxProperties: 64 };
1224
+ var record4 = {
1225
+ type: "object",
1226
+ required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
1227
+ additionalProperties: false,
1228
+ properties: {
1229
+ id,
1230
+ content,
1231
+ metadata,
1232
+ createdAt: { type: "integer", minimum: 0 },
1233
+ updatedAt: { type: "integer", minimum: 0 },
1234
+ expiresAt: { anyOf: [{ type: "integer", minimum: 0 }, { type: "null" }] }
1235
+ }
1236
+ };
1237
+ var MEMORY_OPERATION_DECLARATIONS = [
1238
+ {
1239
+ op: "remember",
1240
+ description: "Persist or replace one record in the invocation's authenticated Memory partition.",
1241
+ schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata } },
1242
+ resultSchema: record4,
1243
+ effect: "idempotent",
1244
+ recovery: { kind: "idempotency-key" },
1245
+ async: false,
1246
+ usage: { meter: "none", priceTable: null }
1247
+ },
1248
+ {
1249
+ op: "search",
1250
+ description: "Retrieve relevant records from the invocation's authenticated Memory partition.",
1251
+ schema: {
1252
+ type: "object",
1253
+ required: ["query"],
1254
+ additionalProperties: false,
1255
+ properties: { query: { type: "string", minLength: 1, maxLength: 8192 }, limit: { type: "integer", minimum: 1, maximum: 100 } }
1256
+ },
1257
+ resultSchema: {
1258
+ type: "object",
1259
+ required: ["hits"],
1260
+ additionalProperties: false,
1261
+ properties: { hits: { type: "array", maxItems: 100, items: {
1262
+ ...record4,
1263
+ required: [...record4.required, "score"],
1264
+ properties: { ...record4.properties, score: { type: "number", minimum: 0, maximum: 1 } }
1265
+ } } }
1266
+ },
1267
+ effect: "read-only",
1268
+ recovery: { kind: "repeat" },
1269
+ async: false,
1270
+ usage: { meter: "none", priceTable: null }
1271
+ },
1272
+ {
1273
+ op: "get",
1274
+ description: "Read one record from the invocation's authenticated Memory partition.",
1275
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
1276
+ resultSchema: { anyOf: [record4, { type: "null" }] },
1277
+ effect: "read-only",
1278
+ recovery: { kind: "repeat" },
1279
+ async: false,
1280
+ usage: { meter: "none", priceTable: null }
1281
+ },
1282
+ {
1283
+ op: "delete",
1284
+ description: "Delete one record from the invocation's authenticated Memory partition.",
1285
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
1286
+ resultSchema: { type: "object", required: ["deleted"], additionalProperties: false, properties: { deleted: { type: "boolean" } } },
1287
+ effect: "idempotent",
1288
+ recovery: { kind: "idempotency-key" },
1289
+ async: false,
1290
+ usage: { meter: "none", priceTable: null }
1291
+ },
1292
+ {
1293
+ op: "purge",
1294
+ description: "Delete every record in the invocation's authenticated Memory partition.",
1295
+ schema: { type: "object", additionalProperties: false, properties: {} },
1296
+ resultSchema: {
1297
+ type: "object",
1298
+ required: ["deleted"],
1299
+ additionalProperties: false,
1300
+ properties: { deleted: { type: "integer", minimum: 0 } }
1301
+ },
1302
+ effect: "idempotent",
1303
+ recovery: { kind: "idempotency-key" },
1304
+ async: false,
1305
+ usage: { meter: "none", priceTable: null }
1306
+ }
1307
+ ];
1308
+
1309
+ // src/integration.ts
1310
+ var ApiError = class extends Error {
1311
+ constructor(status, body, disposition = "uncertain") {
1312
+ super(`${status}: ${body}`);
1313
+ this.status = status;
1314
+ this.body = body;
1315
+ this.disposition = disposition;
1316
+ this.name = "ApiError";
1317
+ }
1318
+ status;
1319
+ body;
1320
+ disposition;
1321
+ };
1322
+ var IntegrationRequestNotSent = class extends Error {
1323
+ constructor(message = "integration request was not sent") {
1324
+ super(message);
1325
+ this.name = "IntegrationRequestNotSent";
1326
+ }
1327
+ };
1328
+ var TerminalIntegrationFailure = class extends Error {
1329
+ constructor(message = "integration operation failed terminally") {
1330
+ super(message);
1331
+ this.name = "TerminalIntegrationFailure";
1332
+ }
1333
+ };
1334
+ var OPERATION3 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
1335
+ function integrationEgressPolicy(value) {
1336
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1337
+ if (!source || !Array.isArray(source.rules) || source.rules.length > 128 || Object.keys(source).some((key) => key !== "rules")) {
1338
+ throw new TypeError("integration egress policy is invalid");
1339
+ }
1340
+ const rules = source.rules.map((raw) => {
1341
+ const rule = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
1342
+ const paths = Number(rule?.pathPrefix !== void 0) + Number(rule?.pathExact !== void 0);
1343
+ if (!rule || !Array.isArray(rule.operations) || rule.operations.length === 0 || rule.operations.length > 128 || rule.operations.some((operation) => typeof operation !== "string" || operation !== "*" && !OPERATION3.test(operation)) || typeof rule.origin !== "string" || paths !== 1 || !Array.isArray(rule.methods) || rule.methods.length === 0 || rule.methods.length > 8 || rule.methods.some((method) => typeof method !== "string" || !/^(?:GET|POST|PUT|PATCH|DELETE)$/u.test(method)) || Object.keys(rule).some((key) => !["operations", "origin", "pathPrefix", "pathExact", "methods"].includes(key))) {
1344
+ throw new TypeError("integration egress rule is invalid");
1345
+ }
1346
+ let origin;
1347
+ try {
1348
+ origin = new URL(rule.origin);
1349
+ } catch {
1350
+ throw new TypeError("integration egress origin is invalid");
1351
+ }
1352
+ if (origin.protocol !== "https:" || origin.origin !== rule.origin || origin.username || origin.password) {
1353
+ throw new TypeError("integration egress origin is invalid");
1354
+ }
1355
+ const path = String(rule.pathPrefix ?? rule.pathExact);
1356
+ if (!path.startsWith("/") || path.includes("?") || path.includes("#")) throw new TypeError("integration egress path is invalid");
1357
+ return rule;
1358
+ });
1359
+ return { rules };
1360
+ }
1361
+
1362
+ // src/training.ts
1363
+ var HASH2 = /^[a-f0-9]{64}$/u;
1364
+ var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
1365
+ var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
1366
+ var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
1367
+ var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
1368
+ var TRAINING_PROVIDER_CAPABILITY = {
1369
+ id: "constal.training-provider",
1370
+ version: "1",
1371
+ hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
1372
+ };
1373
+ function record5(value) {
1374
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1375
+ }
1376
+ function integer(value, field2, minimum, maximum) {
1377
+ if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum) {
1378
+ throw new TypeError(`${field2} is invalid`);
1379
+ }
1380
+ return Number(value);
1381
+ }
1382
+ function finite(value, field2, minimum, maximum) {
1383
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum) {
1384
+ throw new TypeError(`${field2} is invalid`);
1385
+ }
1386
+ return value;
1387
+ }
1388
+ function providerPin(value) {
1389
+ const candidate = record5(value);
1390
+ 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");
1391
+ const parts = parseResourceName(candidate.crn);
1392
+ if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
1393
+ return candidate;
1394
+ }
1395
+ function resumePoint(value) {
1396
+ if (value === null) return null;
1397
+ const candidate = record5(value);
1398
+ 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))) {
1399
+ throw new TypeError("training resume point is invalid");
1400
+ }
1401
+ return candidate;
1402
+ }
1403
+ function trainingProviderMetadata(value) {
1404
+ const candidate = record5(value);
1405
+ const checkpoints = record5(candidate?.checkpoints);
1406
+ 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) || candidate.models.length > 512 || !checkpoints || !Array.isArray(checkpoints.formats) || checkpoints.formats.length === 0 || checkpoints.formats.length > 32 || 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))) {
1407
+ throw new TypeError("Training Provider metadata is invalid");
1408
+ }
1409
+ const models = candidate.models.map((raw) => {
1410
+ const model = record5(raw);
1411
+ const pricing = record5(model?.pricing);
1412
+ 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))) {
1413
+ throw new TypeError("Training Provider model offer is invalid");
1414
+ }
1415
+ return raw;
1416
+ });
1417
+ if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
1418
+ throw new TypeError("Training Provider model offers must be unique");
1419
+ }
1420
+ return {
1421
+ lifecycleVersion: 1,
1422
+ methods: candidate.methods,
1423
+ models,
1424
+ checkpoints
1425
+ };
1426
+ }
1427
+ function datasetRef(value, field2) {
1428
+ const candidate = record5(value);
1429
+ 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))) {
1430
+ throw new TypeError(`${field2} is invalid`);
1431
+ }
1432
+ return candidate;
1433
+ }
1434
+ function scorerRef(value, field2) {
1435
+ const candidate = record5(value);
1436
+ 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))) {
1437
+ throw new TypeError(`${field2} is invalid`);
1438
+ }
1439
+ return candidate;
1440
+ }
1441
+ function trainingRecipe(value) {
1442
+ const candidate = record5(value);
1443
+ const allowed = [
1444
+ "method",
1445
+ "baseModel",
1446
+ "dataset",
1447
+ "validationDataset",
1448
+ "scorers",
1449
+ "loraRank",
1450
+ "learningRate",
1451
+ "epochs",
1452
+ "batchSize",
1453
+ "groupSize",
1454
+ "temperature",
1455
+ "seed",
1456
+ "checkpointEvery",
1457
+ "evalEvery",
1458
+ "maxTrainTokens",
1459
+ "maxSampleTokens",
1460
+ "budgetMicroUsd"
1461
+ ];
1462
+ if (!candidate || candidate.method !== "sft" && candidate.method !== "rl" || typeof candidate.baseModel !== "string" || !PROVIDER_MODEL_ID.test(candidate.baseModel) || !Array.isArray(candidate.scorers) || candidate.scorers.length > 32 || candidate.method === "rl" && candidate.scorers.length === 0 || Object.keys(candidate).some((key) => !allowed.includes(key))) throw new TypeError("training recipe is invalid");
1463
+ const recipe = {
1464
+ method: candidate.method,
1465
+ baseModel: candidate.baseModel,
1466
+ dataset: datasetRef(candidate.dataset, "training dataset"),
1467
+ validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
1468
+ scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
1469
+ loraRank: integer(candidate.loraRank, "LoRA rank", 1, 256),
1470
+ learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE, 1),
1471
+ epochs: integer(candidate.epochs, "epochs", 1, 100),
1472
+ batchSize: integer(candidate.batchSize, "batch size", 1, 256),
1473
+ groupSize: integer(candidate.groupSize, "group size", 1, 32),
1474
+ temperature: finite(candidate.temperature, "temperature", 0, 2),
1475
+ seed: integer(candidate.seed, "seed", 0, 2147483647),
1476
+ checkpointEvery: integer(candidate.checkpointEvery, "checkpoint interval", 1, 1e6),
1477
+ evalEvery: integer(candidate.evalEvery, "evaluation interval", 1, 1e6),
1478
+ maxTrainTokens: integer(candidate.maxTrainTokens, "training token limit", 1, 1e10),
1479
+ maxSampleTokens: integer(candidate.maxSampleTokens, "sample token limit", 1, 1e9),
1480
+ budgetMicroUsd: integer(candidate.budgetMicroUsd, "training budget", 1, 1e10)
1481
+ };
1482
+ if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
1483
+ return recipe;
1484
+ }
1485
+ function startTrainingRequest(value) {
1486
+ const candidate = record5(value);
1487
+ 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))) {
1488
+ throw new TypeError("training request is invalid");
1489
+ }
1490
+ return {
1491
+ ...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
1492
+ ...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
1493
+ ...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
1494
+ recipe: trainingRecipe(candidate.recipe),
1495
+ outputModelId: candidate.outputModelId
1496
+ };
1497
+ }
1498
+ function renderTrainingCompletion(input, expected) {
1499
+ const text = (value) => typeof value === "string" ? value : canonicalJson(value);
1500
+ return { prompt: `Input:
1501
+ ${text(input)}
1502
+
1503
+ Response:
1504
+ `, completion: expected === void 0 || expected === null ? null : text(expected) };
1505
+ }
1506
+
1507
+ // src/gateway.ts
1508
+ async function checkpointArtifactRef(value) {
1509
+ return await sha256Hex(canonicalJson(value));
1510
+ }
1511
+ var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
1512
+ var HASH3 = /^[a-f0-9]{64}$/u;
1513
+ var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1514
+ function httpsUrl(value, field2) {
1515
+ if (value === void 0) return;
1516
+ if (typeof value !== "string" || value.length > 2048) throw new TypeError(`${field2} is invalid`);
1517
+ let parsed;
1518
+ try {
1519
+ parsed = new URL(value);
1520
+ } catch {
1521
+ throw new TypeError(`${field2} is invalid`);
1522
+ }
1523
+ if (parsed.protocol !== "https:") throw new TypeError(`${field2} is invalid`);
1524
+ }
1525
+ function slotMetadata(value) {
1526
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Gateway Credential slots are invalid");
1527
+ const entries = Object.entries(value);
1528
+ if (entries.length > 32) throw new TypeError("Gateway Credential slots are invalid");
1529
+ const output = {};
1530
+ for (const [slot, raw] of entries) {
1531
+ const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
1532
+ if (!SLOT.test(slot) || !item || typeof item.title !== "string" || !item.title || item.title.length > 128 || item.description !== void 0 && (typeof item.description !== "string" || item.description.length > 1024) || item.required !== void 0 && typeof item.required !== "boolean" || item.provider !== void 0 && (typeof item.provider !== "string" || !SLOT.test(item.provider)) || Object.keys(item).some((key) => !["title", "description", "documentationUrl", "required", "provider"].includes(key))) {
1533
+ throw new TypeError("Gateway Credential slots are invalid");
1534
+ }
1535
+ httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
1536
+ output[slot] = item;
1537
+ }
1538
+ return output;
1539
+ }
1540
+ function configEgressBindings(value) {
1541
+ if (value === void 0) return [];
1542
+ if (!Array.isArray(value) || value.length > 16) throw new TypeError("Gateway config egress bindings are invalid");
1543
+ return value.map((raw) => {
1544
+ const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
1545
+ if (!item || !SLOT.test(String(item.urlProperty ?? "")) || !Array.isArray(item.operations) || item.operations.length === 0 || item.operations.length > 128 || item.operations.some((operation) => typeof operation !== "string" || operation !== "*" && !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u.test(operation)) || !Array.isArray(item.methods) || item.methods.length === 0 || item.methods.length > 8 || item.methods.some((method) => typeof method !== "string" || !/^(?:GET|POST|PUT|PATCH|DELETE)$/u.test(method)) || Object.keys(item).some((key) => !["urlProperty", "operations", "methods"].includes(key))) {
1546
+ throw new TypeError("Gateway config egress bindings are invalid");
1547
+ }
1548
+ return {
1549
+ urlProperty: String(item.urlProperty),
1550
+ operations: [...new Set(item.operations)],
1551
+ methods: [...new Set(item.methods)]
1552
+ };
1553
+ });
1554
+ }
1555
+ function discoverySetup(value) {
1556
+ if (value === void 0) return void 0;
1557
+ const item = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1558
+ if (!item || !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u.test(String(item.operation ?? "")) || !SLOT.test(String(item.resultConfigProperty ?? "")) || Object.keys(item).some((key) => !["operation", "resultConfigProperty"].includes(key))) {
1559
+ throw new TypeError("Gateway discovery setup is invalid");
1560
+ }
1561
+ return { operation: String(item.operation), resultConfigProperty: String(item.resultConfigProperty) };
1562
+ }
1563
+ function checkpointImportMetadata(value) {
1564
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1565
+ if (!source || source.lifecycleVersion !== 1 || !Array.isArray(source.formats) || source.formats.length === 0 || source.formats.length > 32 || source.formats.some((format) => typeof format !== "string" || !/^[a-z0-9][a-z0-9._+-]{0,63}$/u.test(format)) || new Set(source.formats).size !== source.formats.length || Object.keys(source).some((key) => !["lifecycleVersion", "formats"].includes(key))) {
1566
+ throw new TypeError("Gateway checkpoint import metadata is invalid");
1567
+ }
1568
+ return { lifecycleVersion: 1, formats: [...source.formats] };
1569
+ }
1570
+ function checkpointImportRequest(value) {
1571
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1572
+ const provenance = source?.source && typeof source.source === "object" && !Array.isArray(source.source) ? source.source : null;
1573
+ const provider = provenance?.provider && typeof provenance.provider === "object" && !Array.isArray(provenance.provider) ? provenance.provider : null;
1574
+ const checkpoint = provenance?.checkpoint && typeof provenance.checkpoint === "object" && !Array.isArray(provenance.checkpoint) ? provenance.checkpoint : null;
1575
+ const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
1576
+ const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
1577
+ const model = source?.model && typeof source.model === "object" && !Array.isArray(source.model) ? source.model : null;
1578
+ 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 || model.displayName.length > 128 || 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))) {
1579
+ throw new TypeError("checkpoint import request is invalid");
1580
+ }
1581
+ try {
1582
+ if (new TextEncoder().encode(canonicalJson(artifactValue)).byteLength > 65536) throw new TypeError();
1583
+ } catch {
1584
+ throw new TypeError("checkpoint import request is invalid");
1585
+ }
1586
+ try {
1587
+ parseResourceName(String(provider.crn));
1588
+ } catch {
1589
+ throw new TypeError("checkpoint import request is invalid");
1590
+ }
1591
+ return source;
1592
+ }
1593
+ function checkpointDeploymentRequest(value) {
1594
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1595
+ const gateway2 = source?.gateway && typeof source.gateway === "object" && !Array.isArray(source.gateway) ? source.gateway : null;
1596
+ 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))) {
1597
+ throw new TypeError("checkpoint deployment request is invalid");
1598
+ }
1599
+ try {
1600
+ parseResourceName(gateway2.crn);
1601
+ } catch {
1602
+ throw new TypeError("checkpoint deployment request is invalid");
1603
+ }
1604
+ return { gateway: gateway2, import: checkpointImportRequest(source.import) };
1605
+ }
1606
+ var MODEL_ID_CONTROL = /[\u0000-\u001f\u007f]/u;
1607
+ function gatewayModelOffer(value) {
1608
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1609
+ if (!source || typeof source.id !== "string" || !source.id || source.id.length > 512 || source.id !== source.id.trim() || MODEL_ID_CONTROL.test(source.id) || typeof source.displayName !== "string" || !source.displayName || source.displayName.length > 128 || !Number.isSafeInteger(source.contextTokens) || Number(source.contextTokens) <= 0 || !Number.isSafeInteger(source.maxOutputTokens) || Number(source.maxOutputTokens) <= 0 || Number(source.maxOutputTokens) > Number(source.contextTokens) || !Object.hasOwn(source, "pricing") || Object.keys(source).some((key) => ![
1610
+ "id",
1611
+ "displayName",
1612
+ "contextTokens",
1613
+ "maxOutputTokens",
1614
+ "inputModalities",
1615
+ "outputModalities",
1616
+ "pricing"
1617
+ ].includes(key))) {
1618
+ throw new TypeError("Gateway Model offer is invalid");
1619
+ }
1620
+ const modalities = (field2) => {
1621
+ const values = source[field2];
1622
+ if (values === void 0) return void 0;
1623
+ if (!Array.isArray(values) || values.length === 0 || values.length > 16 || values.some((item) => typeof item !== "string" || !SLOT.test(item)) || new Set(values).size !== values.length) {
1624
+ throw new TypeError("Gateway Model offer is invalid");
1625
+ }
1626
+ return values;
1627
+ };
1628
+ const pricing = source.pricing === null ? null : modelAdvertisedPricing(source.pricing);
1629
+ const inputModalities = modalities("inputModalities");
1630
+ const outputModalities = modalities("outputModalities");
1631
+ return {
1632
+ id: source.id,
1633
+ displayName: source.displayName,
1634
+ contextTokens: Number(source.contextTokens),
1635
+ maxOutputTokens: Number(source.maxOutputTokens),
1636
+ ...inputModalities ? { inputModalities } : {},
1637
+ ...outputModalities ? { outputModalities } : {},
1638
+ pricing
1639
+ };
1640
+ }
1641
+ function assertNonSecretGatewayConfig(value, field2 = "config") {
1642
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
1643
+ const source = value;
1644
+ if (source.format === "password" || /(?:secret|password|private[-_ ]?key|access[-_ ]?token|api[-_ ]?key)/iu.test(field2)) {
1645
+ throw new TypeError("Gateway secrets must use declared Credential slots");
1646
+ }
1647
+ const properties = source.properties && typeof source.properties === "object" && !Array.isArray(source.properties) ? source.properties : {};
1648
+ for (const [name, declaration] of Object.entries(properties)) assertNonSecretGatewayConfig(declaration, name);
1649
+ if (source.items) assertNonSecretGatewayConfig(source.items, field2);
1650
+ if (source.additionalProperties && typeof source.additionalProperties === "object") {
1651
+ assertNonSecretGatewayConfig(source.additionalProperties, field2);
1652
+ }
1653
+ }
1654
+ function gatewayPackageMetadata(value) {
1655
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1656
+ if (!source || source.lifecycleVersion !== 1 || typeof source.displayName !== "string" || !source.displayName || source.displayName.length > 128 || typeof source.description !== "string" || !source.description || source.description.length > 1024 || source.service !== void 0 && (typeof source.service !== "string" || !source.service || source.service.length > 128) || !Array.isArray(source.capabilities) || source.capabilities.length === 0 || source.capabilities.length > 32 || !source.billing || typeof source.billing !== "object" || Array.isArray(source.billing) || !["platform", "tenant"].includes(String(source.billing.upstreamPayer ?? ""))) {
1657
+ throw new TypeError("Gateway package metadata is invalid");
1658
+ }
1659
+ httpsUrl(source.documentationUrl, "Gateway documentation URL");
1660
+ const credentialSlots = slotMetadata(source.credentialSlots);
1661
+ const modelOffers = source.modelOffers === void 0 ? [] : Array.isArray(source.modelOffers) ? source.modelOffers.map(gatewayModelOffer) : (() => {
1662
+ throw new TypeError("Gateway Model offers are invalid");
1663
+ })();
1664
+ if (modelOffers.length > 512 || new Set(modelOffers.map((offer) => offer.id)).size !== modelOffers.length) {
1665
+ throw new TypeError("Gateway Model offers are invalid");
1666
+ }
1667
+ const capabilities = source.capabilities.map(capabilityContractRef);
1668
+ if (new Set(capabilities.map((contract) => `${contract.id}@${contract.version}#${contract.hash}`)).size !== capabilities.length) {
1669
+ throw new TypeError("Gateway capability contracts must be unique");
1670
+ }
1671
+ const egress = integrationEgressPolicy(source.egress);
1672
+ const configEgress = configEgressBindings(source.configEgress);
1673
+ const discovery = discoverySetup(source.discovery);
1674
+ const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
1675
+ const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
1676
+ if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
1677
+ throw new TypeError("Training Provider packages must implement the exact Training Provider capability");
1678
+ }
1679
+ 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))) {
1680
+ throw new TypeError("Checkpoint import Gateways must implement exact completion and checkpoint import capabilities");
1681
+ }
1682
+ return {
1683
+ lifecycleVersion: 1,
1684
+ displayName: source.displayName,
1685
+ description: source.description,
1686
+ ...typeof source.documentationUrl === "string" ? { documentationUrl: source.documentationUrl } : {},
1687
+ ...typeof source.service === "string" ? { service: source.service } : {},
1688
+ credentialSlots,
1689
+ modelOffers,
1690
+ capabilities,
1691
+ billing: { upstreamPayer: source.billing.upstreamPayer },
1692
+ egress,
1693
+ ...configEgress.length ? { configEgress } : {},
1694
+ ...discovery ? { discovery } : {},
1695
+ ...training ? { training } : {},
1696
+ ...checkpointImport ? { checkpointImport } : {}
1697
+ };
1698
+ }
1699
+ function resolveGatewayEgress(metadata2, config) {
1700
+ const derived = (metadata2.configEgress ?? []).map((binding) => {
1701
+ let endpoint;
1702
+ try {
1703
+ endpoint = new URL(String(config[binding.urlProperty] ?? ""));
1704
+ } catch {
1705
+ throw new TypeError(`Gateway ${binding.urlProperty} must be an HTTPS endpoint`);
1706
+ }
1707
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) {
1708
+ throw new TypeError(`Gateway ${binding.urlProperty} must be an exact HTTPS endpoint without credentials, query, or fragment`);
1709
+ }
1710
+ return { operations: binding.operations, origin: endpoint.origin, pathExact: endpoint.pathname, methods: binding.methods };
1711
+ });
1712
+ return integrationEgressPolicy({ rules: [...metadata2.egress.rules, ...derived] });
1713
+ }
1714
+ function gateway(definition) {
1715
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition.id) || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition.version) || !["cas", "web", "service", "mcp", "db", "browser", "sandbox-pool", "vault"].includes(definition.kind) || typeof definition.catalog !== "function" || typeof definition.invoke !== "function" || definition.reconcile !== void 0 && typeof definition.reconcile !== "function" || definition.cancel !== void 0 && typeof definition.cancel !== "function") {
1716
+ throw new TypeError("Gateway definition is invalid");
1717
+ }
1718
+ const schemaError = validateJsonSchemaDefinition(definition.configSchema);
1719
+ if (schemaError) throw new TypeError(`Gateway config schema is invalid: ${schemaError}`);
1720
+ const configSchema = definition.configSchema;
1721
+ if (configSchema.type !== "object") throw new TypeError('Gateway config schema root type must be "object"');
1722
+ if (configSchema.additionalProperties !== false) throw new TypeError("Gateway config schema must reject unknown root fields");
1723
+ assertNonSecretGatewayConfig(configSchema);
1724
+ const gateway2 = gatewayPackageMetadata({
1725
+ lifecycleVersion: 1,
1726
+ displayName: definition.displayName,
1727
+ description: definition.description,
1728
+ documentationUrl: definition.documentationUrl,
1729
+ service: definition.service,
1730
+ credentialSlots: definition.credentialSlots,
1731
+ modelOffers: definition.modelOffers ?? [],
1732
+ capabilities: definition.capabilities,
1733
+ billing: definition.billing,
1734
+ egress: definition.egress,
1735
+ configEgress: definition.configEgress,
1736
+ discovery: definition.discovery,
1737
+ training: definition.training,
1738
+ checkpointImport: definition.checkpointImport
1739
+ });
1740
+ const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
1741
+ for (const binding of gateway2.configEgress ?? []) {
1742
+ const property = properties[binding.urlProperty];
1743
+ if (!property || property.type !== "string" || property.format !== "uri") {
1744
+ throw new TypeError(`Gateway config egress property must be a URI string: ${binding.urlProperty}`);
1745
+ }
1746
+ }
1747
+ if (gateway2.discovery) {
1748
+ const property = properties[gateway2.discovery.resultConfigProperty];
1749
+ if (!property || property.type !== "array") throw new TypeError("Gateway discovery result config property must be an array");
1750
+ const required2 = Array.isArray(configSchema.required) ? configSchema.required : [];
1751
+ if (!required2.includes(gateway2.discovery.resultConfigProperty)) {
1752
+ throw new TypeError("Gateway discovery result config property must be required");
1753
+ }
1754
+ if (property.readOnly !== true) throw new TypeError("Gateway discovery result config property must be read-only");
1755
+ }
1756
+ const authoredCatalog = definition.catalog;
1757
+ const wrapped = { ...definition, metadata: gateway2, catalog(config) {
1758
+ const declarations = authoredCatalog(config);
1759
+ if (gateway2.checkpointImport) {
1760
+ const operation = declarations.find((candidate) => candidate.op === "importCheckpoint");
1761
+ if (!operation || !operation.async || operation.effect !== "reconcilable" || operation.recovery.kind !== "reconcile") {
1762
+ throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
1763
+ }
1764
+ }
1765
+ return declarations;
1766
+ } };
1767
+ return Object.freeze(wrapped);
1768
+ }
1769
+ function trainingProvider(definition) {
1770
+ const authoredCatalog = definition.catalog;
1771
+ return gateway({
1772
+ ...definition,
1773
+ capabilities: [...definition.capabilities, ...definition.capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash) ? [] : [TRAINING_PROVIDER_CAPABILITY]],
1774
+ catalog(config) {
1775
+ const declarations = authoredCatalog(config);
1776
+ const train = declarations.find((operation) => operation.op === "train");
1777
+ if (!train || !train.async || train.effect !== "reconcilable" || train.recovery.kind !== "reconcile") {
1778
+ throw new TypeError("Training Provider train must be asynchronous, reconcilable, and recovered by reconcile");
1779
+ }
1780
+ return declarations;
1781
+ }
1782
+ });
1783
+ }
1784
+ var MODEL_COMPLETION_CAPABILITY = {
1785
+ id: "constal.model-completion",
1786
+ version: "1",
1787
+ hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
1788
+ };
1789
+ var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
1790
+ id: "constal.model-checkpoint-import",
1791
+ version: "1",
1792
+ hash: "49563823899586a87dcee82e9db969af5f2f5364adb3eb808a19e86b862e87ba"
1793
+ };
1794
+ var MCP_CLIENT_CAPABILITY = {
1795
+ id: "constal.mcp-client",
1796
+ version: "1",
1797
+ hash: "a694af71191432e75980dc73962d9239dc8ea324aff084f183a2f45603bd2267"
1798
+ };
1799
+
1800
+ // src/credential-provider.ts
1801
+ function assertNonSecretConfigSchema(value, field2 = "config") {
1802
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
1803
+ const source = value;
1804
+ if (source.format === "password" || /(?:secret|password|private[-_ ]?key|access[-_ ]?token|api[-_ ]?key)/iu.test(field2)) {
1805
+ throw new TypeError("credential provider secrets must use declared bootstrap Credential slots");
1806
+ }
1807
+ const properties = source.properties && typeof source.properties === "object" && !Array.isArray(source.properties) ? source.properties : {};
1808
+ for (const [name, declaration] of Object.entries(properties)) assertNonSecretConfigSchema(declaration, name);
1809
+ if (source.items) assertNonSecretConfigSchema(source.items, field2);
1810
+ if (source.additionalProperties && typeof source.additionalProperties === "object") assertNonSecretConfigSchema(source.additionalProperties, field2);
1811
+ }
1812
+ function credentialProviderConfigSchema(value) {
1813
+ const error = validateJsonSchemaDefinition(value);
1814
+ if (error) throw new TypeError(`credential provider config schema is invalid: ${error}`);
1815
+ const schema = value;
1816
+ if (schema.type !== "object") throw new TypeError('credential provider config schema root type must be "object"');
1817
+ if (schema.additionalProperties !== false) throw new TypeError("credential provider config schema must reject unknown root fields");
1818
+ assertNonSecretConfigSchema(schema);
1819
+ return schema;
1820
+ }
1821
+ function interactionRecord(value) {
1822
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1823
+ }
1824
+ function exactKeys2(value, allowed) {
1825
+ return Object.keys(value).every((key) => allowed.includes(key));
1826
+ }
1827
+ function boundedText(value, maximum) {
1828
+ return typeof value === "string" && value.length > 0 && value.length <= maximum;
1829
+ }
1830
+ function interactionExpiry(value, sessionExpiresAt) {
1831
+ if (value === void 0 || value === null) return null;
1832
+ return Number.isSafeInteger(value) && Number(value) > Date.now() && Number(value) <= sessionExpiresAt ? Number(value) : NaN;
1833
+ }
1834
+ function credentialInteractionEvent(value) {
1835
+ const event = interactionRecord(value);
1836
+ if (!event || !["callback", "submit", "continue", "poll"].includes(String(event.kind ?? ""))) {
1837
+ throw new TypeError("credential interaction event is invalid");
1838
+ }
1839
+ if (event.kind === "callback") {
1840
+ const parameters = interactionRecord(event.parameters);
1841
+ const headers = interactionRecord(event.headers);
1842
+ if (!exactKeys2(event, ["kind", "method", "parameters", "headers", "bodyBase64"]) || !["GET", "POST"].includes(String(event.method ?? "")) || !parameters || Object.keys(parameters).length > 32 || Object.entries(parameters).some(([key, item]) => key.length > 128 || typeof item !== "string" || item.length > 4096) || !headers || Object.keys(headers).length > 64 || Object.entries(headers).some(([key, item]) => key.length > 128 || typeof item !== "string" || item.length > 8192) || event.bodyBase64 !== null && (typeof event.bodyBase64 !== "string" || event.bodyBase64.length > 35e4 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(event.bodyBase64))) {
1843
+ throw new TypeError("credential interaction callback is invalid");
1844
+ }
1845
+ } else if (event.kind === "submit") {
1846
+ if (!exactKeys2(event, ["kind", "value"]) || new TextEncoder().encode(canonicalJson(event.value)).byteLength > 65536) {
1847
+ throw new TypeError("credential interaction submission is invalid");
1848
+ }
1849
+ } else if (!exactKeys2(event, ["kind"])) throw new TypeError("credential interaction event is invalid");
1850
+ return event;
1851
+ }
1852
+ function credentialInteractionPrimaryAction(value, origins) {
1853
+ const action2 = interactionRecord(value);
1854
+ const event = interactionRecord(action2?.event);
1855
+ if (!action2 || !event || !boundedText(action2.label, 64) || !exactKeys2(event, ["kind"]) || event.kind !== "continue") {
1856
+ throw new TypeError("credential interaction primary action is invalid");
1857
+ }
1858
+ if (action2.kind === "continue") {
1859
+ if (!exactKeys2(action2, ["kind", "label", "event"])) throw new TypeError("credential interaction primary action is invalid");
1860
+ } else if (action2.kind === "open-url") {
1861
+ if (!exactKeys2(action2, ["kind", "label", "url", "event"]) || !boundedText(action2.url, 4096)) {
1862
+ throw new TypeError("credential interaction primary action is invalid");
1863
+ }
1864
+ let url;
1865
+ try {
1866
+ url = new URL(action2.url);
1867
+ } catch {
1868
+ throw new TypeError("credential interaction primary action URL is invalid");
1869
+ }
1870
+ if (url.protocol !== "https:" || url.username || url.password || !origins.includes(url.origin)) {
1871
+ throw new TypeError("credential interaction primary action URL is not authorized");
1872
+ }
1873
+ } else throw new TypeError("credential interaction primary action is invalid");
1874
+ return action2;
1875
+ }
1876
+ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
1877
+ const action2 = interactionRecord(value);
1878
+ if (!action2 || !["redirect", "form", "display", "wait", "complete"].includes(String(action2.kind ?? ""))) {
1879
+ throw new TypeError("credential interaction action is invalid");
1880
+ }
1881
+ const expiresAt = action2.kind === "complete" ? null : interactionExpiry(action2.expiresAt, sessionExpiresAt);
1882
+ if (Number.isNaN(expiresAt)) throw new TypeError("credential interaction action expiry is invalid");
1883
+ if (action2.kind === "redirect") {
1884
+ if (!exactKeys2(action2, ["kind", "url", "expiresAt"]) || !boundedText(action2.url, 4096)) {
1885
+ throw new TypeError("credential interaction redirect is invalid");
1886
+ }
1887
+ let url;
1888
+ try {
1889
+ url = new URL(action2.url);
1890
+ } catch {
1891
+ throw new TypeError("credential interaction redirect is invalid");
1892
+ }
1893
+ if (url.protocol !== "https:" || url.username || url.password || url.hash || !origins.includes(url.origin) || url.searchParams.getAll("state").length !== 1 || url.searchParams.get("state") !== state) {
1894
+ throw new TypeError("credential interaction redirect is not authorized");
1895
+ }
1896
+ } else if (action2.kind === "form") {
1897
+ if (!exactKeys2(action2, ["kind", "schema", "title", "description", "submitLabel", "expiresAt"]) || action2.title !== void 0 && !boundedText(action2.title, 128) || action2.description !== void 0 && !boundedText(action2.description, 1024) || action2.submitLabel !== void 0 && !boundedText(action2.submitLabel, 64)) {
1898
+ throw new TypeError("credential interaction form is invalid");
1899
+ }
1900
+ const schemaError = validateJsonSchemaDefinition(action2.schema, "$interaction.form.schema");
1901
+ const formSchema = interactionRecord(action2.schema);
1902
+ if (schemaError || !formSchema || formSchema.type !== "object" || formSchema.additionalProperties !== false || new TextEncoder().encode(canonicalJson(action2.schema)).byteLength > 65536) {
1903
+ throw new TypeError(`credential interaction form schema is invalid${schemaError ? `: ${schemaError}` : ""}`);
1904
+ }
1905
+ } else if (action2.kind === "display") {
1906
+ if (!exactKeys2(action2, ["kind", "instructions", "title", "userCode", "primaryAction", "expiresAt"]) || !boundedText(action2.instructions, 4096) || action2.title !== void 0 && !boundedText(action2.title, 128) || action2.userCode !== void 0 && !boundedText(action2.userCode, 512)) {
1907
+ throw new TypeError("credential interaction display is invalid");
1908
+ }
1909
+ credentialInteractionPrimaryAction(action2.primaryAction, origins);
1910
+ } else if (action2.kind === "wait") {
1911
+ if (!exactKeys2(action2, ["kind", "resume", "expiresAt", "pollAfterMs"]) || !["callback", "poll"].includes(String(action2.resume ?? "")) || expiresAt === null || action2.pollAfterMs !== void 0 && (!Number.isSafeInteger(action2.pollAfterMs) || Number(action2.pollAfterMs) < 1e3 || Number(action2.pollAfterMs) > 3e5) || action2.resume === "poll" && action2.pollAfterMs === void 0 || action2.resume === "callback" && action2.pollAfterMs !== void 0) {
1912
+ throw new TypeError("credential interaction wait action is invalid");
1913
+ }
1914
+ } else {
1915
+ if (!exactKeys2(action2, ["kind", "material", "expiresAt"]) || !boundedText(action2.material, 1048576) || action2.expiresAt !== void 0 && action2.expiresAt !== null && (!Number.isSafeInteger(action2.expiresAt) || Number(action2.expiresAt) <= Date.now())) {
1916
+ throw new TypeError("credential interaction completion is invalid");
1917
+ }
1918
+ }
1919
+ return action2;
1920
+ }
1921
+ function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
1922
+ const result = interactionRecord(value);
1923
+ if (!result || !exactKeys2(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
1924
+ const privateState = result.privateState;
1925
+ if (privateState !== void 0 && privateState !== null && (typeof privateState !== "string" || new TextEncoder().encode(privateState).byteLength > 1048576)) throw new TypeError("credential interaction private state is invalid");
1926
+ return {
1927
+ action: credentialInteractionAction(result.action, origins, state, sessionExpiresAt),
1928
+ ...privateState === void 0 ? {} : { privateState }
1929
+ };
1930
+ }
1931
+ function credentialProviderSetupMetadata(value, slots) {
1932
+ if (value === void 0) return void 0;
1933
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential provider setup metadata is invalid");
1934
+ const setup = value;
1935
+ const allowed = /* @__PURE__ */ new Set(["service", "useCase", "recommended", "credentialSlots"]);
1936
+ if (Object.keys(setup).some((key) => !allowed.has(key)) || setup.service !== void 0 && (typeof setup.service !== "string" || !setup.service || setup.service.length > 64) || setup.useCase !== void 0 && (typeof setup.useCase !== "string" || !setup.useCase || setup.useCase.length > 256) || setup.recommended !== void 0 && typeof setup.recommended !== "boolean") {
1937
+ throw new TypeError("credential provider setup metadata is invalid");
1938
+ }
1939
+ const declarations = setup.credentialSlots;
1940
+ if (declarations !== void 0) {
1941
+ if (!declarations || typeof declarations !== "object" || Array.isArray(declarations) || Object.keys(declarations).some((slot) => !slots.includes(slot))) {
1942
+ throw new TypeError("credential provider setup Credential slots are invalid");
1943
+ }
1944
+ for (const declaration of Object.values(declarations)) {
1945
+ if (!declaration || typeof declaration !== "object" || Array.isArray(declaration)) {
1946
+ throw new TypeError("credential provider setup Credential slots are invalid");
1947
+ }
1948
+ const slot = declaration;
1949
+ const slotAllowed = /* @__PURE__ */ new Set(["title", "description", "documentationUrl", "input", "accept"]);
1950
+ if (Object.keys(slot).some((key) => !slotAllowed.has(key)) || typeof slot.title !== "string" || !slot.title || slot.title.length > 128 || slot.description !== void 0 && (typeof slot.description !== "string" || !slot.description || slot.description.length > 512) || slot.input !== void 0 && !["secret", "multiline", "file"].includes(String(slot.input))) {
1951
+ throw new TypeError("credential provider setup Credential slots are invalid");
1952
+ }
1953
+ if (slot.documentationUrl !== void 0) {
1954
+ let documentationUrl;
1955
+ try {
1956
+ documentationUrl = new URL(String(slot.documentationUrl));
1957
+ } catch {
1958
+ throw new TypeError("credential provider setup Credential slot documentation URL is invalid");
1959
+ }
1960
+ if (typeof slot.documentationUrl !== "string" || slot.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
1961
+ throw new TypeError("credential provider setup Credential slot documentation URL is invalid");
1962
+ }
1963
+ }
1964
+ if (slot.accept !== void 0 && (!Array.isArray(slot.accept) || slot.accept.length > 16 || slot.accept.some((item) => typeof item !== "string" || !item || item.length > 64))) {
1965
+ throw new TypeError("credential provider setup Credential slot file types are invalid");
1966
+ }
1967
+ }
1968
+ }
1969
+ return value;
1970
+ }
1971
+ function credentialProvider(definition) {
1972
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition.id) || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition.version) || !definition.displayName || definition.displayName.length > 128 || !definition.description || definition.description.length > 1024 || typeof definition.mint !== "function" || definition.verify !== void 0 && typeof definition.verify !== "function" || definition.destroy !== void 0 && typeof definition.destroy !== "function") {
1973
+ throw new TypeError("credential provider metadata is invalid");
1974
+ }
1975
+ if (definition.documentationUrl !== void 0) {
1976
+ if (typeof definition.documentationUrl !== "string") throw new TypeError("credential provider documentation URL is invalid");
1977
+ let documentationUrl;
1978
+ try {
1979
+ documentationUrl = new URL(definition.documentationUrl);
1980
+ } catch {
1981
+ throw new TypeError("credential provider documentation URL is invalid");
1982
+ }
1983
+ if (definition.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
1984
+ throw new TypeError("credential provider documentation URL is invalid");
1985
+ }
1986
+ }
1987
+ credentialRotationDefaults(definition.rotation);
1988
+ credentialProviderConfigSchema(definition.configSchema);
1989
+ credentialProviderConfigSchema(definition.credentialConfigSchema);
1990
+ if (!Array.isArray(definition.credentialSlots) || definition.credentialSlots.length > 32 || new Set(definition.credentialSlots).size !== definition.credentialSlots.length || definition.credentialSlots.some((slot) => typeof slot !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(slot))) {
1991
+ throw new TypeError("credential provider bootstrap slots are invalid");
1992
+ }
1993
+ const setup = credentialProviderSetupMetadata(definition.setup, definition.credentialSlots);
1994
+ const interaction = definition.interaction ?? null;
1995
+ if (interaction && (!Array.isArray(interaction.origins) || interaction.origins.length === 0 || interaction.origins.length > 16 || new Set(interaction.origins).size !== interaction.origins.length || interaction.origins.some((origin) => {
1996
+ try {
1997
+ const url = new URL(origin);
1998
+ return url.protocol !== "https:" || url.origin !== origin;
1999
+ } catch {
2000
+ return true;
2001
+ }
2002
+ }))) {
2003
+ throw new TypeError("credential provider interaction origins are invalid");
2004
+ }
2005
+ const mintRecovery = definition.mintRecovery ?? { kind: "idempotency-key" };
2006
+ if (!["idempotency-key", "outcome-unknown"].includes(mintRecovery.kind)) {
2007
+ throw new TypeError("credential provider mint recovery is invalid");
2008
+ }
2009
+ if (interaction && (typeof interaction.start !== "function" || typeof interaction.advance !== "function")) {
2010
+ throw new TypeError("credential provider interaction is invalid");
2011
+ }
2012
+ const metadata2 = {
2013
+ lifecycleVersion: 3,
2014
+ displayName: definition.displayName,
2015
+ description: definition.description,
2016
+ ...definition.documentationUrl ? { documentationUrl: definition.documentationUrl } : {},
2017
+ ...setup ? { setup } : {},
2018
+ credentialSlots: [...definition.credentialSlots].sort(),
2019
+ credentialConfigSchema: definition.credentialConfigSchema,
2020
+ interaction: interaction ? { origins: [...interaction.origins].sort() } : null,
2021
+ rotation: definition.rotation,
2022
+ egress: integrationEgressPolicy(definition.egress)
2023
+ };
2024
+ return Object.freeze({ ...definition, mintRecovery, metadata: metadata2 });
2025
+ }
2026
+
2027
+ // src/model.ts
2028
+ var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2029
+ var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2030
+ var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2031
+ function record6(value) {
2032
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2033
+ }
2034
+ function credentialHeader(value, name) {
2035
+ if (value === null || value === void 0) return null;
2036
+ const source = record6(value);
2037
+ 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`);
2038
+ return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2039
+ }
2040
+ function normalizeModelGatewayConfig(value) {
2041
+ const source = record6(value);
2042
+ 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) {
2043
+ throw new TypeError("model gateway config is invalid");
2044
+ }
2045
+ const maxOutputTokens = source.maxOutputTokens === void 0 ? 256 : Number(source.maxOutputTokens);
2046
+ const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2047
+ if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 8192 || temperature !== null && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2048
+ throw new TypeError("model gateway generation limits are invalid");
2049
+ }
2050
+ const normalized = {
2051
+ baseUrl: source.baseUrl,
2052
+ protocol: source.protocol,
2053
+ model: source.model,
2054
+ maxOutputTokens,
2055
+ temperature,
2056
+ gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2057
+ providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2058
+ };
2059
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2060
+ throw new TypeError("gateway and provider credentials cannot share one header");
2061
+ }
2062
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2063
+ throw new TypeError("gateway and provider credentials cannot share one slot");
2064
+ }
2065
+ modelGatewayEndpoint(normalized);
2066
+ return normalized;
2067
+ }
2068
+ function modelGatewayEndpoint(config) {
2069
+ let endpoint;
2070
+ try {
2071
+ endpoint = new URL(config.baseUrl);
2072
+ } catch {
2073
+ throw new TypeError("model gateway baseUrl is invalid");
2074
+ }
2075
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2076
+ throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
2077
+ }
2078
+ const hostname = endpoint.hostname.toLowerCase();
2079
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2080
+ throw new TypeError("model gateway baseUrl must use a public hostname");
2081
+ }
2082
+ const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2083
+ if (!suffix) throw new TypeError("model gateway protocol is invalid");
2084
+ endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2085
+ return endpoint;
2086
+ }
2087
+ function modelPrompt(args) {
2088
+ return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2089
+ }
2090
+ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2091
+ const prompt = modelPrompt(args);
2092
+ if (protocol === "anthropic") return {
2093
+ model,
2094
+ system: args.system ?? "",
2095
+ messages: [{ role: "user", content: prompt }],
2096
+ max_tokens: maxOutputTokens,
2097
+ ...temperature === null ? {} : { temperature },
2098
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {}
2099
+ };
2100
+ if (protocol === "openai") return {
2101
+ model,
2102
+ messages: [
2103
+ ...args.system ? [{ role: "developer", content: args.system }] : [],
2104
+ { role: "user", content: prompt }
2105
+ ],
2106
+ max_completion_tokens: maxOutputTokens,
2107
+ ...temperature === null ? {} : { temperature },
2108
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({
2109
+ type: "function",
2110
+ function: { name: tool.name, description: tool.description, parameters: tool.schema }
2111
+ })) } : {}
2112
+ };
2113
+ throw new TypeError("model gateway protocol is invalid");
2114
+ }
2115
+ function integer2(value) {
2116
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
2117
+ }
2118
+ function costMetadata(usage) {
2119
+ const cost = usage.cost;
2120
+ const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
2121
+ return {
2122
+ ...costUsd !== void 0 ? { costUsd } : {},
2123
+ ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
2124
+ ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
2125
+ };
2126
+ }
2127
+ function modelProtocolResult(protocol, raw, provider, model) {
2128
+ const source = record6(raw) ?? {};
2129
+ const toolCalls = [];
2130
+ let content2 = "";
2131
+ let usage;
2132
+ if (protocol === "anthropic") {
2133
+ const blocks = Array.isArray(source.content) ? source.content : [];
2134
+ content2 = blocks.map((candidate) => {
2135
+ const block = record6(candidate);
2136
+ if (block?.type === "text" && typeof block.text === "string") return block.text;
2137
+ if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
2138
+ toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
2139
+ }
2140
+ return "";
2141
+ }).join("");
2142
+ const values = record6(source.usage) ?? {};
2143
+ const cached = integer2(values.cache_read_input_tokens);
2144
+ usage = {
2145
+ input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
2146
+ output: integer2(values.output_tokens),
2147
+ cached,
2148
+ ...costMetadata(values)
2149
+ };
2150
+ } else if (protocol === "openai") {
2151
+ const choice = record6(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2152
+ const message = record6(choice.message) ?? {};
2153
+ content2 = typeof message.content === "string" ? message.content : "";
2154
+ for (const candidate of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
2155
+ const call = record6(candidate);
2156
+ const fn = record6(call?.function);
2157
+ if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
2158
+ let args;
2159
+ try {
2160
+ args = JSON.parse(fn.arguments);
2161
+ } catch {
2162
+ throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
2163
+ }
2164
+ toolCalls.push({ id: call.id, name: fn.name, args });
2165
+ }
2166
+ const values = record6(source.usage) ?? {};
2167
+ usage = {
2168
+ input: integer2(values.prompt_tokens),
2169
+ output: integer2(values.completion_tokens),
2170
+ cached: integer2(record6(values.prompt_tokens_details)?.cached_tokens),
2171
+ ...costMetadata(values)
2172
+ };
2173
+ } else throw new TypeError("model gateway protocol is invalid");
2174
+ if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
2175
+ return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model };
2176
+ }
2177
+
2178
+ // src/scorer.ts
2179
+ function validPointer(value) {
2180
+ return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));
2181
+ }
2182
+ function record7(value) {
2183
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2184
+ }
2185
+ function exactKeys3(value, allowed) {
2186
+ return Object.keys(value).every((key) => allowed.includes(key));
2187
+ }
2188
+ function scorerRule(value, depth, state) {
2189
+ const rule = record7(value);
2190
+ if (!rule || depth > 32 || ++state.rules > 1024 || typeof rule.op !== "string") throw new TypeError("Code Scorer IR is invalid");
2191
+ if (rule.op === "all" || rule.op === "any") {
2192
+ if (!exactKeys3(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1 || rule.rules.length > 128) {
2193
+ throw new TypeError("Code Scorer logical rule is invalid");
2194
+ }
2195
+ return { op: rule.op, rules: rule.rules.map((child) => scorerRule(child, depth + 1, state)) };
2196
+ }
2197
+ if (rule.op === "not") {
2198
+ if (!exactKeys3(rule, ["op", "rule"])) throw new TypeError("Code Scorer not rule is invalid");
2199
+ return { op: "not", rule: scorerRule(rule.rule, depth + 1, state) };
2200
+ }
2201
+ if (rule.op === "schema") {
2202
+ if (!exactKeys3(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record7(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
2203
+ return rule;
2204
+ }
2205
+ if (rule.op === "regex") {
2206
+ if (!exactKeys3(rule, ["op", "path", "pattern", "flags"]) || !validPointer(rule.path) || typeof rule.pattern !== "string" || rule.pattern.length > 4096 || ![void 0, "", "i", "m", "im"].includes(rule.flags)) {
2207
+ throw new TypeError("Code Scorer regex rule is invalid");
2208
+ }
2209
+ try {
2210
+ new RegExp(rule.pattern, String(rule.flags ?? "") + "u");
2211
+ } catch {
2212
+ throw new TypeError("Code Scorer regex rule is invalid");
2213
+ }
2214
+ return rule;
2215
+ }
2216
+ if (rule.op === "range") {
2217
+ if (!exactKeys3(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");
2218
+ return rule;
2219
+ }
2220
+ if (rule.op === "equals" || rule.op === "contains") {
2221
+ if (!exactKeys3(rule, ["op", "path", "value"]) || !validPointer(rule.path) || !Object.hasOwn(rule, "value") || new TextEncoder().encode(canonicalJson(rule.value)).byteLength > 65536) {
2222
+ throw new TypeError(`Code Scorer ${rule.op} rule is invalid`);
2223
+ }
2224
+ return rule;
2225
+ }
2226
+ if (rule.op === "tool-sequence") {
2227
+ if (!exactKeys3(rule, ["op", "path", "expected", "mode"]) || !validPointer(rule.path) || !Array.isArray(rule.expected) || rule.expected.length > 256 || 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");
2228
+ return rule;
2229
+ }
2230
+ if (rule.op === "citations-in-source") {
2231
+ if (!exactKeys3(rule, ["op", "textPath", "sourcesPath"]) || !validPointer(rule.textPath) || !validPointer(rule.sourcesPath)) throw new TypeError("Code Scorer citation rule is invalid");
2232
+ return rule;
2233
+ }
2234
+ throw new TypeError("Code Scorer operation is invalid");
2235
+ }
2236
+ function codeScorerIR(value) {
2237
+ const ir = record7(value);
2238
+ if (!ir || ir.v !== 1 || !exactKeys3(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
2239
+ return { v: 1, rule: scorerRule(ir.rule, 0, { rules: 0 }) };
2240
+ }
2241
+ function pointer(value, path) {
2242
+ if (path === "") return { found: true, value };
2243
+ let current = value;
2244
+ for (const encoded of path.slice(1).split("/")) {
2245
+ const key = encoded.replace(/~1/gu, "/").replace(/~0/gu, "~");
2246
+ if (Array.isArray(current)) {
2247
+ if (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length) return { found: false, value: void 0 };
2248
+ current = current[Number(key)];
2249
+ } else {
2250
+ const source = record7(current);
2251
+ if (!source || !Object.hasOwn(source, key)) return { found: false, value: void 0 };
2252
+ current = source[key];
2253
+ }
2254
+ }
2255
+ return { found: true, value: current };
2256
+ }
2257
+ function fail(path, reason) {
2258
+ return { pass: false, checks: 1, failures: [{ path, reason }] };
2259
+ }
2260
+ function pass() {
2261
+ return { pass: true, checks: 1, failures: [] };
2262
+ }
2263
+ function evaluate(rule, subject) {
2264
+ if (rule.op === "all" || rule.op === "any") {
2265
+ const values = rule.rules.map((child) => evaluate(child, subject));
2266
+ const passed = rule.op === "all" ? values.every((value) => value.pass) : values.some((value) => value.pass);
2267
+ return {
2268
+ pass: passed,
2269
+ checks: values.reduce((sum, value) => sum + value.checks, 0),
2270
+ failures: passed && rule.op === "any" ? [] : values.flatMap((value) => value.failures).slice(0, 64)
2271
+ };
2272
+ }
2273
+ if (rule.op === "not") {
2274
+ const value = evaluate(rule.rule, subject);
2275
+ return value.pass ? fail("", "negated rule passed") : { pass: true, checks: value.checks, failures: [] };
2276
+ }
2277
+ if (rule.op === "citations-in-source") {
2278
+ const text = pointer(subject, rule.textPath);
2279
+ const sources = pointer(subject, rule.sourcesPath);
2280
+ if (!text.found || typeof text.value !== "string") return fail(rule.textPath, "citation text is missing");
2281
+ if (!sources.found || !Array.isArray(sources.value)) return fail(rule.sourcesPath, "citation sources are missing");
2282
+ const available = new Set(sources.value.flatMap((source, index) => {
2283
+ if (typeof source === "string") return [source, String(index + 1)];
2284
+ const item = record7(source);
2285
+ return item ? [String(item.id ?? ""), String(index + 1)].filter(Boolean) : [String(index + 1)];
2286
+ }));
2287
+ const citations = [...text.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
2288
+ return citations.length > 0 && citations.every((citation) => available.has(citation)) ? pass() : fail(rule.textPath, "citation is absent or not in sources");
2289
+ }
2290
+ const selected = pointer(subject, rule.path);
2291
+ if (!selected.found) return fail(rule.path, "path is missing");
2292
+ if (rule.op === "schema") {
2293
+ const error = validateJsonSchema(selected.value, rule.schema, rule.path || "$");
2294
+ return error ? fail(rule.path, error) : pass();
2295
+ }
2296
+ if (rule.op === "regex") return typeof selected.value === "string" && new RegExp(rule.pattern, `${rule.flags ?? ""}u`).test(selected.value) ? pass() : fail(rule.path, "value does not match");
2297
+ if (rule.op === "range") return typeof selected.value === "number" && Number.isFinite(selected.value) && (rule.min === void 0 || selected.value >= rule.min) && (rule.max === void 0 || selected.value <= rule.max) ? pass() : fail(rule.path, "value is outside range");
2298
+ if (rule.op === "equals") return canonicalJson(selected.value) === canonicalJson(rule.value) ? pass() : fail(rule.path, "value is not equal");
2299
+ if (rule.op === "contains") {
2300
+ 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));
2301
+ return contains ? pass() : fail(rule.path, "value is not contained");
2302
+ }
2303
+ const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record7(item)?.name ?? "")) : [];
2304
+ const sequence = rule.mode === "exact" ? names.length === rule.expected.length && names.every((name, index) => name === rule.expected[index]) : rule.expected.reduce((cursor, expected) => {
2305
+ const index = names.indexOf(expected, cursor);
2306
+ return index < 0 ? Number.POSITIVE_INFINITY : index + 1;
2307
+ }, 0) !== Number.POSITIVE_INFINITY;
2308
+ return sequence ? pass() : fail(rule.path, "tool sequence does not match");
2309
+ }
2310
+ function evaluateCodeScorer(raw, subject) {
2311
+ const ir = codeScorerIR(raw);
2312
+ const result = evaluate(ir.rule, subject);
2313
+ return {
2314
+ score: result.pass ? 1 : 0,
2315
+ pass: result.pass,
2316
+ dimensions: null,
2317
+ evidence: { rule: canonicalJson(ir.rule), checks: result.checks, failures: result.failures.slice(0, 64) }
2318
+ };
2319
+ }
2320
+
2321
+ // src/errors.ts
2322
+ var GateExhausted = class extends Error {
2323
+ constructor(record8) {
2324
+ super("turn gate exhausted");
2325
+ this.record = record8;
2326
+ this.name = "GateExhausted";
2327
+ }
2328
+ record;
2329
+ };
2330
+ var CommitGateRejected = class extends Error {
2331
+ constructor(evaluation) {
2332
+ super("commit gate rejected the artifact");
2333
+ this.evaluation = evaluation;
2334
+ this.name = "CommitGateRejected";
2335
+ }
2336
+ evaluation;
2337
+ };
2338
+ var SpawnCardinality = class extends Error {
2339
+ constructor(message = "spawn cardinality exceeds the configured cap; use map") {
2340
+ super(message);
2341
+ this.name = "SpawnCardinality";
2342
+ }
2343
+ };
2344
+ var NondeterministicReplay = class extends Error {
2345
+ constructor(pos, expected, actual) {
2346
+ super(`nondeterministic replay at ${pos}`);
2347
+ this.pos = pos;
2348
+ this.expected = expected;
2349
+ this.actual = actual;
2350
+ this.name = "NondeterministicReplay";
2351
+ }
2352
+ pos;
2353
+ expected;
2354
+ actual;
2355
+ };
2356
+ var OutcomeUnknown = class extends Error {
2357
+ constructor(pos, effect) {
2358
+ super(`effect outcome is unknown at ${pos}`);
2359
+ this.pos = pos;
2360
+ this.effect = effect;
2361
+ this.name = "OutcomeUnknown";
2362
+ }
2363
+ pos;
2364
+ effect;
2365
+ };
2366
+ var LeaseLost = class extends Error {
2367
+ constructor(message = "invocation lease is no longer current") {
2368
+ super(message);
2369
+ this.name = "LeaseLost";
2370
+ }
2371
+ };
2372
+ var AfterYield = class extends Error {
2373
+ constructor() {
2374
+ super("ctx operation attempted after invocation yield");
2375
+ this.name = "AfterYield";
2376
+ }
2377
+ };
2378
+ var SwallowedYield = class extends Error {
2379
+ constructor() {
2380
+ super("invocation yield was swallowed by tenant code");
2381
+ this.name = "SwallowedYield";
2382
+ }
2383
+ };
2384
+ var RollbackTargetInvalid = class extends Error {
2385
+ constructor(target) {
2386
+ super(`invalid rollback target: ${target}`);
2387
+ this.target = target;
2388
+ this.name = "RollbackTargetInvalid";
2389
+ }
2390
+ target;
2391
+ };
2392
+ var CommitConflict = class extends Error {
2393
+ constructor(expected, actual) {
2394
+ super("ledger head does not match expectedHead");
2395
+ this.expected = expected;
2396
+ this.actual = actual;
2397
+ this.name = "CommitConflict";
2398
+ }
2399
+ expected;
2400
+ actual;
2401
+ };
2402
+ var ResourceInvalid = class extends Error {
2403
+ constructor(resource) {
2404
+ super(`invalid resource: ${resource}`);
2405
+ this.resource = resource;
2406
+ this.name = "ResourceInvalid";
2407
+ }
2408
+ resource;
2409
+ };
2410
+ var ResourceUnbound = class extends Error {
2411
+ constructor(resource) {
2412
+ super(`resource is not bound to this execution: ${resource}`);
2413
+ this.resource = resource;
2414
+ this.name = "ResourceUnbound";
2415
+ }
2416
+ resource;
2417
+ };
2418
+ var ToolUnavailable = class extends Error {
2419
+ constructor(tool) {
2420
+ super(`Tool is not enabled for this Agent deployment: ${tool}`);
2421
+ this.tool = tool;
2422
+ this.name = "ToolUnavailable";
2423
+ }
2424
+ tool;
2425
+ };
2426
+ var UnknownTool = class extends Error {
2427
+ constructor(tool) {
2428
+ super(`model emitted a Tool that was not offered: ${tool}`);
2429
+ this.tool = tool;
2430
+ this.name = "UnknownTool";
2431
+ }
2432
+ tool;
2433
+ };
2434
+ var EffectCeilingExceeded = class extends Error {
2435
+ constructor(ceiling, observed) {
2436
+ super(`effect ${observed} exceeds ceiling ${ceiling}`);
2437
+ this.ceiling = ceiling;
2438
+ this.observed = observed;
2439
+ this.name = "EffectCeilingExceeded";
2440
+ }
2441
+ ceiling;
2442
+ observed;
2443
+ };
2444
+ var ResourceDisabled = class extends Error {
2445
+ constructor(resource) {
2446
+ super(`resource is disabled: ${resource}`);
2447
+ this.resource = resource;
2448
+ this.name = "ResourceDisabled";
2449
+ }
2450
+ resource;
2451
+ };
2452
+ var PolicyDecisionFailed = class extends Error {
2453
+ constructor(decisionHash, message = "Policy denied operation") {
2454
+ super(message);
2455
+ this.decisionHash = decisionHash;
2456
+ this.name = "PolicyDecisionFailed";
2457
+ }
2458
+ decisionHash;
2459
+ };
2460
+ var PolicyConstraintFailed = class extends PolicyDecisionFailed {
2461
+ constructor(decisionHash, message = "Policy constraint rejected operation") {
2462
+ super(decisionHash, message);
2463
+ this.name = "PolicyConstraintFailed";
2464
+ }
2465
+ };
2466
+ var CredentialUnavailable = class extends Error {
2467
+ constructor(credential) {
2468
+ super(`Credential is unavailable: ${credential}`);
2469
+ this.credential = credential;
2470
+ this.name = "CredentialUnavailable";
2471
+ }
2472
+ credential;
2473
+ };
2474
+ var CredentialRevoked = class extends Error {
2475
+ constructor(credential, version) {
2476
+ super(`Credential is revoked: ${credential}`);
2477
+ this.credential = credential;
2478
+ this.version = version;
2479
+ this.name = "CredentialRevoked";
2480
+ }
2481
+ credential;
2482
+ version;
2483
+ };
2484
+ var DirectNetworkDenied = class extends Error {
2485
+ constructor() {
2486
+ super("tenant direct network access is denied; use ctx.invoke on a bound resource");
2487
+ this.name = "DirectNetworkDenied";
2488
+ }
2489
+ };
2490
+ var SessionDeleted = class extends Error {
2491
+ constructor(session) {
2492
+ super(`session is deleted: ${session}`);
2493
+ this.session = session;
2494
+ this.name = "SessionDeleted";
2495
+ }
2496
+ session;
2497
+ };
2498
+ export {
2499
+ AfterYield,
2500
+ ApiError,
2501
+ CommitConflict,
2502
+ CommitGateRejected,
2503
+ CredentialRevoked,
2504
+ CredentialUnavailable,
2505
+ DirectNetworkDenied,
2506
+ EffectCeilingExceeded,
2507
+ GateExhausted,
2508
+ IntegrationRequestNotSent,
2509
+ LeaseLost,
2510
+ MCP_CLIENT_CAPABILITY,
2511
+ MEMORY_OPERATION_DECLARATIONS,
2512
+ MODEL_CHECKPOINT_IMPORT_CAPABILITY,
2513
+ MODEL_COMPLETION_CAPABILITY,
2514
+ NondeterministicReplay,
2515
+ OutcomeUnknown,
2516
+ PolicyConstraintFailed,
2517
+ PolicyDecisionFailed,
2518
+ ResourceDisabled,
2519
+ ResourceInvalid,
2520
+ ResourceUnbound,
2521
+ RollbackTargetInvalid,
2522
+ SessionDeleted,
2523
+ SpawnCardinality,
2524
+ SwallowedYield,
2525
+ TRAINING_PROVIDER_CAPABILITY,
2526
+ TerminalIntegrationFailure,
2527
+ ToolUnavailable,
2528
+ UnknownTool,
2529
+ action,
2530
+ actionPattern,
2531
+ agent,
2532
+ agentResourceBinding,
2533
+ analyticsEvent,
2534
+ approximateTokens,
2535
+ authProvider,
2536
+ authProviderName,
2537
+ bindingName,
2538
+ bucketFor,
2539
+ canonicalJson,
2540
+ capabilityContractRef,
2541
+ casTool,
2542
+ channel,
2543
+ checkpointArtifactRef,
2544
+ checkpointDeploymentRequest,
2545
+ checkpointImportMetadata,
2546
+ checkpointImportRequest,
2547
+ codeScorerIR,
2548
+ credentialInteractionAction,
2549
+ credentialInteractionEvent,
2550
+ credentialInteractionResult,
2551
+ credentialName,
2552
+ credentialProvider,
2553
+ credentialProviderConfigSchema,
2554
+ credentialProviderName,
2555
+ credentialProviderSetupMetadata,
2556
+ credentialRotationDefaults,
2557
+ customerTenantName,
2558
+ cutBatches,
2559
+ cutPartitions,
2560
+ datasetName,
2561
+ evaluateCodeScorer,
2562
+ evaluatePolicyDefinition,
2563
+ gateway,
2564
+ gatewayModelOffer,
2565
+ gatewayPackageMetadata,
2566
+ hash,
2567
+ hashValue,
2568
+ integrationEgressPolicy,
2569
+ labelSelector,
2570
+ matchesAction,
2571
+ matchesLabelSelector,
2572
+ matchesResource,
2573
+ memoryStoreBinding,
2574
+ modelAdvertisedPricing,
2575
+ modelControls,
2576
+ modelGatewayBinding,
2577
+ modelGatewayEndpoint,
2578
+ modelLimit,
2579
+ modelPrompt,
2580
+ modelProtocolRequest,
2581
+ modelProtocolResult,
2582
+ murmur3_32,
2583
+ normalizeModelGatewayConfig,
2584
+ normalizeSandboxNetworkPolicy,
2585
+ opTool,
2586
+ opTools,
2587
+ parseResourceName,
2588
+ policy,
2589
+ policyName,
2590
+ renderTrainingCompletion,
2591
+ resolveGatewayEgress,
2592
+ resourceContractRef,
2593
+ resourceCredentialBinding,
2594
+ resourceLabelMap,
2595
+ resourceName,
2596
+ resourceNeed,
2597
+ resourcePattern,
2598
+ resourceSelector,
2599
+ sandboxControls,
2600
+ sandboxLimit,
2601
+ scopedBindingKey,
2602
+ scopedCredentialRef,
2603
+ scopedResourceRef,
2604
+ scorerName,
2605
+ sha256Hex,
2606
+ stageOutput,
2607
+ startTrainingRequest,
2608
+ subtask,
2609
+ tableDescribe,
2610
+ tableQuery,
2611
+ trainingProvider,
2612
+ trainingProviderMetadata,
2613
+ trainingRecipe,
2614
+ validateBatchSpec,
2615
+ validateFoldFn,
2616
+ validateJsonSchema,
2617
+ validateJsonSchemaDefinition,
2618
+ validatePartitionFn,
2619
+ validatePartitionSpec,
2620
+ validateStageOutputSpec,
2621
+ validateTool,
2622
+ validateView,
2623
+ webFetch,
2624
+ webSearch
2625
+ };