@constal/sdk 3.2.0 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/publish/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // src/hash.ts
1
+ // packages/sdk/src/hash.ts
2
2
  var encoder = new TextEncoder();
3
3
  function canonicalNumber(value) {
4
4
  if (!Number.isFinite(value)) throw new TypeError("canonical JSON does not support non-finite numbers");
@@ -12,8 +12,8 @@ function canonicalJson(value) {
12
12
  if (typeof value === "string") return JSON.stringify(value);
13
13
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
14
14
  if (typeof value === "object") {
15
- const record9 = value;
16
- return `{${Object.keys(record9).sort().filter((key) => record9[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(record9[key])}`).join(",")}}`;
15
+ const record10 = value;
16
+ return `{${Object.keys(record10).sort().filter((key) => record10[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(record10[key])}`).join(",")}}`;
17
17
  }
18
18
  throw new TypeError(`canonical JSON does not support ${typeof value}`);
19
19
  }
@@ -67,7 +67,7 @@ function bucketFor(value, buckets) {
67
67
  return murmur3_32(canonicalJson(value)) % buckets;
68
68
  }
69
69
 
70
- // src/partition.ts
70
+ // packages/sdk/src/partition.ts
71
71
  var encoder2 = new TextEncoder();
72
72
  function positiveSafeInteger(value) {
73
73
  return Number.isSafeInteger(value) && Number(value) > 0;
@@ -149,25 +149,25 @@ function cutBatches(rows, spec) {
149
149
  return cutPartitions(rows, spec);
150
150
  }
151
151
 
152
- // src/analytics.ts
152
+ // packages/sdk/src/analytics.ts
153
153
  var EVENT_ID = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/u;
154
154
  var FIELD_ID = /^[a-z][a-z0-9_]{0,63}$/u;
155
155
  var VERSION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
156
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]]) {
157
+ function analyticsEvent(definition2) {
158
+ if (typeof definition2.id !== "string" || definition2.id.length > 128 || !EVENT_ID.test(definition2.id)) throw new TypeError("analytics event id is invalid");
159
+ if (RESERVED.has(definition2.id.split(/[.-]/u)[0])) throw new TypeError("analytics event id uses a reserved namespace");
160
+ if (typeof definition2.version !== "string" || !VERSION.test(definition2.version)) throw new TypeError("analytics event version is invalid");
161
+ for (const [kind, fields] of [["dimensions", definition2.dimensions], ["metrics", definition2.metrics]]) {
162
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
163
  if (new Set(fields).size !== fields.length) throw new TypeError(`analytics event ${kind} must be unique`);
164
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]) });
165
+ const metricNames = new Set(definition2.metrics);
166
+ if (definition2.dimensions.some((field2) => metricNames.has(field2))) throw new TypeError("analytics dimension and metric names must not overlap");
167
+ return Object.freeze({ ...definition2, dimensions: Object.freeze([...definition2.dimensions]), metrics: Object.freeze([...definition2.metrics]) });
168
168
  }
169
169
 
170
- // src/schema.ts
170
+ // packages/sdk/src/schema.ts
171
171
  var KEYWORDS = /* @__PURE__ */ new Set([
172
172
  "$schema",
173
173
  "$id",
@@ -276,21 +276,21 @@ function validateJsonSchema(value, schema, path = "$") {
276
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
277
  }
278
278
  if (value && typeof value === "object" && !Array.isArray(value)) {
279
- const record9 = value;
280
- for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in record9)) return `${path}.${key} is required`;
279
+ const record10 = value;
280
+ for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in record10)) return `${path}.${key} is required`;
281
281
  const properties = rule.properties && typeof rule.properties === "object" && !Array.isArray(rule.properties) ? rule.properties : {};
282
- if (typeof rule.minProperties === "number" && Object.keys(record9).length < rule.minProperties) return `${path} has too few properties`;
283
- if (typeof rule.maxProperties === "number" && Object.keys(record9).length > rule.maxProperties) return `${path} has too many properties`;
282
+ if (typeof rule.minProperties === "number" && Object.keys(record10).length < rule.minProperties) return `${path} has too few properties`;
283
+ if (typeof rule.maxProperties === "number" && Object.keys(record10).length > rule.maxProperties) return `${path} has too many properties`;
284
284
  if (rule.additionalProperties === false) {
285
- const extra = Object.keys(record9).find((key) => !(key in properties));
285
+ const extra = Object.keys(record10).find((key) => !(key in properties));
286
286
  if (extra) return `${path}.${extra} is not allowed`;
287
287
  }
288
- for (const [key, child] of Object.entries(properties)) if (key in record9) {
289
- const error = validateJsonSchema(record9[key], child, `${path}.${key}`);
288
+ for (const [key, child] of Object.entries(properties)) if (key in record10) {
289
+ const error = validateJsonSchema(record10[key], child, `${path}.${key}`);
290
290
  if (error) return error;
291
291
  }
292
- if (rule.additionalProperties && typeof rule.additionalProperties === "object") for (const key of Object.keys(record9).filter((candidate) => !(candidate in properties))) {
293
- const error = validateJsonSchema(record9[key], rule.additionalProperties, `${path}.${key}`);
292
+ if (rule.additionalProperties && typeof rule.additionalProperties === "object") for (const key of Object.keys(record10).filter((candidate) => !(candidate in properties))) {
293
+ const error = validateJsonSchema(record10[key], rule.additionalProperties, `${path}.${key}`);
294
294
  if (error) return error;
295
295
  }
296
296
  }
@@ -309,7 +309,7 @@ function validateJsonSchema(value, schema, path = "$") {
309
309
  return null;
310
310
  }
311
311
 
312
- // src/selector.ts
312
+ // packages/sdk/src/selector.ts
313
313
  var PROTECTED_RESOURCE_LABEL_PREFIX = "constal.ai/";
314
314
  var RESOURCE_IDENTITY_LABELS = {
315
315
  crn: "constal.ai/crn",
@@ -406,7 +406,7 @@ function selectableResourceLabels(input) {
406
406
  return resourceLabelMap(labels, { allowProtected: true });
407
407
  }
408
408
 
409
- // src/resources.ts
409
+ // packages/sdk/src/resources.ts
410
410
  var RESOURCE_KINDS = [
411
411
  "agent",
412
412
  "channel",
@@ -466,6 +466,15 @@ function resolveBindingOwner(scope2, context, required2 = true) {
466
466
  }
467
467
  return scope2 === "principal" ? { kind: "principal", principal: name } : { kind: "customer", customer: name };
468
468
  }
469
+ var RESOURCE_CREDENTIAL_BINDING_SCHEMA = { anyOf: [
470
+ { type: "string", minLength: 1, description: "An existing Credential resource CRN." },
471
+ { type: "object", required: ["kind", "key", "owner", "required"], additionalProperties: false, properties: {
472
+ kind: { const: "scoped" },
473
+ key: { type: "string", minLength: 1 },
474
+ owner: { enum: ["tenant", "principal", "customer"] },
475
+ required: { type: "boolean" }
476
+ } }
477
+ ] };
469
478
  function agentSetupRequirements(value, options = {}) {
470
479
  if (!Array.isArray(value) || value.length < 1 || value.length > 64) throw new TypeError("Agent setup requirements are invalid");
471
480
  const requirements = value.map((raw) => {
@@ -569,11 +578,11 @@ function modelGatewayBinding(value) {
569
578
  const candidate = record2(value);
570
579
  if (!candidate) throw new TypeError("Model Gateway binding is invalid");
571
580
  if (candidate.kind === "fixed") {
572
- const resource = record2(candidate.resource);
573
- 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))) {
581
+ const resource2 = record2(candidate.resource);
582
+ if (!resource2 || typeof resource2.crn !== "string" || typeof resource2.hash !== "string" || !HASH.test(resource2.hash) || Object.keys(resource2).some((key) => !["crn", "hash"].includes(key)) || Object.keys(candidate).some((key) => !["kind", "resource", "contract"].includes(key))) {
574
583
  throw new TypeError("fixed Model Gateway binding is invalid");
575
584
  }
576
- const parts = parseResourceName(resource.crn);
585
+ const parts = parseResourceName(resource2.crn);
577
586
  if (!INVOKABLE_KIND_SET.has(parts.kind) || parts.kind === "model" || parts.kind === "memory") {
578
587
  throw new TypeError("Model Gateway must reference a Connection Resource");
579
588
  }
@@ -595,11 +604,11 @@ function memoryStoreBinding(value) {
595
604
  const candidate = record2(value);
596
605
  if (!candidate) throw new TypeError("Memory Store binding is invalid");
597
606
  if (candidate.kind === "fixed") {
598
- const resource = record2(candidate.resource);
599
- 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))) {
607
+ const resource2 = record2(candidate.resource);
608
+ if (!resource2 || typeof resource2.crn !== "string" || typeof resource2.hash !== "string" || !HASH.test(resource2.hash) || Object.keys(resource2).some((key) => !["crn", "hash"].includes(key)) || Object.keys(candidate).some((key) => !["kind", "resource", "contract"].includes(key))) {
600
609
  throw new TypeError("fixed Memory Store binding is invalid");
601
610
  }
602
- const parts = parseResourceName(resource.crn);
611
+ const parts = parseResourceName(resource2.crn);
603
612
  if (!INVOKABLE_KIND_SET.has(parts.kind) || parts.kind === "model" || parts.kind === "memory") {
604
613
  throw new TypeError("Memory Store must reference a Connection Resource");
605
614
  }
@@ -640,6 +649,14 @@ function resourceCredentialBinding(value) {
640
649
  if (typeof value === "string") return credentialName(value);
641
650
  return scopedCredentialRef(value);
642
651
  }
652
+ function resourceCredentialBindings(value) {
653
+ const bindings = record2(value);
654
+ if (!bindings) throw new TypeError("credential bindings must be an object");
655
+ return Object.fromEntries(Object.entries(bindings).map(([slot, binding]) => {
656
+ if (!NAME2.test(slot)) throw new TypeError("credential slot is invalid");
657
+ return [slot, structuredClone(resourceCredentialBinding(binding))];
658
+ }));
659
+ }
643
660
  function validateRotationDefaults(value) {
644
661
  const candidate = record2(value);
645
662
  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");
@@ -833,12 +850,12 @@ function normalizeCidrs(values, allowPrivate) {
833
850
  })) throw new TypeError("sandbox network CIDR intersects a reserved range");
834
851
  return { network, prefix, last, text: `${ipv4Text(network)}/${prefix}` };
835
852
  }).sort((left, right) => left.network - right.network || left.prefix - right.prefix);
836
- const result = [];
853
+ const result2 = [];
837
854
  for (const entry of entries) {
838
- if (result.some((prior) => entry.network >= prior.network && entry.last <= prior.last)) continue;
839
- result.push(entry);
855
+ if (result2.some((prior) => entry.network >= prior.network && entry.last <= prior.last)) continue;
856
+ result2.push(entry);
840
857
  }
841
- return result.map((entry) => entry.text);
858
+ return result2.map((entry) => entry.text);
842
859
  }
843
860
  function normalizeDomains(values) {
844
861
  if (!Array.isArray(values) || values.length === 0 || values.length > 20) throw new TypeError("sandbox network domains must contain 1 to 20 entries");
@@ -892,7 +909,7 @@ function normalizeSandboxNetworkPolicy(value, options = {}) {
892
909
  throw new TypeError("sandbox network policy mode is invalid");
893
910
  }
894
911
 
895
- // src/definitions.ts
912
+ // packages/sdk/src/definitions.ts
896
913
  function requiredString(value, path) {
897
914
  if (typeof value !== "string" || value.trim() === "") throw new TypeError(`${path} must be a non-empty string`);
898
915
  }
@@ -900,14 +917,14 @@ function validateExecutable(value, path) {
900
917
  requiredString(value.id, `${path}.id`);
901
918
  requiredString(value.version, `${path}.version`);
902
919
  }
903
- function validateTool(tool, path = "tool") {
904
- requiredString(tool.name, `${path}.name`);
905
- requiredString(tool.version, `${path}.version`);
906
- if (!["read-only", "idempotent", "reconcilable", "non-idempotent"].includes(tool.maxEffect)) throw new TypeError(`${path}.maxEffect is invalid`);
907
- tool.needs?.forEach(resourceNeed);
908
- if (tool.preview !== void 0 && typeof tool.preview !== "function") throw new TypeError(`${path}.preview must be a function`);
909
- if (typeof tool.run !== "function") throw new TypeError(`${path}.run must be a function`);
910
- return tool;
920
+ function validateTool(tool2, path = "tool") {
921
+ requiredString(tool2.name, `${path}.name`);
922
+ requiredString(tool2.version, `${path}.version`);
923
+ if (!["read-only", "idempotent", "reconcilable", "non-idempotent"].includes(tool2.maxEffect)) throw new TypeError(`${path}.maxEffect is invalid`);
924
+ tool2.needs?.forEach(resourceNeed);
925
+ if (tool2.preview !== void 0 && typeof tool2.preview !== "function") throw new TypeError(`${path}.preview must be a function`);
926
+ if (typeof tool2.run !== "function") throw new TypeError(`${path}.run must be a function`);
927
+ return tool2;
911
928
  }
912
929
  function validateView(view, path = "view") {
913
930
  validateExecutable(view, path);
@@ -948,11 +965,11 @@ function agent(input) {
948
965
  def.partitionFns?.forEach((fn) => validatePartitionFn(fn));
949
966
  def.foldFns?.forEach((fn) => validateFoldFn(fn));
950
967
  def.analytics?.forEach((event) => analyticsEvent(event));
951
- for (const [localName, tool] of Object.entries(def.tools ?? {})) {
952
- if (localName !== tool.name) throw new TypeError(`agent.tools.${localName} must match Tool.name`);
953
- validateTool(tool, `agent.tools.${localName}`);
968
+ for (const [localName, tool2] of Object.entries(def.tools ?? {})) {
969
+ if (localName !== tool2.name) throw new TypeError(`agent.tools.${localName} must match Tool.name`);
970
+ validateTool(tool2, `agent.tools.${localName}`);
954
971
  }
955
- if (new Set(Object.values(def.tools ?? {}).map((tool) => tool.name)).size !== Object.keys(def.tools ?? {}).length) {
972
+ if (new Set(Object.values(def.tools ?? {}).map((tool2) => tool2.name)).size !== Object.keys(def.tools ?? {}).length) {
956
973
  throw new TypeError("agent Tool names must be unique");
957
974
  }
958
975
  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");
@@ -969,16 +986,16 @@ function subtask(def) {
969
986
  return def;
970
987
  }
971
988
 
972
- // src/auth-provider.ts
973
- function authProvider(definition) {
974
- if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition.id)) throw new TypeError("authProvider.id is invalid");
975
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition.version)) throw new TypeError("authProvider.version is invalid");
976
- if (typeof definition.authenticate !== "function") throw new TypeError("authProvider.authenticate must be a function");
977
- definition.needs?.forEach(resourceNeed);
978
- return definition;
989
+ // packages/sdk/src/auth-provider.ts
990
+ function authProvider(definition2) {
991
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition2.id)) throw new TypeError("authProvider.id is invalid");
992
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition2.version)) throw new TypeError("authProvider.version is invalid");
993
+ if (typeof definition2.authenticate !== "function") throw new TypeError("authProvider.authenticate must be a function");
994
+ definition2.needs?.forEach(resourceNeed);
995
+ return definition2;
979
996
  }
980
997
 
981
- // src/channel.ts
998
+ // packages/sdk/src/channel.ts
982
999
  function required(value, path) {
983
1000
  if (typeof value !== "string" || value.trim() === "") throw new TypeError(`${path} must be a non-empty string`);
984
1001
  }
@@ -986,21 +1003,21 @@ function executable(value, path) {
986
1003
  required(value.id, `${path}.id`);
987
1004
  required(value.version, `${path}.version`);
988
1005
  }
989
- function channel(definition) {
990
- executable(definition, "channel");
991
- executable(definition.protocol, "channel.protocol");
992
- 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" || definition.protocol.authorizeSubscription !== void 0 && typeof definition.protocol.authorizeSubscription !== "function") {
1006
+ function channel(definition2) {
1007
+ executable(definition2, "channel");
1008
+ executable(definition2.protocol, "channel.protocol");
1009
+ if (typeof definition2.protocol.receive !== "function" || typeof definition2.protocol.respond !== "function" || definition2.protocol.send !== void 0 && typeof definition2.protocol.send !== "function" || definition2.protocol.alarm !== void 0 && typeof definition2.protocol.alarm !== "function" || definition2.protocol.authorizeSubscription !== void 0 && typeof definition2.protocol.authorizeSubscription !== "function") {
993
1010
  throw new TypeError("channel.protocol must define receive and respond; optional handlers must be functions");
994
1011
  }
995
- resourceDependencyRef(definition.authProvider, ["auth-provider"]);
996
- definition.needs?.forEach(resourceNeed);
997
- const analytics = definition.analytics ?? [];
1012
+ resourceDependencyRef(definition2.authProvider, ["auth-provider"]);
1013
+ definition2.needs?.forEach(resourceNeed);
1014
+ const analytics = definition2.analytics ?? [];
998
1015
  analytics.forEach((event) => analyticsEvent(event));
999
1016
  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");
1000
- return definition;
1017
+ return definition2;
1001
1018
  }
1002
1019
 
1003
- // src/ui.ts
1020
+ // packages/sdk/src/ui.ts
1004
1021
  var PATH2 = /^(?!\/)(?!.*(?:^|\/)\.\.?\/?)(?!.*\/\/)[A-Za-z0-9._~/-]{1,256}$/u;
1005
1022
  var CONTENT_TYPE = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:; charset=utf-8)?$/u;
1006
1023
  var BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
@@ -1013,8 +1030,8 @@ var UI_BUNDLE_BOUNDS = Object.freeze({
1013
1030
  maximumFileBytes: 4194304,
1014
1031
  maximumExpandedBytes: 16777216
1015
1032
  });
