@constal/sdk 3.3.1 → 3.4.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
@@ -67,6 +67,70 @@ function bucketFor(value, buckets) {
67
67
  return murmur3_32(canonicalJson(value)) % buckets;
68
68
  }
69
69
 
70
+ // packages/sdk/src/skills.ts
71
+ function metadata(value) {
72
+ if (!value || typeof value.id !== "string" || !value.id || value.description !== void 0 && typeof value.description !== "string" || value.source !== void 0 && typeof value.source !== "string") {
73
+ throw new TypeError("Skill requires an id and optional description/source strings");
74
+ }
75
+ return {
76
+ id: value.id,
77
+ ...value.description === void 0 ? {} : { description: value.description },
78
+ ...value.source === void 0 ? {} : { source: value.source }
79
+ };
80
+ }
81
+ function catalog(values) {
82
+ if (!Array.isArray(values)) throw new TypeError("Skill source must return a list");
83
+ const result = values.map(metadata);
84
+ if (new Set(result.map((value) => value.id)).size !== result.length) throw new TypeError("Skill source contains duplicate ids");
85
+ return result;
86
+ }
87
+ function skills(input) {
88
+ let source;
89
+ if (Array.isArray(input)) {
90
+ const descriptions = catalog(input);
91
+ const entries = new Map(descriptions.map((description, index) => {
92
+ if (typeof input[index].instructions !== "string") throw new TypeError("Skill instructions must be a string");
93
+ return [description.id, { ...description, instructions: input[index].instructions }];
94
+ }));
95
+ source = { list: () => descriptions, load: (id2) => {
96
+ const value = entries.get(id2);
97
+ if (!value) throw new TypeError(`Skill not found: ${id2}`);
98
+ return value;
99
+ } };
100
+ } else {
101
+ source = input;
102
+ if (!source || typeof source.list !== "function" || typeof source.load !== "function") throw new TypeError("Skill source requires list and load functions");
103
+ }
104
+ const list = async (ctx) => catalog(await source.list(ctx));
105
+ const load = async (id2, ctx) => {
106
+ const value = await source.load(id2, ctx);
107
+ const description = metadata(value);
108
+ if (description.id !== id2) throw new TypeError("Skill source returned a different skill");
109
+ if (typeof value.instructions !== "string") throw new TypeError("Skill instructions must be a string");
110
+ const content2 = { ...description, instructions: value.instructions };
111
+ return { ...content2, hash: await hashValue(content2) };
112
+ };
113
+ const access = { needs: source.needs ?? [], maxEffect: source.maxEffect ?? "read-only" };
114
+ return { list, load, tools: {
115
+ list_skills: {
116
+ name: "list_skills",
117
+ version: "1",
118
+ description: "List available skills with their descriptions and source locations.",
119
+ schema: { type: "object", properties: {}, additionalProperties: false },
120
+ ...access,
121
+ run: (_args, ctx) => list(ctx)
122
+ },
123
+ read_skill: {
124
+ name: "read_skill",
125
+ version: "1",
126
+ description: "Read a skill's complete instructions and content identity.",
127
+ schema: { type: "object", required: ["id"], properties: { id: { type: "string", minLength: 1 } }, additionalProperties: false },
128
+ ...access,
129
+ run: (args, ctx) => load(args.id, ctx)
130
+ }
131
+ } };
132
+ }
133
+
70
134
  // packages/sdk/src/partition.ts
71
135
  var encoder2 = new TextEncoder();
72
136
  function positiveSafeInteger(value) {
@@ -154,17 +218,17 @@ var EVENT_ID = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/u;
154
218
  var FIELD_ID = /^[a-z][a-z0-9_]{0,63}$/u;
155
219
  var VERSION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
156
220
  var RESERVED = /* @__PURE__ */ new Set(["system", "platform", "constal", "billing", "security", "audit"]);
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]]) {
221
+ function analyticsEvent(definition) {
222
+ if (typeof definition.id !== "string" || definition.id.length > 128 || !EVENT_ID.test(definition.id)) throw new TypeError("analytics event id is invalid");
223
+ if (RESERVED.has(definition.id.split(/[.-]/u)[0])) throw new TypeError("analytics event id uses a reserved namespace");
224
+ if (typeof definition.version !== "string" || !VERSION.test(definition.version)) throw new TypeError("analytics event version is invalid");
225
+ for (const [kind, fields] of [["dimensions", definition.dimensions], ["metrics", definition.metrics]]) {
162
226
  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
227
  if (new Set(fields).size !== fields.length) throw new TypeError(`analytics event ${kind} must be unique`);
164
228
  }
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]) });
229
+ const metricNames = new Set(definition.metrics);
230
+ if (definition.dimensions.some((field2) => metricNames.has(field2))) throw new TypeError("analytics dimension and metric names must not overlap");
231
+ return Object.freeze({ ...definition, dimensions: Object.freeze([...definition.dimensions]), metrics: Object.freeze([...definition.metrics]) });
168
232
  }
169
233
 
170
234
  // packages/sdk/src/schema.ts
@@ -466,15 +530,6 @@ function resolveBindingOwner(scope2, context, required2 = true) {
466
530
  }
467
531
  return scope2 === "principal" ? { kind: "principal", principal: name } : { kind: "customer", customer: name };
468
532
  }
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
- ] };
478
533
  function agentSetupRequirements(value, options = {}) {
479
534
  if (!Array.isArray(value) || value.length < 1 || value.length > 64) throw new TypeError("Agent setup requirements are invalid");
480
535
  const requirements = value.map((raw) => {
@@ -538,6 +593,22 @@ var HASH = /^[a-f0-9]{64}$/u;
538
593
  var KINDS = /* @__PURE__ */ new Set([...RESOURCE_KINDS, ...PLATFORM_ADDRESS_KINDS]);
539
594
  var RESOURCE_KIND_SET = new Set(RESOURCE_KINDS);
540
595
  var INVOKABLE_KIND_SET = new Set(INVOKABLE_KINDS);
596
+ var RESOURCE_CREDENTIAL_BINDING_SCHEMA = {
597
+ anyOf: [
598
+ { type: "string", pattern: `^crn:constal:${Array(3).fill(SEGMENT.source.slice(1, -1)).join(":")}:credential/(?!/)(?!\\.{1,2}(?:/|$))(?!.*//)(?!.*\\/\\.{1,2}(?:/|$))(?!.*\\/$)${PATH.source.slice(1, -1)}$` },
599
+ {
600
+ type: "object",
601
+ required: ["kind", "key", "owner", "required"],
602
+ additionalProperties: false,
603
+ properties: {
604
+ kind: { const: "scoped" },
605
+ key: { type: "string", pattern: NAME2.source },
606
+ owner: { enum: ["tenant", "customer", "principal"] },
607
+ required: { type: "boolean" }
608
+ }
609
+ }
610
+ ]
611
+ };
541
612
  function record2(value) {
542
613
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
543
614
  }
@@ -578,11 +649,11 @@ function modelGatewayBinding(value) {
578
649
  const candidate = record2(value);
579
650
  if (!candidate) throw new TypeError("Model Gateway binding is invalid");
580
651
  if (candidate.kind === "fixed") {
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))) {
652
+ const resource = record2(candidate.resource);
653
+ 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))) {
583
654
  throw new TypeError("fixed Model Gateway binding is invalid");
584
655
  }
585
- const parts = parseResourceName(resource2.crn);
656
+ const parts = parseResourceName(resource.crn);
586
657
  if (!INVOKABLE_KIND_SET.has(parts.kind) || parts.kind === "model" || parts.kind === "memory") {
587
658
  throw new TypeError("Model Gateway must reference a Connection Resource");
588
659
  }
@@ -604,11 +675,11 @@ function memoryStoreBinding(value) {
604
675
  const candidate = record2(value);
605
676
  if (!candidate) throw new TypeError("Memory Store binding is invalid");
606
677
  if (candidate.kind === "fixed") {
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))) {
678
+ const resource = record2(candidate.resource);
679
+ 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))) {
609
680
  throw new TypeError("fixed Memory Store binding is invalid");
610
681
  }
611
- const parts = parseResourceName(resource2.crn);
682
+ const parts = parseResourceName(resource.crn);
612
683
  if (!INVOKABLE_KIND_SET.has(parts.kind) || parts.kind === "model" || parts.kind === "memory") {
613
684
  throw new TypeError("Memory Store must reference a Connection Resource");
614
685
  }
@@ -649,13 +720,17 @@ function resourceCredentialBinding(value) {
649
720
  if (typeof value === "string") return credentialName(value);
650
721
  return scopedCredentialRef(value);
651
722
  }
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
- }));
723
+ function invocationCredentialUses(value) {
724
+ if (value === void 0) return {};
725
+ const source = record2(value);
726
+ if (!source || Object.keys(source).length > 64) throw new TypeError("invocation Credential selections are invalid");
727
+ const result = {};
728
+ for (const [slot, raw] of Object.entries(source).sort(([left], [right]) => left.localeCompare(right))) {
729
+ const use = record2(raw), consumer = record2(use?.consumer);
730
+ if (!NAME2.test(slot) || !use || Object.keys(use).some((key) => key !== "binding" && key !== "consumer") || !consumer || Object.keys(consumer).some((key) => !["kind", "delivery", "name"].includes(key)) || consumer.kind !== "process" || consumer.delivery !== "env" && consumer.delivery !== "file" || typeof consumer.name !== "string" || !consumer.name || consumer.name.includes("=") || /[\u0000-\u001f\u007f]/u.test(consumer.name)) throw new TypeError("invocation Credential selection is invalid");
731
+ result[slot] = { binding: resourceCredentialBinding(use.binding), consumer };
732
+ }
733
+ return result;
659
734
  }
660
735
  function validateRotationDefaults(value) {
661
736
  const candidate = record2(value);
@@ -850,12 +925,12 @@ function normalizeCidrs(values, allowPrivate) {
850
925
  })) throw new TypeError("sandbox network CIDR intersects a reserved range");
851
926
  return { network, prefix, last, text: `${ipv4Text(network)}/${prefix}` };
852
927
  }).sort((left, right) => left.network - right.network || left.prefix - right.prefix);
853
- const result2 = [];
928
+ const result = [];
854
929
  for (const entry of entries) {
855
- if (result2.some((prior) => entry.network >= prior.network && entry.last <= prior.last)) continue;
856
- result2.push(entry);
930
+ if (result.some((prior) => entry.network >= prior.network && entry.last <= prior.last)) continue;
931
+ result.push(entry);
857
932
  }
858
- return result2.map((entry) => entry.text);
933
+ return result.map((entry) => entry.text);
859
934
  }
