@techis/ai-contracts 0.0.0-stage → 0.3.0-rc.16

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.
Files changed (175) hide show
  1. package/LICENSE +122 -0
  2. package/README.md +28 -3
  3. package/THIRD_PARTY_NOTICES +34 -0
  4. package/dist/availability.d.ts +21 -0
  5. package/dist/availability.d.ts.map +1 -0
  6. package/dist/availability.js +2 -0
  7. package/dist/availability.js.map +1 -0
  8. package/dist/catalog-adoption.d.ts +20 -0
  9. package/dist/catalog-adoption.d.ts.map +1 -0
  10. package/dist/catalog-adoption.js +76 -0
  11. package/dist/catalog-adoption.js.map +1 -0
  12. package/dist/catalog-composition.d.ts +10 -0
  13. package/dist/catalog-composition.d.ts.map +1 -0
  14. package/dist/catalog-composition.js +66 -0
  15. package/dist/catalog-composition.js.map +1 -0
  16. package/dist/catalog-delivery.d.ts +47 -0
  17. package/dist/catalog-delivery.d.ts.map +1 -0
  18. package/dist/catalog-delivery.js +87 -0
  19. package/dist/catalog-delivery.js.map +1 -0
  20. package/dist/catalog-package-data.d.ts +8 -0
  21. package/dist/catalog-package-data.d.ts.map +1 -0
  22. package/dist/catalog-package-data.js +3845 -0
  23. package/dist/catalog-package-data.js.map +1 -0
  24. package/dist/compatibility.d.ts +68 -0
  25. package/dist/compatibility.d.ts.map +1 -0
  26. package/dist/compatibility.js +207 -0
  27. package/dist/compatibility.js.map +1 -0
  28. package/dist/configuration-bundle.d.ts +204 -0
  29. package/dist/configuration-bundle.d.ts.map +1 -0
  30. package/dist/configuration-bundle.js +626 -0
  31. package/dist/configuration-bundle.js.map +1 -0
  32. package/dist/entities.d.ts +641 -0
  33. package/dist/entities.d.ts.map +1 -0
  34. package/dist/entities.js +2 -0
  35. package/dist/entities.js.map +1 -0
  36. package/dist/fixtures.d.ts +25 -0
  37. package/dist/fixtures.d.ts.map +1 -0
  38. package/dist/fixtures.js +546 -0
  39. package/dist/fixtures.js.map +1 -0
  40. package/dist/hash.d.ts +8 -0
  41. package/dist/hash.d.ts.map +1 -0
  42. package/dist/hash.js +13 -0
  43. package/dist/hash.js.map +1 -0
  44. package/dist/host-qualification.d.ts +107 -0
  45. package/dist/host-qualification.d.ts.map +1 -0
  46. package/dist/host-qualification.js +88 -0
  47. package/dist/host-qualification.js.map +1 -0
  48. package/dist/icc-catalog.d.ts +31 -0
  49. package/dist/icc-catalog.d.ts.map +1 -0
  50. package/dist/icc-catalog.js +321 -0
  51. package/dist/icc-catalog.js.map +1 -0
  52. package/dist/icc-csf-profiles.d.ts +28 -0
  53. package/dist/icc-csf-profiles.d.ts.map +1 -0
  54. package/dist/icc-csf-profiles.js +394 -0
  55. package/dist/icc-csf-profiles.js.map +1 -0
  56. package/dist/index.d.ts +25 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +25 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/model-maintenance.d.ts +216 -0
  61. package/dist/model-maintenance.d.ts.map +1 -0
  62. package/dist/model-maintenance.js +425 -0
  63. package/dist/model-maintenance.js.map +1 -0
  64. package/dist/model-package-data.d.ts +3 -0
  65. package/dist/model-package-data.d.ts.map +1 -0
  66. package/dist/model-package-data.js +4954 -0
  67. package/dist/model-package-data.js.map +1 -0
  68. package/dist/persona-inventory.d.ts +143 -0
  69. package/dist/persona-inventory.d.ts.map +1 -0
  70. package/dist/persona-inventory.js +56 -0
  71. package/dist/persona-inventory.js.map +1 -0
  72. package/dist/profile-identity.d.ts +27 -0
  73. package/dist/profile-identity.d.ts.map +1 -0
  74. package/dist/profile-identity.js +30 -0
  75. package/dist/profile-identity.js.map +1 -0
  76. package/dist/provider-listings.d.ts +9 -0
  77. package/dist/provider-listings.d.ts.map +1 -0
  78. package/dist/provider-listings.js +48 -0
  79. package/dist/provider-listings.js.map +1 -0
  80. package/dist/reasoning-validation.d.ts +9 -0
  81. package/dist/reasoning-validation.d.ts.map +1 -0
  82. package/dist/reasoning-validation.js +79 -0
  83. package/dist/reasoning-validation.js.map +1 -0
  84. package/dist/reasoning.d.ts +55 -0
  85. package/dist/reasoning.d.ts.map +1 -0
  86. package/dist/reasoning.js +13 -0
  87. package/dist/reasoning.js.map +1 -0
  88. package/dist/receipt.d.ts +16 -0
  89. package/dist/receipt.d.ts.map +1 -0
  90. package/dist/receipt.js +18 -0
  91. package/dist/receipt.js.map +1 -0
  92. package/dist/schemas/adoption-change-set.schema.json +91 -0
  93. package/dist/schemas/bundle.d.ts +124 -0
  94. package/dist/schemas/bundle.d.ts.map +1 -0
  95. package/dist/schemas/bundle.js +84 -0
  96. package/dist/schemas/bundle.js.map +1 -0
  97. package/dist/schemas/catalog-release.schema.json +375 -0
  98. package/dist/schemas/catalog-review-input.schema.json +179 -0
  99. package/dist/schemas/catalog-review-output.schema.json +259 -0
  100. package/dist/schemas/catalog-review-output.v2.schema.json +251 -0
  101. package/dist/schemas/catalog-review-record.schema.json +391 -0
  102. package/dist/schemas/client-persona-inventory.schema.json +107 -0
  103. package/dist/schemas/common.schema.json +324 -0
  104. package/dist/schemas/config.d.ts +1106 -0
  105. package/dist/schemas/config.d.ts.map +1 -0
  106. package/dist/schemas/config.js +496 -0
  107. package/dist/schemas/config.js.map +1 -0
  108. package/dist/schemas/configuration-bundle-manifest.schema.json +144 -0
  109. package/dist/schemas/configuration-manifest.schema.json +109 -0
  110. package/dist/schemas/connection.schema.json +49 -0
  111. package/dist/schemas/core.d.ts +2268 -0
  112. package/dist/schemas/core.d.ts.map +1 -0
  113. package/dist/schemas/core.js +367 -0
  114. package/dist/schemas/core.js.map +1 -0
  115. package/dist/schemas/desktop-configuration-revision.schema.json +146 -0
  116. package/dist/schemas/execution-profile-revision.schema.json +235 -0
  117. package/dist/schemas/execution-receipt.schema.json +431 -0
  118. package/dist/schemas/host-adapter-qualification.schema.json +398 -0
  119. package/dist/schemas/host-qualification-policy.schema.json +50 -0
  120. package/dist/schemas/index.d.ts +11 -0
  121. package/dist/schemas/index.d.ts.map +1 -0
  122. package/dist/schemas/index.js +34 -0
  123. package/dist/schemas/index.js.map +1 -0
  124. package/dist/schemas/inventory.d.ts +170 -0
  125. package/dist/schemas/inventory.d.ts.map +1 -0
  126. package/dist/schemas/inventory.js +87 -0
  127. package/dist/schemas/inventory.js.map +1 -0
  128. package/dist/schemas/model-definition.schema.json +628 -0
  129. package/dist/schemas/model-package-release.schema.json +594 -0
  130. package/dist/schemas/model-upgrade-advisory.schema.json +191 -0
  131. package/dist/schemas/operation-contract-document.schema.json +153 -0
  132. package/dist/schemas/persona-assignments.schema.json +125 -0
  133. package/dist/schemas/persona-registry-overlay.schema.json +93 -0
  134. package/dist/schemas/persona-source-document.schema.json +86 -0
  135. package/dist/schemas/persona-specification.schema.json +122 -0
  136. package/dist/schemas/price-revision.schema.json +299 -0
  137. package/dist/schemas/profile-assessment.schema.json +288 -0
  138. package/dist/schemas/scoped.d.ts +424 -0
  139. package/dist/schemas/scoped.d.ts.map +1 -0
  140. package/dist/schemas/scoped.js +203 -0
  141. package/dist/schemas/scoped.js.map +1 -0
  142. package/dist/schemas/usage-aggregate-query.schema.json +86 -0
  143. package/dist/schemas/usage-page.schema.json +22 -0
  144. package/dist/schemas/usage-query.schema.json +77 -0
  145. package/dist/schemas/usage-summary.schema.json +468 -0
  146. package/dist/schemas/usage.d.ts +527 -0
  147. package/dist/schemas/usage.d.ts.map +1 -0
  148. package/dist/schemas/usage.js +142 -0
  149. package/dist/schemas/usage.js.map +1 -0
  150. package/dist/scoped-configuration.d.ts +208 -0
  151. package/dist/scoped-configuration.d.ts.map +1 -0
  152. package/dist/scoped-configuration.js +425 -0
  153. package/dist/scoped-configuration.js.map +1 -0
  154. package/dist/scripts/emit-schemas.d.ts +2 -0
  155. package/dist/scripts/emit-schemas.d.ts.map +1 -0
  156. package/dist/scripts/emit-schemas.js +24 -0
  157. package/dist/scripts/emit-schemas.js.map +1 -0
  158. package/dist/scripts/verify-bundle.d.ts +3 -0
  159. package/dist/scripts/verify-bundle.d.ts.map +1 -0
  160. package/dist/scripts/verify-bundle.js +59 -0
  161. package/dist/scripts/verify-bundle.js.map +1 -0
  162. package/dist/validation.d.ts +11 -0
  163. package/dist/validation.d.ts.map +1 -0
  164. package/dist/validation.js +41 -0
  165. package/dist/validation.js.map +1 -0
  166. package/package.json +31 -4
  167. package/third-party-licenses/ajv-formats@3.0.1/LICENSE +21 -0
  168. package/third-party-licenses/ajv@8.20.0/LICENSE +22 -0
  169. package/third-party-licenses/fast-deep-equal@3.1.3/LICENSE +21 -0
  170. package/third-party-licenses/fast-uri@3.1.7/LICENSE +30 -0
  171. package/third-party-licenses/json-schema-traverse@1.0.0/LICENSE +21 -0
  172. package/third-party-licenses/require-from-string@2.0.2/license +21 -0
  173. package/third-party-licenses/typescript@5.9.3/LICENSE.txt +55 -0
  174. package/third-party-licenses/typescript@5.9.3/ThirdPartyNoticeText.txt +193 -0
  175. package/third-party-licenses.json +102 -0