1016
- function object(value, message) {
1017
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError(message);
1033
+ function object(value, message2) {
1034
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError(message2);
1018
1035
  return value;
1019
1036
  }
1020
1037
  function exactKeys(value, allowed, required2) {
@@ -1118,7 +1135,7 @@ function uiBundle(value, execution) {
1118
1135
  return { manifest, modules: normalizedModules, assets: normalizedAssets };
1119
1136
  }
1120
1137
 
1121
- // src/ingress.ts
1138
+ // packages/sdk/src/ingress.ts
1122
1139
  var encoder3 = new TextEncoder();
1123
1140
  function object2(value) {
1124
1141
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
@@ -1177,7 +1194,7 @@ function channelIngressRequest(value) {
1177
1194
  return { method: input.method, url: input.url, headers, bodyBase64: input.bodyBase64 };
1178
1195
  }
1179
1196
 
1180
- // src/setup-workflow.ts
1197
+ // packages/sdk/src/setup-workflow.ts
1181
1198
  var ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1182
1199
  var MAX_SCREEN_BYTES = 262144;
1183
1200
  function record3(value) {
@@ -1205,9 +1222,9 @@ function actions(value) {
1205
1222
  function panelBase(source) {
1206
1223
  const id2 = text(source.id, 63);
1207
1224
  const title = text(source.title, 256);
1208
- const description = text(source.description, 4096, true);
1225
+ const description2 = text(source.description, 4096, true);
1209
1226
  const parsedActions = actions(source.actions);
1210
- return id2 && ID.test(id2) && title && description !== null && parsedActions ? { id: id2, title, description, actions: parsedActions } : null;
1227
+ return id2 && ID.test(id2) && title && description2 !== null && parsedActions ? { id: id2, title, description: description2, actions: parsedActions } : null;
1211
1228
  }
1212
1229
  function panel(value) {
1213
1230
  const source = record3(value);
@@ -1466,7 +1483,7 @@ function setupScreenView(id2 = "setup-screen") {
1466
1483
  };
1467
1484
  }
1468
1485
 
1469
- // src/agent-setup.ts
1486
+ // packages/sdk/src/agent-setup.ts
1470
1487
  function credentialSetupState(requirement, scope2, inventory, binding) {
1471
1488
  const parsed = agentSetupRequirements([requirement])[0];
1472
1489
  if (parsed.resourceKind !== "credential") throw new TypeError("Credential setup requires a Credential requirement");
@@ -1509,270 +1526,734 @@ function credentialSetupState(requirement, scope2, inventory, binding) {
1509
1526
  };
1510
1527
  }
1511
1528
 
1512
- // src/constal-api.ts
1513
- var CONSTAL_API_CAPABILITY = "constal.api";
1514
- var CONSTAL_API_VERSION = "1";
1515
- var CONSTAL_API_OPERATIONS = [
1516
- "describe",
1517
- "query",
1518
- "get",
1519
- "relations",
1520
- "explainPolicy",
1521
- "plan",
1522
- "apply",
1523
- "observe"
1524
- ];
1525
- var CONSTAL_API_BOUNDS = {
1526
- defaultPageSize: 50,
1527
- maximumPageSize: 200,
1528
- maximumRelationDepth: 3,
1529
- maximumPlanOperations: 64,
1530
- maximumInputBytes: 1048576,
1531
- planTtlMs: 15 * 6e4
1532
- };
1533
- var CONSTAL_API_QUERY_KINDS = [
1534
- ...RESOURCE_KINDS,
1535
- "analytics",
1536
- "customer",
1537
- "binding",
1538
- "session",
1539
- "run",
1540
- "deployment",
1541
- "documentation",
1542
- "analytics-event",
1543
- "namespace",
1544
- "team-member",
1545
- "team-invite",
1546
- "api-key",
1547
- "billing-account",
1548
- "invoice",
1549
- "subscription",
1550
- "resource-contract",
1551
- "dataset-draft",
1552
- "dataset-case",
1553
- "eval-score",
1554
- "eval-sample",
1555
- "eval-policy",
1556
- "eval-suite",
1557
- "eval-baseline",
1558
- "eval-schedule",
1559
- "training-job",
1560
- "checkpoint",
1561
- "training-provider",
1562
- "training-model",
1563
- "checkpoint-gateway",
1564
- "credential-provider-package",
1565
- "credential-consumer",
1566
- "credential-use",
1567
- "credential-event",
1568
- "gateway-package",
1569
- "rollout",
1570
- "wait"
1571
- ];
1572
- var CONSTAL_API_GET_KINDS = CONSTAL_API_QUERY_KINDS;
1573
- var CONSTAL_API_MODEL_TOOL_DESCRIPTIONS = {
1574
- query: "Query authorized Constal objects with bounded pagination and evidence. Select the exact lower-case singular kind from the schema enum; never pluralize, recase, or substitute an abstract kind. If context supplies platformToolContract.queryScope, copy it unchanged. Otherwise use only an exact namespace allowed by the delegated Run authority, and tenant scope only for an explicitly tenant-wide request. Use catalog-advertised fields and filters; constrained kinds require their advertised filter. Preserve next and evidence completeness.",
1575
- get: "Retrieve one exact authorized Constal object or immutable revision. Pass a complete ref unchanged from query, relations, runtime inspection, or a governed receipt; never construct a kind, id, namespace, CRN, hash, or cursor from display text. The schema enum contains every supported addressable kind. For a Run, omit fields for complete diagnosis or request only documented top-level fields, and follow only the returned page cursor."
1576
- };
1577
- var CONSTAL_API_GET_CRN_KINDS = [
1578
- ...RESOURCE_KINDS,
1579
- "analytics",
1580
- "binding",
1581
- "session",
1582
- "run",
1583
- "deployment"
1584
- ];
1585
- var CONSTAL_API_OBJECT_REF_CRN_KINDS = [...CONSTAL_API_GET_CRN_KINDS, "customer"];
1586
- var boundedNameSchema = { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z][A-Za-z0-9._-]{0,127}$" };
1587
- var namespaceSchema = {
1588
- type: "string",
1589
- minLength: 1,
1590
- maxLength: 128,
1591
- pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
1592
- };
1593
- var actionSchema = { type: "string", pattern: ACTION_PATTERN.source };
1594
- var boundedIdSchema = { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9][A-Za-z0-9._~:-]{0,255}$" };
1595
- var hashSchema = { type: "string", pattern: "^[a-f0-9]{64}$" };
1596
- var stringListSchema = { type: "array", maxItems: 128, items: { type: "string", minLength: 1, maxLength: 256 } };
1597
- var scopeSchema = { description: "Use namespace with an exact namespace allowed by the delegated Run authority. Use tenant only for an explicitly tenant-wide request.", anyOf: [
1598
- {
1599
- type: "object",
1600
- required: ["kind", "namespace"],
1601
- additionalProperties: false,
1602
- properties: { kind: { const: "namespace" }, namespace: {
1603
- ...namespaceSchema,
1604
- description: "Exact authorized namespace. Do not infer it from an object name or repository."
1605
- } }
1606
- },
1607
- { type: "object", required: ["kind"], additionalProperties: false, properties: { kind: { const: "tenant" } } }
1608
- ] };
1609
- var crnPattern = (kinds) => `^crn:constal:[a-z0-9][a-z0-9._-]{0,127}:[a-z0-9][a-z0-9._-]{0,127}:[a-z0-9][a-z0-9._-]{0,127}:(?:${kinds.join("|")})/[A-Za-z0-9._~/%-]{1,512}$`;
1610
- var objectRefSchema = { type: "object", additionalProperties: false, properties: {
1611
- kind: { enum: [...CONSTAL_API_GET_KINDS], description: "Exact lower-case object kind returned by a governed platform result." },
1612
- id: { type: "string", minLength: 1, maxLength: 512 },
1613
- crn: { anyOf: [{ type: "null" }, {
1614
- type: "string",
1615
- minLength: 1,
1616
- maxLength: 2048,
1617
- pattern: crnPattern(CONSTAL_API_OBJECT_REF_CRN_KINDS)
1618
- }] },
1619
- hash: { anyOf: [{ type: "null" }, hashSchema] },
1620
- namespace: {
1621
- type: ["string", "null"],
1622
- maxLength: 128,
1623
- pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
1624
- },
1625
- version: { type: ["string", "null"], maxLength: 128 }
1626
- }, required: ["kind", "id", "namespace"] };
1627
- var exactGetCrnSchema = {
1628
- type: "string",
1629
- minLength: 1,
1630
- maxLength: 2048,
1631
- description: "Exact addressable CRN obtained from governed platform evidence.",
1632
- pattern: crnPattern(CONSTAL_API_GET_CRN_KINDS)
1633
- };
1634
- var CONSTAL_API_OPERATION_SCHEMAS = {
1635
- describe: { type: "object", additionalProperties: false, properties: {
1636
- domains: stringListSchema,
1637
- kinds: stringListSchema,
1638
- operations: stringListSchema,
1639
- include: {
1640
- type: "array",
1641
- maxItems: 5,
1642
- uniqueItems: true,
1643
- items: { enum: ["objects", "operations", "relations", "schemas", "docs"] }
1529
+ // packages/sdk/src/skills.ts
1530
+ function description(value) {
1531
+ if (!value || typeof value.id !== "string" || !value.id || value.description !== void 0 && typeof value.description !== "string" || value.source !== void 0 && typeof value.source !== "string") throw new TypeError("Skill metadata requires an id and optional description/source strings");
1532
+ return {
1533
+ id: value.id,
1534
+ ...value.description === void 0 ? {} : { description: value.description },
1535
+ ...value.source === void 0 ? {} : { source: value.source }
1536
+ };
1537
+ }
1538
+ function catalog(values) {
1539
+ if (!Array.isArray(values)) throw new TypeError("Skill source must return a list");
1540
+ const entries = values.map(description);
1541
+ if (new Set(entries.map((entry) => entry.id)).size !== entries.length) throw new TypeError("Skill ids must be unique within a source");
1542
+ return entries;
1543
+ }
1544
+ function skills(input) {
1545
+ let source;
1546
+ if (Array.isArray(input)) {
1547
+ const entries = new Map(input.map((value) => {
1548
+ const metadata2 = description(value);
1549
+ if (typeof value.instructions !== "string") throw new TypeError(`Skill ${metadata2.id} requires instructions`);
1550
+ return [metadata2.id, { ...metadata2, instructions: value.instructions }];
1551
+ }));
1552
+ if (entries.size !== input.length) throw new TypeError("Skill ids must be unique within a source");
1553
+ source = { list: () => [...entries.values()].map(description), load: (id2) => {
1554
+ const value = entries.get(id2);
1555
+ if (!value) throw new TypeError(`Unknown skill: ${id2}`);
1556
+ return value;
1557
+ } };
1558
+ } else {
1559
+ source = input;
1560
+ if (!source || typeof source.list !== "function" || typeof source.load !== "function") throw new TypeError("Skill source requires list and load methods");
1561
+ }
1562
+ const list = async (ctx) => catalog(await source.list(ctx));
1563
+ const load = async (id2, ctx) => {
1564
+ if (typeof id2 !== "string" || !id2) throw new TypeError("Choose a skill id");
1565
+ const value = await source.load(id2, ctx);
1566
+ const metadata2 = description(value);
1567
+ if (metadata2.id !== id2 || typeof value.instructions !== "string") throw new TypeError("Skill source returned a different id or missing instructions");
1568
+ const content2 = { ...metadata2, instructions: value.instructions };
1569
+ return { ...content2, hash: await hashValue(content2) };
1570
+ };
1571
+ const access = { maxEffect: source.maxEffect ?? "read-only", needs: source.needs ?? [] };
1572
+ return { list, load, tools: {
1573
+ list_skills: {
1574
+ name: "list_skills",
1575
+ version: "1",
1576
+ description: "List the optional skills available to this agent, with their descriptions and sources.",
1577
+ schema: { type: "object", properties: {}, additionalProperties: false },
1578
+ ...access,
1579
+ run: (_args, ctx) => list(ctx)
1644
1580
  },
1645
- cursor: { type: "string", maxLength: 4096 },
1646
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize }
1647
- } },
1648
- query: {
1649
- type: "object",
1650
- required: ["kind", "scope"],
1651
- additionalProperties: false,
1652
- description: "Query one exact catalog kind. Kind ids are lower-case, singular, and must be selected from the enum; abstract names and pluralizations are invalid.",
1653
- properties: {
1654
- kind: { enum: [...CONSTAL_API_QUERY_KINDS], description: "Exact queryable kind. Never guess a kind or change its casing." },
1655
- scope: scopeSchema,
1656
- filter: { type: "object", description: "Optional catalog-advertised filter expression." },
1657
- search: { type: "string", maxLength: 512 },
1658
- order: { type: "array", maxItems: 8, items: {
1659
- type: "object",
1660
- required: ["field", "direction"],
1661
- additionalProperties: false,
1662
- properties: { field: boundedNameSchema, direction: { enum: ["ascending", "descending"] } }
1663
- } },
1664
- fields: stringListSchema,
1665
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1666
- cursor: { type: "string", maxLength: 4096 },
1667
- asOf: { type: "integer", minimum: 0 },
1668
- range: { type: "object", required: ["start", "end"], additionalProperties: false, properties: {
1669
- start: { type: "integer", minimum: 0 },
1670
- end: { type: "integer", minimum: 0 }
1671
- } }
1581
+ read_skill: {
1582
+ name: "read_skill",
1583
+ version: "1",
1584
+ description: "Read a selected skill's instructions and source identity. Supporting files can be read or executed with the available Tools.",
1585
+ schema: { type: "object", properties: { id: { type: "string", minLength: 1 } }, required: ["id"], additionalProperties: false },
1586
+ ...access,
1587
+ run: (args, ctx) => load(args.id, ctx)
1588
+ }
1589
+ } };
1590
+ }
1591
+
1592
+ // packages/sdk/src/resource-tools.ts
1593
+ function resource(ctx, binding) {
1594
+ const resources = ctx.capabilities().resources;
1595
+ if (!Object.hasOwn(resources, binding)) throw new TypeError(`Resource binding is unavailable: ${binding}`);
1596
+ return resources[binding];
1597
+ }
1598
+ var bindingProperty = { type: "string", minLength: 1, description: "A binding name from this Run's resource catalog." };
1599
+ function resourceIndex(ctx) {
1600
+ const catalog2 = ctx.capabilities();
1601
+ return {
1602
+ resourcesHash: catalog2.resourcesHash,
1603
+ toolsetHash: catalog2.toolsetHash,
1604
+ resources: Object.entries(catalog2.resources).map(([binding, { operations, ...identity }]) => ({
1605
+ binding,
1606
+ ...identity,
1607
+ operations: operations.map(({ op, description: description2, effect, async }) => ({ op, description: description2, effect, async }))
1608
+ }))
1609
+ };
1610
+ }
1611
+ function resourceContext(ctx) {
1612
+ return ctx.step("resource-context", async () => ({ run: ctx.run, ...resourceIndex(ctx) }));
1613
+ }
1614
+ var resourceTools = {
1615
+ resource_list: {
1616
+ name: "resource_list",
1617
+ version: "1",
1618
+ maxEffect: "read-only",
1619
+ description: "List this Run's bound resources and public operations. These are configured capabilities; each invocation evaluates its current Policy and connection state.",
1620
+ schema: { type: "object", properties: {}, additionalProperties: false },
1621
+ async run(_args, ctx) {
1622
+ return resourceIndex(ctx);
1672
1623
  }
1673
1624
  },
1674
- get: {
1675
- type: "object",
1676
- required: ["ref"],
1677
- additionalProperties: false,
1678
- description: "Read one addressable object using a complete ref returned by query, relations, runtime inspection, or a governed receipt. Do not synthesize refs.",
1679
- properties: {
1680
- ref: {
1681
- description: "Copy a complete object ref from governed output, or supply an exact supported CRN.",
1682
- anyOf: [objectRefSchema, {
1683
- type: "object",
1684
- required: ["crn"],
1685
- additionalProperties: false,
1686
- properties: { crn: exactGetCrnSchema, hash: hashSchema }
1687
- }]
1688
- },
1689
- fields: stringListSchema,
1690
- page: { type: "object", additionalProperties: false, properties: {
1691
- cursor: { type: "string", maxLength: 4096 },
1692
- limit: { type: "integer", minimum: 1, maximum: 500 }
1693
- } }
1625
+ resource_describe: {
1626
+ name: "resource_describe",
1627
+ version: "1",
1628
+ maxEffect: "read-only",
1629
+ description: "Read a bound resource's credential slot names and pinned public operation contracts, including input/output schemas, effects, and recovery behavior.",
1630
+ schema: { type: "object", properties: { binding: bindingProperty }, required: ["binding"], additionalProperties: false },
1631
+ async run(args, ctx) {
1632
+ return { binding: args.binding, ...resource(ctx, args.binding) };
1694
1633
  }
1695
1634
  },
1696
- relations: { type: "object", required: ["start"], additionalProperties: false, properties: {
1697
- start: { anyOf: [objectRefSchema, {
1635
+ resource_invoke: {
1636
+ name: "resource_invoke",
1637
+ version: "1",
1638
+ maxEffect: "non-idempotent",
1639
+ description: "Invoke a public operation on a bound resource with arguments matching its contract. The runtime applies normal authorization, credential resolution, asynchronous handles, and recovery.",
1640
+ schema: {
1698
1641
  type: "object",
1699
- required: ["crn"],
1700
- additionalProperties: false,
1701
- properties: { crn: { type: "string", minLength: 1, maxLength: 2048 }, hash: hashSchema }
1702
- }] },
1703
- direction: { enum: ["outgoing", "incoming", "both"] },
1704
- types: stringListSchema,
1705
- depth: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumRelationDepth },
1706
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1707
- cursor: { type: "string", maxLength: 4096 }
1708
- } },
1709
- explainPolicy: { type: "object", required: ["action", "resource"], additionalProperties: false, properties: {
1710
- principal: { anyOf: [
1711
- { type: "string", maxLength: 2048 },
1712
- { type: "object", required: ["roles", "scopes"], additionalProperties: false, properties: {
1713
- name: { type: "string", maxLength: 2048 },
1714
- roles: {
1715
- type: "array",
1716
- maxItems: 64,
1717
- uniqueItems: true,
1718
- items: { type: "string", minLength: 1, maxLength: 2048 }
1719
- },
1720
- scopes: {
1721
- type: "array",
1722
- maxItems: 256,
1723
- uniqueItems: true,
1724
- items: { type: "string", pattern: "^(?:\\*|[a-z][a-z0-9-]{0,63}:(?:[a-z][a-z0-9-]{0,63}|\\*))$" }
1725
- }
1726
- } }
1727
- ] },
1728
- action: actionSchema,
1729
- resource: { type: "string", minLength: 1, maxLength: 2048 },
1730
- context: { type: "object" },
1731
- arguments: {},
1732
- at: { type: "object", required: ["run"], additionalProperties: false, properties: {
1733
- run: {
1734
- type: "object",
1735
- required: ["namespace", "agent", "session", "run"],
1736
- additionalProperties: false,
1737
- properties: {
1738
- namespace: boundedNameSchema,
1739
- agent: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]{0,62}$" },
1740
- session: boundedIdSchema,
1741
- run: boundedIdSchema
1642
+ properties: {
1643
+ binding: bindingProperty,
1644
+ operation: { type: "string", minLength: 1 },
1645
+ arguments: {},
1646
+ wait: { type: "boolean", description: "For an asynchronous operation, set false to submit it and receive its Handle ID while it continues running." },
1647
+ credentials: {
1648
+ type: "object",
1649
+ additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA,
1650
+ description: "Optional credential references for named adapter slots on this invocation. Supply references, not credential material."
1742
1651
  }
1652
+ },
1653
+ required: ["binding", "operation", "arguments"],
1654
+ additionalProperties: false
1655
+ },
1656
+ async run(args, ctx) {
1657
+ const target = resource(ctx, args.binding);
1658
+ const operation = target.operations.find((candidate) => candidate.op === args.operation);
1659
+ if (!operation) throw new TypeError(`Public operation is unavailable: ${args.binding}#${args.operation}`);
1660
+ const options = args.credentials === void 0 ? [] : [{ credentials: args.credentials }];
1661
+ if (!operation.async) return ctx.invoke(target.crn, operation.op, args.arguments, ...options);
1662
+ const handle = ctx.invokeAsync(target.crn, operation.op, args.arguments, ...options);
1663
+ if (args.wait === false) {
1664
+ await handle.start();
1665
+ return { status: "submitted", handle: handle.id };
1743
1666
  }
1744
- } }
1745
- } },
1746
- plan: { type: "object", required: ["objective", "operations"], additionalProperties: false, properties: {
1747
- objective: { type: "string", minLength: 1, maxLength: 8192 },
1748
- validateOnly: { type: "boolean" },
1749
- operations: {
1750
- type: "array",
1751
- minItems: 1,
1752
- maxItems: CONSTAL_API_BOUNDS.maximumPlanOperations,
1753
- items: { type: "object", required: ["operation", "input"], additionalProperties: false, properties: {
1754
- id: boundedIdSchema,
1755
- operation: boundedNameSchema,
1756
- target: { type: "string", maxLength: 2048 },
1757
- input: {},
1758
- expectedCurrentHash: { anyOf: [{ type: "null" }, hashSchema] },
1759
- dependsOn: { type: "array", maxItems: 64, items: boundedIdSchema }
1760
- } }
1667
+ return await handle;
1761
1668
  }
1762
- } },
1763
- apply: { type: "object", required: ["plan", "eventId"], additionalProperties: false, properties: {
1764
- plan: {
1765
- type: "object",
1766
- required: ["id", "hash"],
1767
- additionalProperties: false,
1768
- properties: { id: boundedIdSchema, hash: hashSchema }
1769
- },
1770
- eventId: boundedIdSchema
1771
- } },
1772
- observe: { type: "object", required: ["id"], additionalProperties: false, properties: { id: boundedIdSchema } }
1669
+ }
1670
+ };
1671
+
1672
+ // packages/sdk/src/connection-state.ts
1673
+ var connectionStateView = {
1674
+ id: "constal-connections",
1675
+ version: "2",
1676
+ over: "facts",
1677
+ init: () => ({}),
1678
+ apply(state, fact) {
1679
+ const value = fact.artifact;
1680
+ if (!value?.run || !value.name) return state;
1681
+ const run = Object.hasOwn(state, value.run) ? state[value.run] : {};
1682
+ const previous = Object.hasOwn(run, value.name) ? run[value.name] : {};
1683
+ let next;
1684
+ if (value.kind === "connection.process" && value.connection) {
1685
+ if (!previous.process && !value.connection.tools) return state;
1686
+ const process = value.connection.tools ? value.connection : { ...previous.process, ...value.connection };
1687
+ next = { ...previous, process };
1688
+ } else if (value.kind === "connection.resource" && value.binding && value.attempt) {
1689
+ next = { ...previous, resource: { binding: value.binding, attempt: value.attempt } };
1690
+ } else return state;
1691
+ return { ...state, [value.run]: { ...run, [value.name]: next } };
1692
+ }
1693
+ };
1694
+ async function connectionStates(ctx) {
1695
+ const state = await ctx.ledger.view(connectionStateView.id);
1696
+ return Object.hasOwn(state, ctx.run.id) ? state[ctx.run.id] : {};
1697
+ }
1698
+
1699
+ // packages/sdk/src/integration.ts
1700
+ var ApiError = class extends Error {
1701
+ constructor(status, body, disposition = "uncertain") {
1702
+ super(`${status}: ${body}`);
1703
+ this.status = status;
1704
+ this.body = body;
1705
+ this.disposition = disposition;
1706
+ this.name = "ApiError";
1707
+ }
1708
+ status;
1709
+ body;
1710
+ disposition;
1711
+ };
1712
+ var IntegrationRequestNotSent = class extends Error {
1713
+ constructor(message2 = "integration request was not sent") {
1714
+ super(message2);
1715
+ this.name = "IntegrationRequestNotSent";
1716
+ }
1717
+ };
1718
+ var TerminalIntegrationFailure = class extends Error {
1719
+ constructor(message2 = "integration operation failed terminally") {
1720
+ super(message2);
1721
+ this.name = "TerminalIntegrationFailure";
1722
+ }
1723
+ };
1724
+ var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
1725
+ function integrationEgressPolicy(value) {
1726
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1727
+ if (!source || !Array.isArray(source.rules) || source.rules.length > 128 || Object.keys(source).some((key) => key !== "rules")) {
1728
+ throw new TypeError("integration egress policy is invalid");
1729
+ }
1730
+ const rules = source.rules.map((raw) => {
1731
+ const rule = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
1732
+ const paths = Number(rule?.pathPrefix !== void 0) + Number(rule?.pathExact !== void 0);
1733
+ if (!rule || !Array.isArray(rule.operations) || rule.operations.length === 0 || rule.operations.length > 128 || rule.operations.some((operation) => typeof operation !== "string" || operation !== "*" && !OPERATION2.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))) {
1734
+ throw new TypeError("integration egress rule is invalid");
1735
+ }
1736
+ let origin;
1737
+ try {
1738
+ origin = new URL(rule.origin);
1739
+ } catch {
1740
+ throw new TypeError("integration egress origin is invalid");
1741
+ }
1742
+ if (origin.protocol !== "https:" || origin.origin !== rule.origin || origin.username || origin.password) {
1743
+ throw new TypeError("integration egress origin is invalid");
1744
+ }
1745
+ const path = String(rule.pathPrefix ?? rule.pathExact);
1746
+ if (!path.startsWith("/") || path.includes("?") || path.includes("#")) throw new TypeError("integration egress path is invalid");
1747
+ return rule;
1748
+ });
1749
+ return { rules };
1750
+ }
1751
+
1752
+ // packages/sdk/src/mcp-protocol.ts
1753
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
1754
+ function record4(value) {
1755
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1756
+ }
1757
+ function message(value) {
1758
+ const item = record4(value);
1759
+ if (!item || item.jsonrpc !== "2.0" || item.method !== void 0 && typeof item.method !== "string" || item.id !== void 0 && item.id !== null && typeof item.id !== "string" && typeof item.id !== "number") {
1760
+ throw new TerminalIntegrationFailure("MCP server returned an invalid JSON-RPC message");
1761
+ }
1762
+ return item;
1763
+ }
1764
+ function result(response) {
1765
+ if (response.error) {
1766
+ const code = typeof response.error.code === "number" || typeof response.error.code === "string" ? response.error.code : "unknown";
1767
+ const detail = typeof response.error.message === "string" ? response.error.message : "MCP request failed";
1768
+ throw new TerminalIntegrationFailure(`MCP ${code}: ${detail}`);
1769
+ }
1770
+ if (!Object.hasOwn(response, "result")) throw new TerminalIntegrationFailure("MCP JSON-RPC response has no result");
1771
+ return response.result;
1772
+ }
1773
+ function initialized(value) {
1774
+ const result2 = record4(value);
1775
+ if (!result2 || typeof result2.protocolVersion !== "string" || !result2.protocolVersion) throw new TerminalIntegrationFailure("MCP initialize result is invalid");
1776
+ return { protocolVersion: result2.protocolVersion, server: record4(result2.serverInfo) ?? {}, capabilities: record4(result2.capabilities) ?? {} };
1777
+ }
1778
+ async function tools(request, maximum) {
1779
+ const tools2 = [], cursors = /* @__PURE__ */ new Set();
1780
+ let cursor;
1781
+ do {
1782
+ const result2 = record4(await request("tools/list", cursor ? { cursor } : {}));
1783
+ if (!result2 || !Array.isArray(result2.tools)) throw new TerminalIntegrationFailure("MCP tools/list result is invalid");
1784
+ tools2.push(...result2.tools.map(tool));
1785
+ if (maximum !== void 0 && tools2.length > maximum) throw new TerminalIntegrationFailure(`MCP server advertises more than ${maximum} tools`);
1786
+ if (result2.nextCursor !== void 0 && typeof result2.nextCursor !== "string") throw new TerminalIntegrationFailure("MCP tools/list cursor is invalid");
1787
+ cursor = result2.nextCursor ? result2.nextCursor : void 0;
1788
+ if (cursor && cursors.has(cursor)) throw new TerminalIntegrationFailure("MCP server returned a repeated pagination cursor");
1789
+ if (cursor) cursors.add(cursor);
1790
+ } while (cursor);
1791
+ if (new Set(tools2.map((tool2) => tool2.name)).size !== tools2.length) throw new TerminalIntegrationFailure("MCP server advertised duplicate tool names");
1792
+ return tools2;
1793
+ }
1794
+ function tool(value) {
1795
+ const tool2 = record4(value);
1796
+ const inputSchema = record4(tool2?.inputSchema);
1797
+ const outputSchema = tool2?.outputSchema === void 0 ? {} : record4(tool2.outputSchema);
1798
+ if (!tool2 || typeof tool2.name !== "string" || !tool2.name || tool2.description !== void 0 && typeof tool2.description !== "string" || !inputSchema || outputSchema === null) throw new TerminalIntegrationFailure("MCP server advertised an invalid tool");
1799
+ return {
1800
+ ...tool2,
1801
+ name: tool2.name,
1802
+ description: typeof tool2.description === "string" ? tool2.description : "",
1803
+ inputSchema,
1804
+ outputSchema,
1805
+ annotations: record4(tool2.annotations) ?? {}
1806
+ };
1807
+ }
1808
+ function textContent(content2) {
1809
+ const text2 = [];
1810
+ for (const value of content2) {
1811
+ const block = record4(value);
1812
+ if (block?.type !== "text") continue;
1813
+ if (typeof block.text !== "string") throw new TerminalIntegrationFailure("MCP tool returned an invalid text content block");
1814
+ text2.push(block.text);
1815
+ }
1816
+ return text2;
1817
+ }
1818
+ function unwrapToolResult(value, outputSchema) {
1819
+ const result2 = record4(value);
1820
+ if (!result2) throw new TerminalIntegrationFailure("MCP tools/call result is invalid");
1821
+ if (result2.isError !== void 0 && typeof result2.isError !== "boolean") {
1822
+ throw new TerminalIntegrationFailure("MCP tools/call result has an invalid isError value");
1823
+ }
1824
+ const content2 = Array.isArray(result2.content) ? result2.content : null;
1825
+ if (result2.isError === true) {
1826
+ const message2 = content2 ? textContent(content2).join("\n").trim() : "";
1827
+ throw new TerminalIntegrationFailure(message2 ? `MCP tool failed: ${message2}` : "MCP tool failed");
1828
+ }
1829
+ if (Object.hasOwn(result2, "structuredContent")) {
1830
+ const structured = record4(result2.structuredContent);
1831
+ if (!structured) throw new TerminalIntegrationFailure("MCP tool returned invalid structuredContent");
1832
+ return structured;
1833
+ }
1834
+ if (!content2) throw new TerminalIntegrationFailure("MCP tool result has no content");
1835
+ const text2 = textContent(content2);
1836
+ if (content2.length === 1 && text2.length === 1) {
1837
+ try {
1838
+ return JSON.parse(text2[0]);
1839
+ } catch {
1840
+ if (Object.keys(outputSchema).length > 0) {
1841
+ throw new TerminalIntegrationFailure("MCP tool result text is not valid JSON for its declared outputSchema");
1842
+ }
1843
+ return text2[0];
1844
+ }
1845
+ }
1846
+ if (Object.keys(outputSchema).length > 0) {
1847
+ throw new TerminalIntegrationFailure("MCP tool result has no structuredContent or single JSON text block for its declared outputSchema");
1848
+ }
1849
+ return content2;
1850
+ }
1851
+ var mcpProtocol = {
1852
+ version: MCP_PROTOCOL_VERSION,
1853
+ message,
1854
+ result,
1855
+ initialized,
1856
+ tool,
1857
+ tools,
1858
+ toolResult: unwrapToolResult,
1859
+ initialization: () => ({ protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "Constal", version: "1.0.0" } })
1860
+ };
1861
+
1862
+ // packages/sdk/src/mcp-process.ts
1863
+ function initialMcpProcessState() {
1864
+ return { offset: 0, protocolVersion: null, server: {}, capabilities: {}, toolsChanged: false };
1865
+ }
1866
+ var McpProcessError = class extends TerminalIntegrationFailure {
1867
+ constructor(kind, message2) {
1868
+ super(message2);
1869
+ this.kind = kind;
1870
+ this.name = "McpProcessError";
1871
+ }
1872
+ kind;
1773
1873
  };
1874
+ function frame(parts, length) {
1875
+ const bytes = new Uint8Array(length);
1876
+ let offset = 0;
1877
+ for (const part of parts) {
1878
+ bytes.set(part, offset);
1879
+ offset += part.length;
1880
+ }
1881
+ try {
1882
+ return mcpProtocol.message(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
1883
+ } catch {
1884
+ throw new McpProcessError("protocol", "MCP process returned an invalid UTF-8 JSON-RPC frame");
1885
+ }
1886
+ }
1887
+ function processMcp(process, state, ctx, options = {}) {
1888
+ const earlierResponses = [];
1889
+ const send = async (message2) => {
1890
+ const data = `${JSON.stringify(message2)}
1891
+ `;
1892
+ const result2 = await process.write({ data }, options.timeoutMs === void 0 ? void 0 : { timeoutMs: options.timeoutMs });
1893
+ if (result2.error || result2.written !== new TextEncoder().encode(data).length) {
1894
+ throw new McpProcessError("write", "MCP request was not fully written to the process");
1895
+ }
1896
+ };
1897
+ async function exchange(method, params) {
1898
+ const id2 = crypto.randomUUID();
1899
+ const deadline = options.timeoutMs === void 0 ? null : Date.now() + options.timeoutMs;
1900
+ await send({ jsonrpc: "2.0", id: id2, method, params });
1901
+ let offset = state.offset, parts = [], length = 0;
1902
+ for (; ; ) {
1903
+ const page = await process.read({
1904
+ stream: "stdout",
1905
+ offset,
1906
+ ...options.timeoutMs === void 0 ? {} : { invoke: { timeoutMs: options.timeoutMs } }
1907
+ });
1908
+ const bytes = Uint8Array.from(atob(page.data), (character) => character.charCodeAt(0));
1909
+ if (page.offset !== offset || page.nextOffset !== offset + bytes.length) throw new McpProcessError("protocol", "MCP process output range changed");
1910
+ let start = 0;
1911
+ while (start < bytes.length) {
1912
+ const newline = bytes.indexOf(10, start), end = newline < 0 ? bytes.length : newline;
1913
+ const part = bytes.subarray(start, end);
1914
+ parts.push(part);
1915
+ length += part.length;
1916
+ if (newline < 0) break;
1917
+ const message2 = frame(parts, length);
1918
+ state.offset = offset + newline + 1;
1919
+ parts = [];
1920
+ length = 0;
1921
+ start = newline + 1;
1922
+ if (message2.method !== void 0) {
1923
+ if (message2.id !== void 0) await send(message2.method === "ping" ? { jsonrpc: "2.0", id: message2.id, result: {} } : { jsonrpc: "2.0", id: message2.id, error: { code: -32601, message: "Client capability is not supported" } });
1924
+ else if (message2.method === "notifications/tools/list_changed") state.toolsChanged = true;
1925
+ } else if (message2.id === id2) return message2;
1926
+ else earlierResponses.push(message2);
1927
+ }
1928
+ offset = page.nextOffset;
1929
+ if (page.exited) throw new McpProcessError("closed", `MCP process exited before responding (exit ${page.exitCode ?? "unknown"})`);
1930
+ const now = deadline === null ? null : Date.now();
1931
+ if (deadline !== null && now >= deadline) throw new McpProcessError("timeout", `MCP request ${id2} timed out; its server-side outcome is unknown`);
1932
+ if (bytes.length === 0) await ctx.await(`mcp-output:${process.id}:${id2}`, { timeout: 250, onTimeout: null, afterRun: "ignore" });
1933
+ }
1934
+ }
1935
+ const request = async (method, params) => mcpProtocol.result(await exchange(method, params));
1936
+ return {
1937
+ state,
1938
+ exchange,
1939
+ request,
1940
+ earlierResponses,
1941
+ async initialize() {
1942
+ const initialized2 = mcpProtocol.initialized(await request("initialize", mcpProtocol.initialization()));
1943
+ if (initialized2.protocolVersion !== mcpProtocol.version) throw new TerminalIntegrationFailure(`MCP process selected unsupported protocol ${initialized2.protocolVersion}`);
1944
+ Object.assign(state, initialized2);
1945
+ await send({ jsonrpc: "2.0", method: "notifications/initialized" });
1946
+ },
1947
+ async tools() {
1948
+ const tools2 = await mcpProtocol.tools(request);
1949
+ state.toolsChanged = false;
1950
+ return tools2;
1951
+ }
1952
+ };
1953
+ }
1954
+
1955
+ // packages/sdk/src/connection-process.ts
1956
+ async function processConnections(ctx) {
1957
+ return Object.fromEntries(Object.entries(await connectionStates(ctx)).flatMap(([name, state]) => state.process ? [[name, state.process]] : []));
1958
+ }
1959
+ function processDefinition(spec) {
1960
+ return hashValue({ pool: spec.pool, command: spec.command });
1961
+ }
1962
+ async function save(ctx, name, connection, catalog2 = false) {
1963
+ const { tools: _tools, ...progress } = connection;
1964
+ await ctx.commit({ kind: "connection.process", run: ctx.run.id, name, connection: structuredClone(catalog2 ? connection : progress) }, { tier: "audit" });
1965
+ return connection;
1966
+ }
1967
+ function clientOptions(spec) {
1968
+ return spec.requestTimeoutMs === void 0 ? {} : { timeoutMs: spec.requestTimeoutMs };
1969
+ }
1970
+ function unavailable(connection) {
1971
+ return { ...describeProcessConnection(connection), message: "The connection attempt failed. Its process and error remain available for diagnosis." };
1972
+ }
1973
+ function describeProcessConnection(connection) {
1974
+ return structuredClone({
1975
+ state: connection.state,
1976
+ process: { id: connection.process, pool: connection.pool },
1977
+ tools: connection.tools,
1978
+ server: connection.protocol.server,
1979
+ capabilities: connection.protocol.capabilities,
1980
+ toolsChanged: connection.protocol.toolsChanged,
1981
+ ...connection.error ? { error: connection.error } : {}
1982
+ });
1983
+ }
1984
+ async function connectProcess(name, spec, ctx, options = {}) {
1985
+ const states = await processConnections(ctx);
1986
+ const previous = Object.hasOwn(states, name) ? states[name] : null;
1987
+ const definition2 = await processDefinition(spec);
1988
+ if (previous && previous.definition === definition2 && !options.restart) {
1989
+ if (previous.state === "connected" && !options.refresh) return previous;
1990
+ }
1991
+ const box = await ctx.sandboxPool(spec.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
1992
+ const reuse = previous?.state === "connected" && previous.definition === definition2 && !options.restart;
1993
+ if (previous && previous.state !== "closed" && !reuse) {
1994
+ const priorBox = previous.pool === spec.pool ? box : await ctx.sandboxPool(previous.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
1995
+ await priorBox.process(previous.process).stop();
1996
+ }
1997
+ const process = reuse ? box.process(previous.process) : await box.startProcess(
1998
+ spec.command,
1999
+ spec.command.timeoutMs === void 0 ? void 0 : { timeoutMs: spec.command.timeoutMs }
2000
+ );
2001
+ const connection = reuse ? structuredClone(previous) : {
2002
+ definition: definition2,
2003
+ pool: spec.pool,
2004
+ process: process.id,
2005
+ state: "connected",
2006
+ protocol: initialMcpProcessState(),
2007
+ tools: []
2008
+ };
2009
+ const client = processMcp(process, connection.protocol, ctx, clientOptions(spec));
2010
+ try {
2011
+ if (!reuse) await client.initialize();
2012
+ connection.tools = await client.tools();
2013
+ connection.error = null;
2014
+ } catch (error) {
2015
+ if (!(error instanceof TerminalIntegrationFailure)) throw error;
2016
+ connection.state = "failed";
2017
+ connection.error = { name: error.name, message: error.message };
2018
+ }
2019
+ return save(ctx, name, connection, true);
2020
+ }
2021
+ async function invokeProcessConnection(name, spec, operation, args, ctx) {
2022
+ const states = await processConnections(ctx);
2023
+ let connection = Object.hasOwn(states, name) ? structuredClone(states[name]) : null;
2024
+ if (!connection || connection.state !== "connected" || connection.definition !== await processDefinition(spec)) {
2025
+ connection = await connectProcess(name, spec, ctx);
2026
+ }
2027
+ if (connection.state !== "connected") return unavailable(connection);
2028
+ if (!connection.tools.some((tool2) => tool2.name === operation)) throw new TypeError(`MCP tool is not in the discovered catalog: ${operation}`);
2029
+ const box = await ctx.sandboxPool(connection.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
2030
+ const client = processMcp(box.process(connection.process), connection.protocol, ctx, clientOptions(spec));
2031
+ let response;
2032
+ try {
2033
+ response = await client.exchange("tools/call", { name: operation, arguments: args });
2034
+ } catch (error) {
2035
+ if (!(error instanceof TerminalIntegrationFailure)) throw error;
2036
+ connection.state = error instanceof McpProcessError && error.kind === "timeout" ? "connected" : "failed";
2037
+ connection.error = { name: error.name, message: error.message };
2038
+ await save(ctx, name, connection);
2039
+ return describeProcessConnection(connection);
2040
+ }
2041
+ connection.error = null;
2042
+ await save(ctx, name, connection);
2043
+ const result2 = mcpProtocol.result(response);
2044
+ if (!client.earlierResponses.length) return result2;
2045
+ const value = result2 && typeof result2 === "object" && !Array.isArray(result2) ? result2 : { result: result2 };
2046
+ const metadata2 = value._meta && typeof value._meta === "object" && !Array.isArray(value._meta) ? value._meta : {};
2047
+ return { ...value, _meta: { ...metadata2, "ai.constal/earlierResponses": client.earlierResponses } };
2048
+ }
2049
+ async function disconnectProcess(name, ctx) {
2050
+ const states = await processConnections(ctx);
2051
+ const connection = Object.hasOwn(states, name) ? states[name] : null;
2052
+ if (!connection || connection.state === "closed") return { name, state: "closed" };
2053
+ const box = await ctx.sandboxPool(connection.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
2054
+ await box.process(connection.process).stop();
2055
+ const closed = await save(ctx, name, { ...connection, state: "closed" });
2056
+ return { name, ...describeProcessConnection(closed) };
2057
+ }
2058
+
2059
+ // packages/sdk/src/connections.ts
2060
+ function object3(value) {
2061
+ return !!value && typeof value === "object" && !Array.isArray(value);
2062
+ }
2063
+ function definition(value) {
2064
+ if (!object3(value) || value.package === void 0 && value.binding === void 0 && value.process === void 0 || value.package !== void 0 && !object3(value.package) || value.config !== void 0 && !object3(value.config) || value.description !== void 0 && typeof value.description !== "string") throw new TypeError("Connection definition is invalid");
2065
+ if (value.binding !== void 0) scopedBindingKey(value.binding);
2066
+ if (value.process !== void 0 && (!object3(value.process) || typeof value.process.pool !== "string" || !object3(value.process.command) || typeof value.process.command.cmd !== "string" || !value.process.command.cmd || value.process.requestTimeoutMs !== void 0 && (!Number.isSafeInteger(value.process.requestTimeoutMs) || Number(value.process.requestTimeoutMs) <= 0) || value.binding !== void 0 || value.package !== void 0 || value.config !== void 0 || value.credentials !== void 0)) throw new TypeError("Process connection definition is invalid");
2067
+ return { ...value, ...value.credentials === void 0 ? {} : { credentials: resourceCredentialBindings(value.credentials) } };
2068
+ }
2069
+ function suppliedSource(values) {
2070
+ return {
2071
+ async list() {
2072
+ return Promise.all(Object.entries(values).map(async ([name, raw]) => {
2073
+ const value = definition(raw);
2074
+ const { description: _description, ...settings } = value;
2075
+ return {
2076
+ name,
2077
+ ...value.process ? { transport: "stdio" } : { binding: value.binding ?? `connection-${(await hashValue({ name, value: settings })).slice(0, 40)}` },
2078
+ ...value.description === void 0 ? {} : { description: value.description }
2079
+ };
2080
+ }));
2081
+ },
2082
+ async load(name) {
2083
+ if (!Object.hasOwn(values, name)) throw new TypeError(`Connection is not configured: ${name}`);
2084
+ return definition(values[name]);
2085
+ }
2086
+ };
2087
+ }
2088
+ async function change(ctx, api, name, operation, input, eventId) {
2089
+ const plan = await ctx.invoke(ctx.resources[api], "plan", {
2090
+ objective: `Connect ${name}`,
2091
+ operations: [{ operation, input }]
2092
+ });
2093
+ return ctx.invokeAsync(ctx.resources[api], "apply", { plan: { id: plan.id, hash: plan.hash }, eventId });
2094
+ }
2095
+ function connections(supplied, options = {}) {
2096
+ const source = typeof supplied.list === "function" && typeof supplied.load === "function" ? supplied : suppliedSource(supplied);
2097
+ const api = options.api ?? "api";
2098
+ scopedBindingKey(api);
2099
+ async function index(ctx) {
2100
+ const descriptions = await source.list(ctx);
2101
+ if (new Set(descriptions.map((item) => item.name)).size !== descriptions.length) throw new TypeError("Connection names are duplicated");
2102
+ for (const item of descriptions) {
2103
+ if (typeof item.name !== "string" || !item.name) throw new TypeError("Connection name is invalid");
2104
+ if (item.transport !== "stdio") scopedBindingKey(item.binding);
2105
+ }
2106
+ const states = descriptions.length ? await connectionStates(ctx) : {};
2107
+ return ctx.step("connection-index", async () => {
2108
+ const resources = ctx.capabilities().resources;
2109
+ return descriptions.map((item) => {
2110
+ const saved = Object.hasOwn(states, item.name) ? states[item.name] : void 0;
2111
+ const local = item.transport === "stdio" ? saved?.process : null;
2112
+ if (local) return { ...item, ...describeProcessConnection(local) };
2113
+ const lastAttempt = item.binding && saved?.resource?.binding === item.binding ? saved.resource.attempt : void 0;
2114
+ const observed = lastAttempt && lastAttempt.state !== "bound" ? lastAttempt.state : "configured";
2115
+ return {
2116
+ ...item,
2117
+ state: item.binding && Object.hasOwn(resources, item.binding) ? "bound" : observed,
2118
+ ...lastAttempt ? { lastAttempt } : {},
2119
+ ...item.binding && Object.hasOwn(resources, item.binding) ? { resource: resources[item.binding] } : {}
2120
+ };
2121
+ });
2122
+ });
2123
+ }
2124
+ async function remember(ctx, selected, attempt) {
2125
+ await ctx.commit({
2126
+ kind: "connection.resource",
2127
+ run: ctx.run.id,
2128
+ name: selected.name,
2129
+ binding: selected.binding,
2130
+ attempt
2131
+ }, { tier: "audit" });
2132
+ return { ...selected, ...attempt, lastAttempt: attempt };
2133
+ }
2134
+ const tools2 = {
2135
+ connection_list: {
2136
+ name: "connection_list",
2137
+ version: "1",
2138
+ maxEffect: "read-only",
2139
+ needs: source.needs ?? [],
2140
+ description: "List configured connections and the Resource bindings currently available in this Run.",
2141
+ schema: { type: "object", properties: {}, additionalProperties: false },
2142
+ async run(_args, ctx) {
2143
+ return index(ctx);
2144
+ }
2145
+ },
2146
+ connection_connect: {
2147
+ name: "connection_connect",
2148
+ version: "1",
2149
+ maxEffect: "non-idempotent",
2150
+ needs: source.needs ?? [],
2151
+ description: "Connect a configured server and discover its tools. Local MCP keeps one process per connection; remote connections use Resource bindings. Explicit restart replaces a local process; refresh reloads its catalog. Policy governs the underlying operations.",
2152
+ schema: { type: "object", required: ["name"], additionalProperties: false, properties: { name: { type: "string", minLength: 1 }, restart: { type: "boolean" }, refresh: { type: "boolean" } } },
2153
+ async run(args, ctx) {
2154
+ const selected = (await index(ctx)).find((item) => item.name === args.name);
2155
+ if (!selected) throw new TypeError(`Connection is not configured: ${args.name}`);
2156
+ if (selected.state === "bound") return selected;
2157
+ const loaded = await source.load(args.name, ctx);
2158
+ const spec = await ctx.step("connection-definition", async () => definition(loaded));
2159
+ if (spec.process) return { ...selected, ...describeProcessConnection(await connectProcess(args.name, spec.process, ctx, args)) };
2160
+ if (!selected.binding) throw new TypeError("A Resource connection requires a binding");
2161
+ if (!spec.package) return remember(ctx, selected, { state: "unavailable", message: "The configured binding is absent and has no installation definition." });
2162
+ if (!ctx.resources[api]) return remember(ctx, selected, { state: "unavailable", message: "The API binding needed for installation is unavailable." });
2163
+ if (spec.binding !== void 0 && spec.binding !== selected.binding) throw new TypeError("Connection binding changed between listing and loading");
2164
+ const identity = await hashValue({ run: ctx.run.id, name: args.name, binding: selected.binding, spec });
2165
+ const id2 = `connection-${identity.slice(0, 40)}`;
2166
+ const installation = await change(ctx, api, args.name, "gateway.install", {
2167
+ namespace: ctx.run.namespace,
2168
+ id: id2,
2169
+ package: spec.package,
2170
+ config: spec.config ?? {},
2171
+ credentials: spec.credentials ?? {}
2172
+ }, `install-${identity}`);
2173
+ if (installation.state !== "succeeded") return remember(ctx, selected, { state: "failed", stage: "installation", installation });
2174
+ const result2 = installation.operations.find((item) => item.operation === "gateway.install")?.result;
2175
+ const resource2 = object3(result2) && object3(result2.data) ? result2.data : result2;
2176
+ if (!object3(resource2) || typeof resource2.crn !== "string" || typeof resource2.hash !== "string") {
2177
+ throw new TypeError("Connection installation returned no Resource identity");
2178
+ }
2179
+ const pin = { crn: resource2.crn, hash: resource2.hash };
2180
+ const attachment = await change(ctx, api, args.name, "run.rebind", {
2181
+ namespace: ctx.run.namespace,
2182
+ agent: ctx.run.agent.id,
2183
+ session: ctx.run.session,
2184
+ run: ctx.run.id,
2185
+ request: { addBindings: { [selected.binding]: pin } }
2186
+ }, `attach-${identity}`);
2187
+ if (attachment.state !== "succeeded") return remember(ctx, selected, { state: "failed", stage: "attachment", installation, attachment });
2188
+ await ctx.commit({
2189
+ kind: "connection.attachment",
2190
+ name: args.name,
2191
+ binding: selected.binding,
2192
+ resource: pin,
2193
+ installation: installation.id,
2194
+ attachment: attachment.id
2195
+ }, { tier: "audit" });
2196
+ const current = await ctx.step("connection-attached", async () => ctx.capabilities().resources[selected.binding] ?? null);
2197
+ if (!current || current.crn !== pin.crn || current.hash !== pin.hash) {
2198
+ return remember(ctx, selected, { state: "unavailable", message: "The requested connection is not present in the applied Run snapshot.", installation, attachment });
2199
+ }
2200
+ return { ...await remember(ctx, selected, { state: "bound", installation, attachment }), resource: current };
2201
+ }
2202
+ },
2203
+ connection_invoke: {
2204
+ name: "connection_invoke",
2205
+ version: "1",
2206
+ maxEffect: "non-idempotent",
2207
+ needs: source.needs ?? [],
2208
+ description: "Call an operation on a configured connection. Local MCP connects lazily and keeps server state across calls; inspect its discovered tools for operation names and arguments.",
2209
+ schema: { type: "object", required: ["name", "operation", "arguments"], additionalProperties: false, properties: {
2210
+ name: { type: "string", minLength: 1 },
2211
+ operation: { type: "string", minLength: 1 },
2212
+ arguments: {}
2213
+ } },
2214
+ async run(args, ctx) {
2215
+ const selected = (await index(ctx)).find((item) => item.name === args.name);
2216
+ if (!selected) throw new TypeError(`Connection is not configured: ${args.name}`);
2217
+ const loaded = await source.load(args.name, ctx);
2218
+ const spec = await ctx.step("connection-definition", async () => definition(loaded));
2219
+ if (spec.process) return invokeProcessConnection(args.name, spec.process, args.operation, args.arguments, ctx);
2220
+ if (selected.state !== "bound") {
2221
+ const connected = await tools2.connection_connect.run({ name: args.name }, ctx);
2222
+ if (connected.state !== "bound") return connected;
2223
+ }
2224
+ return resourceTools.resource_invoke.run({ binding: selected.binding, operation: args.operation, arguments: args.arguments }, ctx);
2225
+ }
2226
+ },
2227
+ connection_disconnect: {
2228
+ name: "connection_disconnect",
2229
+ version: "1",
2230
+ maxEffect: "non-idempotent",
2231
+ needs: source.needs ?? [],
2232
+ description: "Stop a local MCP process and release its process credentials. Remote Resource lifecycles remain controlled by the platform.",
2233
+ schema: { type: "object", required: ["name"], additionalProperties: false, properties: { name: { type: "string", minLength: 1 } } },
2234
+ async run(args, ctx) {
2235
+ const selected = (await index(ctx)).find((item) => item.name === args.name);
2236
+ if (!selected) throw new TypeError(`Connection is not configured: ${args.name}`);
2237
+ if (selected.transport !== "stdio") return { ...selected, message: "This connection uses the platform Resource lifecycle." };
2238
+ return disconnectProcess(args.name, ctx);
2239
+ }
2240
+ }
2241
+ };
2242
+ return { index, tools: tools2, views: [connectionStateView] };
2243
+ }
2244
+
2245
+ // packages/sdk/src/invocation.ts
2246
+ function normalizeInvocationOptions(options) {
2247
+ const credentials = options.credentials === void 0 ? void 0 : resourceCredentialBindings(options.credentials);
2248
+ return {
2249
+ capability: options.capability?.id ?? null,
2250
+ timeoutMs: options.timeoutMs ?? null,
2251
+ dedupeKey: options.dedupeKey ?? null,
2252
+ ...credentials === void 0 ? {} : { credentials }
2253
+ };
2254
+ }
1774
2255
 
1775
- // src/policy-governance.ts
2256
+ // packages/sdk/src/policy-governance.ts
1776
2257
  var SANDBOX_CONTRACT = {
1777
2258
  id: "constal.sandbox-pool",
1778
2259
  version: "1",
@@ -1846,727 +2327,298 @@ function validatePolicyGovernanceConstraint(value) {
1846
2327
  limit(value.contract, [value.meter], value);
1847
2328
  }
1848
2329
 
1849
- // src/authorization.ts
1850
- var MAX_CONSTRAINTS = 64;
1851
- var MAX_OUTCOME_BYTES = 65536;
1852
- var MAX_REASON_BYTES = 1024;
1853
- var DENIAL_CODE = /^[a-z][a-z0-9._-]{0,127}$/u;
1854
- var encoder4 = new TextEncoder();
1855
- function record4(value) {
1856
- return !!value && typeof value === "object" && !Array.isArray(value);
2330
+ // packages/sdk/src/training.ts
2331
+ var HASH2 = /^[a-f0-9]{64}$/u;
2332
+ var VERSION3 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
2333
+ var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2334
+ var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2335
+ var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
2336
+ var TRAINING_PROVIDER_CAPABILITY = {
2337
+ id: "constal.training-provider",
2338
+ version: "1",
2339
+ hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
2340
+ };
2341
+ function record5(value) {
2342
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1857
2343
  }
1858
- function requiredString2(value, path, maximum = 1024) {
1859
- if (typeof value !== "string" || value.length === 0 || encoder4.encode(value).byteLength > maximum) {
1860
- throw new TypeError(`${path} must be a bounded non-empty string`);
2344
+ function integer(value, field2, minimum, maximum) {
2345
+ if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum) {
2346
+ throw new TypeError(`${field2} is invalid`);
1861
2347
  }
2348
+ return Number(value);
1862
2349
  }
1863
- function exactKeys2(value, allowed, required2, path) {
1864
- if (Object.keys(value).some((key) => !allowed.includes(key)) || required2.some((key) => !Object.hasOwn(value, key))) {
1865
- throw new TypeError(`${path} has invalid keys`);
2350
+ function finite(value, field2, minimum, maximum) {
2351
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum) {
2352
+ throw new TypeError(`${field2} is invalid`);
1866
2353
  }
2354
+ return value;
1867
2355
  }
1868
- function scalar(value) {
1869
- return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
2356
+ function providerPin(value) {
2357
+ const candidate = record5(value);
2358
+ 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");
2359
+ const parts = parseResourceName(candidate.crn);
2360
+ if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
2361
+ return candidate;
1870
2362
  }
1871
- function validateGrant(grant, path) {
1872
- if (!record4(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) {
1873
- throw new TypeError(`${path} is invalid`);
2363
+ function resumePoint(value) {
2364
+ if (value === null) return null;
2365
+ const candidate = record5(value);
2366
+ 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))) {
2367
+ throw new TypeError("training resume point is invalid");
1874
2368
  }
1875
- exactKeys2(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
1876
- grant.actions.forEach(actionPattern);
1877
- grant.resources.forEach(resourcePattern);
2369
+ return candidate;
1878
2370
  }
1879
- function validatePolicyConstraint(constraint, path = "constraint") {
1880
- if (!constraint || typeof constraint !== "object" || Array.isArray(constraint) || typeof constraint.kind !== "string") {
1881
- throw new TypeError(`${path} is invalid`);
1882
- }
1883
- const source = constraint;
1884
- if (constraint.kind === "resource-controls" || constraint.kind === "admission-limit") {
1885
- try {
1886
- validatePolicyGovernanceConstraint(constraint);
1887
- } catch (error) {
1888
- throw new TypeError(`${path} is invalid: ${error instanceof Error ? error.message : String(error)}`);
1889
- }
1890
- return;
1891
- }
1892
- if (constraint.kind === "arguments") {
1893
- exactKeys2(source, ["kind", "schema"], ["kind", "schema"], path);
1894
- if (!record4(constraint.schema) || validateJsonSchemaDefinition(constraint.schema)) throw new TypeError(`${path}.schema is invalid`);
1895
- return;
2371
+ function trainingProviderMetadata(value) {
2372
+ const candidate = record5(value);
2373
+ const checkpoints = record5(candidate?.checkpoints);
2374
+ 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))) {
2375
+ throw new TypeError("Training Provider metadata is invalid");
1896
2376
  }
1897
- if (constraint.kind === "context") {
1898
- exactKeys2(source, ["kind", "equals"], ["kind", "equals"], path);
1899
- if (!record4(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))) {
1900
- throw new TypeError(`${path}.equals is invalid`);
2377
+ const models = candidate.models.map((raw) => {
2378
+ const model = record5(raw);
2379
+ const pricing = record5(model?.pricing);
2380
+ 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))) {
2381
+ throw new TypeError("Training Provider model offer is invalid");
1901
2382
  }
1902
- return;
2383
+ return raw;
2384
+ });
2385
+ if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
2386
+ throw new TypeError("Training Provider model offers must be unique");
1903
2387
  }
1904
- if (constraint.kind === "credential-binding") {
1905
- exactKeys2(source, ["kind", "source", "consumer"], ["kind", "source", "consumer"], path);
1906
- credentialName(constraint.source);
1907
- parseResourceName(constraint.consumer);
1908
- return;
2388
+ return {
2389
+ lifecycleVersion: 1,
2390
+ methods: candidate.methods,
2391
+ models,
2392
+ checkpoints
2393
+ };
2394
+ }
2395
+ function datasetRef(value, field2) {
2396
+ const candidate = record5(value);
2397
+ if (!candidate || typeof candidate.crn !== "string" || parseResourceName(datasetName(candidate.crn)).kind !== "dataset" || typeof candidate.version !== "string" || !VERSION3.test(candidate.version) || typeof candidate.hash !== "string" || !HASH2.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "version", "hash"].includes(key))) {
2398
+ throw new TypeError(`${field2} is invalid`);
1909
2399
  }
1910
- throw new TypeError(`${path}.kind is invalid`);
2400
+ return candidate;
1911
2401
  }
1912
- function validateConstraints(value, path, required2) {
1913
- if (value === void 0 && !required2) return [];
1914
- if (!Array.isArray(value) || required2 && value.length === 0 || value.length > MAX_CONSTRAINTS) {
1915
- throw new TypeError(`${path} is invalid`);
2402
+ function scorerRef(value, field2) {
2403
+ const candidate = record5(value);
2404
+ if (!candidate || typeof candidate.crn !== "string" || parseResourceName(scorerName(candidate.crn)).kind !== "scorer" || typeof candidate.version !== "string" || !VERSION3.test(candidate.version) || typeof candidate.hash !== "string" || !HASH2.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "version", "hash"].includes(key))) {
2405
+ throw new TypeError(`${field2} is invalid`);
1916
2406
  }
1917
- value.forEach((constraint, index) => validatePolicyConstraint(constraint, `${path}[${index}]`));
1918
- return value;
2407
+ return candidate;
1919
2408
  }
1920
- function policyOutcome(value) {
1921
- if (!record4(value) || typeof value.kind !== "string") throw new TypeError("Policy outcome is invalid");
1922
- if (value.kind === "allow") exactKeys2(value, ["kind"], ["kind"], "Policy allow outcome");
1923
- else if (value.kind === "deny") {
1924
- exactKeys2(value, ["kind", "code", "reason"], ["kind", "code"], "Policy deny outcome");
1925
- if (typeof value.code !== "string" || !DENIAL_CODE.test(value.code)) throw new TypeError("Policy denial code is invalid");
1926
- if (value.reason !== void 0) requiredString2(value.reason, "Policy denial reason", MAX_REASON_BYTES);
1927
- } else if (value.kind === "constrain") {
1928
- exactKeys2(value, ["kind", "constraints"], ["kind", "constraints"], "Policy constrain outcome");
1929
- validateConstraints(value.constraints, "Policy constraints", true);
1930
- } else if (value.kind === "substitute") {
1931
- exactKeys2(value, ["kind", "value", "constraints"], ["kind", "value"], "Policy substitute outcome");
1932
- canonicalJson(value.value);
1933
- validateConstraints(value.constraints, "Policy constraints", false);
1934
- } else if (value.kind === "require-approval") {
1935
- exactKeys2(value, ["kind", "reason", "constraints"], ["kind"], "Policy approval outcome");
1936
- if (value.reason !== void 0) requiredString2(value.reason, "Policy approval reason", MAX_REASON_BYTES);
1937
- validateConstraints(value.constraints, "Policy constraints", false);
1938
- } else if (value.kind === "grant") {
1939
- exactKeys2(value, ["kind", "grant"], ["kind", "grant"], "Policy grant outcome");
1940
- validateGrant(value.grant, "Policy grant");
1941
- } else throw new TypeError("Policy outcome kind is invalid");
1942
- if (encoder4.encode(canonicalJson(value)).byteLength > MAX_OUTCOME_BYTES) throw new TypeError("Policy outcome is oversized");
1943
- return value;
2409
+ function trainingRecipe(value) {
2410
+ const candidate = record5(value);
2411
+ const allowed = [
2412
+ "method",
2413
+ "baseModel",
2414
+ "dataset",
2415
+ "validationDataset",
2416
+ "scorers",
2417
+ "loraRank",
2418
+ "learningRate",
2419
+ "epochs",
2420
+ "batchSize",
2421
+ "groupSize",
2422
+ "temperature",
2423
+ "seed",
2424
+ "checkpointEvery",
2425
+ "evalEvery",
2426
+ "maxTrainTokens",
2427
+ "maxSampleTokens",
2428
+ "budgetMicroUsd"
2429
+ ];
2430
+ 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");
2431
+ const recipe = {
2432
+ method: candidate.method,
2433
+ baseModel: candidate.baseModel,
2434
+ dataset: datasetRef(candidate.dataset, "training dataset"),
2435
+ validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
2436
+ scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
2437
+ loraRank: integer(candidate.loraRank, "LoRA rank", 1, 256),
2438
+ learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE, 1),
2439
+ epochs: integer(candidate.epochs, "epochs", 1, 100),
2440
+ batchSize: integer(candidate.batchSize, "batch size", 1, 256),
2441
+ groupSize: integer(candidate.groupSize, "group size", 1, 32),
2442
+ temperature: finite(candidate.temperature, "temperature", 0, 2),
2443
+ seed: integer(candidate.seed, "seed", 0, 2147483647),
2444
+ checkpointEvery: integer(candidate.checkpointEvery, "checkpoint interval", 1, 1e6),
2445
+ evalEvery: integer(candidate.evalEvery, "evaluation interval", 1, 1e6),
2446
+ maxTrainTokens: integer(candidate.maxTrainTokens, "training token limit", 1, 1e10),
2447
+ maxSampleTokens: integer(candidate.maxSampleTokens, "sample token limit", 1, 1e9),
2448
+ budgetMicroUsd: integer(candidate.budgetMicroUsd, "training budget", 1, 1e10)
2449
+ };
2450
+ if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
2451
+ return recipe;
1944
2452
  }
1945
-
1946
- // src/policy.ts
1947
- var ID2 = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1948
- var VERSION3 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
1949
- function policy(definition) {
1950
- if (!definition || typeof definition !== "object" || Array.isArray(definition) || Object.keys(definition).some((key) => !["id", "version", "evaluate"].includes(key)) || !ID2.test(definition.id) || !VERSION3.test(definition.version) || typeof definition.evaluate !== "function") throw new TypeError("Policy definition is invalid");
1951
- return Object.freeze(definition);
2453
+ function startTrainingRequest(value) {
2454
+ const candidate = record5(value);
2455
+ 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))) {
2456
+ throw new TypeError("training request is invalid");
2457
+ }
2458
+ return {
2459
+ ...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
2460
+ ...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
2461
+ ...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
2462
+ recipe: trainingRecipe(candidate.recipe),
2463
+ outputModelId: candidate.outputModelId
2464
+ };
1952
2465
  }
1953
- async function evaluatePolicyDefinition(definition, input) {
1954
- return policyOutcome(await definition.evaluate(input));
2466
+ function renderTrainingCompletion(input, expected) {
2467
+ const text2 = (value) => typeof value === "string" ? value : canonicalJson(value);
2468
+ return { prompt: `Input:
2469
+ ${text2(input)}
2470
+
2471
+ Response:
2472
+ `, completion: expected === void 0 || expected === null ? null : text2(expected) };
1955
2473
  }
1956
2474
 
1957
- // src/table.ts
1958
- var identifier = { type: "string", pattern: "^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$", maxLength: 128 };
1959
- var tableName = { type: "string", pattern: "^[a-z0-9][a-z0-9._-]{0,127}$", maxLength: 128 };
1960
- var branchName = { type: "string", pattern: "^[a-z0-9][a-z0-9._/-]{0,127}$", maxLength: 128 };
1961
- var hash2 = { type: "string", pattern: "^[a-f0-9]{64}$" };
1962
- var scalar2 = { type: ["string", "number", "integer", "boolean", "null"], maxLength: 4096 };
1963
- var TABLE_DESCRIBE_SCHEMA = {
1964
- type: "object",
1965
- required: ["table"],
1966
- additionalProperties: false,
1967
- properties: {
1968
- table: tableName,
1969
- branch: branchName,
1970
- snapshot: hash2,
1971
- stageId: hash2,
1972
- waitMs: { type: "integer", minimum: 0, maximum: 25e3 }
1973
- }
2475
+ // packages/sdk/src/model.ts
2476
+ var MODEL_COMPLETION_CAPABILITY = {
2477
+ id: "constal.model-completion",
2478
+ version: "1",
2479
+ hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
1974
2480
  };
1975
- var filterSchema = {
1976
- type: "object",
1977
- required: ["field", "op", "value"],
1978
- additionalProperties: false,
1979
- properties: {
1980
- field: identifier,
1981
- op: { type: "string", enum: ["eq", "ne", "gt", "gte", "lt", "lte", "in", "between"] },
1982
- value: { anyOf: [scalar2, { type: "array", minItems: 1, maxItems: 100, items: scalar2 }] }
2481
+ var MODEL_GENERATION_OPTIONS_SCHEMA = { type: "object", additionalProperties: false, properties: {
2482
+ maxOutputTokens: { type: "integer", minimum: 1, maximum: 1048576 },
2483
+ temperature: { type: "number", minimum: 0, maximum: 2 },
2484
+ effort: { type: "string", minLength: 1 },
2485
+ providerOptions: { type: "object" }
2486
+ } };
2487
+ var MODEL_GENERATION_OPTION_KEYS = Object.freeze(Object.keys(MODEL_GENERATION_OPTIONS_SCHEMA.properties));
2488
+ var MODEL_REQUEST_FIELDS = /* @__PURE__ */ new Set([
2489
+ "model",
2490
+ "system",
2491
+ "messages",
2492
+ "input",
2493
+ "instructions",
2494
+ "tools",
2495
+ "tool_choice",
2496
+ "stream",
2497
+ "stream_options",
2498
+ "max_tokens",
2499
+ "max_completion_tokens",
2500
+ "max_output_tokens",
2501
+ "maxOutputTokens",
2502
+ "temperature",
2503
+ "effort",
2504
+ "reasoning_effort",
2505
+ "inferenceConfig",
2506
+ "n",
2507
+ "best_of",
2508
+ "toolChoice",
2509
+ "rawProtocol",
2510
+ "providerOptions",
2511
+ "provider_options"
2512
+ ]);
2513
+ function modelProviderOptions(value) {
2514
+ if (!record6(value)) throw new TypeError("providerOptions must be a JSON object");
2515
+ let options;
2516
+ try {
2517
+ options = JSON.parse(canonicalJson(value));
2518
+ } catch {
2519
+ throw new TypeError("providerOptions must contain JSON values");
1983
2520
  }
1984
- };
1985
- var TABLE_QUERY_SCHEMA = {
1986
- type: "object",
1987
- required: ["table", "snapshot", "query"],
1988
- additionalProperties: false,
1989
- properties: {
1990
- table: tableName,
1991
- branch: branchName,
1992
- snapshot: hash2,
1993
- query: {
1994
- type: "object",
1995
- additionalProperties: false,
1996
- properties: {
1997
- select: { type: "array", maxItems: 64, uniqueItems: true, items: identifier },
1998
- where: { type: "array", maxItems: 32, items: filterSchema },
1999
- groupBy: { type: "array", maxItems: 16, uniqueItems: true, items: identifier },
2000
- aggregates: { type: "array", maxItems: 32, items: {
2001
- type: "object",
2002
- required: ["fn", "as"],
2003
- additionalProperties: false,
2004
- properties: {
2005
- fn: { type: "string", enum: ["count", "sum", "avg", "min", "max"] },
2006
- field: identifier,
2007
- as: identifier
2008
- }
2009
- } },
2010
- orderBy: { type: "array", maxItems: 8, items: {
2011
- type: "object",
2012
- required: ["field", "direction"],
2013
- additionalProperties: false,
2014
- properties: { field: identifier, direction: { type: "string", enum: ["asc", "desc"] } }
2015
- } },
2016
- limit: { type: "integer", minimum: 1, maximum: 1e3 }
2017
- }
2018
- }
2521
+ for (const key of Object.keys(options)) if (MODEL_REQUEST_FIELDS.has(key)) {
2522
+ throw new TypeError(`providerOptions.${key} belongs to the model invocation contract`);
2019
2523
  }
2020
- };
2021
- function validateStageOutputSpec(value, path = "$.output") {
2022
- if (!value || typeof value !== "object" || Array.isArray(value)) return `${path} must be an object`;
2023
- const output = value;
2024
- const extra = Object.keys(output).find((key) => key !== "schema" && key !== "sortOrder");
2025
- if (extra) return `${path}.${extra} is not allowed`;
2026
- if (!Object.hasOwn(output, "schema")) return `${path}.schema is required`;
2027
- const schemaError = validateJsonSchemaDefinition(output.schema, `${path}.schema`);
2028
- if (schemaError) return schemaError;
2029
- const sortOrder = output.sortOrder ?? [];
2030
- if (!Array.isArray(sortOrder) || sortOrder.length > 64) return `${path}.sortOrder is invalid`;
2031
- const keys = /* @__PURE__ */ new Set();
2032
- for (const [index, raw] of sortOrder.entries()) {
2033
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${path}.sortOrder[${index}] is invalid`;
2034
- const field2 = raw;
2035
- 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)) {
2036
- return `${path}.sortOrder[${index}] is invalid`;
2037
- }
2038
- keys.add(field2.key);
2524
+ if (record6(options.reasoning)?.effort !== void 0 || record6(options.output_config)?.effort !== void 0) {
2525
+ throw new TypeError("Use effort to select model reasoning effort");
2039
2526
  }
2040
- return null;
2527
+ for (const key of ["reasoning", "output_config", "text"]) if (options[key] !== void 0 && !record6(options[key])) {
2528
+ throw new TypeError(`providerOptions.${key} must be a JSON object`);
2529
+ }
2530
+ return options;
2041
2531
  }
2042
- function stageOutput(value) {
2043
- const error = validateStageOutputSpec(value);
2044
- if (error) throw new TypeError(error);
2045
- return value;
2532
+ function applyModelProviderOptions(request, value) {
2533
+ if (value === void 0) return request;
2534
+ const options = modelProviderOptions(value);
2535
+ return {
2536
+ ...request,
2537
+ ...options,
2538
+ ...record6(options.reasoning) ? { reasoning: { ...record6(request.reasoning), ...record6(options.reasoning) } } : {},
2539
+ ...record6(options.output_config) ? { output_config: { ...record6(request.output_config), ...record6(options.output_config) } } : {},
2540
+ ...record6(options.text) ? { text: { ...record6(request.text), ...record6(options.text) } } : {}
2541
+ };
2046
2542
  }
2047
- var tableDescribe = {
2048
- name: "table_describe",
2049
- version: "1",
2050
- description: "Inspect the schema and identity of one exact, queryable Table snapshot before querying it.",
2051
- schema: TABLE_DESCRIBE_SCHEMA,
2052
- maxEffect: "read-only",
2053
- needs: [{ binding: "table_catalog", kind: "service", ops: ["describe"] }],
2054
- async run(args, ctx) {
2055
- return ctx.invoke(ctx.resources.table_catalog, "describe", args);
2543
+ function modelGenerationOptions(source) {
2544
+ const { maxOutputTokens, temperature, effort, providerOptions } = source;
2545
+ if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 1048576)) {
2546
+ throw new TypeError("maxOutputTokens must be an integer from 1 to 1048576");
2056
2547
  }
2057
- };
2058
- var tableQuery = {
2059
- name: "table_query",
2060
- version: "1",
2061
- description: "Query one exact Table snapshot with bounded fields, filters, grouping, aggregates, ordering, and limit.",
2062
- schema: TABLE_QUERY_SCHEMA,
2063
- maxEffect: "read-only",
2064
- needs: [{ binding: "table_catalog", kind: "service", ops: ["query"] }],
2065
- async run(args, ctx) {
2066
- return ctx.invoke(ctx.resources.table_catalog, "query", args);
2548
+ if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2549
+ throw new TypeError("temperature must be a finite number from 0 to 2");
2550
+ }
2551
+ if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2552
+ throw new TypeError("effort must be a nonempty model-supported string");
2067
2553
  }
2068
- };
2069
-
2070
- // src/tools.ts
2071
- var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2072
- var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
2073
- function opTool(binding, op, override = {}) {
2074
- if (!NAME3.test(binding) || !OPERATION2.test(op)) throw new TypeError("opTool binding or operation is invalid");
2075
- const name = override.name ?? op.replaceAll(".", "_");
2076
2554
  return {
2077
- name,
2078
- version: "catalog",
2079
- description: override.description ?? `Invoke ${op} on the bound ${binding} resource.`,
2080
- schema: override.schema ?? { type: "object", additionalProperties: false },
2081
- maxEffect: "read-only",
2082
- needs: [],
2083
- ...override.tier ? { tier: override.tier } : {},
2084
- ...override.once ? { once: override.once } : {},
2085
- ...override.guard ? { guard: override.guard } : {},
2086
- ...override.preview ? { preview: override.preview } : {},
2087
- catalog: { binding, op },
2088
- async run() {
2089
- throw new TypeError(`catalog Tool ${binding}#${op} was not resolved by deployment`);
2090
- }
2555
+ ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2556
+ ...temperature === void 0 ? {} : { temperature },
2557
+ ...effort === void 0 ? {} : { effort },
2558
+ ...providerOptions === void 0 ? {} : { providerOptions: modelProviderOptions(providerOptions) }
2091
2559
  };
2092
2560
  }
2093
- function opTools(binding, ops = []) {
2094
- if (ops.length === 0) throw new TypeError("opTools requires pinned operation names at bundle construction");
2095
- return ops.map((op) => opTool(binding, op));
2561
+ var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2562
+ var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2563
+ var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2564
+ function record6(value) {
2565
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2096
2566
  }
2097
- var WEB_FETCH_ARGUMENT_SCHEMA = {
2098
- type: "object",
2099
- required: ["url"],
2100
- additionalProperties: false,
2101
- properties: {
2102
- url: { type: "string", minLength: 1, maxLength: 2048 },
2103
- accept: { type: "string", maxLength: 256 }
2567
+ function credentialHeader(value, name) {
2568
+ if (value === null || value === void 0) return null;
2569
+ const source = record6(value);
2570
+ if (!source || typeof source.slot !== "string" || !NAME3.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`);
2571
+ return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2572
+ }
2573
+ function normalizeModelGatewayConfig(value) {
2574
+ const source = record6(value);
2575
+ 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) {
2576
+ throw new TypeError("model gateway config is invalid");
2104
2577
  }
2105
- };
2106
- var WEB_SEARCH_ARGUMENT_SCHEMA = {
2107
- type: "object",
2108
- required: ["query"],
2109
- additionalProperties: false,
2110
- properties: {
2111
- query: {
2112
- type: "string",
2113
- minLength: 1,
2114
- maxLength: 4096,
2115
- description: "A self-contained description of the information to find."
2116
- },
2117
- searchQueries: {
2118
- type: "array",
2119
- minItems: 1,
2120
- maxItems: 3,
2121
- uniqueItems: true,
2122
- description: "Optional concise keyword queries that narrow the search.",
2123
- items: { type: "string", minLength: 1, maxLength: 256 }
2124
- },
2125
- maximumResults: {
2126
- type: "integer",
2127
- minimum: 1,
2128
- maximum: 20,
2129
- description: "Maximum number of sources to return."
2130
- },
2131
- maximumCharacters: {
2132
- type: "integer",
2133
- minimum: 1e3,
2134
- maximum: 6e4,
2135
- description: "Maximum total excerpt characters to return."
2136
- },
2137
- includeDomains: {
2138
- type: "array",
2139
- maxItems: 50,
2140
- uniqueItems: true,
2141
- description: "Optional domains to restrict results to.",
2142
- items: { type: "string", minLength: 1, maxLength: 253 }
2143
- },
2144
- excludeDomains: {
2145
- type: "array",
2146
- maxItems: 50,
2147
- uniqueItems: true,
2148
- description: "Optional domains to omit.",
2149
- items: { type: "string", minLength: 1, maxLength: 253 }
2150
- },
2151
- afterDate: {
2152
- type: "string",
2153
- pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
2154
- description: "Optional earliest publication date in YYYY-MM-DD form."
2155
- }
2156
- }
2157
- };
2158
- var webFetch = opTool("web", "get", {
2159
- name: "web_fetch",
2160
- description: "Fetch an HTTPS resource through the bound governed web Resource.",
2161
- schema: WEB_FETCH_ARGUMENT_SCHEMA
2162
- });
2163
- var webSearch = opTool("search", "search", {
2164
- name: "web_search",
2165
- description: "Search the public web through the bound governed search Resource.",
2166
- schema: WEB_SEARCH_ARGUMENT_SCHEMA
2167
- });
2168
- var casTool = {
2169
- name: "cas",
2170
- version: "1",
2171
- description: "Store or load one content-addressed Agent artifact.",
2172
- schema: {
2173
- type: "object",
2174
- required: ["action"],
2175
- additionalProperties: false,
2176
- properties: {
2177
- action: { type: "string", enum: ["put", "get"] },
2178
- value: {},
2179
- ref: { type: "string", pattern: "^[a-f0-9]{64}$" }
2180
- }
2181
- },
2182
- maxEffect: "idempotent",
2183
- needs: [{ binding: "cas", kind: "cas", ops: ["put", "get"] }],
2184
- async run(args, ctx) {
2185
- const input = args && typeof args === "object" && !Array.isArray(args) ? args : {};
2186
- if (input.action === "put") {
2187
- if (!Object.hasOwn(input, "value")) throw new TypeError("cas put requires value");
2188
- return ctx.invoke(ctx.resources.cas, "put", { value: input.value });
2189
- }
2190
- if (input.action === "get") {
2191
- if (typeof input.ref !== "string") throw new TypeError("cas get requires ref");
2192
- return ctx.invoke(ctx.resources.cas, "get", { ref: input.ref });
2193
- }
2194
- throw new TypeError("cas action must be put or get");
2195
- }
2196
- };
2197
-
2198
- // src/memory.ts
2199
- var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 };
2200
- var content = { type: "string", minLength: 1, maxLength: 65536 };
2201
- var metadata = { type: "object", maxProperties: 64 };
2202
- var scope = { type: "string", pattern: "^[a-f0-9]{64}$", maxLength: 64 };
2203
- var record5 = {
2204
- type: "object",
2205
- required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
2206
- additionalProperties: false,
2207
- properties: {
2208
- id,
2209
- content,
2210
- metadata,
2211
- createdAt: { type: "integer", minimum: 0 },
2212
- updatedAt: { type: "integer", minimum: 0 },
2213
- expiresAt: { anyOf: [{ type: "integer", minimum: 0 }, { type: "null" }] }
2578
+ const maxOutputTokens = source.maxOutputTokens === void 0 ? 256 : Number(source.maxOutputTokens);
2579
+ const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2580
+ if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 8192 || temperature !== null && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2581
+ throw new TypeError("model gateway generation limits are invalid");
2214
2582
  }
2215
- };
2216
- var MEMORY_OPERATION_DECLARATIONS = [
2217
- {
2218
- op: "remember",
2219
- description: "Persist or replace one record in the invocation's authenticated Memory partition.",
2220
- schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata, scope } },
2221
- resultSchema: record5,
2222
- effect: "idempotent",
2223
- recovery: { kind: "idempotency-key" },
2224
- async: false,
2225
- usage: { meter: "none", priceTable: null }
2226
- },
2227
- {
2228
- op: "search",
2229
- description: "Retrieve relevant records from the invocation's authenticated Memory partition.",
2230
- schema: {
2231
- type: "object",
2232
- required: ["query"],
2233
- additionalProperties: false,
2234
- properties: { query: { type: "string", minLength: 1, maxLength: 8192 }, limit: { type: "integer", minimum: 1, maximum: 100 }, scope }
2235
- },
2236
- resultSchema: {
2237
- type: "object",
2238
- required: ["hits"],
2239
- additionalProperties: false,
2240
- properties: { hits: { type: "array", maxItems: 100, items: {
2241
- ...record5,
2242
- required: [...record5.required, "score"],
2243
- properties: { ...record5.properties, score: { type: "number", minimum: 0, maximum: 1 } }
2244
- } } }
2245
- },
2246
- effect: "read-only",
2247
- recovery: { kind: "repeat" },
2248
- async: false,
2249
- usage: { meter: "none", priceTable: null }
2250
- },
2251
- {
2252
- op: "get",
2253
- description: "Read one record from the invocation's authenticated Memory partition.",
2254
- schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2255
- resultSchema: { anyOf: [record5, { type: "null" }] },
2256
- effect: "read-only",
2257
- recovery: { kind: "repeat" },
2258
- async: false,
2259
- usage: { meter: "none", priceTable: null }
2260
- },
2261
- {
2262
- op: "delete",
2263
- description: "Delete one record from the invocation's authenticated Memory partition.",
2264
- schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2265
- resultSchema: { type: "object", required: ["deleted"], additionalProperties: false, properties: { deleted: { type: "boolean" } } },
2266
- effect: "idempotent",
2267
- recovery: { kind: "idempotency-key" },
2268
- async: false,
2269
- usage: { meter: "none", priceTable: null }
2270
- },
2271
- {
2272
- op: "purge",
2273
- description: "Delete every record in the invocation's authenticated Memory partition.",
2274
- schema: { type: "object", additionalProperties: false, properties: {} },
2275
- resultSchema: {
2276
- type: "object",
2277
- required: ["deleted"],
2278
- additionalProperties: false,
2279
- properties: { deleted: { type: "integer", minimum: 0 } }
2280
- },
2281
- effect: "idempotent",
2282
- recovery: { kind: "idempotency-key" },
2283
- async: false,
2284
- usage: { meter: "none", priceTable: null }
2583
+ const normalized = {
2584
+ baseUrl: source.baseUrl,
2585
+ protocol: source.protocol,
2586
+ model: source.model,
2587
+ maxOutputTokens,
2588
+ temperature,
2589
+ gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2590
+ providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2591
+ };
2592
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2593
+ throw new TypeError("gateway and provider credentials cannot share one header");
2285
2594
  }
2286
- ];
2287
-
2288
- // src/integration.ts
2289
- var ApiError = class extends Error {
2290
- constructor(status, body, disposition = "uncertain") {
2291
- super(`${status}: ${body}`);
2292
- this.status = status;
2293
- this.body = body;
2294
- this.disposition = disposition;
2295
- this.name = "ApiError";
2595
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2596
+ throw new TypeError("gateway and provider credentials cannot share one slot");
2296
2597
  }
2297
- status;
2298
- body;
2299
- disposition;
2300
- };
2301
- var IntegrationRequestNotSent = class extends Error {
2302
- constructor(message = "integration request was not sent") {
2303
- super(message);
2304
- this.name = "IntegrationRequestNotSent";
2598
+ modelGatewayEndpoint(normalized);
2599
+ return normalized;
2600
+ }
2601
+ function modelGatewayEndpoint(config) {
2602
+ let endpoint;
2603
+ try {
2604
+ endpoint = new URL(config.baseUrl);
2605
+ } catch {
2606
+ throw new TypeError("model gateway baseUrl is invalid");
2305
2607
  }
2306
- };
2307
- var TerminalIntegrationFailure = class extends Error {
2308
- constructor(message = "integration operation failed terminally") {
2309
- super(message);
2310
- this.name = "TerminalIntegrationFailure";
2608
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2609
+ throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
2311
2610
  }
2312
- };
2313
- var OPERATION3 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
2314
- function integrationEgressPolicy(value) {
2315
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2316
- if (!source || !Array.isArray(source.rules) || source.rules.length > 128 || Object.keys(source).some((key) => key !== "rules")) {
2317
- throw new TypeError("integration egress policy is invalid");
2611
+ const hostname = endpoint.hostname.toLowerCase();
2612
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2613
+ throw new TypeError("model gateway baseUrl must use a public hostname");
2318
2614
  }
2319
- const rules = source.rules.map((raw) => {
2320
- const rule = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2321
- const paths = Number(rule?.pathPrefix !== void 0) + Number(rule?.pathExact !== void 0);
2322
- 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))) {
2323
- throw new TypeError("integration egress rule is invalid");
2324
- }
2325
- let origin;
2326
- try {
2327
- origin = new URL(rule.origin);
2328
- } catch {
2329
- throw new TypeError("integration egress origin is invalid");
2330
- }
2331
- if (origin.protocol !== "https:" || origin.origin !== rule.origin || origin.username || origin.password) {
2332
- throw new TypeError("integration egress origin is invalid");
2333
- }
2334
- const path = String(rule.pathPrefix ?? rule.pathExact);
2335
- if (!path.startsWith("/") || path.includes("?") || path.includes("#")) throw new TypeError("integration egress path is invalid");
2336
- return rule;
2337
- });
2338
- return { rules };
2615
+ const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2616
+ if (!suffix) throw new TypeError("model gateway protocol is invalid");
2617
+ endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2618
+ return endpoint;
2339
2619
  }
2340
-
2341
- // src/training.ts
2342
- var HASH2 = /^[a-f0-9]{64}$/u;
2343
- var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
2344
- var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2345
- var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2346
- var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
2347
- var TRAINING_PROVIDER_CAPABILITY = {
2348
- id: "constal.training-provider",
2349
- version: "1",
2350
- hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
2351
- };
2352
- function record6(value) {
2353
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2354
- }
2355
- function integer(value, field2, minimum, maximum) {
2356
- if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum) {
2357
- throw new TypeError(`${field2} is invalid`);
2358
- }
2359
- return Number(value);
2360
- }
2361
- function finite(value, field2, minimum, maximum) {
2362
- if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum) {
2363
- throw new TypeError(`${field2} is invalid`);
2364
- }
2365
- return value;
2366
- }
2367
- function providerPin(value) {
2368
- const candidate = record6(value);
2369
- 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");
2370
- const parts = parseResourceName(candidate.crn);
2371
- if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
2372
- return candidate;
2373
- }
2374
- function resumePoint(value) {
2375
- if (value === null) return null;
2376
- const candidate = record6(value);
2377
- 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))) {
2378
- throw new TypeError("training resume point is invalid");
2379
- }
2380
- return candidate;
2381
- }
2382
- function trainingProviderMetadata(value) {
2383
- const candidate = record6(value);
2384
- const checkpoints = record6(candidate?.checkpoints);
2385
- 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))) {
2386
- throw new TypeError("Training Provider metadata is invalid");
2387
- }
2388
- const models = candidate.models.map((raw) => {
2389
- const model = record6(raw);
2390
- const pricing = record6(model?.pricing);
2391
- 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))) {
2392
- throw new TypeError("Training Provider model offer is invalid");
2393
- }
2394
- return raw;
2395
- });
2396
- if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
2397
- throw new TypeError("Training Provider model offers must be unique");
2398
- }
2399
- return {
2400
- lifecycleVersion: 1,
2401
- methods: candidate.methods,
2402
- models,
2403
- checkpoints
2404
- };
2405
- }
2406
- function datasetRef(value, field2) {
2407
- const candidate = record6(value);
2408
- 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))) {
2409
- throw new TypeError(`${field2} is invalid`);
2410
- }
2411
- return candidate;
2412
- }
2413
- function scorerRef(value, field2) {
2414
- const candidate = record6(value);
2415
- 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))) {
2416
- throw new TypeError(`${field2} is invalid`);
2417
- }
2418
- return candidate;
2419
- }
2420
- function trainingRecipe(value) {
2421
- const candidate = record6(value);
2422
- const allowed = [
2423
- "method",
2424
- "baseModel",
2425
- "dataset",
2426
- "validationDataset",
2427
- "scorers",
2428
- "loraRank",
2429
- "learningRate",
2430
- "epochs",
2431
- "batchSize",
2432
- "groupSize",
2433
- "temperature",
2434
- "seed",
2435
- "checkpointEvery",
2436
- "evalEvery",
2437
- "maxTrainTokens",
2438
- "maxSampleTokens",
2439
- "budgetMicroUsd"
2440
- ];
2441
- 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");
2442
- const recipe = {
2443
- method: candidate.method,
2444
- baseModel: candidate.baseModel,
2445
- dataset: datasetRef(candidate.dataset, "training dataset"),
2446
- validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
2447
- scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
2448
- loraRank: integer(candidate.loraRank, "LoRA rank", 1, 256),
2449
- learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE, 1),
2450
- epochs: integer(candidate.epochs, "epochs", 1, 100),
2451
- batchSize: integer(candidate.batchSize, "batch size", 1, 256),
2452
- groupSize: integer(candidate.groupSize, "group size", 1, 32),
2453
- temperature: finite(candidate.temperature, "temperature", 0, 2),
2454
- seed: integer(candidate.seed, "seed", 0, 2147483647),
2455
- checkpointEvery: integer(candidate.checkpointEvery, "checkpoint interval", 1, 1e6),
2456
- evalEvery: integer(candidate.evalEvery, "evaluation interval", 1, 1e6),
2457
- maxTrainTokens: integer(candidate.maxTrainTokens, "training token limit", 1, 1e10),
2458
- maxSampleTokens: integer(candidate.maxSampleTokens, "sample token limit", 1, 1e9),
2459
- budgetMicroUsd: integer(candidate.budgetMicroUsd, "training budget", 1, 1e10)
2460
- };
2461
- if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
2462
- return recipe;
2463
- }
2464
- function startTrainingRequest(value) {
2465
- const candidate = record6(value);
2466
- 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))) {
2467
- throw new TypeError("training request is invalid");
2468
- }
2469
- return {
2470
- ...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
2471
- ...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
2472
- ...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
2473
- recipe: trainingRecipe(candidate.recipe),
2474
- outputModelId: candidate.outputModelId
2475
- };
2476
- }
2477
- function renderTrainingCompletion(input, expected) {
2478
- const text2 = (value) => typeof value === "string" ? value : canonicalJson(value);
2479
- return { prompt: `Input:
2480
- ${text2(input)}
2481
-
2482
- Response:
2483
- `, completion: expected === void 0 || expected === null ? null : text2(expected) };
2484
- }
2485
-
2486
- // src/model.ts
2487
- var MODEL_COMPLETION_CAPABILITY = {
2488
- id: "constal.model-completion",
2489
- version: "1",
2490
- hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
2491
- };
2492
- function modelGenerationOptions(source) {
2493
- const { maxOutputTokens, temperature, effort } = source;
2494
- if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 1048576)) {
2495
- throw new TypeError("maxOutputTokens must be an integer from 1 to 1048576");
2496
- }
2497
- if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2498
- throw new TypeError("temperature must be a finite number from 0 to 2");
2499
- }
2500
- if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2501
- throw new TypeError("effort must be a nonempty model-supported string");
2502
- }
2503
- return {
2504
- ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2505
- ...temperature === void 0 ? {} : { temperature },
2506
- ...effort === void 0 ? {} : { effort }
2507
- };
2508
- }
2509
- var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2510
- var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2511
- var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2512
- function record7(value) {
2513
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2514
- }
2515
- function credentialHeader(value, name) {
2516
- if (value === null || value === void 0) return null;
2517
- const source = record7(value);
2518
- 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`);
2519
- return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2520
- }
2521
- function normalizeModelGatewayConfig(value) {
2522
- const source = record7(value);
2523
- 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) {
2524
- throw new TypeError("model gateway config is invalid");
2525
- }
2526
- const maxOutputTokens = source.maxOutputTokens === void 0 ? 256 : Number(source.maxOutputTokens);
2527
- const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2528
- if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 8192 || temperature !== null && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2529
- throw new TypeError("model gateway generation limits are invalid");
2530
- }
2531
- const normalized = {
2532
- baseUrl: source.baseUrl,
2533
- protocol: source.protocol,
2534
- model: source.model,
2535
- maxOutputTokens,
2536
- temperature,
2537
- gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2538
- providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2539
- };
2540
- if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2541
- throw new TypeError("gateway and provider credentials cannot share one header");
2542
- }
2543
- if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2544
- throw new TypeError("gateway and provider credentials cannot share one slot");
2545
- }
2546
- modelGatewayEndpoint(normalized);
2547
- return normalized;
2548
- }
2549
- function modelGatewayEndpoint(config) {
2550
- let endpoint;
2551
- try {
2552
- endpoint = new URL(config.baseUrl);
2553
- } catch {
2554
- throw new TypeError("model gateway baseUrl is invalid");
2555
- }
2556
- if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2557
- throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
2558
- }
2559
- const hostname = endpoint.hostname.toLowerCase();
2560
- if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2561
- throw new TypeError("model gateway baseUrl must use a public hostname");
2562
- }
2563
- const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2564
- if (!suffix) throw new TypeError("model gateway protocol is invalid");
2565
- endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2566
- return endpoint;
2567
- }
2568
- function modelPrompt(args) {
2569
- return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2620
+ function modelPrompt(args) {
2621
+ return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2570
2622
  }
2571
2623
  function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2572
2624
  const { effort } = modelGenerationOptions(args);
@@ -2577,17 +2629,17 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
2577
2629
  throw new TypeError("required model Tool choice needs at least one offered Tool");
2578
2630
  }
2579
2631
  const prompt = modelPrompt(args);
2580
- if (protocol === "anthropic") return {
2632
+ if (protocol === "anthropic") return applyModelProviderOptions({
2581
2633
  model,
2582
2634
  system: args.system ?? "",
2583
2635
  messages: [{ role: "user", content: prompt }],
2584
2636
  max_tokens: maxOutputTokens,
2585
2637
  ...effort === void 0 ? {} : { output_config: { effort } },
2586
2638
  ...temperature === null ? {} : { temperature },
2587
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
2639
+ ...args.tools?.length ? { tools: args.tools.map((tool2) => ({ name: tool2.name, description: tool2.description, input_schema: tool2.schema })) } : {},
2588
2640
  ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
2589
- };
2590
- if (protocol === "openai") return {
2641
+ }, args.providerOptions);
2642
+ if (protocol === "openai") return applyModelProviderOptions({
2591
2643
  model,
2592
2644
  messages: [
2593
2645
  ...args.system ? [{ role: "developer", content: args.system }] : [],
@@ -2596,12 +2648,12 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
2596
2648
  max_completion_tokens: maxOutputTokens,
2597
2649
  ...effort === void 0 ? {} : { reasoning_effort: effort },
2598
2650
  ...temperature === null ? {} : { temperature },
2599
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({
2651
+ ...args.tools?.length ? { tools: args.tools.map((tool2) => ({
2600
2652
  type: "function",
2601
- function: { name: tool.name, description: tool.description, parameters: tool.schema }
2653
+ function: { name: tool2.name, description: tool2.description, parameters: tool2.schema }
2602
2654
  })) } : {},
2603
2655
  ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
2604
- };
2656
+ }, args.providerOptions);
2605
2657
  throw new TypeError("model gateway protocol is invalid");
2606
2658
  }
2607
2659
  function integer2(value) {
@@ -2617,21 +2669,21 @@ function costMetadata(usage) {
2617
2669
  };
2618
2670
  }
2619
2671
  function modelProtocolResult(protocol, raw, provider, model) {
2620
- const source = record7(raw) ?? {};
2672
+ const source = record6(raw) ?? {};
2621
2673
  const toolCalls = [];
2622
2674
  let content2 = "";
2623
2675
  let usage;
2624
2676
  if (protocol === "anthropic") {
2625
2677
  const blocks = Array.isArray(source.content) ? source.content : [];
2626
2678
  content2 = blocks.map((candidate) => {
2627
- const block = record7(candidate);
2679
+ const block = record6(candidate);
2628
2680
  if (block?.type === "text" && typeof block.text === "string") return block.text;
2629
2681
  if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
2630
2682
  toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
2631
2683
  }
2632
2684
  return "";
2633
2685
  }).join("");
2634
- const values = record7(source.usage) ?? {};
2686
+ const values = record6(source.usage) ?? {};
2635
2687
  const cached = integer2(values.cache_read_input_tokens);
2636
2688
  usage = {
2637
2689
  input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
@@ -2640,12 +2692,12 @@ function modelProtocolResult(protocol, raw, provider, model) {
2640
2692
  ...costMetadata(values)
2641
2693
  };
2642
2694
  } else if (protocol === "openai") {
2643
- const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2644
- const message = record7(choice.message) ?? {};
2645
- content2 = typeof message.content === "string" ? message.content : "";
2646
- for (const candidate of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
2647
- const call = record7(candidate);
2648
- const fn = record7(call?.function);
2695
+ const choice = record6(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2696
+ const message2 = record6(choice.message) ?? {};
2697
+ content2 = typeof message2.content === "string" ? message2.content : "";
2698
+ for (const candidate of Array.isArray(message2.tool_calls) ? message2.tool_calls : []) {
2699
+ const call = record6(candidate);
2700
+ const fn = record6(call?.function);
2649
2701
  if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
2650
2702
  let args;
2651
2703
  try {
@@ -2653,309 +2705,1048 @@ function modelProtocolResult(protocol, raw, provider, model) {
2653
2705
  } catch {
2654
2706
  throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
2655
2707
  }
2656
- toolCalls.push({ id: call.id, name: fn.name, args });
2708
+ toolCalls.push({ id: call.id, name: fn.name, args });
2709
+ }
2710
+ const values = record6(source.usage) ?? {};
2711
+ usage = {
2712
+ input: integer2(values.prompt_tokens),
2713
+ output: integer2(values.completion_tokens),
2714
+ cached: integer2(record6(values.prompt_tokens_details)?.cached_tokens),
2715
+ ...costMetadata(values)
2716
+ };
2717
+ } else throw new TypeError("model gateway protocol is invalid");
2718
+ if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
2719
+ return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model, completion: modelCompletionStatus(protocol, raw) };
2720
+ }
2721
+ function modelCompletionStatus(protocol, raw) {
2722
+ const source = record6(raw) ?? {};
2723
+ const value = protocol === "anthropic" ? source.stop_reason : record6(Array.isArray(source.choices) ? source.choices[0] : null)?.finish_reason;
2724
+ const reason = typeof value === "string" ? value : null;
2725
+ const complete = protocol === "anthropic" ? ["end_turn", "tool_use", "stop_sequence"] : ["stop", "tool_calls", "function_call"];
2726
+ const incomplete = protocol === "anthropic" ? ["max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"] : ["length", "content_filter", "error", "cancelled", "canceled"];
2727
+ return { status: reason !== null && complete.includes(reason) ? "complete" : reason !== null && incomplete.includes(reason) ? "incomplete" : "unknown", reason };
2728
+ }
2729
+
2730
+ // packages/sdk/src/gateway.ts
2731
+ async function checkpointArtifactRef(value) {
2732
+ return await sha256Hex(canonicalJson(value));
2733
+ }
2734
+ var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2735
+ var HASH3 = /^[a-f0-9]{64}$/u;
2736
+ var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
2737
+ function httpsUrl(value, field2) {
2738
+ if (value === void 0) return;
2739
+ if (typeof value !== "string" || value.length > 2048) throw new TypeError(`${field2} is invalid`);
2740
+ let parsed;
2741
+ try {
2742
+ parsed = new URL(value);
2743
+ } catch {
2744
+ throw new TypeError(`${field2} is invalid`);
2745
+ }
2746
+ if (parsed.protocol !== "https:") throw new TypeError(`${field2} is invalid`);
2747
+ }
2748
+ function slotMetadata(value) {
2749
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Gateway Credential slots are invalid");
2750
+ const entries = Object.entries(value);
2751
+ if (entries.length > 32) throw new TypeError("Gateway Credential slots are invalid");
2752
+ const output = {};
2753
+ for (const [slot, raw] of entries) {
2754
+ const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2755
+ 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))) {
2756
+ throw new TypeError("Gateway Credential slots are invalid");
2757
+ }
2758
+ httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
2759
+ output[slot] = item;
2760
+ }
2761
+ return output;
2762
+ }
2763
+ function configEgressBindings(value) {
2764
+ if (value === void 0) return [];
2765
+ if (!Array.isArray(value) || value.length > 16) throw new TypeError("Gateway config egress bindings are invalid");
2766
+ return value.map((raw) => {
2767
+ const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2768
+ 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))) {
2769
+ throw new TypeError("Gateway config egress bindings are invalid");
2770
+ }
2771
+ return {
2772
+ urlProperty: String(item.urlProperty),
2773
+ operations: [...new Set(item.operations)],
2774
+ methods: [...new Set(item.methods)]
2775
+ };
2776
+ });
2777
+ }
2778
+ function discoverySetup(value) {
2779
+ if (value === void 0) return void 0;
2780
+ const item = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2781
+ 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))) {
2782
+ throw new TypeError("Gateway discovery setup is invalid");
2783
+ }
2784
+ return { operation: String(item.operation), resultConfigProperty: String(item.resultConfigProperty) };
2785
+ }
2786
+ function checkpointImportMetadata(value) {
2787
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2788
+ 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))) {
2789
+ throw new TypeError("Gateway checkpoint import metadata is invalid");
2790
+ }
2791
+ return { lifecycleVersion: 1, formats: [...source.formats] };
2792
+ }
2793
+ function checkpointImportRequest(value) {
2794
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2795
+ const provenance = source?.source && typeof source.source === "object" && !Array.isArray(source.source) ? source.source : null;
2796
+ const provider = provenance?.provider && typeof provenance.provider === "object" && !Array.isArray(provenance.provider) ? provenance.provider : null;
2797
+ const checkpoint = provenance?.checkpoint && typeof provenance.checkpoint === "object" && !Array.isArray(provenance.checkpoint) ? provenance.checkpoint : null;
2798
+ const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
2799
+ const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
2800
+ const model = source?.model && typeof source.model === "object" && !Array.isArray(source.model) ? source.model : null;
2801
+ 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))) {
2802
+ throw new TypeError("checkpoint import request is invalid");
2803
+ }
2804
+ try {
2805
+ if (new TextEncoder().encode(canonicalJson(artifactValue)).byteLength > 65536) throw new TypeError();
2806
+ } catch {
2807
+ throw new TypeError("checkpoint import request is invalid");
2808
+ }
2809
+ try {
2810
+ parseResourceName(String(provider.crn));
2811
+ } catch {
2812
+ throw new TypeError("checkpoint import request is invalid");
2813
+ }
2814
+ return source;
2815
+ }
2816
+ function checkpointDeploymentRequest(value) {
2817
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2818
+ const gateway2 = source?.gateway && typeof source.gateway === "object" && !Array.isArray(source.gateway) ? source.gateway : null;
2819
+ 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))) {
2820
+ throw new TypeError("checkpoint deployment request is invalid");
2821
+ }
2822
+ try {
2823
+ parseResourceName(gateway2.crn);
2824
+ } catch {
2825
+ throw new TypeError("checkpoint deployment request is invalid");
2826
+ }
2827
+ return { gateway: gateway2, import: checkpointImportRequest(source.import) };
2828
+ }
2829
+ var MODEL_ID_CONTROL = /[\u0000-\u001f\u007f]/u;
2830
+ var modelModalitiesSchema = {
2831
+ type: "array",
2832
+ minItems: 1,
2833
+ maxItems: 16,
2834
+ uniqueItems: true,
2835
+ items: { type: "string", pattern: SLOT.source }
2836
+ };
2837
+ var GATEWAY_MODEL_OFFER_SCHEMA = {
2838
+ type: "object",
2839
+ additionalProperties: false,
2840
+ required: ["id", "displayName", "contextTokens", "maxOutputTokens", "pricing"],
2841
+ properties: {
2842
+ id: { type: "string", minLength: 1, maxLength: 512 },
2843
+ displayName: { type: "string", minLength: 1, maxLength: 128 },
2844
+ contextTokens: { type: "integer", minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
2845
+ maxOutputTokens: { type: "integer", minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
2846
+ inputModalities: modelModalitiesSchema,
2847
+ outputModalities: modelModalitiesSchema,
2848
+ pricing: { type: ["object", "null"] }
2849
+ }
2850
+ };
2851
+ function gatewayModelOffer(value) {
2852
+ const source = value;
2853
+ if (validateJsonSchema(value, GATEWAY_MODEL_OFFER_SCHEMA) || source.id !== source.id.trim() || MODEL_ID_CONTROL.test(source.id) || source.maxOutputTokens > source.contextTokens) {
2854
+ throw new TypeError("Gateway Model offer is invalid");
2855
+ }
2856
+ const pricing = source.pricing === null ? null : modelAdvertisedPricing(source.pricing);
2857
+ const { inputModalities, outputModalities } = source;
2858
+ return {
2859
+ id: source.id,
2860
+ displayName: source.displayName,
2861
+ contextTokens: Number(source.contextTokens),
2862
+ maxOutputTokens: Number(source.maxOutputTokens),
2863
+ ...inputModalities ? { inputModalities } : {},
2864
+ ...outputModalities ? { outputModalities } : {},
2865
+ pricing
2866
+ };
2867
+ }
2868
+ function assertNonSecretGatewayConfig(value, field2 = "config") {
2869
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
2870
+ const source = value;
2871
+ if (source.format === "password" || /(?:secret|password|private[-_ ]?key|access[-_ ]?token|api[-_ ]?key)/iu.test(field2)) {
2872
+ throw new TypeError("Gateway secrets must use declared Credential slots");
2873
+ }
2874
+ const properties = source.properties && typeof source.properties === "object" && !Array.isArray(source.properties) ? source.properties : {};
2875
+ for (const [name, declaration] of Object.entries(properties)) assertNonSecretGatewayConfig(declaration, name);
2876
+ if (source.items) assertNonSecretGatewayConfig(source.items, field2);
2877
+ if (source.additionalProperties && typeof source.additionalProperties === "object") {
2878
+ assertNonSecretGatewayConfig(source.additionalProperties, field2);
2879
+ }
2880
+ }
2881
+ function gatewayPackageMetadata(value) {
2882
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2883
+ 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 ?? ""))) {
2884
+ throw new TypeError("Gateway package metadata is invalid");
2885
+ }
2886
+ httpsUrl(source.documentationUrl, "Gateway documentation URL");
2887
+ const credentialSlots = slotMetadata(source.credentialSlots);
2888
+ const modelOffers = source.modelOffers === void 0 ? [] : Array.isArray(source.modelOffers) ? source.modelOffers.map(gatewayModelOffer) : (() => {
2889
+ throw new TypeError("Gateway Model offers are invalid");
2890
+ })();
2891
+ if (modelOffers.length > 512 || new Set(modelOffers.map((offer) => offer.id)).size !== modelOffers.length) {
2892
+ throw new TypeError("Gateway Model offers are invalid");
2893
+ }
2894
+ const capabilities = source.capabilities.map(capabilityContractRef);
2895
+ if (new Set(capabilities.map((contract) => `${contract.id}@${contract.version}#${contract.hash}`)).size !== capabilities.length) {
2896
+ throw new TypeError("Gateway capability contracts must be unique");
2897
+ }
2898
+ const egress = integrationEgressPolicy(source.egress);
2899
+ const configEgress = configEgressBindings(source.configEgress);
2900
+ const discovery = discoverySetup(source.discovery);
2901
+ const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
2902
+ const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
2903
+ if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
2904
+ throw new TypeError("Training Provider packages must implement the exact Training Provider capability");
2905
+ }
2906
+ 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))) {
2907
+ throw new TypeError("Checkpoint import Gateways must implement exact completion and checkpoint import capabilities");
2908
+ }
2909
+ return {
2910
+ lifecycleVersion: 1,
2911
+ displayName: source.displayName,
2912
+ description: source.description,
2913
+ ...typeof source.documentationUrl === "string" ? { documentationUrl: source.documentationUrl } : {},
2914
+ ...typeof source.service === "string" ? { service: source.service } : {},
2915
+ credentialSlots,
2916
+ modelOffers,
2917
+ capabilities,
2918
+ billing: { upstreamPayer: source.billing.upstreamPayer },
2919
+ egress,
2920
+ ...configEgress.length ? { configEgress } : {},
2921
+ ...discovery ? { discovery } : {},
2922
+ ...training ? { training } : {},
2923
+ ...checkpointImport ? { checkpointImport } : {}
2924
+ };
2925
+ }
2926
+ function resolveGatewayEgress(metadata2, config) {
2927
+ const derived = (metadata2.configEgress ?? []).map((binding) => {
2928
+ let endpoint;
2929
+ try {
2930
+ endpoint = new URL(String(config[binding.urlProperty] ?? ""));
2931
+ } catch {
2932
+ throw new TypeError(`Gateway ${binding.urlProperty} must be an HTTPS endpoint`);
2933
+ }
2934
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) {
2935
+ throw new TypeError(`Gateway ${binding.urlProperty} must be an exact HTTPS endpoint without credentials, query, or fragment`);
2936
+ }
2937
+ return { operations: binding.operations, origin: endpoint.origin, pathExact: endpoint.pathname, methods: binding.methods };
2938
+ });
2939
+ return integrationEgressPolicy({ rules: [...metadata2.egress.rules, ...derived] });
2940
+ }
2941
+ function gateway(definition2) {
2942
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition2.id) || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition2.version) || !["cas", "web", "service", "mcp", "db", "browser", "sandbox-pool", "vault"].includes(definition2.kind) || typeof definition2.catalog !== "function" || typeof definition2.invoke !== "function" || definition2.reconcile !== void 0 && typeof definition2.reconcile !== "function" || definition2.cancel !== void 0 && typeof definition2.cancel !== "function") {
2943
+ throw new TypeError("Gateway definition is invalid");
2944
+ }
2945
+ const schemaError = validateJsonSchemaDefinition(definition2.configSchema);
2946
+ if (schemaError) throw new TypeError(`Gateway config schema is invalid: ${schemaError}`);
2947
+ const configSchema = definition2.configSchema;
2948
+ if (configSchema.type !== "object") throw new TypeError('Gateway config schema root type must be "object"');
2949
+ if (configSchema.additionalProperties !== false) throw new TypeError("Gateway config schema must reject unknown root fields");
2950
+ assertNonSecretGatewayConfig(configSchema);
2951
+ const gateway2 = gatewayPackageMetadata({
2952
+ lifecycleVersion: 1,
2953
+ displayName: definition2.displayName,
2954
+ description: definition2.description,
2955
+ documentationUrl: definition2.documentationUrl,
2956
+ service: definition2.service,
2957
+ credentialSlots: definition2.credentialSlots,
2958
+ modelOffers: definition2.modelOffers ?? [],
2959
+ capabilities: definition2.capabilities,
2960
+ billing: definition2.billing,
2961
+ egress: definition2.egress,
2962
+ configEgress: definition2.configEgress,
2963
+ discovery: definition2.discovery,
2964
+ training: definition2.training,
2965
+ checkpointImport: definition2.checkpointImport
2966
+ });
2967
+ const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
2968
+ for (const binding of gateway2.configEgress ?? []) {
2969
+ const property = properties[binding.urlProperty];
2970
+ if (!property || property.type !== "string" || property.format !== "uri") {
2971
+ throw new TypeError(`Gateway config egress property must be a URI string: ${binding.urlProperty}`);
2972
+ }
2973
+ }
2974
+ if (gateway2.discovery) {
2975
+ const property = properties[gateway2.discovery.resultConfigProperty];
2976
+ if (!property || property.type !== "array") throw new TypeError("Gateway discovery result config property must be an array");
2977
+ const required2 = Array.isArray(configSchema.required) ? configSchema.required : [];
2978
+ if (!required2.includes(gateway2.discovery.resultConfigProperty)) {
2979
+ throw new TypeError("Gateway discovery result config property must be required");
2980
+ }
2981
+ if (property.readOnly !== true) throw new TypeError("Gateway discovery result config property must be read-only");
2982
+ }
2983
+ const authoredCatalog = definition2.catalog;
2984
+ const wrapped = { ...definition2, metadata: gateway2, catalog(config) {
2985
+ const declarations = authoredCatalog(config);
2986
+ if (gateway2.checkpointImport) {
2987
+ const operation = declarations.find((candidate) => candidate.op === "importCheckpoint");
2988
+ if (!operation || !operation.async || operation.effect !== "reconcilable" || operation.recovery.kind !== "reconcile") {
2989
+ throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
2990
+ }
2991
+ }
2992
+ return declarations;
2993
+ } };
2994
+ return Object.freeze(wrapped);
2995
+ }
2996
+ function trainingProvider(definition2) {
2997
+ const authoredCatalog = definition2.catalog;
2998
+ return gateway({
2999
+ ...definition2,
3000
+ capabilities: [...definition2.capabilities, ...definition2.capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash) ? [] : [TRAINING_PROVIDER_CAPABILITY]],
3001
+ catalog(config) {
3002
+ const declarations = authoredCatalog(config);
3003
+ const train = declarations.find((operation) => operation.op === "train");
3004
+ if (!train || !train.async || train.effect !== "reconcilable" || train.recovery.kind !== "reconcile") {
3005
+ throw new TypeError("Training Provider train must be asynchronous, reconcilable, and recovered by reconcile");
3006
+ }
3007
+ return declarations;
3008
+ }
3009
+ });
3010
+ }
3011
+ var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
3012
+ id: "constal.model-checkpoint-import",
3013
+ version: "1",
3014
+ hash: "49563823899586a87dcee82e9db969af5f2f5364adb3eb808a19e86b862e87ba"
3015
+ };
3016
+ var MCP_CLIENT_CAPABILITY = {
3017
+ id: "constal.mcp-client",
3018
+ version: "1",
3019
+ hash: "a694af71191432e75980dc73962d9239dc8ea324aff084f183a2f45603bd2267"
3020
+ };
3021
+
3022
+ // packages/sdk/src/constal-api.ts
3023
+ var CONSTAL_API_CAPABILITY = "constal.api";
3024
+ var CONSTAL_API_VERSION = "1";
3025
+ var CONSTAL_API_OPERATIONS = [
3026
+ "describe",
3027
+ "query",
3028
+ "get",
3029
+ "relations",
3030
+ "explainPolicy",
3031
+ "plan",
3032
+ "apply",
3033
+ "observe"
3034
+ ];
3035
+ var CONSTAL_API_BOUNDS = {
3036
+ defaultPageSize: 50,
3037
+ maximumPageSize: 200,
3038
+ maximumRelationDepth: 3,
3039
+ maximumPlanOperations: 64,
3040
+ maximumInputBytes: 1048576,
3041
+ planTtlMs: 15 * 6e4
3042
+ };
3043
+ var CONSTAL_API_QUERY_KINDS = [
3044
+ ...RESOURCE_KINDS,
3045
+ "analytics",
3046
+ "customer",
3047
+ "binding",
3048
+ "session",
3049
+ "run",
3050
+ "deployment",
3051
+ "documentation",
3052
+ "analytics-event",
3053
+ "namespace",
3054
+ "team-member",
3055
+ "team-invite",
3056
+ "api-key",
3057
+ "billing-account",
3058
+ "invoice",
3059
+ "subscription",
3060
+ "resource-contract",
3061
+ "dataset-draft",
3062
+ "dataset-case",
3063
+ "eval-score",
3064
+ "eval-sample",
3065
+ "eval-policy",
3066
+ "eval-suite",
3067
+ "eval-baseline",
3068
+ "eval-schedule",
3069
+ "training-job",
3070
+ "checkpoint",
3071
+ "training-provider",
3072
+ "training-model",
3073
+ "checkpoint-gateway",
3074
+ "credential-provider-package",
3075
+ "credential-consumer",
3076
+ "credential-use",
3077
+ "credential-event",
3078
+ "gateway-package",
3079
+ "rollout",
3080
+ "wait"
3081
+ ];
3082
+ var CONSTAL_API_GET_KINDS = CONSTAL_API_QUERY_KINDS;
3083
+ var CONSTAL_API_MODEL_TOOL_DESCRIPTIONS = {
3084
+ query: "Query authorized Constal objects with bounded pagination and evidence. Select the exact lower-case singular kind from the schema enum; never pluralize, recase, or substitute an abstract kind. If context supplies platformToolContract.queryScope, copy it unchanged. Otherwise use only an exact namespace allowed by the delegated Run authority, and tenant scope only for an explicitly tenant-wide request. Use catalog-advertised fields and filters; constrained kinds require their advertised filter. Preserve next and evidence completeness.",
3085
+ get: "Retrieve one exact authorized Constal object or immutable revision. Pass a complete ref unchanged from query, relations, runtime inspection, or a governed receipt; never construct a kind, id, namespace, CRN, hash, or cursor from display text. The schema enum contains every supported addressable kind. For a Run, omit fields for complete diagnosis or request only documented top-level fields, and follow only the returned page cursor."
3086
+ };
3087
+ var CONSTAL_API_GET_CRN_KINDS = [
3088
+ ...RESOURCE_KINDS,
3089
+ "analytics",
3090
+ "binding",
3091
+ "session",
3092
+ "run",
3093
+ "deployment"
3094
+ ];
3095
+ var CONSTAL_API_OBJECT_REF_CRN_KINDS = [...CONSTAL_API_GET_CRN_KINDS, "customer"];
3096
+ var boundedNameSchema = { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z][A-Za-z0-9._-]{0,127}$" };
3097
+ var namespaceSchema = {
3098
+ type: "string",
3099
+ minLength: 1,
3100
+ maxLength: 128,
3101
+ pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
3102
+ };
3103
+ var actionSchema = { type: "string", pattern: ACTION_PATTERN.source };
3104
+ var boundedIdSchema = { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9][A-Za-z0-9._~:-]{0,255}$" };
3105
+ var hashSchema = { type: "string", pattern: "^[a-f0-9]{64}$" };
3106
+ var stringListSchema = { type: "array", maxItems: 128, items: { type: "string", minLength: 1, maxLength: 256 } };
3107
+ var scopeSchema = { description: "Use namespace with an exact namespace allowed by the delegated Run authority. Use tenant only for an explicitly tenant-wide request.", anyOf: [
3108
+ {
3109
+ type: "object",
3110
+ required: ["kind", "namespace"],
3111
+ additionalProperties: false,
3112
+ properties: { kind: { const: "namespace" }, namespace: {
3113
+ ...namespaceSchema,
3114
+ description: "Exact authorized namespace. Do not infer it from an object name or repository."
3115
+ } }
3116
+ },
3117
+ { type: "object", required: ["kind"], additionalProperties: false, properties: { kind: { const: "tenant" } } }
3118
+ ] };
3119
+ var crnPattern = (kinds) => `^crn:constal:[a-z0-9][a-z0-9._-]{0,127}:[a-z0-9][a-z0-9._-]{0,127}:[a-z0-9][a-z0-9._-]{0,127}:(?:${kinds.join("|")})/[A-Za-z0-9._~/%-]{1,512}$`;
3120
+ var objectRefSchema = { type: "object", additionalProperties: false, properties: {
3121
+ kind: { enum: [...CONSTAL_API_GET_KINDS], description: "Exact lower-case object kind returned by a governed platform result." },
3122
+ id: { type: "string", minLength: 1, maxLength: 512 },
3123
+ crn: { anyOf: [{ type: "null" }, {
3124
+ type: "string",
3125
+ minLength: 1,
3126
+ maxLength: 2048,
3127
+ pattern: crnPattern(CONSTAL_API_OBJECT_REF_CRN_KINDS)
3128
+ }] },
3129
+ hash: { anyOf: [{ type: "null" }, hashSchema] },
3130
+ namespace: {
3131
+ type: ["string", "null"],
3132
+ maxLength: 128,
3133
+ pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
3134
+ },
3135
+ version: { type: ["string", "null"], maxLength: 128 }
3136
+ }, required: ["kind", "id", "namespace"] };
3137
+ var exactGetCrnSchema = {
3138
+ type: "string",
3139
+ minLength: 1,
3140
+ maxLength: 2048,
3141
+ description: "Exact addressable CRN obtained from governed platform evidence.",
3142
+ pattern: crnPattern(CONSTAL_API_GET_CRN_KINDS)
3143
+ };
3144
+ var CONSTAL_MODEL_CREATE_SCHEMA = {
3145
+ type: "object",
3146
+ required: ["id", "gateway", "offer"],
3147
+ additionalProperties: false,
3148
+ properties: {
3149
+ id: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]*$", description: "Name of the new Model Resource." },
3150
+ gateway: { type: "string", minLength: 1, maxLength: 2048, pattern: crnPattern(RESOURCE_KINDS), description: "Exact Gateway Resource CRN." },
3151
+ offer: { description: "Select an advertised provider model or supply manual model metadata.", anyOf: [
3152
+ {
3153
+ type: "object",
3154
+ required: ["kind", "modelId"],
3155
+ additionalProperties: false,
3156
+ properties: { kind: { const: "advertised" }, modelId: GATEWAY_MODEL_OFFER_SCHEMA.properties.id }
3157
+ },
3158
+ {
3159
+ type: "object",
3160
+ required: ["kind", "model"],
3161
+ additionalProperties: false,
3162
+ properties: { kind: { const: "manual" }, model: GATEWAY_MODEL_OFFER_SCHEMA }
3163
+ }
3164
+ ] },
3165
+ defaults: { ...MODEL_GENERATION_OPTIONS_SCHEMA, description: "Generation settings used when calling this Model; omitted settings retain provider defaults." },
3166
+ temperature: MODEL_GENERATION_OPTIONS_SCHEMA.properties.temperature
3167
+ }
3168
+ };
3169
+ var CONSTAL_API_OPERATION_SCHEMAS = {
3170
+ describe: { type: "object", additionalProperties: false, properties: {
3171
+ domains: { ...stringListSchema, description: "Domain IDs returned in catalog.domains. Omit to discover across all domains." },
3172
+ kinds: stringListSchema,
3173
+ operations: stringListSchema,
3174
+ include: {
3175
+ type: "array",
3176
+ maxItems: 5,
3177
+ uniqueItems: true,
3178
+ items: { enum: ["objects", "operations", "relations", "schemas", "docs"] }
3179
+ },
3180
+ cursor: { type: "string", maxLength: 4096 },
3181
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize }
3182
+ } },
3183
+ query: {
3184
+ type: "object",
3185
+ required: ["kind", "scope"],
3186
+ additionalProperties: false,
3187
+ description: "Query one exact catalog kind. Kind ids are lower-case, singular, and must be selected from the enum; abstract names and pluralizations are invalid.",
3188
+ properties: {
3189
+ kind: { enum: [...CONSTAL_API_QUERY_KINDS], description: "Exact queryable kind. Never guess a kind or change its casing." },
3190
+ scope: scopeSchema,
3191
+ filter: { type: "object", description: "Optional catalog-advertised filter expression." },
3192
+ search: { type: "string", maxLength: 512 },
3193
+ order: { type: "array", maxItems: 8, items: {
3194
+ type: "object",
3195
+ required: ["field", "direction"],
3196
+ additionalProperties: false,
3197
+ properties: { field: boundedNameSchema, direction: { enum: ["ascending", "descending"] } }
3198
+ } },
3199
+ fields: stringListSchema,
3200
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
3201
+ cursor: { type: "string", maxLength: 4096 },
3202
+ asOf: { type: "integer", minimum: 0 },
3203
+ range: { type: "object", required: ["start", "end"], additionalProperties: false, properties: {
3204
+ start: { type: "integer", minimum: 0 },
3205
+ end: { type: "integer", minimum: 0 }
3206
+ } }
3207
+ }
3208
+ },
3209
+ get: {
3210
+ type: "object",
3211
+ required: ["ref"],
3212
+ additionalProperties: false,
3213
+ description: "Read one addressable object using a complete ref returned by query, relations, runtime inspection, or a governed receipt. Do not synthesize refs.",
3214
+ properties: {
3215
+ ref: {
3216
+ description: "Copy a complete object ref from governed output, or supply an exact supported CRN.",
3217
+ anyOf: [objectRefSchema, {
3218
+ type: "object",
3219
+ required: ["crn"],
3220
+ additionalProperties: false,
3221
+ properties: { crn: exactGetCrnSchema, hash: hashSchema }
3222
+ }]
3223
+ },
3224
+ fields: stringListSchema,
3225
+ page: { type: "object", additionalProperties: false, properties: {
3226
+ cursor: { type: "string", maxLength: 4096 },
3227
+ limit: { type: "integer", minimum: 1, maximum: 500 }
3228
+ } }
3229
+ }
3230
+ },
3231
+ relations: { type: "object", required: ["start"], additionalProperties: false, properties: {
3232
+ start: { anyOf: [objectRefSchema, {
3233
+ type: "object",
3234
+ required: ["crn"],
3235
+ additionalProperties: false,
3236
+ properties: { crn: { type: "string", minLength: 1, maxLength: 2048 }, hash: hashSchema }
3237
+ }] },
3238
+ direction: { enum: ["outgoing", "incoming", "both"] },
3239
+ types: stringListSchema,
3240
+ depth: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumRelationDepth },
3241
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
3242
+ cursor: { type: "string", maxLength: 4096 }
3243
+ } },
3244
+ explainPolicy: { type: "object", required: ["action", "resource"], additionalProperties: false, properties: {
3245
+ principal: { anyOf: [
3246
+ { type: "string", maxLength: 2048 },
3247
+ { type: "object", required: ["roles", "scopes"], additionalProperties: false, properties: {
3248
+ name: { type: "string", maxLength: 2048 },
3249
+ roles: {
3250
+ type: "array",
3251
+ maxItems: 64,
3252
+ uniqueItems: true,
3253
+ items: { type: "string", minLength: 1, maxLength: 2048 }
3254
+ },
3255
+ scopes: {
3256
+ type: "array",
3257
+ maxItems: 256,
3258
+ uniqueItems: true,
3259
+ items: { type: "string", pattern: "^(?:\\*|[a-z][a-z0-9-]{0,63}:(?:[a-z][a-z0-9-]{0,63}|\\*))$" }
3260
+ }
3261
+ } }
3262
+ ] },
3263
+ action: actionSchema,
3264
+ resource: { type: "string", minLength: 1, maxLength: 2048 },
3265
+ context: { type: "object" },
3266
+ arguments: {},
3267
+ at: { type: "object", required: ["run"], additionalProperties: false, properties: {
3268
+ run: {
3269
+ type: "object",
3270
+ required: ["namespace", "agent", "session", "run"],
3271
+ additionalProperties: false,
3272
+ properties: {
3273
+ namespace: boundedNameSchema,
3274
+ agent: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]{0,62}$" },
3275
+ session: boundedIdSchema,
3276
+ run: boundedIdSchema
3277
+ }
3278
+ }
3279
+ } }
3280
+ } },
3281
+ plan: { type: "object", required: ["objective", "operations"], additionalProperties: false, properties: {
3282
+ objective: { type: "string", minLength: 1, maxLength: 8192 },
3283
+ validateOnly: { type: "boolean" },
3284
+ operations: {
3285
+ type: "array",
3286
+ minItems: 1,
3287
+ maxItems: CONSTAL_API_BOUNDS.maximumPlanOperations,
3288
+ items: { type: "object", required: ["operation", "input"], additionalProperties: false, properties: {
3289
+ id: boundedIdSchema,
3290
+ operation: boundedNameSchema,
3291
+ target: { type: "string", maxLength: 2048 },
3292
+ input: {},
3293
+ expectedCurrentHash: { anyOf: [{ type: "null" }, hashSchema] },
3294
+ dependsOn: { type: "array", maxItems: 64, items: boundedIdSchema }
3295
+ } }
2657
3296
  }
2658
- const values = record7(source.usage) ?? {};
2659
- usage = {
2660
- input: integer2(values.prompt_tokens),
2661
- output: integer2(values.completion_tokens),
2662
- cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
2663
- ...costMetadata(values)
2664
- };
2665
- } else throw new TypeError("model gateway protocol is invalid");
2666
- if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
2667
- return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model };
2668
- }
3297
+ } },
3298
+ apply: { type: "object", required: ["plan", "eventId"], additionalProperties: false, properties: {
3299
+ plan: {
3300
+ type: "object",
3301
+ required: ["id", "hash"],
3302
+ additionalProperties: false,
3303
+ properties: { id: boundedIdSchema, hash: hashSchema }
3304
+ },
3305
+ eventId: boundedIdSchema
3306
+ } },
3307
+ observe: { type: "object", required: ["id"], additionalProperties: false, properties: { id: boundedIdSchema } }
3308
+ };
2669
3309
 