860
935
  function normalizeDomains(values) {
861
936
  if (!Array.isArray(values) || values.length === 0 || values.length > 20) throw new TypeError("sandbox network domains must contain 1 to 20 entries");
@@ -917,14 +992,14 @@ function validateExecutable(value, path) {
917
992
  requiredString(value.id, `${path}.id`);
918
993
  requiredString(value.version, `${path}.version`);
919
994
  }
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;
995
+ function validateTool(tool, path = "tool") {
996
+ requiredString(tool.name, `${path}.name`);
997
+ requiredString(tool.version, `${path}.version`);
998
+ if (!["read-only", "idempotent", "reconcilable", "non-idempotent"].includes(tool.maxEffect)) throw new TypeError(`${path}.maxEffect is invalid`);
999
+ tool.needs?.forEach(resourceNeed);
1000
+ if (tool.preview !== void 0 && typeof tool.preview !== "function") throw new TypeError(`${path}.preview must be a function`);
1001
+ if (typeof tool.run !== "function") throw new TypeError(`${path}.run must be a function`);
1002
+ return tool;
928
1003
  }
929
1004
  function validateView(view, path = "view") {
930
1005
  validateExecutable(view, path);
@@ -965,11 +1040,11 @@ function agent(input) {
965
1040
  def.partitionFns?.forEach((fn) => validatePartitionFn(fn));
966
1041
  def.foldFns?.forEach((fn) => validateFoldFn(fn));
967
1042
  def.analytics?.forEach((event) => analyticsEvent(event));
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}`);
1043
+ for (const [localName, tool] of Object.entries(def.tools ?? {})) {
1044
+ if (localName !== tool.name) throw new TypeError(`agent.tools.${localName} must match Tool.name`);
1045
+ validateTool(tool, `agent.tools.${localName}`);
971
1046
  }
972
- if (new Set(Object.values(def.tools ?? {}).map((tool2) => tool2.name)).size !== Object.keys(def.tools ?? {}).length) {
1047
+ if (new Set(Object.values(def.tools ?? {}).map((tool) => tool.name)).size !== Object.keys(def.tools ?? {}).length) {
973
1048
  throw new TypeError("agent Tool names must be unique");
974
1049
  }
975
1050
  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");
@@ -987,12 +1062,12 @@ function subtask(def) {
987
1062
  }
988
1063
 
989
1064
  // 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;
1065
+ function authProvider(definition) {
1066
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition.id)) throw new TypeError("authProvider.id is invalid");
1067
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition.version)) throw new TypeError("authProvider.version is invalid");
1068
+ if (typeof definition.authenticate !== "function") throw new TypeError("authProvider.authenticate must be a function");
1069
+ definition.needs?.forEach(resourceNeed);
1070
+ return definition;
996
1071
  }
997
1072
 
998
1073
  // packages/sdk/src/channel.ts
@@ -1003,18 +1078,18 @@ function executable(value, path) {
1003
1078
  required(value.id, `${path}.id`);
1004
1079
  required(value.version, `${path}.version`);
1005
1080
  }
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") {
1081
+ function channel(definition) {
1082
+ executable(definition, "channel");
1083
+ executable(definition.protocol, "channel.protocol");
1084
+ 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") {
1010
1085
  throw new TypeError("channel.protocol must define receive and respond; optional handlers must be functions");
1011
1086
  }
1012
- resourceDependencyRef(definition2.authProvider, ["auth-provider"]);
1013
- definition2.needs?.forEach(resourceNeed);
1014
- const analytics = definition2.analytics ?? [];
1087
+ resourceDependencyRef(definition.authProvider, ["auth-provider"]);
1088
+ definition.needs?.forEach(resourceNeed);
1089
+ const analytics = definition.analytics ?? [];
1015
1090
  analytics.forEach((event) => analyticsEvent(event));
1016
1091
  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");
1017
- return definition2;
1092
+ return definition;
1018
1093
  }
1019
1094
 
1020
1095
  // packages/sdk/src/ui.ts
@@ -1049,27 +1124,27 @@ function byteLength(value) {
1049
1124
  return new TextEncoder().encode(value).byteLength;
1050
1125
  }
1051
1126
  function uiBundleManifest(value, execution) {
1052
- const manifest = object(value, "UI bundle manifest is invalid");
1127
+ const manifest2 = object(value, "UI bundle manifest is invalid");
1053
1128
  exactKeys(
1054
- manifest,
1129
+ manifest2,
1055
1130
  ["schemaVersion", "kind", "runtime", "state", "assets", "contentSecurityPolicy"],
1056
1131
  ["schemaVersion", "kind", "runtime", "assets", "contentSecurityPolicy"]
1057
1132
  );
1058
- const runtime = object(manifest.runtime, "UI bundle runtime is invalid");
1059
- const assets = object(manifest.assets, "UI bundle assets manifest is invalid");
1133
+ const runtime = object(manifest2.runtime, "UI bundle runtime is invalid");
1134
+ const assets = object(manifest2.assets, "UI bundle assets manifest is invalid");
1060
1135
  exactKeys(runtime, ["contract", "entry"], ["contract", "entry"]);
1061
1136
  exactKeys(assets, ["root", "fallback"], ["root", "fallback"]);
1062
- if (manifest.schemaVersion !== 1 || manifest.kind !== "constal.ui" || runtime.contract !== "constal.ui-handler.v1" || manifest.contentSecurityPolicy !== "strict") throw new TypeError("UI bundle manifest contract is unsupported");
1137
+ if (manifest2.schemaVersion !== 1 || manifest2.kind !== "constal.ui" || runtime.contract !== "constal.ui-handler.v1" || manifest2.contentSecurityPolicy !== "strict") throw new TypeError("UI bundle manifest contract is unsupported");
1063
1138
  const entry = safePath(runtime.entry, "UI bundle entry");
1064
1139
  const root = safePath(assets.root, "UI asset root");
1065
1140
  const fallback = safePath(assets.fallback, "UI asset fallback");
1066
1141
  if (!entry.endsWith(".mjs") || fallback.startsWith(`${root}/`)) throw new TypeError("UI bundle entry or asset fallback is invalid");
1067
- if (byteLength(JSON.stringify(manifest)) > UI_BUNDLE_BOUNDS.maximumManifestBytes) throw new TypeError("UI bundle manifest exceeds 16 KiB");
1142
+ if (byteLength(JSON.stringify(manifest2)) > UI_BUNDLE_BOUNDS.maximumManifestBytes) throw new TypeError("UI bundle manifest exceeds 16 KiB");
1068
1143
  let state;
1069
1144
  if (execution === "stateless") {
1070
- if (manifest.state !== void 0) throw new TypeError("stateless UI bundles cannot declare SQLite state");
1145
+ if (manifest2.state !== void 0) throw new TypeError("stateless UI bundles cannot declare SQLite state");
1071
1146
  } else {
1072
- const raw = object(manifest.state, "durable UI bundles require a state manifest");
1147
+ const raw = object(manifest2.state, "durable UI bundles require a state manifest");
1073
1148
  const compatible = object(raw.compatibleSchemaVersions, "UI state compatibility is invalid");
1074
1149
  exactKeys(raw, ["schemaVersion", "compatibleSchemaVersions"], ["schemaVersion", "compatibleSchemaVersions"]);
1075
1150
  exactKeys(compatible, ["minimum", "maximum"], ["minimum", "maximum"]);
@@ -1091,12 +1166,12 @@ function uiBundleManifest(value, execution) {
1091
1166
  function uiBundle(value, execution) {
1092
1167
  const bundle = object(value, "UI bundle is invalid");
1093
1168
  exactKeys(bundle, ["manifest", "modules", "assets"], ["manifest", "modules", "assets"]);
1094
- const manifest = uiBundleManifest(bundle.manifest, execution);
1169
+ const manifest2 = uiBundleManifest(bundle.manifest, execution);
1095
1170
  const modules = object(bundle.modules, "UI bundle modules are invalid");
1096
1171
  const assets = object(bundle.assets, "UI bundle assets are invalid");
1097
1172
  const moduleEntries = Object.entries(modules);
1098
1173
  const assetEntries = Object.entries(assets);
1099
- if (moduleEntries.length < 1 || moduleEntries.length > UI_BUNDLE_BOUNDS.maximumModules || assetEntries.length > UI_BUNDLE_BOUNDS.maximumAssets || !Object.hasOwn(modules, manifest.runtime.entry)) {
1174
+ if (moduleEntries.length < 1 || moduleEntries.length > UI_BUNDLE_BOUNDS.maximumModules || assetEntries.length > UI_BUNDLE_BOUNDS.maximumAssets || !Object.hasOwn(modules, manifest2.runtime.entry)) {
1100
1175
  throw new TypeError("UI bundle file inventory is invalid");
1101
1176
  }
1102
1177
  const paths = /* @__PURE__ */ new Set();
@@ -1128,11 +1203,11 @@ function uiBundle(value, execution) {
1128
1203
  expandedBytes += bytes;
1129
1204
  normalizedAssets[path] = { bodyBase64: asset.bodyBase64, contentType: asset.contentType };
1130
1205
  }
1131
- if (!Object.hasOwn(normalizedAssets, `${manifest.assets.root}/${manifest.assets.fallback}`)) {
1206
+ if (!Object.hasOwn(normalizedAssets, `${manifest2.assets.root}/${manifest2.assets.fallback}`)) {
1132
1207
  throw new TypeError("UI bundle fallback asset is unavailable");
1133
1208
  }
1134
1209
  if (expandedBytes > UI_BUNDLE_BOUNDS.maximumExpandedBytes) throw new TypeError("UI bundle exceeds the expanded-size limit");
1135
- return { manifest, modules: normalizedModules, assets: normalizedAssets };
1210
+ return { manifest: manifest2, modules: normalizedModules, assets: normalizedAssets };
1136
1211
  }
1137
1212
 
1138
1213
  // packages/sdk/src/ingress.ts
@@ -1222,9 +1297,9 @@ function actions(value) {
1222
1297
  function panelBase(source) {
1223
1298
  const id2 = text(source.id, 63);
1224
1299
  const title = text(source.title, 256);
1225
- const description2 = text(source.description, 4096, true);
1300
+ const description = text(source.description, 4096, true);
1226
1301
  const parsedActions = actions(source.actions);
1227
- return id2 && ID.test(id2) && title && description2 !== null && parsedActions ? { id: id2, title, description: description2, actions: parsedActions } : null;
1302
+ return id2 && ID.test(id2) && title && description !== null && parsedActions ? { id: id2, title, description, actions: parsedActions } : null;
1228
1303
  }
1229
1304
  function panel(value) {
1230
1305
  const source = record3(value);
@@ -1526,750 +1601,279 @@ function credentialSetupState(requirement, scope2, inventory, binding) {
1526
1601
  };
1527
1602
  }
1528
1603
 
1529
- // packages/sdk/src/skills.ts
1530
- function description(value) {
1531
- if (!value || typeof value.id !== "string" || !value.id || value.description !== void 0 && typeof value.description !== "string" || value.source !== void 0 && typeof value.source !== "string") throw new TypeError("Skill metadata requires an id and optional description/source strings");
1532
- return {
1533
- id: value.id,
1534
- ...value.description === void 0 ? {} : { description: value.description },
1535
- ...value.source === void 0 ? {} : { source: value.source }
1536
- };
1537
- }
1538
- function catalog(values) {
1539
- if (!Array.isArray(values)) throw new TypeError("Skill source must return a list");
1540
- const entries = values.map(description);
1541
- if (new Set(entries.map((entry) => entry.id)).size !== entries.length) throw new TypeError("Skill ids must be unique within a source");
1542
- return entries;
1543
- }
1544
- function skills(input) {
1545
- let source;
1546
- if (Array.isArray(input)) {
1547
- const entries = new Map(input.map((value) => {
1548
- const metadata2 = description(value);
1549
- if (typeof value.instructions !== "string") throw new TypeError(`Skill ${metadata2.id} requires instructions`);
1550
- return [metadata2.id, { ...metadata2, instructions: value.instructions }];
1551
- }));
1552
- if (entries.size !== input.length) throw new TypeError("Skill ids must be unique within a source");
1553
- source = { list: () => [...entries.values()].map(description), load: (id2) => {
1554
- const value = entries.get(id2);
1555
- if (!value) throw new TypeError(`Unknown skill: ${id2}`);
1556
- return value;
1557
- } };
1558
- } else {
1559
- source = input;
1560
- if (!source || typeof source.list !== "function" || typeof source.load !== "function") throw new TypeError("Skill source requires list and load methods");
1561
- }
1562
- const list = async (ctx) => catalog(await source.list(ctx));
1563
- const load = async (id2, ctx) => {
1564
- if (typeof id2 !== "string" || !id2) throw new TypeError("Choose a skill id");
1565
- const value = await source.load(id2, ctx);
1566
- const metadata2 = description(value);
1567
- if (metadata2.id !== id2 || typeof value.instructions !== "string") throw new TypeError("Skill source returned a different id or missing instructions");
1568
- const content2 = { ...metadata2, instructions: value.instructions };
1569
- return { ...content2, hash: await hashValue(content2) };
1570
- };
1571
- const access = { maxEffect: source.maxEffect ?? "read-only", needs: source.needs ?? [] };
1572
- return { list, load, tools: {
1573
- list_skills: {
1574
- name: "list_skills",
1575
- version: "1",
1576
- description: "List the optional skills available to this agent, with their descriptions and sources.",
1577
- schema: { type: "object", properties: {}, additionalProperties: false },
1578
- ...access,
1579
- run: (_args, ctx) => list(ctx)
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
- }
1669
- }
1670
- };
1671
-
1672
- // packages/sdk/src/connection-state.ts
1673
- var connectionStateView = {
1674
- id: "constal-connections",
1675
- version: "2",
1676
- over: "facts",
1677
- init: () => ({}),
1678
- apply(state, fact) {
1679
- const value = fact.artifact;
1680
- if (!value?.run || !value.name) return state;
1681
- const run = Object.hasOwn(state, value.run) ? state[value.run] : {};
1682
- const previous = Object.hasOwn(run, value.name) ? run[value.name] : {};
1683
- let next;
1684
- if (value.kind === "connection.process" && value.connection) {
1685
- if (!previous.process && !value.connection.tools) return state;
1686
- const process = value.connection.tools ? value.connection : { ...previous.process, ...value.connection };
1687
- next = { ...previous, process };
1688
- } else if (value.kind === "connection.resource" && value.binding && value.attempt) {
1689
- next = { ...previous, resource: { binding: value.binding, attempt: value.attempt } };
1690
- } else return state;
1691
- return { ...state, [value.run]: { ...run, [value.name]: next } };
1692
- }
1693
- };
1694
- async function connectionStates(ctx) {
1695
- const state = await ctx.ledger.view(connectionStateView.id);
1696
- return Object.hasOwn(state, ctx.run.id) ? state[ctx.run.id] : {};
1697
- }
1698
-
1699
- // packages/sdk/src/integration.ts
1700
- var ApiError = class extends Error {
1701
- constructor(status, body, disposition = "uncertain") {
1702
- super(`${status}: ${body}`);
1703
- this.status = status;
1704
- this.body = body;
1705
- this.disposition = disposition;
1706
- this.name = "ApiError";
1707
- }
1708
- status;
1709
- body;
1710
- disposition;
1604
+ // packages/sdk/src/constal-api.ts
1605
+ var CONSTAL_API_CAPABILITY = "constal.api";
1606
+ var CONSTAL_API_VERSION = "1";
1607
+ var CONSTAL_API_OPERATIONS = [
1608
+ "describe",
1609
+ "query",
1610
+ "get",
1611
+ "relations",
1612
+ "explainPolicy",
1613
+ "plan",
1614
+ "apply",
1615
+ "observe"
1616
+ ];
1617
+ var CONSTAL_API_BOUNDS = {
1618
+ defaultPageSize: 50,
1619
+ maximumPageSize: 200,
1620
+ maximumRelationDepth: 3,
1621
+ maximumPlanOperations: 64,
1622
+ maximumInputBytes: 1048576,
1623
+ planTtlMs: 15 * 6e4
1711
1624
  };
1712
- var IntegrationRequestNotSent = class extends Error {
1713
- constructor(message2 = "integration request was not sent") {
1714
- super(message2);
1715
- this.name = "IntegrationRequestNotSent";
1716
- }
1625
+ var CONSTAL_API_QUERY_KINDS = [
1626
+ ...RESOURCE_KINDS,
1627
+ "analytics",
1628
+ "customer",
1629
+ "binding",
1630
+ "session",
1631
+ "run",
1632
+ "deployment",
1633
+ "documentation",
1634
+ "analytics-event",
1635
+ "namespace",
1636
+ "team-member",
1637
+ "team-invite",
1638
+ "api-key",
1639
+ "billing-account",
1640
+ "invoice",
1641
+ "subscription",
1642
+ "resource-contract",
1643
+ "dataset-draft",
1644
+ "dataset-case",
1645
+ "eval-score",
1646
+ "eval-sample",
1647
+ "eval-policy",
1648
+ "eval-suite",
1649
+ "eval-baseline",
1650
+ "eval-schedule",
1651
+ "training-job",
1652
+ "checkpoint",
1653
+ "training-provider",
1654
+ "training-model",
1655
+ "checkpoint-gateway",
1656
+ "credential-provider-package",
1657
+ "credential-consumer",
1658
+ "credential-use",
1659
+ "credential-event",
1660
+ "gateway-package",
1661
+ "rollout",
1662
+ "wait"
1663
+ ];
1664
+ var CONSTAL_API_GET_KINDS = CONSTAL_API_QUERY_KINDS;
1665
+ var CONSTAL_API_MODEL_TOOL_DESCRIPTIONS = {
1666
+ 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.",
1667
+ 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."
1717
1668
  };
1718
- var TerminalIntegrationFailure = class extends Error {
1719
- constructor(message2 = "integration operation failed terminally") {
1720
- super(message2);
1721
- this.name = "TerminalIntegrationFailure";
1722
- }
1669
+ var CONSTAL_API_GET_CRN_KINDS = [
1670
+ ...RESOURCE_KINDS,
1671
+ "analytics",
1672
+ "binding",
1673
+ "session",
1674
+ "run",
1675
+ "deployment"
1676
+ ];
1677
+ var CONSTAL_API_OBJECT_REF_CRN_KINDS = [...CONSTAL_API_GET_CRN_KINDS, "customer"];
1678
+ var boundedNameSchema = { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z][A-Za-z0-9._-]{0,127}$" };
1679
+ var namespaceSchema = {
1680
+ type: "string",
1681
+ minLength: 1,
1682
+ maxLength: 128,
1683
+ pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
1723
1684
  };
1724
- var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
1725
- function integrationEgressPolicy(value) {
1726
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
1727
- if (!source || !Array.isArray(source.rules) || source.rules.length > 128 || Object.keys(source).some((key) => key !== "rules")) {
1728
- throw new TypeError("integration egress policy is invalid");
1729
- }
1730
- const rules = source.rules.map((raw) => {
1731
- const rule = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
1732
- const paths = Number(rule?.pathPrefix !== void 0) + Number(rule?.pathExact !== void 0);
1733
- if (!rule || !Array.isArray(rule.operations) || rule.operations.length === 0 || rule.operations.length > 128 || rule.operations.some((operation) => typeof operation !== "string" || operation !== "*" && !OPERATION2.test(operation)) || typeof rule.origin !== "string" || paths !== 1 || !Array.isArray(rule.methods) || rule.methods.length === 0 || rule.methods.length > 8 || rule.methods.some((method) => typeof method !== "string" || !/^(?:GET|POST|PUT|PATCH|DELETE)$/u.test(method)) || Object.keys(rule).some((key) => !["operations", "origin", "pathPrefix", "pathExact", "methods"].includes(key))) {
1734
- throw new TypeError("integration egress rule is invalid");
1735
- }
1736
- let origin;
1737
- try {
1738
- origin = new URL(rule.origin);
1739
- } catch {
1740
- throw new TypeError("integration egress origin is invalid");
1741
- }
1742
- if (origin.protocol !== "https:" || origin.origin !== rule.origin || origin.username || origin.password) {
1743
- throw new TypeError("integration egress origin is invalid");
1744
- }
1745
- const path = String(rule.pathPrefix ?? rule.pathExact);
1746
- if (!path.startsWith("/") || path.includes("?") || path.includes("#")) throw new TypeError("integration egress path is invalid");
1747
- return rule;
1748
- });
1749
- return { rules };
1750
- }
1751
-
1752
- // packages/sdk/src/mcp-protocol.ts
1753
- var MCP_PROTOCOL_VERSION = "2025-06-18";
1754
- function record4(value) {
1755
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1756
- }
1757
- function message(value) {
1758
- const item = record4(value);
1759
- if (!item || item.jsonrpc !== "2.0" || item.method !== void 0 && typeof item.method !== "string" || item.id !== void 0 && item.id !== null && typeof item.id !== "string" && typeof item.id !== "number") {
1760
- throw new TerminalIntegrationFailure("MCP server returned an invalid JSON-RPC message");
1761
- }
1762
- return item;
1763
- }
1764
- function result(response) {
1765
- if (response.error) {
1766
- const code = typeof response.error.code === "number" || typeof response.error.code === "string" ? response.error.code : "unknown";
1767
- const detail = typeof response.error.message === "string" ? response.error.message : "MCP request failed";
1768
- throw new TerminalIntegrationFailure(`MCP ${code}: ${detail}`);
1769
- }
1770
- if (!Object.hasOwn(response, "result")) throw new TerminalIntegrationFailure("MCP JSON-RPC response has no result");
1771
- return response.result;
1772
- }
1773
- function initialized(value) {
1774
- const result2 = record4(value);
1775
- if (!result2 || typeof result2.protocolVersion !== "string" || !result2.protocolVersion) throw new TerminalIntegrationFailure("MCP initialize result is invalid");
1776
- return { protocolVersion: result2.protocolVersion, server: record4(result2.serverInfo) ?? {}, capabilities: record4(result2.capabilities) ?? {} };
1777
- }
1778
- async function tools(request, maximum) {
1779
- const tools2 = [], cursors = /* @__PURE__ */ new Set();
1780
- let cursor;
1781
- do {
1782
- const result2 = record4(await request("tools/list", cursor ? { cursor } : {}));
1783
- if (!result2 || !Array.isArray(result2.tools)) throw new TerminalIntegrationFailure("MCP tools/list result is invalid");
1784
- tools2.push(...result2.tools.map(tool));
1785
- if (maximum !== void 0 && tools2.length > maximum) throw new TerminalIntegrationFailure(`MCP server advertises more than ${maximum} tools`);
1786
- if (result2.nextCursor !== void 0 && typeof result2.nextCursor !== "string") throw new TerminalIntegrationFailure("MCP tools/list cursor is invalid");
1787
- cursor = result2.nextCursor ? result2.nextCursor : void 0;
1788
- if (cursor && cursors.has(cursor)) throw new TerminalIntegrationFailure("MCP server returned a repeated pagination cursor");
1789
- if (cursor) cursors.add(cursor);
1790
- } while (cursor);
1791
- if (new Set(tools2.map((tool2) => tool2.name)).size !== tools2.length) throw new TerminalIntegrationFailure("MCP server advertised duplicate tool names");
1792
- return tools2;
1793
- }
1794
- function tool(value) {
1795
- const tool2 = record4(value);
1796
- const inputSchema = record4(tool2?.inputSchema);
1797
- const outputSchema = tool2?.outputSchema === void 0 ? {} : record4(tool2.outputSchema);
1798
- if (!tool2 || typeof tool2.name !== "string" || !tool2.name || tool2.description !== void 0 && typeof tool2.description !== "string" || !inputSchema || outputSchema === null) throw new TerminalIntegrationFailure("MCP server advertised an invalid tool");
1799
- return {
1800
- ...tool2,
1801
- name: tool2.name,
1802
- description: typeof tool2.description === "string" ? tool2.description : "",
1803
- inputSchema,
1804
- outputSchema,
1805
- annotations: record4(tool2.annotations) ?? {}
1806
- };
1807
- }
1808
- function textContent(content2) {
1809
- const text2 = [];
1810
- for (const value of content2) {
1811
- const block = record4(value);
1812
- if (block?.type !== "text") continue;
1813
- if (typeof block.text !== "string") throw new TerminalIntegrationFailure("MCP tool returned an invalid text content block");
1814
- text2.push(block.text);
1815
- }
1816
- return text2;
1817
- }
1818
- function unwrapToolResult(value, outputSchema) {
1819
- const result2 = record4(value);
1820
- if (!result2) throw new TerminalIntegrationFailure("MCP tools/call result is invalid");
1821
- if (result2.isError !== void 0 && typeof result2.isError !== "boolean") {
1822
- throw new TerminalIntegrationFailure("MCP tools/call result has an invalid isError value");
1823
- }
1824
- const content2 = Array.isArray(result2.content) ? result2.content : null;
1825
- if (result2.isError === true) {
1826
- const message2 = content2 ? textContent(content2).join("\n").trim() : "";
1827
- throw new TerminalIntegrationFailure(message2 ? `MCP tool failed: ${message2}` : "MCP tool failed");
1828
- }
1829
- if (Object.hasOwn(result2, "structuredContent")) {
1830
- const structured = record4(result2.structuredContent);
1831
- if (!structured) throw new TerminalIntegrationFailure("MCP tool returned invalid structuredContent");
1832
- return structured;
1833
- }
1834
- if (!content2) throw new TerminalIntegrationFailure("MCP tool result has no content");
1835
- const text2 = textContent(content2);
1836
- if (content2.length === 1 && text2.length === 1) {
1837
- try {
1838
- return JSON.parse(text2[0]);
1839
- } catch {
1840
- if (Object.keys(outputSchema).length > 0) {
1841
- throw new TerminalIntegrationFailure("MCP tool result text is not valid JSON for its declared outputSchema");
1842
- }
1843
- return text2[0];
1844
- }
1845
- }
1846
- if (Object.keys(outputSchema).length > 0) {
1847
- throw new TerminalIntegrationFailure("MCP tool result has no structuredContent or single JSON text block for its declared outputSchema");
1848
- }
1849
- return content2;
1850
- }
1851
- var mcpProtocol = {
1852
- version: MCP_PROTOCOL_VERSION,
1853
- message,
1854
- result,
1855
- initialized,
1856
- tool,
1857
- tools,
1858
- toolResult: unwrapToolResult,
1859
- initialization: () => ({ protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "Constal", version: "1.0.0" } })
1860
- };
1861
-
1862
- // packages/sdk/src/mcp-process.ts
1863
- function initialMcpProcessState() {
1864
- return { offset: 0, protocolVersion: null, server: {}, capabilities: {}, toolsChanged: false };
1865
- }
1866
- var McpProcessError = class extends TerminalIntegrationFailure {
1867
- constructor(kind, message2) {
1868
- super(message2);
1869
- this.kind = kind;
1870
- this.name = "McpProcessError";
1871
- }
1872
- kind;
1685
+ var actionSchema = { type: "string", pattern: ACTION_PATTERN.source };
1686
+ var boundedIdSchema = { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9][A-Za-z0-9._~:-]{0,255}$" };
1687
+ var hashSchema = { type: "string", pattern: "^[a-f0-9]{64}$" };
1688
+ var stringListSchema = { type: "array", maxItems: 128, items: { type: "string", minLength: 1, maxLength: 256 } };
1689
+ 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: [
1690
+ {
1691
+ type: "object",
1692
+ required: ["kind", "namespace"],
1693
+ additionalProperties: false,
1694
+ properties: { kind: { const: "namespace" }, namespace: {
1695
+ ...namespaceSchema,
1696
+ description: "Exact authorized namespace. Do not infer it from an object name or repository."
1697
+ } }
1698
+ },
1699
+ { type: "object", required: ["kind"], additionalProperties: false, properties: { kind: { const: "tenant" } } }
1700
+ ] };
1701
+ 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}$`;
1702
+ var objectRefSchema = { type: "object", additionalProperties: false, properties: {
1703
+ kind: { enum: [...CONSTAL_API_GET_KINDS], description: "Exact lower-case object kind returned by a governed platform result." },
1704
+ id: { type: "string", minLength: 1, maxLength: 512 },
1705
+ crn: { anyOf: [{ type: "null" }, {
1706
+ type: "string",
1707
+ minLength: 1,
1708
+ maxLength: 2048,
1709
+ pattern: crnPattern(CONSTAL_API_OBJECT_REF_CRN_KINDS)
1710
+ }] },
1711
+ hash: { anyOf: [{ type: "null" }, hashSchema] },
1712
+ namespace: {
1713
+ type: ["string", "null"],
1714
+ maxLength: 128,
1715
+ pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
1716
+ },
1717
+ version: { type: ["string", "null"], maxLength: 128 }
1718
+ }, required: ["kind", "id", "namespace"] };
1719
+ var exactGetCrnSchema = {
1720
+ type: "string",
1721
+ minLength: 1,
1722
+ maxLength: 2048,
1723
+ description: "Exact addressable CRN obtained from governed platform evidence.",
1724
+ pattern: crnPattern(CONSTAL_API_GET_CRN_KINDS)
1873
1725
  };
1874
- function frame(parts, length) {
1875
- const bytes = new Uint8Array(length);
1876
- let offset = 0;
1877
- for (const part of parts) {
1878
- bytes.set(part, offset);
1879
- offset += part.length;
1880
- }
1881
- try {
1882
- return mcpProtocol.message(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)));
1883
- } catch {
1884
- throw new McpProcessError("protocol", "MCP process returned an invalid UTF-8 JSON-RPC frame");
1885
- }
1886
- }
1887
- function processMcp(process, state, ctx, options = {}) {
1888
- const earlierResponses = [];
1889
- const send = async (message2) => {
1890
- const data = `${JSON.stringify(message2)}
1891
- `;
1892
- const result2 = await process.write({ data }, options.timeoutMs === void 0 ? void 0 : { timeoutMs: options.timeoutMs });
1893
- if (result2.error || result2.written !== new TextEncoder().encode(data).length) {
1894
- throw new McpProcessError("write", "MCP request was not fully written to the process");
1895
- }
1896
- };
1897
- async function exchange(method, params) {
1898
- const id2 = crypto.randomUUID();
1899
- const deadline = options.timeoutMs === void 0 ? null : Date.now() + options.timeoutMs;
1900
- await send({ jsonrpc: "2.0", id: id2, method, params });
1901
- let offset = state.offset, parts = [], length = 0;
1902
- for (; ; ) {
1903
- const page = await process.read({
1904
- stream: "stdout",
1905
- offset,
1906
- ...options.timeoutMs === void 0 ? {} : { invoke: { timeoutMs: options.timeoutMs } }
1907
- });
1908
- const bytes = Uint8Array.from(atob(page.data), (character) => character.charCodeAt(0));
1909
- if (page.offset !== offset || page.nextOffset !== offset + bytes.length) throw new McpProcessError("protocol", "MCP process output range changed");
1910
- let start = 0;
1911
- while (start < bytes.length) {
1912
- const newline = bytes.indexOf(10, start), end = newline < 0 ? bytes.length : newline;
1913
- const part = bytes.subarray(start, end);
1914
- parts.push(part);
1915
- length += part.length;
1916
- if (newline < 0) break;
1917
- const message2 = frame(parts, length);
1918
- state.offset = offset + newline + 1;
1919
- parts = [];
1920
- length = 0;
1921
- start = newline + 1;
1922
- if (message2.method !== void 0) {
1923
- if (message2.id !== void 0) await send(message2.method === "ping" ? { jsonrpc: "2.0", id: message2.id, result: {} } : { jsonrpc: "2.0", id: message2.id, error: { code: -32601, message: "Client capability is not supported" } });
1924
- else if (message2.method === "notifications/tools/list_changed") state.toolsChanged = true;
1925
- } else if (message2.id === id2) return message2;
1926
- else earlierResponses.push(message2);
1927
- }
1928
- offset = page.nextOffset;
1929
- if (page.exited) throw new McpProcessError("closed", `MCP process exited before responding (exit ${page.exitCode ?? "unknown"})`);
1930
- const now = deadline === null ? null : Date.now();
1931
- if (deadline !== null && now >= deadline) throw new McpProcessError("timeout", `MCP request ${id2} timed out; its server-side outcome is unknown`);
1932
- if (bytes.length === 0) await ctx.await(`mcp-output:${process.id}:${id2}`, { timeout: 250, onTimeout: null, afterRun: "ignore" });
1933
- }
1934
- }
1935
- const request = async (method, params) => mcpProtocol.result(await exchange(method, params));
1936
- return {
1937
- state,
1938
- exchange,
1939
- request,
1940
- earlierResponses,
1941
- async initialize() {
1942
- const initialized2 = mcpProtocol.initialized(await request("initialize", mcpProtocol.initialization()));
1943
- if (initialized2.protocolVersion !== mcpProtocol.version) throw new TerminalIntegrationFailure(`MCP process selected unsupported protocol ${initialized2.protocolVersion}`);
1944
- Object.assign(state, initialized2);
1945
- await send({ jsonrpc: "2.0", method: "notifications/initialized" });
1946
- },
1947
- async tools() {
1948
- const tools2 = await mcpProtocol.tools(request);
1949
- state.toolsChanged = false;
1950
- return tools2;
1951
- }
1952
- };
1953
- }
1954
-
1955
- // packages/sdk/src/connection-process.ts
1956
- async function processConnections(ctx) {
1957
- return Object.fromEntries(Object.entries(await connectionStates(ctx)).flatMap(([name, state]) => state.process ? [[name, state.process]] : []));
1958
- }
1959
- function processDefinition(spec) {
1960
- return hashValue({ pool: spec.pool, command: spec.command });
1961
- }
1962
- async function save(ctx, name, connection, catalog2 = false) {
1963
- const { tools: _tools, ...progress } = connection;
1964
- await ctx.commit({ kind: "connection.process", run: ctx.run.id, name, connection: structuredClone(catalog2 ? connection : progress) }, { tier: "audit" });
1965
- return connection;
1966
- }
1967
- function clientOptions(spec) {
1968
- return spec.requestTimeoutMs === void 0 ? {} : { timeoutMs: spec.requestTimeoutMs };
1969
- }
1970
- function unavailable(connection) {
1971
- return { ...describeProcessConnection(connection), message: "The connection attempt failed. Its process and error remain available for diagnosis." };
1972
- }
1973
- function describeProcessConnection(connection) {
1974
- return structuredClone({
1975
- state: connection.state,
1976
- process: { id: connection.process, pool: connection.pool },
1977
- tools: connection.tools,
1978
- server: connection.protocol.server,
1979
- capabilities: connection.protocol.capabilities,
1980
- toolsChanged: connection.protocol.toolsChanged,
1981
- ...connection.error ? { error: connection.error } : {}
1982
- });
1983
- }
1984
- async function connectProcess(name, spec, ctx, options = {}) {
1985
- const states = await processConnections(ctx);
1986
- const previous = Object.hasOwn(states, name) ? states[name] : null;
1987
- const definition2 = await processDefinition(spec);
1988
- if (previous && previous.definition === definition2 && !options.restart) {
1989
- if (previous.state === "connected" && !options.refresh) return previous;
1990
- }
1991
- const box = await ctx.sandboxPool(spec.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
1992
- const reuse = previous?.state === "connected" && previous.definition === definition2 && !options.restart;
1993
- if (previous && previous.state !== "closed" && !reuse) {
1994
- const priorBox = previous.pool === spec.pool ? box : await ctx.sandboxPool(previous.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
1995
- await priorBox.process(previous.process).stop();
1996
- }
1997
- const process = reuse ? box.process(previous.process) : await box.startProcess(
1998
- spec.command,
1999
- spec.command.timeoutMs === void 0 ? void 0 : { timeoutMs: spec.command.timeoutMs }
2000
- );
2001
- const connection = reuse ? structuredClone(previous) : {
2002
- definition: definition2,
2003
- pool: spec.pool,
2004
- process: process.id,
2005
- state: "connected",
2006
- protocol: initialMcpProcessState(),
2007
- tools: []
2008
- };
2009
- const client = processMcp(process, connection.protocol, ctx, clientOptions(spec));
2010
- try {
2011
- if (!reuse) await client.initialize();
2012
- connection.tools = await client.tools();
2013
- connection.error = null;
2014
- } catch (error) {
2015
- if (!(error instanceof TerminalIntegrationFailure)) throw error;
2016
- connection.state = "failed";
2017
- connection.error = { name: error.name, message: error.message };
2018
- }
2019
- return save(ctx, name, connection, true);
2020
- }
2021
- async function invokeProcessConnection(name, spec, operation, args, ctx) {
2022
- const states = await processConnections(ctx);
2023
- let connection = Object.hasOwn(states, name) ? structuredClone(states[name]) : null;
2024
- if (!connection || connection.state !== "connected" || connection.definition !== await processDefinition(spec)) {
2025
- connection = await connectProcess(name, spec, ctx);
2026
- }
2027
- if (connection.state !== "connected") return unavailable(connection);
2028
- if (!connection.tools.some((tool2) => tool2.name === operation)) throw new TypeError(`MCP tool is not in the discovered catalog: ${operation}`);
2029
- const box = await ctx.sandboxPool(connection.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
2030
- const client = processMcp(box.process(connection.process), connection.protocol, ctx, clientOptions(spec));
2031
- let response;
2032
- try {
2033
- response = await client.exchange("tools/call", { name: operation, arguments: args });
2034
- } catch (error) {
2035
- if (!(error instanceof TerminalIntegrationFailure)) throw error;
2036
- connection.state = error instanceof McpProcessError && error.kind === "timeout" ? "connected" : "failed";
2037
- connection.error = { name: error.name, message: error.message };
2038
- await save(ctx, name, connection);
2039
- return describeProcessConnection(connection);
2040
- }
2041
- connection.error = null;
2042
- await save(ctx, name, connection);
2043
- const result2 = mcpProtocol.result(response);
2044
- if (!client.earlierResponses.length) return result2;
2045
- const value = result2 && typeof result2 === "object" && !Array.isArray(result2) ? result2 : { result: result2 };
2046
- const metadata2 = value._meta && typeof value._meta === "object" && !Array.isArray(value._meta) ? value._meta : {};
2047
- return { ...value, _meta: { ...metadata2, "ai.constal/earlierResponses": client.earlierResponses } };
2048
- }
2049
- async function disconnectProcess(name, ctx) {
2050
- const states = await processConnections(ctx);
2051
- const connection = Object.hasOwn(states, name) ? states[name] : null;
2052
- if (!connection || connection.state === "closed") return { name, state: "closed" };
2053
- const box = await ctx.sandboxPool(connection.pool).createSandbox(ctx.run.agent.crn, ctx.run.session);
2054
- await box.process(connection.process).stop();
2055
- const closed = await save(ctx, name, { ...connection, state: "closed" });
2056
- return { name, ...describeProcessConnection(closed) };
2057
- }
2058
-
2059
- // packages/sdk/src/connections.ts
2060
- function object3(value) {
2061
- return !!value && typeof value === "object" && !Array.isArray(value);
2062
- }
2063
- function definition(value) {
2064
- if (!object3(value) || value.package === void 0 && value.binding === void 0 && value.process === void 0 || value.package !== void 0 && !object3(value.package) || value.config !== void 0 && !object3(value.config) || value.description !== void 0 && typeof value.description !== "string") throw new TypeError("Connection definition is invalid");
2065
- if (value.binding !== void 0) scopedBindingKey(value.binding);
2066
- if (value.process !== void 0 && (!object3(value.process) || typeof value.process.pool !== "string" || !object3(value.process.command) || typeof value.process.command.cmd !== "string" || !value.process.command.cmd || value.process.requestTimeoutMs !== void 0 && (!Number.isSafeInteger(value.process.requestTimeoutMs) || Number(value.process.requestTimeoutMs) <= 0) || value.binding !== void 0 || value.package !== void 0 || value.config !== void 0 || value.credentials !== void 0)) throw new TypeError("Process connection definition is invalid");
2067
- return { ...value, ...value.credentials === void 0 ? {} : { credentials: resourceCredentialBindings(value.credentials) } };
2068
- }
2069
- function suppliedSource(values) {
2070
- return {
2071
- async list() {
2072
- return Promise.all(Object.entries(values).map(async ([name, raw]) => {
2073
- const value = definition(raw);
2074
- const { description: _description, ...settings } = value;
2075
- return {
2076
- name,
2077
- ...value.process ? { transport: "stdio" } : { binding: value.binding ?? `connection-${(await hashValue({ name, value: settings })).slice(0, 40)}` },
2078
- ...value.description === void 0 ? {} : { description: value.description }
2079
- };
2080
- }));
1726
+ var CONSTAL_API_OPERATION_SCHEMAS = {
1727
+ describe: { type: "object", additionalProperties: false, properties: {
1728
+ domains: stringListSchema,
1729
+ kinds: stringListSchema,
1730
+ operations: stringListSchema,
1731
+ include: {
1732
+ type: "array",
1733
+ maxItems: 5,
1734
+ uniqueItems: true,
1735
+ items: { enum: ["objects", "operations", "relations", "schemas", "docs"] }
2081
1736
  },
2082
- async load(name) {
2083
- if (!Object.hasOwn(values, name)) throw new TypeError(`Connection is not configured: ${name}`);
2084
- return definition(values[name]);
1737
+ cursor: { type: "string", maxLength: 4096 },
1738
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize }
1739
+ } },
1740
+ query: {
1741
+ type: "object",
1742
+ required: ["kind", "scope"],
1743
+ additionalProperties: false,
1744
+ 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.",
1745
+ properties: {
1746
+ kind: { enum: [...CONSTAL_API_QUERY_KINDS], description: "Exact queryable kind. Never guess a kind or change its casing." },
1747
+ scope: scopeSchema,
1748
+ filter: { type: "object", description: "Optional catalog-advertised filter expression." },
1749
+ search: { type: "string", maxLength: 512 },
1750
+ order: { type: "array", maxItems: 8, items: {
1751
+ type: "object",
1752
+ required: ["field", "direction"],
1753
+ additionalProperties: false,
1754
+ properties: { field: boundedNameSchema, direction: { enum: ["ascending", "descending"] } }
1755
+ } },
1756
+ fields: stringListSchema,
1757
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1758
+ cursor: { type: "string", maxLength: 4096 },
1759
+ asOf: { type: "integer", minimum: 0 },
1760
+ range: { type: "object", required: ["start", "end"], additionalProperties: false, properties: {
1761
+ start: { type: "integer", minimum: 0 },
1762
+ end: { type: "integer", minimum: 0 }
1763
+ } }
2085
1764
  }
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);
1765
+ },
1766
+ get: {
1767
+ type: "object",
1768
+ required: ["ref"],
1769
+ additionalProperties: false,
1770
+ description: "Read one addressable object using a complete ref returned by query, relations, runtime inspection, or a governed receipt. Do not synthesize refs.",
1771
+ properties: {
1772
+ ref: {
1773
+ description: "Copy a complete object ref from governed output, or supply an exact supported CRN.",
1774
+ anyOf: [objectRefSchema, {
1775
+ type: "object",
1776
+ required: ["crn"],
1777
+ additionalProperties: false,
1778
+ properties: { crn: exactGetCrnSchema, hash: hashSchema }
1779
+ }]
1780
+ },
1781
+ fields: stringListSchema,
1782
+ page: { type: "object", additionalProperties: false, properties: {
1783
+ cursor: { type: "string", maxLength: 4096 },
1784
+ limit: { type: "integer", minimum: 1, maximum: 500 }
1785
+ } }
2105
1786
  }
2106
- const states = descriptions.length ? await connectionStates(ctx) : {};
2107
- return ctx.step("connection-index", async () => {
2108
- const resources = ctx.capabilities().resources;
2109
- return descriptions.map((item) => {
2110
- const saved = Object.hasOwn(states, item.name) ? states[item.name] : void 0;
2111
- const local = item.transport === "stdio" ? saved?.process : null;
2112
- if (local) return { ...item, ...describeProcessConnection(local) };
2113
- const lastAttempt = item.binding && saved?.resource?.binding === item.binding ? saved.resource.attempt : void 0;
2114
- const observed = lastAttempt && lastAttempt.state !== "bound" ? lastAttempt.state : "configured";
2115
- return {
2116
- ...item,
2117
- state: item.binding && Object.hasOwn(resources, item.binding) ? "bound" : observed,
2118
- ...lastAttempt ? { lastAttempt } : {},
2119
- ...item.binding && Object.hasOwn(resources, item.binding) ? { resource: resources[item.binding] } : {}
2120
- };
2121
- });
2122
- });
2123
- }
2124
- async function remember(ctx, selected, attempt) {
2125
- await ctx.commit({
2126
- kind: "connection.resource",
2127
- run: ctx.run.id,
2128
- name: selected.name,
2129
- binding: selected.binding,
2130
- attempt
2131
- }, { tier: "audit" });
2132
- return { ...selected, ...attempt, lastAttempt: attempt };
2133
- }
2134
- const tools2 = {
2135
- connection_list: {
2136
- name: "connection_list",
2137
- version: "1",
2138
- maxEffect: "read-only",
2139
- needs: source.needs ?? [],
2140
- description: "List configured connections and the Resource bindings currently available in this Run.",
2141
- schema: { type: "object", properties: {}, additionalProperties: false },
2142
- async run(_args, ctx) {
2143
- return index(ctx);
2144
- }
2145
- },
2146
- connection_connect: {
2147
- name: "connection_connect",
2148
- version: "1",
2149
- maxEffect: "non-idempotent",
2150
- needs: source.needs ?? [],
2151
- description: "Connect a configured server and discover its tools. Local MCP keeps one process per connection; remote connections use Resource bindings. Explicit restart replaces a local process; refresh reloads its catalog. Policy governs the underlying operations.",
2152
- schema: { type: "object", required: ["name"], additionalProperties: false, properties: { name: { type: "string", minLength: 1 }, restart: { type: "boolean" }, refresh: { type: "boolean" } } },
2153
- async run(args, ctx) {
2154
- const selected = (await index(ctx)).find((item) => item.name === args.name);
2155
- if (!selected) throw new TypeError(`Connection is not configured: ${args.name}`);
2156
- if (selected.state === "bound") return selected;
2157
- const loaded = await source.load(args.name, ctx);
2158
- const spec = await ctx.step("connection-definition", async () => definition(loaded));
2159
- if (spec.process) return { ...selected, ...describeProcessConnection(await connectProcess(args.name, spec.process, ctx, args)) };
2160
- if (!selected.binding) throw new TypeError("A Resource connection requires a binding");
2161
- if (!spec.package) return remember(ctx, selected, { state: "unavailable", message: "The configured binding is absent and has no installation definition." });
2162
- if (!ctx.resources[api]) return remember(ctx, selected, { state: "unavailable", message: "The API binding needed for installation is unavailable." });
2163
- if (spec.binding !== void 0 && spec.binding !== selected.binding) throw new TypeError("Connection binding changed between listing and loading");
2164
- const identity = await hashValue({ run: ctx.run.id, name: args.name, binding: selected.binding, spec });
2165
- const id2 = `connection-${identity.slice(0, 40)}`;
2166
- const installation = await change(ctx, api, args.name, "gateway.install", {
2167
- namespace: ctx.run.namespace,
2168
- id: id2,
2169
- package: spec.package,
2170
- config: spec.config ?? {},
2171
- credentials: spec.credentials ?? {}
2172
- }, `install-${identity}`);
2173
- if (installation.state !== "succeeded") return remember(ctx, selected, { state: "failed", stage: "installation", installation });
2174
- const result2 = installation.operations.find((item) => item.operation === "gateway.install")?.result;
2175
- const resource2 = object3(result2) && object3(result2.data) ? result2.data : result2;
2176
- if (!object3(resource2) || typeof resource2.crn !== "string" || typeof resource2.hash !== "string") {
2177
- throw new TypeError("Connection installation returned no Resource identity");
2178
- }
2179
- const pin = { crn: resource2.crn, hash: resource2.hash };
2180
- const attachment = await change(ctx, api, args.name, "run.rebind", {
2181
- namespace: ctx.run.namespace,
2182
- agent: ctx.run.agent.id,
2183
- session: ctx.run.session,
2184
- run: ctx.run.id,
2185
- request: { addBindings: { [selected.binding]: pin } }
2186
- }, `attach-${identity}`);
2187
- if (attachment.state !== "succeeded") return remember(ctx, selected, { state: "failed", stage: "attachment", installation, attachment });
2188
- await ctx.commit({
2189
- kind: "connection.attachment",
2190
- name: args.name,
2191
- binding: selected.binding,
2192
- resource: pin,
2193
- installation: installation.id,
2194
- attachment: attachment.id
2195
- }, { tier: "audit" });
2196
- const current = await ctx.step("connection-attached", async () => ctx.capabilities().resources[selected.binding] ?? null);
2197
- if (!current || current.crn !== pin.crn || current.hash !== pin.hash) {
2198
- return remember(ctx, selected, { state: "unavailable", message: "The requested connection is not present in the applied Run snapshot.", installation, attachment });
1787
+ },
1788
+ relations: { type: "object", required: ["start"], additionalProperties: false, properties: {
1789
+ start: { anyOf: [objectRefSchema, {
1790
+ type: "object",
1791
+ required: ["crn"],
1792
+ additionalProperties: false,
1793
+ properties: { crn: { type: "string", minLength: 1, maxLength: 2048 }, hash: hashSchema }
1794
+ }] },
1795
+ direction: { enum: ["outgoing", "incoming", "both"] },
1796
+ types: stringListSchema,
1797
+ depth: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumRelationDepth },
1798
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1799
+ cursor: { type: "string", maxLength: 4096 }
1800
+ } },
1801
+ explainPolicy: { type: "object", required: ["action", "resource"], additionalProperties: false, properties: {
1802
+ principal: { anyOf: [
1803
+ { type: "string", maxLength: 2048 },
1804
+ { type: "object", required: ["roles", "scopes"], additionalProperties: false, properties: {
1805
+ name: { type: "string", maxLength: 2048 },
1806
+ roles: {
1807
+ type: "array",
1808
+ maxItems: 64,
1809
+ uniqueItems: true,
1810
+ items: { type: "string", minLength: 1, maxLength: 2048 }
1811
+ },
1812
+ scopes: {
1813
+ type: "array",
1814
+ maxItems: 256,
1815
+ uniqueItems: true,
1816
+ items: { type: "string", pattern: "^(?:\\*|[a-z][a-z0-9-]{0,63}:(?:[a-z][a-z0-9-]{0,63}|\\*))$" }
2199
1817
  }
2200
- return { ...await remember(ctx, selected, { state: "bound", installation, attachment }), resource: current };
2201
- }
2202
- },
2203
- connection_invoke: {
2204
- name: "connection_invoke",
2205
- version: "1",
2206
- maxEffect: "non-idempotent",
2207
- needs: source.needs ?? [],
2208
- description: "Call an operation on a configured connection. Local MCP connects lazily and keeps server state across calls; inspect its discovered tools for operation names and arguments.",
2209
- schema: { type: "object", required: ["name", "operation", "arguments"], additionalProperties: false, properties: {
2210
- name: { type: "string", minLength: 1 },
2211
- operation: { type: "string", minLength: 1 },
2212
- arguments: {}
2213
- } },
2214
- async run(args, ctx) {
2215
- const selected = (await index(ctx)).find((item) => item.name === args.name);
2216
- if (!selected) throw new TypeError(`Connection is not configured: ${args.name}`);
2217
- const loaded = await source.load(args.name, ctx);
2218
- const spec = await ctx.step("connection-definition", async () => definition(loaded));
2219
- if (spec.process) return invokeProcessConnection(args.name, spec.process, args.operation, args.arguments, ctx);
2220
- if (selected.state !== "bound") {
2221
- const connected = await tools2.connection_connect.run({ name: args.name }, ctx);
2222
- if (connected.state !== "bound") return connected;
1818
+ } }
1819
+ ] },
1820
+ action: actionSchema,
1821
+ resource: { type: "string", minLength: 1, maxLength: 2048 },
1822
+ context: { type: "object" },
1823
+ arguments: {},
1824
+ at: { type: "object", required: ["run"], additionalProperties: false, properties: {
1825
+ run: {
1826
+ type: "object",
1827
+ required: ["namespace", "agent", "session", "run"],
1828
+ additionalProperties: false,
1829
+ properties: {
1830
+ namespace: boundedNameSchema,
1831
+ agent: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]{0,62}$" },
1832
+ session: boundedIdSchema,
1833
+ run: boundedIdSchema
2223
1834
  }
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
1835
  }
1836
+ } }
1837
+ } },
1838
+ plan: { type: "object", required: ["objective", "operations"], additionalProperties: false, properties: {
1839
+ objective: { type: "string", minLength: 1, maxLength: 8192 },
1840
+ validateOnly: { type: "boolean" },
1841
+ operations: {
1842
+ type: "array",
1843
+ minItems: 1,
1844
+ maxItems: CONSTAL_API_BOUNDS.maximumPlanOperations,
1845
+ items: { type: "object", required: ["operation", "input"], additionalProperties: false, properties: {
1846
+ id: boundedIdSchema,
1847
+ operation: boundedNameSchema,
1848
+ target: { type: "string", maxLength: 2048 },
1849
+ input: {},
1850
+ expectedCurrentHash: { anyOf: [{ type: "null" }, hashSchema] },
1851
+ dependsOn: { type: "array", maxItems: 64, items: boundedIdSchema }
1852
+ } }
2240
1853
  }
2241
- };
2242
- return { index, tools: tools2, views: [connectionStateView] };
2243
- }
1854
+ } },
1855
+ apply: { type: "object", required: ["plan", "eventId"], additionalProperties: false, properties: {
1856
+ plan: {
1857
+ type: "object",
1858
+ required: ["id", "hash"],
1859
+ additionalProperties: false,
1860
+ properties: { id: boundedIdSchema, hash: hashSchema }
1861
+ },
1862
+ eventId: boundedIdSchema
1863
+ } },
1864
+ observe: { type: "object", required: ["id"], additionalProperties: false, properties: { id: boundedIdSchema } }
1865
+ };
2244
1866
 
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
- }
1867
+ // packages/sdk/src/artifact-limits.ts
1868
+ var ARTIFACT_MAX_BYTES = 5 * 1024 ** 3;
2255
1869
 
2256
- // packages/sdk/src/policy-governance.ts
2257
- var SANDBOX_CONTRACT = {
1870
+ // packages/sdk/src/sandbox-policy-contract.ts
1871
+ var SANDBOX_CONTRACT_REF = {
2258
1872
  id: "constal.sandbox-pool",
2259
- version: "1",
2260
- hash: "566d919e8bc85fc657c691baab034524ad71e5bd01d9ff8a50d336874423362c"
2261
- };
2262
- var MODEL_CONTRACT = {
2263
- id: "constal.model",
2264
- version: "1",
2265
- hash: "76dd0da40da46adabb6837f911b25ed6f675c965e5d4d919077ee9c3945fbca7"
2266
- };
2267
- var UI_CONTRACT = {
2268
- id: "constal.ui",
2269
- version: "1",
2270
- hash: "133f0ab76ca2f1435dfbaa151652cfc79926ea5237c0892d0c4d3b96d7bb6f48"
1873
+ version: "2",
1874
+ hash: "69157b4e169275334de93ce0d24ffcdfe982c021ca67499ece3a173db25f4d16"
2271
1875
  };
2272
- var sandboxSchema = {
1876
+ var SANDBOX_CONTROLS_SCHEMA = {
2273
1877
  type: "object",
2274
1878
  additionalProperties: false,
2275
1879
  properties: {
@@ -2278,7 +1882,7 @@ var sandboxSchema = {
2278
1882
  disk_gib: { type: "number", minimum: 0, maximum: 1024 },
2279
1883
  idle_stop_ms: { type: "integer", minimum: 1e3, maximum: 864e5 },
2280
1884
  max_concurrent_commands: { type: "integer", minimum: 1, maximum: 1024 },
2281
- max_file_bytes: { type: "integer", minimum: 1, maximum: 16777216 },
1885
+ max_file_bytes: { type: "integer", minimum: 1, maximum: ARTIFACT_MAX_BYTES },
2282
1886
  memory_gib: { type: "number", exclusiveMinimum: 0, maximum: 1024 },
2283
1887
  network_cidrs: { type: "array", minItems: 1, maxItems: 1024, items: { type: "string" } },
2284
1888
  network_domains: { type: "array", minItems: 1, maxItems: 1024, items: { type: "string" } },
@@ -2288,6 +1892,20 @@ var sandboxSchema = {
2288
1892
  permitted_paths: { type: "array", minItems: 1, maxItems: 1024, items: { type: "string" } }
2289
1893
  }
2290
1894
  };
1895
+
1896
+ // packages/sdk/src/policy-governance.ts
1897
+ var SANDBOX_CONTRACT = SANDBOX_CONTRACT_REF;
1898
+ var MODEL_CONTRACT = {
1899
+ id: "constal.model",
1900
+ version: "1",
1901
+ hash: "76dd0da40da46adabb6837f911b25ed6f675c965e5d4d919077ee9c3945fbca7"
1902
+ };
1903
+ var UI_CONTRACT = {
1904
+ id: "constal.ui",
1905
+ version: "1",
1906
+ hash: "133f0ab76ca2f1435dfbaa151652cfc79926ea5237c0892d0c4d3b96d7bb6f48"
1907
+ };
1908
+ var sandboxSchema = SANDBOX_CONTROLS_SCHEMA;
2291
1909
  var modelSchema = { type: "object", additionalProperties: false, properties: {
2292
1910
  max_input_tokens: { type: "integer", minimum: 1, maximum: 1048576 },
2293
1911
  max_output_tokens: { type: "integer", minimum: 1, maximum: 1048576 },
@@ -2327,1424 +1945,1329 @@ function validatePolicyGovernanceConstraint(value) {
2327
1945
  limit(value.contract, [value.meter], value);
2328
1946
  }
2329
1947
 
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;
1948
+ // packages/sdk/src/authorization.ts
1949
+ var MAX_CONSTRAINTS = 64;
1950
+ var MAX_OUTCOME_BYTES = 65536;
1951
+ var MAX_REASON_BYTES = 1024;
1952
+ var DENIAL_CODE = /^[a-z][a-z0-9._-]{0,127}$/u;
1953
+ var encoder4 = new TextEncoder();
1954
+ function record4(value) {
1955
+ return !!value && typeof value === "object" && !Array.isArray(value);
2343
1956
  }
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`);
1957
+ function requiredString2(value, path, maximum = 1024) {
1958
+ if (typeof value !== "string" || value.length === 0 || encoder4.encode(value).byteLength > maximum) {
1959
+ throw new TypeError(`${path} must be a bounded non-empty string`);
2347
1960
  }
2348
- return Number(value);
2349
1961
  }
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`);
1962
+ function exactKeys2(value, allowed, required2, path) {
1963
+ if (Object.keys(value).some((key) => !allowed.includes(key)) || required2.some((key) => !Object.hasOwn(value, key))) {
1964
+ throw new TypeError(`${path} has invalid keys`);
2353
1965
  }
2354
- return value;
2355
1966
  }
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;
1967
+ function scalar(value) {
1968
+ return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
2362
1969
  }
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");
1970
+ function validateGrant(grant, path) {
1971
+ 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) {
1972
+ throw new TypeError(`${path} is invalid`);
2368
1973
  }
2369
- return candidate;
1974
+ exactKeys2(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
1975
+ grant.actions.forEach(actionPattern);
1976
+ grant.resources.forEach(resourcePattern);
2370
1977
  }
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");
1978
+ function validatePolicyConstraint(constraint, path = "constraint") {
1979
+ if (!constraint || typeof constraint !== "object" || Array.isArray(constraint) || typeof constraint.kind !== "string") {
1980
+ throw new TypeError(`${path} is invalid`);
2376
1981
  }
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");
1982
+ const source = constraint;
1983
+ if (constraint.kind === "resource-controls" || constraint.kind === "admission-limit") {
1984
+ try {
1985
+ validatePolicyGovernanceConstraint(constraint);
1986
+ } catch (error) {
1987
+ throw new TypeError(`${path} is invalid: ${error instanceof Error ? error.message : String(error)}`);
2382
1988
  }
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");
1989
+ return;
2387
1990
  }
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`);
1991
+ if (constraint.kind === "arguments") {
1992
+ exactKeys2(source, ["kind", "schema"], ["kind", "schema"], path);
1993
+ if (!record4(constraint.schema) || validateJsonSchemaDefinition(constraint.schema)) throw new TypeError(`${path}.schema is invalid`);
1994
+ return;
2399
1995
  }
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`);
1996
+ if (constraint.kind === "context") {
1997
+ exactKeys2(source, ["kind", "equals"], ["kind", "equals"], path);
1998
+ 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))) {
1999
+ throw new TypeError(`${path}.equals is invalid`);
2000
+ }
2001
+ return;
2406
2002
  }
2407
- return candidate;
2408
- }
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;
2003
+ if (constraint.kind === "credential-binding") {
2004
+ exactKeys2(source, ["kind", "source", "consumer"], ["kind", "source", "consumer"], path);
2005
+ credentialName(constraint.source);
2006
+ parseResourceName(constraint.consumer);
2007
+ return;
2008
+ }
2009
+ throw new TypeError(`${path}.kind is invalid`);
2452
2010
  }
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");
2011
+ function validateConstraints(value, path, required2) {
2012
+ if (value === void 0 && !required2) return [];
2013
+ if (!Array.isArray(value) || required2 && value.length === 0 || value.length > MAX_CONSTRAINTS) {
2014
+ throw new TypeError(`${path} is invalid`);
2457
2015
  }
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
- };
2016
+ value.forEach((constraint, index) => validatePolicyConstraint(constraint, `${path}[${index}]`));
2017
+ return value;
2018
+ }
2019
+ function policyOutcome(value) {
2020
+ if (!record4(value) || typeof value.kind !== "string") throw new TypeError("Policy outcome is invalid");
2021
+ if (value.kind === "allow") exactKeys2(value, ["kind"], ["kind"], "Policy allow outcome");
2022
+ else if (value.kind === "deny") {
2023
+ exactKeys2(value, ["kind", "code", "reason"], ["kind", "code"], "Policy deny outcome");
2024
+ if (typeof value.code !== "string" || !DENIAL_CODE.test(value.code)) throw new TypeError("Policy denial code is invalid");
2025
+ if (value.reason !== void 0) requiredString2(value.reason, "Policy denial reason", MAX_REASON_BYTES);
2026
+ } else if (value.kind === "constrain") {
2027
+ exactKeys2(value, ["kind", "constraints"], ["kind", "constraints"], "Policy constrain outcome");
2028
+ validateConstraints(value.constraints, "Policy constraints", true);
2029
+ } else if (value.kind === "substitute") {
2030
+ exactKeys2(value, ["kind", "value", "constraints"], ["kind", "value"], "Policy substitute outcome");
2031
+ canonicalJson(value.value);
2032
+ validateConstraints(value.constraints, "Policy constraints", false);
2033
+ } else if (value.kind === "require-approval") {
2034
+ exactKeys2(value, ["kind", "reason", "constraints"], ["kind"], "Policy approval outcome");
2035
+ if (value.reason !== void 0) requiredString2(value.reason, "Policy approval reason", MAX_REASON_BYTES);
2036
+ validateConstraints(value.constraints, "Policy constraints", false);
2037
+ } else if (value.kind === "grant") {
2038
+ exactKeys2(value, ["kind", "grant"], ["kind", "grant"], "Policy grant outcome");
2039
+ validateGrant(value.grant, "Policy grant");
2040
+ } else throw new TypeError("Policy outcome kind is invalid");
2041
+ if (encoder4.encode(canonicalJson(value)).byteLength > MAX_OUTCOME_BYTES) throw new TypeError("Policy outcome is oversized");
2042
+ return value;
2465
2043
  }
2466
- function renderTrainingCompletion(input, expected) {
2467
- const text2 = (value) => typeof value === "string" ? value : canonicalJson(value);
2468
- return { prompt: `Input:
2469
- ${text2(input)}
2470
2044
 
2471
- Response:
2472
- `, completion: expected === void 0 || expected === null ? null : text2(expected) };
2045
+ // packages/sdk/src/policy.ts
2046
+ var ID2 = /^[a-z0-9][a-z0-9-]{0,62}$/u;
2047
+ var VERSION3 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
2048
+ function policy(definition) {
2049
+ 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");
2050
+ return Object.freeze(definition);
2051
+ }
2052
+ async function evaluatePolicyDefinition(definition, input) {
2053
+ return policyOutcome(await definition.evaluate(input));
2473
2054
  }
2474
2055
 
2475
- // packages/sdk/src/model.ts
2476
- var MODEL_COMPLETION_CAPABILITY = {
2477
- id: "constal.model-completion",
2478
- version: "1",
2479
- hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
2056
+ // packages/sdk/src/table.ts
2057
+ var identifier = { type: "string", pattern: "^[a-zA-Z_][a-zA-Z0-9_.-]{0,127}$", maxLength: 128 };
2058
+ var tableName = { type: "string", pattern: "^[a-z0-9][a-z0-9._-]{0,127}$", maxLength: 128 };
2059
+ var branchName = { type: "string", pattern: "^[a-z0-9][a-z0-9._/-]{0,127}$", maxLength: 128 };
2060
+ var hash2 = { type: "string", pattern: "^[a-f0-9]{64}$" };
2061
+ var scalar2 = { type: ["string", "number", "integer", "boolean", "null"], maxLength: 4096 };
2062
+ var TABLE_DESCRIBE_SCHEMA = {
2063
+ type: "object",
2064
+ required: ["table"],
2065
+ additionalProperties: false,
2066
+ properties: {
2067
+ table: tableName,
2068
+ branch: branchName,
2069
+ snapshot: hash2,
2070
+ stageId: hash2,
2071
+ waitMs: { type: "integer", minimum: 0, maximum: 25e3 }
2072
+ }
2480
2073
  };
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");
2074
+ var filterSchema = {
2075
+ type: "object",
2076
+ required: ["field", "op", "value"],
2077
+ additionalProperties: false,
2078
+ properties: {
2079
+ field: identifier,
2080
+ op: { type: "string", enum: ["eq", "ne", "gt", "gte", "lt", "lte", "in", "between"] },
2081
+ value: { anyOf: [scalar2, { type: "array", minItems: 1, maxItems: 100, items: scalar2 }] }
2520
2082
  }
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");
2083
+ };
2084
+ var TABLE_QUERY_SCHEMA = {
2085
+ type: "object",
2086
+ required: ["table", "snapshot", "query"],
2087
+ additionalProperties: false,
2088
+ properties: {
2089
+ table: tableName,
2090
+ branch: branchName,
2091
+ snapshot: hash2,
2092
+ query: {
2093
+ type: "object",
2094
+ additionalProperties: false,
2095
+ properties: {
2096
+ select: { type: "array", maxItems: 64, uniqueItems: true, items: identifier },
2097
+ where: { type: "array", maxItems: 32, items: filterSchema },
2098
+ groupBy: { type: "array", maxItems: 16, uniqueItems: true, items: identifier },
2099
+ aggregates: { type: "array", maxItems: 32, items: {
2100
+ type: "object",
2101
+ required: ["fn", "as"],
2102
+ additionalProperties: false,
2103
+ properties: {
2104
+ fn: { type: "string", enum: ["count", "sum", "avg", "min", "max"] },
2105
+ field: identifier,
2106
+ as: identifier
2107
+ }
2108
+ } },
2109
+ orderBy: { type: "array", maxItems: 8, items: {
2110
+ type: "object",
2111
+ required: ["field", "direction"],
2112
+ additionalProperties: false,
2113
+ properties: { field: identifier, direction: { type: "string", enum: ["asc", "desc"] } }
2114
+ } },
2115
+ limit: { type: "integer", minimum: 1, maximum: 1e3 }
2116
+ }
2117
+ }
2526
2118
  }
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`);
2119
+ };
2120
+ function validateStageOutputSpec(value, path = "$.output") {
2121
+ if (!value || typeof value !== "object" || Array.isArray(value)) return `${path} must be an object`;
2122
+ const output = value;
2123
+ const extra = Object.keys(output).find((key) => key !== "schema" && key !== "sortOrder");
2124
+ if (extra) return `${path}.${extra} is not allowed`;
2125
+ if (!Object.hasOwn(output, "schema")) return `${path}.schema is required`;
2126
+ const schemaError = validateJsonSchemaDefinition(output.schema, `${path}.schema`);
2127
+ if (schemaError) return schemaError;
2128
+ const sortOrder = output.sortOrder ?? [];
2129
+ if (!Array.isArray(sortOrder) || sortOrder.length > 64) return `${path}.sortOrder is invalid`;
2130
+ const keys = /* @__PURE__ */ new Set();
2131
+ for (const [index, raw] of sortOrder.entries()) {
2132
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return `${path}.sortOrder[${index}] is invalid`;
2133
+ const field2 = raw;
2134
+ 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)) {
2135
+ return `${path}.sortOrder[${index}] is invalid`;
2136
+ }
2137
+ keys.add(field2.key);
2529
2138
  }
2530
- return options;
2139
+ return null;
2531
2140
  }
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
- };
2141
+ function stageOutput(value) {
2142
+ const error = validateStageOutputSpec(value);
2143
+ if (error) throw new TypeError(error);
2144
+ return value;
2542
2145
  }
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");
2547
- }
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");
2146
+ var tableDescribe = {
2147
+ name: "table_describe",
2148
+ version: "1",
2149
+ description: "Inspect the schema and identity of one exact, queryable Table snapshot before querying it.",
2150
+ schema: TABLE_DESCRIBE_SCHEMA,
2151
+ maxEffect: "read-only",
2152
+ needs: [{ binding: "table_catalog", kind: "service", ops: ["describe"] }],
2153
+ async run(args, ctx) {
2154
+ return ctx.invoke(ctx.resources.table_catalog, "describe", args);
2550
2155
  }
2551
- if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2552
- throw new TypeError("effort must be a nonempty model-supported string");
2156
+ };
2157
+ var tableQuery = {
2158
+ name: "table_query",
2159
+ version: "1",
2160
+ description: "Query one exact Table snapshot with bounded fields, filters, grouping, aggregates, ordering, and limit.",
2161
+ schema: TABLE_QUERY_SCHEMA,
2162
+ maxEffect: "read-only",
2163
+ needs: [{ binding: "table_catalog", kind: "service", ops: ["query"] }],
2164
+ async run(args, ctx) {
2165
+ return ctx.invoke(ctx.resources.table_catalog, "query", args);
2553
2166
  }
2167
+ };
2168
+
2169
+ // packages/sdk/src/tools.ts
2170
+ var NAME3 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2171
+ var OPERATION2 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
2172
+ function opTool(binding, op, override = {}) {
2173
+ if (!NAME3.test(binding) || !OPERATION2.test(op)) throw new TypeError("opTool binding or operation is invalid");
2174
+ const name = override.name ?? op.replaceAll(".", "_");
2554
2175
  return {
2555
- ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2556
- ...temperature === void 0 ? {} : { temperature },
2557
- ...effort === void 0 ? {} : { effort },
2558
- ...providerOptions === void 0 ? {} : { providerOptions: modelProviderOptions(providerOptions) }
2176
+ name,
2177
+ version: "catalog",
2178
+ description: override.description ?? `Invoke ${op} on the bound ${binding} resource.`,
2179
+ schema: override.schema ?? { type: "object", additionalProperties: false },
2180
+ maxEffect: "read-only",
2181
+ needs: [],
2182
+ ...override.tier ? { tier: override.tier } : {},
2183
+ ...override.once ? { once: override.once } : {},
2184
+ ...override.guard ? { guard: override.guard } : {},
2185
+ ...override.preview ? { preview: override.preview } : {},
2186
+ catalog: { binding, op },
2187
+ async run() {
2188
+ throw new TypeError(`catalog Tool ${binding}#${op} was not resolved by deployment`);
2189
+ }
2559
2190
  };
2560
2191
  }
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 };
2192
+ function opTools(binding, ops = []) {
2193
+ if (ops.length === 0) throw new TypeError("opTools requires pinned operation names at bundle construction");
2194
+ return ops.map((op) => opTool(binding, op));
2572
2195
  }
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");
2577
- }
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;
2196
+ async function boundResource(ctx, binding) {
2197
+ const resource = await ctx.describeResource(binding);
2198
+ if (!resource) throw new TypeError(`Resource is not bound: ${binding}`);
2199
+ return resource;
2600
2200
  }
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");
2201
+ var resourceTools = {
2202
+ resource_list: {
2203
+ name: "resource_list",
2204
+ version: "1",
2205
+ maxEffect: "read-only",
2206
+ needs: [],
2207
+ description: "List the Resource bindings accepted by this Run. Inspect a binding with resource_describe to read its public operations.",
2208
+ schema: { type: "object", properties: {}, additionalProperties: false },
2209
+ run: (_args, ctx) => ctx.step("bound-resource-list", async () => Object.entries(ctx.resources).sort(([left], [right]) => left.localeCompare(right)).map(([binding, crn]) => ({ binding, crn })))
2210
+ },
2211
+ resource_describe: {
2212
+ name: "resource_describe",
2213
+ version: "1",
2214
+ maxEffect: "read-only",
2215
+ needs: [],
2216
+ description: "Read a bound Resource's public operations, input/output schemas, and execution semantics. This does not connect or install it.",
2217
+ schema: {
2218
+ type: "object",
2219
+ required: ["binding"],
2220
+ additionalProperties: false,
2221
+ properties: { binding: { type: "string", minLength: 1 } }
2222
+ },
2223
+ run: (args, ctx) => boundResource(ctx, args.binding)
2224
+ },
2225
+ resource_invoke: {
2226
+ name: "resource_invoke",
2227
+ version: "1",
2228
+ maxEffect: "non-idempotent",
2229
+ needs: [],
2230
+ description: "Invoke a public operation on an already-bound Resource using its described input schema. Policy applies to the invocation. This does not install a Resource or add a binding.",
2231
+ schema: {
2232
+ type: "object",
2233
+ required: ["binding", "operation", "arguments"],
2234
+ additionalProperties: false,
2235
+ properties: { binding: { type: "string", minLength: 1 }, operation: { type: "string", minLength: 1 }, arguments: {} }
2236
+ },
2237
+ async run(args, ctx) {
2238
+ const resource = await boundResource(ctx, args.binding);
2239
+ const operation = resource.operations.find((candidate) => candidate.op === args.operation);
2240
+ if (!operation) throw new TypeError(`Resource operation is not available: ${args.binding}#${args.operation}`);
2241
+ return operation.async ? ctx.invokeAsync(resource.crn, operation.op, args.arguments) : ctx.invoke(resource.crn, operation.op, args.arguments);
2242
+ }
2607
2243
  }
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");
2244
+ };
2245
+ var WEB_FETCH_ARGUMENT_SCHEMA = {
2246
+ type: "object",
2247
+ required: ["url"],
2248
+ additionalProperties: false,
2249
+ properties: {
2250
+ url: { type: "string", minLength: 1, maxLength: 2048 },
2251
+ accept: { type: "string", maxLength: 256 }
2610
2252
  }
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");
2253
+ };
2254
+ var WEB_SEARCH_ARGUMENT_SCHEMA = {
2255
+ type: "object",
2256
+ required: ["query"],
2257
+ additionalProperties: false,
2258
+ properties: {
2259
+ query: {
2260
+ type: "string",
2261
+ minLength: 1,
2262
+ maxLength: 4096,
2263
+ description: "A self-contained description of the information to find."
2264
+ },
2265
+ searchQueries: {
2266
+ type: "array",
2267
+ minItems: 1,
2268
+ maxItems: 3,
2269
+ uniqueItems: true,
2270
+ description: "Optional concise keyword queries that narrow the search.",
2271
+ items: { type: "string", minLength: 1, maxLength: 256 }
2272
+ },
2273
+ maximumResults: {
2274
+ type: "integer",
2275
+ minimum: 1,
2276
+ maximum: 20,
2277
+ description: "Maximum number of sources to return."
2278
+ },
2279
+ maximumCharacters: {
2280
+ type: "integer",
2281
+ minimum: 1e3,
2282
+ maximum: 6e4,
2283
+ description: "Maximum total excerpt characters to return."
2284
+ },
2285
+ includeDomains: {
2286
+ type: "array",
2287
+ maxItems: 50,
2288
+ uniqueItems: true,
2289
+ description: "Optional domains to restrict results to.",
2290
+ items: { type: "string", minLength: 1, maxLength: 253 }
2291
+ },
2292
+ excludeDomains: {
2293
+ type: "array",
2294
+ maxItems: 50,
2295
+ uniqueItems: true,
2296
+ description: "Optional domains to omit.",
2297
+ items: { type: "string", minLength: 1, maxLength: 253 }
2298
+ },
2299
+ afterDate: {
2300
+ type: "string",
2301
+ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
2302
+ description: "Optional earliest publication date in YYYY-MM-DD form."
2303
+ }
2614
2304
  }
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;
2619
- }
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");
2627
- }
2628
- if (args.toolChoice === "required" && !args.tools?.length) {
2629
- throw new TypeError("required model Tool choice needs at least one offered Tool");
2630
- }
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;
2665
- return {
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 } : {}
2669
- };
2670
- }
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 });
2305
+ };
2306
+ var webFetch = opTool("web", "get", {
2307
+ name: "web_fetch",
2308
+ description: "Fetch an HTTPS resource through the bound governed web Resource.",
2309
+ schema: WEB_FETCH_ARGUMENT_SCHEMA
2310
+ });
2311
+ var webSearch = opTool("search", "search", {
2312
+ name: "web_search",
2313
+ description: "Search the public web through the bound governed search Resource.",
2314
+ schema: WEB_SEARCH_ARGUMENT_SCHEMA
2315
+ });
2316
+ var casTool = {
2317
+ name: "cas",
2318
+ version: "1",
2319
+ description: "Store or load one content-addressed Agent artifact.",
2320
+ schema: {
2321
+ type: "object",
2322
+ required: ["action"],
2323
+ additionalProperties: false,
2324
+ properties: {
2325
+ action: { type: "string", enum: ["put", "get"] },
2326
+ value: {},
2327
+ ref: { type: "string", pattern: "^[a-f0-9]{64}$" }
2709
2328
  }
2710
- const values = record6(source.usage) ?? {};
2711
- usage = {
2712
- input: integer2(values.prompt_tokens),
2713
- output: integer2(values.completion_tokens),
2714
- cached: integer2(record6(values.prompt_tokens_details)?.cached_tokens),
2715
- ...costMetadata(values)
2716
- };
2717
- } else throw new TypeError("model gateway protocol is invalid");
2718
- if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
2719
- return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model, completion: modelCompletionStatus(protocol, raw) };
2720
- }
2721
- function modelCompletionStatus(protocol, raw) {
2722
- const source = record6(raw) ?? {};
2723
- const value = protocol === "anthropic" ? source.stop_reason : record6(Array.isArray(source.choices) ? source.choices[0] : null)?.finish_reason;
2724
- const reason = typeof value === "string" ? value : null;
2725
- const complete = protocol === "anthropic" ? ["end_turn", "tool_use", "stop_sequence"] : ["stop", "tool_calls", "function_call"];
2726
- const incomplete = protocol === "anthropic" ? ["max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"] : ["length", "content_filter", "error", "cancelled", "canceled"];
2727
- return { status: reason !== null && complete.includes(reason) ? "complete" : reason !== null && incomplete.includes(reason) ? "incomplete" : "unknown", reason };
2728
- }
2729
-
2730
- // packages/sdk/src/gateway.ts
2731
- async function checkpointArtifactRef(value) {
2732
- return await sha256Hex(canonicalJson(value));
2733
- }
2734
- var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2735
- var HASH3 = /^[a-f0-9]{64}$/u;
2736
- var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
2737
- function httpsUrl(value, field2) {
2738
- if (value === void 0) return;
2739
- if (typeof value !== "string" || value.length > 2048) throw new TypeError(`${field2} is invalid`);
2740
- let parsed;
2741
- try {
2742
- parsed = new URL(value);
2743
- } catch {
2744
- throw new TypeError(`${field2} is invalid`);
2745
- }
2746
- if (parsed.protocol !== "https:") throw new TypeError(`${field2} is invalid`);
2747
- }
2748
- function slotMetadata(value) {
2749
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Gateway Credential slots are invalid");
2750
- const entries = Object.entries(value);
2751
- if (entries.length > 32) throw new TypeError("Gateway Credential slots are invalid");
2752
- const output = {};
2753
- for (const [slot, raw] of entries) {
2754
- const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2755
- if (!SLOT.test(slot) || !item || typeof item.title !== "string" || !item.title || item.title.length > 128 || item.description !== void 0 && (typeof item.description !== "string" || item.description.length > 1024) || item.required !== void 0 && typeof item.required !== "boolean" || item.provider !== void 0 && (typeof item.provider !== "string" || !SLOT.test(item.provider)) || Object.keys(item).some((key) => !["title", "description", "documentationUrl", "required", "provider"].includes(key))) {
2756
- throw new TypeError("Gateway Credential slots are invalid");
2329
+ },
2330
+ maxEffect: "idempotent",
2331
+ needs: [{ binding: "cas", kind: "cas", ops: ["put", "get"] }],
2332
+ async run(args, ctx) {
2333
+ const input = args && typeof args === "object" && !Array.isArray(args) ? args : {};
2334
+ if (input.action === "put") {
2335
+ if (!Object.hasOwn(input, "value")) throw new TypeError("cas put requires value");
2336
+ return ctx.invoke(ctx.resources.cas, "put", { value: input.value });
2757
2337
  }
2758
- httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
2759
- output[slot] = item;
2760
- }
2761
- return output;
2762
- }
2763
- function configEgressBindings(value) {
2764
- if (value === void 0) return [];
2765
- if (!Array.isArray(value) || value.length > 16) throw new TypeError("Gateway config egress bindings are invalid");
2766
- return value.map((raw) => {
2767
- const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2768
- if (!item || !SLOT.test(String(item.urlProperty ?? "")) || !Array.isArray(item.operations) || item.operations.length === 0 || item.operations.length > 128 || item.operations.some((operation) => typeof operation !== "string" || operation !== "*" && !/^[A-Za-z][A-Za-z0-9._-]{0,127}$/u.test(operation)) || !Array.isArray(item.methods) || item.methods.length === 0 || item.methods.length > 8 || item.methods.some((method) => typeof method !== "string" || !/^(?:GET|POST|PUT|PATCH|DELETE)$/u.test(method)) || Object.keys(item).some((key) => !["urlProperty", "operations", "methods"].includes(key))) {
2769
- throw new TypeError("Gateway config egress bindings are invalid");
2338
+ if (input.action === "get") {
2339
+ if (typeof input.ref !== "string") throw new TypeError("cas get requires ref");
2340
+ return ctx.invoke(ctx.resources.cas, "get", { ref: input.ref });
2770
2341
  }
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");
2342
+ throw new TypeError("cas action must be put or get");
2826
2343
  }
2827
- return { gateway: gateway2, import: checkpointImportRequest(source.import) };
2828
- }
2829
- var MODEL_ID_CONTROL = /[\u0000-\u001f\u007f]/u;
2830
- var modelModalitiesSchema = {
2831
- type: "array",
2832
- minItems: 1,
2833
- maxItems: 16,
2834
- uniqueItems: true,
2835
- items: { type: "string", pattern: SLOT.source }
2836
2344
  };
2837
- var GATEWAY_MODEL_OFFER_SCHEMA = {
2345
+
2346
+ // packages/sdk/src/memory.ts
2347
+ var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 };
2348
+ var content = { type: "string", minLength: 1, maxLength: 65536 };
2349
+ var metadata2 = { type: "object", maxProperties: 64 };
2350
+ var scope = { type: "string", pattern: "^[a-f0-9]{64}$", maxLength: 64 };
2351
+ var record5 = {
2838
2352
  type: "object",
2353
+ required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
2839
2354
  additionalProperties: false,
2840
- required: ["id", "displayName", "contextTokens", "maxOutputTokens", "pricing"],
2841
2355
  properties: {
2842
- id: { type: "string", minLength: 1, maxLength: 512 },
2843
- displayName: { type: "string", minLength: 1, maxLength: 128 },
2844
- contextTokens: { type: "integer", minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
2845
- maxOutputTokens: { type: "integer", minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
2846
- inputModalities: modelModalitiesSchema,
2847
- outputModalities: modelModalitiesSchema,
2848
- pricing: { type: ["object", "null"] }
2356
+ id,
2357
+ content,
2358
+ metadata: metadata2,
2359
+ createdAt: { type: "integer", minimum: 0 },
2360
+ updatedAt: { type: "integer", minimum: 0 },
2361
+ expiresAt: { anyOf: [{ type: "integer", minimum: 0 }, { type: "null" }] }
2849
2362
  }
2850
2363
  };
2851
- function gatewayModelOffer(value) {
2852
- const source = value;
2853
- if (validateJsonSchema(value, GATEWAY_MODEL_OFFER_SCHEMA) || source.id !== source.id.trim() || MODEL_ID_CONTROL.test(source.id) || source.maxOutputTokens > source.contextTokens) {
2854
- throw new TypeError("Gateway Model offer is invalid");
2855
- }
2856
- const pricing = source.pricing === null ? null : modelAdvertisedPricing(source.pricing);
2857
- const { inputModalities, outputModalities } = source;
2858
- return {
2859
- id: source.id,
2860
- displayName: source.displayName,
2861
- contextTokens: Number(source.contextTokens),
2862
- maxOutputTokens: Number(source.maxOutputTokens),
2863
- ...inputModalities ? { inputModalities } : {},
2864
- ...outputModalities ? { outputModalities } : {},
2865
- pricing
2866
- };
2867
- }
2868
- function assertNonSecretGatewayConfig(value, field2 = "config") {
2869
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
2870
- const source = value;
2871
- if (source.format === "password" || /(?:secret|password|private[-_ ]?key|access[-_ ]?token|api[-_ ]?key)/iu.test(field2)) {
2872
- throw new TypeError("Gateway secrets must use declared Credential slots");
2873
- }
2874
- const properties = source.properties && typeof source.properties === "object" && !Array.isArray(source.properties) ? source.properties : {};
2875
- for (const [name, declaration] of Object.entries(properties)) assertNonSecretGatewayConfig(declaration, name);
2876
- if (source.items) assertNonSecretGatewayConfig(source.items, field2);
2877
- if (source.additionalProperties && typeof source.additionalProperties === "object") {
2878
- assertNonSecretGatewayConfig(source.additionalProperties, field2);
2879
- }
2880
- }
2881
- function gatewayPackageMetadata(value) {
2882
- const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2883
- if (!source || source.lifecycleVersion !== 1 || typeof source.displayName !== "string" || !source.displayName || source.displayName.length > 128 || typeof source.description !== "string" || !source.description || source.description.length > 1024 || source.service !== void 0 && (typeof source.service !== "string" || !source.service || source.service.length > 128) || !Array.isArray(source.capabilities) || source.capabilities.length === 0 || source.capabilities.length > 32 || !source.billing || typeof source.billing !== "object" || Array.isArray(source.billing) || !["platform", "tenant"].includes(String(source.billing.upstreamPayer ?? ""))) {
2884
- throw new TypeError("Gateway package metadata is invalid");
2364
+ var MEMORY_OPERATION_DECLARATIONS = [
2365
+ {
2366
+ op: "remember",
2367
+ description: "Persist or replace one record in the invocation's authenticated Memory partition.",
2368
+ schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata: metadata2, scope } },
2369
+ resultSchema: record5,
2370
+ effect: "idempotent",
2371
+ recovery: { kind: "idempotency-key" },
2372
+ async: false,
2373
+ usage: { meter: "none", priceTable: null }
2374
+ },
2375
+ {
2376
+ op: "search",
2377
+ description: "Retrieve relevant records from the invocation's authenticated Memory partition.",
2378
+ schema: {
2379
+ type: "object",
2380
+ required: ["query"],
2381
+ additionalProperties: false,
2382
+ properties: { query: { type: "string", minLength: 1, maxLength: 8192 }, limit: { type: "integer", minimum: 1, maximum: 100 }, scope }
2383
+ },
2384
+ resultSchema: {
2385
+ type: "object",
2386
+ required: ["hits"],
2387
+ additionalProperties: false,
2388
+ properties: { hits: { type: "array", maxItems: 100, items: {
2389
+ ...record5,
2390
+ required: [...record5.required, "score"],
2391
+ properties: { ...record5.properties, score: { type: "number", minimum: 0, maximum: 1 } }
2392
+ } } }
2393
+ },
2394
+ effect: "read-only",
2395
+ recovery: { kind: "repeat" },
2396
+ async: false,
2397
+ usage: { meter: "none", priceTable: null }
2398
+ },
2399
+ {
2400
+ op: "get",
2401
+ description: "Read one record from the invocation's authenticated Memory partition.",
2402
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2403
+ resultSchema: { anyOf: [record5, { type: "null" }] },
2404
+ effect: "read-only",
2405
+ recovery: { kind: "repeat" },
2406
+ async: false,
2407
+ usage: { meter: "none", priceTable: null }
2408
+ },
2409
+ {
2410
+ op: "delete",
2411
+ description: "Delete one record from the invocation's authenticated Memory partition.",
2412
+ schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
2413
+ resultSchema: { type: "object", required: ["deleted"], additionalProperties: false, properties: { deleted: { type: "boolean" } } },
2414
+ effect: "idempotent",
2415
+ recovery: { kind: "idempotency-key" },
2416
+ async: false,
2417
+ usage: { meter: "none", priceTable: null }
2418
+ },
2419
+ {
2420
+ op: "purge",
2421
+ description: "Delete every record in the invocation's authenticated Memory partition.",
2422
+ schema: { type: "object", additionalProperties: false, properties: {} },
2423
+ resultSchema: {
2424
+ type: "object",
2425
+ required: ["deleted"],
2426
+ additionalProperties: false,
2427
+ properties: { deleted: { type: "integer", minimum: 0 } }
2428
+ },
2429
+ effect: "idempotent",
2430
+ recovery: { kind: "idempotency-key" },
2431
+ async: false,
2432
+ usage: { meter: "none", priceTable: null }
2885
2433
  }
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");
2434
+ ];
2435
+
2436
+ // packages/sdk/src/integration.ts
2437
+ var ApiError = class extends Error {
2438
+ constructor(status, body, disposition = "uncertain") {
2439
+ super(`${status}: ${body}`);
2440
+ this.status = status;
2441
+ this.body = body;
2442
+ this.disposition = disposition;
2443
+ this.name = "ApiError";
2893
2444
  }
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");
2445
+ status;
2446
+ body;
2447
+ disposition;
2448
+ };
2449
+ var IntegrationRequestNotSent = class extends Error {
2450
+ constructor(message2 = "integration request was not sent") {
2451
+ super(message2);
2452
+ this.name = "IntegrationRequestNotSent";
2897
2453
  }
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");
2454
+ };
2455
+ var TerminalIntegrationFailure = class extends Error {
2456
+ constructor(message2 = "integration operation failed terminally") {
2457
+ super(message2);
2458
+ this.name = "TerminalIntegrationFailure";
2905
2459
  }
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");
2460
+ };
2461
+ var OPERATION3 = /^[A-Za-z][A-Za-z0-9._-]{0,127}$/u;
2462
+ function integrationEgressPolicy(value) {
2463
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2464
+ if (!source || !Array.isArray(source.rules) || source.rules.length > 128 || Object.keys(source).some((key) => key !== "rules")) {
2465
+ throw new TypeError("integration egress policy is invalid");
2908
2466
  }
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;
2467
+ const rules = source.rules.map((raw) => {
2468
+ const rule = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
2469
+ const paths = Number(rule?.pathPrefix !== void 0) + Number(rule?.pathExact !== void 0);
2470
+ 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))) {
2471
+ throw new TypeError("integration egress rule is invalid");
2472
+ }
2473
+ let origin;
2929
2474
  try {
2930
- endpoint = new URL(String(config[binding.urlProperty] ?? ""));
2475
+ origin = new URL(rule.origin);
2931
2476
  } catch {
2932
- throw new TypeError(`Gateway ${binding.urlProperty} must be an HTTPS endpoint`);
2477
+ throw new TypeError("integration egress origin is invalid");
2933
2478
  }
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`);
2479
+ if (origin.protocol !== "https:" || origin.origin !== rule.origin || origin.username || origin.password) {
2480
+ throw new TypeError("integration egress origin is invalid");
2936
2481
  }
2937
- return { operations: binding.operations, origin: endpoint.origin, pathExact: endpoint.pathname, methods: binding.methods };
2482
+ const path = String(rule.pathPrefix ?? rule.pathExact);
2483
+ if (!path.startsWith("/") || path.includes("?") || path.includes("#")) throw new TypeError("integration egress path is invalid");
2484
+ return rule;
2938
2485
  });
2939
- return integrationEgressPolicy({ rules: [...metadata2.egress.rules, ...derived] });
2486
+ return { rules };
2940
2487
  }
2941
- function gateway(definition2) {
2942
- if (!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(definition2.id) || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(definition2.version) || !["cas", "web", "service", "mcp", "db", "browser", "sandbox-pool", "vault"].includes(definition2.kind) || typeof definition2.catalog !== "function" || typeof definition2.invoke !== "function" || definition2.reconcile !== void 0 && typeof definition2.reconcile !== "function" || definition2.cancel !== void 0 && typeof definition2.cancel !== "function") {
2943
- throw new TypeError("Gateway definition is invalid");
2944
- }
2945
- const schemaError = validateJsonSchemaDefinition(definition2.configSchema);
2946
- if (schemaError) throw new TypeError(`Gateway config schema is invalid: ${schemaError}`);
2947
- const configSchema = definition2.configSchema;
2948
- if (configSchema.type !== "object") throw new TypeError('Gateway config schema root type must be "object"');
2949
- if (configSchema.additionalProperties !== false) throw new TypeError("Gateway config schema must reject unknown root fields");
2950
- assertNonSecretGatewayConfig(configSchema);
2951
- const gateway2 = gatewayPackageMetadata({
2952
- lifecycleVersion: 1,
2953
- displayName: definition2.displayName,
2954
- description: definition2.description,
2955
- documentationUrl: definition2.documentationUrl,
2956
- service: definition2.service,
2957
- credentialSlots: definition2.credentialSlots,
2958
- modelOffers: definition2.modelOffers ?? [],
2959
- capabilities: definition2.capabilities,
2960
- billing: definition2.billing,
2961
- egress: definition2.egress,
2962
- configEgress: definition2.configEgress,
2963
- discovery: definition2.discovery,
2964
- training: definition2.training,
2965
- checkpointImport: definition2.checkpointImport
2488
+
2489
+ // packages/sdk/src/container-image.ts
2490
+ var REPOSITORY = /^[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:\.|_|__|-+)[a-z0-9]+)*)*$/u;
2491
+ var TAG = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/u;
2492
+ var DIGEST = /^[a-z][a-z0-9+._-]*:[A-Za-z0-9=_-]+$/u;
2493
+ var SHA256 = /^sha256:[a-f0-9]{64}$/u;
2494
+ function containerImageReference(value) {
2495
+ if (typeof value !== "string" || !value || /[\s?#\\]/u.test(value) || value.includes("://")) throw new TypeError("container image reference is invalid");
2496
+ const components = value.split("@");
2497
+ if (components.length > 2) throw new TypeError("container image reference is invalid");
2498
+ let name = components[0];
2499
+ const digest = components[1] ?? null;
2500
+ if (digest !== null && (!DIGEST.test(digest) || digest.startsWith("sha256:") && !SHA256.test(digest))) {
2501
+ throw new TypeError("container image digest is invalid");
2502
+ }
2503
+ const separator = name.lastIndexOf(":"), slash = name.lastIndexOf("/");
2504
+ const tag = separator > slash ? name.slice(separator + 1) : null;
2505
+ if (tag !== null) {
2506
+ if (!TAG.test(tag)) throw new TypeError("container image tag is invalid");
2507
+ name = name.slice(0, separator);
2508
+ }
2509
+ const parts = name.split("/"), explicit = parts.length > 1 && (/[.:]/u.test(parts[0]) || parts[0] === "localhost");
2510
+ const registryInput = explicit ? parts.shift() : "docker.io";
2511
+ let registryUrl;
2512
+ try {
2513
+ registryUrl = new URL(`https://${registryInput}`);
2514
+ } catch {
2515
+ throw new TypeError("container image registry is invalid");
2516
+ }
2517
+ if (registryUrl.username || registryUrl.password || registryUrl.pathname !== "/" || !registryUrl.hostname) throw new TypeError("container image registry is invalid");
2518
+ const registry = registryUrl.host === "index.docker.io" ? "docker.io" : registryUrl.host;
2519
+ if (registry === "docker.io" && parts.length === 1) parts.unshift("library");
2520
+ const repository = parts.join("/");
2521
+ if (!REPOSITORY.test(repository)) throw new TypeError("container image repository is invalid");
2522
+ const selectedTag = tag ?? (digest === null ? "latest" : null);
2523
+ return {
2524
+ registry,
2525
+ repository,
2526
+ tag: selectedTag,
2527
+ digest,
2528
+ reference: `${registry}/${repository}${digest === null ? `:${selectedTag}` : `@${digest}`}`
2529
+ };
2530
+ }
2531
+ function immutableContainerImageReference(value) {
2532
+ const image = containerImageReference(value);
2533
+ if (!image.digest || !SHA256.test(image.digest)) throw new TypeError("container image must be resolved to a SHA-256 digest");
2534
+ return image;
2535
+ }
2536
+ function containerImageSource(value) {
2537
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2538
+ const platform = source?.platform && typeof source.platform === "object" && !Array.isArray(source.platform) ? source.platform : null;
2539
+ const image = typeof source?.reference === "string" ? immutableContainerImageReference(source.reference) : null;
2540
+ if (!source || !image || source.digest !== image.digest || typeof source.mediaType !== "string" || !source.mediaType || !Number.isSafeInteger(source.bytes) || Number(source.bytes) < 1 || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant)) {
2541
+ throw new TypeError("container image source is invalid");
2542
+ }
2543
+ return structuredClone(source);
2544
+ }
2545
+ function containerImageSelection(value) {
2546
+ const selection = value && typeof value === "object" && !Array.isArray(value) ? value : null;
2547
+ const platform = selection?.platform && typeof selection.platform === "object" && !Array.isArray(selection.platform) ? selection.platform : null;
2548
+ const image = typeof selection?.reference === "string" ? immutableContainerImageReference(selection.reference) : null;
2549
+ if (!selection || !image || !platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && (typeof platform.variant !== "string" || !platform.variant) || Object.keys(selection).some((key) => key !== "reference" && key !== "platform") || Object.keys(platform).some((key) => key !== "os" && key !== "architecture" && key !== "variant")) {
2550
+ throw new TypeError("container image selection is invalid");
2551
+ }
2552
+ return { reference: image.reference, platform: structuredClone(platform) };
2553
+ }
2554
+ var OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json";
2555
+ var OCI_INDEX = "application/vnd.oci.image.index.v1+json";
2556
+ var DOCKER_MANIFEST = "application/vnd.docker.distribution.manifest.v2+json";
2557
+ var DOCKER_INDEX = "application/vnd.docker.distribution.manifest.list.v2+json";
2558
+ var ACCEPT = [OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].join(", ");
2559
+ var MANIFEST_BYTES = 4194304;
2560
+ function object3(value) {
2561
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2562
+ }
2563
+ async function manifest(image, reference, request, authorization) {
2564
+ const response = await request({
2565
+ url: `https://${image.registry}/v2/${image.repository}/manifests/${encodeURIComponent(reference)}`,
2566
+ method: "GET",
2567
+ headers: { accept: ACCEPT, ...authorization ? { authorization } : {} },
2568
+ maximumBytes: MANIFEST_BYTES
2966
2569
  });
2967
- const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
2968
- for (const binding of gateway2.configEgress ?? []) {
2969
- const property = properties[binding.urlProperty];
2970
- if (!property || property.type !== "string" || property.format !== "uri") {
2971
- throw new TypeError(`Gateway config egress property must be a URI string: ${binding.urlProperty}`);
2972
- }
2973
- }
2974
- if (gateway2.discovery) {
2975
- const property = properties[gateway2.discovery.resultConfigProperty];
2976
- if (!property || property.type !== "array") throw new TypeError("Gateway discovery result config property must be an array");
2977
- const required2 = Array.isArray(configSchema.required) ? configSchema.required : [];
2978
- if (!required2.includes(gateway2.discovery.resultConfigProperty)) {
2979
- throw new TypeError("Gateway discovery result config property must be required");
2570
+ if (response.status < 200 || response.status >= 300) throw Object.assign(new Error(`container registry manifest request returned ${response.status}`), { status: response.status });
2571
+ if (response.body.byteLength === 0 || response.body.byteLength > MANIFEST_BYTES) throw new TypeError("container registry manifest size is invalid");
2572
+ let value;
2573
+ try {
2574
+ value = object3(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(response.body)));
2575
+ } catch {
2576
+ value = null;
2577
+ }
2578
+ if (!value || value.schemaVersion !== 2) throw new TypeError("container registry manifest is invalid");
2579
+ const declared = typeof value.mediaType === "string" ? value.mediaType : response.headers["content-type"]?.split(";", 1)[0];
2580
+ if (![OCI_MANIFEST, OCI_INDEX, DOCKER_MANIFEST, DOCKER_INDEX].includes(String(declared))) throw new TypeError("container registry manifest media type is unsupported");
2581
+ const digest = `sha256:${await sha256Hex(response.body)}`;
2582
+ const header = response.headers["docker-content-digest"];
2583
+ if (header !== void 0 && header !== digest) throw new TypeError("container registry digest header differs from manifest bytes");
2584
+ return { value, mediaType: declared, digest };
2585
+ }
2586
+ async function resolveContainerImageSource(reference, platform, request, authorization) {
2587
+ const image = containerImageReference(reference);
2588
+ if (!platform || typeof platform.os !== "string" || !platform.os || typeof platform.architecture !== "string" || !platform.architecture || platform.variant !== void 0 && !platform.variant) throw new TypeError("container image platform is invalid");
2589
+ const requested = image.digest ?? image.tag;
2590
+ let selected = await manifest(image, requested, request, authorization);
2591
+ if (image.digest && selected.digest !== image.digest) throw new TypeError("container image digest does not match its manifest");
2592
+ if (selected.mediaType === OCI_INDEX || selected.mediaType === DOCKER_INDEX) {
2593
+ if (!Array.isArray(selected.value.manifests)) throw new TypeError("container image index has no manifests");
2594
+ const matches = selected.value.manifests.filter((raw) => {
2595
+ const item = object3(raw), target = object3(item?.platform);
2596
+ return item && target && target.os === platform.os && target.architecture === platform.architecture && (platform.variant === void 0 ? target.variant === void 0 : target.variant === platform.variant);
2597
+ }).map((item) => object3(item));
2598
+ if (matches.length !== 1 || typeof matches[0].digest !== "string" || !SHA256.test(matches[0].digest)) {
2599
+ throw new TypeError("container image index does not contain one exact requested platform");
2980
2600
  }
2981
- if (property.readOnly !== true) throw new TypeError("Gateway discovery result config property must be read-only");
2601
+ selected = await manifest(image, matches[0].digest, request, authorization);
2602
+ if (selected.digest !== matches[0].digest) throw new TypeError("container image platform descriptor differs from its manifest");
2603
+ }
2604
+ if (selected.mediaType !== OCI_MANIFEST && selected.mediaType !== DOCKER_MANIFEST) throw new TypeError("container image did not resolve to an image manifest");
2605
+ const config = object3(selected.value.config), layers = selected.value.layers;
2606
+ if (!config || !Number.isSafeInteger(config.size) || Number(config.size) < 0 || !Array.isArray(layers) || layers.some((layer) => !object3(layer) || !Number.isSafeInteger(object3(layer).size) || Number(object3(layer).size) < 0)) {
2607
+ throw new TypeError("container image manifest descriptors are invalid");
2608
+ }
2609
+ const bytes = Number(config.size) + layers.reduce((sum, layer) => sum + Number(object3(layer).size), 0);
2610
+ return containerImageSource({
2611
+ reference: `${image.registry}/${image.repository}@${selected.digest}`,
2612
+ digest: selected.digest,
2613
+ mediaType: selected.mediaType,
2614
+ bytes,
2615
+ platform
2616
+ });
2617
+ }
2618
+
2619
+ // packages/sdk/src/sandbox-pool.ts
2620
+ var WORKSPACE_ROOT = "/workspace";
2621
+ function absoluteSandboxPath(value) {
2622
+ const segments = [];
2623
+ for (const segment of value.split("/")) {
2624
+ if (!segment || segment === ".") continue;
2625
+ if (segment === "..") segments.pop();
2626
+ else segments.push(segment);
2982
2627
  }
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);
2628
+ return `/${segments.join("/")}`;
2995
2629
  }
2996
- function trainingProvider(definition2) {
2997
- const authoredCatalog = definition2.catalog;
2998
- return gateway({
2999
- ...definition2,
3000
- capabilities: [...definition2.capabilities, ...definition2.capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash) ? [] : [TRAINING_PROVIDER_CAPABILITY]],
3001
- catalog(config) {
3002
- const declarations = authoredCatalog(config);
3003
- const train = declarations.find((operation) => operation.op === "train");
3004
- if (!train || !train.async || train.effect !== "reconcilable" || train.recovery.kind !== "reconcile") {
3005
- throw new TypeError("Training Provider train must be asynchronous, reconcilable, and recovered by reconcile");
3006
- }
3007
- return declarations;
3008
- }
3009
- });
2630
+ function normalizeSandboxWorkspacePath(path, cwd = WORKSPACE_ROOT) {
2631
+ 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)) {
2632
+ throw new TypeError("sandbox workspace path is invalid");
2633
+ }
2634
+ const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
2635
+ if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
2636
+ throw new TypeError("sandbox working directory is outside /workspace");
2637
+ }
2638
+ const normalized = absoluteSandboxPath(path.startsWith("/") ? path : `${base}/${path}`);
2639
+ if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
2640
+ throw new TypeError("sandbox path is outside /workspace");
2641
+ }
2642
+ return normalized;
3010
2643
  }
