@adcp/sdk 17.0.0-beta.30 → 17.0.0-beta.32

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 (38) hide show
  1. package/dist/lib/identity-3.3/trust.js +10 -4
  2. package/dist/lib/identity-3.3/trust.mjs +10 -4
  3. package/dist/lib/server/create-adcp-server.js +7 -8
  4. package/dist/lib/server/create-adcp-server.mjs +9 -10
  5. package/dist/lib/server/error-arm-tools.d.mts +23 -14
  6. package/dist/lib/server/error-arm-tools.d.ts +23 -14
  7. package/dist/lib/server/error-arm-tools.js +82 -34
  8. package/dist/lib/server/error-arm-tools.mjs +81 -34
  9. package/dist/lib/testing/storyboard/compliance.js +53 -24
  10. package/dist/lib/testing/storyboard/compliance.mjs +53 -24
  11. package/dist/lib/testing/storyboard/context.js +14 -10
  12. package/dist/lib/testing/storyboard/context.mjs +14 -10
  13. package/dist/lib/testing/storyboard/loader.js +2 -2
  14. package/dist/lib/testing/storyboard/loader.mjs +2 -2
  15. package/dist/lib/testing/storyboard/validations.d.mts +1 -1
  16. package/dist/lib/testing/storyboard/validations.d.ts +1 -1
  17. package/dist/lib/testing/storyboard/yaml-cache.d.mts +21 -0
  18. package/dist/lib/testing/storyboard/yaml-cache.d.ts +21 -0
  19. package/dist/lib/testing/storyboard/yaml-cache.js +168 -0
  20. package/dist/lib/testing/storyboard/yaml-cache.mjs +139 -0
  21. package/dist/lib/validation/schema-diagnostic-origins.js +55 -25
  22. package/dist/lib/validation/schema-diagnostic-origins.mjs +55 -25
  23. package/dist/lib/validation/schema-loader.js +499 -44
  24. package/dist/lib/validation/schema-loader.mjs +499 -46
  25. package/dist/lib/validation/schema-validator.js +4 -6
  26. package/dist/lib/validation/schema-validator.mjs +6 -7
  27. package/dist/lib/validation/validator-cache.d.mts +45 -0
  28. package/dist/lib/validation/validator-cache.d.ts +45 -0
  29. package/dist/lib/validation/validator-cache.js +249 -0
  30. package/dist/lib/validation/validator-cache.mjs +227 -0
  31. package/dist/lib/version.d.mts +3 -3
  32. package/dist/lib/version.d.ts +3 -3
  33. package/dist/lib/version.js +3 -3
  34. package/dist/lib/version.mjs +3 -3
  35. package/docs/TYPE-SUMMARY.md +2 -2
  36. package/docs/llms.txt +2 -2
  37. package/docs/migration-14.x-rc-worksheet.md +4 -4
  38. package/package.json +1 -1