2670
- // src/gateway.ts
2671
- async function checkpointArtifactRef(value) {
2672
- return await sha256Hex(canonicalJson(value));
3310
+ // packages/sdk/src/authorization.ts
3311
+ var MAX_CONSTRAINTS = 64;
3312
+ var MAX_OUTCOME_BYTES = 65536;
3313
+ var MAX_REASON_BYTES = 1024;
3314
+ var DENIAL_CODE = /^[a-z][a-z0-9._-]{0,127}$/u;
3315
+ var encoder4 = new TextEncoder();
3316
+ function record7(value) {
3317
+ return !!value && typeof value === "object" && !Array.isArray(value);
2673
3318
  }
2674
- var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2675
- var HASH3 = /^[a-f0-9]{64}$/u;
2676
- var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
2677
- function httpsUrl(value, field2) {
2678
- if (value === void 0) return;
2679
- if (typeof value !== "string" || value.length > 2048) throw new TypeError(`${field2} is invalid`);
2680
- let parsed;
2681
- try {
2682
- parsed = new URL(value);
2683
- } catch {
2684
- throw new TypeError(`${field2} is invalid`);
3319
+ function requiredString2(value, path, maximum = 1024) {
3320
+ if (typeof value !== "string" || value.length === 0 || encoder4.encode(value).byteLength > maximum) {
3321
+ throw new TypeError(`${path} must be a bounded non-empty string`);
2685
3322
  }
2686
- if (parsed.protocol !== "https:") throw new TypeError(`${field2} is invalid`);
2687
3323
  }
2688
- function slotMetadata(value) {
2689
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Gateway Credential slots are invalid");
2690
- const entries = Object.entries(value);
2691
- if (entries.length > 32) throw new TypeError("Gateway Credential slots are invalid");
2692
- const output = {};
2693
- for (const [slot, raw] of entries) {
2694
- const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2695
- 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))) {
2696
- throw new TypeError("Gateway Credential slots are invalid");
2697
- }
2698
- httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
2699
- output[slot] = item;
3324
+ function exactKeys2(value, allowed, required2, path) {
3325
+ if (Object.keys(value).some((key) => !allowed.includes(key)) || required2.some((key) => !Object.hasOwn(value, key))) {
3326
+ throw new TypeError(`${path} has invalid keys`);
2700
3327
  }
2701
- return output;
2702
- }
2703
- function configEgressBindings(value) {
2704
- if (value === void 0) return [];
2705
- if (!Array.isArray(value) || value.length > 16) throw new TypeError("Gateway config egress bindings are invalid");
2706
- return value.map((raw) => {
2707
- const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2708
- 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))) {
2709
- throw new TypeError("Gateway config egress bindings are invalid");
2710
- }
2711
- return {
2712
- urlProperty: String(item.urlProperty),
2713
- operations: [...new Set(item.operations)],
2714
- methods: [...new Set(item.methods)]
2715
- };
2716
- });
2717
3328
  }