3011
- var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
3012
- id: "constal.model-checkpoint-import",
3013
- version: "1",
3014
- hash: "49563823899586a87dcee82e9db969af5f2f5364adb3eb808a19e86b862e87ba"
3015
- };
3016
- var MCP_CLIENT_CAPABILITY = {
3017
- id: "constal.mcp-client",
2644
+ var SANDBOX_PROCESS_IO_OPERATIONS = ["process.status", "process.read", "process.write", "process.close"];
2645
+ var SANDBOX_PROCESS_OPERATIONS = ["process.resolve", ...SANDBOX_PROCESS_IO_OPERATIONS, "process.stop"];
2646
+
2647
+ // packages/sdk/src/training.ts
2648
+ var HASH2 = /^[a-f0-9]{64}$/u;
2649
+ var VERSION4 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
2650
+ var JOB_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2651
+ var MODEL_ID = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2652
+ var PROVIDER_MODEL_ID = /^[^\s]{1,512}$/u;
2653
+ var TRAINING_PROVIDER_CAPABILITY = {
2654
+ id: "constal.training-provider",
3018
2655
  version: "1",
3019
- hash: "a694af71191432e75980dc73962d9239dc8ea324aff084f183a2f45603bd2267"
2656
+ hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
3020
2657
  };
3021
-
3022
- // packages/sdk/src/constal-api.ts
3023
- var CONSTAL_API_CAPABILITY = "constal.api";
3024
- var CONSTAL_API_VERSION = "1";
3025
- var CONSTAL_API_OPERATIONS = [
3026
- "describe",
3027
- "query",
3028
- "get",
3029
- "relations",
3030
- "explainPolicy",
3031
- "plan",
3032
- "apply",
3033
- "observe"
3034
- ];
3035
- var CONSTAL_API_BOUNDS = {
3036
- defaultPageSize: 50,
3037
- maximumPageSize: 200,
3038
- maximumRelationDepth: 3,
3039
- maximumPlanOperations: 64,
3040
- maximumInputBytes: 1048576,
3041
- planTtlMs: 15 * 6e4
3042
- };
3043
- var CONSTAL_API_QUERY_KINDS = [
3044
- ...RESOURCE_KINDS,
3045
- "analytics",
3046
- "customer",
3047
- "binding",
3048
- "session",
3049
- "run",
3050
- "deployment",
3051
- "documentation",
3052
- "analytics-event",
3053
- "namespace",
3054
- "team-member",
3055
- "team-invite",
3056
- "api-key",
3057
- "billing-account",
3058
- "invoice",
3059
- "subscription",
3060
- "resource-contract",
3061
- "dataset-draft",
3062
- "dataset-case",
3063
- "eval-score",
3064
- "eval-sample",
3065
- "eval-policy",
3066
- "eval-suite",
3067
- "eval-baseline",
3068
- "eval-schedule",
3069
- "training-job",
3070
- "checkpoint",
3071
- "training-provider",
3072
- "training-model",
3073
- "checkpoint-gateway",
3074
- "credential-provider-package",
3075
- "credential-consumer",
3076
- "credential-use",
3077
- "credential-event",
3078
- "gateway-package",
3079
- "rollout",
3080
- "wait"
3081
- ];
3082
- var CONSTAL_API_GET_KINDS = CONSTAL_API_QUERY_KINDS;
3083
- var CONSTAL_API_MODEL_TOOL_DESCRIPTIONS = {
3084
- query: "Query authorized Constal objects with bounded pagination and evidence. Select the exact lower-case singular kind from the schema enum; never pluralize, recase, or substitute an abstract kind. If context supplies platformToolContract.queryScope, copy it unchanged. Otherwise use only an exact namespace allowed by the delegated Run authority, and tenant scope only for an explicitly tenant-wide request. Use catalog-advertised fields and filters; constrained kinds require their advertised filter. Preserve next and evidence completeness.",
3085
- get: "Retrieve one exact authorized Constal object or immutable revision. Pass a complete ref unchanged from query, relations, runtime inspection, or a governed receipt; never construct a kind, id, namespace, CRN, hash, or cursor from display text. The schema enum contains every supported addressable kind. For a Run, omit fields for complete diagnosis or request only documented top-level fields, and follow only the returned page cursor."
3086
- };
3087
- var CONSTAL_API_GET_CRN_KINDS = [
3088
- ...RESOURCE_KINDS,
3089
- "analytics",
3090
- "binding",
3091
- "session",
3092
- "run",
3093
- "deployment"
3094
- ];
3095
- var CONSTAL_API_OBJECT_REF_CRN_KINDS = [...CONSTAL_API_GET_CRN_KINDS, "customer"];
3096
- var boundedNameSchema = { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z][A-Za-z0-9._-]{0,127}$" };
3097
- var namespaceSchema = {
3098
- type: "string",
3099
- minLength: 1,
3100
- maxLength: 128,
3101
- pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
3102
- };
3103
- var actionSchema = { type: "string", pattern: ACTION_PATTERN.source };
3104
- var boundedIdSchema = { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9][A-Za-z0-9._~:-]{0,255}$" };
3105
- var hashSchema = { type: "string", pattern: "^[a-f0-9]{64}$" };
3106
- var stringListSchema = { type: "array", maxItems: 128, items: { type: "string", minLength: 1, maxLength: 256 } };
3107
- var scopeSchema = { description: "Use namespace with an exact namespace allowed by the delegated Run authority. Use tenant only for an explicitly tenant-wide request.", anyOf: [
3108
- {
3109
- type: "object",
3110
- required: ["kind", "namespace"],
3111
- additionalProperties: false,
3112
- properties: { kind: { const: "namespace" }, namespace: {
3113
- ...namespaceSchema,
3114
- description: "Exact authorized namespace. Do not infer it from an object name or repository."
3115
- } }
3116
- },
3117
- { type: "object", required: ["kind"], additionalProperties: false, properties: { kind: { const: "tenant" } } }
3118
- ] };
3119
- var crnPattern = (kinds) => `^crn:constal:[a-z0-9][a-z0-9._-]{0,127}:[a-z0-9][a-z0-9._-]{0,127}:[a-z0-9][a-z0-9._-]{0,127}:(?:${kinds.join("|")})/[A-Za-z0-9._~/%-]{1,512}$`;
3120
- var objectRefSchema = { type: "object", additionalProperties: false, properties: {
3121
- kind: { enum: [...CONSTAL_API_GET_KINDS], description: "Exact lower-case object kind returned by a governed platform result." },
3122
- id: { type: "string", minLength: 1, maxLength: 512 },
3123
- crn: { anyOf: [{ type: "null" }, {
3124
- type: "string",
3125
- minLength: 1,
3126
- maxLength: 2048,
3127
- pattern: crnPattern(CONSTAL_API_OBJECT_REF_CRN_KINDS)
3128
- }] },
3129
- hash: { anyOf: [{ type: "null" }, hashSchema] },
3130
- namespace: {
3131
- type: ["string", "null"],
3132
- maxLength: 128,
3133
- pattern: "^[a-z0-9][a-z0-9._-]{0,127}$"
3134
- },
3135
- version: { type: ["string", "null"], maxLength: 128 }
3136
- }, required: ["kind", "id", "namespace"] };
3137
- var exactGetCrnSchema = {
3138
- type: "string",
3139
- minLength: 1,
3140
- maxLength: 2048,
3141
- description: "Exact addressable CRN obtained from governed platform evidence.",
3142
- pattern: crnPattern(CONSTAL_API_GET_CRN_KINDS)
3143
- };
3144
- var CONSTAL_MODEL_CREATE_SCHEMA = {
3145
- type: "object",
3146
- required: ["id", "gateway", "offer"],
3147
- additionalProperties: false,
3148
- properties: {
3149
- id: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]*$", description: "Name of the new Model Resource." },
3150
- gateway: { type: "string", minLength: 1, maxLength: 2048, pattern: crnPattern(RESOURCE_KINDS), description: "Exact Gateway Resource CRN." },
3151
- offer: { description: "Select an advertised provider model or supply manual model metadata.", anyOf: [
3152
- {
3153
- type: "object",
3154
- required: ["kind", "modelId"],
3155
- additionalProperties: false,
3156
- properties: { kind: { const: "advertised" }, modelId: GATEWAY_MODEL_OFFER_SCHEMA.properties.id }
3157
- },
3158
- {
3159
- type: "object",
3160
- required: ["kind", "model"],
3161
- additionalProperties: false,
3162
- properties: { kind: { const: "manual" }, model: GATEWAY_MODEL_OFFER_SCHEMA }
3163
- }
3164
- ] },
3165
- defaults: { ...MODEL_GENERATION_OPTIONS_SCHEMA, description: "Generation settings used when calling this Model; omitted settings retain provider defaults." },
3166
- temperature: MODEL_GENERATION_OPTIONS_SCHEMA.properties.temperature
2658
+ function record6(value) {
2659
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2660
+ }
2661
+ function integer(value, field2, minimum, maximum) {
2662
+ if (!Number.isSafeInteger(value) || Number(value) < minimum || Number(value) > maximum) {
2663
+ throw new TypeError(`${field2} is invalid`);
3167
2664
  }
3168
- };
3169
- var CONSTAL_API_OPERATION_SCHEMAS = {
3170
- describe: { type: "object", additionalProperties: false, properties: {
3171
- domains: { ...stringListSchema, description: "Domain IDs returned in catalog.domains. Omit to discover across all domains." },
3172
- kinds: stringListSchema,
3173
- operations: stringListSchema,
3174
- include: {
3175
- type: "array",
3176
- maxItems: 5,
3177
- uniqueItems: true,
3178
- items: { enum: ["objects", "operations", "relations", "schemas", "docs"] }
3179
- },
3180
- cursor: { type: "string", maxLength: 4096 },
3181
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize }
3182
- } },
3183
- query: {
3184
- type: "object",
3185
- required: ["kind", "scope"],
3186
- additionalProperties: false,
3187
- description: "Query one exact catalog kind. Kind ids are lower-case, singular, and must be selected from the enum; abstract names and pluralizations are invalid.",
3188
- properties: {
3189
- kind: { enum: [...CONSTAL_API_QUERY_KINDS], description: "Exact queryable kind. Never guess a kind or change its casing." },
3190
- scope: scopeSchema,
3191
- filter: { type: "object", description: "Optional catalog-advertised filter expression." },
3192
- search: { type: "string", maxLength: 512 },
3193
- order: { type: "array", maxItems: 8, items: {
3194
- type: "object",
3195
- required: ["field", "direction"],
3196
- additionalProperties: false,
3197
- properties: { field: boundedNameSchema, direction: { enum: ["ascending", "descending"] } }
3198
- } },
3199
- fields: stringListSchema,
3200
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
3201
- cursor: { type: "string", maxLength: 4096 },
3202
- asOf: { type: "integer", minimum: 0 },
3203
- range: { type: "object", required: ["start", "end"], additionalProperties: false, properties: {
3204
- start: { type: "integer", minimum: 0 },
3205
- end: { type: "integer", minimum: 0 }
3206
- } }
3207
- }
3208
- },
3209
- get: {
3210
- type: "object",
3211
- required: ["ref"],
3212
- additionalProperties: false,
3213
- description: "Read one addressable object using a complete ref returned by query, relations, runtime inspection, or a governed receipt. Do not synthesize refs.",
3214
- properties: {
3215
- ref: {
3216
- description: "Copy a complete object ref from governed output, or supply an exact supported CRN.",
3217
- anyOf: [objectRefSchema, {
3218
- type: "object",
3219
- required: ["crn"],
3220
- additionalProperties: false,
3221
- properties: { crn: exactGetCrnSchema, hash: hashSchema }
3222
- }]
3223
- },
3224
- fields: stringListSchema,
3225
- page: { type: "object", additionalProperties: false, properties: {
3226
- cursor: { type: "string", maxLength: 4096 },
3227
- limit: { type: "integer", minimum: 1, maximum: 500 }
3228
- } }
3229
- }
3230
- },
3231
- relations: { type: "object", required: ["start"], additionalProperties: false, properties: {
3232
- start: { anyOf: [objectRefSchema, {
3233
- type: "object",
3234
- required: ["crn"],
3235
- additionalProperties: false,
3236
- properties: { crn: { type: "string", minLength: 1, maxLength: 2048 }, hash: hashSchema }
3237
- }] },
3238
- direction: { enum: ["outgoing", "incoming", "both"] },
3239
- types: stringListSchema,
3240
- depth: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumRelationDepth },
3241
- limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
3242
- cursor: { type: "string", maxLength: 4096 }
3243
- } },
3244
- explainPolicy: { type: "object", required: ["action", "resource"], additionalProperties: false, properties: {
3245
- principal: { anyOf: [
3246
- { type: "string", maxLength: 2048 },
3247
- { type: "object", required: ["roles", "scopes"], additionalProperties: false, properties: {
3248
- name: { type: "string", maxLength: 2048 },
3249
- roles: {
3250
- type: "array",
3251
- maxItems: 64,
3252
- uniqueItems: true,
3253
- items: { type: "string", minLength: 1, maxLength: 2048 }
3254
- },
3255
- scopes: {
3256
- type: "array",
3257
- maxItems: 256,
3258
- uniqueItems: true,
3259
- items: { type: "string", pattern: "^(?:\\*|[a-z][a-z0-9-]{0,63}:(?:[a-z][a-z0-9-]{0,63}|\\*))$" }
3260
- }
3261
- } }
3262
- ] },
3263
- action: actionSchema,
3264
- resource: { type: "string", minLength: 1, maxLength: 2048 },
3265
- context: { type: "object" },
3266
- arguments: {},
3267
- at: { type: "object", required: ["run"], additionalProperties: false, properties: {
3268
- run: {
3269
- type: "object",
3270
- required: ["namespace", "agent", "session", "run"],
3271
- additionalProperties: false,
3272
- properties: {
3273
- namespace: boundedNameSchema,
3274
- agent: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]{0,62}$" },
3275
- session: boundedIdSchema,
3276
- run: boundedIdSchema
3277
- }
3278
- }
3279
- } }
3280
- } },
3281
- plan: { type: "object", required: ["objective", "operations"], additionalProperties: false, properties: {
3282
- objective: { type: "string", minLength: 1, maxLength: 8192 },
3283
- validateOnly: { type: "boolean" },
3284
- operations: {
3285
- type: "array",
3286
- minItems: 1,
3287
- maxItems: CONSTAL_API_BOUNDS.maximumPlanOperations,
3288
- items: { type: "object", required: ["operation", "input"], additionalProperties: false, properties: {
3289
- id: boundedIdSchema,
3290
- operation: boundedNameSchema,
3291
- target: { type: "string", maxLength: 2048 },
3292
- input: {},
3293
- expectedCurrentHash: { anyOf: [{ type: "null" }, hashSchema] },
3294
- dependsOn: { type: "array", maxItems: 64, items: boundedIdSchema }
3295
- } }
2665
+ return Number(value);
2666
+ }
2667
+ function finite(value, field2, minimum, maximum) {
2668
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum) {
2669
+ throw new TypeError(`${field2} is invalid`);
2670
+ }
2671
+ return value;
2672
+ }
2673
+ function providerPin(value) {
2674
+ const candidate = record6(value);
2675
+ 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");
2676
+ const parts = parseResourceName(candidate.crn);
2677
+ if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
2678
+ return candidate;
2679
+ }
2680
+ function resumePoint(value) {
2681
+ if (value === null) return null;
2682
+ const candidate = record6(value);
2683
+ 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))) {
2684
+ throw new TypeError("training resume point is invalid");
2685
+ }
2686
+ return candidate;
2687
+ }
2688
+ function trainingProviderMetadata(value) {
2689
+ const candidate = record6(value);
2690
+ const checkpoints = record6(candidate?.checkpoints);
2691
+ 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))) {
2692
+ throw new TypeError("Training Provider metadata is invalid");
2693
+ }
2694
+ const models = candidate.models.map((raw) => {
2695
+ const model = record6(raw);
2696
+ const pricing = record6(model?.pricing);
2697
+ 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))) {
2698
+ throw new TypeError("Training Provider model offer is invalid");
3296
2699
  }
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
- };
2700
+ return raw;
2701
+ });
2702
+ if (new Set(models.map((model) => model.id)).size !== models.length || new Set(models.map((model) => model.providerModel)).size !== models.length) {
2703
+ throw new TypeError("Training Provider model offers must be unique");
2704
+ }
2705
+ return {
2706
+ lifecycleVersion: 1,
2707
+ methods: candidate.methods,
2708
+ models,
2709
+ checkpoints
2710
+ };
2711
+ }
2712
+ function datasetRef(value, field2) {
2713
+ const candidate = record6(value);
2714
+ 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))) {
2715
+ throw new TypeError(`${field2} is invalid`);
2716
+ }
2717
+ return candidate;
2718
+ }
2719
+ function scorerRef(value, field2) {
2720
+ const candidate = record6(value);
2721
+ 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))) {
2722
+ throw new TypeError(`${field2} is invalid`);
2723
+ }
2724
+ return candidate;
2725
+ }
2726
+ function trainingRecipe(value) {
2727
+ const candidate = record6(value);
2728
+ const allowed = [
2729
+ "method",
2730
+ "baseModel",
2731
+ "dataset",
2732
+ "validationDataset",
2733
+ "scorers",
2734
+ "loraRank",
2735
+ "learningRate",
2736
+ "epochs",
2737
+ "batchSize",
2738
+ "groupSize",
2739
+ "temperature",
2740
+ "seed",
2741
+ "checkpointEvery",
2742
+ "evalEvery",
2743
+ "maxTrainTokens",
2744
+ "maxSampleTokens",
2745
+ "budgetMicroUsd"
2746
+ ];
2747
+ 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");
2748
+ const recipe = {
2749
+ method: candidate.method,
2750
+ baseModel: candidate.baseModel,
2751
+ dataset: datasetRef(candidate.dataset, "training dataset"),
2752
+ validationDataset: candidate.validationDataset === null ? null : datasetRef(candidate.validationDataset, "validation dataset"),
2753
+ scorers: candidate.scorers.map((scorer, index) => scorerRef(scorer, `training scorer ${index}`)),
2754
+ loraRank: integer(candidate.loraRank, "LoRA rank", 1, 256),
2755
+ learningRate: finite(candidate.learningRate, "learning rate", Number.MIN_VALUE, 1),
2756
+ epochs: integer(candidate.epochs, "epochs", 1, 100),
2757
+ batchSize: integer(candidate.batchSize, "batch size", 1, 256),
2758
+ groupSize: integer(candidate.groupSize, "group size", 1, 32),
2759
+ temperature: finite(candidate.temperature, "temperature", 0, 2),
2760
+ seed: integer(candidate.seed, "seed", 0, 2147483647),
2761
+ checkpointEvery: integer(candidate.checkpointEvery, "checkpoint interval", 1, 1e6),
2762
+ evalEvery: integer(candidate.evalEvery, "evaluation interval", 1, 1e6),
2763
+ maxTrainTokens: integer(candidate.maxTrainTokens, "training token limit", 1, 1e10),
2764
+ maxSampleTokens: integer(candidate.maxSampleTokens, "sample token limit", 1, 1e9),
2765
+ budgetMicroUsd: integer(candidate.budgetMicroUsd, "training budget", 1, 1e10)
2766
+ };
2767
+ if (recipe.method === "sft" && recipe.groupSize !== 1) throw new TypeError("SFT group size must be 1");
2768
+ return recipe;
2769
+ }
2770
+ function startTrainingRequest(value) {
2771
+ const candidate = record6(value);
2772
+ 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))) {
2773
+ throw new TypeError("training request is invalid");
2774
+ }
2775
+ return {
2776
+ ...candidate.jobId === void 0 ? {} : { jobId: candidate.jobId },
2777
+ ...candidate.provider === void 0 ? {} : { provider: providerPin(candidate.provider) },
2778
+ ...candidate.resumeFrom === void 0 ? {} : { resumeFrom: resumePoint(candidate.resumeFrom) },
2779
+ recipe: trainingRecipe(candidate.recipe),
2780
+ outputModelId: candidate.outputModelId
2781
+ };
2782
+ }
2783
+ function renderTrainingCompletion(input, expected) {
2784
+ const text2 = (value) => typeof value === "string" ? value : canonicalJson(value);
2785
+ return { prompt: `Input:
2786
+ ${text2(input)}
3309
2787
 
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);
2788
+ Response:
2789
+ `, completion: expected === void 0 || expected === null ? null : text2(expected) };
3318
2790
  }
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`);
2791
+
2792
+ // packages/sdk/src/model.ts
2793
+ var MODEL_COMPLETION_CAPABILITY = {
2794
+ id: "constal.model-completion",
2795
+ version: "1",
2796
+ hash: "0155be6df18b64e7f91ce9939b3c18527813f3dd06260fe65821ed071d94516a"
2797
+ };
2798
+ function modelGenerationOptions(source) {
2799
+ const { maxOutputTokens, temperature, effort } = source;
2800
+ if (maxOutputTokens !== void 0 && (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 1048576)) {
2801
+ throw new TypeError("maxOutputTokens must be an integer from 1 to 1048576");
2802
+ }
2803
+ if (temperature !== void 0 && (typeof temperature !== "number" || !Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2804
+ throw new TypeError("temperature must be a finite number from 0 to 2");
2805
+ }
2806
+ if (effort !== void 0 && (typeof effort !== "string" || !effort.trim())) {
2807
+ throw new TypeError("effort must be a nonempty model-supported string");
3322
2808
  }
2809
+ return {
2810
+ ...maxOutputTokens === void 0 ? {} : { maxOutputTokens },
2811
+ ...temperature === void 0 ? {} : { temperature },
2812
+ ...effort === void 0 ? {} : { effort }
2813
+ };
3323
2814
  }
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`);
2815
+ var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2816
+ var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2817
+ var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2818
+ function record7(value) {
2819
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2820
+ }
2821
+ function credentialHeader(value, name) {
2822
+ if (value === null || value === void 0) return null;
2823
+ const source = record7(value);
2824
+ 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`);
2825
+ return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2826
+ }
2827
+ function normalizeModelGatewayConfig(value) {
2828
+ const source = record7(value);
2829
+ 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) {
2830
+ throw new TypeError("model gateway config is invalid");
2831
+ }
2832
+ const maxOutputTokens = source.maxOutputTokens === void 0 ? 256 : Number(source.maxOutputTokens);
2833
+ const temperature = source.temperature === void 0 ? null : Number(source.temperature);
2834
+ if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens < 1 || maxOutputTokens > 8192 || temperature !== null && (!Number.isFinite(temperature) || temperature < 0 || temperature > 2)) {
2835
+ throw new TypeError("model gateway generation limits are invalid");
2836
+ }
2837
+ const normalized = {
2838
+ baseUrl: source.baseUrl,
2839
+ protocol: source.protocol,
2840
+ model: source.model,
2841
+ maxOutputTokens,
2842
+ temperature,
2843
+ gatewayAuth: credentialHeader(source.gatewayAuth, "gatewayAuth"),
2844
+ providerAuth: credentialHeader(source.providerAuth, "providerAuth")
2845
+ };
2846
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.header === normalized.providerAuth.header) {
2847
+ throw new TypeError("gateway and provider credentials cannot share one header");
3327
2848
  }
3328
- }
3329
- function scalar(value) {
3330
- return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
3331
- }
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`);
2849
+ if (normalized.gatewayAuth && normalized.providerAuth && normalized.gatewayAuth.slot === normalized.providerAuth.slot) {
2850
+ throw new TypeError("gateway and provider credentials cannot share one slot");
3335
2851
  }
