@constal/sdk 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/publish/index.js CHANGED
@@ -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,9 +1135,67 @@ function uiBundle(value, execution) {
1118
1135
  return { manifest, modules: normalizedModules, assets: normalizedAssets };
1119
1136
  }
1120
1137
 
1121
- // src/setup-workflow.ts
1138
+ // packages/sdk/src/ingress.ts
1139
+ var encoder3 = new TextEncoder();
1140
+ function object2(value) {
1141
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1142
+ }
1143
+ function channelSourceEvidence(value) {
1144
+ const input = object2(value), channel2 = object2(input?.channel), authProvider2 = object2(input?.authProvider);
1145
+ if (!input || !channel2 || !authProvider2 || typeof authProvider2.crn !== "string" || typeof authProvider2.hash !== "string" || !/^[a-f0-9]{64}$/u.test(authProvider2.hash) || typeof channel2.crn !== "string" || typeof channel2.hash !== "string" || !/^[a-f0-9]{64}$/u.test(channel2.hash) || typeof input.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(input.id) || typeof input.requestHash !== "string" || !/^[a-f0-9]{64}$/u.test(input.requestHash)) throw new TypeError("Channel source evidence is invalid");
1146
+ const source = channelIngressSource(input.source), name = parseResourceName(channel2.crn), authentication = parseResourceName(authProvider2.crn);
1147
+ if (name.kind !== "channel" || name.tenant !== "platform" || name.namespace !== "ingress" || name.path !== source.provider || authentication.kind !== "auth-provider" || authentication.environment !== name.environment || authentication.tenant !== name.tenant || authentication.namespace !== name.namespace) {
1148
+ throw new TypeError("Channel source evidence is outside its source");
1149
+ }
1150
+ return { channel: { crn: channel2.crn, hash: channel2.hash }, authProvider: { crn: authProvider2.crn, hash: authProvider2.hash }, source, id: input.id, requestHash: input.requestHash };
1151
+ }
1152
+ function credentialEvidence(value) {
1153
+ const input = object2(value), provider = object2(input?.provider), claims = object2(input?.claims);
1154
+ if (!input || typeof input.credential !== "string" || !provider || typeof provider.crn !== "string" || typeof provider.hash !== "string" || !/^[a-f0-9]{64}$/u.test(provider.hash) || !Number.isSafeInteger(input.version) || Number(input.version) < 1 || input.expiresAt !== null && (!Number.isSafeInteger(input.expiresAt) || Number(input.expiresAt) < 1) || !claims || Object.keys(claims).length > 32 || encoder3.encode(JSON.stringify(claims)).byteLength > 65536 || Object.entries(claims).some(([key, value2]) => !/^[A-Za-z0-9._-]{1,128}$/u.test(key) || !(typeof value2 === "string" && value2.length <= 2048 || typeof value2 === "boolean" || typeof value2 === "number" && Number.isFinite(value2) || Array.isArray(value2) && value2.length <= 500 && value2.every((item) => typeof item === "string" && item.length <= 256)))) {
1155
+ throw new TypeError("Credential evidence is invalid");
1156
+ }
1157
+ if (parseResourceName(input.credential).kind !== "credential" || parseResourceName(provider.crn).kind !== "credential-provider") {
1158
+ throw new TypeError("Credential evidence identity is invalid");
1159
+ }
1160
+ return {
1161
+ credential: input.credential,
1162
+ provider: { crn: provider.crn, hash: provider.hash },
1163
+ version: Number(input.version),
1164
+ expiresAt: input.expiresAt,
1165
+ claims
1166
+ };
1167
+ }
1168
+ function channelIngressSource(value) {
1169
+ const source = object2(value);
1170
+ if (!source || typeof source.provider !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(source.provider) || typeof source.key !== "string" || !/^[A-Za-z0-9._:-]{1,256}$/u.test(source.key)) throw new TypeError("Channel ingress source is invalid");
1171
+ return { provider: source.provider, key: source.key };
1172
+ }
1173
+ function channelSubscriptionRequest(value) {
1174
+ const input = object2(value), configuration = object2(input?.configuration);
1175
+ if (!input || !configuration || typeof input.channel !== "string" || typeof input.principal !== "string") throw new TypeError("Channel subscription is invalid");
1176
+ const channel2 = parseResourceName(input.channel), principal = parseResourceName(input.principal);
1177
+ if (channel2.kind !== "channel" || principal.kind !== "principal" || channel2.environment !== principal.environment || channel2.tenant !== principal.tenant) {
1178
+ throw new TypeError("Channel subscription crosses the authenticated tenant");
1179
+ }
1180
+ const credentials = input.credentials ?? [];
1181
+ if (!Array.isArray(credentials) || credentials.length > 32) throw new TypeError("Channel subscription Credentials are invalid");
1182
+ const proofs = credentials.map(credentialEvidence);
1183
+ for (const proof of proofs) {
1184
+ const owner = parseResourceName(proof.credential), provider = parseResourceName(proof.provider.crn);
1185
+ if (owner.tenant !== channel2.tenant || owner.environment !== channel2.environment || provider.environment !== channel2.environment) {
1186
+ throw new TypeError("Channel subscription Credential crosses the authenticated tenant");
1187
+ }
1188
+ }
1189
+ return { source: channelIngressSource(input.source), channel: input.channel, principal: input.principal, configuration, credentials: proofs };
1190
+ }
1191
+ function channelIngressRequest(value) {
1192
+ const input = object2(value), headers = object2(input?.headers);
1193
+ if (!input || !["GET", "POST", "PUT", "PATCH", "DELETE"].includes(String(input.method)) || typeof input.url !== "string" || !input.url || input.url.length > 2048 || !headers || Object.keys(headers).length > 128 || Object.entries(headers).some(([key, value2]) => !/^[a-z0-9-]{1,128}$/u.test(key) || typeof value2 !== "string" || value2.length > 8192) || input.bodyBase64 !== null && (typeof input.bodyBase64 !== "string" || input.bodyBase64.length > 5592408) || encoder3.encode(JSON.stringify(input)).byteLength > 6 * 1024 * 1024) throw new TypeError("Channel ingress request is invalid");
1194
+ return { method: input.method, url: input.url, headers, bodyBase64: input.bodyBase64 };
1195
+ }
1196
+
1197
+ // packages/sdk/src/setup-workflow.ts
1122
1198
  var ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1123
- var CRN = /^crn:constal:[a-z0-9-]+:[a-z0-9-]+:[a-z0-9-]+:credential-provider\/[A-Za-z0-9._~/%-]{1,512}$/u;
1124
1199
  var MAX_SCREEN_BYTES = 262144;
1125
1200
  function record3(value) {
1126
1201
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
@@ -1147,9 +1222,9 @@ function actions(value) {
1147
1222
  function panelBase(source) {
1148
1223
  const id2 = text(source.id, 63);
1149
1224
  const title = text(source.title, 256);
1150
- const description = text(source.description, 4096, true);
1225
+ const description2 = text(source.description, 4096, true);
1151
1226
  const parsedActions = actions(source.actions);
1152
- 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;
1153
1228
  }
1154
1229
  function panel(value) {
1155
1230
  const source = record3(value);
@@ -1165,13 +1240,38 @@ function panel(value) {
1165
1240
  if (source.kind === "credential-interaction") {
1166
1241
  const provider = text(source.provider, 1024);
1167
1242
  const credentialId = text(source.credentialId, 63);
1168
- if (!provider || !CRN.test(provider) || !credentialId || !ID.test(credentialId) || !["connect", "reauthorize", "manage"].includes(String(source.operation)) || !exact(source, ["kind", "id", "title", "description", "actions", "provider", "credentialId", "operation"])) return null;
1243
+ if (!provider || !credentialId || !ID.test(credentialId) || !["connect", "reauthorize", "manage"].includes(String(source.operation)) || source.receipt !== void 0 && !["reference", "evidence"].includes(String(source.receipt)) || source.receipt !== void 0 && base.actions.filter((action3) => action3.intent === "primary").length !== 1 || (source.selection !== void 0 || source.configuration !== void 0) && source.receipt === void 0 || source.configuration !== void 0 && !record3(source.configuration) || !exact(source, ["kind", "id", "title", "description", "actions", "provider", "credentialId", "operation", "receipt", "selection", "configuration"])) return null;
1244
+ try {
1245
+ if (parseResourceName(provider).kind !== "credential-provider") return null;
1246
+ } catch {
1247
+ return null;
1248
+ }
1249
+ let selection;
1250
+ if (source.selection !== void 0) {
1251
+ const input = record3(source.selection);
1252
+ if (!input || !exact(input, ["selector", "binding"]) || !record3(input.selector)) return null;
1253
+ try {
1254
+ const requirement = agentSetupRequirements([{
1255
+ id: base.id,
1256
+ title: base.title,
1257
+ resourceKind: "credential",
1258
+ selector: input.selector,
1259
+ binding: input.binding
1260
+ }])[0];
1261
+ selection = { selector: requirement.selector, binding: requirement.binding };
1262
+ } catch {
1263
+ return null;
1264
+ }
1265
+ }
1169
1266
  return {
1170
1267
  ...base,
1171
1268
  kind: "credential-interaction",
1172
1269
  provider,
1173
1270
  credentialId,
1174
- operation: source.operation
1271
+ operation: source.operation,
1272
+ ...source.receipt === void 0 ? {} : { receipt: source.receipt },
1273
+ ...selection ? { selection } : {},
1274
+ ...source.configuration === void 0 ? {} : { configuration: source.configuration }
1175
1275
  };
1176
1276
  }
1177
1277
  if (source.kind === "review") {
@@ -1264,6 +1364,9 @@ function setupSubmission(value, screen) {
1264
1364
  const error = validateJsonSchema(values ?? {}, screen.current.schema, "$setup.submission.values");
1265
1365
  if (error) throw new TypeError(error);
1266
1366
  }
1367
+ if (screen.current.kind === "credential-interaction" && screen.current.receipt !== void 0 && source.action === screen.current.actions.find(({ intent }) => intent === "primary")?.id) {
1368
+ setupCredentialReceipt(values, screen.current);
1369
+ }
1267
1370
  return {
1268
1371
  object: "constal.setup.submission",
1269
1372
  version: 1,
@@ -1274,8 +1377,78 @@ function setupSubmission(value, screen) {
1274
1377
  ...values ? { values } : {}
1275
1378
  };
1276
1379
  }
1380
+ function setupCredentialReceipt(value, panel2) {
1381
+ const source = record3(value), credential = record3(source?.credential), binding = record3(source?.binding);
1382
+ const hash3 = (value2) => typeof value2 === "string" && /^[a-f0-9]{64}$/u.test(value2);
1383
+ if (!panel2.receipt || !source || source.object !== "constal.setup.credential" || source.version !== 1 || !exact(source, ["object", "version", "credential", "evidence", "binding"]) || !credential || !exact(credential, ["crn", "hash"]) || typeof credential.crn !== "string" || !hash3(credential.hash)) {
1384
+ throw new TypeError("Setup Credential receipt is invalid");
1385
+ }
1386
+ const target = parseResourceName(credential.crn), provider = parseResourceName(panel2.provider);
1387
+ if (target.kind !== "credential" || target.environment !== provider.environment || provider.tenant !== "platform" && provider.tenant !== target.tenant) throw new TypeError("Setup Credential receipt identity is invalid");
1388
+ const evidence = source.evidence === null ? null : credentialEvidence(source.evidence);
1389
+ if (panel2.receipt === "evidence" && !evidence || panel2.receipt === "reference" && evidence || evidence && (evidence.credential !== credential.crn || evidence.provider.crn !== panel2.provider)) {
1390
+ throw new TypeError("Setup Credential evidence does not match its step");
1391
+ }
1392
+ if (panel2.selection) {
1393
+ if (!binding || !exact(binding, ["crn", "headSeq", "revisionHash"]) || typeof binding.crn !== "string" || !Number.isSafeInteger(binding.headSeq) || Number(binding.headSeq) < 1 || !hash3(binding.revisionHash)) {
1394
+ throw new TypeError("Setup Credential binding receipt is invalid");
1395
+ }
1396
+ const owner = parseResourceName(binding.crn);
1397
+ if (owner.kind !== "binding" || owner.tenant !== target.tenant || owner.environment !== target.environment) {
1398
+ throw new TypeError("Setup Credential binding receipt is outside its tenant");
1399
+ }
1400
+ } else if (source.binding !== null) throw new TypeError("Setup Credential step did not declare a binding");
1401
+ return {
1402
+ object: "constal.setup.credential",
1403
+ version: 1,
1404
+ credential: { crn: credential.crn, hash: credential.hash },
1405
+ evidence,
1406
+ binding: binding ? { crn: binding.crn, headSeq: Number(binding.headSeq), revisionHash: binding.revisionHash } : null
1407
+ };
1408
+ }
1277
1409
  function setupAwait(screen) {
1278
1410
  if (screen.status !== "active" || !screen.waitLabel) throw new TypeError("Only an active Setup screen can open a wait");
1411
+ const current = screen.current;
1412
+ const hash3 = { type: "string", pattern: "^[a-f0-9]{64}$" };
1413
+ const reference = {
1414
+ type: "object",
1415
+ additionalProperties: false,
1416
+ required: ["crn", "hash"],
1417
+ properties: { crn: { type: "string", maxLength: 1024 }, hash: hash3 }
1418
+ };
1419
+ const receipt = current.kind === "credential-interaction" && current.receipt !== void 0 ? {
1420
+ type: "object",
1421
+ additionalProperties: false,
1422
+ required: ["object", "version", "credential", "evidence", "binding"],
1423
+ properties: {
1424
+ object: { const: "constal.setup.credential" },
1425
+ version: { const: 1 },
1426
+ credential: reference,
1427
+ evidence: current.receipt === "reference" ? { type: "null" } : {
1428
+ type: "object",
1429
+ additionalProperties: false,
1430
+ required: ["credential", "provider", "version", "expiresAt", "claims"],
1431
+ properties: {
1432
+ credential: { type: "string", maxLength: 1024 },
1433
+ provider: {
1434
+ ...reference,
1435
+ properties: { crn: { const: current.provider }, hash: hash3 }
1436
+ },
1437
+ version: { type: "integer", minimum: 1 },
1438
+ expiresAt: { type: ["integer", "null"], minimum: 1 },
1439
+ claims: { type: "object", maxProperties: 32 }
1440
+ }
1441
+ },
1442
+ binding: current.selection ? {
1443
+ type: "object",
1444
+ additionalProperties: false,
1445
+ required: ["crn", "headSeq", "revisionHash"],
1446
+ properties: { crn: { type: "string", maxLength: 1024 }, headSeq: { type: "integer", minimum: 1 }, revisionHash: hash3 }
1447
+ } : { type: "null" }
1448
+ }
1449
+ } : null;
1450
+ const primary = current.actions.find((action3) => action3.intent === "primary");
1451
+ const secondary = current.actions.filter((action3) => action3.id !== primary?.id).map((action3) => action3.id);
1279
1452
  return { maxBytes: 262144, schema: {
1280
1453
  type: "object",
1281
1454
  additionalProperties: false,
@@ -1288,7 +1461,11 @@ function setupAwait(screen) {
1288
1461
  step: { const: screen.current.id },
1289
1462
  action: { enum: screen.current.actions.map(({ id: id2 }) => id2) },
1290
1463
  values: { type: "object", additionalProperties: true }
1291
- }
1464
+ },
1465
+ ...receipt && primary ? { anyOf: [
1466
+ { required: ["values"], properties: { action: { const: primary.id }, values: receipt } },
1467
+ ...secondary.length ? [{ properties: { action: { enum: secondary } } }] : []
1468
+ ] } : {}
1292
1469
  } };
1293
1470
  }
1294
1471
  function setupScreenView(id2 = "setup-screen") {
@@ -1306,7 +1483,7 @@ function setupScreenView(id2 = "setup-screen") {
1306
1483
  };
1307
1484
  }
1308
1485
 
1309
- // src/agent-setup.ts
1486
+ // packages/sdk/src/agent-setup.ts
1310
1487
  function credentialSetupState(requirement, scope2, inventory, binding) {
1311
1488
  const parsed = agentSetupRequirements([requirement])[0];
1312
1489
  if (parsed.resourceKind !== "credential") throw new TypeError("Credential setup requires a Credential requirement");
@@ -1349,329 +1526,734 @@ function credentialSetupState(requirement, scope2, inventory, binding) {
1349
1526
  };
1350
1527
  }
1351
1528
 
1352
- // src/ingress.ts
1353
- var encoder3 = new TextEncoder();
1354
- function object2(value) {
1355
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
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
+ };
1356
1537
  }
1357
- function channelSourceEvidence(value) {
1358
- const input = object2(value), channel2 = object2(input?.channel), authProvider2 = object2(input?.authProvider);
1359
- if (!input || !channel2 || !authProvider2 || typeof authProvider2.crn !== "string" || typeof authProvider2.hash !== "string" || !/^[a-f0-9]{64}$/u.test(authProvider2.hash) || typeof channel2.crn !== "string" || typeof channel2.hash !== "string" || !/^[a-f0-9]{64}$/u.test(channel2.hash) || typeof input.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u.test(input.id) || typeof input.requestHash !== "string" || !/^[a-f0-9]{64}$/u.test(input.requestHash)) throw new TypeError("Channel source evidence is invalid");
1360
- const source = channelIngressSource(input.source), name = parseResourceName(channel2.crn), authentication = parseResourceName(authProvider2.crn);
1361
- if (name.kind !== "channel" || name.tenant !== "platform" || name.namespace !== "ingress" || name.path !== source.provider || authentication.kind !== "auth-provider" || authentication.environment !== name.environment || authentication.tenant !== name.tenant || authentication.namespace !== name.namespace) {
1362
- throw new TypeError("Channel source evidence is outside its source");
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)
1580
+ },
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);
1623
+ }
1624
+ },
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) };
1633
+ }
1634
+ },
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: {
1641
+ type: "object",
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."
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 };
1666
+ }
1667
+ return await handle;
1668
+ }
1363
1669
  }