2718
- function discoverySetup(value) {
2719
- if (value === void 0) return void 0;
2720
- const item = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2721
- 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))) {
2722
- throw new TypeError("Gateway discovery setup is invalid");
2723
- }
2724
- return { operation: String(item.operation), resultConfigProperty: String(item.resultConfigProperty) };
3329
+ function scalar(value) {
3330
+ return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
2725
3331
  }
2726
- function checkpointImportMetadata(value) {
2727
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2728
- 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))) {
2729
- throw new TypeError("Gateway checkpoint import metadata is invalid");
3332
+ function validateGrant(grant, path) {
3333
+ if (!record7(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) {
3334
+ throw new TypeError(`${path} is invalid`);
2730
3335
  }
2731
- return { lifecycleVersion: 1, formats: [...source.formats] };
3336
+ exactKeys2(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
3337
+ grant.actions.forEach(actionPattern);
3338
+ grant.resources.forEach(resourcePattern);
2732
3339
  }
2733
- function checkpointImportRequest(value) {
2734
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2735
- const provenance = source?.source && typeof source.source === "object" && !Array.isArray(source.source) ? source.source : null;
2736
- const provider = provenance?.provider && typeof provenance.provider === "object" && !Array.isArray(provenance.provider) ? provenance.provider : null;
2737
- const checkpoint = provenance?.checkpoint && typeof provenance.checkpoint === "object" && !Array.isArray(provenance.checkpoint) ? provenance.checkpoint : null;
2738
- const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
2739
- const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
2740
- const model = source?.model && typeof source.model === "object" && !Array.isArray(source.model) ? source.model : null;
2741
- 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))) {
2742
- throw new TypeError("checkpoint import request is invalid");
3340
+ function validatePolicyConstraint(constraint, path = "constraint") {
3341
+ if (!constraint || typeof constraint !== "object" || Array.isArray(constraint) || typeof constraint.kind !== "string") {
3342
+ throw new TypeError(`${path} is invalid`);
2743
3343
  }
2744
- try {
2745
- if (new TextEncoder().encode(canonicalJson(artifactValue)).byteLength > 65536) throw new TypeError();
2746
- } catch {
2747
- throw new TypeError("checkpoint import request is invalid");
3344
+ const source = constraint;
3345
+ if (constraint.kind === "resource-controls" || constraint.kind === "admission-limit") {
3346
+ try {
3347
+ validatePolicyGovernanceConstraint(constraint);
3348
+ } catch (error) {
3349
+ throw new TypeError(`${path} is invalid: ${error instanceof Error ? error.message : String(error)}`);
3350
+ }
3351
+ return;
2748
3352
  }
2749
- try {
2750
- parseResourceName(String(provider.crn));
2751
- } catch {
2752
- throw new TypeError("checkpoint import request is invalid");
3353
+ if (constraint.kind === "arguments") {
3354
+ exactKeys2(source, ["kind", "schema"], ["kind", "schema"], path);
3355
+ if (!record7(constraint.schema) || validateJsonSchemaDefinition(constraint.schema)) throw new TypeError(`${path}.schema is invalid`);
3356
+ return;
2753
3357
  }
2754
- return source;
2755
- }
2756
- function checkpointDeploymentRequest(value) {
2757
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2758
- const gateway2 = source?.gateway && typeof source.gateway === "object" && !Array.isArray(source.gateway) ? source.gateway : null;
2759
- 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))) {
2760
- throw new TypeError("checkpoint deployment request is invalid");
3358
+ if (constraint.kind === "context") {
3359
+ exactKeys2(source, ["kind", "equals"], ["kind", "equals"], path);
3360
+ if (!record7(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))) {
3361
+ throw new TypeError(`${path}.equals is invalid`);
3362
+ }
3363
+ return;
2761
3364
  }
2762
- try {
2763
- parseResourceName(gateway2.crn);
2764
- } catch {
2765
- throw new TypeError("checkpoint deployment request is invalid");
3365
+ if (constraint.kind === "credential-binding") {
3366
+ exactKeys2(source, ["kind", "source", "consumer"], ["kind", "source", "consumer"], path);
3367
+ credentialName(constraint.source);
3368
+ parseResourceName(constraint.consumer);
3369
+ return;
2766
3370
  }
2767
- return { gateway: gateway2, import: checkpointImportRequest(source.import) };
3371
+ throw new TypeError(`${path}.kind is invalid`);
2768
3372
  }
2769
- var MODEL_ID_CONTROL = /[\u0000-\u001f\u007f]/u;
2770
- function gatewayModelOffer(value) {
2771
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2772
- 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) => ![
2773
- "id",
2774
- "displayName",
2775
- "contextTokens",
2776
- "maxOutputTokens",
2777
- "inputModalities",
2778
- "outputModalities",
2779
- "pricing"
2780
- ].includes(key))) {
2781
- throw new TypeError("Gateway Model offer is invalid");
3373
+ function validateConstraints(value, path, required2) {
3374
+ if (value === void 0 && !required2) return [];
3375
+ if (!Array.isArray(value) || required2 && value.length === 0 || value.length > MAX_CONSTRAINTS) {
3376
+ throw new TypeError(`${path} is invalid`);
2782
3377
  }
2783
- const modalities = (field2) => {
2784
- const values = source[field2];
2785
- if (values === void 0) return void 0;
2786
- 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) {
2787
- throw new TypeError("Gateway Model offer is invalid");
2788
- }
2789
- return values;
2790
- };
2791
- const pricing = source.pricing === null ? null : modelAdvertisedPricing(source.pricing);
2792
- const inputModalities = modalities("inputModalities");
2793
- const outputModalities = modalities("outputModalities");
2794
- return {
2795
- id: source.id,
2796
- displayName: source.displayName,
2797
- contextTokens: Number(source.contextTokens),
2798
- maxOutputTokens: Number(source.maxOutputTokens),
2799
- ...inputModalities ? { inputModalities } : {},
2800
- ...outputModalities ? { outputModalities } : {},
2801
- pricing
2802
- };
3378
+ value.forEach((constraint, index) => validatePolicyConstraint(constraint, `${path}[${index}]`));
3379
+ return value;
2803
3380
  }