3336
- exactKeys2(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
3337
- grant.actions.forEach(actionPattern);
3338
- grant.resources.forEach(resourcePattern);
2852
+ modelGatewayEndpoint(normalized);
2853
+ return normalized;
3339
2854
  }
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`);
2855
+ function modelGatewayEndpoint(config) {
2856
+ let endpoint;
2857
+ try {
2858
+ endpoint = new URL(config.baseUrl);
2859
+ } catch {
2860
+ throw new TypeError("model gateway baseUrl is invalid");
3343
2861
  }
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;
2862
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
2863
+ throw new TypeError("model gateway baseUrl must be a credential-free HTTPS URL");
3352
2864
  }
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;
2865
+ const hostname = endpoint.hostname.toLowerCase();
2866
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
2867
+ throw new TypeError("model gateway baseUrl must use a public hostname");
3357
2868
  }
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;
2869
+ const suffix = config.protocol === "anthropic" ? "v1/messages" : config.protocol === "openai" ? "v1/chat/completions" : null;
2870
+ if (!suffix) throw new TypeError("model gateway protocol is invalid");
2871
+ endpoint.pathname = `${endpoint.pathname.replace(/\/+$/u, "")}/${suffix}`.replace(/^\/+/u, "/");
2872
+ return endpoint;
2873
+ }
2874
+ function modelPrompt(args) {
2875
+ return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2876
+ }
2877
+ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2878
+ const { effort } = modelGenerationOptions(args);
2879
+ if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
2880
+ throw new TypeError("model Tool choice is invalid");
3364
2881
  }
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;
2882
+ if (args.toolChoice === "required" && !args.tools?.length) {
2883
+ throw new TypeError("required model Tool choice needs at least one offered Tool");
3370
2884
  }
3371
- throw new TypeError(`${path}.kind is invalid`);
2885
+ const prompt = modelPrompt(args);
2886
+ if (protocol === "anthropic") return {
2887
+ model,
2888
+ system: args.system ?? "",
2889
+ messages: [{ role: "user", content: prompt }],
2890
+ max_tokens: maxOutputTokens,
2891
+ ...effort === void 0 ? {} : { output_config: { effort } },
2892
+ ...temperature === null ? {} : { temperature },
2893
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
2894
+ ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
2895
+ };
2896
+ if (protocol === "openai") return {
2897
+ model,
2898
+ messages: [
2899
+ ...args.system ? [{ role: "developer", content: args.system }] : [],
2900
+ { role: "user", content: prompt }
2901
+ ],
2902
+ max_completion_tokens: maxOutputTokens,
2903
+ ...effort === void 0 ? {} : { reasoning_effort: effort },
2904
+ ...temperature === null ? {} : { temperature },
2905
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({
2906
+ type: "function",
2907
+ function: { name: tool.name, description: tool.description, parameters: tool.schema }
2908
+ })) } : {},
2909
+ ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
2910
+ };
2911
+ throw new TypeError("model gateway protocol is invalid");
3372
2912
  }
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`);
3377
- }
3378
- value.forEach((constraint, index) => validatePolicyConstraint(constraint, `${path}[${index}]`));
3379
- return value;
2913
+ function integer2(value) {
2914
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
3380
2915
  }
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;
2916
+ function costMetadata(usage) {
2917
+ const cost = usage.cost;
2918
+ const costUsd = cost === null ? null : typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
2919
+ return {
2920
+ ...costUsd !== void 0 ? { costUsd } : {},
2921
+ ...typeof usage.cost_source === "string" ? { costSource: usage.cost_source } : {},
2922
+ ...typeof usage.cost_estimated === "boolean" ? { costEstimated: usage.cost_estimated } : {}
2923
+ };
3405
2924
  }
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);
2925
+ function modelProtocolResult(protocol, raw, provider, model) {
2926
+ const source = record7(raw) ?? {};
2927
+ const toolCalls = [];
2928
+ let content2 = "";
2929
+ let usage;
2930
+ if (protocol === "anthropic") {
2931
+ const blocks = Array.isArray(source.content) ? source.content : [];
2932
+ content2 = blocks.map((candidate) => {
2933
+ const block = record7(candidate);
2934
+ if (block?.type === "text" && typeof block.text === "string") return block.text;
2935
+ if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
2936
+ toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
2937
+ }
2938
+ return "";
2939
+ }).join("");
2940
+ const values = record7(source.usage) ?? {};
2941
+ const cached = integer2(values.cache_read_input_tokens);
2942
+ usage = {
2943
+ input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
2944
+ output: integer2(values.output_tokens),
2945
+ cached,
2946
+ ...costMetadata(values)
2947
+ };
2948
+ } else if (protocol === "openai") {
2949
+ const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2950
+ const message2 = record7(choice.message) ?? {};
2951
+ content2 = typeof message2.content === "string" ? message2.content : "";
2952
+ for (const candidate of Array.isArray(message2.tool_calls) ? message2.tool_calls : []) {
2953
+ const call = record7(candidate);
2954
+ const fn = record7(call?.function);
2955
+ if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
2956
+ let args;
2957
+ try {
2958
+ args = JSON.parse(fn.arguments);
2959
+ } catch {
2960
+ throw new TypeError("OpenAI-compatible tool arguments are not valid JSON");
2961
+ }
2962
+ toolCalls.push({ id: call.id, name: fn.name, args });
2963
+ }
2964
+ const values = record7(source.usage) ?? {};
2965
+ usage = {
2966
+ input: integer2(values.prompt_tokens),
2967
+ output: integer2(values.completion_tokens),
2968
+ cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
2969
+ ...costMetadata(values)
2970
+ };
2971
+ } else throw new TypeError("model gateway protocol is invalid");
2972
+ if (!content2 && toolCalls.length === 0) throw new TypeError("model gateway response had no content or Tool calls");
2973
+ return { content: content2, ...toolCalls.length ? { toolCalls } : {}, usage, provider, model, completion: modelCompletionStatus(protocol, raw) };
3413
2974
  }