@@ -33,6 +33,7 @@ __export(schema_loader_exports, {
33
33
  acceptEnvelopeOnClosedResponseRoot: () => acceptEnvelopeOnClosedResponseRoot,
34
34
  acceptEnvelopeOnClosedResponseRootForVersion: () => acceptEnvelopeOnClosedResponseRootForVersion,
35
35
  bindIdentity33SchemaScope: () => bindIdentity33SchemaScope,
36
+ definesToolRequest: () => definesToolRequest,
36
37
  getActiveSchemaArtifactLocation: () => getActiveSchemaArtifactLocation,
37
38
  getCanonicalToolValidatorForVersion: () => getCanonicalToolValidatorForVersion,
38
39
  getMcpProfileInputSchema: () => getMcpProfileInputSchema,
@@ -48,6 +49,7 @@ __export(schema_loader_exports, {
48
49
  getToolSchemaDocument: () => getToolSchemaDocument,
49
50
  getValidator: () => getValidator,
50
51
  getValidatorDiagnosticOrigin: () => getValidatorDiagnosticOrigin,
52
+ getValidatorRootSchemaId: () => getValidatorRootSchemaId,
51
53
  hasSchemaBundle: () => hasSchemaBundle,
52
54
  isExternalSchemaRootActive: () => isExternalSchemaRootActive,
53
55
  isIdentity33SchemaScope: () => isIdentity33SchemaScope,
@@ -73,6 +75,8 @@ var import_ajv_formats = __toESM(require("ajv-formats"));
73
75
  var import_async_hooks = require("async_hooks");
74
76
  var import_fs = require("fs");
75
77
  var import_path = __toESM(require("path"));
78
+ var import_module = require("module");
79
+ var import_node_crypto = require("node:crypto");
76
80
  var import_node_util = require("node:util");
77
81
  var import_version = require('../version.js');
78
82
  var import_errors = require('../errors/index.js');
@@ -216,11 +220,26 @@ function compareBundleNamesDesc(a, b) {
216
220
  }
217
221
  const states = /* @__PURE__ */ new Map();
218
222
  const validatorDiagnosticOrigins = /* @__PURE__ */ new WeakMap();
223
+ const pendingDiagnosticOrigins = /* @__PURE__ */ new WeakMap();
224
+ const cachedValidatorRootSchemaIds = /* @__PURE__ */ new WeakMap();
225
+ const modularOriginStates = /* @__PURE__ */ new WeakMap();
226
+ function diagnosticOriginsFor(validator) {
227
+ pendingDiagnosticOrigins.get(validator)?.();
228
+ const origins = validatorDiagnosticOrigins.get(validator);
229
+ const state = origins && modularOriginStates.get(origins);
230
+ if (state) flushDeferredCompiles(state);
231
+ return origins;
232
+ }
219
233
  function resolveValidatorDiagnosticPath(validator, schemaPath) {
220
- return validatorDiagnosticOrigins.get(validator)?.resolve(schemaPath);
234
+ return diagnosticOriginsFor(validator)?.resolve(schemaPath);
221
235
  }
222
236
  function getValidatorDiagnosticOrigin(validator, schemaPath) {
223
- return validatorDiagnosticOrigins.get(validator)?.origin(schemaPath);
237
+ return diagnosticOriginsFor(validator)?.origin(schemaPath);
238
+ }
239
+ function getValidatorRootSchemaId(validator) {
240
+ if (cachedValidatorRootSchemaIds.has(validator)) return cachedValidatorRootSchemaIds.get(validator);
241
+ const root = validator.schema;
242
+ return root && typeof root === "object" && typeof root.$id === "string" ? root.$id : void 0;
224
243
  }
225
244
  const schemaRefValidators = /* @__PURE__ */ new Map();
226
245
  const keywordSchemaRefValidators = /* @__PURE__ */ new WeakMap();
@@ -233,8 +252,10 @@ const scopedExternalSchemaRoots = new import_async_hooks.AsyncLocalStorage();
233
252
  function stateCacheKey(bundleKey, root) {
234
253
  return `${bundleKey}\0${root}`;
235
254
  }
255
+ const epochRootFingerprints = /* @__PURE__ */ new Map();
236
256
  function clearStatesForBundle(bundleKey) {
237
257
  keywordCacheGeneration++;
258
+ epochRootFingerprints.delete(bundleKey);
238
259
  for (const [stateKey, state] of states) {
239
260
  if (state.version === bundleKey) states.delete(stateKey);
240
261
  }
@@ -242,13 +263,156 @@ function clearStatesForBundle(bundleKey) {
242
263
  if (cacheKey.startsWith(`${bundleKey}\0`)) schemaRefValidators.delete(cacheKey);
243
264
  }
244
265
  }
245
- function hasSchemaRootShape(root) {
266
+ function enterSchemaRootEpoch(aliases, root, fingerprint) {
267
+ for (const alias of aliases) {
268
+ if (fingerprint !== void 0 && epochRootFingerprints.get(alias)?.get(root) === fingerprint) continue;
269
+ clearStatesForBundle(alias);
270
+ if (fingerprint !== void 0) epochRootFingerprints.set(alias, /* @__PURE__ */ new Map([[root, fingerprint]]));
271
+ }
272
+ }
273
+ function newRootCheckReads(root) {
274
+ return { identities: /* @__PURE__ */ new Map(), stats: /* @__PURE__ */ new Map(), root };
275
+ }
276
+ function persistedRootIdentityKey(root) {
277
+ const { validatorCacheKey } = require('./validator-cache.js');
278
+ return validatorCacheKey(["schema-root-identities", ...bundledValidatorCacheStaticKey(), import_path.default.resolve(root)]);
279
+ }
280
+ function persistedRootIdentities(reads) {
281
+ if (reads.persisted !== void 0) return reads.persisted;
282
+ reads.persisted = null;
283
+ const cache = openLoaderDataCache();
284
+ if (!cache) return null;
285
+ const value = cache.readData(persistedRootIdentityKey(reads.root));
286
+ if (!value || value.root !== import_path.default.resolve(reads.root) || !Array.isArray(value.documents)) return null;
287
+ const identities = /* @__PURE__ */ new Map();
288
+ for (const record of value.documents) {
289
+ if (!Array.isArray(record) || typeof record[0] !== "string" || typeof record[1] !== "string") return null;
290
+ const [file, stat, kind, $id, $schema] = record;
291
+ const identity = kind === "null" ? null : kind === "object" ? {
292
+ ...typeof $id === "string" && { $id },
293
+ ...typeof $schema === "string" && { $schema }
294
+ } : void 0;
295
+ identities.set(file, { stat, identity });
296
+ }
297
+ reads.persisted = identities;
298
+ return identities;
299
+ }
300
+ function persistRootCheck(reads) {
301
+ if (!reads.stats || reads.stats.size === 0) return;
302
+ const cache = openLoaderDataCache();
303
+ if (!cache) return;
304
+ const stored = persistedRootIdentities(reads);
305
+ let changed = stored === null || stored.size !== reads.stats.size;
306
+ const documents = [];
307
+ for (const [file, { stat, identity }] of reads.stats) {
308
+ documents.push([
309
+ file,
310
+ stat,
311
+ identity === void 0 ? "unparseable" : identity === null ? "null" : "object",
312
+ identity?.$id ?? null,
313
+ identity?.$schema ?? null
314
+ ]);
315
+ const previous = stored?.get(file);
316
+ if (!changed && (previous?.stat !== stat || !(0, import_node_util.isDeepStrictEqual)(previous.identity, identity))) changed = true;
317
+ }
318
+ if (changed) cache.writeData(persistedRootIdentityKey(reads.root), { root: import_path.default.resolve(reads.root), documents });
319
+ }
320
+ function rootFingerprint(root, reads) {
321
+ if (!reads.stats || reads.stats.size === 0 || import_path.default.basename(root) === "bundled") return void 0;
322
+ const hash = (0, import_node_crypto.createHash)("sha256");
323
+ for (const [file, { stat }] of [...reads.stats].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
324
+ hash.update(file).update("\0").update(stat).update("\0");
325
+ }
326
+ return hash.digest("hex");
327
+ }
328
+ const ROOT_DOCUMENT_SETTLE_NS = 3000000000n;
329
+ const ROOT_DOCUMENT_CACHE_LIMIT = 5e4;
330
+ function rootDocumentIdentityCache() {
331
+ const key = /* @__PURE__ */ Symbol.for(`@adcp/sdk.schema-root-document-identities.${import_version.LIBRARY_VERSION}`);
332
+ const registry = globalThis;
333
+ return registry[key] ??= /* @__PURE__ */ new Map();
334
+ }
335
+ function rootDocumentIdentity(schema) {
336
+ if (schema === null) return null;
337
+ const record = schema;
338
+ return {
339
+ ...typeof record.$id === "string" && { $id: record.$id },
340
+ ...typeof record.$schema === "string" && { $schema: record.$schema }
341
+ };
342
+ }
343
+ function readRootDocument(file, reads) {
344
+ let identity = reads.identities.get(file);
345
+ if (identity === void 0) {
346
+ try {
347
+ identity = readRootDocumentUncached(file, reads);
348
+ } catch (error) {
349
+ identity = error instanceof Error ? error : new Error(String(error));
350
+ }
351
+ reads.identities.set(file, identity);
352
+ }
353
+ if (identity instanceof Error) throw identity;
354
+ return identity;
355
+ }
356
+ function rememberRootDocumentIdentity(cache, file, entry) {
357
+ cache.delete(file);
358
+ cache.set(file, entry);
359
+ if (cache.size > ROOT_DOCUMENT_CACHE_LIMIT) {
360
+ const oldest = cache.keys().next().value;
361
+ if (oldest !== void 0) cache.delete(oldest);
362
+ }
363
+ }
364
+ function readRootDocumentUncached(file, reads) {
365
+ const bundled = file.includes(`${import_path.default.sep}bundled${import_path.default.sep}`);
366
+ const nowNs = BigInt(Date.now()) * 1000000n;
367
+ let stat;
368
+ try {
369
+ stat = (0, import_fs.statSync)(file, { bigint: true });
370
+ } catch {
371
+ stat = void 0;
372
+ }
373
+ if (!stat?.isFile()) {
374
+ reads.stats = void 0;
375
+ return rootDocumentIdentity(loadJson(file));
376
+ }
377
+ const cache = rootDocumentIdentityCache();
378
+ const cacheKey = import_path.default.resolve(file);
379
+ const statKey = `${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
380
+ let known = cache.get(cacheKey);
381
+ if (known?.stat !== statKey) {
382
+ const persisted = persistedRootIdentities(reads)?.get(cacheKey);
383
+ known = persisted?.stat === statKey ? persisted : void 0;
384
+ if (known) rememberRootDocumentIdentity(cache, cacheKey, known);
385
+ }
386
+ if (known) {
387
+ reads.stats?.set(cacheKey, known);
388
+ if (known.identity === void 0) throw new Error(`Schema document does not parse: ${file}`);
389
+ return known.identity;
390
+ }
391
+ let identity;
392
+ try {
393
+ const schema = (bundled ? (0, import_bundled_schema_store.loadBundledSchemaFile)(file) : void 0) ?? JSON.parse((0, import_fs.readFileSync)(file, "utf-8"));
394
+ identity = rootDocumentIdentity(schema);
395
+ } catch {
396
+ identity = void 0;
397
+ }
398
+ const settled = stat.mtimeNs < nowNs - ROOT_DOCUMENT_SETTLE_NS && stat.ctimeNs < nowNs - ROOT_DOCUMENT_SETTLE_NS;
399
+ if (settled) {
400
+ const entry = { stat: statKey, identity };
401
+ reads.stats?.set(cacheKey, entry);
402
+ rememberRootDocumentIdentity(cache, cacheKey, entry);
403
+ } else {
404
+ reads.stats = void 0;
405
+ }
406
+ if (identity === void 0) throw new Error(`Schema document does not parse: ${file}`);
407
+ return identity;
408
+ }
409
+ function hasSchemaRootShape(root, reads = newRootCheckReads(root)) {
246
410
  if (!(0, import_fs.existsSync)(root)) return false;
247
411
  const bundledRoot = import_path.default.join(root, "bundled");
248
412
  const files = (0, import_bundled_schema_store.hasBundledSchemaStore)(bundledRoot) ? walkJsonFiles(bundledRoot) : walkJsonFiles(root);
249
413
  return files.some((file) => {
250
414
  try {
251
- const schema = loadJson(file);
415
+ const schema = readRootDocument(file, reads);
252
416
  return typeof schema.$id === "string" || typeof schema.$schema === "string";
253
417
  } catch {
254
418
  return false;
@@ -258,22 +422,6 @@ function hasSchemaRootShape(root) {
258
422
  function schemaIdVersionHint(schemaId) {
259
423
  return schemaId.match(/\/schemas\/([^/]+)\//)?.[1];
260
424
  }
261
- function collectSchemaRootVersionAliases(root) {
262
- const aliases = /* @__PURE__ */ new Set();
263
- for (const file of walkJsonFiles(root)) {
264
- let schema;
265
- try {
266
- schema = loadJson(file);
267
- } catch {
268
- continue;
269
- }
270
- if (typeof schema.$id !== "string") continue;
271
- const hint = schemaIdVersionHint(schema.$id);
272
- if (!hint) continue;
273
- for (const alias of schemaRootVersionAliases(hint)) aliases.add(alias);
274
- }
275
- return aliases;
276
- }
277
425
  function schemaRootVersionAliases(version) {
278
426
  const aliases = /* @__PURE__ */ new Set([version]);
279
427
  try {
@@ -292,19 +440,25 @@ function schemaRootVersionAliases(version) {
292
440
  function prereleaseFamilyAlias(releasePrecisionVersion) {
293
441
  return releasePrecisionVersion.match(/^(\d+\.\d+-[0-9A-Za-z-]+)\.\d+$/)?.[1];
294
442
  }
295
- function collectSchemaRootVersionAliasGroups(root) {
443
+ function collectSchemaRootVersionAliasGroups(root, reads) {
296
444
  const groups = [];
445
+ const aliasesByHint = /* @__PURE__ */ new Map();
297
446
  for (const file of walkJsonFiles(root)) {
298
447
  let schema;
299
448
  try {
300
- schema = loadJson(file);
449
+ schema = readRootDocument(file, reads);
301
450
  } catch {
302
451
  continue;
303
452
  }
304
453
  if (typeof schema.$id !== "string") continue;
305
454
  const hint = schemaIdVersionHint(schema.$id);
306
455
  if (!hint) continue;
307
- groups.push({ hint, aliases: schemaRootVersionAliases(hint) });
456
+ let aliases = aliasesByHint.get(hint);
457
+ if (!aliases) {
458
+ aliases = schemaRootVersionAliases(hint);
459
+ aliasesByHint.set(hint, aliases);
460
+ }
461
+ groups.push({ hint, aliases });
308
462
  }
309
463
  return groups;
310
464
  }
@@ -323,10 +477,10 @@ function readSchemaRootDeclaredVersion(root) {
323
477
  }
324
478
  return void 0;
325
479
  }
326
- function assertSchemaRootMatchesVersion(version, root) {
480
+ function assertSchemaRootMatchesVersion(version, root, reads = newRootCheckReads(root)) {
327
481
  const expectedAliases = schemaRootVersionAliases(version);
328
- const rootGroups = collectSchemaRootVersionAliasGroups(root);
329
- const rootAliases = collectSchemaRootVersionAliases(root);
482
+ const rootGroups = collectSchemaRootVersionAliasGroups(root, reads);
483
+ const rootAliases = new Set(rootGroups.flatMap((group) => [...group.aliases]));
330
484
  const declaredVersion = readSchemaRootDeclaredVersion(root);
331
485
  const declaredAliases = declaredVersion ? schemaRootVersionAliases(declaredVersion) : /* @__PURE__ */ new Set();
332
486
  const latestIsPinnedByIndex = [...declaredAliases].some((alias) => expectedAliases.has(alias));
@@ -344,15 +498,15 @@ const externalSchemaRootAliases = /* @__PURE__ */ new Map();
344
498
  function registerExternalSchemaRoot(version, root) {
345
499
  const key = resolveBundleKey(version);
346
500
  (0, import_bundled_schema_store.clearBundledSchemaStoreCache)(import_path.default.join(root, "bundled"));
347
- if (!hasSchemaRootShape(root)) {
501
+ const reads = newRootCheckReads(root);
502
+ if (!hasSchemaRootShape(root, reads)) {
348
503
  throw new Error(`External AdCP schema root for version "${version}" not found or empty at ${root}`);
349
504
  }
350
- const aliases = assertSchemaRootMatchesVersion(version, root);
505
+ const aliases = assertSchemaRootMatchesVersion(version, root, reads);
506
+ persistRootCheck(reads);
351
507
  externalSchemaRootAliases.set(key, aliases);
352
- for (const alias of aliases) {
353
- externalSchemaRoots.set(alias, root);
354
- clearStatesForBundle(alias);
355
- }
508
+ for (const alias of aliases) externalSchemaRoots.set(alias, root);
509
+ enterSchemaRootEpoch(aliases, root, rootFingerprint(root, reads));
356
510
  }
357
511
  function unregisterExternalSchemaRoot(version) {
358
512
  const key = resolveBundleKey(version);
@@ -371,16 +525,16 @@ function unregisterExternalSchemaRoot(version) {
371
525
  function withExternalSchemaRoot(version, root, fn) {
372
526
  if (root === void 0) return fn();
373
527
  (0, import_bundled_schema_store.clearBundledSchemaStoreCache)(import_path.default.join(root, "bundled"));
374
- if (!hasSchemaRootShape(root)) {
528
+ const reads = newRootCheckReads(root);
529
+ if (!hasSchemaRootShape(root, reads)) {
375
530
  throw new Error(`External AdCP schema root for version "${version}" not found or empty at ${root}`);
376
531
  }
377
- const aliases = assertSchemaRootMatchesVersion(version, root);
532
+ const aliases = assertSchemaRootMatchesVersion(version, root, reads);
533
+ persistRootCheck(reads);
378
534
  const parent = scopedExternalSchemaRoots.getStore();
379
535
  const next = new Map(parent);
380
- for (const alias of aliases) {
381
- next.set(alias, root);
382
- clearStatesForBundle(alias);
383
- }
536
+ for (const alias of aliases) next.set(alias, root);
537
+ enterSchemaRootEpoch(aliases, root, rootFingerprint(root, reads));
384
538
  return scopedExternalSchemaRoots.run(next, fn);
385
539
  }
386
540
  function getActiveSchemaArtifactLocation(version) {
@@ -576,12 +730,29 @@ function ensureInit(version) {
576
730
  code: { process: diagnosticOrigins.process }
577
731
  });
578
732
  (0, import_ajv_formats.default)(ajv);
733
+ const bundledCache = openBundledValidatorCache();
579
734
  const bundledAjv = new import_ajv.default({
580
735
  inlineRefs: false,
581
736
  strict: false,
582
737
  allErrors: true,
583
738
  allowUnionTypes: true,
584
- code: { process: bundledDiagnosticOrigins.process }
739
+ code: bundledCache ? {
740
+ // Ajv keeps the code from before code.process; the cache records
741
+ // the processed code so stored modules carry the origin rewrite.
742
+ source: true,
743
+ process: (source, environment) => {
744
+ const output = bundledDiagnosticOrigins.process(
745
+ source,
746
+ environment
747
+ );
748
+ bundledCache.compileLog?.push({
749
+ env: environment,
750
+ source,
751
+ output
752
+ });
753
+ return output;
754
+ }
755
+ } : { process: bundledDiagnosticOrigins.process }
585
756
  });
586
757
  (0, import_ajv_formats.default)(bundledAjv);
587
758
  const state = {
@@ -596,13 +767,24 @@ function ensureInit(version) {
596
767
  entityPaths: /* @__PURE__ */ new Map(),
597
768
  root,
598
769
  coreLoaded: false,
599
- version: key
770
+ version: key,
771
+ ...bundledCache && { bundledCache }
600
772
  };
773
+ modularOriginStates.set(diagnosticOrigins, state);
601
774
  states.set(cacheKey, state);
602
775
  return state;
603
776
  }
604
777
  function ensureCoreLoaded(s) {
605
778
  if (s.coreLoaded) return;
779
+ try {
780
+ registerCoreDocuments(s);
781
+ } catch (error) {
782
+ s.coreLoadFailed = true;
783
+ throw error;
784
+ }
785
+ s.coreLoaded = true;
786
+ }
787
+ function registerCoreDocuments(s) {
606
788
  const selectedToolsById = /* @__PURE__ */ new Map();
607
789
  const responseToolFiles = /* @__PURE__ */ new Set();
608
790
  for (const [key, indexedFile] of s.fileIndex) {
@@ -634,10 +816,11 @@ function ensureCoreLoaded(s) {
634
816
  }
635
817
  }
636
818
  }
637
- s.coreLoaded = true;
638
819
  }
639
820
  function getValidator(toolName, direction, version = import_version.ADCP_VERSION) {
640
- const s = ensureInit(version);
821
+ return validatorForState(ensureInit(version), toolName, direction);
822
+ }
823
+ function validatorForState(s, toolName, direction) {
641
824
  const cacheKey = `${toolName}::${direction}`;
642
825
  const cached = s.validators.get(cacheKey);
643
826
  if (cached) return cached;
@@ -649,6 +832,12 @@ function getValidator(toolName, direction, version = import_version.ADCP_VERSION
649
832
  const rawSchema = loadJson(file);
650
833
  const prepared = fromBundled ? stripNestedIds(rawSchema) : rawSchema;
651
834
  const envelope = direction === "request" ? prepared : acceptEnvelopeOnClosedResponseRoot(prepared, s.root);
835
+ if (fromBundled && s.bundledCache) {
836
+ const resolved = resolveBundledValidatorWithCache(s, s.bundledCache, cacheKey, envelope);
837
+ s.validators.set(cacheKey, resolved);
838
+ validatorDiagnosticOrigins.set(resolved, s.bundledDiagnosticOrigins);
839
+ return resolved;
840
+ }
652
841
  const schema = fromBundled ? compactSchemaForValidation(envelope) : envelope;
653
842
  const ajv = fromBundled ? s.bundledAjv : s.ajv;
654
843
  const existing = typeof schema.$id === "string" ? ajv.getSchema(schema.$id) : void 0;
@@ -657,6 +846,265 @@ function getValidator(toolName, direction, version = import_version.ADCP_VERSION
657
846
  validatorDiagnosticOrigins.set(compiled, fromBundled ? s.bundledDiagnosticOrigins : s.diagnosticOrigins);
658
847
  return compiled;
659
848
  }
849
+ function definesToolRequest(toolName, version = import_version.ADCP_VERSION) {
850
+ const s = ensureInit(version);
851
+ const key = `${toolName}::request`;
852
+ if (s.validators.has(key) || s.cachedCompiles?.has(key)) return true;
853
+ const indexedFile = s.fileIndex.get(key);
854
+ if (!indexedFile) return false;
855
+ const modular = !runtimeToolSchemaFile(s, indexedFile, "request").includes(`${import_path.default.sep}bundled${import_path.default.sep}`);
856
+ const cache = modular ? openLoaderDataCache() : void 0;
857
+ const digest = cache ? stateContentDigest(s) : void 0;
858
+ if (!cache || digest === void 0 || s.coreLoadFailed) return compilesForState(s, toolName, "request");
859
+ const { validatorCacheKey } = require('./validator-cache.js');
860
+ const outcomeKey = validatorCacheKey([
861
+ "modular-request-compiles",
862
+ ...bundledValidatorCacheStaticKey(),
863
+ process.versions.v8,
864
+ process.versions.unicode ?? null,
865
+ s.version,
866
+ digest,
867
+ toolName
868
+ ]);
869
+ if (cache.readData(outcomeKey)?.compiles === true) {
870
+ (s.cachedCompiles ??= /* @__PURE__ */ new Set()).add(key);
871
+ (s.deferredCompiles ??= /* @__PURE__ */ new Set()).add(key);
872
+ return true;
873
+ }
874
+ const compiles = compilesForState(s, toolName, "request");
875
+ if (compiles && !s.coreLoadFailed && contentUnchangedSinceDigest(s)) {
876
+ cache.writeData(outcomeKey, { compiles: true });
877
+ }
878
+ return compiles;
879
+ }
880
+ function compilesForState(s, toolName, direction) {
881
+ try {
882
+ return validatorForState(s, toolName, direction) !== void 0;
883
+ } catch {
884
+ return false;
885
+ }
886
+ }
887
+ function flushDeferredCompiles(s) {
888
+ const deferred = s.deferredCompiles;
889
+ if (!deferred) return;
890
+ s.deferredCompiles = void 0;
891
+ for (const key of deferred) {
892
+ if (!s.validators.has(key)) compilesForState(s, key.slice(0, -"::request".length), "request");
893
+ }
894
+ }
895
+ function stateContentDigest(s) {
896
+ if (s.contentDigest === void 0) s.contentDigest = s.coreLoaded ? null : rootContentDigest(s);
897
+ return s.contentDigest ?? void 0;
898
+ }
899
+ function contentUnchangedSinceDigest(s) {
900
+ if (!s.contentDigestChecked) {
901
+ s.contentDigestChecked = true;
902
+ if (rootContentDigest(s) !== s.contentDigest) s.contentDigest = null;
903
+ }
904
+ return typeof s.contentDigest === "string";
905
+ }
906
+ function rootContentDigest(s) {
907
+ const files = /* @__PURE__ */ new Set();
908
+ for (const entry of (0, import_fs.readdirSync)(s.root, { withFileTypes: true })) {
909
+ if (entry.isDirectory()) {
910
+ if (isRuntimeSchemaDirectory(entry.name)) {
911
+ for (const file of walkJsonFiles(import_path.default.join(s.root, entry.name))) files.add(file);
912
+ }
913
+ } else if (entry.isFile() && entry.name.endsWith(".json")) {
914
+ files.add(import_path.default.join(s.root, entry.name));
915
+ }
916
+ }
917
+ for (const indexedFile of s.fileIndex.values()) files.add(authoredToolSchemaFile(s, indexedFile));
918
+ const byPath = (a, b) => a < b ? -1 : a > b ? 1 : 0;
919
+ const hash = (0, import_node_crypto.createHash)("sha256");
920
+ for (const [key, file] of [...s.fileIndex].sort(([a], [b]) => byPath(a, b))) {
921
+ hash.update(`index\0${key}\0${import_path.default.relative(s.root, file)}\0`);
922
+ }
923
+ for (const file of [...files].sort(byPath)) {
924
+ hash.update(`file\0${import_path.default.relative(s.root, file)}\0`);
925
+ hash.update(documentBytes(file));
926
+ hash.update("\0");
927
+ }
928
+ return hash.digest("hex");
929
+ }
930
+ function documentBytes(file) {
931
+ try {
932
+ return (0, import_fs.readFileSync)(file);
933
+ } catch (error) {
934
+ if (file.includes(`${import_path.default.sep}bundled${import_path.default.sep}`)) {
935
+ try {
936
+ const entry = (0, import_bundled_schema_store.loadBundledSchemaFile)(file);
937
+ if (entry) return `archive\0${JSON.stringify(entry)}`;
938
+ } catch {
939
+ }
940
+ }
941
+ return `unreadable\0${error.code ?? ""}`;
942
+ }
943
+ }
944
+ const VALIDATOR_CACHE_CODE_FILES = [
945
+ "schema-loader",
946
+ "compact-schema",
947
+ "schema-diagnostic-origins",
948
+ "bundled-schema-store",
949
+ "validator-cache"
950
+ ];
951
+ const BUNDLED_AJV_KEY = {
952
+ inlineRefs: false,
953
+ strict: false,
954
+ allErrors: true,
955
+ allowUnionTypes: true,
956
+ formats: "ajv-formats"
957
+ };
958
+ let validatorCacheStaticKey;
959
+ function openBundledValidatorCache() {
960
+ const dir = validatorCacheDir();
961
+ if (dir === void 0) return void 0;
962
+ const { openValidatorCache } = require('./validator-cache.js');
963
+ const cache = openValidatorCache(dir, import_path.default.join(__dirname, "schema-loader.js"));
964
+ return cache ? { cache, compileLog: void 0, byId: /* @__PURE__ */ new Map() } : void 0;
965
+ }
966
+ function validatorCacheDir() {
967
+ const dir = process.env.ADCP_VALIDATOR_CACHE_DIR;
968
+ return dir && import_path.default.isAbsolute(dir) ? dir : void 0;
969
+ }
970
+ let loaderDataCache;
971
+ function openLoaderDataCache() {
972
+ const dir = validatorCacheDir();
973
+ if (dir === void 0) return void 0;
974
+ if (loaderDataCache?.dir !== dir) {
975
+ const { openValidatorCache } = require('./validator-cache.js');
976
+ loaderDataCache = { dir, cache: openValidatorCache(dir, import_path.default.join(__dirname, "schema-loader.js")) };
977
+ }
978
+ return loaderDataCache.cache;
979
+ }
980
+ function bundledValidatorCacheStaticKey() {
981
+ if (validatorCacheStaticKey) return validatorCacheStaticKey;
982
+ const { filesDigest } = require('./validator-cache.js');
983
+ const loaderRequire = (0, import_module.createRequire)(import_path.default.join(__dirname, "schema-loader.js"));
984
+ const packageVersion = (name, from) => {
985
+ try {
986
+ return from(`${name}/package.json`).version ?? null;
987
+ } catch {
988
+ return null;
989
+ }
990
+ };
991
+ let ajvRequire = loaderRequire;
992
+ try {
993
+ ajvRequire = (0, import_module.createRequire)(loaderRequire.resolve("ajv"));
994
+ } catch {
995
+ }
996
+ validatorCacheStaticKey = [
997
+ import_version.LIBRARY_VERSION,
998
+ filesDigest(
999
+ VALIDATOR_CACHE_CODE_FILES.flatMap((name) => [`${name}.js`, `${name}.mjs`]).map((file) => import_path.default.join(__dirname, file))
1000
+ ),
1001
+ packageVersion("ajv", loaderRequire),
1002
+ packageVersion("ajv-formats", loaderRequire),
1003
+ packageVersion("fast-uri", ajvRequire),
1004
+ packageVersion("json-schema-traverse", ajvRequire),
1005
+ packageVersion("fast-deep-equal", ajvRequire),
1006
+ BUNDLED_AJV_KEY
1007
+ ];
1008
+ return validatorCacheStaticKey;
1009
+ }
1010
+ function compileBundledRecorded(s, bc, schema, wantModule) {
1011
+ const log = [];
1012
+ bc.compileLog = log;
1013
+ let compiled;
1014
+ try {
1015
+ compiled = s.bundledAjv.compile(schema);
1016
+ } finally {
1017
+ bc.compileLog = void 0;
1018
+ }
1019
+ let moduleCode;
1020
+ try {
1021
+ let exact = wantModule && !compiled.$async && log.length > 0;
1022
+ for (const entry of log) {
1023
+ const fn = entry.env.validate;
1024
+ const validateCode = fn?.source?.validateCode;
1025
+ if (!fn || typeof validateCode !== "string" || !entry.source.endsWith(validateCode)) {
1026
+ exact = false;
1027
+ continue;
1028
+ }
1029
+ const prefixLength = entry.source.length - validateCode.length;
1030
+ if (!entry.source.slice(0, prefixLength).endsWith("return ") || entry.output.slice(0, prefixLength) !== entry.source.slice(0, prefixLength)) {
1031
+ exact = false;
1032
+ continue;
1033
+ }
1034
+ fn.source.validateCode = entry.output.slice(prefixLength);
1035
+ }
1036
+ if (exact) {
1037
+ const standaloneCode = require("ajv/dist/standalone").default;
1038
+ const code = standaloneCode(s.bundledAjv, compiled);
1039
+ if (!code.includes("urn:adcp:schema-origin:")) moduleCode = code;
1040
+ }
1041
+ } catch {
1042
+ moduleCode = void 0;
1043
+ } finally {
1044
+ for (const entry of log) delete entry.env.validate?.source;
1045
+ }
1046
+ return { compiled, ...moduleCode !== void 0 && { moduleCode } };
1047
+ }
1048
+ function resolveBundledValidatorWithCache(s, bc, toolKey, envelope) {
1049
+ const id = typeof envelope.$id === "string" ? envelope.$id : void 0;
1050
+ const known = id !== void 0 ? bc.byId.get(id) : void 0;
1051
+ if (known) return known;
1052
+ const { validatorCacheKey } = require('./validator-cache.js');
1053
+ const key = validatorCacheKey([...bundledValidatorCacheStaticKey(), s.version, toolKey, envelope]);
1054
+ const entry = bc.cache.read(key);
1055
+ if (entry) {
1056
+ const fn = entry.validate;
1057
+ let compacted;
1058
+ const compactedSchema = () => compacted ??= compactSchemaForValidation(envelope);
1059
+ const materialize = () => {
1060
+ pendingDiagnosticOrigins.delete(fn);
1061
+ try {
1062
+ const schema2 = compactedSchema();
1063
+ const existing2 = typeof schema2.$id === "string" ? s.bundledAjv.getSchema(schema2.$id) : void 0;
1064
+ return existing2 ?? compileBundledRecorded(s, bc, schema2, false).compiled;
1065
+ } catch {
1066
+ return void 0;
1067
+ }
1068
+ };
1069
+ pendingDiagnosticOrigins.set(fn, () => void materialize());
1070
+ Object.defineProperty(fn, "schema", {
1071
+ configurable: true,
1072
+ enumerable: true,
1073
+ get() {
1074
+ const value = compactedSchema();
1075
+ Object.defineProperty(fn, "schema", { value, writable: true, enumerable: true, configurable: true });
1076
+ return value;
1077
+ }
1078
+ });
1079
+ Object.defineProperty(fn, "schemaEnv", {
1080
+ configurable: true,
1081
+ enumerable: true,
1082
+ get() {
1083
+ const live = (pendingDiagnosticOrigins.has(fn) ? materialize() : void 0) ?? (typeof compactedSchema().$id === "string" ? s.bundledAjv.getSchema(compactedSchema().$id) : void 0);
1084
+ const value = live?.schemaEnv;
1085
+ Object.defineProperty(fn, "schemaEnv", { value, writable: true, enumerable: true, configurable: true });
1086
+ return value;
1087
+ }
1088
+ });
1089
+ cachedValidatorRootSchemaIds.set(fn, entry.rootSchemaId);
1090
+ if (id !== void 0) bc.byId.set(id, fn);
1091
+ return fn;
1092
+ }
1093
+ const schema = compactSchemaForValidation(envelope);
1094
+ const existing = typeof schema.$id === "string" ? s.bundledAjv.getSchema(schema.$id) : void 0;
1095
+ let compiled;
1096
+ if (existing) {
1097
+ compiled = existing;
1098
+ } else {
1099
+ const result = compileBundledRecorded(s, bc, schema, true);
1100
+ compiled = result.compiled;
1101
+ if (result.moduleCode !== void 0) {
1102
+ bc.cache.write(key, result.moduleCode, typeof schema.$id === "string" ? schema.$id : void 0);
1103
+ }
1104
+ }
1105
+ if (id !== void 0) bc.byId.set(id, compiled);
1106
+ return compiled;
1107
+ }
660
1108
  function authoredToolSchemaFile(state, indexedFile) {
661
1109
  const bundledRoot = import_path.default.join(state.root, "bundled");
662
1110
  const relative = import_path.default.relative(bundledRoot, indexedFile);
@@ -899,6 +1347,7 @@ function listValidatorKeys(version = import_version.ADCP_VERSION) {
899
1347
  }
900
1348
  function getRegisteredSchemaIds(version = import_version.ADCP_VERSION) {
901
1349
  const s = ensureInit(version);
1350
+ flushDeferredCompiles(s);
902
1351
  const registry = s.ajv.schemas;
903
1352
  const bundledRegistry = s.bundledAjv.schemas;
904
1353
  return [.../* @__PURE__ */ new Set([...Object.keys(registry ?? {}), ...Object.keys(bundledRegistry ?? {})])];
@@ -941,10 +1390,12 @@ function withServedReleaseSchemaRoots(roots, fn) {
941
1390
  const memoKey = `${version}\0${root}`;
942
1391
  let aliases = servedReleaseRootAliases.get(memoKey);
943
1392
  if (!aliases) {
944
- if (!hasSchemaRootShape(root)) {
1393
+ const reads = newRootCheckReads(root);
1394
+ if (!hasSchemaRootShape(root, reads)) {
945
1395
  throw new Error(`Served-release AdCP schema root for version "${version}" not found or empty at ${root}`);
946
1396
  }
947
- aliases = assertSchemaRootMatchesVersion(version, root);
1397
+ aliases = assertSchemaRootMatchesVersion(version, root, reads);
1398
+ persistRootCheck(reads);
948
1399
  servedReleaseRootAliases.set(memoKey, aliases);
949
1400
  }
950
1401
  const conflict = entries.find((entry) => entry.root !== root && [...aliases].some((alias) => entry.aliases.has(alias)));
@@ -1101,6 +1552,8 @@ function _resetValidationLoader(version) {
1101
1552
  if (version === void 0) {
1102
1553
  states.clear();
1103
1554
  schemaRefValidators.clear();
1555
+ epochRootFingerprints.clear();
1556
+ rootDocumentIdentityCache().clear();
1104
1557
  keywordCacheGeneration++;
1105
1558
  } else {
1106
1559
  clearStatesForBundle(resolveBundleKey(version));
@@ -1279,6 +1732,7 @@ function cloneJsonValue(value) {
1279
1732
  acceptEnvelopeOnClosedResponseRoot,
1280
1733
  acceptEnvelopeOnClosedResponseRootForVersion,
1281
1734
  bindIdentity33SchemaScope,
1735
+ definesToolRequest,
1282
1736
  getActiveSchemaArtifactLocation,
1283
1737
  getCanonicalToolValidatorForVersion,
1284
1738
  getMcpProfileInputSchema,
@@ -1294,6 +1748,7 @@ function cloneJsonValue(value) {
1294
1748
  getToolSchemaDocument,
1295
1749
  getValidator,
1296
1750
  getValidatorDiagnosticOrigin,
1751
+ getValidatorRootSchemaId,
1297
1752
  hasSchemaBundle,
1298
1753
  isExternalSchemaRootActive,
1299
1754
  isIdentity33SchemaScope,