2804
- function assertNonSecretGatewayConfig(value, field2 = "config") {
2805
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
2806
- const source = value;
2807
- if (source.format === "password" || /(?:secret|password|private[-_ ]?key|access[-_ ]?token|api[-_ ]?key)/iu.test(field2)) {
2808
- throw new TypeError("Gateway secrets must use declared Credential slots");
2809
- }
2810
- const properties = source.properties && typeof source.properties === "object" && !Array.isArray(source.properties) ? source.properties : {};
2811
- for (const [name, declaration] of Object.entries(properties)) assertNonSecretGatewayConfig(declaration, name);
2812
- if (source.items) assertNonSecretGatewayConfig(source.items, field2);
2813
- if (source.additionalProperties && typeof source.additionalProperties === "object") {
2814
- assertNonSecretGatewayConfig(source.additionalProperties, field2);
2815
- }
3381
+ function policyOutcome(value) {
3382
+ if (!record7(value) || typeof value.kind !== "string") throw new TypeError("Policy outcome is invalid");
3383
+ if (value.kind === "allow") exactKeys2(value, ["kind"], ["kind"], "Policy allow outcome");
3384
+ else if (value.kind === "deny") {
3385
+ exactKeys2(value, ["kind", "code", "reason"], ["kind", "code"], "Policy deny outcome");
3386
+ if (typeof value.code !== "string" || !DENIAL_CODE.test(value.code)) throw new TypeError("Policy denial code is invalid");
3387
+ if (value.reason !== void 0) requiredString2(value.reason, "Policy denial reason", MAX_REASON_BYTES);
3388
+ } else if (value.kind === "constrain") {
3389
+ exactKeys2(value, ["kind", "constraints"], ["kind", "constraints"], "Policy constrain outcome");
3390
+ validateConstraints(value.constraints, "Policy constraints", true);
3391
+ } else if (value.kind === "substitute") {
3392
+ exactKeys2(value, ["kind", "value", "constraints"], ["kind", "value"], "Policy substitute outcome");
3393
+ canonicalJson(value.value);
3394
+ validateConstraints(value.constraints, "Policy constraints", false);
3395
+ } else if (value.kind === "require-approval") {
3396
+ exactKeys2(value, ["kind", "reason", "constraints"], ["kind"], "Policy approval outcome");
3397
+ if (value.reason !== void 0) requiredString2(value.reason, "Policy approval reason", MAX_REASON_BYTES);
3398
+ validateConstraints(value.constraints, "Policy constraints", false);
3399
+ } else if (value.kind === "grant") {
3400
+ exactKeys2(value, ["kind", "grant"], ["kind", "grant"], "Policy grant outcome");
3401
+ validateGrant(value.grant, "Policy grant");
3402
+ } else throw new TypeError("Policy outcome kind is invalid");
3403
+ if (encoder4.encode(canonicalJson(value)).byteLength > MAX_OUTCOME_BYTES) throw new TypeError("Policy outcome is oversized");
3404
+ return value;
2816
3405
  }
2817
- function gatewayPackageMetadata(value) {
2818
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2819
- 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 ?? ""))) {
2820
- throw new TypeError("Gateway package metadata is invalid");
3406
+
3407
+ // packages/sdk/src/policy.ts
3408
+ var ID2 = /^[a-z0-9][a-z0-9-]{0,62}$/u;
3409
+ var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
3410
+ function policy(definition2) {
3411
+ if (!definition2 || typeof definition2 !== "object" || Array.isArray(definition2) || Object.keys(definition2).some((key) => !["id", "version", "evaluate"].includes(key)) || !ID2.test(definition2.id) || !VERSION4.test(definition2.version) || typeof definition2.evaluate !== "function") throw new TypeError("Policy definition is invalid");
3412
+ return Object.freeze(definition2);
3413
+ }
3414
+ async function evaluatePolicyDefinition(definition2, input) {
3415
+ return policyOutcome(await definition2.evaluate(input));
3416
+ }
3417
+
3418
+ // packages/sdk/src/table.ts
3419
+ var identifier = { type: "string", pattern: "^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$", maxLength: 128 };
3420
+ var tableName = { type: "string", pattern: "^[a-z0-9][a-z0-9._-]{0,127}$", maxLength: 128 };
3421
+ var branchName = { type: "string", pattern: "^[a-z0-9][a-z0-9._/-]{0,127}$", maxLength: 128 };
3422
+ var hash2 = { type: "string", pattern: "^[a-f0-9]{64}$" };
3423
+ var scalar2 = { type: ["string", "number", "integer", "boolean", "null"], maxLength: 4096 };
3424
+ var TABLE_DESCRIBE_SCHEMA = {
3425
+ type: "object",
3426
+ required: ["table"],
3427
+ additionalProperties: false,
3428
+ properties: {
3429
+ table: tableName,
3430
+ branch: branchName,
3431
+ snapshot: hash2,
3432
+ stageId: hash2,
3433
+ waitMs: { type: "integer", minimum: 0, maximum: 25e3 }
2821
3434
  }
2822
- httpsUrl(source.documentationUrl, "Gateway documentation URL");
2823
- const credentialSlots = slotMetadata(source.credentialSlots);
2824
- const modelOffers = source.modelOffers === void 0 ? [] : Array.isArray(source.modelOffers) ? source.modelOffers.map(gatewayModelOffer) : (() => {
2825
- throw new TypeError("Gateway Model offers are invalid");
2826
- })();
2827
- if (modelOffers.length > 512 || new Set(modelOffers.map((offer) => offer.id)).size !== modelOffers.length) {
2828
- throw new TypeError("Gateway Model offers are invalid");
3435
+ };
3436
+ var filterSchema = {
3437
+ type: "object",
3438
+ required: ["field", "op", "value"],
3439
+ additionalProperties: false,
3440
+ properties: {
3441
+ field: identifier,
3442
+ op: { type: "string", enum: ["eq", "ne", "gt", "gte", "lt", "lte", "in", "between"] },
3443
+ value: { anyOf: [scalar2, { type: "array", minItems: 1, maxItems: 100, items: scalar2 }] }
2829
3444
  }
2830
- const capabilities = source.capabilities.map(capabilityContractRef);
2831
- if (new Set(capabilities.map((contract) => `${contract.id}@${contract.version}#${contract.hash}`)).size !== capabilities.length) {
2832
- throw new TypeError("Gateway capability contracts must be unique");
3445
+ };
3446
+ var TABLE_QUERY_SCHEMA = {
3447
+ type: "object",
3448
+ required: ["table", "snapshot", "query"],
3449
+ additionalProperties: false,
3450
+ properties: {
3451
+ table: tableName,
3452
+ branch: branchName,
3453
+ snapshot: hash2,
3454
+ query: {
3455
+ type: "object",
3456
+ additionalProperties: false,
3457
+ properties: {
3458
+ select: { type: "array", maxItems: 64, uniqueItems: true, items: identifier },
3459
+ where: { type: "array", maxItems: 32, items: filterSchema },
3460
+ groupBy: { type: "array", maxItems: 16, uniqueItems: true, items: identifier },
3461
+ aggregates: { type: "array", maxItems: 32, items: {
3462
+ type: "object",
3463
+ required: ["fn", "as"],
3464
+ additionalProperties: false,
3465
+ properties: {
3466
+ fn: { type: "string", enum: ["count", "sum", "avg", "min", "max"] },
3467
+ field: identifier,
3468
+ as: identifier
3469
+ }
3470
+ } },
3471
+ orderBy: { type: "array", maxItems: 8, items: {
3472
+ type: "object",
3473
+ required: ["field", "direction"],
3474
+ additionalProperties: false,
3475
+ properties: { field: identifier, direction: { type: "string", enum: ["asc", "desc"] } }
3476
+ } },
3477
+ limit: { type: "integer", minimum: 1, maximum: 1e3 }
3478
+ }
3479
+ }
2833
3480
  }
2834
- const egress = integrationEgressPolicy(source.egress);
2835
- const configEgress = configEgressBindings(source.configEgress);
2836
- const discovery = discoverySetup(source.discovery);
2837
- const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
2838
- const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
2839
- if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
2840
- throw new TypeError("Training Provider packages must implement the exact Training Provider capability");
3481
+ };
3482
+ function validateStageOutputSpec(value, path = "$.output") {
3483
+ if (!value || typeof value !== "object" || Array.isArray(value)) return `${path} must be an object`;
3484
+ const output = value;
3485
+ const extra = Object.keys(output).find((key) => key !== "schema" && key !== "sortOrder");
3486
+ if (extra) return `${path}.${extra} is not allowed`;
3487
+ if (!Object.hasOwn(output, "schema")) return `${path}.schema is required`;
3488
+ const schemaError = validateJsonSchemaDefinition(output.schema, `${path}.schema`);
3489
+ if (schemaError) return schemaError;
3490
+ const sortOrder = output.sortOrder ?? [];
3491
+ if (!Array.isArray(sortOrder) || sortOrder.length > 64) return `${path}.sortOrder is invalid`;
3492
+ const keys = /* @__PURE__ */ new Set();
3493
+ for (const [index, raw] of sortOrder.entries()) {
3494
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${path}.sortOrder[${index}] is invalid`;
3495
+ const field2 = raw;
3496
+ 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)) {
3497
+ return `${path}.sortOrder[${index}] is invalid`;
3498
+ }
3499
+ keys.add(field2.key);
2841
3500
  }
2842
- 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))) {
2843
- throw new TypeError("Checkpoint import Gateways must implement exact completion and checkpoint import capabilities");
3501
+ return null;
3502
+ }
3503
+ function stageOutput(value) {
3504
+ const error = validateStageOutputSpec(value);
3505
+ if (error) throw new TypeError(error);
3506
+ return value;
3507
+ }
3508
+ var tableDescribe = {
3509
+ name: "table_describe",
3510
+ version: "1",
3511
+ description: "Inspect the schema and identity of one exact, queryable Table snapshot before querying it.",
3512
+ schema: TABLE_DESCRIBE_SCHEMA,
3513
+ maxEffect: "read-only",
3514
+ needs: [{ binding: "table_catalog", kind: "service", ops: ["describe"] }],
3515
+ async run(args, ctx) {
3516
+ return ctx.invoke(ctx.resources.table_catalog, "describe", args);
3517
+ }
3518
+ };
3519
+ var tableQuery = {
3520
+ name: "table_query",
3521
+ version: "1",
3522
+ description: "Query one exact Table snapshot with bounded fields, filters, grouping, aggregates, ordering, and limit.",
3523
+ schema: TABLE_QUERY_SCHEMA,
3524
+ maxEffect: "read-only",
3525
+ needs: [{ binding: "table_catalog", kind: "service", ops: ["query"] }],
3526
+ async run(args, ctx) {
3527
+ return ctx.invoke(ctx.resources.table_catalog, "query", args);
2844
3528
  }
3529
+ };
3530
+
3531
+ // packages/sdk/src/tools.ts
3532
+ var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
3533
+ var OPERATION3 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
3534
+ function opTool(binding, op, override = {}) {
3535
+ if (!NAME4.test(binding) || !OPERATION3.test(op)) throw new TypeError("opTool binding or operation is invalid");
3536
+ const name = override.name ?? op.replaceAll(".", "_");
2845
3537
  return {
2846
- lifecycleVersion: 1,
2847
- displayName: source.displayName,
2848
- description: source.description,
2849
- ...typeof source.documentationUrl === "string" ? { documentationUrl: source.documentationUrl } : {},
2850
- ...typeof source.service === "string" ? { service: source.service } : {},
2851
- credentialSlots,
2852
- modelOffers,
2853
- capabilities,
2854
- billing: { upstreamPayer: source.billing.upstreamPayer },
2855
- egress,
2856
- ...configEgress.length ? { configEgress } : {},
2857
- ...discovery ? { discovery } : {},
2858
- ...training ? { training } : {},
2859
- ...checkpointImport ? { checkpointImport } : {}
2860
- };
2861
- }
2862
- function resolveGatewayEgress(metadata2, config) {
2863
- const derived = (metadata2.configEgress ?? []).map((binding) => {
2864
- let endpoint;
2865
- try {
2866
- endpoint = new URL(String(config[binding.urlProperty] ?? ""));
2867
- } catch {
2868
- throw new TypeError(`Gateway ${binding.urlProperty} must be an HTTPS endpoint`);
2869
- }
2870
- if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) {
2871
- throw new TypeError(`Gateway ${binding.urlProperty} must be an exact HTTPS endpoint without credentials, query, or fragment`);
3538
+ name,
3539
+ version: "catalog",
3540
+ description: override.description ?? `Invoke ${op} on the bound ${binding} resource.`,
3541
+ schema: override.schema ?? { type: "object", additionalProperties: false },
3542
+ maxEffect: "read-only",
3543
+ needs: [],
3544
+ ...override.tier ? { tier: override.tier } : {},
3545
+ ...override.once ? { once: override.once } : {},
3546
+ ...override.guard ? { guard: override.guard } : {},
3547
+ ...override.preview ? { preview: override.preview } : {},
3548
+ catalog: { binding, op },
3549
+ async run() {
3550
+ throw new TypeError(`catalog Tool ${binding}#${op} was not resolved by deployment`);
2872
3551
  }
2873
- return { operations: binding.operations, origin: endpoint.origin, pathExact: endpoint.pathname, methods: binding.methods };
2874
- });
2875
- return integrationEgressPolicy({ rules: [...metadata2.egress.rules, ...derived] });
3552
+ };
2876
3553
  }