3414
- async function evaluatePolicyDefinition(definition2, input) {
3415
- return policyOutcome(await definition2.evaluate(input));
2975
+ function modelCompletionStatus(protocol, raw) {
2976
+ const source = record7(raw) ?? {};
2977
+ const value = protocol === "anthropic" ? source.stop_reason : record7(Array.isArray(source.choices) ? source.choices[0] : null)?.finish_reason;
2978
+ const reason = typeof value === "string" ? value : null;
2979
+ const complete = protocol === "anthropic" ? ["end_turn", "tool_use", "stop_sequence"] : ["stop", "tool_calls", "function_call"];
2980
+ const incomplete = protocol === "anthropic" ? ["max_tokens", "refusal", "pause_turn", "model_context_window_exceeded"] : ["length", "content_filter", "error", "cancelled", "canceled"];
2981
+ return { status: reason !== null && complete.includes(reason) ? "complete" : reason !== null && incomplete.includes(reason) ? "incomplete" : "unknown", reason };
3416
2982
  }
3417
2983
 
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 }
3434
- }
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 }] }
2984
+ // packages/sdk/src/gateway.ts
2985
+ async function checkpointArtifactRef(value) {
2986
+ return await sha256Hex(canonicalJson(value));
2987
+ }
2988
+ var SLOT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2989
+ var HASH3 = /^[a-f0-9]{64}$/u;
2990
+ var MODEL_RESOURCE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
2991
+ function httpsUrl(value, field2) {
2992
+ if (value === void 0) return;
2993
+ if (typeof value !== "string" || value.length > 2048) throw new TypeError(`${field2} is invalid`);
2994
+ let parsed;
2995
+ try {
2996
+ parsed = new URL(value);
2997
+ } catch {
2998
+ throw new TypeError(`${field2} is invalid`);
3444
2999
  }
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
- }
3000
+ if (parsed.protocol !== "https:") throw new TypeError(`${field2} is invalid`);
3001
+ }
3002
+ function slotMetadata(value) {
3003
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Gateway Credential slots are invalid");
3004
+ const entries = Object.entries(value);
3005
+ if (entries.length > 32) throw new TypeError("Gateway Credential slots are invalid");
3006
+ const output = {};
3007
+ for (const [slot, raw] of entries) {
3008
+ const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
3009
+ 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))) {
3010
+ throw new TypeError("Gateway Credential slots are invalid");
3479
3011
  }