1364
- return { channel: { crn: channel2.crn, hash: channel2.hash }, authProvider: { crn: authProvider2.crn, hash: authProvider2.hash }, source, id: input.id, requestHash: input.requestHash };
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] : {};
1365
1697
  }
1366
- function credentialEvidence(value) {
1367
- const input = object2(value), provider = object2(input?.provider), claims = object2(input?.claims);
1368
- if (!input || typeof input.credential !== "string" || !provider || typeof provider.crn !== "string" || typeof provider.hash !== "string" || !/^[a-f0-9]{64}$/u.test(provider.hash) || !Number.isSafeInteger(input.version) || Number(input.version) < 1 || input.expiresAt !== null && (!Number.isSafeInteger(input.expiresAt) || Number(input.expiresAt) < 1) || !claims || Object.keys(claims).length > 32 || encoder3.encode(JSON.stringify(claims)).byteLength > 65536 || Object.entries(claims).some(([key, value2]) => !/^[A-Za-z0-9._-]{1,128}$/u.test(key) || !(typeof value2 === "string" && value2.length <= 2048 || typeof value2 === "boolean" || typeof value2 === "number" && Number.isFinite(value2) || Array.isArray(value2) && value2.length <= 500 && value2.every((item) => typeof item === "string" && item.length <= 256)))) {
1369
- throw new TypeError("Credential evidence is invalid");
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";
1370
1707
  }
1371
- if (parseResourceName(input.credential).kind !== "credential" || parseResourceName(provider.crn).kind !== "credential-provider") {
1372
- throw new TypeError("Credential evidence identity is invalid");
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");
1373
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");
1374
1799
  return {
1375
- credential: input.credential,
1376
- provider: { crn: provider.crn, hash: provider.hash },
1377
- version: Number(input.version),
1378
- expiresAt: input.expiresAt,
1379
- claims
1800
+ ...tool2,
1801
+ name: tool2.name,
1802
+ description: typeof tool2.description === "string" ? tool2.description : "",
1803
+ inputSchema,
1804
+ outputSchema,
1805
+ annotations: record4(tool2.annotations) ?? {}
1380
1806
  };
1381
1807
  }
1382
- function channelIngressSource(value) {
1383
- const source = object2(value);
1384
- if (!source || typeof source.provider !== "string" || !/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(source.provider) || typeof source.key !== "string" || !/^[A-Za-z0-9._:-]{1,256}$/u.test(source.key)) throw new TypeError("Channel ingress source is invalid");
1385
- return { provider: source.provider, key: source.key };
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;
1386
1850
  }
1387
- function channelSubscriptionRequest(value) {
1388
- const input = object2(value), configuration = object2(input?.configuration);
1389
- if (!input || !configuration || typeof input.channel !== "string" || typeof input.principal !== "string") throw new TypeError("Channel subscription is invalid");
1390
- const channel2 = parseResourceName(input.channel), principal = parseResourceName(input.principal);
1391
- if (channel2.kind !== "channel" || principal.kind !== "principal" || channel2.environment !== principal.environment || channel2.tenant !== principal.tenant) {
1392
- throw new TypeError("Channel subscription crosses the authenticated tenant");
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";
1393
1871
  }
1394
- const credentials = input.credentials ?? [];
1395
- if (!Array.isArray(credentials) || credentials.length > 32) throw new TypeError("Channel subscription Credentials are invalid");
1396
- const proofs = credentials.map(credentialEvidence);
1397
- for (const proof of proofs) {
1398
- const owner = parseResourceName(proof.credential), provider = parseResourceName(proof.provider.crn);
1399
- if (owner.tenant !== channel2.tenant || owner.environment !== channel2.environment || provider.environment !== channel2.environment) {
1400
- throw new TypeError("Channel subscription Credential crosses the authenticated tenant");
1872
+ kind;
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" });
1401
1933
  }
1402
1934
  }
1403
- return { source: channelIngressSource(input.source), channel: input.channel, principal: input.principal, configuration, credentials: proofs };
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
+ };
1404
1953
  }
1405
- function channelIngressRequest(value) {
1406
- const input = object2(value), headers = object2(input?.headers);
1407
- if (!input || !["GET", "POST", "PUT", "PATCH", "DELETE"].includes(String(input.method)) || typeof input.url !== "string" || !input.url || input.url.length > 2048 || !headers || Object.keys(headers).length > 128 || Object.entries(headers).some(([key, value2]) => !/^[a-z0-9-]{1,128}$/u.test(key) || typeof value2 !== "string" || value2.length > 8192) || input.bodyBase64 !== null && (typeof input.bodyBase64 !== "string" || input.bodyBase64.length > 5592408) || encoder3.encode(JSON.stringify(input)).byteLength > 6 * 1024 * 1024) throw new TypeError("Channel ingress request is invalid");
1408
- return { method: input.method, url: input.url, headers, bodyBase64: input.bodyBase64 };
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) };
1409
2057
  }
1410
2058
 