2877
- function gateway(definition) {
2878
- 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") {
2879
- throw new TypeError("Gateway definition is invalid");
3554
+ function opTools(binding, ops = []) {
3555
+ if (ops.length === 0) throw new TypeError("opTools requires pinned operation names at bundle construction");
3556
+ return ops.map((op) => opTool(binding, op));
3557
+ }
3558
+ var WEB_FETCH_ARGUMENT_SCHEMA = {
3559
+ type: "object",
3560
+ required: ["url"],
3561
+ additionalProperties: false,
3562
+ properties: {
3563
+ url: { type: "string", minLength: 1, maxLength: 2048 },
3564
+ accept: { type: "string", maxLength: 256 }
2880
3565
  }
2881
- const schemaError = validateJsonSchemaDefinition(definition.configSchema);
2882
- if (schemaError) throw new TypeError(`Gateway config schema is invalid: ${schemaError}`);
2883
- const configSchema = definition.configSchema;
2884
- if (configSchema.type !== "object") throw new TypeError('Gateway config schema root type must be "object"');
2885
- if (configSchema.additionalProperties !== false) throw new TypeError("Gateway config schema must reject unknown root fields");
2886
- assertNonSecretGatewayConfig(configSchema);
2887
- const gateway2 = gatewayPackageMetadata({
2888
- lifecycleVersion: 1,
2889
- displayName: definition.displayName,
2890
- description: definition.description,
2891
- documentationUrl: definition.documentationUrl,
2892
- service: definition.service,
2893
- credentialSlots: definition.credentialSlots,
2894
- modelOffers: definition.modelOffers ?? [],
2895
- capabilities: definition.capabilities,
2896
- billing: definition.billing,
2897
- egress: definition.egress,
2898
- configEgress: definition.configEgress,
2899
- discovery: definition.discovery,
2900
- training: definition.training,
2901
- checkpointImport: definition.checkpointImport
2902
- });
2903
- const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
2904
- for (const binding of gateway2.configEgress ?? []) {
2905
- const property = properties[binding.urlProperty];
2906
- if (!property || property.type !== "string" || property.format !== "uri") {
2907
- throw new TypeError(`Gateway config egress property must be a URI string: ${binding.urlProperty}`);
3566
+ };
3567
+ var WEB_SEARCH_ARGUMENT_SCHEMA = {
3568
+ type: "object",
3569
+ required: ["query"],
3570
+ additionalProperties: false,
3571
+ properties: {
3572
+ query: {
3573
+ type: "string",
3574
+ minLength: 1,
3575
+ maxLength: 4096,
3576
+ description: "A self-contained description of the information to find."
3577
+ },
3578
+ searchQueries: {
3579
+ type: "array",
3580
+ minItems: 1,
3581
+ maxItems: 3,
3582
+ uniqueItems: true,
3583
+ description: "Optional concise keyword queries that narrow the search.",
3584
+ items: { type: "string", minLength: 1, maxLength: 256 }
3585
+ },
3586
+ maximumResults: {
3587
+ type: "integer",
3588
+ minimum: 1,
3589
+ maximum: 20,
3590
+ description: "Maximum number of sources to return."
3591
+ },
3592
+ maximumCharacters: {
3593
+ type: "integer",
3594
+ minimum: 1e3,
3595
+ maximum: 6e4,
3596
+ description: "Maximum total excerpt characters to return."
3597
+ },
3598
+ includeDomains: {
3599
+ type: "array",
3600
+ maxItems: 50,
3601
+ uniqueItems: true,
3602
+ description: "Optional domains to restrict results to.",
3603
+ items: { type: "string", minLength: 1, maxLength: 253 }
3604
+ },
3605
+ excludeDomains: {
3606
+ type: "array",
3607
+ maxItems: 50,
3608
+ uniqueItems: true,
3609
+ description: "Optional domains to omit.",
3610
+ items: { type: "string", minLength: 1, maxLength: 253 }
3611
+ },
3612
+ afterDate: {
3613
+ type: "string",
3614
+ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
3615
+ description: "Optional earliest publication date in YYYY-MM-DD form."
2908
3616
  }
2909
3617
  }
2910
- if (gateway2.discovery) {
2911
- const property = properties[gateway2.discovery.resultConfigProperty];
2912
- if (!property || property.type !== "array") throw new TypeError("Gateway discovery result config property must be an array");
2913
- const required2 = Array.isArray(configSchema.required) ? configSchema.required : [];
2914
- if (!required2.includes(gateway2.discovery.resultConfigProperty)) {
2915
- throw new TypeError("Gateway discovery result config property must be required");
3618
+ };
3619
+ var webFetch = opTool("web", "get", {
3620
+ name: "web_fetch",
3621
+ description: "Fetch an HTTPS resource through the bound governed web Resource.",
3622
+ schema: WEB_FETCH_ARGUMENT_SCHEMA
3623
+ });
3624
+ var webSearch = opTool("search", "search", {
3625
+ name: "web_search",
3626
+ description: "Search the public web through the bound governed search Resource.",
3627
+ schema: WEB_SEARCH_ARGUMENT_SCHEMA
3628
+ });
3629
+ var casTool = {
3630
+ name: "cas",
3631
+ version: "1",
3632
+ description: "Store or load one content-addressed Agent artifact.",
3633
+ schema: {
3634
+ type: "object",
3635
+ required: ["action"],
3636
+ additionalProperties: false,
3637
+ properties: {
3638
+ action: { type: "string", enum: ["put", "get"] },
3639
+ value: {},
3640
+ ref: { type: "string", pattern: "^[a-f0-9]{64}$" }
2916
3641
  }
2917
- if (property.readOnly !== true) throw new TypeError("Gateway discovery result config property must be read-only");
2918
- }
2919
- const authoredCatalog = definition.catalog;
2920
- const wrapped = { ...definition, metadata: gateway2, catalog(config) {
2921
- const declarations = authoredCatalog(config);
2922
- if (gateway2.checkpointImport) {
2923
- const operation = declarations.find((candidate) => candidate.op === "importCheckpoint");
2924
- if (!operation || !operation.async || operation.effect !== "reconcilable" || operation.recovery.kind !== "reconcile") {
2925
- throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
2926
- }
3642
+ },
3643
+ maxEffect: "idempotent",
3644
+ needs: [{ binding: "cas", kind: "cas", ops: ["put", "get"] }],
3645
+ async run(args, ctx) {
3646
+ const input = args && typeof args === "object" && !Array.isArray(args) ? args : {};
3647
+ if (input.action === "put") {
3648
+ if (!Object.hasOwn(input, "value")) throw new TypeError("cas put requires value");
3649
+ return ctx.invoke(ctx.resources.cas, "put", { value: input.value });
2927
3650
  }
2928
- return declarations;
2929
- } };
2930
- return Object.freeze(wrapped);
2931
- }
2932
- function trainingProvider(definition) {
2933
- const authoredCatalog = definition.catalog;
2934
- return gateway({
2935
- ...definition,
2936
- 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]],
2937
- catalog(config) {
2938
- const declarations = authoredCatalog(config);
2939
- const train = declarations.find((operation) => operation.op === "train");
2940
- if (!train || !train.async || train.effect !== "reconcilable" || train.recovery.kind !== "reconcile") {
2941
- throw new TypeError("Training Provider train must be asynchronous, reconcilable, and recovered by reconcile");
2942
- }
2943
- return declarations;
3651
+ if (input.action === "get") {
3652
+ if (typeof input.ref !== "string") throw new TypeError("cas get requires ref");
3653
+ return ctx.invoke(ctx.resources.cas, "get", { ref: input.ref });
2944
3654
  }
2945
- });
2946
- }
2947
- var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
2948
- id: "constal.model-checkpoint-import",
2949
- version: "1",
2950
- hash: "49563823899586a87dcee82e9db969af5f2f5364adb3eb808a19e86b862e87ba"
3655
+ throw new TypeError("cas action must be put or get");
3656
+ }
2951
3657
  };
2952
- var MCP_CLIENT_CAPABILITY = {
2953
- id: "constal.mcp-client",
2954
- version: "1",
2955
- hash: "a694af71191432e75980dc73962d9239dc8ea324aff084f183a2f45603bd2267"
3658
+
3659
+ // packages/sdk/src/memory.ts
3660
+ var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 };
3661
+ var content = { type: "string", minLength: 1, maxLength: 65536 };
3662
+ var metadata = { type: "object", maxProperties: 64 };
3663
+ var scope = { type: "string", pattern: "^[a-f0-9]{64}$", maxLength: 64 };
3664
+ var record8 = {
3665
+ type: "object",
3666
+ required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
3667
+ additionalProperties: false,
3668
+ properties: {
3669
+ id,
3670
+ content,
3671
+ metadata,
3672
+ createdAt: { type: "integer", minimum: 0 },
3673
+ updatedAt: { type: "integer", minimum: 0 },
3674
+ expiresAt: { anyOf: [{ type: "integer", minimum: 0 }, { type: "null" }] }
3675
+ }
2956
3676
  };
3677
+ var MEMORY_OPERATION_DECLARATIONS = [
3678
+ {
3679
+ op: "remember",
3680
+ description: "Persist or replace one record in the invocation's authenticated Memory partition.",
3681
+ schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata, scope } },
3682
+ resultSchema: record8,
3683
+ effect: "idempotent",
3684
+ recovery: { kind: "idempotency-key" },
3685
+ async: false,
3686
+ usage: { meter: "none", priceTable: null }
3687
+ },
3688
+ {
3689
+ op: "search",
3690
+ description: "Retrieve relevant records from the invocation's authenticated Memory partition.",
3691
+ schema: {
3692
+ type: "object",
3693
+ required: ["query"],
3694
+ additionalProperties: false,
3695
+ properties: { query: { type: "string", minLength: 1, maxLength: 8192 }, limit: { type: "integer", minimum: 1, maximum: 100 }, scope }
3696
+ },
3697
+ resultSchema: {
3698
+ type: "object",
3699
+ required: ["hits"],
3700
+ additionalProperties: false,
3701
+ properties: { hits: { type: "array", maxItems: 100, items: {
3702
+ ...record8,
3703
+ required: [...record8.required, "score"],
3704
+ properties: { ...record8.properties, score: { type: "number", minimum: 0, maximum: 1 } }
3705
+ } } }
3706
+ },
3707
+ effect: "read-only",
3708
+ recovery: { kind: "repeat" },
3709
+ async: false,
3710
+ usage: { meter: "none", priceTable: null }
3711
+ },
3712
+ {
3713
+ op: "get",
3714
+ description: "Read one record from the invocation's authenticated Memory partition.",
3715
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
3716
+ resultSchema: { anyOf: [record8, { type: "null" }] },
3717
+ effect: "read-only",
3718
+ recovery: { kind: "repeat" },
3719
+ async: false,
3720
+ usage: { meter: "none", priceTable: null }
3721
+ },
3722
+ {
3723
+ op: "delete",
3724
+ description: "Delete one record from the invocation's authenticated Memory partition.",
3725
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
3726
+ resultSchema: { type: "object", required: ["deleted"], additionalProperties: false, properties: { deleted: { type: "boolean" } } },
3727
+ effect: "idempotent",
3728
+ recovery: { kind: "idempotency-key" },
3729
+ async: false,
3730
+ usage: { meter: "none", priceTable: null }
3731
+ },
3732
+ {
3733
+ op: "purge",
3734
+ description: "Delete every record in the invocation's authenticated Memory partition.",
3735
+ schema: { type: "object", additionalProperties: false, properties: {} },
3736
+ resultSchema: {
3737
+ type: "object",
3738
+ required: ["deleted"],
3739
+ additionalProperties: false,
3740
+ properties: { deleted: { type: "integer", minimum: 0 } }
3741
+ },
3742
+ effect: "idempotent",
3743
+ recovery: { kind: "idempotency-key" },
3744
+ async: false,
3745
+ usage: { meter: "none", priceTable: null }
3746
+ }
3747
+ ];
2957
3748
 
2958
- // src/credential-provider.ts
3749
+ // packages/sdk/src/credential-provider.ts
2959
3750
  function assertNonSecretConfigSchema(value, field2 = "config") {
2960
3751
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
2961
3752
  const source = value;
@@ -3077,12 +3868,12 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
3077
3868
  return action3;
3078
3869
  }
3079
3870
  function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
3080
- const result = interactionRecord(value);
3081
- if (!result || !exactKeys3(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
3082
- const privateState = result.privateState;
3871
+ const result2 = interactionRecord(value);
3872
+ if (!result2 || !exactKeys3(result2, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
3873
+ const privateState = result2.privateState;
3083
3874
  if (privateState !== void 0 && privateState !== null && (typeof privateState !== "string" || new TextEncoder().encode(privateState).byteLength > 1048576)) throw new TypeError("credential interaction private state is invalid");
3084
3875
  return {
3085
- action: credentialInteractionAction(result.action, origins, state, sessionExpiresAt),
3876
+ action: credentialInteractionAction(result2.action, origins, state, sessionExpiresAt),
3086
3877
  ...privateState === void 0 ? {} : { privateState }
3087
3878
  };
3088
3879
  }
@@ -3126,30 +3917,30 @@ function credentialProviderSetupMetadata(value, slots) {
3126
3917
  }
3127
3918
  return value;
3128
3919
  }
3129
- function credentialProvider(definition) {
3130
- 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") {
3920
+ function credentialProvider(definition2) {
3921
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition2.id) || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition2.version) || !definition2.displayName || definition2.displayName.length > 128 || !definition2.description || definition2.description.length > 1024 || typeof definition2.mint !== "function" || definition2.verify !== void 0 && typeof definition2.verify !== "function" || definition2.destroy !== void 0 && typeof definition2.destroy !== "function") {
3131
3922
  throw new TypeError("credential provider metadata is invalid");
3132
3923
  }
3133
- if (definition.documentationUrl !== void 0) {
3134
- if (typeof definition.documentationUrl !== "string") throw new TypeError("credential provider documentation URL is invalid");
3924
+ if (definition2.documentationUrl !== void 0) {
3925
+ if (typeof definition2.documentationUrl !== "string") throw new TypeError("credential provider documentation URL is invalid");
3135
3926
  let documentationUrl;
3136
3927
  try {
3137
- documentationUrl = new URL(definition.documentationUrl);
3928
+ documentationUrl = new URL(definition2.documentationUrl);
3138
3929
  } catch {
3139
3930
  throw new TypeError("credential provider documentation URL is invalid");
3140
3931
  }
3141
- if (definition.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
3932
+ if (definition2.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
3142
3933
  throw new TypeError("credential provider documentation URL is invalid");
3143
3934
  }
3144
3935
  }
3145
- credentialRotationDefaults(definition.rotation);
3146
- credentialProviderConfigSchema(definition.configSchema);
3147
- credentialProviderConfigSchema(definition.credentialConfigSchema);
3148
- 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))) {
3936
+ credentialRotationDefaults(definition2.rotation);
3937
+ credentialProviderConfigSchema(definition2.configSchema);
3938
+ credentialProviderConfigSchema(definition2.credentialConfigSchema);
3939
+ if (!Array.isArray(definition2.credentialSlots) || definition2.credentialSlots.length > 32 || new Set(definition2.credentialSlots).size !== definition2.credentialSlots.length || definition2.credentialSlots.some((slot) => typeof slot !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(slot))) {
3149
3940
  throw new TypeError("credential provider bootstrap slots are invalid");
3150
3941
  }
3151
- const setup = credentialProviderSetupMetadata(definition.setup, definition.credentialSlots);
3152
- const interaction = definition.interaction ?? null;
3942
+ const setup = credentialProviderSetupMetadata(definition2.setup, definition2.credentialSlots);
3943
+ const interaction = definition2.interaction ?? null;
3153
3944
  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) => {
3154
3945
  try {
3155
3946
  const url = new URL(origin);
@@ -3160,7 +3951,7 @@ function credentialProvider(definition) {
3160
3951
  }))) {
3161
3952
  throw new TypeError("credential provider interaction origins are invalid");
3162
3953
  }