@@ -0,0 +1,626 @@
1
+ import { validateEntity } from "./validation.js";
2
+ import { hashInstructions } from "./hash.js";
3
+ import { canonicalJsonV2, hashDocumentV2, sha256HexV2 } from "./scoped-configuration.js";
4
+ import { evaluateProfileCompatibility } from "./compatibility.js";
5
+ import { assertStableProfileIdentities } from "./profile-identity.js";
6
+ /**
7
+ * D2: the subsystem configuration-bundle contract (schema version 1).
8
+ *
9
+ * Formalizes the manifest format ICC invented client-side (resources/embedded-models/)
10
+ * rather than inventing a second one: an immutable, exact-revision document set — catalog,
11
+ * profiles, default bindings, persona sources, operation contract, connection references
12
+ * and app-specific extras — with per-document SHA-256 over the exact file content,
13
+ * provenance, a runtime-compatibility range and the secrets-excluded invariant.
14
+ *
15
+ * Verification lives at the hand-off boundaries and is source-neutral: the management
16
+ * API/Studio validate a bundle at export, the runtime re-verifies at load (loading is
17
+ * verifying, failing closed). This module is the shared verification core; it makes no
18
+ * filesystem assumptions beyond an injected read of each document's raw content, so
19
+ * consumers install only @techis/ai-runtime + @techis/ai-contracts and no verifier
20
+ * package ever enters their dependency graph.
21
+ */
22
+ export const CONFIGURATION_BUNDLE_SCHEMA_VERSION = 1;
23
+ export const CONFIGURATION_BUNDLE_KIND = "techis-configuration-bundle-manifest";
24
+ /** First reader release supporting catalog/model v2 availability and unknown lifecycle. */
25
+ export const MINIMUM_CATALOG_V2_RUNTIME_VERSION = "0.3.0-rc.7";
26
+ export const MINIMUM_PRICE_V2_RUNTIME_VERSION = "0.3.0-rc.8";
27
+ export const MINIMUM_CATALOG_V3_RUNTIME_VERSION = "0.3.0-rc.16";
28
+ /** Manifest file name inside every bundle directory. */
29
+ export const BUNDLE_MANIFEST_FILE = "manifest.json";
30
+ /** Document names this contract knows; anything else declared in the manifest is rejected. */
31
+ export const REQUIRED_BUNDLE_DOCUMENTS = ["catalog.json", "profiles.json", "default-bindings.json"];
32
+ export const OPTIONAL_BUNDLE_DOCUMENTS = ["persona-sources.json", "operation-contract.json", "selection-rules.json", "connections.json"];
33
+ export const KNOWN_BUNDLE_DOCUMENTS = [...REQUIRED_BUNDLE_DOCUMENTS, ...OPTIONAL_BUNDLE_DOCUMENTS];
34
+ export class ConfigurationBundleValidationError extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = "ConfigurationBundleValidationError";
38
+ }
39
+ }
40
+ export function assertConfigurationBundleManifest(value) {
41
+ const validation = validateEntity("configuration-bundle-manifest", value);
42
+ if (!validation.valid) {
43
+ throw new ConfigurationBundleValidationError(`Configuration bundle manifest is invalid: ${validation.errors.join("; ")}`);
44
+ }
45
+ }
46
+ /**
47
+ * Content-addressed bundle identity. The runtime reports this as the manifest revision on
48
+ * receipts (D14): same bundle content ⇒ same identity, different content ⇒ different
49
+ * identity, and a reused bundleVersion string can never masquerade as the same revision.
50
+ */
51
+ export function configurationBundleIdentity(manifest) {
52
+ return `bundle-sha256-${hashDocumentV2(manifest).slice(0, 40)}`;
53
+ }
54
+ // ---------------------------------------------------------------------------
55
+ // Runtime version ranges (a deliberate subset of npm semantics)
56
+ // ---------------------------------------------------------------------------
57
+ export const RUNTIME_PACKAGE_NAME = "@techis/ai-runtime";
58
+ /** Parses "@techis/ai-runtime@>=0.3.0-rc.1 <0.4.0" into package name and range. */
59
+ export function parseRuntimeCompatibility(compatibleRuntime) {
60
+ const at = compatibleRuntime.indexOf("@", 1);
61
+ if (at <= 0) {
62
+ throw new ConfigurationBundleValidationError(`compatibleRuntime must have the form ${RUNTIME_PACKAGE_NAME}@<range>; received ${JSON.stringify(compatibleRuntime)}.`);
63
+ }
64
+ const packageName = compatibleRuntime.slice(0, at);
65
+ const range = compatibleRuntime.slice(at + 1).trim();
66
+ if (!range) {
67
+ throw new ConfigurationBundleValidationError(`compatibleRuntime declares an empty version range.`);
68
+ }
69
+ return { packageName, range };
70
+ }
71
+ export function parseSemanticVersion(value) {
72
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(value.trim());
73
+ if (!match) {
74
+ throw new ConfigurationBundleValidationError(`"${value}" is not a valid X.Y.Z semver string (optional -prerelease, optional leading v).`);
75
+ }
76
+ return {
77
+ major: Number(match[1]),
78
+ minor: Number(match[2]),
79
+ patch: Number(match[3]),
80
+ prerelease: match[4] ? match[4].split(".") : []
81
+ };
82
+ }
83
+ function comparePrereleaseIdentifiers(left, right) {
84
+ const leftNumeric = /^[0-9]+$/.test(left);
85
+ const rightNumeric = /^[0-9]+$/.test(right);
86
+ if (leftNumeric && rightNumeric) {
87
+ const delta = Number(left) - Number(right);
88
+ return delta < 0 ? -1 : delta > 0 ? 1 : 0;
89
+ }
90
+ // Numeric identifiers always rank below alphanumeric ones (semver 2.0 §11.4).
91
+ if (leftNumeric)
92
+ return -1;
93
+ if (rightNumeric)
94
+ return 1;
95
+ return left < right ? -1 : left > right ? 1 : 0;
96
+ }
97
+ function compareParsedVersions(left, right) {
98
+ for (const key of ["major", "minor", "patch"]) {
99
+ if (left[key] !== right[key])
100
+ return left[key] - right[key] < 0 ? -1 : 1;
101
+ }
102
+ if (left.prerelease.length === 0 && right.prerelease.length === 0)
103
+ return 0;
104
+ // A release outranks any of its own prereleases.
105
+ if (left.prerelease.length === 0)
106
+ return 1;
107
+ if (right.prerelease.length === 0)
108
+ return -1;
109
+ const length = Math.min(left.prerelease.length, right.prerelease.length);
110
+ for (let index = 0; index < length; index += 1) {
111
+ const delta = comparePrereleaseIdentifiers(left.prerelease[index], right.prerelease[index]);
112
+ if (delta !== 0)
113
+ return delta;
114
+ }
115
+ return left.prerelease.length - right.prerelease.length;
116
+ }
117
+ /** Semver 2.0 ordering: negative when `left` is older, positive when newer, 0 when equal. */
118
+ export function compareVersions(left, right) {
119
+ return compareParsedVersions(parseSemanticVersion(left), parseSemanticVersion(right));
120
+ }
121
+ function parseRange(range) {
122
+ const tokens = range.split(/[\s,]+/).filter(Boolean);
123
+ if (tokens.length === 0)
124
+ throw new ConfigurationBundleValidationError(`Empty version range.`);
125
+ const comparators = [];
126
+ let any = false;
127
+ for (const token of tokens) {
128
+ if (token === "*") {
129
+ any = true;
130
+ continue;
131
+ }
132
+ const match = /^(\^|~|>=|>|<=|<=|<|=)?\s*v?([0-9][0-9A-Za-z.-]*)$/.exec(token);
133
+ if (!match) {
134
+ throw new ConfigurationBundleValidationError(`"${token}" is not a supported range token. Supported: *, X.Y.Z, =X.Y.Z, >=X.Y.Z, >X.Y.Z, <=X.Y.Z, <X.Y.Z, ^X.Y.Z, ~X.Y.Z, joined by spaces (AND).`);
135
+ }
136
+ const version = parseSemanticVersion(match[2]);
137
+ switch (match[1]) {
138
+ case "^":
139
+ comparators.push({ operator: ">=", version, raw: token }, caretUpper(version, token));
140
+ break;
141
+ case "~":
142
+ comparators.push({ operator: ">=", version, raw: token }, tildeUpper(version, token));
143
+ break;
144
+ default:
145
+ comparators.push({ operator: (match[1] ?? "="), version, raw: token });
146
+ }
147
+ }
148
+ return { any, comparators };
149
+ }
150
+ function caretUpper(version, raw) {
151
+ // ^X.Y.Z allows changes that do not modify the left-most non-zero component.
152
+ if (version.major > 0)
153
+ return { operator: "<", version: { major: version.major + 1, minor: 0, patch: 0, prerelease: [] }, raw };
154
+ if (version.minor > 0)
155
+ return { operator: "<", version: { major: 0, minor: version.minor + 1, patch: 0, prerelease: [] }, raw };
156
+ return { operator: "<", version: { major: 0, minor: 0, patch: version.patch + 1, prerelease: [] }, raw };
157
+ }
158
+ function tildeUpper(version, raw) {
159
+ if (version.major > 0) {
160
+ return { operator: "<", version: { major: version.major, minor: version.minor + 1, patch: 0, prerelease: [] }, raw };
161
+ }
162
+ return { operator: "<", version: { major: 0, minor: version.minor + 1, patch: 0, prerelease: [] }, raw };
163
+ }
164
+ /**
165
+ * Whether a runtime version satisfies a declared range. Follows semver 2.0 ordering plus
166
+ * the npm rule that a prerelease version only satisfies a range when some comparator in
167
+ * the range carries a prerelease on the same [major, minor, patch] tuple — so
168
+ * ">=0.3.0-rc.1 <0.4.0" accepts 0.3.0-rc.2 and 0.3.0 but rejects 0.4.0-rc.1.
169
+ */
170
+ /** True only when a range explicitly excludes readers older than the required schema. */
171
+ export function runtimeRangeHasMinimum(range, minimumVersion) {
172
+ const minimum = parseSemanticVersion(minimumVersion);
173
+ return parseRange(range).comparators.some(comparator => [">=", ">", "="].includes(comparator.operator) &&
174
+ compareParsedVersions(comparator.version, minimum) >= 0);
175
+ }
176
+ export function satisfiesRuntimeRange(version, range) {
177
+ const parsedVersion = parseSemanticVersion(version);
178
+ const parsed = parseRange(range);
179
+ if (parsed.any && parsed.comparators.length === 0)
180
+ return true;
181
+ for (const comparator of parsed.comparators) {
182
+ const delta = compareParsedVersions(parsedVersion, comparator.version);
183
+ const satisfied = comparator.operator === ">=" ? delta >= 0
184
+ : comparator.operator === ">" ? delta > 0
185
+ : comparator.operator === "<=" ? delta <= 0
186
+ : comparator.operator === "<" ? delta < 0
187
+ : delta === 0;
188
+ if (!satisfied)
189
+ return false;
190
+ }
191
+ if (parsedVersion.prerelease.length > 0 && !parsed.any) {
192
+ const tupleMatches = parsed.comparators.some((comparator) => comparator.version.prerelease.length > 0 &&
193
+ comparator.version.major === parsedVersion.major &&
194
+ comparator.version.minor === parsedVersion.minor &&
195
+ comparator.version.patch === parsedVersion.patch);
196
+ if (!tupleMatches)
197
+ return false;
198
+ }
199
+ return true;
200
+ }
201
+ /**
202
+ * The release-line range for a given runtime version: ">=0.3.0-rc.1 <0.4.0" for
203
+ * 0.3.0-rc.1. Producers (management export) declare this for the running line.
204
+ */
205
+ export function runtimeReleaseLine(version) {
206
+ const parsed = parseSemanticVersion(version);
207
+ const upper = parsed.major === 0 ? `0.${parsed.minor + 1}.0` : `${parsed.major + 1}.0.0`;
208
+ return `>=${version} <${upper}`;
209
+ }
210
+ /** Secret-shaped patterns; a bundle carrying material matching any of these is rejected. */
211
+ const SECRET_PATTERNS = [
212
+ /sk-[A-Za-z0-9]{16,}/,
213
+ /encryptedOpenAiKey/,
214
+ /encryptedGeminiKey/,
215
+ /encryptedZaiKey/,
216
+ /Bearer\s+[A-Za-z0-9._-]{16,}/
217
+ ];
218
+ /** Conservative existing bundle check, also used for public catalog-review/package material. */
219
+ export function containsSecretShapedMaterial(value) {
220
+ const raw = typeof value === "string" ? value : JSON.stringify(value);
221
+ return typeof raw === "string" && SECRET_PATTERNS.some(pattern => pattern.test(raw));
222
+ }
223
+ function isRecord(value) {
224
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
225
+ }
226
+ function assertBundlePersonaSource(value, index) {
227
+ if (!isRecord(value))
228
+ throw new ConfigurationBundleValidationError(`persona-sources[${index}] must be an object.`);
229
+ const bindingId = value.bindingId;
230
+ if (typeof bindingId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(bindingId)) {
231
+ throw new ConfigurationBundleValidationError(`persona-sources[${index}] bindingId is missing or malformed.`);
232
+ }
233
+ for (const key of ["name", "systemInstructions", "instructionHash"]) {
234
+ if (typeof value[key] !== "string" || value[key].length === 0) {
235
+ throw new ConfigurationBundleValidationError(`persona source ${bindingId} field "${key}" must be a non-empty string.`);
236
+ }
237
+ }
238
+ if (value.inheritsBinding !== undefined && typeof value.inheritsBinding !== "string") {
239
+ throw new ConfigurationBundleValidationError(`persona source ${bindingId} inheritsBinding must be a string.`);
240
+ }
241
+ if (value.sourceVersion !== undefined && typeof value.sourceVersion !== "string") {
242
+ throw new ConfigurationBundleValidationError(`persona source ${bindingId} sourceVersion must be a string.`);
243
+ }
244
+ return value;
245
+ }
246
+ function assertBundleOperationRequirement(value, index) {
247
+ if (!isRecord(value))
248
+ throw new ConfigurationBundleValidationError(`operation-contract.operations[${index}] must be an object.`);
249
+ for (const key of ["operationId", "bindingId"]) {
250
+ if (typeof value[key] !== "string" || value[key].length === 0) {
251
+ throw new ConfigurationBundleValidationError(`operation ${index} field "${key}" must be a non-empty string.`);
252
+ }
253
+ }
254
+ if (!Array.isArray(value.inputModalities) || value.inputModalities.some((m) => typeof m !== "string")) {
255
+ throw new ConfigurationBundleValidationError(`operation ${value.operationId} inputModalities must be an array of modality strings.`);
256
+ }
257
+ if (!Array.isArray(value.providerTools) || value.providerTools.some((t) => typeof t !== "string")) {
258
+ throw new ConfigurationBundleValidationError(`operation ${value.operationId} providerTools must be an array of strings.`);
259
+ }
260
+ if (!["none", "sanitized", "forbidden"].includes(value.protectedPayloadPolicy)) {
261
+ throw new ConfigurationBundleValidationError(`operation ${value.operationId} protectedPayloadPolicy is invalid.`);
262
+ }
263
+ if (typeof value.timeoutMs !== "number" || !Number.isSafeInteger(value.timeoutMs) || value.timeoutMs < 1) {
264
+ throw new ConfigurationBundleValidationError(`operation ${value.operationId} timeoutMs must be a positive integer.`);
265
+ }
266
+ if (typeof value.webSearch !== "boolean" || typeof value.structuredOutput !== "boolean") {
267
+ throw new ConfigurationBundleValidationError(`operation ${value.operationId} webSearch and structuredOutput must be booleans.`);
268
+ }
269
+ return value;
270
+ }
271
+ /**
272
+ * Full verification of a configuration bundle: manifest schema, document set, per-document
273
+ * SHA-256, document schemas (profile schema v2 only — the D1 break), instruction hashes,
274
+ * cross-references, profile compatibility, runtime-range and secrets exclusion. Any
275
+ * mismatch makes the whole bundle invalid; callers fail closed on `valid === false`.
276
+ */
277
+ export async function verifyConfigurationBundle(input) {
278
+ const errors = [];
279
+ const warnings = [];
280
+ const fail = (message) => {
281
+ errors.push(message);
282
+ return null;
283
+ };
284
+ const manifestValidation = validateEntity("configuration-bundle-manifest", input.manifest);
285
+ if (!manifestValidation.valid) {
286
+ // A manifest that fails its own schema cannot be verified further.
287
+ return { valid: false, errors: [`Bundle manifest is invalid: ${manifestValidation.errors.join("; ")}`], warnings, bundle: null };
288
+ }
289
+ const manifest = input.manifest;
290
+ // Runtime compatibility is checked before any document is trusted to load.
291
+ if (input.runtimeVersion !== undefined) {
292
+ try {
293
+ const declaration = parseRuntimeCompatibility(manifest.compatibleRuntime);
294
+ if (declaration.packageName !== RUNTIME_PACKAGE_NAME) {
295
+ errors.push(`compatibleRuntime names package ${declaration.packageName}; this loader is ${RUNTIME_PACKAGE_NAME}.`);
296
+ }
297
+ else if (!satisfiesRuntimeRange(input.runtimeVersion, declaration.range)) {
298
+ errors.push(`Bundle declares ${RUNTIME_PACKAGE_NAME}@${declaration.range}, which excludes the loading runtime ${input.runtimeVersion}. Regenerate the bundle against a compatible release line (see docs/compatibility-matrix.md).`);
299
+ }
300
+ }
301
+ catch (error) {
302
+ fail(error instanceof Error ? error.message : String(error));
303
+ }
304
+ }
305
+ // Document set: every required document declared, nothing unknown declared.
306
+ const declared = Object.keys(manifest.documents);
307
+ for (const name of REQUIRED_BUNDLE_DOCUMENTS) {
308
+ if (!(name in manifest.documents))
309
+ errors.push(`Manifest does not declare required document ${name}.`);
310
+ }
311
+ for (const name of declared) {
312
+ if (!KNOWN_BUNDLE_DOCUMENTS.includes(name)) {
313
+ errors.push(`Manifest declares unknown document ${name}; this contract verifies only ${KNOWN_BUNDLE_DOCUMENTS.join(", ")}.`);
314
+ }
315
+ }
316
+ // Per-document hash over the exact shipped content.
317
+ const rawDocuments = new Map();
318
+ for (const name of declared) {
319
+ if (!KNOWN_BUNDLE_DOCUMENTS.includes(name))
320
+ continue;
321
+ let raw;
322
+ try {
323
+ raw = await input.readDocument(name);
324
+ }
325
+ catch (error) {
326
+ errors.push(`Declared document ${name} could not be read: ${error instanceof Error ? error.message : String(error)}.`);
327
+ continue;
328
+ }
329
+ const actual = sha256HexV2(raw);
330
+ if (actual !== manifest.documents[name]) {
331
+ errors.push(`Document ${name} failed its manifest hash check (expected ${manifest.documents[name]}, content hashes to ${actual}).`);
332
+ continue;
333
+ }
334
+ if (containsSecretShapedMaterial(raw)) {
335
+ errors.push(`Document ${name} contains secret-shaped material; bundles are secrets-excluded by contract.`);
336
+ continue;
337
+ }
338
+ try {
339
+ rawDocuments.set(name, JSON.parse(raw));
340
+ }
341
+ catch (error) {
342
+ errors.push(`Document ${name} is not valid JSON: ${error instanceof Error ? error.message : String(error)}.`);
343
+ }
344
+ }
345
+ if (errors.length > 0)
346
+ return { valid: false, errors, warnings, bundle: null };
347
+ // Catalog.
348
+ const catalog = rawDocuments.get("catalog.json");
349
+ const catalogValidation = validateEntity("catalog-release", catalog);
350
+ if (!catalogValidation.valid)
351
+ errors.push(`catalog.json is invalid: ${catalogValidation.errors.join("; ")}`);
352
+ const catalogRelease = catalog;
353
+ if (catalogRelease?.schemaVersion !== manifest.schemaVersions.catalog)
354
+ errors.push("Manifest catalog schema version does not match catalog.json.");
355
+ if (catalogRelease?.schemaVersion === 2 || catalogRelease?.schemaVersion === 3) {
356
+ try {
357
+ const { range } = parseRuntimeCompatibility(manifest.compatibleRuntime);
358
+ const minimumVersion = catalogRelease.schemaVersion === 3 ? MINIMUM_CATALOG_V3_RUNTIME_VERSION : catalogRelease.prices?.some(price => price.schemaVersion === 2)
359
+ ? MINIMUM_PRICE_V2_RUNTIME_VERSION : MINIMUM_CATALOG_V2_RUNTIME_VERSION;
360
+ const minimum = parseSemanticVersion(minimumVersion);
361
+ if (!parseRange(range).comparators.some(comparator => [">=", ">", "="].includes(comparator.operator) &&
362
+ compareParsedVersions(comparator.version, minimum) >= 0)) {
363
+ errors.push(`Catalog v${catalogRelease.schemaVersion} requires an explicit runtime minimum of ${minimumVersion} or newer.`);
364
+ }
365
+ }
366
+ catch (error) {
367
+ fail(error instanceof Error ? error.message : String(error));
368
+ }
369
+ }
370
+ // Profiles: schema v2 only.
371
+ const profilesDocument = rawDocuments.get("profiles.json");
372
+ const profiles = [];
373
+ if (Array.isArray(profilesDocument)) {
374
+ const seen = new Set();
375
+ for (const [index, entry] of profilesDocument.entries()) {
376
+ const validation = validateEntity("execution-profile-revision", entry);
377
+ if (!validation.valid) {
378
+ errors.push(`profiles.json[${index}] is invalid: ${validation.errors.join("; ")}`);
379
+ continue;
380
+ }
381
+ const profile = entry;
382
+ if (profile.schemaVersion !== 2) {
383
+ errors.push(`profiles.json[${index}] carries schemaVersion ${profile.schemaVersion}; profile schema v1 is not accepted (see docs/compatibility-matrix.md).`);
384
+ continue;
385
+ }
386
+ if (profile.status !== "published") {
387
+ errors.push(`Profile ${profile.profileId}@${profile.revision} is ${profile.status}; only published revisions may be bundled.`);
388
+ }
389
+ const key = `${profile.profileId}@${profile.revision}`;
390
+ if (seen.has(key))
391
+ errors.push(`Duplicate profile ${key} in bundle.`);
392
+ seen.add(key);
393
+ profiles.push(profile);
394
+ }
395
+ }
396
+ else {
397
+ errors.push("profiles.json must be an array of execution profile revisions.");
398
+ }
399
+ if (manifest.schemaVersions.profiles !== 2)
400
+ errors.push("Manifest schemaVersions.profiles must be 2.");
401
+ try {
402
+ assertStableProfileIdentities(profiles);
403
+ }
404
+ catch (error) {
405
+ errors.push(error instanceof Error ? error.message : String(error));
406
+ }
407
+ // Default bindings.
408
+ const bindingsDocument = rawDocuments.get("default-bindings.json");
409
+ const defaultBindings = {};
410
+ const subPersonaInheritance = {};
411
+ if (isRecord(bindingsDocument) && isRecord(bindingsDocument.defaultBindings)) {
412
+ for (const [bindingId, profileId] of Object.entries(bindingsDocument.defaultBindings)) {
413
+ if (typeof profileId !== "string") {
414
+ errors.push(`Default binding ${bindingId} must map to a profile ID string.`);
415
+ continue;
416
+ }
417
+ if (!profiles.some((profile) => profile.profileId === profileId)) {
418
+ errors.push(`Default binding ${bindingId} references missing profile ${profileId}.`);
419
+ continue;
420
+ }
421
+ defaultBindings[bindingId] = profileId;
422
+ }
423
+ if (isRecord(bindingsDocument.subPersonaInheritance)) {
424
+ for (const [subPersona, parent] of Object.entries(bindingsDocument.subPersonaInheritance)) {
425
+ if (typeof parent !== "string") {
426
+ errors.push(`Sub-persona ${subPersona} inheritance must map to a parent binding string.`);
427
+ continue;
428
+ }
429
+ if (!(parent in defaultBindings))
430
+ errors.push(`Sub-persona ${subPersona} inherits unknown parent binding ${parent}.`);
431
+ subPersonaInheritance[subPersona] = parent;
432
+ }
433
+ }
434
+ }
435
+ else {
436
+ errors.push("default-bindings.json must be an object with a defaultBindings record.");
437
+ }
438
+ // Persona sources (optional).
439
+ let personaSources = [];
440
+ const personaSourcesDocument = rawDocuments.get("persona-sources.json");
441
+ if (personaSourcesDocument !== undefined) {
442
+ if (!Array.isArray(personaSourcesDocument)) {
443
+ errors.push("persona-sources.json must be an array of persona source templates.");
444
+ }
445
+ else {
446
+ try {
447
+ personaSources = personaSourcesDocument.map((entry, index) => assertBundlePersonaSource(entry, index));
448
+ const byBinding = new Set(personaSources.map((source) => source.bindingId));
449
+ for (const source of personaSources) {
450
+ if (hashInstructions(source.systemInstructions) !== source.instructionHash) {
451
+ errors.push(`Persona source ${source.bindingId} instruction hash mismatch.`);
452
+ }
453
+ if (source.inheritsBinding !== undefined && !byBinding.has(source.inheritsBinding)) {
454
+ errors.push(`Persona source ${source.bindingId} inherits unknown parent binding ${source.inheritsBinding}.`);
455
+ }
456
+ }
457
+ for (const bindingId of Object.keys(defaultBindings)) {
458
+ if (!byBinding.has(bindingId) && !(bindingId in subPersonaInheritance)) {
459
+ warnings.push(`Binding ${bindingId} has no persona source template in the bundle.`);
460
+ }
461
+ }
462
+ }
463
+ catch (error) {
464
+ errors.push(error instanceof Error ? error.message : String(error));
465
+ }
466
+ }
467
+ }
468
+ // Operation contract (optional).
469
+ let operationContract = null;
470
+ const contractDocument = rawDocuments.get("operation-contract.json");
471
+ if (contractDocument !== undefined) {
472
+ if (!isRecord(contractDocument) || typeof contractDocument.contractId !== "string" || !Array.isArray(contractDocument.operations)) {
473
+ errors.push("operation-contract.json must be an object with contractId and operations.");
474
+ }
475
+ else {
476
+ try {
477
+ const operations = contractDocument.operations.map((entry, index) => assertBundleOperationRequirement(entry, index));
478
+ operationContract = { contractId: contractDocument.contractId, operations };
479
+ for (const operation of operations) {
480
+ if (operation.bindingId !== "*" && !(operation.bindingId in defaultBindings) && !(operation.bindingId in subPersonaInheritance)) {
481
+ errors.push(`Operation ${operation.operationId} references unknown binding ${operation.bindingId}.`);
482
+ }
483
+ }
484
+ }
485
+ catch (error) {
486
+ errors.push(error instanceof Error ? error.message : String(error));
487
+ }
488
+ }
489
+ }
490
+ // Connections (optional): credential references only — never secret values.
491
+ let connections = [];
492
+ const connectionsDocument = rawDocuments.get("connections.json");
493
+ if (connectionsDocument !== undefined) {
494
+ if (!Array.isArray(connectionsDocument)) {
495
+ errors.push("connections.json must be an array of connection documents.");
496
+ }
497
+ else {
498
+ for (const [index, entry] of connectionsDocument.entries()) {
499
+ const validation = validateEntity("connection", entry);
500
+ if (!validation.valid) {
501
+ errors.push(`connections.json[${index}] is invalid: ${validation.errors.join("; ")}`);
502
+ continue;
503
+ }
504
+ connections.push(entry);
505
+ }
506
+ }
507
+ }
508
+ // Selection rules (optional): application-specific; structure is opaque here, content is hash-pinned.
509
+ let selectionRules = null;
510
+ const rulesDocument = rawDocuments.get("selection-rules.json");
511
+ if (rulesDocument !== undefined) {
512
+ if (!isRecord(rulesDocument)) {
513
+ errors.push("selection-rules.json must be a JSON object.");
514
+ }
515
+ else {
516
+ selectionRules = rulesDocument;
517
+ }
518
+ }
519
+ // Every bundled profile's slots must resolve inside the pinned catalog, with or without
520
+ // adapter knowledge (slot-model membership is a pure cross-reference).
521
+ if (catalogRelease) {
522
+ const modelsById = new Set(catalogRelease.models.map((model) => model.catalogId));
523
+ for (const profile of profiles) {
524
+ for (const slot of [profile.primary, ...profile.fallbacks]) {
525
+ if (!modelsById.has(slot.catalogId)) {
526
+ errors.push(`Profile ${profile.profileId}@${profile.revision} slot model ${slot.catalogId} is absent from the bundle catalog.`);
527
+ }
528
+ }
529
+ }
530
+ }
531
+ // Profile compatibility against the pinned catalog (when adapters are known).
532
+ if (input.installedAdapters && catalogRelease && errors.length === 0) {
533
+ for (const [bindingId, profileId] of Object.entries(defaultBindings)) {
534
+ const profile = profiles.find((entry) => entry.profileId === profileId);
535
+ const evaluation = evaluateProfileCompatibility({
536
+ profile,
537
+ catalog: catalogRelease,
538
+ installedAdapters: input.installedAdapters,
539
+ ...(input.requestingApplicationId ? { requestingApplicationId: input.requestingApplicationId } : {})
540
+ });
541
+ if (!evaluation.compatible) {
542
+ errors.push(`Default binding ${bindingId} profile ${profileId} incompatible: ${evaluation.reasons.map((reason) => reason.message).join("; ")}`);
543
+ }
544
+ }
545
+ }
546
+ if (errors.length > 0 || !catalogRelease) {
547
+ return { valid: false, errors, warnings, bundle: null };
548
+ }
549
+ const bundle = {
550
+ manifest,
551
+ manifestIdentity: configurationBundleIdentity(manifest),
552
+ catalog: catalogRelease,
553
+ profiles,
554
+ personaSources,
555
+ operationContract,
556
+ defaultBindings,
557
+ subPersonaInheritance,
558
+ selectionRules,
559
+ connections
560
+ };
561
+ return { valid: true, errors, warnings, bundle };
562
+ }
563
+ /**
564
+ * Assembles a bundle from already-validated documents and hashes the exact serialized
565
+ * content into the manifest. The result is self-verifying: handing `files` to a directory
566
+ * and loading it through the runtime (or verifyConfigurationBundle) must succeed —
567
+ * management export runs that same verification before serving the bundle.
568
+ */
569
+ export function assembleConfigurationBundle(input) {
570
+ if (input.profiles.some((profile) => profile.schemaVersion !== 2)) {
571
+ throw new ConfigurationBundleValidationError("Bundled profiles must be schema v2; v1 profiles cannot be exported.");
572
+ }
573
+ if (input.profiles.some((profile) => profile.status !== "published")) {
574
+ throw new ConfigurationBundleValidationError("Bundled profiles must be published revisions.");
575
+ }
576
+ const profileIds = new Set(input.profiles.map((profile) => profile.profileId));
577
+ for (const [bindingId, profileId] of Object.entries(input.defaultBindings)) {
578
+ if (!profileIds.has(profileId)) {
579
+ throw new ConfigurationBundleValidationError(`Default binding ${bindingId} references a profile not included in the bundle.`);
580
+ }
581
+ }
582
+ // The declared range must at least parse; an unloadable declaration is a producer bug.
583
+ parseRange(input.runtimeVersionRange);
584
+ const files = {
585
+ "catalog.json": JSON.stringify(input.catalog, null, 2),
586
+ "profiles.json": JSON.stringify(input.profiles, null, 2),
587
+ "default-bindings.json": JSON.stringify({
588
+ defaultBindings: input.defaultBindings,
589
+ ...(input.subPersonaInheritance ? { subPersonaInheritance: input.subPersonaInheritance } : {})
590
+ }, null, 2)
591
+ };
592
+ if (input.personaSources && input.personaSources.length > 0)
593
+ files["persona-sources.json"] = JSON.stringify(input.personaSources, null, 2);
594
+ if (input.operationContract)
595
+ files["operation-contract.json"] = JSON.stringify(input.operationContract, null, 2);
596
+ if (input.selectionRules)
597
+ files["selection-rules.json"] = JSON.stringify(input.selectionRules, null, 2);
598
+ if (input.connections && input.connections.length > 0)
599
+ files["connections.json"] = JSON.stringify(input.connections, null, 2);
600
+ const manifest = {
601
+ schemaVersion: CONFIGURATION_BUNDLE_SCHEMA_VERSION,
602
+ kind: CONFIGURATION_BUNDLE_KIND,
603
+ bundleVersion: input.bundleVersion,
604
+ compatibleRuntime: `${RUNTIME_PACKAGE_NAME}@${input.runtimeVersionRange}` +
605
+ (input.catalog.schemaVersion === 3 ? ` >=${MINIMUM_CATALOG_V3_RUNTIME_VERSION}` : input.catalog.schemaVersion === 2 ? ` >=${input.catalog.prices.some(price => price.schemaVersion === 2)
606
+ ? MINIMUM_PRICE_V2_RUNTIME_VERSION : MINIMUM_CATALOG_V2_RUNTIME_VERSION}` : ""),
607
+ schemaVersions: {
608
+ profiles: 2,
609
+ catalog: input.catalog.schemaVersion,
610
+ ...(files["persona-sources.json"] ? { personaSources: 2 } : {}),
611
+ ...(files["operation-contract.json"] ? { operationContract: 2 } : {})
612
+ },
613
+ provenance: {
614
+ builtAt: (input.now ?? (() => new Date))().toISOString(),
615
+ builtBy: input.builtBy,
616
+ secretsIncluded: false,
617
+ source: input.provenance
618
+ },
619
+ documents: Object.fromEntries(Object.entries(files).map(([name, content]) => [name, sha256HexV2(content)]))
620
+ };
621
+ files[BUNDLE_MANIFEST_FILE] = JSON.stringify(manifest, null, 2);
622
+ return { manifest, files };
623
+ }
624
+ /** Convenience re-export: canonical helpers used by bundle tooling. */
625
+ export { canonicalJsonV2, hashDocumentV2 };
626
+ //# sourceMappingURL=configuration-bundle.js.map