@constal/sdk 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/publish/index.js CHANGED
@@ -12,8 +12,8 @@ function canonicalJson(value) {
12
12
  if (typeof value === "string") return JSON.stringify(value);
13
13
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
14
14
  if (typeof value === "object") {
15
- const record8 = value;
16
- return `{${Object.keys(record8).sort().filter((key) => record8[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(record8[key])}`).join(",")}}`;
15
+ const record9 = value;
16
+ return `{${Object.keys(record9).sort().filter((key) => record9[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(record9[key])}`).join(",")}}`;
17
17
  }
18
18
  throw new TypeError(`canonical JSON does not support ${typeof value}`);
19
19
  }
@@ -107,8 +107,8 @@ function field(row, name, purpose) {
107
107
  return row[name];
108
108
  }
109
109
  function approximateTokens(value) {
110
- const text = typeof value === "string" ? value : canonicalJson(value);
111
- return Math.max(1, Math.ceil(encoder2.encode(text).byteLength / 4));
110
+ const text2 = typeof value === "string" ? value : canonicalJson(value);
111
+ return Math.max(1, Math.ceil(encoder2.encode(text2).byteLength / 4));
112
112
  }
113
113
  function cutByWeight(rows, limit2, weight, framing) {
114
114
  const partitions = [];
@@ -276,21 +276,21 @@ function validateJsonSchema(value, schema, path = "$") {
276
276
  if (typeof rule.multipleOf === "number" && Math.abs(value / rule.multipleOf - Math.round(value / rule.multipleOf)) > Number.EPSILON * 8) return `${path} is not a multiple`;
277
277
  }
278
278
  if (value && typeof value === "object" && !Array.isArray(value)) {
279
- const record8 = value;
280
- for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in record8)) return `${path}.${key} is required`;
279
+ const record9 = value;
280
+ for (const key of Array.isArray(rule.required) ? rule.required : []) if (typeof key === "string" && !(key in record9)) return `${path}.${key} is required`;
281
281
  const properties = rule.properties && typeof rule.properties === "object" && !Array.isArray(rule.properties) ? rule.properties : {};
282
- if (typeof rule.minProperties === "number" && Object.keys(record8).length < rule.minProperties) return `${path} has too few properties`;
283
- if (typeof rule.maxProperties === "number" && Object.keys(record8).length > rule.maxProperties) return `${path} has too many properties`;
282
+ if (typeof rule.minProperties === "number" && Object.keys(record9).length < rule.minProperties) return `${path} has too few properties`;
283
+ if (typeof rule.maxProperties === "number" && Object.keys(record9).length > rule.maxProperties) return `${path} has too many properties`;
284
284
  if (rule.additionalProperties === false) {
285
- const extra = Object.keys(record8).find((key) => !(key in properties));
285
+ const extra = Object.keys(record9).find((key) => !(key in properties));
286
286
  if (extra) return `${path}.${extra} is not allowed`;
287
287
  }
288
- for (const [key, child] of Object.entries(properties)) if (key in record8) {
289
- const error = validateJsonSchema(record8[key], child, `${path}.${key}`);
288
+ for (const [key, child] of Object.entries(properties)) if (key in record9) {
289
+ const error = validateJsonSchema(record9[key], child, `${path}.${key}`);
290
290
  if (error) return error;
291
291
  }
292
- if (rule.additionalProperties && typeof rule.additionalProperties === "object") for (const key of Object.keys(record8).filter((candidate) => !(candidate in properties))) {
293
- const error = validateJsonSchema(record8[key], rule.additionalProperties, `${path}.${key}`);
292
+ if (rule.additionalProperties && typeof rule.additionalProperties === "object") for (const key of Object.keys(record9).filter((candidate) => !(candidate in properties))) {
293
+ const error = validateJsonSchema(record9[key], rule.additionalProperties, `${path}.${key}`);
294
294
  if (error) return error;
295
295
  }
296
296
  }
@@ -392,6 +392,7 @@ function matchesLabelSelector(selector, labels) {
392
392
  var RESOURCE_KINDS = [
393
393
  "agent",
394
394
  "channel",
395
+ "ui",
395
396
  "auth-provider",
396
397
  "policy",
397
398
  "credential-provider",
@@ -425,6 +426,17 @@ var PLATFORM_ADDRESS_KINDS = [
425
426
  ];
426
427
  var INVOKABLE_KINDS = ["model", "memory", "cas", "web", "service", "mcp", "db", "browser", "sandbox-pool", "vault"];
427
428
  var POLICY_TARGET_KINDS = [...RESOURCE_KINDS, ...PLATFORM_ADDRESS_KINDS];
429
+ var UI_RESOURCE_BOUNDS = Object.freeze({
430
+ maximumRequestBodyBytes: 1048576,
431
+ maximumResponseBodyBytes: 16777216,
432
+ maximumCpuMs: 3e4,
433
+ maximumSubrequests: 100,
434
+ maximumDatabaseBytes: 1073741824,
435
+ maximumRowsReadPerRequest: 1e6,
436
+ maximumRowsWrittenPerRequest: 1e5,
437
+ maximumSqlResultBytes: 1048576
438
+ });
439
+ var ACTION_PATTERN = /^[a-z][a-z0-9-]{0,63}:[a-z][a-z0-9-]{0,63}$/u;
428
440
  var SEGMENT = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
429
441
  var PATH = /^[A-Za-z0-9._~/%-]{1,512}$/u;
430
442
  var NAME2 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
@@ -587,6 +599,10 @@ function authProviderName(value) {
587
599
  if (parseResourceName(value).kind !== "auth-provider") throw new TypeError("AuthProvider CRN is invalid");
588
600
  return value;
589
601
  }
602
+ function uiName(value) {
603
+ if (parseResourceName(value).kind !== "ui") throw new TypeError("UI CRN is invalid");
604
+ return value;
605
+ }
590
606
  function policyName(value) {
591
607
  if (parseResourceName(value).kind !== "policy") throw new TypeError("Policy CRN is invalid");
592
608
  return value;
@@ -624,7 +640,7 @@ function matchesResource(pattern, value) {
624
640
  return wildcard(pattern, value);
625
641
  }
626
642
  function action(value) {
627
- if (!/^[a-z][a-z0-9-]{0,63}:[a-z][a-z0-9-]{0,63}$/u.test(value)) throw new TypeError("action is invalid");
643
+ if (!ACTION_PATTERN.test(value)) throw new TypeError("action is invalid");
628
644
  return value;
629
645
  }
630
646
  function actionPattern(value) {
@@ -777,6 +793,7 @@ function validateTool(tool, path = "tool") {
777
793
  requiredString(tool.version, `${path}.version`);
778
794
  if (!["read-only", "idempotent", "reconcilable", "non-idempotent"].includes(tool.maxEffect)) throw new TypeError(`${path}.maxEffect is invalid`);
779
795
  tool.needs?.forEach(resourceNeed);
796
+ if (tool.preview !== void 0 && typeof tool.preview !== "function") throw new TypeError(`${path}.preview must be a function`);
780
797
  if (typeof tool.run !== "function") throw new TypeError(`${path}.run must be a function`);
781
798
  return tool;
782
799
  }
@@ -866,6 +883,481 @@ function channel(definition) {
866
883
  return definition;
867
884
  }
868
885
 
886
+ // src/ui.ts
887
+ var PATH2 = /^(?!\/)(?!.*(?:^|\/)\.\.?\/?)(?!.*\/\/)[A-Za-z0-9._~/-]{1,256}$/u;
888
+ var CONTENT_TYPE = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:; charset=utf-8)?$/u;
889
+ var BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
890
+ var SECRET = /(?:sk_(?:live|test)_[A-Za-z0-9]{16,}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|CONSTAL_API_KEY\s*=|\.env(?:\.|\/|$))/u;
891
+ var PLATFORM_MODULE_PREFIX = "__constal_";
892
+ var UI_BUNDLE_BOUNDS = Object.freeze({
893
+ maximumManifestBytes: 16384,
894
+ maximumModules: 128,
895
+ maximumAssets: 512,
896
+ maximumFileBytes: 4194304,
897
+ maximumExpandedBytes: 16777216
898
+ });
899
+ function object(value, message) {
900
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError(message);
901
+ return value;
902
+ }
903
+ function exactKeys(value, allowed, required2) {
904
+ if (Object.keys(value).some((key) => !allowed.includes(key)) || required2.some((key) => !Object.hasOwn(value, key))) {
905
+ throw new TypeError("UI bundle contains unsupported fields");
906
+ }
907
+ }
908
+ function safePath(value, label) {
909
+ if (typeof value !== "string" || !PATH2.test(value) || value.split("/").some((part) => part === "." || part === "..")) {
910
+ throw new TypeError(`${label} is invalid`);
911
+ }
912
+ return value;
913
+ }
914
+ function byteLength(value) {
915
+ return new TextEncoder().encode(value).byteLength;
916
+ }
917
+ function uiBundleManifest(value, execution) {
918
+ const manifest = object(value, "UI bundle manifest is invalid");
919
+ exactKeys(
920
+ manifest,
921
+ ["schemaVersion", "kind", "runtime", "state", "assets", "contentSecurityPolicy"],
922
+ ["schemaVersion", "kind", "runtime", "assets", "contentSecurityPolicy"]
923
+ );
924
+ const runtime = object(manifest.runtime, "UI bundle runtime is invalid");
925
+ const assets = object(manifest.assets, "UI bundle assets manifest is invalid");
926
+ exactKeys(runtime, ["contract", "entry"], ["contract", "entry"]);
927
+ exactKeys(assets, ["root", "fallback"], ["root", "fallback"]);
928
+ 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");
929
+ const entry = safePath(runtime.entry, "UI bundle entry");
930
+ const root = safePath(assets.root, "UI asset root");
931
+ const fallback = safePath(assets.fallback, "UI asset fallback");
932
+ if (!entry.endsWith(".mjs") || fallback.startsWith(`${root}/`)) throw new TypeError("UI bundle entry or asset fallback is invalid");
933
+ if (byteLength(JSON.stringify(manifest)) > UI_BUNDLE_BOUNDS.maximumManifestBytes) throw new TypeError("UI bundle manifest exceeds 16 KiB");
934
+ let state;
935
+ if (execution === "stateless") {
936
+ if (manifest.state !== void 0) throw new TypeError("stateless UI bundles cannot declare SQLite state");
937
+ } else {
938
+ const raw = object(manifest.state, "durable UI bundles require a state manifest");
939
+ const compatible = object(raw.compatibleSchemaVersions, "UI state compatibility is invalid");
940
+ exactKeys(raw, ["schemaVersion", "compatibleSchemaVersions"], ["schemaVersion", "compatibleSchemaVersions"]);
941
+ exactKeys(compatible, ["minimum", "maximum"], ["minimum", "maximum"]);
942
+ const version = Number(raw.schemaVersion);
943
+ const minimum = Number(compatible.minimum);
944
+ const maximum = Number(compatible.maximum);
945
+ if (!Number.isSafeInteger(version) || version < 1 || ![minimum, maximum].every((item) => Number.isSafeInteger(item) && item >= 0) || minimum > version || version > maximum) throw new TypeError("UI state schema compatibility is invalid");
946
+ state = { schemaVersion: version, compatibleSchemaVersions: { minimum, maximum } };
947
+ }
948
+ return {
949
+ schemaVersion: 1,
950
+ kind: "constal.ui",
951
+ runtime: { contract: "constal.ui-handler.v1", entry },
952
+ ...state ? { state } : {},
953
+ assets: { root, fallback },
954
+ contentSecurityPolicy: "strict"
955
+ };
956
+ }
957
+ function uiBundle(value, execution) {
958
+ const bundle = object(value, "UI bundle is invalid");
959
+ exactKeys(bundle, ["manifest", "modules", "assets"], ["manifest", "modules", "assets"]);
960
+ const manifest = uiBundleManifest(bundle.manifest, execution);
961
+ const modules = object(bundle.modules, "UI bundle modules are invalid");
962
+ const assets = object(bundle.assets, "UI bundle assets are invalid");
963
+ const moduleEntries = Object.entries(modules);
964
+ const assetEntries = Object.entries(assets);
965
+ if (moduleEntries.length < 1 || moduleEntries.length > UI_BUNDLE_BOUNDS.maximumModules || assetEntries.length > UI_BUNDLE_BOUNDS.maximumAssets || !Object.hasOwn(modules, manifest.runtime.entry)) {
966
+ throw new TypeError("UI bundle file inventory is invalid");
967
+ }
968
+ const paths = /* @__PURE__ */ new Set();
969
+ let expandedBytes = 0;
970
+ const normalizedModules = {};
971
+ for (const [rawPath, rawModule] of moduleEntries.sort(([left], [right]) => left.localeCompare(right))) {
972
+ const path = safePath(rawPath, "UI module path");
973
+ const module = object(rawModule, "UI module is invalid");
974
+ exactKeys(module, ["type", "source"], ["type", "source"]);
975
+ if (path.split("/").some((part) => part.startsWith(PLATFORM_MODULE_PREFIX))) {
976
+ throw new TypeError("UI module path uses the reserved platform namespace");
977
+ }
978
+ if (module.type !== "esmodule" || typeof module.source !== "string" || SECRET.test(module.source)) throw new TypeError("UI module is invalid or contains secret material");
979
+ const bytes = byteLength(module.source);
980
+ if (bytes > UI_BUNDLE_BOUNDS.maximumFileBytes || paths.has(path)) throw new TypeError("UI module path or size is invalid");
981
+ paths.add(path);
982
+ expandedBytes += bytes;
983
+ normalizedModules[path] = { type: "esmodule", source: module.source };
984
+ }
985
+ const normalizedAssets = {};
986
+ for (const [rawPath, rawAsset] of assetEntries.sort(([left], [right]) => left.localeCompare(right))) {
987
+ const path = safePath(rawPath, "UI asset path");
988
+ const asset = object(rawAsset, "UI asset is invalid");
989
+ exactKeys(asset, ["bodyBase64", "contentType"], ["bodyBase64", "contentType"]);
990
+ if (typeof asset.bodyBase64 !== "string" || !BASE64.test(asset.bodyBase64) || typeof asset.contentType !== "string" || !CONTENT_TYPE.test(asset.contentType) || paths.has(path)) throw new TypeError("UI asset is invalid");
991
+ const bytes = Math.floor(asset.bodyBase64.length * 3 / 4) - (asset.bodyBase64.endsWith("==") ? 2 : asset.bodyBase64.endsWith("=") ? 1 : 0);
992
+ if (bytes > UI_BUNDLE_BOUNDS.maximumFileBytes) throw new TypeError("UI asset exceeds the file limit");
993
+ paths.add(path);
994
+ expandedBytes += bytes;
995
+ normalizedAssets[path] = { bodyBase64: asset.bodyBase64, contentType: asset.contentType };
996
+ }
997
+ if (!Object.hasOwn(normalizedAssets, `${manifest.assets.root}/${manifest.assets.fallback}`)) {
998
+ throw new TypeError("UI bundle fallback asset is unavailable");
999
+ }
1000
+ if (expandedBytes > UI_BUNDLE_BOUNDS.maximumExpandedBytes) throw new TypeError("UI bundle exceeds the expanded-size limit");
1001
+ return { manifest, modules: normalizedModules, assets: normalizedAssets };
1002
+ }
1003
+
1004
+ // src/setup-workflow.ts
1005
+ var ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1006
+ var CRN = /^crn:constal:[a-z0-9-]+:[a-z0-9-]+:[a-z0-9-]+:credential-provider\/[A-Za-z0-9._~/%-]{1,512}$/u;
1007
+ var MAX_SCREEN_BYTES = 262144;
1008
+ function record3(value) {
1009
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1010
+ }
1011
+ function text(value, maximum, allowEmpty = false) {
1012
+ return typeof value === "string" && value.length <= maximum && (allowEmpty || value.trim().length > 0) ? value : null;
1013
+ }
1014
+ function exact(value, fields) {
1015
+ return Object.keys(value).every((key) => fields.includes(key));
1016
+ }
1017
+ function action2(value) {
1018
+ const source = record3(value);
1019
+ const id2 = text(source?.id, 63);
1020
+ const label = text(source?.label, 128);
1021
+ if (!source || !id2 || !ID.test(id2) || !label || !["primary", "secondary", "danger"].includes(String(source.intent)) || !exact(source, ["id", "label", "intent"])) return null;
1022
+ return { id: id2, label, intent: source.intent };
1023
+ }
1024
+ function actions(value) {
1025
+ if (!Array.isArray(value) || value.length > 8) return null;
1026
+ const parsed = value.map(action2);
1027
+ if (parsed.some((item) => !item) || new Set(parsed.map((item) => item.id)).size !== parsed.length) return null;
1028
+ return parsed;
1029
+ }
1030
+ function panelBase(source) {
1031
+ const id2 = text(source.id, 63);
1032
+ const title = text(source.title, 256);
1033
+ const description = text(source.description, 4096, true);
1034
+ const parsedActions = actions(source.actions);
1035
+ return id2 && ID.test(id2) && title && description !== null && parsedActions ? { id: id2, title, description, actions: parsedActions } : null;
1036
+ }
1037
+ function panel(value) {
1038
+ const source = record3(value);
1039
+ if (!source) return null;
1040
+ const base = panelBase(source);
1041
+ if (!base) return null;
1042
+ if (source.kind === "form") {
1043
+ const schema = record3(source.schema);
1044
+ const initialValues = source.initialValues === void 0 ? void 0 : record3(source.initialValues);
1045
+ if (!schema || validateJsonSchemaDefinition(schema, "$setup.current.schema") || schema.type !== "object" || schema.additionalProperties !== false || Object.keys(record3(schema.properties) ?? {}).length > 64 || initialValues === null || initialValues && validateJsonSchema(initialValues, schema) || !exact(source, ["kind", "id", "title", "description", "actions", "schema", "initialValues"])) return null;
1046
+ return { ...base, kind: "form", schema, ...initialValues ? { initialValues } : {} };
1047
+ }
1048
+ if (source.kind === "credential-interaction") {
1049
+ const provider = text(source.provider, 1024);
1050
+ const credentialId = text(source.credentialId, 63);
1051
+ if (!provider || !CRN.test(provider) || !credentialId || !ID.test(credentialId) || !["connect", "reauthorize", "manage"].includes(String(source.operation)) || !exact(source, ["kind", "id", "title", "description", "actions", "provider", "credentialId", "operation"])) return null;
1052
+ return {
1053
+ ...base,
1054
+ kind: "credential-interaction",
1055
+ provider,
1056
+ credentialId,
1057
+ operation: source.operation
1058
+ };
1059
+ }
1060
+ if (source.kind === "review") {
1061
+ if (!Array.isArray(source.sections) || source.sections.length > 32 || !exact(source, ["kind", "id", "title", "description", "actions", "sections"])) return null;
1062
+ const sections = [];
1063
+ for (const rawSection of source.sections) {
1064
+ const section = record3(rawSection);
1065
+ const id2 = text(section?.id, 63);
1066
+ const title = text(section?.title, 256);
1067
+ if (!section || !id2 || !ID.test(id2) || !title || !Array.isArray(section.rows) || section.rows.length > 64 || !exact(section, ["id", "title", "rows"])) return null;
1068
+ const rows = [];
1069
+ for (const rawRow of section.rows) {
1070
+ const row = record3(rawRow);
1071
+ const label = text(row?.label, 256);
1072
+ const rowValue = text(row?.value, 8192, true);
1073
+ if (!row || !label || rowValue === null || row.tone !== void 0 && !["default", "muted", "warning"].includes(String(row.tone)) || !exact(row, ["label", "value", "tone"])) return null;
1074
+ rows.push({ label, value: rowValue, ...row.tone ? { tone: row.tone } : {} });
1075
+ }
1076
+ sections.push({ id: id2, title, rows });
1077
+ }
1078
+ return { ...base, kind: "review", sections };
1079
+ }
1080
+ if (source.kind === "progress") {
1081
+ if (!Array.isArray(source.progress) || source.progress.length > 64 || !exact(source, ["kind", "id", "title", "description", "actions", "progress"])) return null;
1082
+ const progress = [];
1083
+ for (const rawItem of source.progress) {
1084
+ const item = record3(rawItem);
1085
+ const id2 = text(item?.id, 63);
1086
+ const label = text(item?.label, 256);
1087
+ const detail = item?.detail === void 0 ? void 0 : text(item.detail, 4096, true);
1088
+ if (!item || !id2 || !ID.test(id2) || !label || detail === null || !["pending", "running", "complete", "failed"].includes(String(item.status)) || !exact(item, ["id", "label", "status", "detail"])) return null;
1089
+ progress.push({ id: id2, label, status: item.status, ...detail === void 0 ? {} : { detail } });
1090
+ }
1091
+ return { ...base, kind: "progress", progress };
1092
+ }
1093
+ if (source.kind === "complete" || source.kind === "blocked") {
1094
+ const summary = text(source.summary, 8192);
1095
+ const details = source.details === void 0 ? [] : source.details;
1096
+ if (!summary || !Array.isArray(details) || details.length > 64 || !exact(source, ["kind", "id", "title", "description", "actions", "summary", "details"])) return null;
1097
+ const parsedDetails = [];
1098
+ for (const rawDetail of details) {
1099
+ const detail = record3(rawDetail);
1100
+ const label = text(detail?.label, 256);
1101
+ const detailValue = text(detail?.value, 8192, true);
1102
+ if (!detail || !label || detailValue === null || !exact(detail, ["label", "value"])) return null;
1103
+ parsedDetails.push({ label, value: detailValue });
1104
+ }
1105
+ return { ...base, kind: source.kind, summary, ...parsedDetails.length ? { details: parsedDetails } : {} };
1106
+ }
1107
+ return null;
1108
+ }
1109
+ function setupScreen(value) {
1110
+ const source = record3(value);
1111
+ const workflow = record3(source?.workflow);
1112
+ const current = panel(source?.current);
1113
+ if (!source || source.object !== "constal.setup.screen" || source.version !== 1 || !workflow || !current || !ID.test(String(workflow.id ?? "")) || !text(workflow.version, 64) || !ID.test(String(workflow.targetAgent ?? "")) || !Number.isSafeInteger(source.revision) || Number(source.revision) < 1 || !["active", "blocked", "complete", "cancelled"].includes(String(source.status)) || !text(source.title, 256) || text(source.description, 4096, true) === null || !Array.isArray(source.steps) || source.steps.length < 1 || source.steps.length > 64 || source.waitLabel !== null && !text(source.waitLabel, 256) || !exact(workflow, ["id", "version", "targetAgent"]) || !exact(source, ["object", "version", "workflow", "revision", "status", "title", "description", "steps", "current", "waitLabel"])) {
1114
+ throw new TypeError("Setup screen is invalid");
1115
+ }
1116
+ const parsedSteps = [];
1117
+ for (const rawStep of source.steps) {
1118
+ const step = record3(rawStep);
1119
+ const id2 = text(step?.id, 63);
1120
+ const label = text(step?.label, 128);
1121
+ if (!step || !id2 || !ID.test(id2) || !label || !["pending", "current", "complete", "blocked"].includes(String(step.status)) || step.optional !== void 0 && typeof step.optional !== "boolean" || !exact(step, ["id", "label", "status", "optional"])) throw new TypeError("Setup screen step is invalid");
1122
+ parsedSteps.push({ id: id2, label, status: step.status, ...step.optional === void 0 ? {} : { optional: step.optional } });
1123
+ }
1124
+ if (new Set(parsedSteps.map(({ id: id2 }) => id2)).size !== parsedSteps.length || parsedSteps.filter(({ status }) => status === "current").length > 1 || source.status === "active" && parsedSteps.filter(({ status }) => status === "current").length !== 1 || source.status === "active" && !source.waitLabel || source.status !== "active" && source.waitLabel !== null || source.status === "complete" && current.kind !== "complete" || source.status === "blocked" && current.kind !== "blocked") throw new TypeError("Setup screen state is inconsistent");
1125
+ const normalized = {
1126
+ object: "constal.setup.screen",
1127
+ version: 1,
1128
+ workflow: { id: String(workflow.id), version: String(workflow.version), targetAgent: String(workflow.targetAgent) },
1129
+ revision: Number(source.revision),
1130
+ status: source.status,
1131
+ title: String(source.title),
1132
+ description: String(source.description),
1133
+ steps: parsedSteps,
1134
+ current,
1135
+ waitLabel: source.waitLabel === null ? null : String(source.waitLabel)
1136
+ };
1137
+ if (new TextEncoder().encode(canonicalJson(normalized)).byteLength > MAX_SCREEN_BYTES) throw new TypeError("Setup screen exceeds 256 KiB");
1138
+ return normalized;
1139
+ }
1140
+ function setupSubmission(value, screen) {
1141
+ const source = record3(value);
1142
+ const values = source?.values === void 0 ? void 0 : record3(source.values);
1143
+ if (!source || source.object !== "constal.setup.submission" || source.version !== 1 || source.workflow !== screen.workflow.id || source.revision !== screen.revision || source.step !== screen.current.id || !screen.current.actions.some(({ id: id2 }) => id2 === source.action) || values === null || !exact(source, ["object", "version", "workflow", "revision", "step", "action", "values"])) {
1144
+ throw new TypeError("Setup submission is stale or invalid");
1145
+ }
1146
+ if (screen.current.kind === "form" && source.action === screen.current.actions.find(({ intent }) => intent === "primary")?.id) {
1147
+ const error = validateJsonSchema(values ?? {}, screen.current.schema, "$setup.submission.values");
1148
+ if (error) throw new TypeError(error);
1149
+ }
1150
+ return {
1151
+ object: "constal.setup.submission",
1152
+ version: 1,
1153
+ workflow: String(source.workflow),
1154
+ revision: Number(source.revision),
1155
+ step: String(source.step),
1156
+ action: String(source.action),
1157
+ ...values ? { values } : {}
1158
+ };
1159
+ }
1160
+ function setupAwait(screen) {
1161
+ if (screen.status !== "active" || !screen.waitLabel) throw new TypeError("Only an active Setup screen can open a wait");
1162
+ return { maxBytes: 262144, schema: {
1163
+ type: "object",
1164
+ additionalProperties: false,
1165
+ required: ["object", "version", "workflow", "revision", "step", "action"],
1166
+ properties: {
1167
+ object: { const: "constal.setup.submission" },
1168
+ version: { const: 1 },
1169
+ workflow: { const: screen.workflow.id },
1170
+ revision: { const: screen.revision },
1171
+ step: { const: screen.current.id },
1172
+ action: { enum: screen.current.actions.map(({ id: id2 }) => id2) },
1173
+ values: { type: "object", additionalProperties: true }
1174
+ }
1175
+ } };
1176
+ }
1177
+ function setupScreenView(id2 = "setup-screen") {
1178
+ if (!ID.test(id2)) throw new TypeError("Setup view id is invalid");
1179
+ return {
1180
+ id: id2,
1181
+ version: "1",
1182
+ over: "facts",
1183
+ init: () => null,
1184
+ apply(state, fact) {
1185
+ const artifact = record3(fact.artifact);
1186
+ if (artifact?.object !== "constal.setup.screen") return state;
1187
+ return setupScreen(artifact);
1188
+ }
1189
+ };
1190
+ }
1191
+
1192
+ // src/constal-api.ts
1193
+ var CONSTAL_API_CAPABILITY = "constal.api";
1194
+ var CONSTAL_API_VERSION = "1";
1195
+ var CONSTAL_API_OPERATIONS = [
1196
+ "describe",
1197
+ "query",
1198
+ "get",
1199
+ "relations",
1200
+ "explainPolicy",
1201
+ "plan",
1202
+ "apply",
1203
+ "observe"
1204
+ ];
1205
+ var CONSTAL_API_BOUNDS = {
1206
+ defaultPageSize: 50,
1207
+ maximumPageSize: 200,
1208
+ maximumRelationDepth: 3,
1209
+ maximumPlanOperations: 64,
1210
+ maximumInputBytes: 1048576,
1211
+ planTtlMs: 15 * 6e4
1212
+ };
1213
+ var boundedNameSchema = { type: "string", minLength: 1, maxLength: 128, pattern: "^[A-Za-z][A-Za-z0-9._-]{0,127}$" };
1214
+ var actionSchema = { type: "string", pattern: ACTION_PATTERN.source };
1215
+ var boundedIdSchema = { type: "string", minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9][A-Za-z0-9._~:-]{0,255}$" };
1216
+ var hashSchema = { type: "string", pattern: "^[a-f0-9]{64}$" };
1217
+ var stringListSchema = { type: "array", maxItems: 128, items: { type: "string", minLength: 1, maxLength: 256 } };
1218
+ var scopeSchema = { anyOf: [
1219
+ {
1220
+ type: "object",
1221
+ required: ["kind", "namespace"],
1222
+ additionalProperties: false,
1223
+ properties: { kind: { const: "namespace" }, namespace: boundedNameSchema }
1224
+ },
1225
+ { type: "object", required: ["kind"], additionalProperties: false, properties: { kind: { const: "tenant" } } }
1226
+ ] };
1227
+ var objectRefSchema = { type: "object", additionalProperties: false, properties: {
1228
+ kind: { type: "string", maxLength: 128 },
1229
+ id: { type: "string", maxLength: 512 },
1230
+ crn: { type: ["string", "null"], maxLength: 2048 },
1231
+ hash: { anyOf: [{ type: "null" }, hashSchema] },
1232
+ namespace: { type: ["string", "null"], maxLength: 128 },
1233
+ version: { type: ["string", "null"], maxLength: 128 }
1234
+ } };
1235
+ var CONSTAL_API_OPERATION_SCHEMAS = {
1236
+ describe: { type: "object", additionalProperties: false, properties: {
1237
+ domains: stringListSchema,
1238
+ kinds: stringListSchema,
1239
+ operations: stringListSchema,
1240
+ include: {
1241
+ type: "array",
1242
+ maxItems: 5,
1243
+ uniqueItems: true,
1244
+ items: { enum: ["objects", "operations", "relations", "schemas", "docs"] }
1245
+ },
1246
+ cursor: { type: "string", maxLength: 4096 },
1247
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize }
1248
+ } },
1249
+ query: { type: "object", required: ["kind", "scope"], additionalProperties: false, properties: {
1250
+ kind: boundedNameSchema,
1251
+ scope: scopeSchema,
1252
+ filter: { type: "object" },
1253
+ search: { type: "string", maxLength: 512 },
1254
+ order: { type: "array", maxItems: 8, items: {
1255
+ type: "object",
1256
+ required: ["field", "direction"],
1257
+ additionalProperties: false,
1258
+ properties: { field: boundedNameSchema, direction: { enum: ["ascending", "descending"] } }
1259
+ } },
1260
+ fields: stringListSchema,
1261
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1262
+ cursor: { type: "string", maxLength: 4096 },
1263
+ asOf: { type: "integer", minimum: 0 },
1264
+ range: { type: "object", required: ["start", "end"], additionalProperties: false, properties: {
1265
+ start: { type: "integer", minimum: 0 },
1266
+ end: { type: "integer", minimum: 0 }
1267
+ } }
1268
+ } },
1269
+ get: { type: "object", required: ["ref"], additionalProperties: false, properties: {
1270
+ ref: { anyOf: [objectRefSchema, {
1271
+ type: "object",
1272
+ required: ["crn"],
1273
+ additionalProperties: false,
1274
+ properties: { crn: { type: "string", minLength: 1, maxLength: 2048 }, hash: hashSchema }
1275
+ }] },
1276
+ fields: stringListSchema,
1277
+ page: { type: "object", additionalProperties: false, properties: {
1278
+ cursor: { type: "string", maxLength: 4096 },
1279
+ limit: { type: "integer", minimum: 1, maximum: 500 }
1280
+ } }
1281
+ } },
1282
+ relations: { type: "object", required: ["start"], additionalProperties: false, properties: {
1283
+ start: { anyOf: [objectRefSchema, {
1284
+ type: "object",
1285
+ required: ["crn"],
1286
+ additionalProperties: false,
1287
+ properties: { crn: { type: "string", minLength: 1, maxLength: 2048 }, hash: hashSchema }
1288
+ }] },
1289
+ direction: { enum: ["outgoing", "incoming", "both"] },
1290
+ types: stringListSchema,
1291
+ depth: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumRelationDepth },
1292
+ limit: { type: "integer", minimum: 1, maximum: CONSTAL_API_BOUNDS.maximumPageSize },
1293
+ cursor: { type: "string", maxLength: 4096 }
1294
+ } },
1295
+ explainPolicy: { type: "object", required: ["action", "resource"], additionalProperties: false, properties: {
1296
+ principal: { anyOf: [
1297
+ { type: "string", maxLength: 2048 },
1298
+ { type: "object", required: ["roles", "scopes"], additionalProperties: false, properties: {
1299
+ name: { type: "string", maxLength: 2048 },
1300
+ roles: {
1301
+ type: "array",
1302
+ maxItems: 64,
1303
+ uniqueItems: true,
1304
+ items: { type: "string", minLength: 1, maxLength: 2048 }
1305
+ },
1306
+ scopes: {
1307
+ type: "array",
1308
+ maxItems: 256,
1309
+ uniqueItems: true,
1310
+ items: { type: "string", pattern: "^(?:\\*|[a-z][a-z0-9-]{0,63}:(?:[a-z][a-z0-9-]{0,63}|\\*))$" }
1311
+ }
1312
+ } }
1313
+ ] },
1314
+ action: actionSchema,
1315
+ resource: { type: "string", minLength: 1, maxLength: 2048 },
1316
+ context: { type: "object" },
1317
+ arguments: {},
1318
+ at: { type: "object", required: ["run"], additionalProperties: false, properties: {
1319
+ run: {
1320
+ type: "object",
1321
+ required: ["namespace", "agent", "session", "run"],
1322
+ additionalProperties: false,
1323
+ properties: {
1324
+ namespace: boundedNameSchema,
1325
+ agent: { type: "string", minLength: 1, maxLength: 63, pattern: "^[a-z0-9][a-z0-9-]{0,62}$" },
1326
+ session: boundedIdSchema,
1327
+ run: boundedIdSchema
1328
+ }
1329
+ }
1330
+ } }
1331
+ } },
1332
+ plan: { type: "object", required: ["objective", "operations"], additionalProperties: false, properties: {
1333
+ objective: { type: "string", minLength: 1, maxLength: 8192 },
1334
+ validateOnly: { type: "boolean" },
1335
+ operations: {
1336
+ type: "array",
1337
+ minItems: 1,
1338
+ maxItems: CONSTAL_API_BOUNDS.maximumPlanOperations,
1339
+ items: { type: "object", required: ["operation", "input"], additionalProperties: false, properties: {
1340
+ id: boundedIdSchema,
1341
+ operation: boundedNameSchema,
1342
+ target: { type: "string", maxLength: 2048 },
1343
+ input: {},
1344
+ expectedCurrentHash: { anyOf: [{ type: "null" }, hashSchema] },
1345
+ dependsOn: { type: "array", maxItems: 64, items: boundedIdSchema }
1346
+ } }
1347
+ }
1348
+ } },
1349
+ apply: { type: "object", required: ["plan", "eventId"], additionalProperties: false, properties: {
1350
+ plan: {
1351
+ type: "object",
1352
+ required: ["id", "hash"],
1353
+ additionalProperties: false,
1354
+ properties: { id: boundedIdSchema, hash: hashSchema }
1355
+ },
1356
+ eventId: boundedIdSchema
1357
+ } },
1358
+ observe: { type: "object", required: ["id"], additionalProperties: false, properties: { id: boundedIdSchema } }
1359
+ };
1360
+
869
1361
  // src/policy-governance.ts
870
1362
  var SANDBOX_CONTRACT = {
871
1363
  id: "constal.sandbox-pool",
@@ -877,6 +1369,11 @@ var MODEL_CONTRACT = {
877
1369
  version: "1",
878
1370
  hash: "76dd0da40da46adabb6837f911b25ed6f675c965e5d4d919077ee9c3945fbca7"
879
1371
  };
1372
+ var UI_CONTRACT = {
1373
+ id: "constal.ui",
1374
+ version: "1",
1375
+ hash: "133f0ab76ca2f1435dfbaa151652cfc79926ea5237c0892d0c4d3b96d7bb6f48"
1376
+ };
880
1377
  var sandboxSchema = {
881
1378
  type: "object",
882
1379
  additionalProperties: false,
@@ -922,6 +1419,9 @@ function modelControls(values) {
922
1419
  function modelLimit(input) {
923
1420
  return limit(MODEL_CONTRACT, ["cached_input_tokens", "input_tokens", "output_tokens", "requests"], input);
924
1421
  }
1422
+ function uiLimit(input) {
1423
+ return limit(UI_CONTRACT, ["requests"], input);
1424
+ }
925
1425
  function validatePolicyGovernanceConstraint(value) {
926
1426
  if (value.kind === "resource-controls") {
927
1427
  if (!value.contract || typeof value.contract.id !== "string" || typeof value.contract.version !== "string" || !/^[a-f0-9]{64}$/u.test(value.contract.hash) || !value.values || typeof value.values !== "object" || Array.isArray(value.values)) {
@@ -938,7 +1438,7 @@ var MAX_OUTCOME_BYTES = 65536;
938
1438
  var MAX_REASON_BYTES = 1024;
939
1439
  var DENIAL_CODE = /^[a-z][a-z0-9._-]{0,127}$/u;
940
1440
  var encoder3 = new TextEncoder();
941
- function record3(value) {
1441
+ function record4(value) {
942
1442
  return !!value && typeof value === "object" && !Array.isArray(value);
943
1443
  }
944
1444
  function requiredString2(value, path, maximum = 1024) {
@@ -946,7 +1446,7 @@ function requiredString2(value, path, maximum = 1024) {
946
1446
  throw new TypeError(`${path} must be a bounded non-empty string`);
947
1447
  }
948
1448
  }
949
- function exactKeys(value, allowed, required2, path) {
1449
+ function exactKeys2(value, allowed, required2, path) {
950
1450
  if (Object.keys(value).some((key) => !allowed.includes(key)) || required2.some((key) => !Object.hasOwn(value, key))) {
951
1451
  throw new TypeError(`${path} has invalid keys`);
952
1452
  }
@@ -955,10 +1455,10 @@ function scalar(value) {
955
1455
  return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
956
1456
  }
957
1457
  function validateGrant(grant, path) {
958
- if (!record3(grant) || !Array.isArray(grant.actions) || grant.actions.length === 0 || grant.actions.length > 256 || !Array.isArray(grant.resources) || grant.resources.length === 0 || grant.resources.length > 256 || !Number.isSafeInteger(grant.ttlMs) || grant.ttlMs < 1 || grant.ttlMs > 864e5) {
1458
+ 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) {
959
1459
  throw new TypeError(`${path} is invalid`);
960
1460
  }
961
- exactKeys(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
1461
+ exactKeys2(grant, ["actions", "resources", "ttlMs"], ["actions", "resources", "ttlMs"], path);
962
1462
  grant.actions.forEach(actionPattern);
963
1463
  grant.resources.forEach(resourcePattern);
964
1464
  }
@@ -976,19 +1476,19 @@ function validatePolicyConstraint(constraint, path = "constraint") {
976
1476
  return;
977
1477
  }
978
1478
  if (constraint.kind === "arguments") {
979
- exactKeys(source, ["kind", "schema"], ["kind", "schema"], path);
980
- if (!record3(constraint.schema) || validateJsonSchemaDefinition(constraint.schema)) throw new TypeError(`${path}.schema is invalid`);
1479
+ exactKeys2(source, ["kind", "schema"], ["kind", "schema"], path);
1480
+ if (!record4(constraint.schema) || validateJsonSchemaDefinition(constraint.schema)) throw new TypeError(`${path}.schema is invalid`);
981
1481
  return;
982
1482
  }
983
1483
  if (constraint.kind === "context") {
984
- exactKeys(source, ["kind", "equals"], ["kind", "equals"], path);
985
- if (!record3(constraint.equals) || Object.keys(constraint.equals).length === 0 || Object.keys(constraint.equals).length > 64 || Object.entries(constraint.equals).some(([key, value]) => !key || key.length > 256 || !scalar(value))) {
1484
+ exactKeys2(source, ["kind", "equals"], ["kind", "equals"], path);
1485
+ 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))) {
986
1486
  throw new TypeError(`${path}.equals is invalid`);
987
1487
  }
988
1488
  return;
989
1489
  }
990
1490
  if (constraint.kind === "credential-binding") {
991
- exactKeys(source, ["kind", "source", "consumer"], ["kind", "source", "consumer"], path);
1491
+ exactKeys2(source, ["kind", "source", "consumer"], ["kind", "source", "consumer"], path);
992
1492
  credentialName(constraint.source);
993
1493
  parseResourceName(constraint.consumer);
994
1494
  return;
@@ -1004,25 +1504,25 @@ function validateConstraints(value, path, required2) {
1004
1504
  return value;
1005
1505
  }
1006
1506
  function policyOutcome(value) {
1007
- if (!record3(value) || typeof value.kind !== "string") throw new TypeError("Policy outcome is invalid");
1008
- if (value.kind === "allow") exactKeys(value, ["kind"], ["kind"], "Policy allow outcome");
1507
+ if (!record4(value) || typeof value.kind !== "string") throw new TypeError("Policy outcome is invalid");
1508
+ if (value.kind === "allow") exactKeys2(value, ["kind"], ["kind"], "Policy allow outcome");
1009
1509
  else if (value.kind === "deny") {
1010
- exactKeys(value, ["kind", "code", "reason"], ["kind", "code"], "Policy deny outcome");
1510
+ exactKeys2(value, ["kind", "code", "reason"], ["kind", "code"], "Policy deny outcome");
1011
1511
  if (typeof value.code !== "string" || !DENIAL_CODE.test(value.code)) throw new TypeError("Policy denial code is invalid");
1012
1512
  if (value.reason !== void 0) requiredString2(value.reason, "Policy denial reason", MAX_REASON_BYTES);
1013
1513
  } else if (value.kind === "constrain") {
1014
- exactKeys(value, ["kind", "constraints"], ["kind", "constraints"], "Policy constrain outcome");
1514
+ exactKeys2(value, ["kind", "constraints"], ["kind", "constraints"], "Policy constrain outcome");
1015
1515
  validateConstraints(value.constraints, "Policy constraints", true);
1016
1516
  } else if (value.kind === "substitute") {
1017
- exactKeys(value, ["kind", "value", "constraints"], ["kind", "value"], "Policy substitute outcome");
1517
+ exactKeys2(value, ["kind", "value", "constraints"], ["kind", "value"], "Policy substitute outcome");
1018
1518
  canonicalJson(value.value);
1019
1519
  validateConstraints(value.constraints, "Policy constraints", false);
1020
1520
  } else if (value.kind === "require-approval") {
1021
- exactKeys(value, ["kind", "reason", "constraints"], ["kind"], "Policy approval outcome");
1521
+ exactKeys2(value, ["kind", "reason", "constraints"], ["kind"], "Policy approval outcome");
1022
1522
  if (value.reason !== void 0) requiredString2(value.reason, "Policy approval reason", MAX_REASON_BYTES);
1023
1523
  validateConstraints(value.constraints, "Policy constraints", false);
1024
1524
  } else if (value.kind === "grant") {
1025
- exactKeys(value, ["kind", "grant"], ["kind", "grant"], "Policy grant outcome");
1525
+ exactKeys2(value, ["kind", "grant"], ["kind", "grant"], "Policy grant outcome");
1026
1526
  validateGrant(value.grant, "Policy grant");
1027
1527
  } else throw new TypeError("Policy outcome kind is invalid");
1028
1528
  if (encoder3.encode(canonicalJson(value)).byteLength > MAX_OUTCOME_BYTES) throw new TypeError("Policy outcome is oversized");
@@ -1030,10 +1530,10 @@ function policyOutcome(value) {
1030
1530
  }
1031
1531
 
1032
1532
  // src/policy.ts
1033
- var ID = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1533
+ var ID2 = /^[a-z0-9][a-z0-9-]{0,62}$/u;
1034
1534
  var VERSION3 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;
1035
1535
  function policy(definition) {
1036
- if (!definition || typeof definition !== "object" || Array.isArray(definition) || Object.keys(definition).some((key) => !["id", "version", "evaluate"].includes(key)) || !ID.test(definition.id) || !VERSION3.test(definition.version) || typeof definition.evaluate !== "function") throw new TypeError("Policy definition is invalid");
1536
+ 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");
1037
1537
  return Object.freeze(definition);
1038
1538
  }
1039
1539
  async function evaluatePolicyDefinition(definition, input) {
@@ -1163,12 +1663,13 @@ function opTool(binding, op, override = {}) {
1163
1663
  name,
1164
1664
  version: "catalog",
1165
1665
  description: override.description ?? `Invoke ${op} on the bound ${binding} resource.`,
1166
- schema: { type: "object", additionalProperties: false },
1666
+ schema: override.schema ?? { type: "object", additionalProperties: false },
1167
1667
  maxEffect: "read-only",
1168
1668
  needs: [],
1169
1669
  ...override.tier ? { tier: override.tier } : {},
1170
1670
  ...override.once ? { once: override.once } : {},
1171
1671
  ...override.guard ? { guard: override.guard } : {},
1672
+ ...override.preview ? { preview: override.preview } : {},
1172
1673
  catalog: { binding, op },
1173
1674
  async run() {
1174
1675
  throw new TypeError(`catalog Tool ${binding}#${op} was not resolved by deployment`);
@@ -1179,13 +1680,81 @@ function opTools(binding, ops = []) {
1179
1680
  if (ops.length === 0) throw new TypeError("opTools requires pinned operation names at bundle construction");
1180
1681
  return ops.map((op) => opTool(binding, op));
1181
1682
  }
1683
+ var WEB_FETCH_ARGUMENT_SCHEMA = {
1684
+ type: "object",
1685
+ required: ["url"],
1686
+ additionalProperties: false,
1687
+ properties: {
1688
+ url: { type: "string", minLength: 1, maxLength: 2048 },
1689
+ accept: { type: "string", maxLength: 256 }
1690
+ }
1691
+ };
1692
+ var WEB_SEARCH_ARGUMENT_SCHEMA = {
1693
+ type: "object",
1694
+ required: ["query"],
1695
+ additionalProperties: false,
1696
+ properties: {
1697
+ query: {
1698
+ type: "string",
1699
+ minLength: 1,
1700
+ maxLength: 4096,
1701
+ description: "A self-contained description of the information to find."
1702
+ },
1703
+ searchQueries: {
1704
+ type: "array",
1705
+ minItems: 1,
1706
+ maxItems: 3,
1707
+ uniqueItems: true,
1708
+ description: "Optional concise keyword queries that narrow the search.",
1709
+ items: { type: "string", minLength: 1, maxLength: 256 }
1710
+ },
1711
+ maximumResults: {
1712
+ type: "integer",
1713
+ minimum: 1,
1714
+ maximum: 20,
1715
+ description: "Maximum number of sources to return."
1716
+ },
1717
+ maximumCharacters: {
1718
+ type: "integer",
1719
+ minimum: 1e3,
1720
+ maximum: 6e4,
1721
+ description: "Maximum total excerpt characters to return."
1722
+ },
1723
+ includeDomains: {
1724
+ type: "array",
1725
+ maxItems: 50,
1726
+ uniqueItems: true,
1727
+ description: "Optional domains to restrict results to.",
1728
+ items: { type: "string", minLength: 1, maxLength: 253 }
1729
+ },
1730
+ excludeDomains: {
1731
+ type: "array",
1732
+ maxItems: 50,
1733
+ uniqueItems: true,
1734
+ description: "Optional domains to omit.",
1735
+ items: { type: "string", minLength: 1, maxLength: 253 }
1736
+ },
1737
+ afterDate: {
1738
+ type: "string",
1739
+ pattern: "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",
1740
+ description: "Optional earliest publication date in YYYY-MM-DD form."
1741
+ },
1742
+ searchDepth: { type: "string", enum: ["basic", "advanced"], description: "Provider search depth when supported." },
1743
+ includeAnswer: { type: "boolean", description: "Request a provider-synthesized answer when supported." },
1744
+ includeRawContent: { type: "boolean", description: "Include bounded raw source content when supported." },
1745
+ includeImages: { type: "boolean", description: "Include relevant image results when supported." },
1746
+ includeImageDescriptions: { type: "boolean", description: "Include image descriptions when supported." }
1747
+ }
1748
+ };
1182
1749
  var webFetch = opTool("web", "get", {
1183
1750
  name: "web_fetch",
1184
- description: "Fetch an HTTPS resource through the bound governed web Resource."
1751
+ description: "Fetch an HTTPS resource through the bound governed web Resource.",
1752
+ schema: WEB_FETCH_ARGUMENT_SCHEMA
1185
1753
  });
1186
1754
  var webSearch = opTool("search", "search", {
1187
1755
  name: "web_search",
1188
- description: "Search the public web through the bound governed search Resource."
1756
+ description: "Search the public web through the bound governed search Resource.",
1757
+ schema: WEB_SEARCH_ARGUMENT_SCHEMA
1189
1758
  });
1190
1759
  var casTool = {
1191
1760
  name: "cas",
@@ -1221,7 +1790,8 @@ var casTool = {
1221
1790
  var id = { type: "string", pattern: "^[A-Za-z0-9._~-]{1,256}$", maxLength: 256 };
1222
1791
  var content = { type: "string", minLength: 1, maxLength: 65536 };
1223
1792
  var metadata = { type: "object", maxProperties: 64 };
1224
- var record4 = {
1793
+ var scope = { type: "string", pattern: "^[a-f0-9]{64}$", maxLength: 64 };
1794
+ var record5 = {
1225
1795
  type: "object",
1226
1796
  required: ["id", "content", "metadata", "createdAt", "updatedAt", "expiresAt"],
1227
1797
  additionalProperties: false,
@@ -1238,8 +1808,8 @@ var MEMORY_OPERATION_DECLARATIONS = [
1238
1808
  {
1239
1809
  op: "remember",
1240
1810
  description: "Persist or replace one record in the invocation's authenticated Memory partition.",
1241
- schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata } },
1242
- resultSchema: record4,
1811
+ schema: { type: "object", required: ["content"], additionalProperties: false, properties: { id, content, metadata, scope } },
1812
+ resultSchema: record5,
1243
1813
  effect: "idempotent",
1244
1814
  recovery: { kind: "idempotency-key" },
1245
1815
  async: false,
@@ -1252,16 +1822,16 @@ var MEMORY_OPERATION_DECLARATIONS = [
1252
1822
  type: "object",
1253
1823
  required: ["query"],
1254
1824
  additionalProperties: false,
1255
- properties: { query: { type: "string", minLength: 1, maxLength: 8192 }, limit: { type: "integer", minimum: 1, maximum: 100 } }
1825
+ properties: { query: { type: "string", minLength: 1, maxLength: 8192 }, limit: { type: "integer", minimum: 1, maximum: 100 }, scope }
1256
1826
  },
1257
1827
  resultSchema: {
1258
1828
  type: "object",
1259
1829
  required: ["hits"],
1260
1830
  additionalProperties: false,
1261
1831
  properties: { hits: { type: "array", maxItems: 100, items: {
1262
- ...record4,
1263
- required: [...record4.required, "score"],
1264
- properties: { ...record4.properties, score: { type: "number", minimum: 0, maximum: 1 } }
1832
+ ...record5,
1833
+ required: [...record5.required, "score"],
1834
+ properties: { ...record5.properties, score: { type: "number", minimum: 0, maximum: 1 } }
1265
1835
  } } }
1266
1836
  },
1267
1837
  effect: "read-only",
@@ -1273,7 +1843,7 @@ var MEMORY_OPERATION_DECLARATIONS = [
1273
1843
  op: "get",
1274
1844
  description: "Read one record from the invocation's authenticated Memory partition.",
1275
1845
  schema: { type: "object", required: ["id"], additionalProperties: false, properties: { id } },
1276
- resultSchema: { anyOf: [record4, { type: "null" }] },
1846
+ resultSchema: { anyOf: [record5, { type: "null" }] },
1277
1847
  effect: "read-only",
1278
1848
  recovery: { kind: "repeat" },
1279
1849
  async: false,
@@ -1370,7 +1940,7 @@ var TRAINING_PROVIDER_CAPABILITY = {
1370
1940
  version: "1",
1371
1941
  hash: "c23ed69afdb42e0bdafdeb716067d1f4a506fc5180894854d18200df23a0f5da"
1372
1942
  };
1373
- function record5(value) {
1943
+ function record6(value) {
1374
1944
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1375
1945
  }
1376
1946
  function integer(value, field2, minimum, maximum) {
@@ -1386,7 +1956,7 @@ function finite(value, field2, minimum, maximum) {
1386
1956
  return value;
1387
1957
  }
1388
1958
  function providerPin(value) {
1389
- const candidate = record5(value);
1959
+ const candidate = record6(value);
1390
1960
  if (!candidate || typeof candidate.crn !== "string" || typeof candidate.hash !== "string" || !HASH2.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "hash"].includes(key))) throw new TypeError("training provider pin is invalid");
1391
1961
  const parts = parseResourceName(candidate.crn);
1392
1962
  if (["model", "memory"].includes(parts.kind)) throw new TypeError("training provider pin is invalid");
@@ -1394,21 +1964,21 @@ function providerPin(value) {
1394
1964
  }
1395
1965
  function resumePoint(value) {
1396
1966
  if (value === null) return null;
1397
- const candidate = record5(value);
1967
+ const candidate = record6(value);
1398
1968
  if (!candidate || typeof candidate.job !== "string" || !JOB_ID.test(candidate.job) || !Number.isSafeInteger(candidate.step) || Number(candidate.step) < 0 || typeof candidate.ref !== "string" || !HASH2.test(candidate.ref) || Object.keys(candidate).some((key) => !["job", "step", "ref"].includes(key))) {
1399
1969
  throw new TypeError("training resume point is invalid");
1400
1970
  }
1401
1971
  return candidate;
1402
1972
  }
1403
1973
  function trainingProviderMetadata(value) {
1404
- const candidate = record5(value);
1405
- const checkpoints = record5(candidate?.checkpoints);
1974
+ const candidate = record6(value);
1975
+ const checkpoints = record6(candidate?.checkpoints);
1406
1976
  if (!candidate || candidate.lifecycleVersion !== 1 || !Array.isArray(candidate.methods) || candidate.methods.length === 0 || candidate.methods.length > 2 || candidate.methods.some((method) => method !== "sft" && method !== "rl") || new Set(candidate.methods).size !== candidate.methods.length || !Array.isArray(candidate.models) || candidate.models.length > 512 || !checkpoints || !Array.isArray(checkpoints.formats) || checkpoints.formats.length === 0 || checkpoints.formats.length > 32 || checkpoints.formats.some((format) => typeof format !== "string" || !/^[a-z0-9][a-z0-9._+-]{0,63}$/u.test(format)) || new Set(checkpoints.formats).size !== checkpoints.formats.length || typeof checkpoints.resume !== "boolean" || typeof checkpoints.fork !== "boolean" || Object.keys(checkpoints).some((key) => !["formats", "resume", "fork"].includes(key)) || Object.keys(candidate).some((key) => !["lifecycleVersion", "methods", "models", "checkpoints"].includes(key))) {
1407
1977
  throw new TypeError("Training Provider metadata is invalid");
1408
1978
  }
1409
1979
  const models = candidate.models.map((raw) => {
1410
- const model = record5(raw);
1411
- const pricing = record5(model?.pricing);
1980
+ const model = record6(raw);
1981
+ const pricing = record6(model?.pricing);
1412
1982
  if (!model || typeof model.id !== "string" || !JOB_ID.test(model.id) || typeof model.name !== "string" || !model.name || model.name.length > 128 || typeof model.providerModel !== "string" || !PROVIDER_MODEL_ID.test(model.providerModel) || !Number.isSafeInteger(model.contextTokens) || Number(model.contextTokens) < 1 || !pricing || pricing.currency !== "USD" || pricing.unit !== "million_tokens" || ["prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].some((key) => !Number.isSafeInteger(pricing[key]) || Number(pricing[key]) < 0) || Object.keys(pricing).some((key) => !["currency", "unit", "prefillMicroUsd", "cachedPrefillMicroUsd", "sampleMicroUsd", "trainMicroUsd"].includes(key)) || Object.keys(model).some((key) => !["id", "name", "providerModel", "contextTokens", "pricing"].includes(key))) {
1413
1983
  throw new TypeError("Training Provider model offer is invalid");
1414
1984
  }
@@ -1425,21 +1995,21 @@ function trainingProviderMetadata(value) {
1425
1995
  };
1426
1996
  }
1427
1997
  function datasetRef(value, field2) {
1428
- const candidate = record5(value);
1998
+ const candidate = record6(value);
1429
1999
  if (!candidate || typeof candidate.crn !== "string" || parseResourceName(datasetName(candidate.crn)).kind !== "dataset" || typeof candidate.version !== "string" || !VERSION4.test(candidate.version) || typeof candidate.hash !== "string" || !HASH2.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "version", "hash"].includes(key))) {
1430
2000
  throw new TypeError(`${field2} is invalid`);
1431
2001
  }
1432
2002
  return candidate;
1433
2003
  }
1434
2004
  function scorerRef(value, field2) {
1435
- const candidate = record5(value);
2005
+ const candidate = record6(value);
1436
2006
  if (!candidate || typeof candidate.crn !== "string" || parseResourceName(scorerName(candidate.crn)).kind !== "scorer" || typeof candidate.version !== "string" || !VERSION4.test(candidate.version) || typeof candidate.hash !== "string" || !HASH2.test(candidate.hash) || Object.keys(candidate).some((key) => !["crn", "version", "hash"].includes(key))) {
1437
2007
  throw new TypeError(`${field2} is invalid`);
1438
2008
  }
1439
2009
  return candidate;
1440
2010
  }
1441
2011
  function trainingRecipe(value) {
1442
- const candidate = record5(value);
2012
+ const candidate = record6(value);
1443
2013
  const allowed = [
1444
2014
  "method",
1445
2015
  "baseModel",
@@ -1483,7 +2053,7 @@ function trainingRecipe(value) {
1483
2053
  return recipe;
1484
2054
  }
1485
2055
  function startTrainingRequest(value) {
1486
- const candidate = record5(value);
2056
+ const candidate = record6(value);
1487
2057
  if (!candidate || candidate.jobId !== void 0 && (typeof candidate.jobId !== "string" || !JOB_ID.test(candidate.jobId)) || typeof candidate.outputModelId !== "string" || !MODEL_ID.test(candidate.outputModelId) || Object.keys(candidate).some((key) => !["jobId", "provider", "resumeFrom", "recipe", "outputModelId"].includes(key))) {
1488
2058
  throw new TypeError("training request is invalid");
1489
2059
  }
@@ -1496,12 +2066,12 @@ function startTrainingRequest(value) {
1496
2066
  };
1497
2067
  }
1498
2068
  function renderTrainingCompletion(input, expected) {
1499
- const text = (value) => typeof value === "string" ? value : canonicalJson(value);
2069
+ const text2 = (value) => typeof value === "string" ? value : canonicalJson(value);
1500
2070
  return { prompt: `Input:
1501
- ${text(input)}
2071
+ ${text2(input)}
1502
2072
 
1503
2073
  Response:
1504
- `, completion: expected === void 0 || expected === null ? null : text(expected) };
2074
+ `, completion: expected === void 0 || expected === null ? null : text2(expected) };
1505
2075
  }
1506
2076
 
1507
2077
  // src/gateway.ts
@@ -1821,7 +2391,7 @@ function credentialProviderConfigSchema(value) {
1821
2391
  function interactionRecord(value) {
1822
2392
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
1823
2393
  }
1824
- function exactKeys2(value, allowed) {
2394
+ function exactKeys3(value, allowed) {
1825
2395
  return Object.keys(value).every((key) => allowed.includes(key));
1826
2396
  }
1827
2397
  function boundedText(value, maximum) {
@@ -1839,31 +2409,31 @@ function credentialInteractionEvent(value) {
1839
2409
  if (event.kind === "callback") {
1840
2410
  const parameters = interactionRecord(event.parameters);
1841
2411
  const headers = interactionRecord(event.headers);
1842
- if (!exactKeys2(event, ["kind", "method", "parameters", "headers", "bodyBase64"]) || !["GET", "POST"].includes(String(event.method ?? "")) || !parameters || Object.keys(parameters).length > 32 || Object.entries(parameters).some(([key, item]) => key.length > 128 || typeof item !== "string" || item.length > 4096) || !headers || Object.keys(headers).length > 64 || Object.entries(headers).some(([key, item]) => key.length > 128 || typeof item !== "string" || item.length > 8192) || event.bodyBase64 !== null && (typeof event.bodyBase64 !== "string" || event.bodyBase64.length > 35e4 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(event.bodyBase64))) {
2412
+ if (!exactKeys3(event, ["kind", "method", "parameters", "headers", "bodyBase64"]) || !["GET", "POST"].includes(String(event.method ?? "")) || !parameters || Object.keys(parameters).length > 32 || Object.entries(parameters).some(([key, item]) => key.length > 128 || typeof item !== "string" || item.length > 4096) || !headers || Object.keys(headers).length > 64 || Object.entries(headers).some(([key, item]) => key.length > 128 || typeof item !== "string" || item.length > 8192) || event.bodyBase64 !== null && (typeof event.bodyBase64 !== "string" || event.bodyBase64.length > 35e4 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(event.bodyBase64))) {
1843
2413
  throw new TypeError("credential interaction callback is invalid");
1844
2414
  }
1845
2415
  } else if (event.kind === "submit") {
1846
- if (!exactKeys2(event, ["kind", "value"]) || new TextEncoder().encode(canonicalJson(event.value)).byteLength > 65536) {
2416
+ if (!exactKeys3(event, ["kind", "value"]) || new TextEncoder().encode(canonicalJson(event.value)).byteLength > 65536) {
1847
2417
  throw new TypeError("credential interaction submission is invalid");
1848
2418
  }
1849
- } else if (!exactKeys2(event, ["kind"])) throw new TypeError("credential interaction event is invalid");
2419
+ } else if (!exactKeys3(event, ["kind"])) throw new TypeError("credential interaction event is invalid");
1850
2420
  return event;
1851
2421
  }
1852
2422
  function credentialInteractionPrimaryAction(value, origins) {
1853
- const action2 = interactionRecord(value);
1854
- const event = interactionRecord(action2?.event);
1855
- if (!action2 || !event || !boundedText(action2.label, 64) || !exactKeys2(event, ["kind"]) || event.kind !== "continue") {
2423
+ const action3 = interactionRecord(value);
2424
+ const event = interactionRecord(action3?.event);
2425
+ if (!action3 || !event || !boundedText(action3.label, 64) || !exactKeys3(event, ["kind"]) || event.kind !== "continue") {
1856
2426
  throw new TypeError("credential interaction primary action is invalid");
1857
2427
  }
1858
- if (action2.kind === "continue") {
1859
- if (!exactKeys2(action2, ["kind", "label", "event"])) throw new TypeError("credential interaction primary action is invalid");
1860
- } else if (action2.kind === "open-url") {
1861
- if (!exactKeys2(action2, ["kind", "label", "url", "event"]) || !boundedText(action2.url, 4096)) {
2428
+ if (action3.kind === "continue") {
2429
+ if (!exactKeys3(action3, ["kind", "label", "event"])) throw new TypeError("credential interaction primary action is invalid");
2430
+ } else if (action3.kind === "open-url") {
2431
+ if (!exactKeys3(action3, ["kind", "label", "url", "event"]) || !boundedText(action3.url, 4096)) {
1862
2432
  throw new TypeError("credential interaction primary action is invalid");
1863
2433
  }
1864
2434
  let url;
1865
2435
  try {
1866
- url = new URL(action2.url);
2436
+ url = new URL(action3.url);
1867
2437
  } catch {
1868
2438
  throw new TypeError("credential interaction primary action URL is invalid");
1869
2439
  }
@@ -1871,56 +2441,56 @@ function credentialInteractionPrimaryAction(value, origins) {
1871
2441
  throw new TypeError("credential interaction primary action URL is not authorized");
1872
2442
  }
1873
2443
  } else throw new TypeError("credential interaction primary action is invalid");
1874
- return action2;
2444
+ return action3;
1875
2445
  }
1876
2446
  function credentialInteractionAction(value, origins, state, sessionExpiresAt) {
1877
- const action2 = interactionRecord(value);
1878
- if (!action2 || !["redirect", "form", "display", "wait", "complete"].includes(String(action2.kind ?? ""))) {
2447
+ const action3 = interactionRecord(value);
2448
+ if (!action3 || !["redirect", "form", "display", "wait", "complete"].includes(String(action3.kind ?? ""))) {
1879
2449
  throw new TypeError("credential interaction action is invalid");
1880
2450
  }
1881
- const expiresAt = action2.kind === "complete" ? null : interactionExpiry(action2.expiresAt, sessionExpiresAt);
2451
+ const expiresAt = action3.kind === "complete" ? null : interactionExpiry(action3.expiresAt, sessionExpiresAt);
1882
2452
  if (Number.isNaN(expiresAt)) throw new TypeError("credential interaction action expiry is invalid");
1883
- if (action2.kind === "redirect") {
1884
- if (!exactKeys2(action2, ["kind", "url", "expiresAt"]) || !boundedText(action2.url, 4096)) {
2453
+ if (action3.kind === "redirect") {
2454
+ if (!exactKeys3(action3, ["kind", "url", "expiresAt"]) || !boundedText(action3.url, 4096)) {
1885
2455
  throw new TypeError("credential interaction redirect is invalid");
1886
2456
  }
1887
2457
  let url;
1888
2458
  try {
1889
- url = new URL(action2.url);
2459
+ url = new URL(action3.url);
1890
2460
  } catch {
1891
2461
  throw new TypeError("credential interaction redirect is invalid");
1892
2462
  }
1893
2463
  if (url.protocol !== "https:" || url.username || url.password || url.hash || !origins.includes(url.origin) || url.searchParams.getAll("state").length !== 1 || url.searchParams.get("state") !== state) {
1894
2464
  throw new TypeError("credential interaction redirect is not authorized");
1895
2465
  }
1896
- } else if (action2.kind === "form") {
1897
- if (!exactKeys2(action2, ["kind", "schema", "title", "description", "submitLabel", "expiresAt"]) || action2.title !== void 0 && !boundedText(action2.title, 128) || action2.description !== void 0 && !boundedText(action2.description, 1024) || action2.submitLabel !== void 0 && !boundedText(action2.submitLabel, 64)) {
2466
+ } else if (action3.kind === "form") {
2467
+ if (!exactKeys3(action3, ["kind", "schema", "title", "description", "submitLabel", "expiresAt"]) || action3.title !== void 0 && !boundedText(action3.title, 128) || action3.description !== void 0 && !boundedText(action3.description, 1024) || action3.submitLabel !== void 0 && !boundedText(action3.submitLabel, 64)) {
1898
2468
  throw new TypeError("credential interaction form is invalid");
1899
2469
  }
1900
- const schemaError = validateJsonSchemaDefinition(action2.schema, "$interaction.form.schema");
1901
- const formSchema = interactionRecord(action2.schema);
1902
- if (schemaError || !formSchema || formSchema.type !== "object" || formSchema.additionalProperties !== false || new TextEncoder().encode(canonicalJson(action2.schema)).byteLength > 65536) {
2470
+ const schemaError = validateJsonSchemaDefinition(action3.schema, "$interaction.form.schema");
2471
+ const formSchema = interactionRecord(action3.schema);
2472
+ if (schemaError || !formSchema || formSchema.type !== "object" || formSchema.additionalProperties !== false || new TextEncoder().encode(canonicalJson(action3.schema)).byteLength > 65536) {
1903
2473
  throw new TypeError(`credential interaction form schema is invalid${schemaError ? `: ${schemaError}` : ""}`);
1904
2474
  }
1905
- } else if (action2.kind === "display") {
1906
- if (!exactKeys2(action2, ["kind", "instructions", "title", "userCode", "primaryAction", "expiresAt"]) || !boundedText(action2.instructions, 4096) || action2.title !== void 0 && !boundedText(action2.title, 128) || action2.userCode !== void 0 && !boundedText(action2.userCode, 512)) {
2475
+ } else if (action3.kind === "display") {
2476
+ if (!exactKeys3(action3, ["kind", "instructions", "title", "userCode", "primaryAction", "expiresAt"]) || !boundedText(action3.instructions, 4096) || action3.title !== void 0 && !boundedText(action3.title, 128) || action3.userCode !== void 0 && !boundedText(action3.userCode, 512)) {
1907
2477
  throw new TypeError("credential interaction display is invalid");
1908
2478
  }
1909
- credentialInteractionPrimaryAction(action2.primaryAction, origins);
1910
- } else if (action2.kind === "wait") {
1911
- if (!exactKeys2(action2, ["kind", "resume", "expiresAt", "pollAfterMs"]) || !["callback", "poll"].includes(String(action2.resume ?? "")) || expiresAt === null || action2.pollAfterMs !== void 0 && (!Number.isSafeInteger(action2.pollAfterMs) || Number(action2.pollAfterMs) < 1e3 || Number(action2.pollAfterMs) > 3e5) || action2.resume === "poll" && action2.pollAfterMs === void 0 || action2.resume === "callback" && action2.pollAfterMs !== void 0) {
2479
+ credentialInteractionPrimaryAction(action3.primaryAction, origins);
2480
+ } else if (action3.kind === "wait") {
2481
+ if (!exactKeys3(action3, ["kind", "resume", "expiresAt", "pollAfterMs"]) || !["callback", "poll"].includes(String(action3.resume ?? "")) || expiresAt === null || action3.pollAfterMs !== void 0 && (!Number.isSafeInteger(action3.pollAfterMs) || Number(action3.pollAfterMs) < 1e3 || Number(action3.pollAfterMs) > 3e5) || action3.resume === "poll" && action3.pollAfterMs === void 0 || action3.resume === "callback" && action3.pollAfterMs !== void 0) {
1912
2482
  throw new TypeError("credential interaction wait action is invalid");
1913
2483
  }
1914
2484
  } else {
1915
- if (!exactKeys2(action2, ["kind", "material", "expiresAt"]) || !boundedText(action2.material, 1048576) || action2.expiresAt !== void 0 && action2.expiresAt !== null && (!Number.isSafeInteger(action2.expiresAt) || Number(action2.expiresAt) <= Date.now())) {
2485
+ if (!exactKeys3(action3, ["kind", "material", "expiresAt"]) || !boundedText(action3.material, 1048576) || action3.expiresAt !== void 0 && action3.expiresAt !== null && (!Number.isSafeInteger(action3.expiresAt) || Number(action3.expiresAt) <= Date.now())) {
1916
2486
  throw new TypeError("credential interaction completion is invalid");
1917
2487
  }
1918
2488
  }
1919
- return action2;
2489
+ return action3;
1920
2490
  }
1921
2491
  function credentialInteractionResult(value, origins, state, sessionExpiresAt) {
1922
2492
  const result = interactionRecord(value);
1923
- if (!result || !exactKeys2(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
2493
+ if (!result || !exactKeys3(result, ["action", "privateState"])) throw new TypeError("credential interaction result is invalid");
1924
2494
  const privateState = result.privateState;
1925
2495
  if (privateState !== void 0 && privateState !== null && (typeof privateState !== "string" || new TextEncoder().encode(privateState).byteLength > 1048576)) throw new TypeError("credential interaction private state is invalid");
1926
2496
  return {
@@ -2028,17 +2598,17 @@ function credentialProvider(definition) {
2028
2598
  var NAME4 = /^[a-z0-9][a-z0-9._-]{0,127}$/u;
2029
2599
  var HEADER = /^[a-z0-9][a-z0-9-]{0,63}$/u;
2030
2600
  var RESERVED_HEADERS = /* @__PURE__ */ new Set(["connection", "content-type", "host", "anthropic-version", "proxy-authorization", "transfer-encoding"]);
2031
- function record6(value) {
2601
+ function record7(value) {
2032
2602
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2033
2603
  }
2034
2604
  function credentialHeader(value, name) {
2035
2605
  if (value === null || value === void 0) return null;
2036
- const source = record6(value);
2606
+ const source = record7(value);
2037
2607
  if (!source || typeof source.slot !== "string" || !NAME4.test(source.slot) || typeof source.header !== "string" || !HEADER.test(source.header.toLowerCase()) || RESERVED_HEADERS.has(source.header.toLowerCase()) || source.header.toLowerCase().startsWith("cf-") || source.scheme !== "bearer" && source.scheme !== "raw") throw new TypeError(`${name} is invalid`);
2038
2608
  return { slot: source.slot, header: source.header.toLowerCase(), scheme: source.scheme };
2039
2609
  }
2040
2610
  function normalizeModelGatewayConfig(value) {
2041
- const source = record6(value);
2611
+ const source = record7(value);
2042
2612
  if (!source || typeof source.baseUrl !== "string" || source.baseUrl.length > 2048 || source.protocol !== "anthropic" && source.protocol !== "openai" || typeof source.model !== "string" || source.model.length === 0 || source.model.length > 256) {
2043
2613
  throw new TypeError("model gateway config is invalid");
2044
2614
  }
@@ -2088,6 +2658,12 @@ function modelPrompt(args) {
2088
2658
  return JSON.stringify({ objective: args.objective ?? null, context: args.context ?? null, feedback: args.feedback ?? [] });
2089
2659
  }
2090
2660
  function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, args) {
2661
+ if (args.toolChoice !== void 0 && args.toolChoice !== "auto" && args.toolChoice !== "required") {
2662
+ throw new TypeError("model Tool choice is invalid");
2663
+ }
2664
+ if (args.toolChoice === "required" && !args.tools?.length) {
2665
+ throw new TypeError("required model Tool choice needs at least one offered Tool");
2666
+ }
2091
2667
  const prompt = modelPrompt(args);
2092
2668
  if (protocol === "anthropic") return {
2093
2669
  model,
@@ -2095,7 +2671,8 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
2095
2671
  messages: [{ role: "user", content: prompt }],
2096
2672
  max_tokens: maxOutputTokens,
2097
2673
  ...temperature === null ? {} : { temperature },
2098
- ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {}
2674
+ ...args.tools?.length ? { tools: args.tools.map((tool) => ({ name: tool.name, description: tool.description, input_schema: tool.schema })) } : {},
2675
+ ...args.toolChoice === void 0 ? {} : { tool_choice: { type: args.toolChoice === "required" ? "any" : "auto" } }
2099
2676
  };
2100
2677
  if (protocol === "openai") return {
2101
2678
  model,
@@ -2108,7 +2685,8 @@ function modelProtocolRequest(protocol, model, maxOutputTokens, temperature, arg
2108
2685
  ...args.tools?.length ? { tools: args.tools.map((tool) => ({
2109
2686
  type: "function",
2110
2687
  function: { name: tool.name, description: tool.description, parameters: tool.schema }
2111
- })) } : {}
2688
+ })) } : {},
2689
+ ...args.toolChoice === void 0 ? {} : { tool_choice: args.toolChoice }
2112
2690
  };
2113
2691
  throw new TypeError("model gateway protocol is invalid");
2114
2692
  }
@@ -2125,21 +2703,21 @@ function costMetadata(usage) {
2125
2703
  };
2126
2704
  }
2127
2705
  function modelProtocolResult(protocol, raw, provider, model) {
2128
- const source = record6(raw) ?? {};
2706
+ const source = record7(raw) ?? {};
2129
2707
  const toolCalls = [];
2130
2708
  let content2 = "";
2131
2709
  let usage;
2132
2710
  if (protocol === "anthropic") {
2133
2711
  const blocks = Array.isArray(source.content) ? source.content : [];
2134
2712
  content2 = blocks.map((candidate) => {
2135
- const block = record6(candidate);
2713
+ const block = record7(candidate);
2136
2714
  if (block?.type === "text" && typeof block.text === "string") return block.text;
2137
2715
  if (block?.type === "tool_use" && typeof block.id === "string" && typeof block.name === "string") {
2138
2716
  toolCalls.push({ id: block.id, name: block.name, args: block.input ?? {} });
2139
2717
  }
2140
2718
  return "";
2141
2719
  }).join("");
2142
- const values = record6(source.usage) ?? {};
2720
+ const values = record7(source.usage) ?? {};
2143
2721
  const cached = integer2(values.cache_read_input_tokens);
2144
2722
  usage = {
2145
2723
  input: integer2(values.input_tokens) + integer2(values.cache_creation_input_tokens) + cached,
@@ -2148,12 +2726,12 @@ function modelProtocolResult(protocol, raw, provider, model) {
2148
2726
  ...costMetadata(values)
2149
2727
  };
2150
2728
  } else if (protocol === "openai") {
2151
- const choice = record6(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2152
- const message = record6(choice.message) ?? {};
2729
+ const choice = record7(Array.isArray(source.choices) ? source.choices[0] : null) ?? {};
2730
+ const message = record7(choice.message) ?? {};
2153
2731
  content2 = typeof message.content === "string" ? message.content : "";
2154
2732
  for (const candidate of Array.isArray(message.tool_calls) ? message.tool_calls : []) {
2155
- const call = record6(candidate);
2156
- const fn = record6(call?.function);
2733
+ const call = record7(candidate);
2734
+ const fn = record7(call?.function);
2157
2735
  if (typeof call?.id !== "string" || typeof fn?.name !== "string" || typeof fn.arguments !== "string") continue;
2158
2736
  let args;
2159
2737
  try {
@@ -2163,11 +2741,11 @@ function modelProtocolResult(protocol, raw, provider, model) {
2163
2741
  }
2164
2742
  toolCalls.push({ id: call.id, name: fn.name, args });
2165
2743
  }
2166
- const values = record6(source.usage) ?? {};
2744
+ const values = record7(source.usage) ?? {};
2167
2745
  usage = {
2168
2746
  input: integer2(values.prompt_tokens),
2169
2747
  output: integer2(values.completion_tokens),
2170
- cached: integer2(record6(values.prompt_tokens_details)?.cached_tokens),
2748
+ cached: integer2(record7(values.prompt_tokens_details)?.cached_tokens),
2171
2749
  ...costMetadata(values)
2172
2750
  };
2173
2751
  } else throw new TypeError("model gateway protocol is invalid");
@@ -2179,31 +2757,31 @@ function modelProtocolResult(protocol, raw, provider, model) {
2179
2757
  function validPointer(value) {
2180
2758
  return typeof value === "string" && value.length <= 4096 && (value === "" || value.startsWith("/") && !/~(?:[^01]|$)/u.test(value));
2181
2759
  }
2182
- function record7(value) {
2760
+ function record8(value) {
2183
2761
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2184
2762
  }
2185
- function exactKeys3(value, allowed) {
2763
+ function exactKeys4(value, allowed) {
2186
2764
  return Object.keys(value).every((key) => allowed.includes(key));
2187
2765
  }
2188
2766
  function scorerRule(value, depth, state) {
2189
- const rule = record7(value);
2767
+ const rule = record8(value);
2190
2768
  if (!rule || depth > 32 || ++state.rules > 1024 || typeof rule.op !== "string") throw new TypeError("Code Scorer IR is invalid");
2191
2769
  if (rule.op === "all" || rule.op === "any") {
2192
- if (!exactKeys3(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1 || rule.rules.length > 128) {
2770
+ if (!exactKeys4(rule, ["op", "rules"]) || !Array.isArray(rule.rules) || rule.rules.length < 1 || rule.rules.length > 128) {
2193
2771
  throw new TypeError("Code Scorer logical rule is invalid");
2194
2772
  }
2195
2773
  return { op: rule.op, rules: rule.rules.map((child) => scorerRule(child, depth + 1, state)) };
2196
2774
  }
2197
2775
  if (rule.op === "not") {
2198
- if (!exactKeys3(rule, ["op", "rule"])) throw new TypeError("Code Scorer not rule is invalid");
2776
+ if (!exactKeys4(rule, ["op", "rule"])) throw new TypeError("Code Scorer not rule is invalid");
2199
2777
  return { op: "not", rule: scorerRule(rule.rule, depth + 1, state) };
2200
2778
  }
2201
2779
  if (rule.op === "schema") {
2202
- if (!exactKeys3(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record7(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
2780
+ if (!exactKeys4(rule, ["op", "path", "schema"]) || !validPointer(rule.path) || !record8(rule.schema) || validateJsonSchemaDefinition(rule.schema)) throw new TypeError("Code Scorer schema rule is invalid");
2203
2781
  return rule;
2204
2782
  }
2205
2783
  if (rule.op === "regex") {
2206
- if (!exactKeys3(rule, ["op", "path", "pattern", "flags"]) || !validPointer(rule.path) || typeof rule.pattern !== "string" || rule.pattern.length > 4096 || ![void 0, "", "i", "m", "im"].includes(rule.flags)) {
2784
+ if (!exactKeys4(rule, ["op", "path", "pattern", "flags"]) || !validPointer(rule.path) || typeof rule.pattern !== "string" || rule.pattern.length > 4096 || ![void 0, "", "i", "m", "im"].includes(rule.flags)) {
2207
2785
  throw new TypeError("Code Scorer regex rule is invalid");
2208
2786
  }
2209
2787
  try {
@@ -2214,28 +2792,28 @@ function scorerRule(value, depth, state) {
2214
2792
  return rule;
2215
2793
  }
2216
2794
  if (rule.op === "range") {
2217
- if (!exactKeys3(rule, ["op", "path", "min", "max"]) || !validPointer(rule.path) || rule.min === void 0 && rule.max === void 0 || rule.min !== void 0 && (typeof rule.min !== "number" || !Number.isFinite(rule.min)) || rule.max !== void 0 && (typeof rule.max !== "number" || !Number.isFinite(rule.max)) || typeof rule.min === "number" && typeof rule.max === "number" && rule.min > rule.max) throw new TypeError("Code Scorer range rule is invalid");
2795
+ if (!exactKeys4(rule, ["op", "path", "min", "max"]) || !validPointer(rule.path) || rule.min === void 0 && rule.max === void 0 || rule.min !== void 0 && (typeof rule.min !== "number" || !Number.isFinite(rule.min)) || rule.max !== void 0 && (typeof rule.max !== "number" || !Number.isFinite(rule.max)) || typeof rule.min === "number" && typeof rule.max === "number" && rule.min > rule.max) throw new TypeError("Code Scorer range rule is invalid");
2218
2796
  return rule;
2219
2797
  }
2220
2798
  if (rule.op === "equals" || rule.op === "contains") {
2221
- if (!exactKeys3(rule, ["op", "path", "value"]) || !validPointer(rule.path) || !Object.hasOwn(rule, "value") || new TextEncoder().encode(canonicalJson(rule.value)).byteLength > 65536) {
2799
+ if (!exactKeys4(rule, ["op", "path", "value"]) || !validPointer(rule.path) || !Object.hasOwn(rule, "value") || new TextEncoder().encode(canonicalJson(rule.value)).byteLength > 65536) {
2222
2800
  throw new TypeError(`Code Scorer ${rule.op} rule is invalid`);
2223
2801
  }
2224
2802
  return rule;
2225
2803
  }
2226
2804
  if (rule.op === "tool-sequence") {
2227
- if (!exactKeys3(rule, ["op", "path", "expected", "mode"]) || !validPointer(rule.path) || !Array.isArray(rule.expected) || rule.expected.length > 256 || rule.expected.some((item) => typeof item !== "string" || !/^[A-Za-z0-9._-]{1,128}$/u.test(item)) || rule.mode !== "exact" && rule.mode !== "ordered-subsequence") throw new TypeError("Code Scorer tool sequence rule is invalid");
2805
+ if (!exactKeys4(rule, ["op", "path", "expected", "mode"]) || !validPointer(rule.path) || !Array.isArray(rule.expected) || rule.expected.length > 256 || rule.expected.some((item) => typeof item !== "string" || !/^[A-Za-z0-9._-]{1,128}$/u.test(item)) || rule.mode !== "exact" && rule.mode !== "ordered-subsequence") throw new TypeError("Code Scorer tool sequence rule is invalid");
2228
2806
  return rule;
2229
2807
  }
2230
2808
  if (rule.op === "citations-in-source") {
2231
- if (!exactKeys3(rule, ["op", "textPath", "sourcesPath"]) || !validPointer(rule.textPath) || !validPointer(rule.sourcesPath)) throw new TypeError("Code Scorer citation rule is invalid");
2809
+ if (!exactKeys4(rule, ["op", "textPath", "sourcesPath"]) || !validPointer(rule.textPath) || !validPointer(rule.sourcesPath)) throw new TypeError("Code Scorer citation rule is invalid");
2232
2810
  return rule;
2233
2811
  }
2234
2812
  throw new TypeError("Code Scorer operation is invalid");
2235
2813
  }
2236
2814
  function codeScorerIR(value) {
2237
- const ir = record7(value);
2238
- if (!ir || ir.v !== 1 || !exactKeys3(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
2815
+ const ir = record8(value);
2816
+ if (!ir || ir.v !== 1 || !exactKeys4(ir, ["v", "rule"])) throw new TypeError("Code Scorer IR is invalid");
2239
2817
  return { v: 1, rule: scorerRule(ir.rule, 0, { rules: 0 }) };
2240
2818
  }
2241
2819
  function pointer(value, path) {
@@ -2247,7 +2825,7 @@ function pointer(value, path) {
2247
2825
  if (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length) return { found: false, value: void 0 };
2248
2826
  current = current[Number(key)];
2249
2827
  } else {
2250
- const source = record7(current);
2828
+ const source = record8(current);
2251
2829
  if (!source || !Object.hasOwn(source, key)) return { found: false, value: void 0 };
2252
2830
  current = source[key];
2253
2831
  }
@@ -2275,16 +2853,16 @@ function evaluate(rule, subject) {
2275
2853
  return value.pass ? fail("", "negated rule passed") : { pass: true, checks: value.checks, failures: [] };
2276
2854
  }
2277
2855
  if (rule.op === "citations-in-source") {
2278
- const text = pointer(subject, rule.textPath);
2856
+ const text2 = pointer(subject, rule.textPath);
2279
2857
  const sources = pointer(subject, rule.sourcesPath);
2280
- if (!text.found || typeof text.value !== "string") return fail(rule.textPath, "citation text is missing");
2858
+ if (!text2.found || typeof text2.value !== "string") return fail(rule.textPath, "citation text is missing");
2281
2859
  if (!sources.found || !Array.isArray(sources.value)) return fail(rule.sourcesPath, "citation sources are missing");
2282
2860
  const available = new Set(sources.value.flatMap((source, index) => {
2283
2861
  if (typeof source === "string") return [source, String(index + 1)];
2284
- const item = record7(source);
2862
+ const item = record8(source);
2285
2863
  return item ? [String(item.id ?? ""), String(index + 1)].filter(Boolean) : [String(index + 1)];
2286
2864
  }));
2287
- const citations = [...text.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
2865
+ const citations = [...text2.value.matchAll(/\[([^\]\n]{1,128})\]/gu)].map((match) => match[1].trim());
2288
2866
  return citations.length > 0 && citations.every((citation) => available.has(citation)) ? pass() : fail(rule.textPath, "citation is absent or not in sources");
2289
2867
  }
2290
2868
  const selected = pointer(subject, rule.path);
@@ -2300,7 +2878,7 @@ function evaluate(rule, subject) {
2300
2878
  const contains = typeof selected.value === "string" && typeof rule.value === "string" ? selected.value.includes(rule.value) : Array.isArray(selected.value) && selected.value.some((value) => canonicalJson(value) === canonicalJson(rule.value));
2301
2879
  return contains ? pass() : fail(rule.path, "value is not contained");
2302
2880
  }
2303
- const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record7(item)?.name ?? "")) : [];
2881
+ const names = Array.isArray(selected.value) ? selected.value.map((item) => typeof item === "string" ? item : String(record8(item)?.name ?? "")) : [];
2304
2882
  const sequence = rule.mode === "exact" ? names.length === rule.expected.length && names.every((name, index) => name === rule.expected[index]) : rule.expected.reduce((cursor, expected) => {
2305
2883
  const index = names.indexOf(expected, cursor);
2306
2884
  return index < 0 ? Number.POSITIVE_INFINITY : index + 1;
@@ -2320,9 +2898,9 @@ function evaluateCodeScorer(raw, subject) {
2320
2898
 
2321
2899
  // src/errors.ts
2322
2900
  var GateExhausted = class extends Error {
2323
- constructor(record8) {
2901
+ constructor(record9) {
2324
2902
  super("turn gate exhausted");
2325
- this.record = record8;
2903
+ this.record = record9;
2326
2904
  this.name = "GateExhausted";
2327
2905
  }
2328
2906
  record;
@@ -2498,6 +3076,10 @@ var SessionDeleted = class extends Error {
2498
3076
  export {
2499
3077
  AfterYield,
2500
3078
  ApiError,
3079
+ CONSTAL_API_CAPABILITY,
3080
+ CONSTAL_API_OPERATIONS,
3081
+ CONSTAL_API_OPERATION_SCHEMAS,
3082
+ CONSTAL_API_VERSION,
2501
3083
  CommitConflict,
2502
3084
  CommitGateRejected,
2503
3085
  CredentialRevoked,
@@ -2525,7 +3107,10 @@ export {
2525
3107
  TRAINING_PROVIDER_CAPABILITY,
2526
3108
  TerminalIntegrationFailure,
2527
3109
  ToolUnavailable,
3110
+ UI_BUNDLE_BOUNDS,
2528
3111
  UnknownTool,
3112
+ WEB_FETCH_ARGUMENT_SCHEMA,
3113
+ WEB_SEARCH_ARGUMENT_SCHEMA,
2529
3114
  action,
2530
3115
  actionPattern,
2531
3116
  agent,
@@ -2602,6 +3187,10 @@ export {
2602
3187
  scopedCredentialRef,
2603
3188
  scopedResourceRef,
2604
3189
  scorerName,
3190
+ setupAwait,
3191
+ setupScreen,
3192
+ setupScreenView,
3193
+ setupSubmission,
2605
3194
  sha256Hex,
2606
3195
  stageOutput,
2607
3196
  startTrainingRequest,
@@ -2611,6 +3200,10 @@ export {
2611
3200
  trainingProvider,
2612
3201
  trainingProviderMetadata,
2613
3202
  trainingRecipe,
3203
+ uiBundle,
3204
+ uiBundleManifest,
3205
+ uiLimit,
3206
+ uiName,
2614
3207
  validateBatchSpec,
2615
3208
  validateFoldFn,
2616
3209
  validateJsonSchema,