3163
- const mintRecovery = definition.mintRecovery ?? { kind: "idempotency-key" };
3954
+ const mintRecovery = definition2.mintRecovery ?? { kind: "idempotency-key" };
3164
3955
  if (!["idempotency-key", "outcome-unknown"].includes(mintRecovery.kind)) {
3165
3956
  throw new TypeError("credential provider mint recovery is invalid");
3166
3957
  }
@@ -3169,31 +3960,124 @@ function credentialProvider(definition) {
3169
3960
  }
3170
3961
  const metadata2 = {
3171
3962
  lifecycleVersion: 3,
3172
- displayName: definition.displayName,
3173
- description: definition.description,
3174
- ...definition.documentationUrl ? { documentationUrl: definition.documentationUrl } : {},
3963
+ displayName: definition2.displayName,
3964
+ description: definition2.description,
3965
+ ...definition2.documentationUrl ? { documentationUrl: definition2.documentationUrl } : {},
3175
3966
  ...setup ? { setup } : {},
3176
- credentialSlots: [...definition.credentialSlots].sort(),
3177
- credentialConfigSchema: definition.credentialConfigSchema,
3967
+ credentialSlots: [...definition2.credentialSlots].sort(),
3968
+ credentialConfigSchema: definition2.credentialConfigSchema,
3178
3969
  interaction: interaction ? { origins: [...interaction.origins].sort() } : null,
3179
- rotation: definition.rotation,
3180
- egress: integrationEgressPolicy(definition.egress)
3970
+ rotation: definition2.rotation,
3971
+ egress: integrationEgressPolicy(definition2.egress)
3181
3972
  };