1411
- // src/constal-api.ts
1412
- var CONSTAL_API_CAPABILITY = "constal.api";
1413
- var CONSTAL_API_VERSION = "1";
1414
- var CONSTAL_API_OPERATIONS = [
1415
- "describe",
1416
- "query",
1417
- "get",
1418
- "relations",
1419
- "explainPolicy",
1420
- "plan",
1421
- "apply",
1422
- "observe"
1423
- ];
1424
- var CONSTAL_API_BOUNDS = {
1425
- defaultPageSize: 50,
1426
- maximumPageSize: 200,
1427
- maximumRelationDepth: 3,
1428
- maximumPlanOperations: 64,
1429
- maximumInputBytes: 1048576,
1430
- planTtlMs: 15 * 6e4
1431
- };
1432
- var CONSTAL_API_QUERY_KINDS = [
1433
- ...RESOURCE_KINDS,
1434
- "analytics",
1435
- "customer",
1436
- "binding",
1437
- "session",
1438
- "run",
1439
- "deployment",
1440
- "documentation",
1441
- "analytics-event",
1442
- "namespace",
1443
- "team-member",
1444
- "team-invite",
1445
- "api-key",
1446
- "billing-account",
1447
- "invoice",
1448
- "subscription",
1449
- "resource-contract",
1450
- "dataset-draft",
1451
- "dataset-case",
1452
- "eval-score",
1453
- "eval-sample",
1454
- "eval-policy",
1455
- "eval-suite",
1456
- "eval-baseline",
1457
- "eval-schedule",
1458
- "training-job",
1459
- "checkpoint",
1460
- "training-provider",
1461
- "training-model",
1462
- "checkpoint-gateway",
1463
- "credential-provider-package",
1464
- "credential-consumer",
1465
- "credential-use",
1466
- "credential-event",
1467
- "gateway-package",
1468
- "rollout",
1469
- "wait"
1470
- ];
1471
- var CONSTAL_API_GET_KINDS = CONSTAL_API_QUERY_KINDS;
1472
- var CONSTAL_API_MODEL_TOOL_DESCRIPTIONS = {
1473
- 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.",
1474
- 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."
1475
- };
1476
- var CONSTAL_API_GET_CRN_KINDS = [
1477
- ...RESOURCE_KINDS,
1478
- "analytics",
1479
- "binding",
1480
- "session",
1481
- "run",
1482
- "deployment"
1483
- ];
1484
- var CONSTAL_API_OBJECT_REF_CRN_KINDS = [...CONSTAL_API_GET_CRN_KINDS, "customer"];
1485
- var boundedNameSchema = { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z][A-Za-z0-9._-]{0,127}$" };
1486
- var namespaceSchema = {
1487
- type: "string",
1488
- minLength: 1,
1489
- maxLength: 128,
1490
- pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
1491
- };
1492
- var actionSchema = { type: "string", pattern: ACTION_PATTERN.source };
1493
- var boundedIdSchema = { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9][A-Za-z0-9._~:-]{0,255}$" };
1494
- var hashSchema = { type: "string", pattern: "^[a-f0-9]{64}$" };
1495
- var stringListSchema = { type: "array", maxItems: 128, items: { type: "string", minLength: 1, maxLength: 256 } };
1496
- 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: [
1497
- {
1498
- type: "object",
1499
- required: ["kind", "namespace"],
1500
- additionalProperties: false,
1501
- properties: { kind: { const: "namespace" }, namespace: {
1502
- ...namespaceSchema,
1503
- description: "Exact authorized namespace. Do not infer it from an object name or repository."
1504
- } }
1505
- },
1506
- { type: "object", required: ["kind"], additionalProperties: false, properties: { kind: { const: "tenant" } } }
1507
- ] };
1508
- 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}$`;
1509
- var objectRefSchema = { type: "object", additionalProperties: false, properties: {
1510
- kind: { enum: [...CONSTAL_API_GET_KINDS], description: "Exact lower-case object kind returned by a governed platform result." },
1511
- id: { type: "string", minLength: 1, maxLength: 512 },
1512
- crn: { anyOf: [{ type: "null" }, {
1513
- type: "string",
1514
- minLength: 1,
1515
- maxLength: 2048,
1516
- pattern: crnPattern(CONSTAL_API_OBJECT_REF_CRN_KINDS)
1517
- }] },
1518
- hash: { anyOf: [{ type: "null" }, hashSchema] },
1519
- namespace: {
1520
- type: ["string", "null"],
1521
- maxLength: 128,
1522
- pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
1523
- },
1524
- version: { type: ["string", "null"], maxLength: 128 }
1525
- }, required: ["kind", "id", "namespace"] };
1526
- var exactGetCrnSchema = {
1527
- type: "string",
1528
- minLength: 1,
1529
- maxLength: 2048,
1530
- description: "Exact addressable CRN obtained from governed platform evidence.",
1531
- pattern: crnPattern(CONSTAL_API_GET_CRN_KINDS)
1532
- };
1533
- var CONSTAL_API_OPERATION_SCHEMAS = {
1534
- describe: { type: "object", additionalProperties: false, properties: {
1535
- domains: stringListSchema,
1536
- kinds: stringListSchema,
1537
- operations: stringListSchema,
1538
- include: {
1539
- type: "array",
1540
- maxItems: 5,
1541
- uniqueItems: true,
1542
- items: { enum: ["objects", "operations", "relations", "schemas", "docs"] }
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
+ }));
1543
2081
  },
1544
- cursor: { type: "string", maxLength: 4096 },
1545
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize }
1546
- } },
1547
- query: {
1548
- type: "object",
1549
- required: ["kind", "scope"],
1550
- additionalProperties: false,
1551
- 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.",
1552
- properties: {
1553
- kind: { enum: [...CONSTAL_API_QUERY_KINDS], description: "Exact queryable kind. Never guess a kind or change its casing." },
1554
- scope: scopeSchema,
1555
- filter: { type: "object", description: "Optional catalog-advertised filter expression." },
1556
- search: { type: "string", maxLength: 512 },
1557
- order: { type: "array", maxItems: 8, items: {
1558
- type: "object",
1559
- required: ["field", "direction"],
1560
- additionalProperties: false,
1561
- properties: { field: boundedNameSchema, direction: { enum: ["ascending", "descending"] } }
1562
- } },
1563
- fields: stringListSchema,
1564
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1565
- cursor: { type: "string", maxLength: 4096 },
1566
- asOf: { type: "integer", minimum: 0 },
1567
- range: { type: "object", required: ["start", "end"], additionalProperties: false, properties: {
1568
- start: { type: "integer", minimum: 0 },
1569
- end: { type: "integer", minimum: 0 }
1570
- } }
2082
+ async load(name) {
2083
+ if (!Object.hasOwn(values, name)) throw new TypeError(`Connection is not configured: ${name}`);
2084
+ return definition(values[name]);
1571
2085
  }
1572
- },
1573
- get: {
1574
- type: "object",
1575
- required: ["ref"],
1576
- additionalProperties: false,
1577
- description: "Read one addressable object using a complete ref returned by query, relations, runtime inspection, or a governed receipt. Do not synthesize refs.",
1578
- properties: {
1579
- ref: {
1580
- description: "Copy a complete object ref from governed output, or supply an exact supported CRN.",
1581
- anyOf: [objectRefSchema, {
1582
- type: "object",
1583
- required: ["crn"],
1584
- additionalProperties: false,
1585
- properties: { crn: exactGetCrnSchema, hash: hashSchema }
1586
- }]
1587
- },
1588
- fields: stringListSchema,
1589
- page: { type: "object", additionalProperties: false, properties: {
1590
- cursor: { type: "string", maxLength: 4096 },
1591
- limit: { type: "integer", minimum: 1, maximum: 500 }
1592
- } }
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);
1593
2105
  }
1594
- },
1595
- relations: { type: "object", required: ["start"], additionalProperties: false, properties: {
1596
- start: { anyOf: [objectRefSchema, {
1597
- type: "object",
1598
- required: ["crn"],
1599
- additionalProperties: false,
1600
- properties: { crn: { type: "string", minLength: 1, maxLength: 2048 }, hash: hashSchema }
1601
- }] },
1602
- direction: { enum: ["outgoing", "incoming", "both"] },
1603
- types: stringListSchema,
1604
- depth: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumRelationDepth },
1605
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1606
- cursor: { type: "string", maxLength: 4096 }
1607
- } },
1608
- explainPolicy: { type: "object", required: ["action", "resource"], additionalProperties: false, properties: {
1609
- principal: { anyOf: [
1610
- { type: "string", maxLength: 2048 },
1611
- { type: "object", required: ["roles", "scopes"], additionalProperties: false, properties: {
1612
- name: { type: "string", maxLength: 2048 },
1613
- roles: {
1614
- type: "array",
1615
- maxItems: 64,
1616
- uniqueItems: true,
1617
- items: { type: "string", minLength: 1, maxLength: 2048 }
1618
- },
1619
- scopes: {
1620
- type: "array",
1621
- maxItems: 256,
1622
- uniqueItems: true,
1623
- items: { type: "string", pattern: "^(?:\\*|[a-z][a-z0-9-]{0,63}:(?:[a-z][a-z0-9-]{0,63}|\\*))$" }
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");
1624
2178
  }
1625
- } }
1626
- ] },
1627
- action: actionSchema,
1628
- resource: { type: "string", minLength: 1, maxLength: 2048 },
1629
- context: { type: "object" },
1630
- arguments: {},
1631
- at: { type: "object", required: ["run"], additionalProperties: false, properties: {
1632
- run: {
1633
- type: "object",
1634
- required: ["namespace", "agent", "session", "run"],
1635
- additionalProperties: false,
1636
- properties: {
1637
- namespace: boundedNameSchema,
1638
- agent: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]{0,62}$" },
1639
- session: boundedIdSchema,
1640
- run: boundedIdSchema
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 });
1641
2199
  }
2200
+ return { ...await remember(ctx, selected, { state: "bound", installation, attachment }), resource: current };
1642
2201
  }
1643
- } }
1644
- } },
1645
- plan: { type: "object", required: ["objective", "operations"], additionalProperties: false, properties: {
1646
- objective: { type: "string", minLength: 1, maxLength: 8192 },
1647
- validateOnly: { type: "boolean" },
1648
- operations: {
1649
- type: "array",
1650
- minItems: 1,
1651
- maxItems: CONSTAL_API_BOUNDS.maximumPlanOperations,
1652
- items: { type: "object", required: ["operation", "input"], additionalProperties: false, properties: {
1653
- id: boundedIdSchema,
1654
- operation: boundedNameSchema,
1655
- target: { type: "string", maxLength: 2048 },
1656
- input: {},
1657
- expectedCurrentHash: { anyOf: [{ type: "null" }, hashSchema] },
1658
- dependsOn: { type: "array", maxItems: 64, items: boundedIdSchema }
1659
- } }
1660
- }
1661
- } },
1662
- apply: { type: "object", required: ["plan", "eventId"], additionalProperties: false, properties: {
1663
- plan: {
1664
- type: "object",
1665
- required: ["id", "hash"],
1666
- additionalProperties: false,
1667
- properties: { id: boundedIdSchema, hash: hashSchema }
1668
2202
  },
1669
- eventId: boundedIdSchema
1670
- } },
1671
- observe: { type: "object", required: ["id"], additionalProperties: false, properties: { id: boundedIdSchema } }
1672
- };
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
+ }
1673
2244
 
1674
- // src/policy-governance.ts
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
+ }
2255
+
2256
+ // packages/sdk/src/policy-governance.ts
1675
2257
  var SANDBOX_CONTRACT = {
1676
2258
  id: "constal.sandbox-pool",
1677
2259
  version: "1",
@@ -1745,1116 +2327,1426 @@ function validatePolicyGovernanceConstraint(value) {
1745
2327
  limit(value.contract, [value.meter], value);
1746
2328
  }
1747
2329
 
1748
- // src/authorization.ts
1749
- var MAX_CONSTRAINTS = 64;
1750
- var MAX_OUTCOME_BYTES = 65536;
1751
- var MAX_REASON_BYTES = 1024;
1752
- var DENIAL_CODE = /^[a-z][a-z0-9._-]{0,127}$/u;
1753
- var encoder4 = new TextEncoder();
1754
- function record4(value) {
1755
- 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;
1756
2343
  }
1757
- function requiredString2(value, path, maximum = 1024) {
1758
- if (typeof value !== "string" || value.length === 0 || encoder4.encode(value).byteLength > maximum) {
1759
- 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`);
1760
2347
  }
2348
+ return Number(value);
1761
2349
  }
1762
- function exactKeys2(value, allowed, required2, path) {
1763
- if (Object.keys(value).some((key) => !allowed.includes(key)) || required2.some((key) => !Object.hasOwn(value, key))) {
1764
- 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`);
1765
2353
  }
2354
+ return value;
1766
2355
  }
1767
- function scalar(value) {
1768
- 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;
1769
2362
  }
1770
- function validateGrant(grant, path) {
1771
- 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) {
1772
- 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");
1773
2368
  }
1774
- exactKeys2(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
1775
- grant.actions.forEach(actionPattern);
1776
- grant.resources.forEach(resourcePattern);
2369
+ return candidate;
1777
2370
  }
1778
- function validatePolicyConstraint(constraint, path = "constraint") {
1779
- if (!constraint || typeof constraint !== "object" || Array.isArray(constraint) || typeof constraint.kind !== "string") {
1780
- throw new TypeError(`${path} is invalid`);
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");
1781
2376
  }
1782
- const source = constraint;
1783
- if (constraint.kind === "resource-controls" || constraint.kind === "admission-limit") {
1784
- try {
1785
- validatePolicyGovernanceConstraint(constraint);
1786
- } catch (error) {
1787
- throw new TypeError(`${path} is invalid: ${error instanceof Error ? error.message : String(error)}`);
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");
1788
2382
  }
1789
- return;
1790
- }
1791
- if (constraint.kind === "arguments") {
1792
- exactKeys2(source, ["kind", "schema"], ["kind", "schema"], path);
1793
- if (!record4(constraint.schema) || validateJsonSchemaDefinition(constraint.schema)) throw new TypeError(`${path}.schema is invalid`);
1794
- 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");
1795
2387
  }
1796
- if (constraint.kind === "context") {
1797
- exactKeys2(source, ["kind", "equals"], ["kind", "equals"], path);
1798
- 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))) {
1799
- throw new TypeError(`${path}.equals is invalid`);
1800
- }
1801
- 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`);
1802
2399
  }
1803
- if (constraint.kind === "credential-binding") {
1804
- exactKeys2(source, ["kind", "source", "consumer"], ["kind", "source", "consumer"], path);
1805
- credentialName(constraint.source);
1806
- parseResourceName(constraint.consumer);
1807
- return;
2400
+ return candidate;
2401
+ }
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`);
1808
2406
  }
1809
- throw new TypeError(`${path}.kind is invalid`);
2407
+ return candidate;
1810
2408
  }
1811
- function validateConstraints(value, path, required2) {
1812
- if (value === void 0 && !required2) return [];
1813
- if (!Array.isArray(value) || required2 && value.length === 0 || value.length > MAX_CONSTRAINTS) {
1814
- throw new TypeError(`${path} is invalid`);
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;
2452
+ }
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");
1815
2457
  }
1816
- value.forEach((constraint, index) => validatePolicyConstraint(constraint, `${path}[${index}]`));
1817
- return value;
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
+ };
1818
2465
  }
1819
- function policyOutcome(value) {
1820
- if (!record4(value) || typeof value.kind !== "string") throw new TypeError("Policy outcome is invalid");
1821
- if (value.kind === "allow") exactKeys2(value, ["kind"], ["kind"], "Policy allow outcome");
1822
- else if (value.kind === "deny") {
1823
- exactKeys2(value, ["kind", "code", "reason"], ["kind", "code"], "Policy deny outcome");
1824
- if (typeof value.code !== "string" || !DENIAL_CODE.test(value.code)) throw new TypeError("Policy denial code is invalid");
1825
- if (value.reason !== void 0) requiredString2(value.reason, "Policy denial reason", MAX_REASON_BYTES);
1826
- } else if (value.kind === "constrain") {
1827
- exactKeys2(value, ["kind", "constraints"], ["kind", "constraints"], "Policy constrain outcome");
1828
- validateConstraints(value.constraints, "Policy constraints", true);
1829
- } else if (value.kind === "substitute") {
1830
- exactKeys2(value, ["kind", "value", "constraints"], ["kind", "value"], "Policy substitute outcome");
1831
- canonicalJson(value.value);
1832
- validateConstraints(value.constraints, "Policy constraints", false);
1833
- } else if (value.kind === "require-approval") {
1834
- exactKeys2(value, ["kind", "reason", "constraints"], ["kind"], "Policy approval outcome");
1835
- if (value.reason !== void 0) requiredString2(value.reason, "Policy approval reason", MAX_REASON_BYTES);
1836
- validateConstraints(value.constraints, "Policy constraints", false);
1837
- } else if (value.kind === "grant") {
1838
- exactKeys2(value, ["kind", "grant"], ["kind", "grant"], "Policy grant outcome");
1839
- validateGrant(value.grant, "Policy grant");
1840
- } else throw new TypeError("Policy outcome kind is invalid");
1841
- if (encoder4.encode(canonicalJson(value)).byteLength > MAX_OUTCOME_BYTES) throw new TypeError("Policy outcome is oversized");
1842
- return value;
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) };
1843
2473
  }
1844
2474
 
1845
- // src/policy.ts
1846
- var ID2 = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1847
- var VERSION3 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
1848
- function policy(definition) {
1849
- 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");
1850
- return Object.freeze(definition);
2475
+ // packages/sdk/src/model.ts
2476
+ var MODEL_COMPLETION_CAPABILITY = {
2477
+ id: "constal.model-completion",
2478
+ version: "1",
2479
+ hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
2480
+ };
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");
2520
+ }
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`);
2523
+ }
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");
2526
+ }
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;
1851
2531
  }
1852
- async function evaluatePolicyDefinition(definition, input) {
1853
- return policyOutcome(await definition.evaluate(input));
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
+ };
1854
2542
  }