3012
+ httpsUrl(item.documentationUrl, "Gateway Credential slot documentation URL");
3013
+ output[slot] = item;
3480
3014
  }
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`;
3015
+ return output;
3016
+ }
3017
+ function configEgressBindings(value) {
3018
+ if (value === void 0) return [];
3019
+ if (!Array.isArray(value) || value.length > 16) throw new TypeError("Gateway config egress bindings are invalid");
3020
+ return value.map((raw) => {
3021
+ const item = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : null;
3022
+ 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))) {
3023
+ throw new TypeError("Gateway config egress bindings are invalid");
3498
3024
  }
3499
- keys.add(field2.key);
3025
+ return {
3026
+ urlProperty: String(item.urlProperty),
3027
+ operations: [...new Set(item.operations)],
3028
+ methods: [...new Set(item.methods)]
3029
+ };
3030
+ });
3031
+ }
3032
+ function discoverySetup(value) {
3033
+ if (value === void 0) return void 0;
3034
+ const item = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3035
+ 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))) {
3036
+ throw new TypeError("Gateway discovery setup is invalid");
3500
3037
  }
3501
- return null;
3038
+ return { operation: String(item.operation), resultConfigProperty: String(item.resultConfigProperty) };
3502
3039
  }
3503
- function stageOutput(value) {
3504
- const error = validateStageOutputSpec(value);
3505
- if (error) throw new TypeError(error);
3506
- return value;
3040
+ function checkpointImportMetadata(value) {
3041
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3042
+ 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))) {
3043
+ throw new TypeError("Gateway checkpoint import metadata is invalid");
3044
+ }
3045
+ return { lifecycleVersion: 1, formats: [...source.formats] };
3507
3046
  }
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);
3047
+ function checkpointImportRequest(value) {
3048
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3049
+ const provenance = source?.source && typeof source.source === "object" && !Array.isArray(source.source) ? source.source : null;
3050
+ const provider = provenance?.provider && typeof provenance.provider === "object" && !Array.isArray(provenance.provider) ? provenance.provider : null;
3051
+ const checkpoint = provenance?.checkpoint && typeof provenance.checkpoint === "object" && !Array.isArray(provenance.checkpoint) ? provenance.checkpoint : null;
3052
+ const artifact = source?.artifact && typeof source.artifact === "object" && !Array.isArray(source.artifact) ? source.artifact : null;
3053
+ const artifactValue = artifact?.value && typeof artifact.value === "object" && !Array.isArray(artifact.value) ? artifact.value : null;
3054
+ const model = source?.model && typeof source.model === "object" && !Array.isArray(source.model) ? source.model : null;
3055
+ 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))) {
3056
+ throw new TypeError("checkpoint import request is invalid");
3517
3057
  }
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);
3058
+ try {
3059
+ if (new TextEncoder().encode(canonicalJson(artifactValue)).byteLength > 65536) throw new TypeError();
3060
+ } catch {
3061
+ throw new TypeError("checkpoint import request is invalid");
3528
3062
  }
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(".", "_");
3537
- return {
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`);
3063
+ try {
3064
+ parseResourceName(String(provider.crn));
3065
+ } catch {
3066
+ throw new TypeError("checkpoint import request is invalid");
3067
+ }
3068
+ return source;
3069
+ }
3070
+ function checkpointDeploymentRequest(value) {
3071
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3072
+ const gateway2 = source?.gateway && typeof source.gateway === "object" && !Array.isArray(source.gateway) ? source.gateway : null;
3073
+ 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))) {
3074
+ throw new TypeError("checkpoint deployment request is invalid");
3075
+ }
3076
+ try {
3077
+ parseResourceName(gateway2.crn);
3078
+ } catch {
3079
+ throw new TypeError("checkpoint deployment request is invalid");
3080
+ }
3081
+ return { gateway: gateway2, import: checkpointImportRequest(source.import) };
3082
+ }
3083
+ var MODEL_ID_CONTROL = /[\u0000-\u001f\u007f]/u;
3084
+ function gatewayModelOffer(value) {
3085
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3086
+ 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) => ![
3087
+ "id",
3088
+ "displayName",
3089
+ "contextTokens",
3090
+ "maxOutputTokens",
3091
+ "inputModalities",
3092
+ "outputModalities",
3093
+ "pricing"
3094
+ ].includes(key))) {
3095
+ throw new TypeError("Gateway Model offer is invalid");
3096
+ }
3097
+ const modalities = (field2) => {
3098
+ const values = source[field2];
3099
+ if (values === void 0) return void 0;
3100
+ 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) {
3101
+ throw new TypeError("Gateway Model offer is invalid");
3551
3102
  }