3182
- return Object.freeze({ ...definition, mintRecovery, metadata: metadata2 });
3973
+ return Object.freeze({ ...definition2, mintRecovery, metadata: metadata2 });
3974
+ }
3975
+
3976
+ // packages/sdk/src/sandbox-build.ts
3977
+ var recipeProperties = {
3978
+ context: { type: "string", minLength: 1 },
3979
+ dockerfile: { type: "string", minLength: 1 },
3980
+ target: { type: "string", minLength: 1 },
3981
+ platform: { type: "string", minLength: 1 },
3982
+ buildArgs: { type: "object", additionalProperties: { type: "string" } },
3983
+ cache: { type: "boolean" }
3984
+ };
3985
+ var SANDBOX_IMAGE_BUILD_SCHEMA = {
3986
+ type: "object",
3987
+ additionalProperties: false,
3988
+ required: ["sandbox"],
3989
+ properties: {
3990
+ ...recipeProperties,
3991
+ sandbox: { type: "string", pattern: "^sbx-[a-f0-9]{36}$" },
3992
+ secretTargets: { type: "object", additionalProperties: { type: "string", minLength: 1 } },
3993
+ registryTargets: { type: "object", additionalProperties: {
3994
+ type: "object",
3995
+ required: ["username", "slot"],
3996
+ additionalProperties: false,
3997
+ properties: { username: { type: "string" }, slot: { type: "string", minLength: 1 } }
3998
+ } }
3999
+ }
4000
+ };
4001
+ function sandboxImageBuildInput(value) {
4002
+ const invalid = validateJsonSchema(value, { type: "object", additionalProperties: false, properties: {
4003
+ ...recipeProperties,
4004
+ secrets: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA },
4005
+ registries: { type: "object", additionalProperties: {
4006
+ type: "object",
4007
+ required: ["username", "credential"],
4008
+ additionalProperties: false,
4009
+ properties: { username: { type: "string" }, credential: RESOURCE_CREDENTIAL_BINDING_SCHEMA }
4010
+ } }
4011
+ } });
4012
+ if (invalid) throw new TypeError(`Invalid sandbox image build: ${invalid}`);
4013
+ const result2 = structuredClone(value);
4014
+ for (const binding of Object.values(result2.secrets ?? {})) resourceCredentialBinding(binding);
4015
+ for (const registry of Object.values(result2.registries ?? {})) resourceCredentialBinding(registry.credential);
4016
+ return result2;
4017
+ }
4018
+
4019
+ // packages/sdk/src/sandbox-pool.ts
4020
+ var WORKSPACE_ROOT = "/workspace";
4021
+ function absoluteSandboxPath(value) {
4022
+ const segments = [];
4023
+ for (const segment of value.split("/")) {
4024
+ if (!segment || segment === ".") continue;
4025
+ if (segment === "..") segments.pop();
4026
+ else segments.push(segment);
4027
+ }
4028
+ return `/${segments.join("/")}`;
4029
+ }
4030
+ function normalizeSandboxWorkspacePath(path, cwd = WORKSPACE_ROOT) {
4031
+ if (typeof path !== "string" || !path || typeof cwd !== "string" || !cwd || new TextEncoder().encode(path).byteLength > 4096 || new TextEncoder().encode(cwd).byteLength > 4096 || /[\u0000-\u001f\u007f]/u.test(path) || /[\u0000-\u001f\u007f]/u.test(cwd)) {
4032
+ throw new TypeError("sandbox workspace path is invalid");
4033
+ }
4034
+ const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
4035
+ if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
4036
+ throw new TypeError("sandbox working directory is outside /workspace");
4037
+ }
4038
+ const normalized = absoluteSandboxPath(path.startsWith("/") ? path : `${base}/${path}`);
4039
+ if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
4040
+ throw new TypeError("sandbox path is outside /workspace");
4041
+ }
4042
+ return normalized;
4043
+ }
4044
+ var SANDBOX_PROCESS_CREDENTIALS_SCHEMA = { type: "object", additionalProperties: false, properties: {
4045
+ env: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA },
4046
+ files: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA }
4047
+ } };
4048
+ function processCredentialMaps(value, resolve) {
4049
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("process credentials are invalid");
4050
+ const source = value;
4051
+ if (Object.keys(source).some((key) => key !== "env" && key !== "files")) throw new TypeError("process credential kind is invalid");
4052
+ const result2 = {};
4053
+ for (const kind of ["env", "files"]) {
4054
+ const entries = source[kind];
4055
+ if (entries === void 0) continue;
4056
+ if (!entries || typeof entries !== "object" || Array.isArray(entries)) throw new TypeError("process credential map is invalid");
4057
+ result2[kind] = Object.fromEntries(Object.entries(entries).map(([name, binding]) => {
4058
+ if (!name || name.includes("=") || name.includes("\0")) throw new TypeError("process credential variable is invalid");
4059
+ return [name, resolve(binding)];
4060
+ }));
4061
+ }
4062
+ if (Object.keys(result2.env ?? {}).some((name) => Object.hasOwn(result2.files ?? {}, name))) throw new TypeError("a process variable cannot receive both a value and a file path");
4063
+ return result2;
4064
+ }
4065
+ function sandboxProcessCredentials(value) {
4066
+ return processCredentialMaps(value, resourceCredentialBinding);
3183
4067
  }
3184
4068
 
3185
- // src/scorer.ts
4069
+ // packages/sdk/src/scorer.ts
3186
4070
  function validPointer(value) {
3187
4071
  return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));
3188
4072
  }
3189
- function record8(value) {
4073
+ function record9(value) {
3190
4074
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3191
4075
  }
3192
4076
  function exactKeys4(value, allowed) {
3193
4077
  return Object.keys(value).every((key) => allowed.includes(key));
3194
4078
  }
3195
4079
  function scorerRule(value, depth, state) {
3196
- const rule = record8(value);
4080
+ const rule = record9(value);
3197
4081
  if (!rule || depth > 32 || ++state.rules > 1024 || typeof rule.op !== "string") throw new TypeError("Code Scorer IR is invalid");
3198
4082
  if (rule.op === "all" || rule.op === "any") {
3199
4083
  if (!exactKeys4(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1 || rule.rules.length > 128) {
@@ -3206,7 +4090,7 @@ function scorerRule(value, depth, state) {
3206
4090
  return { op: "not", rule: scorerRule(rule.rule, depth + 1, state) };
3207
4091
  }
3208
4092
  if (rule.op === "schema") {
3209
- if (!exactKeys4(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record8(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
4093
+ if (!exactKeys4(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record9(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
3210
4094
  return rule;
3211
4095
  }
3212
4096
  if (rule.op === "regex") {
@@ -3241,7 +4125,7 @@ function scorerRule(value, depth, state) {
3241
4125
  throw new TypeError("Code Scorer operation is invalid");
3242
4126
  }
3243
4127
  function codeScorerIR(value) {
3244
- const ir = record8(value);
4128
+ const ir = record9(value);
3245
4129
  if (!ir || ir.v !== 1 || !exactKeys4(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
3246
4130
  return { v: 1, rule: scorerRule(ir.rule, 0, { rules: 0 }) };
3247
4131
  }
@@ -3254,7 +4138,7 @@ function pointer(value, path) {
3254
4138
  if (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length) return { found: false, value: void 0 };
3255
4139
  current = current[Number(key)];
3256
4140
  } else {
3257
- const source = record8(current);
4141
+ const source = record9(current);
3258
4142
  if (!source || !Object.hasOwn(source, key)) return { found: false, value: void 0 };
3259
4143
  current = source[key];
3260
4144
  }
@@ -3288,7 +4172,7 @@ function evaluate(rule, subject) {
3288
4172
  if (!sources.found || !Array.isArray(sources.value)) return fail(rule.sourcesPath, "citation sources are missing");
3289
4173
  const available = new Set(sources.value.flatMap((source, index) => {
3290
4174
  if (typeof source === "string") return [source, String(index + 1)];
3291
- const item = record8(source);
4175
+ const item = record9(source);
3292
4176
  return item ? [String(item.id ?? ""), String(index + 1)].filter(Boolean) : [String(index + 1)];
3293
4177
  }));
3294
4178
  const citations = [...text2.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
@@ -3307,7 +4191,7 @@ function evaluate(rule, subject) {
3307
4191
  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));
3308
4192
  return contains ? pass() : fail(rule.path, "value is not contained");
3309
4193
  }
3310
- const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record8(item)?.name ?? "")) : [];
4194
+ const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record9(item)?.name ?? "")) : [];
3311
4195
  const sequence = rule.mode === "exact" ? names.length === rule.expected.length && names.every((name, index) => name === rule.expected[index]) : rule.expected.reduce((cursor, expected) => {
3312
4196
  const index = names.indexOf(expected, cursor);
3313
4197
  return index < 0 ? Number.POSITIVE_INFINITY : index + 1;
@@ -3316,20 +4200,20 @@ function evaluate(rule, subject) {
3316
4200
  }
3317
4201
  function evaluateCodeScorer(raw, subject) {
3318
4202
  const ir = codeScorerIR(raw);
3319
- const result = evaluate(ir.rule, subject);
4203
+ const result2 = evaluate(ir.rule, subject);
3320
4204
  return {
3321
- score: result.pass ? 1 : 0,
3322
- pass: result.pass,
4205
+ score: result2.pass ? 1 : 0,
4206
+ pass: result2.pass,
3323
4207
  dimensions: null,
3324
- evidence: { rule: canonicalJson(ir.rule), checks: result.checks, failures: result.failures.slice(0, 64) }
4208
+ evidence: { rule: canonicalJson(ir.rule), checks: result2.checks, failures: result2.failures.slice(0, 64) }
3325
4209
  };
3326
4210
  }
3327
4211
 
3328
- // src/errors.ts
4212
+ // packages/sdk/src/errors.ts
3329
4213
  var GateExhausted = class extends Error {
3330
- constructor(record9) {
4214
+ constructor(record10) {
3331
4215
  super("turn gate exhausted");
3332
- this.record = record9;
4216
+ this.record = record10;
3333
4217
  this.name = "GateExhausted";
3334
4218
  }
3335
4219
  record;
@@ -3343,8 +4227,8 @@ var CommitGateRejected = class extends Error {
3343
4227
  evaluation;
3344
4228
  };
3345
4229
  var SpawnCardinality = class extends Error {
3346
- constructor(message = "spawn cardinality exceeds the configured cap; use map") {
3347
- super(message);
4230
+ constructor(message2 = "spawn cardinality exceeds the configured cap; use map") {
4231
+ super(message2);
3348
4232
  this.name = "SpawnCardinality";
3349
4233
  }
3350
4234
  };
@@ -3371,8 +4255,8 @@ var OutcomeUnknown = class extends Error {
3371
4255
  effect;
3372
4256
  };
3373
4257
  var LeaseLost = class extends Error {
3374
- constructor(message = "invocation lease is no longer current") {
3375
- super(message);
4258
+ constructor(message2 = "invocation lease is no longer current") {
4259
+ super(message2);
3376
4260
  this.name = "LeaseLost";
3377
4261
  }
3378
4262
  };
@@ -3407,33 +4291,33 @@ var CommitConflict = class extends Error {
3407
4291
  actual;
3408
4292
  };
3409
4293
  var ResourceInvalid = class extends Error {
3410
- constructor(resource) {
3411
- super(`invalid resource: ${resource}`);
3412
- this.resource = resource;
4294
+ constructor(resource2) {
4295
+ super(`invalid resource: ${resource2}`);
4296
+ this.resource = resource2;
3413
4297
  this.name = "ResourceInvalid";
3414
4298
  }
3415
4299
  resource;
3416
4300
  };
3417
4301
  var ResourceUnbound = class extends Error {
3418
- constructor(resource) {
3419
- super(`resource is not bound to this execution: ${resource}`);
3420
- this.resource = resource;
4302
+ constructor(resource2) {
4303
+ super(`resource is not bound to this execution: ${resource2}`);
4304
+ this.resource = resource2;
3421
4305
  this.name = "ResourceUnbound";
3422
4306
  }
3423
4307
  resource;
3424
4308
  };
3425
4309
  var ToolUnavailable = class extends Error {
3426
- constructor(tool) {
3427
- super(`Tool is not enabled for this Agent deployment: ${tool}`);
3428
- this.tool = tool;
4310
+ constructor(tool2) {
4311
+ super(`Tool is not enabled for this Agent deployment: ${tool2}`);
4312
+ this.tool = tool2;
3429
4313
  this.name = "ToolUnavailable";
3430
4314
  }
3431
4315
  tool;
3432
4316
  };
3433
4317
  var UnknownTool = class extends Error {
3434
- constructor(tool) {
3435
- super(`model emitted a Tool that was not offered: ${tool}`);
3436
- this.tool = tool;
4318
+ constructor(tool2) {
4319
+ super(`model emitted a Tool that was not offered: ${tool2}`);
4320
+ this.tool = tool2;
3437
4321
  this.name = "UnknownTool";
3438
4322
  }
3439
4323
  tool;
@@ -3449,24 +4333,24 @@ var EffectCeilingExceeded = class extends Error {
3449
4333
  observed;
3450
4334
  };
3451
4335
  var ResourceDisabled = class extends Error {
3452
- constructor(resource) {
3453
- super(`resource is disabled: ${resource}`);
3454
- this.resource = resource;
4336
+ constructor(resource2) {
4337
+ super(`resource is disabled: ${resource2}`);
4338
+ this.resource = resource2;
3455
4339
  this.name = "ResourceDisabled";
3456
4340
  }
3457
4341
  resource;
3458
4342
  };
3459
4343
  var PolicyDecisionFailed = class extends Error {
3460
- constructor(decisionHash, message = "Policy denied operation") {
3461
- super(message);
4344
+ constructor(decisionHash, message2 = "Policy denied operation") {
4345
+ super(message2);
3462
4346
  this.decisionHash = decisionHash;
3463
4347
  this.name = "PolicyDecisionFailed";
3464
4348
  }
3465
4349
  decisionHash;
3466
4350
  };
3467
4351
  var PolicyConstraintFailed = class extends PolicyDecisionFailed {
3468
- constructor(decisionHash, message = "Policy constraint rejected operation") {
3469
- super(decisionHash, message);
4352
+ constructor(decisionHash, message2 = "Policy constraint rejected operation") {
4353
+ super(decisionHash, message2);
3470
4354
  this.name = "PolicyConstraintFailed";
3471
4355
  }
3472
4356
  };
@@ -3512,12 +4396,14 @@ export {
3512
4396
  CONSTAL_API_OPERATION_SCHEMAS,
3513
4397
  CONSTAL_API_QUERY_KINDS,
3514
4398
  CONSTAL_API_VERSION,
4399
+ CONSTAL_MODEL_CREATE_SCHEMA,
3515
4400
  CommitConflict,
3516
4401
  CommitGateRejected,
3517
4402
  CredentialRevoked,
3518
4403
  CredentialUnavailable,
3519
4404
  DirectNetworkDenied,
3520
4405
  EffectCeilingExceeded,
4406
+ GATEWAY_MODEL_OFFER_SCHEMA,
3521
4407
  GateExhausted,
3522
4408
  IntegrationRequestNotSent,
3523
4409
  LeaseLost,
@@ -3525,15 +4411,19 @@ export {
3525
4411
  MEMORY_OPERATION_DECLARATIONS,
3526
4412
  MODEL_CHECKPOINT_IMPORT_CAPABILITY,
3527
4413
  MODEL_COMPLETION_CAPABILITY,
4414
+ MODEL_GENERATION_OPTIONS_SCHEMA,
4415
+ MODEL_GENERATION_OPTION_KEYS,
3528
4416
  NondeterministicReplay,
3529
4417
  OutcomeUnknown,
3530
4418
  PolicyConstraintFailed,
3531
4419
  PolicyDecisionFailed,
4420
+ RESOURCE_CREDENTIAL_BINDING_SCHEMA,
3532
4421
  RESOURCE_KINDS,
3533
4422
  ResourceDisabled,
3534
4423
  ResourceInvalid,
3535
4424
  ResourceUnbound,
3536
4425
  RollbackTargetInvalid,
4426
+ SANDBOX_PROCESS_CREDENTIALS_SCHEMA,
3537
4427
  SessionDeleted,
3538
4428
  SpawnCardinality,
3539
4429
  SwallowedYield,
@@ -3551,6 +4441,7 @@ export {
3551
4441
  agentSetupMetadata,
3552
4442
  agentSetupRequirements,
3553
4443
  analyticsEvent,
4444
+ applyModelProviderOptions,
3554
4445
  approximateTokens,
3555
4446
  authProvider,
3556
4447
  authProviderName,
@@ -3570,6 +4461,7 @@ export {
3570
4461
  checkpointImportMetadata,
3571
4462
  checkpointImportRequest,
3572
4463
  codeScorerIR,
4464
+ connections,
3573
4465
  credentialEvidence,
3574
4466
  credentialInteractionAction,
3575
4467
  credentialInteractionEvent,
@@ -3597,18 +4489,23 @@ export {
3597
4489
  matchesAction,
3598
4490
  matchesLabelSelector,
3599
4491
  matchesResource,
4492
+ mcpProtocol,
3600
4493
  memoryStoreBinding,
3601
4494
  modelAdvertisedPricing,
3602
4495
  modelControls,
3603
4496
  modelGatewayBinding,
3604
4497
  modelGatewayEndpoint,
4498
+ modelGenerationOptions,
3605
4499
  modelLimit,
3606
4500
  modelPrompt,
3607
4501
  modelProtocolRequest,
3608
4502
  modelProtocolResult,
4503
+ modelProviderOptions,
3609
4504
  murmur3_32,
4505
+ normalizeInvocationOptions,
3610
4506
  normalizeModelGatewayConfig,
3611
4507
  normalizeSandboxNetworkPolicy,
4508
+ normalizeSandboxWorkspacePath,
3612
4509
  opTool,
3613
4510
  opTools,
3614
4511
  parseResourceName,
@@ -3618,16 +4515,22 @@ export {
3618
4515
  resolveBindingOwner,
3619
4516
  resolveGatewayEgress,
3620
4517
  resolveResourceDependencyRef,
4518
+ resourceContext,
3621
4519
  resourceContractRef,
3622
4520
  resourceCredentialBinding,
4521
+ resourceCredentialBindings,
3623
4522
  resourceDependencyRef,
4523
+ resourceIndex,
3624
4524
  resourceLabelMap,
3625
4525
  resourceName,
3626
4526
  resourceNeed,
3627
4527
  resourcePattern,
3628
4528
  resourceSelector,
4529
+ resourceTools,
3629
4530
  sandboxControls,
4531
+ sandboxImageBuildInput,
3630
4532
  sandboxLimit,
4533
+ sandboxProcessCredentials,
3631
4534
  scopedBindingKey,
3632
4535
  scopedCredentialRef,
3633
4536
  scopedResourceRef,
@@ -3639,6 +4542,7 @@ export {
3639
4542
  setupScreenView,
3640
4543
  setupSubmission,
3641
4544
  sha256Hex,
4545
+ skills,
3642
4546
  stageOutput,
3643
4547
  startTrainingRequest,
3644
4548
  subtask,