1855
-
1856
- // src/table.ts
1857
- var identifier = { type: "string", pattern: "^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$", maxLength: 128 };
1858
- var tableName = { type: "string", pattern: "^[a-z0-9][a-z0-9._-]{0,127}$", maxLength: 128 };
1859
- var branchName = { type: "string", pattern: "^[a-z0-9][a-z0-9._/-]{0,127}$", maxLength: 128 };
1860
- var hash2 = { type: "string", pattern: "^[a-f0-9]{64}$" };
1861
- var scalar2 = { type: ["string", "number", "integer", "boolean", "null"], maxLength: 4096 };
1862
- var TABLE_DESCRIBE_SCHEMA = {
1863
- type: "object",
1864
- required: ["table"],
1865
- additionalProperties: false,
1866
- properties: {
1867
- table: tableName,
1868
- branch: branchName,
1869
- snapshot: hash2,
1870
- stageId: hash2,
1871
- waitMs: { type: "integer", minimum: 0, maximum: 25e3 }
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");
1872
2547
  }
1873
- };
1874
- var filterSchema = {
1875
- type: "object",
1876
- required: ["field", "op", "value"],
1877
- additionalProperties: false,
1878
- properties: {
1879
- field: identifier,
1880
- op: { type: "string", enum: ["eq", "ne", "gt", "gte", "lt", "lte", "in", "between"] },
1881
- value: { anyOf: [scalar2, { type: "array", minItems: 1, maxItems: 100, items: scalar2 }] }
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");
1882
2550
  }
1883
- };
1884
- var TABLE_QUERY_SCHEMA = {
1885
- type: "object",
1886
- required: ["table", "snapshot", "query"],
1887
- additionalProperties: false,
1888
- properties: {
1889
- table: tableName,
1890
- branch: branchName,
1891
- snapshot: hash2,
1892
- query: {
1893
- type: "object",
1894
- additionalProperties: false,
1895
- properties: {
1896
- select: { type: "array", maxItems: 64, uniqueItems: true, items: identifier },
1897
- where: { type: "array", maxItems: 32, items: filterSchema },
1898
- groupBy: { type: "array", maxItems: 16, uniqueItems: true, items: identifier },
1899
- aggregates: { type: "array", maxItems: 32, items: {
1900
- type: "object",
1901
- required: ["fn", "as"],
1902
- additionalProperties: false,
1903
- properties: {
1904
- fn: { type: "string", enum: ["count", "sum", "avg", "min", "max"] },
1905
- field: identifier,
1906
- as: identifier
1907
- }
1908
- } },
1909
- orderBy: { type: "array", maxItems: 8, items: {
1910
- type: "object",
1911
- required: ["field", "direction"],
1912
- additionalProperties: false,
1913
- properties: { field: identifier, direction: { type: "string", enum: ["asc", "desc"] } }
1914
- } },
1915
- limit: { type: "integer", minimum: 1, maximum: 1e3 }
1916
- }
1917
- }
2551
+ if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2552
+ throw new TypeError("effort must be a nonempty model-supported string");
1918
2553
  }
1919
- };
1920
- function validateStageOutputSpec(value, path = "$.output") {
1921
- if (!value || typeof value !== "object" || Array.isArray(value)) return `${path} must be an object`;
1922
- const output = value;
1923
- const extra = Object.keys(output).find((key) => key !== "schema" && key !== "sortOrder");
1924
- if (extra) return `${path}.${extra} is not allowed`;
1925
- if (!Object.hasOwn(output, "schema")) return `${path}.schema is required`;
1926
- const schemaError = validateJsonSchemaDefinition(output.schema, `${path}.schema`);
1927
- if (schemaError) return schemaError;
1928
- const sortOrder = output.sortOrder ?? [];
1929
- if (!Array.isArray(sortOrder) || sortOrder.length > 64) return `${path}.sortOrder is invalid`;
1930
- const keys = /* @__PURE__ */ new Set();
1931
- for (const [index, raw] of sortOrder.entries()) {
1932
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${path}.sortOrder[${index}] is invalid`;
1933
- const field2 = raw;
1934
- 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)) {
1935
- return `${path}.sortOrder[${index}] is invalid`;
1936
- }
1937
- keys.add(field2.key);
2554
+ return {
2555
+ ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2556
+ ...temperature === void 0 ? {} : { temperature },
2557
+ ...effort === void 0 ? {} : { effort },
2558
+ ...providerOptions === void 0 ? {} : { providerOptions: modelProviderOptions(providerOptions) }
2559
+ };
2560
+ }
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;
2566
+ }
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");
1938
2577
  }
1939
- return 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");
2582
+ }
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");
2594
+ }
2595
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2596
+ throw new TypeError("gateway and provider credentials cannot share one slot");
2597
+ }
2598
+ modelGatewayEndpoint(normalized);
2599
+ return normalized;
1940
2600
  }
1941
- function stageOutput(value) {
1942
- const error = validateStageOutputSpec(value);
1943
- if (error) throw new TypeError(error);
1944
- return value;
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");
2607
+ }
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");
2610
+ }
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");
2614
+ }
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;
1945
2619
  }
1946
- var tableDescribe = {
1947
- name: "table_describe",
1948
- version: "1",
1949
- description: "Inspect the schema and identity of one exact, queryable Table snapshot before querying it.",
1950
- schema: TABLE_DESCRIBE_SCHEMA,
1951
- maxEffect: "read-only",
1952
- needs: [{ binding: "table_catalog", kind: "service", ops: ["describe"] }],
1953
- async run(args, ctx) {
1954
- return ctx.invoke(ctx.resources.table_catalog, "describe", args);
2620
+ function modelPrompt(args) {
2621
+ return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2622
+ }
2623
+ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2624
+ const { effort } = modelGenerationOptions(args);
2625
+ if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
2626
+ throw new TypeError("model Tool choice is invalid");
1955
2627
  }
1956
- };
1957
- var tableQuery = {
1958
- name: "table_query",
1959
- version: "1",
1960
- description: "Query one exact Table snapshot with bounded fields, filters, grouping, aggregates, ordering, and limit.",
1961
- schema: TABLE_QUERY_SCHEMA,
1962
- maxEffect: "read-only",
1963
- needs: [{ binding: "table_catalog", kind: "service", ops: ["query"] }],
1964
- async run(args, ctx) {
1965
- return ctx.invoke(ctx.resources.table_catalog, "query", args);
2628
+ if (args.toolChoice === "required" && !args.tools?.length) {
2629
+ throw new TypeError("required model Tool choice needs at least one offered Tool");
1966
2630
  }
1967
- };
1968
-
1969
- // src/tools.ts
1970
- var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
1971
- var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
1972
- function opTool(binding, op, override = {}) {
1973
- if (!NAME3.test(binding) || !OPERATION2.test(op)) throw new TypeError("opTool binding or operation is invalid");
1974
- const name = override.name ?? op.replaceAll(".", "_");
2631
+ const prompt = modelPrompt(args);
2632
+ if (protocol === "anthropic") return applyModelProviderOptions({
2633
+ model,
2634
+ system: args.system ?? "",
2635
+ messages: [{ role: "user", content: prompt }],
2636
+ max_tokens: maxOutputTokens,
2637
+ ...effort === void 0 ? {} : { output_config: { effort } },
2638
+ ...temperature === null ? {} : { temperature },
2639
+ ...args.tools?.length ? { tools: args.tools.map((tool2) => ({ name: tool2.name, description: tool2.description, input_schema: tool2.schema })) } : {},
2640
+ ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
2641
+ }, args.providerOptions);
2642
+ if (protocol === "openai") return applyModelProviderOptions({
2643
+ model,
2644
+ messages: [
2645
+ ...args.system ? [{ role: "developer", content: args.system }] : [],
2646
+ { role: "user", content: prompt }
2647
+ ],
2648
+ max_completion_tokens: maxOutputTokens,
2649
+ ...effort === void 0 ? {} : { reasoning_effort: effort },
2650
+ ...temperature === null ? {} : { temperature },
2651
+ ...args.tools?.length ? { tools: args.tools.map((tool2) => ({
2652
+ type: "function",
2653
+ function: { name: tool2.name, description: tool2.description, parameters: tool2.schema }
2654
+ })) } : {},
2655
+ ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
2656
+ }, args.providerOptions);
2657
+ throw new TypeError("model gateway protocol is invalid");
2658
+ }
2659
+ function integer2(value) {
2660
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
2661
+ }
2662
+ function costMetadata(usage) {
2663
+ const cost = usage.cost;
2664
+ const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
1975
2665
  return {
1976
- name,
1977
- version: "catalog",
1978
- description: override.description ?? `Invoke ${op} on the bound ${binding} resource.`,
1979
- schema: override.schema ?? { type: "object", additionalProperties: false },
1980
- maxEffect: "read-only",
1981
- needs: [],
1982
- ...override.tier ? { tier: override.tier } : {},
1983
- ...override.once ? { once: override.once } : {},
1984
- ...override.guard ? { guard: override.guard } : {},
1985
- ...override.preview ? { preview: override.preview } : {},
1986
- catalog: { binding, op },
1987
- async run() {
1988
- throw new TypeError(`catalog Tool ${binding}#${op} was not resolved by deployment`);
1989
- }
2666
+ ...costUsd !== void 0 ? { costUsd } : {},
2667
+ ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
2668
+ ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
1990
2669
  };
1991
2670
  }
1992
- function opTools(binding, ops = []) {
1993
- if (ops.length === 0) throw new TypeError("opTools requires pinned operation names at bundle construction");
1994
- return ops.map((op) => opTool(binding, op));
2671
+ function modelProtocolResult(protocol, raw, provider, model) {
2672
+ const source = record6(raw) ?? {};
2673
+ const toolCalls = [];
2674
+ let content2 = "";
2675
+ let usage;
2676
+ if (protocol === "anthropic") {
2677
+ const blocks = Array.isArray(source.content) ? source.content : [];
2678
+ content2 = blocks.map((candidate) => {
2679
+ const block = record6(candidate);
2680
+ if (block?.type === "text" && typeof block.text === "string") return block.text;
2681
+ if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
2682
+ toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
2683
+ }
2684
+ return "";
2685
+ }).join("");
2686
+ const values = record6(source.usage) ?? {};
2687
+ const cached = integer2(values.cache_read_input_tokens);
2688
+ usage = {
2689
+ input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
2690
+ output: integer2(values.output_tokens),
2691
+ cached,
2692
+ ...costMetadata(values)
2693
+ };
2694
+ } else if (protocol === "openai") {
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);
2701
+ if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
2702
+ let args;
2703
+ try {
2704
+ args = JSON.parse(fn.arguments);
2705
+ } catch {
2706
+ throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
2707
+ }
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) };
1995
2720
  }
1996
- var WEB_FETCH_ARGUMENT_SCHEMA = {
1997
- type: "object",
1998
- required: ["url"],
1999
- additionalProperties: false,
2000
- properties: {
2001
- url: { type: "string", minLength: 1, maxLength: 2048 },
2002
- accept: { type: "string", maxLength: 256 }
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`);
2003
2745
  }
2004
- };
2005
- var WEB_SEARCH_ARGUMENT_SCHEMA = {
2006
- type: "object",
2007
- required: ["query"],
2008
- additionalProperties: false,
2009
- properties: {
2010
- query: {
2011
- type: "string",
2012
- minLength: 1,
2013
- maxLength: 4096,
2014
- description: "A self-contained description of the information to find."
2015
- },
2016
- searchQueries: {
2017
- type: "array",
2018
- minItems: 1,
2019
- maxItems: 3,
2020
- uniqueItems: true,
2021
- description: "Optional concise keyword queries that narrow the search.",
2022
- items: { type: "string", minLength: 1, maxLength: 256 }
2023
- },
2024
- maximumResults: {
2025
- type: "integer",
2026
- minimum: 1,
2027
- maximum: 20,
2028
- description: "Maximum number of sources to return."
2029
- },
2030
- maximumCharacters: {
2031
- type: "integer",
2032
- minimum: 1e3,
2033
- maximum: 6e4,
2034
- description: "Maximum total excerpt characters to return."
2035
- },
2036
- includeDomains: {
2037
- type: "array",
2038
- maxItems: 50,
2039
- uniqueItems: true,
2040
- description: "Optional domains to restrict results to.",
2041
- items: { type: "string", minLength: 1, maxLength: 253 }
2042
- },
2043
- excludeDomains: {
2044
- type: "array",
2045
- maxItems: 50,
2046
- uniqueItems: true,
2047
- description: "Optional domains to omit.",
2048
- items: { type: "string", minLength: 1, maxLength: 253 }
2049
- },
2050
- afterDate: {
2051
- type: "string",
2052
- pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
2053
- description: "Optional earliest publication date in YYYY-MM-DD form."
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");
2054
2757
  }
2758
+ httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
2759
+ output[slot] = item;
2055
2760
  }
2056
- };
2057
- var webFetch = opTool("web", "get", {
2058
- name: "web_fetch",
2059
- description: "Fetch an HTTPS resource through the bound governed web Resource.",
2060
- schema: WEB_FETCH_ARGUMENT_SCHEMA
2061
- });
2062
- var webSearch = opTool("search", "search", {
2063
- name: "web_search",
2064
- description: "Search the public web through the bound governed search Resource.",
2065
- schema: WEB_SEARCH_ARGUMENT_SCHEMA
2066
- });
2067
- var casTool = {
2068
- name: "cas",
2069
- version: "1",
2070
- description: "Store or load one content-addressed Agent artifact.",
2071
- schema: {
2072
- type: "object",
2073
- required: ["action"],
2074
- additionalProperties: false,
2075
- properties: {
2076
- action: { type: "string", enum: ["put", "get"] },
2077
- value: {},
2078
- ref: { type: "string", pattern: "^[a-f0-9]{64}$" }
2079
- }
2080
- },
2081
- maxEffect: "idempotent",
2082
- needs: [{ binding: "cas", kind: "cas", ops: ["put", "get"] }],
2083
- async run(args, ctx) {
2084
- const input = args && typeof args === "object" && !Array.isArray(args) ? args : {};
2085
- if (input.action === "put") {
2086
- if (!Object.hasOwn(input, "value")) throw new TypeError("cas put requires value");
2087
- return ctx.invoke(ctx.resources.cas, "put", { value: input.value });
2088
- }
2089
- if (input.action === "get") {
2090
- if (typeof input.ref !== "string") throw new TypeError("cas get requires ref");
2091
- return ctx.invoke(ctx.resources.cas, "get", { ref: input.ref });
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");
2092
2770
  }
2093
- throw new TypeError("cas action must be put or get");
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");
2094
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 }
2095
2836
  };
2096
-
2097
- // src/memory.ts
2098
- var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 };
2099
- var content = { type: "string", minLength: 1, maxLength: 65536 };
2100
- var metadata = { type: "object", maxProperties: 64 };
2101
- var scope = { type: "string", pattern: "^[a-f0-9]{64}$", maxLength: 64 };
2102
- var record5 = {
2837
+ var GATEWAY_MODEL_OFFER_SCHEMA = {
2103
2838
  type: "object",
2104
- required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
2105
2839
  additionalProperties: false,
2840
+ required: ["id", "displayName", "contextTokens", "maxOutputTokens", "pricing"],
2106
2841
  properties: {
2107
- id,
2108
- content,
2109
- metadata,
2110
- createdAt: { type: "integer", minimum: 0 },
2111
- updatedAt: { type: "integer", minimum: 0 },
2112
- expiresAt: { anyOf: [{ type: "integer", minimum: 0 }, { type: "null" }] }
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"] }
2113
2849
  }
2114
2850
  };
2115
- var MEMORY_OPERATION_DECLARATIONS = [
2116
- {
2117
- op: "remember",
2118
- description: "Persist or replace one record in the invocation's authenticated Memory partition.",
2119
- schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata, scope } },
2120
- resultSchema: record5,
2121
- effect: "idempotent",
2122
- recovery: { kind: "idempotency-key" },
2123
- async: false,
2124
- usage: { meter: "none", priceTable: null }
2125
- },
2126
- {
2127
- op: "search",
2128
- description: "Retrieve relevant records from the invocation's authenticated Memory partition.",
2129
- schema: {
2130
- type: "object",
2131
- required: ["query"],
2132
- additionalProperties: false,
2133
- properties: { query: { type: "string", minLength: 1, maxLength: 8192 }, limit: { type: "integer", minimum: 1, maximum: 100 }, scope }
2134
- },
2135
- resultSchema: {
2136
- type: "object",
2137
- required: ["hits"],
2138
- additionalProperties: false,
2139
- properties: { hits: { type: "array", maxItems: 100, items: {
2140
- ...record5,
2141
- required: [...record5.required, "score"],
2142
- properties: { ...record5.properties, score: { type: "number", minimum: 0, maximum: 1 } }
2143
- } } }
2144
- },
2145
- effect: "read-only",
2146
- recovery: { kind: "repeat" },
2147
- async: false,
2148
- usage: { meter: "none", priceTable: null }
2149
- },
2150
- {
2151
- op: "get",
2152
- description: "Read one record from the invocation's authenticated Memory partition.",
2153
- schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2154
- resultSchema: { anyOf: [record5, { type: "null" }] },
2155
- effect: "read-only",
2156
- recovery: { kind: "repeat" },
2157
- async: false,
2158
- usage: { meter: "none", priceTable: null }
2159
- },
2160
- {
2161
- op: "delete",
2162
- description: "Delete one record from the invocation's authenticated Memory partition.",
2163
- schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2164
- resultSchema: { type: "object", required: ["deleted"], additionalProperties: false, properties: { deleted: { type: "boolean" } } },
2165
- effect: "idempotent",
2166
- recovery: { kind: "idempotency-key" },
2167
- async: false,
2168
- usage: { meter: "none", priceTable: null }
2169
- },
2170
- {
2171
- op: "purge",
2172
- description: "Delete every record in the invocation's authenticated Memory partition.",
2173
- schema: { type: "object", additionalProperties: false, properties: {} },
2174
- resultSchema: {
2175
- type: "object",
2176
- required: ["deleted"],
2177
- additionalProperties: false,
2178
- properties: { deleted: { type: "integer", minimum: 0 } }
2179
- },
2180
- effect: "idempotent",
2181
- recovery: { kind: "idempotency-key" },
2182
- async: false,
2183
- usage: { meter: "none", priceTable: null }
2184
- }
2185
- ];
2186
-
2187
- // src/integration.ts
2188
- var ApiError = class extends Error {
2189
- constructor(status, body, disposition = "uncertain") {
2190
- super(`${status}: ${body}`);
2191
- this.status = status;
2192
- this.body = body;
2193
- this.disposition = disposition;
2194
- this.name = "ApiError";
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");
2195
2855
  }
2196
- status;
2197
- body;
2198
- disposition;
2199
- };
2200
- var IntegrationRequestNotSent = class extends Error {
2201
- constructor(message = "integration request was not sent") {
2202
- super(message);
2203
- this.name = "IntegrationRequestNotSent";
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");
2204
2873
  }
2205
- };
2206
- var TerminalIntegrationFailure = class extends Error {
2207
- constructor(message = "integration operation failed terminally") {
2208
- super(message);
2209
- this.name = "TerminalIntegrationFailure";
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);
2210
2879
  }
2211
- };
2212
- var OPERATION3 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
2213
- function integrationEgressPolicy(value) {
2880
+ }
2881
+ function gatewayPackageMetadata(value) {
2214
2882
  const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2215
- if (!source || !Array.isArray(source.rules) || source.rules.length > 128 || Object.keys(source).some((key) => key !== "rules")) {
2216
- throw new TypeError("integration egress policy is invalid");
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");
2217
2885
  }
2218
- const rules = source.rules.map((raw) => {
2219
- const rule = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2220
- const paths = Number(rule?.pathPrefix !== void 0) + Number(rule?.pathExact !== void 0);
2221
- 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))) {
2222
- throw new TypeError("integration egress rule is invalid");
2223
- }
2224
- let origin;
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;
2225
2929
  try {
2226
- origin = new URL(rule.origin);
2930
+ endpoint = new URL(String(config[binding.urlProperty] ?? ""));
2227
2931
  } catch {
2228
- throw new TypeError("integration egress origin is invalid");
2932
+ throw new TypeError(`Gateway ${binding.urlProperty} must be an HTTPS endpoint`);
2229
2933
  }
2230
- if (origin.protocol !== "https:" || origin.origin !== rule.origin || origin.username || origin.password) {
2231
- throw new TypeError("integration egress origin is invalid");
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`);
2232
2936
  }