3103
+ return values;
3104
+ };
3105
+ const pricing = source.pricing === null ? null : modelAdvertisedPricing(source.pricing);
3106
+ const inputModalities = modalities("inputModalities");
3107
+ const outputModalities = modalities("outputModalities");
3108
+ return {
3109
+ id: source.id,
3110
+ displayName: source.displayName,
3111
+ contextTokens: Number(source.contextTokens),
3112
+ maxOutputTokens: Number(source.maxOutputTokens),
3113
+ ...inputModalities ? { inputModalities } : {},
3114
+ ...outputModalities ? { outputModalities } : {},
3115
+ pricing
3552
3116
  };
3553
3117
  }
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));
3118
+ function assertNonSecretGatewayConfig(value, field2 = "config") {
3119
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
3120
+ const source = value;
3121
+ if (source.format === "password" || /(?:secret|password|private[-_ ]?key|access[-_ ]?token|api[-_ ]?key)/iu.test(field2)) {
3122
+ throw new TypeError("Gateway secrets must use declared Credential slots");
3123
+ }
3124
+ const properties = source.properties && typeof source.properties === "object" && !Array.isArray(source.properties) ? source.properties : {};
3125
+ for (const [name, declaration] of Object.entries(properties)) assertNonSecretGatewayConfig(declaration, name);
3126
+ if (source.items) assertNonSecretGatewayConfig(source.items, field2);
3127
+ if (source.additionalProperties && typeof source.additionalProperties === "object") {
3128
+ assertNonSecretGatewayConfig(source.additionalProperties, field2);
3129
+ }
3557
3130
  }
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 }
3131
+ function gatewayPackageMetadata(value) {
3132
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : null;
3133
+ 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 ?? ""))) {
3134
+ throw new TypeError("Gateway package metadata is invalid");
3565
3135
  }
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."
3136
+ httpsUrl(source.documentationUrl, "Gateway documentation URL");
3137
+ const credentialSlots = slotMetadata(source.credentialSlots);
3138
+ const modelOffers = source.modelOffers === void 0 ? [] : Array.isArray(source.modelOffers) ? source.modelOffers.map(gatewayModelOffer) : (() => {
3139
+ throw new TypeError("Gateway Model offers are invalid");
3140
+ })();
3141
+ if (modelOffers.length > 512 || new Set(modelOffers.map((offer) => offer.id)).size !== modelOffers.length) {
3142
+ throw new TypeError("Gateway Model offers are invalid");
3143
+ }
3144
+ const capabilities = source.capabilities.map(capabilityContractRef);
3145
+ if (new Set(capabilities.map((contract) => `${contract.id}@${contract.version}#${contract.hash}`)).size !== capabilities.length) {
3146
+ throw new TypeError("Gateway capability contracts must be unique");
3147
+ }
3148
+ const egress = integrationEgressPolicy(source.egress);
3149
+ const configEgress = configEgressBindings(source.configEgress);
3150
+ const discovery = discoverySetup(source.discovery);
3151
+ const training = source.training === void 0 ? void 0 : trainingProviderMetadata(source.training);
3152
+ const checkpointImport = source.checkpointImport === void 0 ? void 0 : checkpointImportMetadata(source.checkpointImport);
3153
+ if (training && !capabilities.some((contract) => contract.id === TRAINING_PROVIDER_CAPABILITY.id && contract.version === TRAINING_PROVIDER_CAPABILITY.version && contract.hash === TRAINING_PROVIDER_CAPABILITY.hash)) {
3154
+ throw new TypeError("Training Provider packages must implement the exact Training Provider capability");
3155
+ }
3156
+ 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))) {
3157
+ throw new TypeError("Checkpoint import Gateways must implement exact completion and checkpoint import capabilities");
3158
+ }
3159
+ return {
3160
+ lifecycleVersion: 1,
3161
+ displayName: source.displayName,
3162
+ description: source.description,
3163
+ ...typeof source.documentationUrl === "string" ? { documentationUrl: source.documentationUrl } : {},
3164
+ ...typeof source.service === "string" ? { service: source.service } : {},
3165
+ credentialSlots,
3166
+ modelOffers,
3167
+ capabilities,
3168
+ billing: { upstreamPayer: source.billing.upstreamPayer },
3169
+ egress,
3170
+ ...configEgress.length ? { configEgress } : {},
3171
+ ...discovery ? { discovery } : {},
3172
+ ...training ? { training } : {},
3173
+ ...checkpointImport ? { checkpointImport } : {}
3174
+ };
3175
+ }
3176
+ function resolveGatewayEgress(metadata3, config) {
3177
+ const derived = (metadata3.configEgress ?? []).map((binding) => {
3178
+ let endpoint;
3179
+ try {
3180
+ endpoint = new URL(String(config[binding.urlProperty] ?? ""));
3181
+ } catch {
3182
+ throw new TypeError(`Gateway ${binding.urlProperty} must be an HTTPS endpoint`);
3616
3183
  }
3617
- }
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}$" }
3184
+ if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.hash || endpoint.search) {
3185
+ throw new TypeError(`Gateway ${binding.urlProperty} must be an exact HTTPS endpoint without credentials, query, or fragment`);
3641
3186
  }
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 });
3187
+ return { operations: binding.operations, origin: endpoint.origin, pathExact: endpoint.pathname, methods: binding.methods };
3188
+ });
3189
+ return integrationEgressPolicy({ rules: [...metadata3.egress.rules, ...derived] });
3190
+ }
3191
+ function gateway(definition) {
3192
+ 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" || definition.release !== void 0 && typeof definition.release !== "function") {
3193
+ throw new TypeError("Gateway definition is invalid");
3194
+ }
3195
+ const schemaError = validateJsonSchemaDefinition(definition.configSchema);
3196
+ if (schemaError) throw new TypeError(`Gateway config schema is invalid: ${schemaError}`);
3197
+ const configSchema = definition.configSchema;
3198
+ if (configSchema.type !== "object") throw new TypeError('Gateway config schema root type must be "object"');
3199
+ if (configSchema.additionalProperties !== false) throw new TypeError("Gateway config schema must reject unknown root fields");
3200
+ assertNonSecretGatewayConfig(configSchema);
3201
+ const gateway2 = gatewayPackageMetadata({
3202
+ lifecycleVersion: 1,
3203
+ displayName: definition.displayName,
3204
+ description: definition.description,
3205
+ documentationUrl: definition.documentationUrl,
3206
+ service: definition.service,
3207
+ credentialSlots: definition.credentialSlots,
3208
+ modelOffers: definition.modelOffers ?? [],
3209
+ capabilities: definition.capabilities,
3210
+ billing: definition.billing,
3211
+ egress: definition.egress,
3212
+ configEgress: definition.configEgress,
3213
+ discovery: definition.discovery,
3214
+ training: definition.training,
3215
+ checkpointImport: definition.checkpointImport
3216
+ });
3217
+ const properties = configSchema.properties && typeof configSchema.properties === "object" && !Array.isArray(configSchema.properties) ? configSchema.properties : {};
3218
+ for (const binding of gateway2.configEgress ?? []) {
3219
+ const property = properties[binding.urlProperty];
3220
+ if (!property || property.type !== "string" || property.format !== "uri") {
3221
+ throw new TypeError(`Gateway config egress property must be a URI string: ${binding.urlProperty}`);
3650
3222
  }
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 });
3223
+ }
3224
+ if (gateway2.discovery) {
3225
+ const property = properties[gateway2.discovery.resultConfigProperty];
3226
+ if (!property || property.type !== "array") throw new TypeError("Gateway discovery result config property must be an array");
3227
+ const required2 = Array.isArray(configSchema.required) ? configSchema.required : [];
3228
+ if (!required2.includes(gateway2.discovery.resultConfigProperty)) {
3229
+ throw new TypeError("Gateway discovery result config property must be required");
3654
3230
  }
3655
- throw new TypeError("cas action must be put or get");
3231
+ if (property.readOnly !== true) throw new TypeError("Gateway discovery result config property must be read-only");
3656
3232
  }
3233
+ const authoredCatalog = definition.catalog;
3234
+ const wrapped = { ...definition, metadata: gateway2, catalog(config) {
3235
+ const declarations = authoredCatalog(config);
3236
+ if (gateway2.checkpointImport) {
3237
+ const operation = declarations.find((candidate) => candidate.op === "importCheckpoint");
3238
+ if (!operation || !operation.async || operation.effect !== "reconcilable" || operation.recovery.kind !== "reconcile") {
3239
+ throw new TypeError("Checkpoint Gateway importCheckpoint must be asynchronous, reconcilable, and recovered by reconcile");
3240
+ }
3241
+ }
3242
+ return declarations;
3243
+ } };
3244
+ return Object.freeze(wrapped);
3245
+ }
3246
+ function trainingProvider(definition) {
3247
+ const authoredCatalog = definition.catalog;
3248
+ return gateway({
3249
+ ...definition,
3250
+ 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]],
3251
+ catalog(config) {
3252
+ const declarations = authoredCatalog(config);
3253
+ const train = declarations.find((operation) => operation.op === "train");
3254
+ if (!train || !train.async || train.effect !== "reconcilable" || train.recovery.kind !== "reconcile") {
3255
+ throw new TypeError("Training Provider train must be asynchronous, reconcilable, and recovered by reconcile");
3256
+ }
3257
+ return declarations;
3258
+ }
3259
+ });
3260
+ }
3261
+ var MODEL_CHECKPOINT_IMPORT_CAPABILITY = {
3262
+ id: "constal.model-checkpoint-import",
3263
+ version: "1",
3264
+ hash: "49563823899586a87dcee82e9db969af5f2f5364adb3eb808a19e86b862e87ba"
3657
3265
  };
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
- }
3266
+ var MCP_CLIENT_CAPABILITY = {
3267
+ id: "constal.mcp-client",
3268
+ version: "1",
3269
+ hash: "a694af71191432e75980dc73962d9239dc8ea324aff084f183a2f45603bd2267"
3676
3270
  };
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
- ];
3748
3271
 
3749
3272
  // packages/sdk/src/credential-provider.ts
3750
3273
  function assertNonSecretConfigSchema(value, field2 = "config") {
@@ -3868,12 +3391,12 @@ function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
3868
3391
  return action3;
3869
3392
  }
3870
3393
  function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
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;
3394
+ const result = interactionRecord(value);
3395
+ if (!result || !exactKeys3(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
3396
+ const privateState = result.privateState;
3874
3397
  if (privateState !== void 0 && privateState !== null && (typeof privateState !== "string" || new TextEncoder().encode(privateState).byteLength > 1048576)) throw new TypeError("credential interaction private state is invalid");
3875
3398
  return {
3876
- action: credentialInteractionAction(result2.action, origins, state, sessionExpiresAt),
3399
+ action: credentialInteractionAction(result.action, origins, state, sessionExpiresAt),
3877
3400
  ...privateState === void 0 ? {} : { privateState }
3878
3401
  };
3879
3402
  }
@@ -3917,30 +3440,30 @@ function credentialProviderSetupMetadata(value, slots) {
3917
3440
  }
3918
3441
  return value;
3919
3442
  }
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") {
3443
+ function credentialProvider(definition) {
3444
+ 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") {
3922
3445
  throw new TypeError("credential provider metadata is invalid");
3923
3446
  }