2233
- const path = String(rule.pathPrefix ?? rule.pathExact);
2234
- if (!path.startsWith("/") || path.includes("?") || path.includes("#")) throw new TypeError("integration egress path is invalid");
2235
- return rule;
2937
+ return { operations: binding.operations, origin: endpoint.origin, pathExact: endpoint.pathname, methods: binding.methods };
2236
2938
  });
2237
- return { rules };
2238
- }
2239
-
2240
- // src/training.ts
2241
- var HASH2 = /^[a-f0-9]{64}$/u;
2242
- var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
2243
- var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2244
- var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2245
- var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
2246
- var TRAINING_PROVIDER_CAPABILITY = {
2247
- id: "constal.training-provider",
2248
- version: "1",
2249
- hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
2250
- };
2251
- function record6(value) {
2252
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2939
+ return integrationEgressPolicy({ rules: [...metadata2.egress.rules, ...derived] });
2253
2940
  }
2254
- function integer(value, field2, minimum, maximum) {
2255
- if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum) {
2256
- throw new TypeError(`${field2} is invalid`);
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");
2257
2944
  }
2258
- return Number(value);
2259
- }
2260
- function finite(value, field2, minimum, maximum) {
2261
- if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum) {
2262
- throw new TypeError(`${field2} is invalid`);
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
+ }
2263
2973
  }
2264
- return value;
2265
- }
2266
- function providerPin(value) {
2267
- const candidate = record6(value);
2268
- 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");
2269
- const parts = parseResourceName(candidate.crn);
2270
- if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
2271
- return candidate;
2272
- }
2273
- function resumePoint(value) {
2274
- if (value === null) return null;
2275
- const candidate = record6(value);
2276
- 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))) {
2277
- throw new TypeError("training resume point is invalid");
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");
2278
2982
  }
2279
- return candidate;
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);
2280
2995
  }
2281
- function trainingProviderMetadata(value) {
2282
- const candidate = record6(value);
2283
- const checkpoints = record6(candidate?.checkpoints);
2284
- 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))) {
2285
- throw new TypeError("Training Provider metadata is invalid");
2286
- }
2287
- const models = candidate.models.map((raw) => {
2288
- const model = record6(raw);
2289
- const pricing = record6(model?.pricing);
2290
- 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))) {
2291
- throw new TypeError("Training Provider model offer is invalid");
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;
2292
3008
  }
2293
- return raw;
2294
3009
  });
2295
- if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
2296
- throw new TypeError("Training Provider model offers must be unique");
2297
- }
2298
- return {
2299
- lifecycleVersion: 1,
2300
- methods: candidate.methods,
2301
- models,
2302
- checkpoints
2303
- };
2304
- }
2305
- function datasetRef(value, field2) {
2306
- const candidate = record6(value);
2307
- 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))) {
2308
- throw new TypeError(`${field2} is invalid`);
2309
- }
2310
- return candidate;
2311
- }
2312
- function scorerRef(value, field2) {
2313
- const candidate = record6(value);
2314
- 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))) {
2315
- throw new TypeError(`${field2} is invalid`);
2316
- }
2317
- return candidate;
2318
- }
2319
- function trainingRecipe(value) {
2320
- const candidate = record6(value);
2321
- const allowed = [
2322
- "method",
2323
- "baseModel",
2324
- "dataset",
2325
- "validationDataset",
2326
- "scorers",
2327
- "loraRank",
2328
- "learningRate",
2329
- "epochs",
2330
- "batchSize",
2331
- "groupSize",
2332
- "temperature",
2333
- "seed",
2334
- "checkpointEvery",
2335
- "evalEvery",
2336
- "maxTrainTokens",
2337
- "maxSampleTokens",
2338
- "budgetMicroUsd"
2339
- ];
2340
- 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");
2341
- const recipe = {
2342
- method: candidate.method,
2343
- baseModel: candidate.baseModel,
2344
- dataset: datasetRef(candidate.dataset, "training dataset"),
2345
- validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
2346
- scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
2347
- loraRank: integer(candidate.loraRank, "LoRA rank", 1, 256),
2348
- learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE, 1),
2349
- epochs: integer(candidate.epochs, "epochs", 1, 100),
2350
- batchSize: integer(candidate.batchSize, "batch size", 1, 256),
2351
- groupSize: integer(candidate.groupSize, "group size", 1, 32),
2352
- temperature: finite(candidate.temperature, "temperature", 0, 2),
2353
- seed: integer(candidate.seed, "seed", 0, 2147483647),
2354
- checkpointEvery: integer(candidate.checkpointEvery, "checkpoint interval", 1, 1e6),
2355
- evalEvery: integer(candidate.evalEvery, "evaluation interval", 1, 1e6),
2356
- maxTrainTokens: integer(candidate.maxTrainTokens, "training token limit", 1, 1e10),
2357
- maxSampleTokens: integer(candidate.maxSampleTokens, "sample token limit", 1, 1e9),
2358
- budgetMicroUsd: integer(candidate.budgetMicroUsd, "training budget", 1, 1e10)
2359
- };
2360
- if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
2361
- return recipe;
2362
- }
2363
- function startTrainingRequest(value) {
2364
- const candidate = record6(value);
2365
- 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))) {
2366
- throw new TypeError("training request is invalid");
2367
- }
2368
- return {
2369
- ...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
2370
- ...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
2371
- ...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
2372
- recipe: trainingRecipe(candidate.recipe),
2373
- outputModelId: candidate.outputModelId
2374
- };
2375
3010
  }
2376
- function renderTrainingCompletion(input, expected) {
2377
- const text2 = (value) => typeof value === "string" ? value : canonicalJson(value);
2378
- return { prompt: `Input:
2379
- ${text2(input)}
2380
-
2381
- Response:
2382
- `, completion: expected === void 0 || expected === null ? null : text2(expected) };
2383
- }
2384
-
2385
- // src/model.ts
2386
- var MODEL_COMPLETION_CAPABILITY = {
2387
- id: "constal.model-completion",
3011
+ var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
3012
+ id: "constal.model-checkpoint-import",
2388
3013
  version: "1",
2389
- hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
3014
+ hash: "49563823899586a87dcee82e9db969af5f2f5364adb3eb808a19e86b862e87ba"
2390
3015
  };
2391
- function modelGenerationOptions(source) {
2392
- const { maxOutputTokens, temperature, effort } = source;
2393
- if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 1048576)) {
2394
- throw new TypeError("maxOutputTokens must be an integer from 1 to 1048576");
2395
- }
2396
- if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2397
- throw new TypeError("temperature must be a finite number from 0 to 2");
2398
- }
2399
- if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2400
- throw new TypeError("effort must be a nonempty model-supported string");
2401
- }
2402
- return {
2403
- ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2404
- ...temperature === void 0 ? {} : { temperature },
2405
- ...effort === void 0 ? {} : { effort }
2406
- };
2407
- }
2408
- var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2409
- var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2410
- var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2411
- function record7(value) {
2412
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2413
- }
2414
- function credentialHeader(value, name) {
2415
- if (value === null || value === void 0) return null;
2416
- const source = record7(value);
2417
- if (!source || typeof source.slot !== "string" || !NAME4.test(source.slot) || typeof source.header !== "string" || !HEADER.test(source.header.toLowerCase()) || RESERVED_HEADERS.has(source.header.toLowerCase()) || source.header.toLowerCase().startsWith("cf-") || source.scheme !== "bearer" && source.scheme !== "raw") throw new TypeError(`${name} is invalid`);
2418
- return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2419
- }
2420
- function normalizeModelGatewayConfig(value) {
2421
- const source = record7(value);
2422
- if (!source || typeof source.baseUrl !== "string" || source.baseUrl.length > 2048 || source.protocol !== "anthropic" && source.protocol !== "openai" || typeof source.model !== "string" || source.model.length === 0 || source.model.length > 256) {
2423
- throw new TypeError("model gateway config is invalid");
2424
- }
2425
- const maxOutputTokens = source.maxOutputTokens === void 0 ? 256 : Number(source.maxOutputTokens);
2426
- const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2427
- if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 8192 || temperature !== null && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2428
- throw new TypeError("model gateway generation limits are invalid");
2429
- }
2430
- const normalized = {
2431
- baseUrl: source.baseUrl,
2432
- protocol: source.protocol,
2433
- model: source.model,
2434
- maxOutputTokens,
2435
- temperature,
2436
- gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2437
- providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2438
- };
2439
- if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2440
- throw new TypeError("gateway and provider credentials cannot share one header");
2441
- }
2442
- if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2443
- throw new TypeError("gateway and provider credentials cannot share one slot");
2444
- }
2445
- modelGatewayEndpoint(normalized);
2446
- return normalized;
2447
- }
2448
- function modelGatewayEndpoint(config) {
2449
- let endpoint;
2450
- try {
2451
- endpoint = new URL(config.baseUrl);
2452
- } catch {
2453
- throw new TypeError("model gateway baseUrl is invalid");
2454
- }
2455
- if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2456
- throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
2457
- }
2458
- const hostname = endpoint.hostname.toLowerCase();
2459
- if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2460
- throw new TypeError("model gateway baseUrl must use a public hostname");
2461
- }
2462
- const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2463
- if (!suffix) throw new TypeError("model gateway protocol is invalid");
2464
- endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2465
- return endpoint;
2466
- }
2467
- function modelPrompt(args) {
2468
- return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2469
- }
2470
- function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2471
- const { effort } = modelGenerationOptions(args);
2472
- if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
2473
- throw new TypeError("model Tool choice is invalid");
2474
- }
2475
- if (args.toolChoice === "required" && !args.tools?.length) {
2476
- throw new TypeError("required model Tool choice needs at least one offered Tool");
2477
- }
2478
- const prompt = modelPrompt(args);
2479
- if (protocol === "anthropic") return {
2480
- model,
2481
- system: args.system ?? "",
2482
- messages: [{ role: "user", content: prompt }],
2483
- max_tokens: maxOutputTokens,
2484
- ...effort === void 0 ? {} : { output_config: { effort } },
2485
- ...temperature === null ? {} : { temperature },
2486
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
2487
- ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
2488
- };
2489
- if (protocol === "openai") return {
2490
- model,
2491
- messages: [
2492
- ...args.system ? [{ role: "developer", content: args.system }] : [],
2493
- { role: "user", content: prompt }
2494
- ],
2495
- max_completion_tokens: maxOutputTokens,
2496
- ...effort === void 0 ? {} : { reasoning_effort: effort },
2497
- ...temperature === null ? {} : { temperature },
2498
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({
2499
- type: "function",
2500
- function: { name: tool.name, description: tool.description, parameters: tool.schema }
2501
- })) } : {},
2502
- ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
2503
- };
2504
- throw new TypeError("model gateway protocol is invalid");
2505
- }
2506
- function integer2(value) {
2507
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
2508
- }
2509
- function costMetadata(usage) {
2510
- const cost = usage.cost;
2511
- const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
2512
- return {
2513
- ...costUsd !== void 0 ? { costUsd } : {},
2514
- ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
2515
- ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
2516
- };
2517
- }
2518
- function modelProtocolResult(protocol, raw, provider, model) {
2519
- const source = record7(raw) ?? {};
2520
- const toolCalls = [];
2521
- let content2 = "";
2522
- let usage;
2523
- if (protocol === "anthropic") {
2524
- const blocks = Array.isArray(source.content) ? source.content : [];
2525
- content2 = blocks.map((candidate) => {
2526
- const block = record7(candidate);
2527
- if (block?.type === "text" && typeof block.text === "string") return block.text;
2528
- if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
2529
- toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
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 }
2530
3163
  }
2531
- return "";
2532
- }).join("");
2533
- const values = record7(source.usage) ?? {};
2534
- const cached = integer2(values.cache_read_input_tokens);
2535
- usage = {
2536
- input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
2537
- output: integer2(values.output_tokens),
2538
- cached,
2539
- ...costMetadata(values)
2540
- };
2541
- } else if (protocol === "openai") {
2542
- const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2543
- const message = record7(choice.message) ?? {};
2544
- content2 = typeof message.content === "string" ? message.content : "";
2545
- for (const candidate of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
2546
- const call = record7(candidate);
2547
- const fn = record7(call?.function);
2548
- if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
2549
- let args;
2550
- try {
2551
- args = JSON.parse(fn.arguments);
2552
- } catch {
2553
- throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
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
+ }
2554
3278
  }
2555
- toolCalls.push({ id: call.id, name: fn.name, args });
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
+ } }
2556
3296
  }
2557
- const values = record7(source.usage) ?? {};
2558
- usage = {
2559
- input: integer2(values.prompt_tokens),
2560
- output: integer2(values.completion_tokens),
2561
- cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
2562
- ...costMetadata(values)
2563
- };
2564
- } else throw new TypeError("model gateway protocol is invalid");
2565
- if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
2566
- return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model };
2567
- }
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
+ };
2568
3309
 
2569
- // src/gateway.ts
2570
- async function checkpointArtifactRef(value) {
2571
- 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);
2572
3318
  }
2573
- var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2574
- var HASH3 = /^[a-f0-9]{64}$/u;
2575
- var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
2576
- function httpsUrl(value, field2) {
2577
- if (value === void 0) return;
2578
- if (typeof value !== "string" || value.length > 2048) throw new TypeError(`${field2} is invalid`);
2579
- let parsed;
2580
- try {
2581
- parsed = new URL(value);
2582
- } catch {
2583
- 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`);
2584
3322
  }
2585
- if (parsed.protocol !== "https:") throw new TypeError(`${field2} is invalid`);
2586
3323
  }
2587
- function slotMetadata(value) {
2588
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Gateway Credential slots are invalid");
2589
- const entries = Object.entries(value);
2590
- if (entries.length > 32) throw new TypeError("Gateway Credential slots are invalid");
2591
- const output = {};
2592
- for (const [slot, raw] of entries) {
2593
- const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2594
- 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))) {
2595
- throw new TypeError("Gateway Credential slots are invalid");
2596
- }
2597
- httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
2598
- 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`);
2599
3327
  }
2600
- return output;
2601
- }
2602
- function configEgressBindings(value) {
2603
- if (value === void 0) return [];
2604
- if (!Array.isArray(value) || value.length > 16) throw new TypeError("Gateway config egress bindings are invalid");
2605
- return value.map((raw) => {
2606
- const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2607
- 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))) {
2608
- throw new TypeError("Gateway config egress bindings are invalid");
2609
- }
2610
- return {
2611
- urlProperty: String(item.urlProperty),
2612
- operations: [...new Set(item.operations)],
2613
- methods: [...new Set(item.methods)]
2614
- };
2615
- });
2616
3328
  }
2617
- function discoverySetup(value) {
2618
- if (value === void 0) return void 0;
2619
- const item = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2620
- 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))) {
2621
- throw new TypeError("Gateway discovery setup is invalid");
2622
- }
2623
- 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);
2624
3331
  }
2625
- function checkpointImportMetadata(value) {
2626
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2627
- 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))) {
2628
- 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`);
2629
3335
  }
2630
- 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);
2631
3339
  }
2632
- function checkpointImportRequest(value) {
2633
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2634
- const provenance = source?.source && typeof source.source === "object" && !Array.isArray(source.source) ? source.source : null;
2635
- const provider = provenance?.provider && typeof provenance.provider === "object" && !Array.isArray(provenance.provider) ? provenance.provider : null;
2636
- const checkpoint = provenance?.checkpoint && typeof provenance.checkpoint === "object" && !Array.isArray(provenance.checkpoint) ? provenance.checkpoint : null;
2637
- const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
2638
- const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
2639
- const model = source?.model && typeof source.model === "object" && !Array.isArray(source.model) ? source.model : null;
2640
- 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))) {
2641
- 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`);
2642
3343
  }
2643
- try {
2644
- if (new TextEncoder().encode(canonicalJson(artifactValue)).byteLength > 65536) throw new TypeError();
2645
- } catch {
2646
- 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;
2647
3352
  }
2648
- try {
2649
- parseResourceName(String(provider.crn));
2650
- } catch {
2651
- 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;
2652
3357
  }
2653
- return source;
2654
- }
2655
- function checkpointDeploymentRequest(value) {
2656
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2657
- const gateway2 = source?.gateway && typeof source.gateway === "object" && !Array.isArray(source.gateway) ? source.gateway : null;
2658
- 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))) {
2659
- 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;
2660
3364
  }
2661
- try {
2662
- parseResourceName(gateway2.crn);
2663
- } catch {
2664
- 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;
2665
3370
  }
2666
- return { gateway: gateway2, import: checkpointImportRequest(source.import) };
3371
+ throw new TypeError(`${path}.kind is invalid`);
2667
3372
  }
2668
- var MODEL_ID_CONTROL = /[\u0000-\u001f\u007f]/u;
2669
- function gatewayModelOffer(value) {
2670
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2671
- 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) => ![
2672
- "id",
2673
- "displayName",
2674
- "contextTokens",
2675
- "maxOutputTokens",
2676
- "inputModalities",
2677
- "outputModalities",
2678
- "pricing"
2679
- ].includes(key))) {
2680
- 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`);
2681
3377
  }
2682
- const modalities = (field2) => {
2683
- const values = source[field2];
2684
- if (values === void 0) return void 0;
2685
- 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) {
2686
- throw new TypeError("Gateway Model offer is invalid");
2687
- }
2688
- return values;
2689
- };
2690
- const pricing = source.pricing === null ? null : modelAdvertisedPricing(source.pricing);
2691
- const inputModalities = modalities("inputModalities");
2692
- const outputModalities = modalities("outputModalities");
2693
- return {
2694
- id: source.id,
2695
- displayName: source.displayName,
2696
- contextTokens: Number(source.contextTokens),
2697
- maxOutputTokens: Number(source.maxOutputTokens),
2698
- ...inputModalities ? { inputModalities } : {},
2699
- ...outputModalities ? { outputModalities } : {},
2700
- pricing
2701
- };
3378
+ value.forEach((constraint, index) => validatePolicyConstraint(constraint, `${path}[${index}]`));
3379
+ return value;
2702
3380
  }
2703
- function assertNonSecretGatewayConfig(value, field2 = "config") {
2704
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
2705
- const source = value;
2706
- if (source.format === "password" || /(?:secret|password|private[-_ ]?key|access[-_ ]?token|api[-_ ]?key)/iu.test(field2)) {
2707
- throw new TypeError("Gateway secrets must use declared Credential slots");
2708
- }
2709
- const properties = source.properties && typeof source.properties === "object" && !Array.isArray(source.properties) ? source.properties : {};
2710
- for (const [name, declaration] of Object.entries(properties)) assertNonSecretGatewayConfig(declaration, name);
2711
- if (source.items) assertNonSecretGatewayConfig(source.items, field2);
2712
- if (source.additionalProperties && typeof source.additionalProperties === "object") {
2713
- assertNonSecretGatewayConfig(source.additionalProperties, field2);
2714
- }
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;
2715
3405
  }
2716
- function gatewayPackageMetadata(value) {
2717
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2718
- 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 ?? ""))) {
2719
- 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 }
2720
3434
  }
2721
- httpsUrl(source.documentationUrl, "Gateway documentation URL");
2722
- const credentialSlots = slotMetadata(source.credentialSlots);
2723
- const modelOffers = source.modelOffers === void 0 ? [] : Array.isArray(source.modelOffers) ? source.modelOffers.map(gatewayModelOffer) : (() => {
2724
- throw new TypeError("Gateway Model offers are invalid");
2725
- })();
2726
- if (modelOffers.length > 512 || new Set(modelOffers.map((offer) => offer.id)).size !== modelOffers.length) {
2727
- 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 }] }
2728
3444
  }
2729
- const capabilities = source.capabilities.map(capabilityContractRef);
2730
- if (new Set(capabilities.map((contract) => `${contract.id}@${contract.version}#${contract.hash}`)).size !== capabilities.length) {
2731
- 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
+ }
2732
3480
  }
2733
- const egress = integrationEgressPolicy(source.egress);
2734
- const configEgress = configEgressBindings(source.configEgress);
2735
- const discovery = discoverySetup(source.discovery);
2736
- const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
2737
- const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
2738
- if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
2739
- 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);
2740
3500
  }