3924
- if (definition2.documentationUrl !== void 0) {
3925
- if (typeof definition2.documentationUrl !== "string") throw new TypeError("credential provider documentation URL is invalid");
3447
+ if (definition.documentationUrl !== void 0) {
3448
+ if (typeof definition.documentationUrl !== "string") throw new TypeError("credential provider documentation URL is invalid");
3926
3449
  let documentationUrl;
3927
3450
  try {
3928
- documentationUrl = new URL(definition2.documentationUrl);
3451
+ documentationUrl = new URL(definition.documentationUrl);
3929
3452
  } catch {
3930
3453
  throw new TypeError("credential provider documentation URL is invalid");
3931
3454
  }
3932
- if (definition2.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
3455
+ if (definition.documentationUrl.length > 2048 || documentationUrl.protocol !== "https:") {
3933
3456
  throw new TypeError("credential provider documentation URL is invalid");
3934
3457
  }
3935
3458
  }
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))) {
3459
+ credentialRotationDefaults(definition.rotation);
3460
+ credentialProviderConfigSchema(definition.configSchema);
3461
+ credentialProviderConfigSchema(definition.credentialConfigSchema);
3462
+ 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))) {
3940
3463
  throw new TypeError("credential provider bootstrap slots are invalid");
3941
3464
  }
3942
- const setup = credentialProviderSetupMetadata(definition2.setup, definition2.credentialSlots);
3943
- const interaction = definition2.interaction ?? null;
3465
+ const setup = credentialProviderSetupMetadata(definition.setup, definition.credentialSlots);
3466
+ const interaction = definition.interaction ?? null;
3944
3467
  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) => {
3945
3468
  try {
3946
3469
  const url = new URL(origin);
@@ -3951,120 +3474,165 @@ function credentialProvider(definition2) {
3951
3474
  }))) {
3952
3475
  throw new TypeError("credential provider interaction origins are invalid");
3953
3476
  }
3954
- const mintRecovery = definition2.mintRecovery ?? { kind: "idempotency-key" };
3477
+ const mintRecovery = definition.mintRecovery ?? { kind: "idempotency-key" };
3955
3478
  if (!["idempotency-key", "outcome-unknown"].includes(mintRecovery.kind)) {
3956
3479
  throw new TypeError("credential provider mint recovery is invalid");
3957
3480
  }
3958
3481
  if (interaction && (typeof interaction.start !== "function" || typeof interaction.advance !== "function")) {
3959
3482
  throw new TypeError("credential provider interaction is invalid");
3960
3483
  }
3961
- const metadata2 = {
3484
+ const metadata3 = {
3962
3485
  lifecycleVersion: 3,
3963
- displayName: definition2.displayName,
3964
- description: definition2.description,
3965
- ...definition2.documentationUrl ? { documentationUrl: definition2.documentationUrl } : {},
3486
+ displayName: definition.displayName,
3487
+ description: definition.description,
3488
+ ...definition.documentationUrl ? { documentationUrl: definition.documentationUrl } : {},
3966
3489
  ...setup ? { setup } : {},
3967
- credentialSlots: [...definition2.credentialSlots].sort(),
3968
- credentialConfigSchema: definition2.credentialConfigSchema,
3490
+ credentialSlots: [...definition.credentialSlots].sort(),
3491
+ credentialConfigSchema: definition.credentialConfigSchema,
3969
3492
  interaction: interaction ? { origins: [...interaction.origins].sort() } : null,
3970
- rotation: definition2.rotation,
3971
- egress: integrationEgressPolicy(definition2.egress)
3493
+ rotation: definition.rotation,
3494
+ egress: integrationEgressPolicy(definition.egress)
3972
3495
  };
3973
- return Object.freeze({ ...definition2, mintRecovery, metadata: metadata2 });
3496
+ return Object.freeze({ ...definition, mintRecovery, metadata: metadata3 });
3974
3497
  }
3975
3498
 
3976
- // packages/sdk/src/sandbox-build.ts
3977
- var recipeProperties = {
3978
- context: { type: "string", minLength: 1 },
3979
- dockerfile: { type: "string", minLength: 1 },
3980
- target: { type: "string", minLength: 1 },
3981
- platform: { type: "string", minLength: 1 },
3982
- buildArgs: { type: "object", additionalProperties: { type: "string" } },
3983
- cache: { type: "boolean" }
3984
- };
3985
- var SANDBOX_IMAGE_BUILD_SCHEMA = {
3986
- type: "object",
3987
- additionalProperties: false,
3988
- required: ["sandbox"],
3989
- properties: {
3990
- ...recipeProperties,
3991
- sandbox: { type: "string", pattern: "^sbx-[a-f0-9]{36}$" },
3992
- secretTargets: { type: "object", additionalProperties: { type: "string", minLength: 1 } },
3993
- registryTargets: { type: "object", additionalProperties: {
3994
- type: "object",
3995
- required: ["username", "slot"],
3996
- additionalProperties: false,
3997
- properties: { username: { type: "string" }, slot: { type: "string", minLength: 1 } }
3998
- } }
3999
- }
4000
- };
4001
- function sandboxImageBuildInput(value) {
4002
- const invalid = validateJsonSchema(value, { type: "object", additionalProperties: false, properties: {
4003
- ...recipeProperties,
4004
- secrets: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA },
4005
- registries: { type: "object", additionalProperties: {
4006
- type: "object",
4007
- required: ["username", "credential"],
4008
- additionalProperties: false,
4009
- properties: { username: { type: "string" }, credential: RESOURCE_CREDENTIAL_BINDING_SCHEMA }
4010
- } }
4011
- } });
4012
- if (invalid) throw new TypeError(`Invalid sandbox image build: ${invalid}`);
4013
- const result2 = structuredClone(value);
4014
- for (const binding of Object.values(result2.secrets ?? {})) resourceCredentialBinding(binding);
4015
- for (const registry of Object.values(result2.registries ?? {})) resourceCredentialBinding(registry.credential);
4016
- return result2;
3499
+ // packages/sdk/src/mcp.ts
3500
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
3501
+ function record8(value) {
3502
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
4017
3503
  }
4018
-
4019
- // packages/sdk/src/sandbox-pool.ts
4020
- var WORKSPACE_ROOT = "/workspace";
4021
- function absoluteSandboxPath(value) {
4022
- const segments = [];
4023
- for (const segment of value.split("/")) {
4024
- if (!segment || segment === ".") continue;
4025
- if (segment === "..") segments.pop();
4026
- else segments.push(segment);
3504
+ function mcpToolDescription(value) {
3505
+ const tool = record8(value), inputSchema = record8(tool?.inputSchema);
3506
+ const outputSchema = tool?.outputSchema === void 0 ? {} : record8(tool.outputSchema);
3507
+ if (!tool || typeof tool.name !== "string" || !tool.name || tool.description !== void 0 && typeof tool.description !== "string" || !inputSchema || outputSchema === null) throw new TerminalIntegrationFailure("MCP server advertised an invalid tool");
3508
+ return {
3509
+ name: tool.name,
3510
+ description: typeof tool.description === "string" ? tool.description : "",
3511
+ inputSchema,
3512
+ outputSchema,
3513
+ annotations: record8(tool.annotations) ?? {}
3514
+ };
3515
+ }
3516
+ function mcpToolResult(value) {
3517
+ const result = record8(value);
3518
+ if (!result || result.isError !== void 0 && typeof result.isError !== "boolean" || result?.content !== void 0 && !Array.isArray(result.content) || result?.structuredContent !== void 0 && !record8(result.structuredContent) || result && result.content === void 0 && result.structuredContent === void 0) {
3519
+ throw new TerminalIntegrationFailure("MCP tools/call result is invalid");
4027
3520
  }
4028
- return `/${segments.join("/")}`;
3521
+ return result;
4029
3522
  }
4030
- function normalizeSandboxWorkspacePath(path, cwd = WORKSPACE_ROOT) {
4031
- if (typeof path !== "string" || !path || typeof cwd !== "string" || !cwd || new TextEncoder().encode(path).byteLength > 4096 || new TextEncoder().encode(cwd).byteLength > 4096 || /[\u0000-\u001f\u007f]/u.test(path) || /[\u0000-\u001f\u007f]/u.test(cwd)) {
4032
- throw new TypeError("sandbox workspace path is invalid");
3523
+ function message(value) {
3524
+ const item = record8(value);
3525
+ if (!item || item.jsonrpc !== "2.0") throw new TerminalIntegrationFailure("MCP transport returned an invalid JSON-RPC message");
3526
+ return item;
3527
+ }
3528
+ var McpClient = class {
3529
+ constructor(transport, options = {}) {
3530
+ this.transport = transport;
3531
+ this.options = options;
3532
+ this.#protocol = options.state?.protocolVersion ?? null;
3533
+ this.#next = options.state?.nextRequestId ?? 0;
3534
+ if (!Number.isSafeInteger(this.#next) || this.#next < 0 || this.#protocol !== null && !this.#protocol) {
3535
+ throw new TypeError("invalid MCP client state");
3536
+ }
4033
3537
  }
4034
- const base = absoluteSandboxPath(cwd.startsWith("/") ? cwd : `${WORKSPACE_ROOT}/${cwd}`);
4035
- if (base !== WORKSPACE_ROOT && !base.startsWith(`${WORKSPACE_ROOT}/`)) {
4036
- throw new TypeError("sandbox working directory is outside /workspace");
3538
+ transport;
3539
+ options;
3540
+ #protocol;
3541
+ #next;
3542
+ #tail = Promise.resolve();
3543
+ state() {
3544
+ if (!this.#protocol) throw new TerminalIntegrationFailure("MCP session is not initialized");
3545
+ return { protocolVersion: this.#protocol, nextRequestId: this.#next };
3546
+ }
3547
+ async #serialized(operation) {
3548
+ const prior = this.#tail;
3549
+ let release;
3550
+ this.#tail = new Promise((resolve) => {
3551
+ release = resolve;
3552
+ });
3553
+ await prior;
3554
+ try {
3555
+ return await operation();
3556
+ } finally {
3557
+ release();
3558
+ }
4037
3559
  }
4038
- const normalized = absoluteSandboxPath(path.startsWith("/") ? path : `${base}/${path}`);
4039
- if (normalized !== WORKSPACE_ROOT && !normalized.startsWith(`${WORKSPACE_ROOT}/`)) {
4040
- throw new TypeError("sandbox path is outside /workspace");
3560
+ async #response(id2) {
3561
+ for (; ; ) {
3562
+ const received = message(await this.transport.receive());
3563
+ if (received.id === id2) {
3564
+ if (record8(received.error)) {
3565
+ const error = received.error;
3566
+ throw new TerminalIntegrationFailure(`MCP ${typeof error.code === "number" || typeof error.code === "string" ? error.code : "unknown"}: ${typeof error.message === "string" ? error.message : "request failed"}`);
3567
+ }
3568
+ if (!Object.hasOwn(received, "result")) throw new TerminalIntegrationFailure("MCP response has no result");
3569
+ return received.result;
3570
+ }
3571
+ if (typeof received.method === "string") {
3572
+ if (received.id !== void 0) {
3573
+ await this.transport.send(received.method === "ping" ? { jsonrpc: "2.0", id: received.id, result: {} } : { jsonrpc: "2.0", id: received.id, error: { code: -32601, message: "Method not found" } });
3574
+ } else await this.options.onNotification?.({ method: received.method, ...received.params === void 0 ? {} : { params: received.params } });
3575
+ continue;
3576
+ }
3577
+ throw new TerminalIntegrationFailure("MCP response id does not match the active request");
3578
+ }
4041
3579
  }
4042
- return normalized;
4043
- }
4044
- var SANDBOX_PROCESS_CREDENTIALS_SCHEMA = { type: "object", additionalProperties: false, properties: {
4045
- env: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA },
4046
- files: { type: "object", additionalProperties: RESOURCE_CREDENTIAL_BINDING_SCHEMA }
4047
- } };
4048
- function processCredentialMaps(value, resolve) {
4049
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("process credentials are invalid");
4050
- const source = value;
4051
- if (Object.keys(source).some((key) => key !== "env" && key !== "files")) throw new TypeError("process credential kind is invalid");
4052
- const result2 = {};
4053
- for (const kind of ["env", "files"]) {
4054
- const entries = source[kind];
4055
- if (entries === void 0) continue;
4056
- if (!entries || typeof entries !== "object" || Array.isArray(entries)) throw new TypeError("process credential map is invalid");
4057
- result2[kind] = Object.fromEntries(Object.entries(entries).map(([name, binding]) => {
4058
- if (!name || name.includes("=") || name.includes("\0")) throw new TypeError("process credential variable is invalid");
4059
- return [name, resolve(binding)];
3580
+ async #request(method, params) {
3581
+ return this.#serialized(async () => {
3582
+ const id2 = ++this.#next;
3583
+ await this.transport.send({ jsonrpc: "2.0", id: id2, method, params });
3584
+ return this.#response(id2);
3585
+ });
3586
+ }
3587
+ async initialize() {
3588
+ if (this.#protocol) return { protocolVersion: this.#protocol, server: {} };
3589
+ const result = record8(await this.#request("initialize", {
3590
+ protocolVersion: MCP_PROTOCOL_VERSION,
3591
+ capabilities: {},
3592
+ clientInfo: this.options.client ?? { name: "Constal", version: "1.0.0" }
4060
3593
  }));
3594
+ if (!result || typeof result.protocolVersion !== "string" || !result.protocolVersion) {
3595
+ throw new TerminalIntegrationFailure("MCP initialize result is invalid");
3596
+ }
3597
+ this.#protocol = result.protocolVersion;
3598
+ await this.transport.negotiated?.(this.#protocol);
3599
+ await this.#serialized(() => this.transport.send({ jsonrpc: "2.0", method: "notifications/initialized" }));
3600
+ return { protocolVersion: this.#protocol, server: record8(result.serverInfo) ?? {} };
3601
+ }
3602
+ async request(method, params) {
3603
+ if (!this.#protocol) throw new TerminalIntegrationFailure("MCP session is not initialized");
3604
+ return this.#request(method, params);
3605
+ }
3606
+ async tools() {
3607
+ const tools = [], cursors = /* @__PURE__ */ new Set();
3608
+ let cursor;
3609
+ do {
3610
+ const result = record8(await this.request("tools/list", cursor ? { cursor } : {}));
3611
+ if (!result || !Array.isArray(result.tools) || result.tools.some((item) => !record8(item))) {
3612
+ throw new TerminalIntegrationFailure("MCP tools/list result is invalid");
3613
+ }
3614
+ tools.push(...result.tools);
3615
+ if (result.nextCursor === void 0 || result.nextCursor === null) cursor = void 0;
3616
+ else if (typeof result.nextCursor !== "string" || !result.nextCursor) {
3617
+ throw new TerminalIntegrationFailure("MCP tools/list cursor is invalid");
3618
+ } else if (cursors.has(result.nextCursor)) {
3619
+ throw new TerminalIntegrationFailure("MCP server returned a repeated pagination cursor");
3620
+ } else {
3621
+ cursor = result.nextCursor;
3622
+ cursors.add(cursor);
3623
+ }
3624
+ } while (cursor);
3625
+ return tools;
4061
3626
  }
4062
- if (Object.keys(result2.env ?? {}).some((name) => Object.hasOwn(result2.files ?? {}, name))) throw new TypeError("a process variable cannot receive both a value and a file path");
4063
- return result2;
4064
- }
4065
- function sandboxProcessCredentials(value) {
4066
- return processCredentialMaps(value, resourceCredentialBinding);
4067
- }
3627
+ callTool(name, args) {
3628
+ if (!name) throw new TypeError("MCP tool name is required");
3629
+ return this.request("tools/call", { name, arguments: args });
3630
+ }
3631
+ async close() {
3632
+ await this.#tail;
3633
+ await this.transport.close();
3634
+ }
3635
+ };
4068
3636
 
4069
3637
  // packages/sdk/src/scorer.ts
4070
3638
  function validPointer(value) {
@@ -4200,12 +3768,12 @@ function evaluate(rule, subject) {
4200
3768
  }
4201
3769
  function evaluateCodeScorer(raw, subject) {
4202
3770
  const ir = codeScorerIR(raw);
4203
- const result2 = evaluate(ir.rule, subject);
3771
+ const result = evaluate(ir.rule, subject);
4204
3772
  return {
4205
- score: result2.pass ? 1 : 0,
4206
- pass: result2.pass,
3773
+ score: result.pass ? 1 : 0,
3774
+ pass: result.pass,
4207
3775
  dimensions: null,
4208
- evidence: { rule: canonicalJson(ir.rule), checks: result2.checks, failures: result2.failures.slice(0, 64) }
3776
+ evidence: { rule: canonicalJson(ir.rule), checks: result.checks, failures: result.failures.slice(0, 64) }
4209
3777
  };
4210
3778
  }
4211
3779
 
@@ -4291,33 +3859,33 @@ var CommitConflict = class extends Error {
4291
3859
  actual;
4292
3860
  };
4293
3861
  var ResourceInvalid = class extends Error {
4294
- constructor(resource2) {
4295
- super(`invalid resource: ${resource2}`);
4296
- this.resource = resource2;
3862
+ constructor(resource) {
3863
+ super(`invalid resource: ${resource}`);
3864
+ this.resource = resource;
4297
3865
  this.name = "ResourceInvalid";
4298
3866
  }
4299
3867
  resource;
4300
3868
  };
4301
3869
  var ResourceUnbound = class extends Error {
4302
- constructor(resource2) {
4303
- super(`resource is not bound to this execution: ${resource2}`);
4304
- this.resource = resource2;
3870
+ constructor(resource) {
3871
+ super(`resource is not bound to this execution: ${resource}`);
3872
+ this.resource = resource;
4305
3873
  this.name = "ResourceUnbound";
4306
3874
  }
4307
3875
  resource;
4308
3876
  };
4309
3877
  var ToolUnavailable = class extends Error {
4310
- constructor(tool2) {
4311
- super(`Tool is not enabled for this Agent deployment: ${tool2}`);
4312
- this.tool = tool2;
3878
+ constructor(tool) {
3879
+ super(`Tool is not enabled for this Agent deployment: ${tool}`);
3880
+ this.tool = tool;
4313
3881
  this.name = "ToolUnavailable";
4314
3882
  }
4315
3883
  tool;
4316
3884
  };
4317
3885
  var UnknownTool = class extends Error {
4318
- constructor(tool2) {
4319
- super(`model emitted a Tool that was not offered: ${tool2}`);
4320
- this.tool = tool2;
3886
+ constructor(tool) {
3887
+ super(`model emitted a Tool that was not offered: ${tool}`);
3888
+ this.tool = tool;
4321
3889
  this.name = "UnknownTool";
4322
3890
  }
4323
3891
  tool;
@@ -4333,9 +3901,9 @@ var EffectCeilingExceeded = class extends Error {
4333
3901
  observed;
4334
3902
  };
4335
3903
  var ResourceDisabled = class extends Error {
4336
- constructor(resource2) {
4337
- super(`resource is disabled: ${resource2}`);
4338
- this.resource = resource2;
3904
+ constructor(resource) {
3905
+ super(`resource is disabled: ${resource}`);
3906
+ this.resource = resource;
4339
3907
  this.name = "ResourceDisabled";
4340
3908
  }
4341
3909
  resource;
@@ -4396,23 +3964,21 @@ export {
4396
3964
  CONSTAL_API_OPERATION_SCHEMAS,
4397
3965
  CONSTAL_API_QUERY_KINDS,
4398
3966
  CONSTAL_API_VERSION,
4399
- CONSTAL_MODEL_CREATE_SCHEMA,
4400
3967
  CommitConflict,
4401
3968
  CommitGateRejected,
4402
3969
  CredentialRevoked,
4403
3970
  CredentialUnavailable,
4404
3971
  DirectNetworkDenied,
4405
3972
  EffectCeilingExceeded,
4406
- GATEWAY_MODEL_OFFER_SCHEMA,
4407
3973
  GateExhausted,
4408
3974
  IntegrationRequestNotSent,
4409
3975
  LeaseLost,
4410
3976
  MCP_CLIENT_CAPABILITY,
3977
+ MCP_PROTOCOL_VERSION,
4411
3978
  MEMORY_OPERATION_DECLARATIONS,
4412
3979
  MODEL_CHECKPOINT_IMPORT_CAPABILITY,
4413
3980
  MODEL_COMPLETION_CAPABILITY,
4414
- MODEL_GENERATION_OPTIONS_SCHEMA,
4415
- MODEL_GENERATION_OPTION_KEYS,
3981
+ McpClient,
4416
3982
  NondeterministicReplay,
4417
3983
  OutcomeUnknown,
4418
3984
  PolicyConstraintFailed,
@@ -4423,7 +3989,6 @@ export {
4423
3989
  ResourceInvalid,
4424
3990
  ResourceUnbound,
4425
3991
  RollbackTargetInvalid,
4426
- SANDBOX_PROCESS_CREDENTIALS_SCHEMA,
4427
3992
  SessionDeleted,
4428
3993
  SpawnCardinality,
4429
3994
  SwallowedYield,
@@ -4441,7 +4006,6 @@ export {
4441
4006
  agentSetupMetadata,
4442
4007
  agentSetupRequirements,
4443
4008
  analyticsEvent,
4444
- applyModelProviderOptions,
4445
4009
  approximateTokens,
4446
4010
  authProvider,
4447
4011
  authProviderName,
@@ -4461,7 +4025,9 @@ export {
4461
4025
  checkpointImportMetadata,
4462
4026
  checkpointImportRequest,
4463
4027
  codeScorerIR,
4464
- connections,
4028
+ containerImageReference,
4029
+ containerImageSelection,
4030
+ containerImageSource,
4465
4031
  credentialEvidence,
4466
4032
  credentialInteractionAction,
4467
4033
  credentialInteractionEvent,
@@ -4484,12 +4050,15 @@ export {
4484
4050
  gatewayPackageMetadata,
4485
4051
  hash,
4486
4052
  hashValue,
4053
+ immutableContainerImageReference,
4487
4054
  integrationEgressPolicy,
4055
+ invocationCredentialUses,
4488
4056
  labelSelector,
4489
4057
  matchesAction,
4490
4058
  matchesLabelSelector,
4491
4059
  matchesResource,
4492
- mcpProtocol,
4060
+ mcpToolDescription,
4061
+ mcpToolResult,
4493
4062
  memoryStoreBinding,
4494
4063
  modelAdvertisedPricing,
4495
4064
  modelControls,
@@ -4500,9 +4069,7 @@ export {
4500
4069
  modelPrompt,
4501
4070
  modelProtocolRequest,
4502
4071
  modelProtocolResult,
4503
- modelProviderOptions,
4504
4072
  murmur3_32,
4505
- normalizeInvocationOptions,
4506
4073
  normalizeModelGatewayConfig,
4507
4074
  normalizeSandboxNetworkPolicy,
4508
4075
  normalizeSandboxWorkspacePath,
@@ -4513,14 +4080,12 @@ export {
4513
4080
  policyName,
4514
4081
  renderTrainingCompletion,
4515
4082
  resolveBindingOwner,
4083
+ resolveContainerImageSource,
4516
4084
  resolveGatewayEgress,
4517
4085
  resolveResourceDependencyRef,
4518
- resourceContext,
4519
4086
  resourceContractRef,
4520
4087
  resourceCredentialBinding,
4521
- resourceCredentialBindings,
4522
4088
  resourceDependencyRef,
4523
- resourceIndex,
4524
4089
  resourceLabelMap,
4525
4090
  resourceName,
4526
4091
  resourceNeed,
@@ -4528,9 +4093,7 @@ export {
4528
4093
  resourceSelector,
4529
4094
  resourceTools,
4530
4095
  sandboxControls,
4531
- sandboxImageBuildInput,
4532
4096
  sandboxLimit,
4533
- sandboxProcessCredentials,
4534
4097
  scopedBindingKey,
4535
4098
  scopedCredentialRef,
4536
4099
  scopedResourceRef,