2741
- 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))) {
2742
- 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);
2743
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(".", "_");
2744
3537
  return {
2745
- lifecycleVersion: 1,
2746
- displayName: source.displayName,
2747
- description: source.description,
2748
- ...typeof source.documentationUrl === "string" ? { documentationUrl: source.documentationUrl } : {},
2749
- ...typeof source.service === "string" ? { service: source.service } : {},
2750
- credentialSlots,
2751
- modelOffers,
2752
- capabilities,
2753
- billing: { upstreamPayer: source.billing.upstreamPayer },
2754
- egress,
2755
- ...configEgress.length ? { configEgress } : {},
2756
- ...discovery ? { discovery } : {},
2757
- ...training ? { training } : {},
2758
- ...checkpointImport ? { checkpointImport } : {}
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`);
3551
+ }
2759
3552
  };
2760
3553
  }
2761
- function resolveGatewayEgress(metadata2, config) {
2762
- const derived = (metadata2.configEgress ?? []).map((binding) => {
2763
- let endpoint;
2764
- try {
2765
- endpoint = new URL(String(config[binding.urlProperty] ?? ""));
2766
- } catch {
2767
- throw new TypeError(`Gateway ${binding.urlProperty} must be an HTTPS endpoint`);
2768
- }
2769
- if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) {
2770
- throw new TypeError(`Gateway ${binding.urlProperty} must be an exact HTTPS endpoint without credentials, query, or fragment`);
2771
- }
2772
- return { operations: binding.operations, origin: endpoint.origin, pathExact: endpoint.pathname, methods: binding.methods };
2773
- });
2774
- return integrationEgressPolicy({ rules: [...metadata2.egress.rules, ...derived] });
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));
2775
3557
  }
2776
- function gateway(definition) {
2777
- 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") {
2778
- throw new TypeError("Gateway definition is invalid");
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 }
2779
3565
  }
2780
- const schemaError = validateJsonSchemaDefinition(definition.configSchema);
2781
- if (schemaError) throw new TypeError(`Gateway config schema is invalid: ${schemaError}`);
2782
- const configSchema = definition.configSchema;
2783
- if (configSchema.type !== "object") throw new TypeError('Gateway config schema root type must be "object"');
2784
- if (configSchema.additionalProperties !== false) throw new TypeError("Gateway config schema must reject unknown root fields");
2785
- assertNonSecretGatewayConfig(configSchema);
2786
- const gateway2 = gatewayPackageMetadata({
2787
- lifecycleVersion: 1,
2788
- displayName: definition.displayName,
2789
- description: definition.description,
2790
- documentationUrl: definition.documentationUrl,
2791
- service: definition.service,
2792
- credentialSlots: definition.credentialSlots,
2793
- modelOffers: definition.modelOffers ?? [],
2794
- capabilities: definition.capabilities,
2795
- billing: definition.billing,
2796
- egress: definition.egress,
2797
- configEgress: definition.configEgress,
2798
- discovery: definition.discovery,
2799
- training: definition.training,
2800
- checkpointImport: definition.checkpointImport
2801
- });
2802
- const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
2803
- for (const binding of gateway2.configEgress ?? []) {
2804
- const property = properties[binding.urlProperty];
2805
- if (!property || property.type !== "string" || property.format !== "uri") {
2806
- 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."
2807
3616
  }
2808
3617
  }
2809
- if (gateway2.discovery) {
2810
- const property = properties[gateway2.discovery.resultConfigProperty];
2811
- if (!property || property.type !== "array") throw new TypeError("Gateway discovery result config property must be an array");
2812
- const required2 = Array.isArray(configSchema.required) ? configSchema.required : [];
2813
- if (!required2.includes(gateway2.discovery.resultConfigProperty)) {
2814
- 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}$" }
2815
3641
  }
2816
- if (property.readOnly !== true) throw new TypeError("Gateway discovery result config property must be read-only");
2817
- }
2818
- const authoredCatalog = definition.catalog;
2819
- const wrapped = { ...definition, metadata: gateway2, catalog(config) {
2820
- const declarations = authoredCatalog(config);
2821
- if (gateway2.checkpointImport) {
2822
- const operation = declarations.find((candidate) => candidate.op === "importCheckpoint");
2823
- if (!operation || !operation.async || operation.effect !== "reconcilable" || operation.recovery.kind !== "reconcile") {
2824
- throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
2825
- }
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 });
2826
3650
  }
2827
- return declarations;
2828
- } };
2829
- return Object.freeze(wrapped);
2830
- }
2831
- function trainingProvider(definition) {
2832
- const authoredCatalog = definition.catalog;
2833
- return gateway({
2834
- ...definition,
2835
- 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]],
2836
- catalog(config) {
2837
- const declarations = authoredCatalog(config);
2838
- const train = declarations.find((operation) => operation.op === "train");
2839
- if (!train || !train.async || train.effect !== "reconcilable" || train.recovery.kind !== "reconcile") {
2840
- throw new TypeError("Training Provider train must be asynchronous, reconcilable, and recovered by reconcile");
2841
- }
2842
- 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 });
2843
3654
  }
2844
- });
2845
- }
2846
- var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
2847
- id: "constal.model-checkpoint-import",
2848
- version: "1",
2849
- hash: "49563823899586a87dcee82e9db969af5f2f5364adb3eb808a19e86b862e87ba"
3655
+ throw new TypeError("cas action must be put or get");
3656
+ }
2850
3657
  };
2851
- var MCP_CLIENT_CAPABILITY = {
2852
- id: "constal.mcp-client",
2853
- version: "1",
2854
- 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
+ }
2855
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
+ ];
2856
3748
 
2857
- // src/credential-provider.ts
3749
+ // packages/sdk/src/credential-provider.ts
2858
3750
  function assertNonSecretConfigSchema(value, field2 = "config") {
2859
3751
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
2860
3752
  const source = value;
@@ -2976,12 +3868,12 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
2976
3868
  return action3;
2977
3869
  }
2978
3870
  function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
2979
- const result = interactionRecord(value);
2980
- if (!result || !exactKeys3(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
2981
- 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;
2982
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");
2983
3875
  return {
2984
- action: credentialInteractionAction(result.action, origins, state, sessionExpiresAt),
3876
+ action: credentialInteractionAction(result2.action, origins, state, sessionExpiresAt),
2985
3877
  ...privateState === void 0 ? {} : { privateState }
2986
3878
  };
2987
3879
  }
@@ -3025,30 +3917,30 @@ function credentialProviderSetupMetadata(value, slots) {
3025
3917
  }
3026
3918
  return value;
3027
3919
  }
3028
- function credentialProvider(definition) {
3029
- 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") {
3030
3922
  throw new TypeError("credential provider metadata is invalid");
3031
3923
  }
3032
- if (definition.documentationUrl !== void 0) {
3033
- 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");
3034
3926
  let documentationUrl;
3035
3927
  try {
3036
- documentationUrl = new URL(definition.documentationUrl);
3928
+ documentationUrl = new URL(definition2.documentationUrl);
3037
3929
  } catch {
3038
3930
  throw new TypeError("credential provider documentation URL is invalid");
3039
3931
  }
3040
- if (definition.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
3932
+ if (definition2.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
3041
3933
  throw new TypeError("credential provider documentation URL is invalid");
3042
3934
  }
3043
3935
  }
3044
- credentialRotationDefaults(definition.rotation);
3045
- credentialProviderConfigSchema(definition.configSchema);
3046
- credentialProviderConfigSchema(definition.credentialConfigSchema);
3047
- 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))) {
3048
3940
  throw new TypeError("credential provider bootstrap slots are invalid");
3049
3941
  }
3050
- const setup = credentialProviderSetupMetadata(definition.setup, definition.credentialSlots);
3051
- const interaction = definition.interaction ?? null;
3942
+ const setup = credentialProviderSetupMetadata(definition2.setup, definition2.credentialSlots);
3943
+ const interaction = definition2.interaction ?? null;
3052
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) => {
3053
3945
  try {
3054
3946
  const url = new URL(origin);
@@ -3059,7 +3951,7 @@ function credentialProvider(definition) {
3059
3951
  }))) {
3060
3952
  throw new TypeError("credential provider interaction origins are invalid");
3061
3953
  }
3062
- const mintRecovery = definition.mintRecovery ?? { kind: "idempotency-key" };
3954
+ const mintRecovery = definition2.mintRecovery ?? { kind: "idempotency-key" };
3063
3955
  if (!["idempotency-key", "outcome-unknown"].includes(mintRecovery.kind)) {
3064
3956
  throw new TypeError("credential provider mint recovery is invalid");
3065
3957
  }
@@ -3068,31 +3960,183 @@ function credentialProvider(definition) {
3068
3960
  }
3069
3961
  const metadata2 = {
3070
3962
  lifecycleVersion: 3,
3071
- displayName: definition.displayName,
3072
- description: definition.description,
3073
- ...definition.documentationUrl ? { documentationUrl: definition.documentationUrl } : {},
3963
+ displayName: definition2.displayName,
3964
+ description: definition2.description,
3965
+ ...definition2.documentationUrl ? { documentationUrl: definition2.documentationUrl } : {},
3074
3966
  ...setup ? { setup } : {},
3075
- credentialSlots: [...definition.credentialSlots].sort(),
3076
- credentialConfigSchema: definition.credentialConfigSchema,
3967
+ credentialSlots: [...definition2.credentialSlots].sort(),
3968
+ credentialConfigSchema: definition2.credentialConfigSchema,
3077
3969
  interaction: interaction ? { origins: [...interaction.origins].sort() } : null,
3078
- rotation: definition.rotation,
3079
- egress: integrationEgressPolicy(definition.egress)
3970
+ rotation: definition2.rotation,
3971
+ egress: integrationEgressPolicy(definition2.egress)
3972
+ };
3973
+ return Object.freeze({ ...definition2, mintRecovery, metadata: metadata2 });
3974
+ }
3975
+
3976
+ // packages/sdk/src/container-images.ts
3977
+ var REPOSITORY = /^[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*$/u;
3978
+ function containerImageReference(value) {
3979
+ if (typeof value !== "string" || !value || /[\s?#\\]/u.test(value) || value.includes("://")) throw new TypeError("Container image reference is invalid");
3980
+ const components = value.split("@");
3981
+ if (components.length > 2) throw new TypeError("Container image reference is invalid");
3982
+ let name = components[0];
3983
+ const digest = components[1] ?? null;
3984
+ if (digest !== null && !/^[a-z][a-z0-9+._-]*:[A-Za-z0-9=_-]+$/u.test(digest)) throw new TypeError("Container image digest is invalid");
3985
+ if (digest?.startsWith("sha256:") && !/^sha256:[a-f0-9]{64}$/u.test(digest)) throw new TypeError("Container image SHA-256 digest is invalid");
3986
+ const separator = name.lastIndexOf(":");
3987
+ const tag = separator > name.lastIndexOf("/") ? name.slice(separator + 1) : null;
3988
+ if (tag !== null) {
3989
+ if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/u.test(tag)) throw new TypeError("Container image tag is invalid");
3990
+ name = name.slice(0, separator);
3991
+ }
3992
+ const parts = name.split("/");
3993
+ const explicitRegistry = parts.length > 1 && (/[.:]/u.test(parts[0]) || parts[0] === "localhost");
3994
+ const registryInput = explicitRegistry ? parts.shift() : "docker.io";
3995
+ let host;
3996
+ try {
3997
+ host = new URL(`https://${registryInput}`);
3998
+ } catch {
3999
+ throw new TypeError("Container image registry is invalid");
4000
+ }
4001
+ if (host.username || host.password || host.pathname !== "/" || !host.hostname) throw new TypeError("Container image registry is invalid");
4002
+ const registry = host.host === "index.docker.io" ? "docker.io" : host.host;
4003
+ if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
4004
+ const repository = parts.join("/");
4005
+ if (!REPOSITORY.test(repository)) throw new TypeError("Container image repository is invalid");
4006
+ const selectedTag = tag ?? (digest === null ? "latest" : null);
4007
+ return {
4008
+ registry,
4009
+ repository,
4010
+ tag: selectedTag,
4011
+ digest,
4012
+ reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
4013
+ };
4014
+ }
4015
+
4016
+ // packages/sdk/src/sandbox-build.ts
4017
+ var recipeProperties = {
4018
+ context: { type: "string", minLength: 1 },
4019
+ dockerfile: { type: "string", minLength: 1 },
4020
+ target: { type: "string", minLength: 1 },
4021
+ platform: { type: "string", minLength: 1 },
4022
+ buildArgs: { type: "object", additionalProperties: { type: "string" } },
4023
+ cache: { type: "boolean" }
4024
+ };
4025
+ var SANDBOX_IMAGE_BUILD_SCHEMA = {
4026
+ type: "object",
4027
+ additionalProperties: false,
4028
+ required: ["sandbox"],
4029
+ properties: {
4030
+ ...recipeProperties,
4031
+ sandbox: { type: "string", pattern: "^sbx-[a-f0-9]{36}$" },
4032
+ secretTargets: { type: "object", additionalProperties: { type: "string", minLength: 1 } },
4033
+ registryTargets: { type: "object", additionalProperties: {
4034
+ type: "object",
4035
+ required: ["username", "slot"],
4036
+ additionalProperties: false,
4037
+ properties: { username: { type: "string" }, slot: { type: "string", minLength: 1 } }
4038
+ } }
4039
+ }
4040
+ };
4041
+ function sandboxImageBuildInput(value) {
4042
+ const invalid = validateJsonSchema(value, { type: "object", additionalProperties: false, properties: {
4043
+ ...recipeProperties,
4044
+ secrets: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA },
4045
+ registries: { type: "object", additionalProperties: {
4046
+ type: "object",
4047
+ required: ["username", "credential"],
4048
+ additionalProperties: false,
4049
+ properties: { username: { type: "string" }, credential: RESOURCE_CREDENTIAL_BINDING_SCHEMA }
4050
+ } }
4051
+ } });
4052
+ if (invalid) throw new TypeError(`Invalid sandbox image build: ${invalid}`);
4053
+ const result2 = structuredClone(value);
4054
+ for (const binding of Object.values(result2.secrets ?? {})) resourceCredentialBinding(binding);
4055
+ for (const registry of Object.values(result2.registries ?? {})) resourceCredentialBinding(registry.credential);
4056
+ return result2;
4057
+ }
4058
+
4059
+ // packages/sdk/src/sandbox-pool.ts
4060
+ var WORKSPACE_ROOT = "/workspace";
4061
+ function absoluteSandboxPath(value) {
4062
+ const segments = [];
4063
+ for (const segment of value.split("/")) {
4064
+ if (!segment || segment === ".") continue;
4065
+ if (segment === "..") segments.pop();
4066
+ else segments.push(segment);
4067
+ }
4068
+ return `/${segments.join("/")}`;
4069
+ }
4070
+ function normalizeSandboxWorkspacePath(path, cwd = WORKSPACE_ROOT) {
4071
+ 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)) {
4072
+ throw new TypeError("sandbox workspace path is invalid");
4073
+ }
4074
+ const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
4075
+ if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
4076
+ throw new TypeError("sandbox working directory is outside /workspace");
4077
+ }
4078
+ const normalized = absoluteSandboxPath(path.startsWith("/") ? path : `${base}/${path}`);
4079
+ if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
4080
+ throw new TypeError("sandbox path is outside /workspace");
4081
+ }
4082
+ return normalized;
4083
+ }
4084
+ var SANDBOX_PROCESS_CREDENTIALS_SCHEMA = { type: "object", additionalProperties: false, properties: {
4085
+ env: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA },
4086
+ files: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA }
4087
+ } };
4088
+ function processCredentialMaps(value, resolve) {
4089
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("process credentials are invalid");
4090
+ const source = value;
4091
+ if (Object.keys(source).some((key) => key !== "env" && key !== "files")) throw new TypeError("process credential kind is invalid");
4092
+ const result2 = {};
4093
+ for (const kind of ["env", "files"]) {
4094
+ const entries = source[kind];
4095
+ if (entries === void 0) continue;
4096
+ if (!entries || typeof entries !== "object" || Array.isArray(entries)) throw new TypeError("process credential map is invalid");
4097
+ result2[kind] = Object.fromEntries(Object.entries(entries).map(([name, binding]) => {
4098
+ if (!name || name.includes("=") || name.includes("\0")) throw new TypeError("process credential variable is invalid");
4099
+ return [name, resolve(binding)];
4100
+ }));
4101
+ }
4102
+ 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");
4103
+ return result2;
4104
+ }
4105
+ function sandboxProcessCredentials(value) {
4106
+ return processCredentialMaps(value, resourceCredentialBinding);
4107
+ }
4108
+ function importSandboxImageInput(value) {
4109
+ const error = validateJsonSchema(value, { type: "object", required: ["reference"], additionalProperties: false, properties: {
4110
+ cache: { type: "boolean" },
4111
+ reference: { type: "string", minLength: 1 },
4112
+ registry: {
4113
+ type: "object",
4114
+ required: ["username", "credential"],
4115
+ additionalProperties: false,
4116
+ properties: { username: { type: "string", minLength: 1 }, credential: RESOURCE_CREDENTIAL_BINDING_SCHEMA }
4117
+ }
4118
+ } });
4119
+ if (error) throw new TypeError(`Invalid sandbox image input: ${error}`);
4120
+ const source = structuredClone(value);
4121
+ return {
4122
+ reference: containerImageReference(source.reference).reference,
4123
+ ...source.cache === void 0 ? {} : { cache: source.cache },
4124
+ ...source.registry ? { registry: { username: source.registry.username, credential: resourceCredentialBinding(source.registry.credential) } } : {}
3080
4125
  };
3081
- return Object.freeze({ ...definition, mintRecovery, metadata: metadata2 });
3082
4126
  }
3083
4127
 
3084
- // src/scorer.ts
4128
+ // packages/sdk/src/scorer.ts
3085
4129
  function validPointer(value) {
3086
4130
  return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));
3087
4131
  }
3088
- function record8(value) {
4132
+ function record9(value) {
3089
4133
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
3090
4134
  }
3091
4135
  function exactKeys4(value, allowed) {
3092
4136
  return Object.keys(value).every((key) => allowed.includes(key));
3093
4137
  }
3094
4138
  function scorerRule(value, depth, state) {
3095
- const rule = record8(value);
4139
+ const rule = record9(value);
3096
4140
  if (!rule || depth > 32 || ++state.rules > 1024 || typeof rule.op !== "string") throw new TypeError("Code Scorer IR is invalid");
3097
4141
  if (rule.op === "all" || rule.op === "any") {
3098
4142
  if (!exactKeys4(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1 || rule.rules.length > 128) {
@@ -3105,7 +4149,7 @@ function scorerRule(value, depth, state) {
3105
4149
  return { op: "not", rule: scorerRule(rule.rule, depth + 1, state) };
3106
4150
  }
3107
4151
  if (rule.op === "schema") {
3108
- if (!exactKeys4(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record8(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
4152
+ if (!exactKeys4(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record9(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
3109
4153
  return rule;
3110
4154
  }
3111
4155
  if (rule.op === "regex") {
@@ -3140,7 +4184,7 @@ function scorerRule(value, depth, state) {
3140
4184
  throw new TypeError("Code Scorer operation is invalid");
3141
4185
  }
3142
4186
  function codeScorerIR(value) {
3143
- const ir = record8(value);
4187
+ const ir = record9(value);
3144
4188
  if (!ir || ir.v !== 1 || !exactKeys4(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
3145
4189
  return { v: 1, rule: scorerRule(ir.rule, 0, { rules: 0 }) };
3146
4190
  }
@@ -3153,7 +4197,7 @@ function pointer(value, path) {
3153
4197
  if (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length) return { found: false, value: void 0 };
3154
4198
  current = current[Number(key)];
3155
4199
  } else {
3156
- const source = record8(current);
4200
+ const source = record9(current);
3157
4201
  if (!source || !Object.hasOwn(source, key)) return { found: false, value: void 0 };
3158
4202
  current = source[key];
3159
4203
  }
@@ -3187,7 +4231,7 @@ function evaluate(rule, subject) {
3187
4231
  if (!sources.found || !Array.isArray(sources.value)) return fail(rule.sourcesPath, "citation sources are missing");
3188
4232
  const available = new Set(sources.value.flatMap((source, index) => {
3189
4233
  if (typeof source === "string") return [source, String(index + 1)];
3190
- const item = record8(source);
4234
+ const item = record9(source);
3191
4235
  return item ? [String(item.id ?? ""), String(index + 1)].filter(Boolean) : [String(index + 1)];
3192
4236
  }));
3193
4237
  const citations = [...text2.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
@@ -3206,7 +4250,7 @@ function evaluate(rule, subject) {
3206
4250
  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));
3207
4251
  return contains ? pass() : fail(rule.path, "value is not contained");
3208
4252
  }
3209
- const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record8(item)?.name ?? "")) : [];
4253
+ const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record9(item)?.name ?? "")) : [];
3210
4254
  const sequence = rule.mode === "exact" ? names.length === rule.expected.length && names.every((name, index) => name === rule.expected[index]) : rule.expected.reduce((cursor, expected) => {
3211
4255
  const index = names.indexOf(expected, cursor);
3212
4256
  return index < 0 ? Number.POSITIVE_INFINITY : index + 1;
@@ -3215,20 +4259,20 @@ function evaluate(rule, subject) {
3215
4259
  }
3216
4260
  function evaluateCodeScorer(raw, subject) {
3217
4261
  const ir = codeScorerIR(raw);
3218
- const result = evaluate(ir.rule, subject);
4262
+ const result2 = evaluate(ir.rule, subject);
3219
4263
  return {
3220
- score: result.pass ? 1 : 0,
3221
- pass: result.pass,
4264
+ score: result2.pass ? 1 : 0,
4265
+ pass: result2.pass,
3222
4266
  dimensions: null,
3223
- evidence: { rule: canonicalJson(ir.rule), checks: result.checks, failures: result.failures.slice(0, 64) }
4267
+ evidence: { rule: canonicalJson(ir.rule), checks: result2.checks, failures: result2.failures.slice(0, 64) }
3224
4268
  };
3225
4269
  }
3226
4270
 
3227
- // src/errors.ts
4271
+ // packages/sdk/src/errors.ts
3228
4272
  var GateExhausted = class extends Error {
3229
- constructor(record9) {
4273
+ constructor(record10) {
3230
4274
  super("turn gate exhausted");
3231
- this.record = record9;
4275
+ this.record = record10;
3232
4276
  this.name = "GateExhausted";
3233
4277
  }
3234
4278
  record;
@@ -3242,8 +4286,8 @@ var CommitGateRejected = class extends Error {
3242
4286
  evaluation;
3243
4287
  };
3244
4288
  var SpawnCardinality = class extends Error {
3245
- constructor(message = "spawn cardinality exceeds the configured cap; use map") {
3246
- super(message);
4289
+ constructor(message2 = "spawn cardinality exceeds the configured cap; use map") {
4290
+ super(message2);
3247
4291
  this.name = "SpawnCardinality";
3248
4292
  }
3249
4293
  };
@@ -3270,8 +4314,8 @@ var OutcomeUnknown = class extends Error {
3270
4314
  effect;
3271
4315
  };
3272
4316
  var LeaseLost = class extends Error {
3273
- constructor(message = "invocation lease is no longer current") {
3274
- super(message);
4317
+ constructor(message2 = "invocation lease is no longer current") {
4318
+ super(message2);
3275
4319
  this.name = "LeaseLost";
3276
4320
  }
3277
4321
  };
@@ -3306,33 +4350,33 @@ var CommitConflict = class extends Error {
3306
4350
  actual;
3307
4351
  };
3308
4352
  var ResourceInvalid = class extends Error {
3309
- constructor(resource) {
3310
- super(`invalid resource: ${resource}`);
3311
- this.resource = resource;
4353
+ constructor(resource2) {
4354
+ super(`invalid resource: ${resource2}`);
4355
+ this.resource = resource2;
3312
4356
  this.name = "ResourceInvalid";
3313
4357
  }
3314
4358
  resource;
3315
4359
  };
3316
4360
  var ResourceUnbound = class extends Error {
3317
- constructor(resource) {
3318
- super(`resource is not bound to this execution: ${resource}`);
3319
- this.resource = resource;
4361
+ constructor(resource2) {
4362
+ super(`resource is not bound to this execution: ${resource2}`);
4363
+ this.resource = resource2;
3320
4364
  this.name = "ResourceUnbound";
3321
4365
  }
3322
4366
  resource;
3323
4367
  };
3324
4368
  var ToolUnavailable = class extends Error {
3325
- constructor(tool) {
3326
- super(`Tool is not enabled for this Agent deployment: ${tool}`);
3327
- this.tool = tool;
4369
+ constructor(tool2) {
4370
+ super(`Tool is not enabled for this Agent deployment: ${tool2}`);
4371
+ this.tool = tool2;
3328
4372
  this.name = "ToolUnavailable";
3329
4373
  }
3330
4374
  tool;
3331
4375
  };
3332
4376
  var UnknownTool = class extends Error {
3333
- constructor(tool) {
3334
- super(`model emitted a Tool that was not offered: ${tool}`);
3335
- this.tool = tool;
4377
+ constructor(tool2) {
4378
+ super(`model emitted a Tool that was not offered: ${tool2}`);
4379
+ this.tool = tool2;
3336
4380
  this.name = "UnknownTool";
3337
4381
  }
3338
4382
  tool;
@@ -3348,24 +4392,24 @@ var EffectCeilingExceeded = class extends Error {
3348
4392
  observed;
3349
4393
  };
3350
4394
  var ResourceDisabled = class extends Error {
3351
- constructor(resource) {
3352
- super(`resource is disabled: ${resource}`);
3353
- this.resource = resource;
4395
+ constructor(resource2) {
4396
+ super(`resource is disabled: ${resource2}`);
4397
+ this.resource = resource2;
3354
4398
  this.name = "ResourceDisabled";
3355
4399
  }
3356
4400
  resource;
3357
4401
  };
3358
4402
  var PolicyDecisionFailed = class extends Error {
3359
- constructor(decisionHash, message = "Policy denied operation") {
3360
- super(message);
4403
+ constructor(decisionHash, message2 = "Policy denied operation") {
4404
+ super(message2);
3361
4405
  this.decisionHash = decisionHash;
3362
4406
  this.name = "PolicyDecisionFailed";
3363
4407
  }
3364
4408
  decisionHash;
3365
4409
  };
3366
4410
  var PolicyConstraintFailed = class extends PolicyDecisionFailed {
3367
- constructor(decisionHash, message = "Policy constraint rejected operation") {
3368
- super(decisionHash, message);
4411
+ constructor(decisionHash, message2 = "Policy constraint rejected operation") {
4412
+ super(decisionHash, message2);
3369
4413
  this.name = "PolicyConstraintFailed";
3370
4414
  }
3371
4415
  };
@@ -3411,12 +4455,14 @@ export {
3411
4455
  CONSTAL_API_OPERATION_SCHEMAS,
3412
4456
  CONSTAL_API_QUERY_KINDS,
3413
4457
  CONSTAL_API_VERSION,
4458
+ CONSTAL_MODEL_CREATE_SCHEMA,
3414
4459
  CommitConflict,
3415
4460
  CommitGateRejected,
3416
4461
  CredentialRevoked,
3417
4462
  CredentialUnavailable,
3418
4463
  DirectNetworkDenied,
3419
4464
  EffectCeilingExceeded,
4465
+ GATEWAY_MODEL_OFFER_SCHEMA,
3420
4466
  GateExhausted,
3421
4467
  IntegrationRequestNotSent,
3422
4468
  LeaseLost,
@@ -3424,15 +4470,19 @@ export {
3424
4470
  MEMORY_OPERATION_DECLARATIONS,
3425
4471
  MODEL_CHECKPOINT_IMPORT_CAPABILITY,
3426
4472
  MODEL_COMPLETION_CAPABILITY,
4473
+ MODEL_GENERATION_OPTIONS_SCHEMA,
4474
+ MODEL_GENERATION_OPTION_KEYS,
3427
4475
  NondeterministicReplay,
3428
4476
  OutcomeUnknown,
3429
4477
  PolicyConstraintFailed,
3430
4478
  PolicyDecisionFailed,
4479
+ RESOURCE_CREDENTIAL_BINDING_SCHEMA,
3431
4480
  RESOURCE_KINDS,
3432
4481
  ResourceDisabled,
3433
4482
  ResourceInvalid,
3434
4483
  ResourceUnbound,
3435
4484
  RollbackTargetInvalid,
4485
+ SANDBOX_PROCESS_CREDENTIALS_SCHEMA,
3436
4486
  SessionDeleted,
3437
4487
  SpawnCardinality,
3438
4488
  SwallowedYield,
@@ -3450,6 +4500,7 @@ export {
3450
4500
  agentSetupMetadata,
3451
4501
  agentSetupRequirements,
3452
4502
  analyticsEvent,
4503
+ applyModelProviderOptions,
3453
4504
  approximateTokens,
3454
4505
  authProvider,
3455
4506
  authProviderName,
@@ -3469,6 +4520,7 @@ export {
3469
4520
  checkpointImportMetadata,
3470
4521
  checkpointImportRequest,
3471
4522
  codeScorerIR,
4523
+ connections,
3472
4524
  credentialEvidence,
3473
4525
  credentialInteractionAction,
3474
4526
  credentialInteractionEvent,
@@ -3491,23 +4543,29 @@ export {
3491
4543
  gatewayPackageMetadata,
3492
4544
  hash,
3493
4545
  hashValue,
4546
+ importSandboxImageInput,
3494
4547
  integrationEgressPolicy,
3495
4548
  labelSelector,
3496
4549
  matchesAction,
3497
4550
  matchesLabelSelector,
3498
4551
  matchesResource,
4552
+ mcpProtocol,
3499
4553
  memoryStoreBinding,
3500
4554
  modelAdvertisedPricing,
3501
4555
  modelControls,
3502
4556
  modelGatewayBinding,
3503
4557
  modelGatewayEndpoint,
4558
+ modelGenerationOptions,
3504
4559
  modelLimit,
3505
4560
  modelPrompt,
3506
4561
  modelProtocolRequest,
3507
4562
  modelProtocolResult,
4563
+ modelProviderOptions,
3508
4564
  murmur3_32,
4565
+ normalizeInvocationOptions,
3509
4566
  normalizeModelGatewayConfig,
3510
4567
  normalizeSandboxNetworkPolicy,
4568
+ normalizeSandboxWorkspacePath,
3511
4569
  opTool,
3512
4570
  opTools,
3513
4571
  parseResourceName,
@@ -3517,26 +4575,34 @@ export {
3517
4575
  resolveBindingOwner,
3518
4576
  resolveGatewayEgress,
3519
4577
  resolveResourceDependencyRef,
4578
+ resourceContext,
3520
4579
  resourceContractRef,
3521
4580
  resourceCredentialBinding,
4581
+ resourceCredentialBindings,
3522
4582
  resourceDependencyRef,
4583
+ resourceIndex,
3523
4584
  resourceLabelMap,
3524
4585
  resourceName,
3525
4586
  resourceNeed,
3526
4587
  resourcePattern,
3527
4588
  resourceSelector,
4589
+ resourceTools,
3528
4590
  sandboxControls,
4591
+ sandboxImageBuildInput,
3529
4592
  sandboxLimit,
4593
+ sandboxProcessCredentials,
3530
4594
  scopedBindingKey,
3531
4595
  scopedCredentialRef,
3532
4596
  scopedResourceRef,
3533
4597
  scorerName,
3534
4598
  selectableResourceLabels,
3535
4599
  setupAwait,
4600
+ setupCredentialReceipt,
3536
4601
  setupScreen,
3537
4602
  setupScreenView,
3538
4603
  setupSubmission,
3539
4604
  sha256Hex,
4605
+ skills,
3540
4606
  stageOutput,
3541
4607
  startTrainingRequest,
3542
4608
  subtask,