@kya-os/checkpoint-shared 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,11 +2,8 @@
2
2
 
3
3
  var providerRegistry = require('@kya-os/provider-registry');
4
4
  var yaml = require('js-yaml');
5
- var canonicalize = require('canonicalize');
6
- var ed25519 = require('@noble/ed25519');
7
- var base58 = require('multiformats/bases/base58');
8
-
9
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
5
+ var sha2_js = require('@noble/hashes/sha2.js');
6
+ var utils_js = require('@noble/hashes/utils.js');
10
7
 
11
8
  function _interopNamespace(e) {
12
9
  if (e && e.__esModule) return e;
@@ -27,7 +24,6 @@ function _interopNamespace(e) {
27
24
  }
28
25
 
29
26
  var yaml__namespace = /*#__PURE__*/_interopNamespace(yaml);
30
- var canonicalize__default = /*#__PURE__*/_interopDefault(canonicalize);
31
27
 
32
28
  var __defProp = Object.defineProperty;
33
29
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -111,7 +107,7 @@ var require_merged_rules = __commonJS({
111
107
  lastUpdated: "2025-01-10T00:00:00Z"
112
108
  }
113
109
  ],
114
- hash: "58f3ec67889f255c78bc571031af8dca3d9e2b6975ad42803758b2342516070b"
110
+ hash: "01eccdc0313dec99ffa8128c3e4c20818a9e58cfb0c0b41f428d0be5b4dbe5bf"
115
111
  },
116
112
  rules: {
117
113
  userAgents: {
@@ -386,9 +382,15 @@ var require_merged_rules = __commonJS({
386
382
  description: "Perplexity AI assistant (Perplexity-User, Perplexity/N, Comet browser)",
387
383
  category: "ai_assistant"
388
384
  },
385
+ amazon_quick_crawler: {
386
+ patterns: ["Amazon-Quick", "aws-quick"],
387
+ confidence: 0.95,
388
+ category: "scraper",
389
+ description: "Amazon Quick web crawler (formerly Amazon Q)"
390
+ },
389
391
  amazon_q: {
390
392
  patterns: ["NovaAct", "Amazon-Q"],
391
- confidence: 0.95,
393
+ confidence: 0.85,
392
394
  description: "Amazon Q AI assistant",
393
395
  category: "ai_assistant"
394
396
  },
@@ -5041,9 +5043,11 @@ var ReasoningStepSchema = external_exports.object({
5041
5043
  });
5042
5044
  var TraceStepSchema = external_exports.object({
5043
5045
  /**
5044
- * Stable stage identifier. Canonical names: `"detection"` | `"identity"`
5045
- * | `"scope"` | `"reputation"` | `"policy"`. Mirrors `TraceStep::name`
5046
- * on the Rust side.
5046
+ * Stable stage identifier. Canonical names: `"detection"` (PlainHttp) or
5047
+ * `"identity"` | `"signature"` | `"revocation"` | `"expiration"` |
5048
+ * `"scope"` | `"reputation"` | `"policy"` (MCP-I's 7-stage pipeline).
5049
+ * Not a union on the wire — new step names are non-breaking. Mirrors
5050
+ * `TraceStep::name` on the Rust side.
5047
5051
  */
5048
5052
  name: external_exports.string(),
5049
5053
  /**
@@ -5138,6 +5142,11 @@ var DetectionDetailSchema = external_exports.object({
5138
5142
  "kyaos_handshake",
5139
5143
  "kya-http",
5140
5144
  "kya-http-delegated",
5145
+ // Tier-1 RFC 9421 (Web Bot Auth) verification. The engine emits this
5146
+ // on a verified HTTP Message Signature (api.rs Tier-1 path); without
5147
+ // it here, Zod-validating a Tier-1 verdict rejects a legitimately
5148
+ // signature-verified agent.
5149
+ "tier1_rfc9421",
5141
5150
  "none",
5142
5151
  "error"
5143
5152
  ]).optional(),
@@ -5408,6 +5417,95 @@ function normalizeConfidence(value, context) {
5408
5417
  }
5409
5418
  return Math.max(0, Math.min(value, 1));
5410
5419
  }
5420
+ var ENTROPY_CONFIDENCE_FLOOR = 0.02;
5421
+ var ENTROPY_CONFIDENCE_CEILING = 0.98;
5422
+ var CONFIDENCE_SCALE_BITS = 8;
5423
+ var GROUP_DISCOUNT = 0.5;
5424
+ var PLANE_DISCOUNT = 0.75;
5425
+ var TIER_INFO_BITS = {
5426
+ high: 6,
5427
+ medium: 3,
5428
+ low: 1
5429
+ };
5430
+ var MIN_COINCIDENCE_PROBABILITY = 1e-6;
5431
+ function signalInfoBits(signal) {
5432
+ if (signal.mode === "never") return 0;
5433
+ if (signal.u !== null && Number.isFinite(signal.u)) {
5434
+ const u = Math.min(Math.max(signal.u, MIN_COINCIDENCE_PROBABILITY), 1);
5435
+ return -Math.log2(u);
5436
+ }
5437
+ return TIER_INFO_BITS[signal.tier] ?? 0;
5438
+ }
5439
+ function sortedGeometricSum(values, discount) {
5440
+ return [...values].sort((a, b) => b - a).reduce((sum, value, rank) => sum + value * discount ** rank, 0);
5441
+ }
5442
+ function computeEntropyConfidence(observed) {
5443
+ const bitsByPlaneAndGroup = /* @__PURE__ */ new Map();
5444
+ for (const signal of observed) {
5445
+ const bits = signalInfoBits(signal);
5446
+ if (bits <= 0) continue;
5447
+ let groups = bitsByPlaneAndGroup.get(signal.plane);
5448
+ if (!groups) {
5449
+ groups = /* @__PURE__ */ new Map();
5450
+ bitsByPlaneAndGroup.set(signal.plane, groups);
5451
+ }
5452
+ const bitsInGroup = groups.get(signal.group);
5453
+ if (bitsInGroup) {
5454
+ bitsInGroup.push(bits);
5455
+ } else {
5456
+ groups.set(signal.group, [bits]);
5457
+ }
5458
+ }
5459
+ let totalBits = 0;
5460
+ for (const groups of bitsByPlaneAndGroup.values()) {
5461
+ const groupContributions = Array.from(
5462
+ groups.values(),
5463
+ (bitsInGroup) => sortedGeometricSum(bitsInGroup, GROUP_DISCOUNT)
5464
+ );
5465
+ totalBits += sortedGeometricSum(groupContributions, PLANE_DISCOUNT);
5466
+ }
5467
+ return ENTROPY_CONFIDENCE_FLOOR + (ENTROPY_CONFIDENCE_CEILING - ENTROPY_CONFIDENCE_FLOOR) * (1 - Math.exp(-totalBits / CONFIDENCE_SCALE_BITS));
5468
+ }
5469
+
5470
+ // src/core/verdict-evidence.ts
5471
+ var VerdictEvidenceSchema = external_exports.object({
5472
+ signal: external_exports.string(),
5473
+ plane: DetectionSignalSchema.shape.signalType,
5474
+ weight: external_exports.number().min(0).max(1),
5475
+ probabilityContribution: external_exports.number().min(0).max(1)
5476
+ });
5477
+ function signalContribution(signal) {
5478
+ return signal.weight * (signal.confidence / 100);
5479
+ }
5480
+ function buildVerdictEvidence(signals) {
5481
+ if (!signals || signals.length === 0) return [];
5482
+ const entries = [];
5483
+ for (const raw of signals) {
5484
+ const parsed = DetectionSignalSchema.safeParse(raw);
5485
+ if (!parsed.success) continue;
5486
+ const signal = parsed.data;
5487
+ entries.push({
5488
+ signal: signal.source,
5489
+ plane: signal.signalType,
5490
+ weight: signal.weight,
5491
+ probabilityContribution: signalContribution(signal)
5492
+ });
5493
+ }
5494
+ entries.sort((a, b) => {
5495
+ if (a.plane !== b.plane) return a.plane < b.plane ? -1 : 1;
5496
+ if (a.signal !== b.signal) return a.signal < b.signal ? -1 : 1;
5497
+ return b.probabilityContribution - a.probabilityContribution;
5498
+ });
5499
+ return entries;
5500
+ }
5501
+ var UNCALIBRATED_NOISY_OR_PRIOR = 0.1;
5502
+ function reconstructConfidenceFromEvidence(evidence) {
5503
+ const probabilityAbsent = evidence.reduce(
5504
+ (acc, entry) => acc * (1 - entry.probabilityContribution),
5505
+ 1 - UNCALIBRATED_NOISY_OR_PRIOR
5506
+ );
5507
+ return (1 - probabilityAbsent) * 100;
5508
+ }
5411
5509
 
5412
5510
  // src/config/shield.ts
5413
5511
  var CacheConfigSchema = external_exports.object({
@@ -5659,7 +5757,16 @@ var KNOWN_AGENT_PATTERNS = [
5659
5757
  type: "anthropic",
5660
5758
  name: "Anthropic-AI Crawler",
5661
5759
  patterns: ["anthropic-ai"],
5662
- confidence: 0.9,
5760
+ // 0.95, matching every other single-exact-token vendor crawler
5761
+ // (openai-gptbot, anthropic-claudebot, meta-externalagent,
5762
+ // gemini-deep-research, deepseek-bot). Previously 0.9, tied with
5763
+ // anthropic-generic below — classifyByUserAgent picks the first
5764
+ // match on a confidence tie (strict `>`, no stable order), so an
5765
+ // 'anthropic-ai' UA could resolve to either row depending on DB
5766
+ // iteration order, reopening the exact misclassification this
5767
+ // taxonomy split retires the token to fix. Caught by Bugbot on
5768
+ // #4172 once the migration landing this row made the tie live.
5769
+ confidence: 0.95,
5663
5770
  category: "scraper",
5664
5771
  isLegitimate: true
5665
5772
  },
@@ -5736,7 +5843,8 @@ var KNOWN_AGENT_PATTERNS = [
5736
5843
  },
5737
5844
  {
5738
5845
  // ORDERING NOTE: `gemini-deep-research` MUST appear BEFORE
5739
- // `google-bard` so the more-specific 'Gemini-Deep-Research'
5846
+ // `gemini` (renamed from `google-bard`, migration 0201) so the
5847
+ // more-specific 'Gemini-Deep-Research'
5740
5848
  // pattern wins under the engine's first-match-wins iteration over
5741
5849
  // AI_AGENT_PATTERNS. The legacy YAML→Rust output collapsed all
5742
5850
  // Google patterns under a single "Google AI" name with identical
@@ -5755,9 +5863,22 @@ var KNOWN_AGENT_PATTERNS = [
5755
5863
  isLegitimate: true
5756
5864
  },
5757
5865
  {
5758
- id: "google-bard",
5866
+ // Renamed from 'google-bard' (migration 0201, P4 follow-up). The prior
5867
+ // fix (Fix-Gemini-Mislabeled-As-Google-Bard-1) deliberately left the id
5868
+ // as `google-bard` and only renamed the human-facing `name` below,
5869
+ // because the id is the stable codegen/stored key (Rust pattern ids via
5870
+ // build.rs -> known-agent-patterns.json, the agent_types.name DB row,
5871
+ // `agent-classification.service.ts`'s directMappings). This PR does the
5872
+ // full id rename instead: verified zero live project/org policies
5873
+ // (cedar_policy_text, allowed/denied agent-type lists) reference the
5874
+ // 'google-bard' slug (checked against a Neon branch off prod main,
5875
+ // 2026-08-14), so the earlier narrower fix's risk no longer applies.
5876
+ // `agent_types.agent_did` already reads
5877
+ // `did:web:knowthat.ai:agents:gemini` — this id rename just catches the
5878
+ // codegen/DB slug up to what the DID already assumed.
5879
+ id: "gemini",
5759
5880
  type: "google",
5760
- name: "Google Bard",
5881
+ name: "Google Gemini",
5761
5882
  // Engine-Pattern-Codegen-Retirement-1 corrections:
5762
5883
  // - REMOVED `Google-InspectionTool` from this entry. The legacy
5763
5884
  // YAML→Rust pipeline classified Google-InspectionTool as a
@@ -5770,17 +5891,45 @@ var KNOWN_AGENT_PATTERNS = [
5770
5891
  // YAML had it under Google AI) and `GoogleAgent-Mariner`
5771
5892
  // (Google's browser-controlling agent product) — both were in
5772
5893
  // the retired pipeline, never in TS.
5773
- // - The broad 'gemini' pattern below shadows narrower Gemini-*
5774
- // UAs under first-match-wins. The Gemini-Deep-Research entry
5775
- // above must stay ordered first to avoid being shadowed.
5894
+ //
5895
+ // Engine-Pattern-Codegen-Retirement-2 (this PR, Bugbot #ae22713a and
5896
+ // #6984df6d): bare 'gemini'/'palm' matched `GeminiiOS` (Google's own
5897
+ // Gemini app rendering a page in its in-app webview — a HUMAN, not an
5898
+ // agent) as a plain unanchored substring — `build.rs` emits every
5899
+ // pattern here into `format!("(?i){pattern}")` with no escaping and no
5900
+ // boundary, so a literal `'gemini'` compiles to `Regex::new("(?i)gemini")`,
5901
+ // which `.is_match()`-style scanning matches anywhere. That reopened,
5902
+ // one layer down, the exact hole migration 0208 closed on the
5903
+ // DB-side `classifyByUserAgent` path: this PR's own `lookupAgentDid`
5904
+ // fix matches the WASM engine's emitted `name` ('Google Gemini')
5905
+ // against `agent_types.displayName` for the enforce/pixel-track
5906
+ // routes, which run no TS classifier and never touch
5907
+ // `classifyByUserAgent` at all — so `GeminiiOS` could still reach the
5908
+ // live `gemini` DID via this second, engine-only path.
5909
+ //
5910
+ // First attempt was an outright removal, which closed the hole but
5911
+ // also dropped genuine coverage: a bare `Gemini/1.0` or
5912
+ // `Google-Gemini/1.0` UA carrying no specific model suffix no longer
5913
+ // matched anything (caught by Bugbot #6984df6d's follow-up review,
5914
+ // and independently by 4 apps/web unit tests asserting exactly that
5915
+ // coverage — see git history). Word-boundary anchors close the false
5916
+ // positive AND keep the coverage: `\bgemini\b` matches `Gemini/1.0`
5917
+ // and `Google-Gemini/1.0` (boundary before the leading `G`/after `-`,
5918
+ // and before the trailing `/`) but NOT `GeminiiOS` (no boundary
5919
+ // between the two `i`s — both are word characters). Same shape for
5920
+ // `\bpalm\b` vs `palm2` (own explicit token, digit is a word
5921
+ // character so no double-match) vs a hypothetical `PalmOS`-style
5922
+ // collision. TS string literals need `\\b` (double backslash) to
5923
+ // produce a literal `\b` in the resulting string — `\b` alone is the
5924
+ // JS backspace escape, not a regex boundary.
5776
5925
  patterns: [
5777
5926
  "Bard",
5778
- "gemini",
5927
+ "\\bgemini\\b",
5779
5928
  "gemini-pro",
5780
5929
  "gemini-1.5",
5781
5930
  "gemini-1.5-pro",
5782
5931
  "gemini-ultra",
5783
- "palm",
5932
+ "\\bpalm\\b",
5784
5933
  "palm2",
5785
5934
  "LaMDA",
5786
5935
  "GoogleAgent-Mariner"
@@ -6065,15 +6214,50 @@ var KNOWN_AGENT_PATTERNS = [
6065
6214
  category: "scraper",
6066
6215
  isLegitimate: true
6067
6216
  },
6217
+ // Amazon Quick — AWS's rendering web crawler (formerly launched as part
6218
+ // of the "Amazon Q" family, since renamed; docs.aws.amazon.com/quick).
6219
+ // UA convention is `amazon-Quick-on-behalf-of-<id>` / AWS's own
6220
+ // documented `aws-quick-on-behalf-of-<UUID>`. Declared BEFORE
6221
+ // `amazon-q` below: the Rust engine's AI_AGENT_PATTERNS match is
6222
+ // first-match-wins in TS source order (see patterns.rs
6223
+ // `analyze_user_agent`), and 'Amazon-Quick' is a superstring of
6224
+ // 'Amazon-Q' below, so the more specific pattern must be tried first
6225
+ // there. `classifyByUserAgent` (TS/DB path) doesn't use source order —
6226
+ // it tie-breaks on confidence — so this row's confidence must also
6227
+ // stay strictly above `amazon-q`'s (mirrors the anthropic-ai-crawler /
6228
+ // anthropic-generic split: specific crawler token > broad label).
6229
+ // is_legitimate: AWS's docs describe it as a JS-rendering, non-
6230
+ // interactive crawler (no simulated user interaction) — the taxonomy's
6231
+ // `scraper` bucket, not `ai_assistant` (real-time human-driven use).
6232
+ {
6233
+ id: "amazon-quick",
6234
+ type: "amazon",
6235
+ name: "Amazon Quick",
6236
+ patterns: ["Amazon-Quick", "aws-quick"],
6237
+ confidence: 0.95,
6238
+ category: "scraper",
6239
+ isLegitimate: true
6240
+ },
6068
6241
  // Amazon Q + NovaAct — Amazon's AI assistant product family.
6069
6242
  // NovaAct is the AWS-branded browser-controlling agent (parallel to
6070
6243
  // Anthropic's Claude-Code, Google's GoogleAgent-Mariner).
6244
+ //
6245
+ // Confidence intentionally below `amazon-quick` above, by MORE than the
6246
+ // TS/DB path's max multi-pattern bonus (+5 for 2+ pattern matches — see
6247
+ // calculateConfidence in agent-classification.service.ts): 0.85 not 0.90.
6248
+ // A UA containing both of amazon-q's patterns ('Amazon-Q' — substring-
6249
+ // matched by 'Amazon-Quick' — and 'NovaAct', plausible on the same
6250
+ // product family's browser-driving traffic) would score 90 + 5 = 95,
6251
+ // tying amazon-quick's flat 95 and recreating the exact order-dependent
6252
+ // tie this split exists to eliminate (own regression test:
6253
+ // agent-classification-amazon-quick-crawler-tie.test.ts). At 0.85 the
6254
+ // bonus tops out at 85 + 5 = 90, still short of amazon-quick's 95.
6071
6255
  {
6072
6256
  id: "amazon-q",
6073
6257
  type: "amazon",
6074
6258
  name: "Amazon Q",
6075
6259
  patterns: ["Amazon-Q", "NovaAct"],
6076
- confidence: 0.95,
6260
+ confidence: 0.85,
6077
6261
  category: "ai_assistant",
6078
6262
  isLegitimate: true
6079
6263
  },
@@ -6252,21 +6436,21 @@ var TRADITIONAL_BOT_PATTERNS = [
6252
6436
  {
6253
6437
  id: "googlebot",
6254
6438
  type: "search_engine",
6255
- name: "GoogleBot",
6439
+ name: "Googlebot",
6256
6440
  patterns: ["googlebot", "google-structured-data-testing-tool"],
6257
6441
  confidence: 0.95
6258
6442
  },
6259
6443
  {
6260
6444
  id: "bingbot",
6261
6445
  type: "search_engine",
6262
- name: "BingBot",
6446
+ name: "Bingbot",
6263
6447
  patterns: ["bingbot", "bingpreview", "msnbot"],
6264
6448
  confidence: 0.95
6265
6449
  },
6266
6450
  {
6267
6451
  id: "yandexbot",
6268
6452
  type: "search_engine",
6269
- name: "YandexBot",
6453
+ name: "Yandexbot",
6270
6454
  patterns: ["yandexbot", "yandex"],
6271
6455
  confidence: 0.9
6272
6456
  },
@@ -6274,14 +6458,14 @@ var TRADITIONAL_BOT_PATTERNS = [
6274
6458
  {
6275
6459
  id: "facebook",
6276
6460
  type: "social_media",
6277
- name: "Facebook",
6461
+ name: "Meta Crawler",
6278
6462
  patterns: ["facebookexternalhit", "facebookcatalog", "Meta-ExternalAgent"],
6279
6463
  confidence: 0.9
6280
6464
  },
6281
6465
  {
6282
6466
  id: "twitter",
6283
6467
  type: "social_media",
6284
- name: "Twitter",
6468
+ name: "Twitterbot",
6285
6469
  patterns: ["twitterbot"],
6286
6470
  confidence: 0.9
6287
6471
  },
@@ -6296,7 +6480,7 @@ var TRADITIONAL_BOT_PATTERNS = [
6296
6480
  {
6297
6481
  id: "ahrefs",
6298
6482
  type: "seo_tool",
6299
- name: "Ahrefs",
6483
+ name: "Ahrefsbot",
6300
6484
  patterns: ["ahrefsbot"],
6301
6485
  confidence: 0.85
6302
6486
  },
@@ -6304,7 +6488,7 @@ var TRADITIONAL_BOT_PATTERNS = [
6304
6488
  {
6305
6489
  id: "generic-crawler",
6306
6490
  type: "crawler",
6307
- name: "Generic Crawler",
6491
+ name: "Generic Bot",
6308
6492
  patterns: ["crawler", "spider", "bot/"],
6309
6493
  confidence: 0.6
6310
6494
  },
@@ -6512,6 +6696,9 @@ function getEnvVar(key) {
6512
6696
  return process.env[key] || DEFAULT_ENV_VARS[key];
6513
6697
  }
6514
6698
 
6699
+ // src/constants/delegation.ts
6700
+ var ATTESTED_BEARER_MAX_TTL_SECONDS = 900;
6701
+
6515
6702
  // src/constants/errors.ts
6516
6703
  var ERROR_CATEGORIES = {
6517
6704
  AUTH: "AUTH",
@@ -7092,12 +7279,7 @@ var USER_AGENT_PATTERNS = {
7092
7279
  UPTIMEROBOT: /UptimeRobot/i,
7093
7280
  PINGDOM: /Pingdom/i,
7094
7281
  NEWRELIC: /NewRelicPinger/i,
7095
- DATADOG: /Datadog/i,
7096
- // Security Scanners
7097
- NESSUS: /Nessus/i,
7098
- NMAP: /Nmap/i,
7099
- BURPSUITE: /BurpSuite/i,
7100
- SQLMAP: /sqlmap/i
7282
+ DATADOG: /Datadog/i
7101
7283
  };
7102
7284
  var HEADER_PATTERNS = {
7103
7285
  // AI-specific headers
@@ -7615,6 +7797,11 @@ var PixelTrackingRequestSchema = external_exports.object({
7615
7797
  // User identification
7616
7798
  userId: external_exports.string().nullable().optional(),
7617
7799
  // Identified user ID
7800
+ // Prior (typically anonymous) user id for an `identify` alias. When present
7801
+ // and different from `userId`, the server COPIES older properties from this
7802
+ // profile onto the newly-identified one (properties are never merged across
7803
+ // profiles automatically). Mirrors the analytics-SDK `identify(previousId)` arg.
7804
+ previousId: external_exports.string().optional(),
7618
7805
  userTraits: external_exports.record(external_exports.unknown()).optional().refine((traits) => !traits || JSON.stringify(traits).length < 1e4, {
7619
7806
  message: "User traits too large (max 10KB)"
7620
7807
  }).refine((traits) => !traits || Object.keys(traits).length < 50, {
@@ -7625,7 +7812,9 @@ var PixelTrackingRequestSchema = external_exports.object({
7625
7812
  const validateDepth = (obj, depth = 0) => {
7626
7813
  if (depth > 3) return false;
7627
7814
  if (typeof obj !== "object" || obj === null) return true;
7628
- return Object.values(obj).every((val) => validateDepth(val, depth + 1));
7815
+ return Object.values(obj).every(
7816
+ (val) => validateDepth(val, depth + 1)
7817
+ );
7629
7818
  };
7630
7819
  return validateDepth(traits);
7631
7820
  },
@@ -7654,6 +7843,20 @@ var PixelTrackingRequestSchema = external_exports.object({
7654
7843
  // "America/New_York"
7655
7844
  language: external_exports.string().optional(),
7656
7845
  // "en-US"
7846
+ platform: external_exports.string().optional(),
7847
+ // navigator.platform
7848
+ cookiesEnabled: external_exports.boolean().optional(),
7849
+ // navigator.cookieEnabled
7850
+ onLine: external_exports.boolean().optional(),
7851
+ // navigator.onLine
7852
+ timezoneOffset: external_exports.number().optional(),
7853
+ // Date.getTimezoneOffset()
7854
+ connectionType: external_exports.string().optional(),
7855
+ // navigator.connection.effectiveType
7856
+ connectionSpeed: external_exports.number().optional(),
7857
+ // navigator.connection.downlink
7858
+ // Device identity — cross-subdomain cookie set by pixel.js
7859
+ deviceId: external_exports.string().optional(),
7657
7860
  // Behavioral (if available)
7658
7861
  timeOnPage: external_exports.number().optional(),
7659
7862
  // Milliseconds
@@ -7663,11 +7866,17 @@ var PixelTrackingRequestSchema = external_exports.object({
7663
7866
  // Number of clicks
7664
7867
  scrollDepth: external_exports.number().optional(),
7665
7868
  // Percentage 0-100
7869
+ pageLoadTime: external_exports.number().optional(),
7870
+ // performance.timing load duration, ms
7871
+ domContentLoadedTime: external_exports.number().optional(),
7872
+ // performance.timing DCL duration, ms
7666
7873
  // Client-side detection data (NEW)
7667
7874
  clientDetection: ClientDetectionSchema.optional(),
7668
7875
  // Request tracking (client-provided, will be validated server-side)
7669
7876
  requestId: external_exports.string().optional(),
7670
7877
  // Unique request ID for deduplication
7878
+ correlationId: external_exports.string().optional(),
7879
+ // Cross-surface correlation id (validated/normalized server-side)
7671
7880
  // Event type for special events
7672
7881
  eventType: external_exports.string().optional(),
7673
7882
  // 'pageview', 'identify', 'logout', etc.
@@ -8226,6 +8435,67 @@ var BULK_ERROR_CODES = {
8226
8435
  NOT_FOUND: "NOT_FOUND"
8227
8436
  };
8228
8437
 
8438
+ // src/constants/ai-traffic-taxonomy.ts
8439
+ var REPORT_AI_CRAWLER_NAMES = [
8440
+ "GPTBot",
8441
+ "ClaudeBot",
8442
+ "Anthropic-AI Crawler",
8443
+ "PerplexityBot",
8444
+ "Google-Extended",
8445
+ "Gemini-Deep-Research",
8446
+ "Meta-ExternalAgent",
8447
+ "Meta AI",
8448
+ "CohereBot",
8449
+ "DeepSeekBot",
8450
+ "MistralBot",
8451
+ "Amazonbot",
8452
+ "Amazon Bedrock",
8453
+ "Common Crawl",
8454
+ "Bytedance Crawler"
8455
+ ];
8456
+ var REPORT_AI_AGENT_NAMES = [
8457
+ "ChatGPT",
8458
+ "ChatGPT-User",
8459
+ "OpenAI",
8460
+ "Claude",
8461
+ "Claude-User",
8462
+ "Anthropic",
8463
+ "Perplexity",
8464
+ "Perplexity-User",
8465
+ "Google Gemini",
8466
+ "Microsoft Copilot",
8467
+ "DeepSeek AI",
8468
+ "xAI Grok",
8469
+ "Amazon Q",
8470
+ "Kya Agent"
8471
+ ];
8472
+ var CRAWLER_NAME_SET = new Set(REPORT_AI_CRAWLER_NAMES.map((name) => name.toLowerCase()));
8473
+ var AGENT_NAME_SET = new Set(REPORT_AI_AGENT_NAMES.map((name) => name.toLowerCase()));
8474
+ function buildKnownPatternLookup(patterns) {
8475
+ const map = /* @__PURE__ */ new Map();
8476
+ for (const entry of patterns) {
8477
+ const nameKey = entry.name.toLowerCase();
8478
+ const idKey = entry.id.toLowerCase();
8479
+ if (!map.has(nameKey)) map.set(nameKey, entry);
8480
+ if (!map.has(idKey)) map.set(idKey, entry);
8481
+ }
8482
+ return map;
8483
+ }
8484
+ var KNOWN_PATTERN_BY_NAME_OR_ID = buildKnownPatternLookup(KNOWN_AGENT_PATTERNS);
8485
+ function classifyAgentTaxonomy(agentType, detectionClass) {
8486
+ if (detectionClass === "human") return "human";
8487
+ const normalized = agentType?.trim().toLowerCase();
8488
+ if (normalized) {
8489
+ if (CRAWLER_NAME_SET.has(normalized)) return "ai_crawler";
8490
+ if (AGENT_NAME_SET.has(normalized)) return "ai_agent";
8491
+ const known = KNOWN_PATTERN_BY_NAME_OR_ID.get(normalized);
8492
+ if (known) {
8493
+ return (known.category ?? "ai_assistant") === "ai_assistant" ? "ai_agent" : "ai_crawler";
8494
+ }
8495
+ }
8496
+ return detectionClass === "ai_agent" ? "ai_agent" : "other_automation";
8497
+ }
8498
+
8229
8499
  // src/types/entities.ts
8230
8500
  var UserPlanSchema = external_exports.enum(["free", "pro", "enterprise"]);
8231
8501
  var ApiKeyPermissionSchema = external_exports.enum(["read", "write", "admin"]);
@@ -8258,6 +8528,10 @@ var ProjectSchema = external_exports.object({
8258
8528
  name: external_exports.string().min(1).max(255),
8259
8529
  domain: external_exports.string().optional(),
8260
8530
  settings: ProjectSettingsSchema.default({}),
8531
+ // Setup Flow v2 step 1 ("What brings you here?") selections, if this
8532
+ // project was created via that flow — see CreateProjectSchema's own
8533
+ // doc comment. Null/absent for every other creation path.
8534
+ setupGoals: external_exports.array(external_exports.string()).nullable().optional(),
8261
8535
  createdAt: external_exports.date(),
8262
8536
  updatedAt: external_exports.date()
8263
8537
  });
@@ -8428,6 +8702,18 @@ var OAuth2ProviderSchema = BaseAuthProviderSchema.extend({
8428
8702
  tokenEndpoint: external_exports.string().max(500),
8429
8703
  userInfoUrl: httpUrlSchema(500).optional(),
8430
8704
  // User info endpoint for identity resolution
8705
+ /**
8706
+ * Optional dot-path field mapping into the `userInfoUrl` response for
8707
+ * merchant identity extraction (native consent merchant-oauth leg).
8708
+ * When absent, extraction defaults to: userId ← first present of
8709
+ * `sub`/`id`/`customerId`; userEmail ← `email`.
8710
+ */
8711
+ userInfoFields: external_exports.object({
8712
+ userId: external_exports.string().max(255).optional(),
8713
+ // JSON dot-path to the customer id
8714
+ userEmail: external_exports.string().max(255).optional()
8715
+ // JSON dot-path to the customer email
8716
+ }).optional(),
8431
8717
  redirectUri: external_exports.string().max(500),
8432
8718
  scopes: external_exports.array(external_exports.string()).optional(),
8433
8719
  supportsPKCE: external_exports.boolean().optional(),
@@ -8557,6 +8843,9 @@ var ConsentConfigMetadataSchema = external_exports.object({
8557
8843
  updatedAt: external_exports.string().datetime().nullable().optional(),
8558
8844
  bumpedAt: external_exports.string().datetime().nullable().optional()
8559
8845
  });
8846
+ function requiresSensitiveTier(riskLevel) {
8847
+ return riskLevel === "high" || riskLevel === "critical";
8848
+ }
8560
8849
  var ConsentCapabilitySchema = external_exports.object({
8561
8850
  id: external_exports.string().min(1).max(64).regex(
8562
8851
  /^[a-z][a-z0-9._-]*$/,
@@ -8589,6 +8878,14 @@ var ConsentCapabilitySchema = external_exports.object({
8589
8878
  ),
8590
8879
  scopes: external_exports.array(external_exports.string().min(1).max(120)).min(1).max(20),
8591
8880
  category: external_exports.string().max(80).optional()
8881
+ }).superRefine((capability, ctx) => {
8882
+ if (requiresSensitiveTier(capability.riskLevel) && capability.defaultOn) {
8883
+ ctx.addIssue({
8884
+ code: external_exports.ZodIssueCode.custom,
8885
+ path: ["defaultOn"],
8886
+ message: `Capability "${capability.id}" has riskLevel "${capability.riskLevel}" and cannot default on. High/critical capabilities must be structurally unmintable at first contact (First-Contact Scope Cap section 3, Rule 1).`
8887
+ });
8888
+ }
8592
8889
  });
8593
8890
  var ConsentCapabilityGroupSchema = external_exports.object({
8594
8891
  id: external_exports.string().min(1).max(64).regex(/^[a-z][a-z0-9._-]*$/),
@@ -8600,8 +8897,16 @@ var ConsentAgentMetadataSchema = external_exports.object({
8600
8897
  did: external_exports.string().min(1).max(500),
8601
8898
  vendor: external_exports.string().max(80).optional(),
8602
8899
  surfaceLabel: external_exports.string().max(40).optional(),
8900
+ // Display-only. NOT authoritative for grant decisions: First-Contact
8901
+ // Scope Cap Rules 2 and 3 read first contact and verification from
8902
+ // server state (see FirstContactScopeCap resolver in
8903
+ // apps/web/lib/bouncer/services), never from this field, because it
8904
+ // sits inside the same config object an operator writes. Kept here only
8905
+ // so already-stored configs (and any future display use) keep parsing.
8603
8906
  verified: external_exports.boolean(),
8604
8907
  logoUrl: httpUrlSchema(500).optional(),
8908
+ // Display-only, same as `verified` above: not consulted for grant
8909
+ // decisions.
8605
8910
  connectedAt: external_exports.string().datetime().optional()
8606
8911
  });
8607
8912
  var ConsentConfigSchema = external_exports.object({
@@ -8615,7 +8920,28 @@ var ConsentConfigSchema = external_exports.object({
8615
8920
  // server renders the new design-language consent screen; when absent the
8616
8921
  // legacy raw-scope checkboxes are shown.
8617
8922
  capabilities: external_exports.array(ConsentCapabilityGroupSchema).max(20).optional(),
8923
+ // Populated server-side only: `UpdateBouncerConfigSchema` (the one
8924
+ // write path) unconditionally rejects a write that sets this, so an
8925
+ // operator can never self-attest an agent's identity or verification
8926
+ // status. Display-only; see `ConsentAgentMetadataSchema` above. NOT
8927
+ // consulted by First-Contact Scope Cap Rules 2/3, which read server
8928
+ // state instead (apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts).
8618
8929
  agentMetadata: ConsentAgentMetadataSchema.optional(),
8930
+ // First-Contact Scope Cap section 3, Rules 2 and 3 opt-in. Per-project,
8931
+ // defaults to off/absent so every existing config, and every config that
8932
+ // hasn't explicitly opted in, renders byte-identically to before this
8933
+ // field existed. Flip to `true` on one project's consentConfig (a
8934
+ // normal PUT/PATCH) to turn the probe gate on for that project.
8935
+ //
8936
+ // This flag is read at RENDER time, not enforced by this schema: Rules 2
8937
+ // and 3 are not write-time properties of a config, they depend on who is
8938
+ // in front of the screen right now, which this schema has no way to
8939
+ // know. See `applyFirstContactScopeCap` in
8940
+ // apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts for
8941
+ // the actual enforcement, which resolves first contact and verification
8942
+ // from server state (delegations, and a verification seam that returns
8943
+ // `indeterminate` until a real agent-verification source exists).
8944
+ firstContactScopeCapEnabled: external_exports.boolean().optional(),
8619
8945
  consentTheme: external_exports.enum(["light", "dark"]).optional(),
8620
8946
  headlineVerb: external_exports.string().min(1).max(40).optional(),
8621
8947
  revocationPath: external_exports.string().min(1).max(120).optional(),
@@ -8697,7 +9023,15 @@ var UpdateBouncerConfigSchema = external_exports.object({
8697
9023
  mcpServerUrl: httpUrlSchema().nullable().optional(),
8698
9024
  // Organization settings
8699
9025
  isEnabled: external_exports.boolean().optional()
8700
- }).strict();
9026
+ }).strict().superRefine((data, ctx) => {
9027
+ if (data.consentConfig?.agentMetadata !== void 0) {
9028
+ ctx.addIssue({
9029
+ code: external_exports.ZodIssueCode.custom,
9030
+ path: ["consentConfig", "agentMetadata"],
9031
+ message: "consentConfig.agentMetadata cannot be set through this endpoint. It represents verified facts about a specific requesting agent, not an operator preference, and this is not the write path that populates it."
9032
+ });
9033
+ }
9034
+ });
8701
9035
  var RefreshScopesRequestSchema = external_exports.object({
8702
9036
  mcpServerUrl: httpUrlSchema().optional()
8703
9037
  }).strict();
@@ -8707,7 +9041,7 @@ var DelegationSchema = external_exports.object({
8707
9041
  projectId: external_exports.string().uuid(),
8708
9042
  agentDid: external_exports.string().max(500),
8709
9043
  agentName: external_exports.string().max(255).nullable().optional(),
8710
- // User identification - userDid is primary for MCP-I, others for backward compatibility
9044
+ // User identification - userDid is primary for KYA-OS, others for backward compatibility
8711
9045
  userDid: external_exports.string().max(500).nullable().optional(),
8712
9046
  // DID of authorizing user (did:key or did:web)
8713
9047
  userId: external_exports.string().max(500).nullable().optional(),
@@ -8799,12 +9133,12 @@ var OAuthProviderMetadataSchema = external_exports.object({
8799
9133
  tokenEndpointAuthMethod: external_exports.enum(["client_secret_post", "client_secret_basic"]).optional(),
8800
9134
  responseType: external_exports.string().optional(),
8801
9135
  grantType: external_exports.string().optional(),
8802
- // MCP-I coordination fields (added per OAUTH_FLOW_COORDINATION_PLAN.md)
9136
+ // KYA-OS coordination fields (added per OAUTH_FLOW_COORDINATION_PLAN.md)
8803
9137
  configured: external_exports.boolean().optional(),
8804
9138
  // Whether this provider is configured for the project
8805
9139
  mode: OAuthModeSchema.optional(),
8806
- // OAuth flow mode: 'direct' (PKCE) or 'proxy' (AgentShield)
8807
- // MCP-I Provider Registry: Secret resolution metadata
9140
+ // OAuth flow mode: 'direct' (PKCE) or 'proxy' (Checkpoint)
9141
+ // KYA-OS Provider Registry: Secret resolution metadata
8808
9142
  metadata: external_exports.object({
8809
9143
  clientSecretName: external_exports.string().optional(),
8810
9144
  clientIdSecretName: external_exports.string().optional(),
@@ -9084,10 +9418,11 @@ var ProjectIdSchema = external_exports.string().refine(
9084
9418
  const uuidRegex2 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
9085
9419
  const ktaIdRegex = /^kta-[a-z0-9]{6}$/;
9086
9420
  const friendlyIdRegex = /^[a-z0-9-]+-[a-z0-9]{6}$/;
9087
- return uuidRegex2.test(val) || ktaIdRegex.test(val) || friendlyIdRegex.test(val);
9421
+ const bareSlugRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
9422
+ return uuidRegex2.test(val) || ktaIdRegex.test(val) || friendlyIdRegex.test(val) || val.length <= 20 && bareSlugRegex.test(val);
9088
9423
  },
9089
9424
  {
9090
- message: 'Invalid project ID format. Must be a UUID, kta-XXXXXX, or friendly ID (e.g., "my-project-a1b2c3")'
9425
+ message: 'Invalid project ID format. Must be a UUID, kta-XXXXXX, or friendly ID (e.g., "my-project-a1b2c3" or "my-project")'
9091
9426
  }
9092
9427
  );
9093
9428
  var OrganizationIdSchema = external_exports.string().refine(
@@ -9113,6 +9448,13 @@ var CreateProjectSchema = external_exports.object({
9113
9448
  // Changed: removed .url() validation to be more lenient
9114
9449
  organizationId: external_exports.string().uuid().optional(),
9115
9450
  // Optional - backend uses auth session as fallback
9451
+ // Setup Flow v2 step 1 ("What brings you here?") — the stable
9452
+ // SetupV2NeedDef.id keys the user selected (apps/web's
9453
+ // lib/setup-v2/flow-types.ts owns the id -> label/product mapping; this
9454
+ // shared package only validates shape, not membership, matching
9455
+ // settings.allowedOrigins/blockedAgents below). Optional: only the
9456
+ // setup-v2 flow ever sends it.
9457
+ setupGoals: external_exports.array(external_exports.string().min(1).max(100)).max(50).optional(),
9116
9458
  settings: external_exports.object({
9117
9459
  blockOnHighConfidence: external_exports.boolean().default(false),
9118
9460
  confidenceThreshold: external_exports.number().min(0).max(1).default(0.8),
@@ -9176,6 +9518,117 @@ var UpdateApiKeySchema = external_exports.object({
9176
9518
  rateLimits: ApiKeyRateLimitsSchema.optional(),
9177
9519
  expiresAt: external_exports.string().datetime().optional().nullable()
9178
9520
  });
9521
+ var MarketplaceSourceSchema = external_exports.enum([
9522
+ "vercel",
9523
+ "shopify",
9524
+ "netlify",
9525
+ "railway",
9526
+ "shopware"
9527
+ ]);
9528
+ var ProvisioningModeSchema = external_exports.enum(["observe", "enforce"]);
9529
+ var ProvisionKeyRequestSchema = external_exports.object({
9530
+ source: MarketplaceSourceSchema,
9531
+ /** Provider installation/configuration id (e.g. Vercel configurationId). */
9532
+ externalId: external_exports.string().min(1).max(255),
9533
+ /**
9534
+ * Provider resource id (e.g. one Vercel project); idempotency key with (source, externalId).
9535
+ * Single-resource providers repeat `externalId` here rather than inventing a sentinel — a
9536
+ * Shopware shop, for instance, has no sub-resource comparable to a Vercel project, so its
9537
+ * triple is ('shopware', shopId, shopId). Intentional, not a caller bug.
9538
+ */
9539
+ resourceId: external_exports.string().min(1).max(255),
9540
+ /** Human-readable label for the dashboard (e.g. "Vercel / team_xxx / my-project"). */
9541
+ label: external_exports.string().min(1).max(200),
9542
+ /**
9543
+ * Owner of the provisioned project. `email` is the account-linking key: we find-or-create
9544
+ * the KYA-OS user + personal org from it (Shopify-parity), so an address matching an
9545
+ * existing account provisions INTO that account — including the org it lands in.
9546
+ *
9547
+ * The caller MUST send an address it has verified belongs to the installer. Nothing here
9548
+ * enforces that: there is no verification flag and no per-provider gate, so a wrong address
9549
+ * silently mints a project inside a stranger's org. Adapters carrying a verified identity
9550
+ * (Vercel's OIDC `user_email`, Railway's OIDC userinfo `email`) satisfy this directly;
9551
+ * Shopware satisfies it by convention only, since its app handshake carries no user identity
9552
+ * and the address is merchant-confirmed in the shop admin.
9553
+ *
9554
+ * Rationale, per-provider trust, and the accepted exposure:
9555
+ * `docs/integrations/provisioning-owner-email-trust.md`.
9556
+ */
9557
+ owner: external_exports.object({
9558
+ email: external_exports.string().email(),
9559
+ name: external_exports.string().min(1).max(255).optional()
9560
+ }),
9561
+ /** Recorded on the provision for the dashboard; the SDK's enforcementMode is code-level today. */
9562
+ mode: ProvisioningModeSchema.default("observe"),
9563
+ /**
9564
+ * Org the installer chose in the adapter UI. Treated as a HINT: the backend binds the
9565
+ * installation to it and mints there only when the resolved user OWNS or ADMINISTERS it
9566
+ * (matching the orgs the list endpoint surfaces) — otherwise it falls back to the personal
9567
+ * org (owner/admin backstop in `mintWithinTx`). Omitted = legacy behavior (personal/default
9568
+ * org).
9569
+ */
9570
+ organizationId: external_exports.string().uuid().optional(),
9571
+ /** Optional non-secret provider context (teamId, userId, resource name). */
9572
+ metadata: external_exports.record(external_exports.unknown()).optional()
9573
+ });
9574
+ var ProvisionKeyResponseSchema = external_exports.object({
9575
+ /**
9576
+ * Plaintext API key — injected by the adapter as CHECKPOINT_API_KEY. Returned once on mint;
9577
+ * on idempotent re-provision the same key is returned (decrypted from storage).
9578
+ */
9579
+ apiKey: external_exports.string().min(1),
9580
+ /** The KYA-OS project the key is scoped to. */
9581
+ projectId: external_exports.string().uuid(),
9582
+ /** The API key row id (revoke is keyed by source/externalId/resourceId, not this). */
9583
+ apiKeyId: external_exports.string().uuid(),
9584
+ organizationId: external_exports.string().uuid(),
9585
+ /** True when an existing provision was returned rather than a new one created. */
9586
+ idempotent: external_exports.boolean()
9587
+ });
9588
+ var SsoLinkRequestSchema = external_exports.object({
9589
+ source: MarketplaceSourceSchema,
9590
+ /** Provider installation/configuration id (e.g. Vercel configurationId). */
9591
+ externalId: external_exports.string().min(1).max(255),
9592
+ /** Optional provider resource id — present → deep-link to that project; absent → org landing. */
9593
+ resourceId: external_exports.string().min(1).max(255).optional(),
9594
+ /** Verified installer email (the OIDC `user_email` claim). */
9595
+ ownerEmail: external_exports.string().email()
9596
+ });
9597
+ var SsoLinkResponseSchema = external_exports.object({
9598
+ /** Ready-to-redirect URL: the integration 302s the browser here. Establishes the session and lands on the friendly-id dashboard route. */
9599
+ url: external_exports.string().min(1)
9600
+ });
9601
+ var RevokeProvisionQuerySchema = external_exports.object({
9602
+ source: MarketplaceSourceSchema,
9603
+ externalId: external_exports.string().min(1).max(255),
9604
+ resourceId: external_exports.string().min(1).max(255).optional()
9605
+ });
9606
+ var RevokeProvisionResponseSchema = external_exports.object({
9607
+ /** Number of provisions revoked (0 if nothing matched — DELETE is idempotent). */
9608
+ revoked: external_exports.number().int().nonnegative()
9609
+ });
9610
+ var ProvisioningOrganizationRoleSchema = external_exports.enum(["owner", "admin"]);
9611
+ var ProvisioningOrganizationSummarySchema = external_exports.object({
9612
+ id: external_exports.string().uuid(),
9613
+ name: external_exports.string(),
9614
+ slug: external_exports.string(),
9615
+ role: ProvisioningOrganizationRoleSchema
9616
+ });
9617
+ var ListProvisioningOrganizationsRequestSchema = external_exports.object({
9618
+ email: external_exports.string().email()
9619
+ });
9620
+ var ListProvisioningOrganizationsResponseSchema = external_exports.object({
9621
+ organizations: external_exports.array(ProvisioningOrganizationSummarySchema)
9622
+ });
9623
+ var CreateProvisioningOrganizationRequestSchema = external_exports.object({
9624
+ email: external_exports.string().email(),
9625
+ name: CreateOrganizationInputSchema.shape.name,
9626
+ slug: CreateOrganizationInputSchema.shape.slug
9627
+ });
9628
+ var CreateProvisioningOrganizationResponseSchema = external_exports.object({
9629
+ /** The just-created org; `role` is always `owner` (the creator is inserted as owner). */
9630
+ organization: ProvisioningOrganizationSummarySchema
9631
+ });
9179
9632
  var CreateOrganizationSchema = CreateOrganizationInputSchema;
9180
9633
  var UpdateOrganizationSchema = UpdateOrganizationInputSchema;
9181
9634
  external_exports.object({
@@ -9749,18 +10202,302 @@ var StatsUpdateEventSchema = external_exports.object({
9749
10202
  })
9750
10203
  });
9751
10204
 
10205
+ // src/deploy/index.ts
10206
+ var DidStringSchema = external_exports.string().min(8, "DID must be at least 8 characters").regex(/^did:[a-z0-9]+:\S+$/, "DID must match format did:<method>:<method-specific-id>");
10207
+ external_exports.enum([
10208
+ "ams",
10209
+ // Amsterdam, Netherlands
10210
+ "arn",
10211
+ // Stockholm, Sweden
10212
+ "atl",
10213
+ // Atlanta, Georgia (US)
10214
+ "bog",
10215
+ // Bogotá, Colombia
10216
+ "bos",
10217
+ // Boston, Massachusetts (US)
10218
+ "cdg",
10219
+ // Paris, France
10220
+ "den",
10221
+ // Denver, Colorado (US)
10222
+ "dfw",
10223
+ // Dallas, Texas (US)
10224
+ "ewr",
10225
+ // Secaucus, NJ (US)
10226
+ "eze",
10227
+ // Ezeiza, Argentina
10228
+ "fra",
10229
+ // Frankfurt, Germany
10230
+ "gdl",
10231
+ // Guadalajara, Mexico
10232
+ "gig",
10233
+ // Rio de Janeiro, Brazil
10234
+ "gru",
10235
+ // São Paulo, Brazil
10236
+ "hkg",
10237
+ // Hong Kong
10238
+ "iad",
10239
+ // Ashburn, Virginia (US)
10240
+ "jnb",
10241
+ // Johannesburg, South Africa
10242
+ "lax",
10243
+ // Los Angeles, California (US)
10244
+ "lhr",
10245
+ // London, United Kingdom
10246
+ "mad",
10247
+ // Madrid, Spain
10248
+ "mia",
10249
+ // Miami, Florida (US)
10250
+ "nrt",
10251
+ // Tokyo, Japan
10252
+ "ord",
10253
+ // Chicago, Illinois (US)
10254
+ "otp",
10255
+ // Bucharest, Romania
10256
+ "phx",
10257
+ // Phoenix, Arizona (US)
10258
+ "qro",
10259
+ // Querétaro, Mexico
10260
+ "scl",
10261
+ // Santiago, Chile
10262
+ "sea",
10263
+ // Seattle, Washington (US)
10264
+ "sin",
10265
+ // Singapore
10266
+ "sjc",
10267
+ // San Jose, California (US)
10268
+ "syd",
10269
+ // Sydney, Australia
10270
+ "waw",
10271
+ // Warsaw, Poland
10272
+ "yul",
10273
+ // Montreal, Canada
10274
+ "yyz"
10275
+ // Toronto, Canada
10276
+ ]);
10277
+ external_exports.enum(["byok", "managed", "managed-byoa"]);
10278
+ var AuditAssuranceProfileSchema = external_exports.enum(["AAP-0", "AAP-1", "AAP-2", "AAP-3", "AAP-4"]);
10279
+ var AuditDeliveryModeSchema = external_exports.enum(["best-effort", "buffered", "required"]);
10280
+ var AuditDeploymentConfigSchema = external_exports.object({
10281
+ enabled: external_exports.boolean(),
10282
+ requestedProfile: AuditAssuranceProfileSchema,
10283
+ delivery: AuditDeliveryModeSchema,
10284
+ evidenceMode: external_exports.enum(["none", "encrypted-separate", "encrypted-inline"]),
10285
+ retentionClass: external_exports.string().min(1).max(128),
10286
+ retentionDays: external_exports.number().int().min(0).max(3650),
10287
+ residency: external_exports.enum(["inherit-project", "us", "eu", "global"]),
10288
+ keyCustody: external_exports.enum(["none", "checkpoint-managed", "customer-managed-kms"]),
10289
+ recorderTopology: external_exports.enum(["none", "self-hosted", "managed", "verified-mirror"])
10290
+ }).strict().superRefine((value, context) => {
10291
+ if (!value.enabled && value.requestedProfile !== "AAP-0") {
10292
+ context.addIssue({
10293
+ code: external_exports.ZodIssueCode.custom,
10294
+ path: ["requestedProfile"],
10295
+ message: "Disabled audit configuration must request AAP-0"
10296
+ });
10297
+ }
10298
+ if (value.enabled && value.requestedProfile === "AAP-0") {
10299
+ context.addIssue({
10300
+ code: external_exports.ZodIssueCode.custom,
10301
+ path: ["requestedProfile"],
10302
+ message: "Enabled audit configuration must request AAP-1 or higher"
10303
+ });
10304
+ }
10305
+ if (Number(value.requestedProfile.slice(-1)) >= 2 && value.delivery === "best-effort") {
10306
+ context.addIssue({
10307
+ code: external_exports.ZodIssueCode.custom,
10308
+ path: ["delivery"],
10309
+ message: "AAP-2 or higher cannot use best-effort delivery"
10310
+ });
10311
+ }
10312
+ if (!value.enabled && (value.keyCustody !== "none" || value.recorderTopology !== "none")) {
10313
+ context.addIssue({
10314
+ code: external_exports.ZodIssueCode.custom,
10315
+ message: "Disabled audit configuration cannot claim key custody or recorder topology"
10316
+ });
10317
+ }
10318
+ });
10319
+ var AuditRuntimeCapabilitiesSchema = external_exports.object({
10320
+ recorderTopology: external_exports.enum(["none", "self-hosted", "managed", "verified-mirror"]),
10321
+ delivery: AuditDeliveryModeSchema,
10322
+ journalDurability: external_exports.enum(["none", "ephemeral", "durable"]),
10323
+ atomicAppend: external_exports.boolean(),
10324
+ sourceHighWater: external_exports.boolean(),
10325
+ merkleCheckpoints: external_exports.boolean(),
10326
+ independentObservation: external_exports.boolean(),
10327
+ supportingAnchors: external_exports.array(external_exports.enum(["worm", "rfc3161", "scitt"])),
10328
+ evidenceRetention: external_exports.enum(["none", "inline", "separate"])
10329
+ }).strict();
10330
+ var AuditRuntimeCanaryResultSchema = external_exports.object({
10331
+ passed: external_exports.boolean(),
10332
+ observedAt: external_exports.number().int().nonnegative(),
10333
+ capabilities: AuditRuntimeCapabilitiesSchema,
10334
+ checks: external_exports.array(
10335
+ external_exports.object({
10336
+ id: external_exports.string().min(1).max(128),
10337
+ passed: external_exports.boolean()
10338
+ }).strict()
10339
+ ).min(1),
10340
+ bundleHash: external_exports.string().min(1).max(256).optional()
10341
+ }).strict().superRefine((value, context) => {
10342
+ if (value.passed !== value.checks.every((check) => check.passed)) {
10343
+ context.addIssue({
10344
+ code: external_exports.ZodIssueCode.custom,
10345
+ path: ["passed"],
10346
+ message: "Canary result must equal the aggregate of its mechanical checks"
10347
+ });
10348
+ }
10349
+ });
10350
+ external_exports.object({
10351
+ requestedProfile: AuditAssuranceProfileSchema,
10352
+ effectiveProfile: AuditAssuranceProfileSchema,
10353
+ status: external_exports.enum(["disabled", "ready", "degraded"]),
10354
+ capabilities: AuditRuntimeCapabilitiesSchema.nullable(),
10355
+ canary: AuditRuntimeCanaryResultSchema.nullable(),
10356
+ reasonCodes: external_exports.array(external_exports.string().min(1).max(128))
10357
+ }).strict();
10358
+ external_exports.enum([
10359
+ "pending",
10360
+ "in_progress",
10361
+ "completed",
10362
+ "failed",
10363
+ "skipped"
10364
+ ]);
10365
+ external_exports.object({
10366
+ /** Agent DID this heartbeat is for */
10367
+ agentDid: DidStringSchema,
10368
+ /** Current compute process status */
10369
+ status: external_exports.enum(["starting", "running", "error", "stopping"]),
10370
+ /** @kya-os/compute package version (from package.json) */
10371
+ computeVersion: external_exports.string().min(1).max(50),
10372
+ /** Installed OpenClaw version (from npm ls) */
10373
+ openclawVersion: external_exports.string().max(50).optional(),
10374
+ /** Fly machine ID (from FLY_MACHINE_ID env var) */
10375
+ machineId: external_exports.string().max(255).optional(),
10376
+ /** Seconds since compute process started */
10377
+ uptimeSeconds: external_exports.number().nonnegative().optional(),
10378
+ /** Current RSS memory in MB */
10379
+ memoryMb: external_exports.number().nonnegative().optional()
10380
+ });
10381
+ var StopCommandSchema = external_exports.object({
10382
+ type: external_exports.literal("stop")
10383
+ }).strict();
10384
+ var RestartCommandSchema = external_exports.object({
10385
+ type: external_exports.literal("restart")
10386
+ }).strict();
10387
+ var UpdateConfigCommandSchema = external_exports.object({
10388
+ type: external_exports.literal("update_config")
10389
+ }).strict();
10390
+ var UpdateVersionCommandSchema = external_exports.object({
10391
+ type: external_exports.literal("update_version"),
10392
+ payload: external_exports.object({
10393
+ /** Target OpenClaw version to install */
10394
+ version: external_exports.string().min(1).max(50)
10395
+ })
10396
+ }).strict();
10397
+ var ComputeCommandSchema = external_exports.discriminatedUnion("type", [
10398
+ StopCommandSchema,
10399
+ RestartCommandSchema,
10400
+ UpdateConfigCommandSchema,
10401
+ UpdateVersionCommandSchema
10402
+ ]);
10403
+ external_exports.object({
10404
+ /** Always true for successful heartbeats */
10405
+ ack: external_exports.literal(true),
10406
+ /** Pending commands for the compute process to execute */
10407
+ commands: external_exports.array(ComputeCommandSchema).default([]),
10408
+ /** ISO timestamp of last config change (compute compares to detect updates) */
10409
+ configUpdatedAt: external_exports.string().datetime().optional()
10410
+ });
10411
+ external_exports.object({
10412
+ /** Schema version — 2 for managed bundles */
10413
+ version: external_exports.number().int().positive(),
10414
+ /** Kill switch — if true, compute must exit immediately */
10415
+ killed: external_exports.boolean(),
10416
+ /** Target OpenClaw version to install */
10417
+ openclawVersion: external_exports.string().min(1).max(50),
10418
+ /** Agent personality/system prompt file contents (max 100KB) */
10419
+ soulFile: external_exports.string().max(1e5).nullable(),
10420
+ /** Gateway auth token for OpenClaw */
10421
+ gatewayToken: external_exports.string().min(1).max(500),
10422
+ /** Channel configurations */
10423
+ channels: external_exports.object({
10424
+ telegram: external_exports.object({
10425
+ enabled: external_exports.boolean(),
10426
+ token: external_exports.string().optional()
10427
+ }).optional(),
10428
+ discord: external_exports.object({
10429
+ enabled: external_exports.boolean(),
10430
+ token: external_exports.string().optional()
10431
+ }).optional(),
10432
+ slack: external_exports.object({
10433
+ enabled: external_exports.boolean(),
10434
+ token: external_exports.string().optional(),
10435
+ appToken: external_exports.string().optional()
10436
+ }).optional(),
10437
+ whatsapp: external_exports.object({
10438
+ enabled: external_exports.boolean()
10439
+ }).strict().optional()
10440
+ }),
10441
+ /** AI provider configuration — key is decrypted, sent over TLS */
10442
+ aiProvider: external_exports.object({
10443
+ type: external_exports.enum(["anthropic", "openai"]),
10444
+ apiKey: external_exports.string().min(1).max(500),
10445
+ /**
10446
+ * Optional base URL override. When set, OpenClaw routes all provider
10447
+ * traffic through this URL instead of the provider's default endpoint.
10448
+ * Used by managed deployments where AgentShield issues a per-deployment
10449
+ * gateway token and proxies to the upstream provider with budget tracking.
10450
+ */
10451
+ baseUrl: external_exports.string().url().optional()
10452
+ }),
10453
+ /**
10454
+ * Optional OpenClaw heartbeat interval (`agents.defaults.heartbeat.every`).
10455
+ * Drives how often OpenClaw wakes the agent for HEARTBEAT.md processing —
10456
+ * the primary token-cost lever. Examples: "30m" (active), "6h" (idle),
10457
+ * "off" (dormant — heartbeat disabled entirely). When absent, the patcher
10458
+ * preserves whatever value already lives in openclaw.json (OpenClaw's
10459
+ * built-in default of "30m").
10460
+ */
10461
+ heartbeatEvery: external_exports.string().min(1).max(20).optional(),
10462
+ /**
10463
+ * Optional override for `agents.defaults.model.primary` (e.g.
10464
+ * "anthropic/claude-haiku-4-5" for idle agents). When absent, the patcher
10465
+ * derives the model from `aiProvider.type` as before. Format must be
10466
+ * "<provider>/<model-id>".
10467
+ */
10468
+ modelOverride: external_exports.string().min(1).max(100).optional(),
10469
+ /** ISO timestamp of last config modification */
10470
+ updatedAt: external_exports.string().datetime()
10471
+ });
10472
+ external_exports.object({
10473
+ /** Whether the agent runtime is healthy */
10474
+ healthy: external_exports.boolean(),
10475
+ /** Seconds since compute process started */
10476
+ uptimeSeconds: external_exports.number().nonnegative(),
10477
+ /** Installed OpenClaw version */
10478
+ openclawVersion: external_exports.string().min(1).max(50),
10479
+ /** @kya-os/compute version */
10480
+ computeVersion: external_exports.string().min(1).max(50),
10481
+ /** Number of active WS connections to control server */
10482
+ activeConnections: external_exports.number().int().nonnegative(),
10483
+ /** Current RSS memory in MB */
10484
+ memoryMb: external_exports.number().nonnegative(),
10485
+ /** CPU usage percentage (0-100) */
10486
+ cpuPercent: external_exports.number().nonnegative().max(100)
10487
+ });
10488
+
9752
10489
  // src/events/deploy-progress.ts
9753
10490
  var DEPLOY_STEPS = [
9754
- { id: "github_verify", label: "Verifying GitHub connection", order: 1 },
9755
- { id: "repo_check", label: "Checking repository availability", order: 2 },
9756
- { id: "project_create", label: "Creating AgentShield project", order: 3 },
9757
- { id: "api_key", label: "Generating API key", order: 4 },
9758
- { id: "scaffold", label: "Scaffolding project files", order: 5 },
9759
- { id: "kta_register", label: "Registering agent for reputation", order: 6 },
9760
- { id: "repo_create", label: "Creating GitHub repository", order: 7 },
9761
- { id: "commit_files", label: "Committing files", order: 8 },
9762
- { id: "add_secrets", label: "Adding repository secrets", order: 9 },
9763
- { id: "cloudflare_deploy", label: "Deploying to Cloudflare", order: 10 },
10491
+ { id: "github_verify", label: "Verifying your GitHub connection", order: 1 },
10492
+ { id: "repo_check", label: "Checking your repository name", order: 2 },
10493
+ { id: "project_create", label: "Creating your project", order: 3 },
10494
+ { id: "api_key", label: "Generating your API key", order: 4 },
10495
+ { id: "scaffold", label: "Generating your server files", order: 5 },
10496
+ { id: "kta_register", label: "Setting up your agent identity", order: 6 },
10497
+ { id: "repo_create", label: "Creating your GitHub repository", order: 7 },
10498
+ { id: "commit_files", label: "Committing your server code", order: 8 },
10499
+ { id: "add_secrets", label: "Securing your repository secrets", order: 9 },
10500
+ { id: "cloudflare_deploy", label: "Deploying your server to Cloudflare", order: 10 },
9764
10501
  { id: "complete", label: "Deployment complete!", order: 11 }
9765
10502
  ];
9766
10503
  var DeployStepIdSchema = external_exports.enum([
@@ -9807,12 +10544,16 @@ var DeployProgressEventSchema = external_exports.object({
9807
10544
  projectId: external_exports.string(),
9808
10545
  /** Human-readable project ID for URL construction */
9809
10546
  friendlyId: external_exports.string().nullable().optional(),
10547
+ /** kyaosDeployments row id — drives the live-step "Go to server" deployment-detail link. */
10548
+ deploymentId: external_exports.string().optional(),
9810
10549
  /** Full API key - only shown once at completion! */
9811
10550
  apiKey: external_exports.string(),
9812
10551
  /** Preview (sk_...xxx) for display after initial view */
9813
10552
  apiKeyPreview: external_exports.string(),
9814
10553
  cloudflareUrl: external_exports.string().optional(),
9815
10554
  cloudflareDeployed: external_exports.boolean().optional(),
10555
+ /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */
10556
+ cloudflareError: external_exports.string().optional(),
9816
10557
  /** Agent DID (decentralized identifier) - did:web for reputation enabled, did:key for disabled */
9817
10558
  agentDid: external_exports.string().optional(),
9818
10559
  /** Whether agent was registered with Know That AI for reputation tracking */
@@ -9833,13 +10574,40 @@ var DeploymentMetadataSchema = external_exports.object({
9833
10574
  repoName: external_exports.string(),
9834
10575
  template: external_exports.string(),
9835
10576
  platform: external_exports.string(),
9836
- /** Hosting mode: 'managed' (AgentShield hosted) or 'byok' (Bring Your Own Cloudflare) */
10577
+ /** Hosting mode: 'managed' (Checkpoint hosted) or 'byok' (Bring Your Own Cloudflare) */
9837
10578
  hostingMode: external_exports.enum(["managed", "byok"]).optional().default("byok"),
10579
+ /** 'repo-only' scaffolds + pushes the repo but never triggers the Cloudflare worker upload, regardless of connection state (defaults to 'cloudflare') */
10580
+ deployTarget: external_exports.enum(["cloudflare", "repo-only"]).optional(),
9838
10581
  status: external_exports.enum(["pending", "running", "complete", "error"]),
9839
10582
  /** Enable reputation tracking via Know That AI (defaults to true) */
9840
10583
  enableReputation: external_exports.boolean().optional(),
10584
+ /** Requested audit posture. Old stored metadata may omit this and resolves to AAP-0 at use. */
10585
+ audit: AuditDeploymentConfigSchema.optional(),
9841
10586
  /** Existing project ID to deploy to (if provided, skips project creation) - Unified Project Schema v1.3 */
9842
10587
  existingProjectId: external_exports.string().uuid().optional(),
10588
+ /** Pre-generated source supplied by another intake flow (for example OpenAPI). */
10589
+ generatedFiles: external_exports.array(
10590
+ external_exports.object({
10591
+ path: external_exports.string(),
10592
+ content: external_exports.string(),
10593
+ isBase64: external_exports.boolean().optional()
10594
+ })
10595
+ ).optional(),
10596
+ /** Identity paired with pre-generated source. */
10597
+ generatedIdentity: external_exports.object({
10598
+ did: external_exports.string(),
10599
+ // Optional so historical metadata already sitting in Redis without a
10600
+ // kid still parses. The producing route always populates it now (see
10601
+ // KYA-956 phase 3); the deploy pipeline treats a missing kid as a
10602
+ // scaffold-time failure rather than injecting a broken identity.
10603
+ kid: external_exports.string().optional(),
10604
+ publicKey: external_exports.string(),
10605
+ privateKey: external_exports.string()
10606
+ }).optional(),
10607
+ /** Validated source-specific secrets forwarded to GitHub/Cloudflare. */
10608
+ additionalSecrets: external_exports.record(external_exports.string()).optional(),
10609
+ /** Semantic source type used for descriptions and registry metadata. */
10610
+ agentType: external_exports.string().optional(),
9843
10611
  createdAt: external_exports.number(),
9844
10612
  updatedAt: external_exports.number(),
9845
10613
  /** Result data (populated on completion) */
@@ -9853,10 +10621,14 @@ var DeploymentMetadataSchema = external_exports.object({
9853
10621
  projectId: external_exports.string(),
9854
10622
  /** Human-readable project ID for URL construction */
9855
10623
  friendlyId: external_exports.string().nullable().optional(),
10624
+ /** kyaosDeployments row id — powers the live-step deployment-detail link (all sources). */
10625
+ deploymentId: external_exports.string().optional(),
9856
10626
  /** API key preview e.g. "sk_...xxx" (BYOK deploy only) */
9857
10627
  apiKeyPreview: external_exports.string().optional(),
9858
10628
  cloudflareUrl: external_exports.string().optional(),
9859
10629
  cloudflareDeployed: external_exports.boolean().optional(),
10630
+ /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */
10631
+ cloudflareError: external_exports.string().optional(),
9860
10632
  agentDid: external_exports.string().optional(),
9861
10633
  ktaRegistered: external_exports.boolean().optional(),
9862
10634
  ktaClaimUrl: external_exports.string().optional()
@@ -10160,122 +10932,6 @@ var SessionTokenPayloadSchema = external_exports.object({
10160
10932
  metadata: external_exports.record(external_exports.unknown()).optional()
10161
10933
  });
10162
10934
 
10163
- // src/types/beacon.ts
10164
- var ConnectionTypeSchema = external_exports.enum([
10165
- "bluetooth",
10166
- "cellular",
10167
- "ethernet",
10168
- "none",
10169
- "wifi",
10170
- "wimax",
10171
- "other",
10172
- "unknown"
10173
- ]);
10174
- var BeaconCollectorDataSchema = external_exports.object({
10175
- // Request Headers
10176
- userAgent: external_exports.string(),
10177
- referer: external_exports.string().optional(),
10178
- acceptLanguage: external_exports.string().optional(),
10179
- acceptEncoding: external_exports.string().optional(),
10180
- // Page Context
10181
- url: external_exports.string().url(),
10182
- timestamp: external_exports.number(),
10183
- sessionId: external_exports.string(),
10184
- // Detection Signals
10185
- screenResolution: external_exports.string().optional(),
10186
- // e.g., "1920x1080"
10187
- viewport: external_exports.string().optional(),
10188
- // e.g., "1200x800"
10189
- timezone: external_exports.string().optional(),
10190
- platform: external_exports.string().optional(),
10191
- // Performance Metrics
10192
- pageLoadTime: external_exports.number().optional(),
10193
- connectionType: ConnectionTypeSchema.optional(),
10194
- connectionSpeed: external_exports.number().optional()
10195
- // Mbps
10196
- });
10197
- var BeaconConfigSchema = external_exports.object({
10198
- // API Configuration
10199
- apiKey: external_exports.string(),
10200
- endpoint: external_exports.string().url().default("https://kya.vouched.id/v1/beacon"),
10201
- // Batching Configuration
10202
- batchSize: external_exports.number().min(1).max(100).default(10),
10203
- flushInterval: external_exports.number().min(1e3).max(6e4).default(5e3),
10204
- // Worker Configuration
10205
- useWorker: external_exports.boolean().default(true),
10206
- workerUrl: external_exports.string().optional(),
10207
- workerConfig: external_exports.object({
10208
- maxRetries: external_exports.number().min(0).max(10).default(3),
10209
- retryDelay: external_exports.number().min(100).max(1e4).default(1e3),
10210
- heartbeatInterval: external_exports.number().min(1e3).max(6e4).default(5e3),
10211
- maxUnhealthyCount: external_exports.number().min(1).max(10).default(3),
10212
- enableResourceMonitoring: external_exports.boolean().default(true),
10213
- enableCompression: external_exports.boolean().default(true),
10214
- compressionThreshold: external_exports.number().min(0).default(5120),
10215
- // 5KB
10216
- messageTimeout: external_exports.number().min(1e3).max(6e4).default(3e4),
10217
- poolSize: external_exports.number().min(1).max(10).default(1),
10218
- autoScale: external_exports.boolean().default(false),
10219
- allowFallback: external_exports.boolean().default(true),
10220
- crossOriginIsolated: external_exports.boolean().default(false)
10221
- }).optional(),
10222
- // Privacy Configuration
10223
- respectDoNotTrack: external_exports.boolean().default(true),
10224
- anonymizeIp: external_exports.boolean().default(false),
10225
- // Session Configuration
10226
- sessionTimeout: external_exports.number().min(6e4).default(18e5),
10227
- // 30 minutes
10228
- sessionCookieName: external_exports.string().default("_as_beacon_session"),
10229
- // Debug Configuration
10230
- debug: external_exports.boolean().default(false),
10231
- logLevel: external_exports.enum(["error", "warn", "info", "debug"]).default("error"),
10232
- // Performance Configuration
10233
- maxQueueSize: external_exports.number().min(10).max(1e3).default(100),
10234
- retryAttempts: external_exports.number().min(0).max(10).default(3),
10235
- retryDelay: external_exports.number().min(1e3).max(6e4).default(2e3)
10236
- });
10237
- var BeaconEventTypeSchema = external_exports.enum([
10238
- "pageview",
10239
- "pageunload",
10240
- "error",
10241
- "custom",
10242
- "heartbeat"
10243
- ]);
10244
- var BeaconEventSchema = external_exports.object({
10245
- type: BeaconEventTypeSchema,
10246
- data: BeaconCollectorDataSchema,
10247
- metadata: external_exports.record(external_exports.unknown()).optional()
10248
- });
10249
- var BeaconBatchSchema = external_exports.object({
10250
- apiKey: external_exports.string(),
10251
- events: external_exports.array(BeaconEventSchema).min(1).max(100),
10252
- sessionId: external_exports.string(),
10253
- batchId: external_exports.string().uuid(),
10254
- timestamp: external_exports.number()
10255
- });
10256
- var BeaconWorkerMessageTypeSchema = external_exports.enum([
10257
- "init",
10258
- "collect",
10259
- "flush",
10260
- "config",
10261
- "status",
10262
- "error"
10263
- ]);
10264
- var BeaconWorkerMessageSchema = external_exports.object({
10265
- type: BeaconWorkerMessageTypeSchema,
10266
- id: external_exports.string(),
10267
- payload: external_exports.unknown().optional(),
10268
- timestamp: external_exports.number()
10269
- });
10270
- var TransportStatusSchema = external_exports.enum(["idle", "sending", "success", "failed", "retrying"]);
10271
- var CollectorTypeSchema = external_exports.enum([
10272
- "browser",
10273
- "performance",
10274
- "behavioral",
10275
- "error",
10276
- "custom"
10277
- ]);
10278
-
10279
10935
  // src/types/transport.ts
10280
10936
  var TransportConfigSchema = external_exports.object({
10281
10937
  batchSize: external_exports.number().min(1).max(100).default(10),
@@ -11281,7 +11937,13 @@ function supportsServerEnhanced(integration) {
11281
11937
  return ["middleware", "express"].includes(integration);
11282
11938
  }
11283
11939
 
11940
+ // src/types/signing-vendors.generated.ts
11941
+ var PINNED_SIGNING_VENDORS = ["openai"];
11942
+
11284
11943
  // src/types/agent-classification.ts
11944
+ function hasPinnedSigningVendor(aliases) {
11945
+ return aliases?.some((alias) => PINNED_SIGNING_VENDORS.includes(alias)) ?? false;
11946
+ }
11285
11947
  var AgentCategorySchema = external_exports.enum([
11286
11948
  "ai_assistant",
11287
11949
  // ChatGPT, Claude, Gemini, Perplexity
@@ -11312,6 +11974,11 @@ var AgentTypeDefinitionSchema = external_exports.object({
11312
11974
  confidenceThreshold: external_exports.number().min(0).max(100),
11313
11975
  detectionPatterns: external_exports.array(external_exports.string()),
11314
11976
  signatureSupport: external_exports.boolean(),
11977
+ // Vendor tokens (own name + company aliases, e.g. ['chatgpt','openai']) matched
11978
+ // against a host-VERIFIED RFC 9421 Signature-Agent value to attribute a signed
11979
+ // agent to this type at ingest. Optional/additive; empty or absent ⇒ this type is
11980
+ // not resolvable by signature (only signatureSupport vendors carry aliases).
11981
+ signatureVendorAliases: external_exports.array(external_exports.string()).optional(),
11315
11982
  documentationUrl: external_exports.string().optional(),
11316
11983
  createdAt: external_exports.date(),
11317
11984
  updatedAt: external_exports.date()
@@ -11405,7 +12072,8 @@ var DEFAULT_AGENT_TYPES = [
11405
12072
  description: "OpenAI ChatGPT Browser",
11406
12073
  isLegitimate: true,
11407
12074
  confidenceThreshold: 95,
11408
- signatureSupport: true,
12075
+ signatureSupport: hasPinnedSigningVendor(["chatgpt", "openai"]),
12076
+ signatureVendorAliases: ["chatgpt", "openai"],
11409
12077
  detectionPatterns: ["GPTBot", "ChatGPT-User", "x-gpt-signature"]
11410
12078
  },
11411
12079
  {
@@ -11415,7 +12083,12 @@ var DEFAULT_AGENT_TYPES = [
11415
12083
  description: "Anthropic Claude Assistant",
11416
12084
  isLegitimate: true,
11417
12085
  confidenceThreshold: 95,
11418
- signatureSupport: true,
12086
+ // Derived FALSE today: Anthropic publishes no web-bot-auth key
12087
+ // directory (verified 2026-08-26) and the engine pins no anthropic
12088
+ // key. Flips automatically once anthropic.json lands in vendor-keys
12089
+ // and the manifest is regenerated.
12090
+ signatureSupport: hasPinnedSigningVendor(["claude", "anthropic"]),
12091
+ signatureVendorAliases: ["claude", "anthropic"],
11419
12092
  detectionPatterns: ["Claude-Web", "Claude-User", "anthropic-ai", "x-claude-signature"]
11420
12093
  },
11421
12094
  {
@@ -11482,6 +12155,59 @@ var auditLogQuerySchema = external_exports.object({
11482
12155
  search: external_exports.string().optional()
11483
12156
  });
11484
12157
 
12158
+ // src/types/admin-overview.ts
12159
+ var ADMIN_OVERVIEW_WINDOWS = ["7d", "30d", "90d"];
12160
+ var DEFAULT_ADMIN_OVERVIEW_WINDOW = "30d";
12161
+ var ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT = 100;
12162
+ var ADMIN_OVERVIEW_LIST_LIMIT_MAX = 500;
12163
+ function isCalendarDate(value) {
12164
+ const [year, month, day] = value.split("-").map(Number);
12165
+ if (!year || !month || !day) return false;
12166
+ const date = new Date(Date.UTC(year, month - 1, day));
12167
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
12168
+ }
12169
+ var adminOverviewQuerySchema = external_exports.object({
12170
+ window: external_exports.enum(ADMIN_OVERVIEW_WINDOWS).default(DEFAULT_ADMIN_OVERVIEW_WINDOW),
12171
+ // YYYY-MM-DD, must be a real calendar date (reject 2026-02-30, 2026-13-01, '2026-1-5', ISO datetimes)
12172
+ compareTo: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine(isCalendarDate, {
12173
+ message: "compareTo must be a real calendar date in YYYY-MM-DD form"
12174
+ }).optional(),
12175
+ listLimit: external_exports.coerce.number().int().min(1).max(ADMIN_OVERVIEW_LIST_LIMIT_MAX).default(ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT)
12176
+ });
12177
+ var ADMIN_DELTA_BASES = ["created_at", "rollup", "none"];
12178
+ var INSTALLATION_KINDS = [
12179
+ "agent",
12180
+ "pixel",
12181
+ "middleware",
12182
+ "dns_gateway",
12183
+ "mcp_server",
12184
+ "beacon"
12185
+ ];
12186
+ var INSTALLATION_TYPES = [
12187
+ "pixel",
12188
+ "middleware_node",
12189
+ "middleware_dotnet",
12190
+ "middleware_no_traffic",
12191
+ "dns_gateway",
12192
+ "beacon"
12193
+ ];
12194
+ var TRAFFIC_TAXONOMY_BUCKETS = [
12195
+ "human",
12196
+ "ai_agent",
12197
+ "ai_crawler",
12198
+ "other_automation"
12199
+ ];
12200
+ var EXCLUSION_BUCKETS = [
12201
+ "vouched",
12202
+ "internal_team",
12203
+ "test_pattern",
12204
+ "shopify_review",
12205
+ "cohort"
12206
+ ];
12207
+ var ADMIN_OVERVIEW_SECTIONS = ["ladder", "installations", "traffic", "lists"];
12208
+ var ADMIN_OVERVIEW_CACHE_STATUSES = ["hit", "stale", "miss", "bypass"];
12209
+ var SERVICE_TRAFFIC_KEYS = [...INSTALLATION_KINDS, "mixed", "none"];
12210
+
11485
12211
  // src/types/api.ts
11486
12212
  var API_ERROR_CODES = {
11487
12213
  // Authentication & Authorization
@@ -11668,8 +12394,14 @@ function isKyaOsHandshakeMethod(value) {
11668
12394
  function isKyaOsWireMethod(value) {
11669
12395
  return value === KYA_OS_WIRE_METHODS.LEGACY || value === KYA_OS_WIRE_METHODS.CANONICAL;
11670
12396
  }
12397
+ function normalizeHandshakeMethod(value) {
12398
+ return isKyaOsHandshakeMethod(value) ? KYA_OS_HANDSHAKE_METHODS.CANONICAL : value;
12399
+ }
12400
+ function normalizeWireMethod(value) {
12401
+ return isKyaOsWireMethod(value) ? KYA_OS_WIRE_METHODS.CANONICAL : value;
12402
+ }
11671
12403
  function getVerificationMethodDescription(method) {
11672
- switch (method) {
12404
+ switch (normalizeHandshakeMethod(method)) {
11673
12405
  case "signature":
11674
12406
  return "HTTP Signature Verification";
11675
12407
  case "pattern":
@@ -11678,9 +12410,7 @@ function getVerificationMethodDescription(method) {
11678
12410
  return "Behavioral Analysis";
11679
12411
  case "network":
11680
12412
  return "Network-based Detection";
11681
- // Dual-accept: legacy `mcp_i_handshake` + canonical `kyaos_handshake`.
11682
- case "mcp_i_handshake":
11683
- case "kyaos_handshake":
12413
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL:
11684
12414
  return "MCP Handshake Detection";
11685
12415
  case "error":
11686
12416
  return "Detection Error";
@@ -11690,13 +12420,11 @@ function getVerificationMethodDescription(method) {
11690
12420
  }
11691
12421
  }
11692
12422
  function getVerificationReliability(method) {
11693
- switch (method) {
12423
+ switch (normalizeHandshakeMethod(method)) {
11694
12424
  case "signature":
11695
12425
  return 1;
11696
12426
  // Highest reliability
11697
- // Dual-accept: legacy `mcp_i_handshake` + canonical `kyaos_handshake`.
11698
- case "mcp_i_handshake":
11699
- case "kyaos_handshake":
12427
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL:
11700
12428
  return 0.95;
11701
12429
  case "behavioral":
11702
12430
  return 0.8;
@@ -11712,7 +12440,7 @@ function getVerificationReliability(method) {
11712
12440
  }
11713
12441
  }
11714
12442
  function isHighConfidenceVerification(method) {
11715
- return ["signature", "mcp_i_handshake", "kyaos_handshake"].includes(method);
12443
+ return method === "signature" || isKyaOsHandshakeMethod(method);
11716
12444
  }
11717
12445
  function getVerificationRiskLevel(method, confidence) {
11718
12446
  if (method === "signature") {
@@ -11792,6 +12520,76 @@ function normalizeDetectionClassEnum(value) {
11792
12520
  return "incomplete_data";
11793
12521
  }
11794
12522
 
12523
+ // src/utils/agent-runtime-label.ts
12524
+ var CLAUDE_CANONICAL_DISPLAY = "Claude";
12525
+ var CLAUDE_DEPRECATED_TWIN = /^Claude \(deprecated/i;
12526
+ function isClaudeProductLabel(displayName) {
12527
+ if (!displayName) return false;
12528
+ const d = displayName.trim();
12529
+ return d === CLAUDE_CANONICAL_DISPLAY || CLAUDE_DEPRECATED_TWIN.test(d);
12530
+ }
12531
+ function claudeRuntimeLabel(userAgent) {
12532
+ const ua = (userAgent ?? "").toLowerCase();
12533
+ if (!ua) return "Claude";
12534
+ if (ua.includes("claude-code") || ua.includes("claude code")) return "Claude Code";
12535
+ if (ua.includes("claude-cowork")) return "Claude Cowork";
12536
+ if (ua.includes("claude-searchbot")) return "Claude SearchBot";
12537
+ if (ua.includes("claude-user")) return "Claude (web fetch)";
12538
+ return "Claude";
12539
+ }
12540
+ function refineClaudeDisplayLabel(displayName, userAgent) {
12541
+ return isClaudeProductLabel(displayName) ? claudeRuntimeLabel(userAgent) : displayName;
12542
+ }
12543
+
12544
+ // src/utils/correlation-id.ts
12545
+ var CORRELATION_ID_HEADER = "x-kya-correlation-id";
12546
+ var CorrelationIdSchema = external_exports.string().regex(/^[0-9a-f]{32}$/);
12547
+ var TRACEPARENT_RE = /^(?<ver>[0-9a-f]{2})-(?<trace>[0-9a-f]{32})-(?<span>[0-9a-f]{16})-(?<flags>[0-9a-f]{2})$/;
12548
+ var ZERO_TRACE_ID = "0".repeat(32);
12549
+ function getHeader(headers, name) {
12550
+ const lower = name.toLowerCase();
12551
+ if (typeof headers.get === "function") {
12552
+ const value = headers.get(lower);
12553
+ return value && value.length > 0 ? value : null;
12554
+ }
12555
+ const record = headers;
12556
+ for (const key of Object.keys(record)) {
12557
+ if (key.toLowerCase() !== lower) continue;
12558
+ const raw = record[key];
12559
+ const value = Array.isArray(raw) ? raw[0] : raw;
12560
+ return value && value.length > 0 ? value : null;
12561
+ }
12562
+ return null;
12563
+ }
12564
+ function normalizeHex(value) {
12565
+ if (typeof value !== "string" || value.length === 0) return null;
12566
+ const candidate = value.toLowerCase().replace(/-/g, "");
12567
+ const parsed = CorrelationIdSchema.safeParse(candidate);
12568
+ return parsed.success ? parsed.data : null;
12569
+ }
12570
+ function extractTraceId(traceparent) {
12571
+ if (!traceparent) return null;
12572
+ const match = TRACEPARENT_RE.exec(traceparent);
12573
+ const trace = match?.groups?.trace;
12574
+ if (!trace || trace === ZERO_TRACE_ID) return null;
12575
+ return trace;
12576
+ }
12577
+ function toStoredCorrelationId(value) {
12578
+ return normalizeHex(value);
12579
+ }
12580
+ function extractCorrelationIdFromHeaders(headers) {
12581
+ const fromTrace = extractTraceId(getHeader(headers, "traceparent"));
12582
+ if (fromTrace) return fromTrace;
12583
+ return normalizeHex(getHeader(headers, CORRELATION_ID_HEADER));
12584
+ }
12585
+ function deriveCorrelationId(headers, fallback) {
12586
+ const fromHeaders = extractCorrelationIdFromHeaders(headers);
12587
+ if (fromHeaders) return fromHeaders;
12588
+ const fromFallback = normalizeHex(fallback);
12589
+ if (fromFallback) return fromFallback;
12590
+ return globalThis.crypto.randomUUID().replace(/-/g, "").toLowerCase();
12591
+ }
12592
+
11795
12593
  // src/schemas/auth.ts
11796
12594
  var passwordSchema = external_exports.string().min(8, "Password must be at least 8 characters long").max(128, "Password must not exceed 128 characters").regex(
11797
12595
  /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
@@ -12079,7 +12877,30 @@ var upstreamServerSchema = external_exports.object({
12079
12877
  transport: external_exports.enum(["http", "sse"]).default("http"),
12080
12878
  authType: external_exports.enum(["none", "vault", "static"]).default("none"),
12081
12879
  envVarNames: external_exports.array(external_exports.string()).optional(),
12880
+ // ─────────────────────────────────────────────────────────────────
12881
+ // Static-header credential plane (hygiene-scorecard gap #1)
12882
+ //
12883
+ // `staticHeaders` (plaintext) is DEPRECATED as an at-rest field —
12884
+ // kept here only so `.parse()` doesn't silently drop rows written
12885
+ // before this fix while they wait to be re-encrypted. It remains the
12886
+ // wire-input field name (the admin form still submits plaintext
12887
+ // header values; the PUT handler encrypts them into
12888
+ // `staticHeadersEncrypted` before persisting and opportunistically
12889
+ // migrates any legacy plaintext it finds on every save that touches
12890
+ // an upstream). Never populated in an API response.
12082
12891
  staticHeaders: external_exports.record(external_exports.string()).optional(),
12892
+ // AES-256-GCM ciphertext (base64: iv|ciphertext|authTag) of the
12893
+ // JSON-serialized staticHeaders map — the at-rest form going
12894
+ // forward. Encrypt/decrypt via `@kya-os/checkpoint-db/crypto`'s
12895
+ // `encryptStaticHeaders`/`resolveStaticHeaders`. Never populated in
12896
+ // an API response — see `staticHeaderKeys` for the redacted view.
12897
+ staticHeadersEncrypted: external_exports.string().nullable().optional(),
12898
+ // Read-only projection of the configured header NAMES (never
12899
+ // values). Populated by the gateway-mcp config GET/PUT response
12900
+ // serializer (`redactGatewayConfig`) so the dashboard can render
12901
+ // "N headers configured" without ever receiving secret material or
12902
+ // ciphertext. Ignored on write — `upstreamServerInputSchema` omits it.
12903
+ staticHeaderKeys: external_exports.array(external_exports.string()).optional(),
12083
12904
  // ─────────────────────────────────────────────────────────────────
12084
12905
  // #1600 Phase 1 Part 2 — credential flow method selection
12085
12906
  //
@@ -12110,8 +12931,37 @@ var upstreamServerSchema = external_exports.object({
12110
12931
  // ─────────────────────────────────────────────────────────────────
12111
12932
  supportedAuthMethods: external_exports.array(external_exports.enum(["paste", "oauth"])).default(["paste"]),
12112
12933
  oauthProvider: external_exports.enum(["github", "slack", "notion", "linear"]).optional(),
12934
+ // ─────────────────────────────────────────────────────────────────
12935
+ // Stateless (UCP-style) upstreams
12936
+ //
12937
+ // Some MCP-transport endpoints reject `initialize` and `tools/list`
12938
+ // outright and treat every POST as an independent request — UCP
12939
+ // servers (ucp.dev) such as the Shopify Global Catalog are the
12940
+ // motivating case. `sessionMode: 'stateless'` tells the gateway to
12941
+ // skip the initialize handshake and the per-user session cache for
12942
+ // this upstream, and to serve its tool list ONLY from a persisted
12943
+ // manifest (live discovery cannot succeed by design, and attempting
12944
+ // it would feed the health tracker until the upstream is marked
12945
+ // down). Absent means the standard MCP handshake — optional rather
12946
+ // than defaulted so the field stays optional on the inferred type
12947
+ // and pre-existing rows/fixtures parse unchanged.
12948
+ //
12949
+ // `ucpProfileUrl` is the UCP agent-profile document the gateway
12950
+ // injects as `arguments.meta["ucp-agent"].profile` on tools/call
12951
+ // when the caller didn't supply its own — UCP servers reject calls
12952
+ // without it. `safeUrl` (not a plain URL check) because the value
12953
+ // is fetched by third-party upstreams and must never point at a
12954
+ // private/internal host.
12955
+ // ─────────────────────────────────────────────────────────────────
12956
+ sessionMode: external_exports.enum(["standard", "stateless"]).optional(),
12957
+ ucpProfileUrl: safeUrl.optional(),
12113
12958
  enabled: external_exports.boolean().default(true),
12114
- healthStatus: external_exports.enum(["healthy", "degraded", "down"]).default("healthy"),
12959
+ // No default on purpose: the gateway's health-tracker persistence is a
12960
+ // v1 no-op (see apps/gateway/src/bootstrap.ts), so nothing writes real
12961
+ // status yet. A `.default('healthy')` here made every upstream render a
12962
+ // false green "Healthy" dot. `undefined` means "never checked" and
12963
+ // consumers must render a neutral "Unchecked" state for it.
12964
+ healthStatus: external_exports.enum(["healthy", "degraded", "down"]).optional(),
12115
12965
  consecutiveFailures: external_exports.number().int().min(0).default(0),
12116
12966
  // ─────────────────────────────────────────────────────────────────
12117
12967
  // v1.1 KTA Trust Layer forward-compat (see #1549)
@@ -12132,7 +12982,7 @@ var upstreamServerSchema = external_exports.object({
12132
12982
  ktaLastFetchedAt: external_exports.string().datetime().nullable().optional(),
12133
12983
  // ─────────────────────────────────────────────────────────────────
12134
12984
  // Per-upstream project lifecycle (Option A — #1566)
12135
- // Links this upstream to a dedicated AgentShield project for
12985
+ // Links this upstream to a dedicated Checkpoint project for
12136
12986
  // per-upstream detection, policy, and audit isolation.
12137
12987
  // ─────────────────────────────────────────────────────────────────
12138
12988
  projectId: external_exports.string().uuid().nullable().optional(),
@@ -12148,7 +12998,7 @@ var upstreamServerSchema = external_exports.object({
12148
12998
  // is AUTHORITATIVE — consumers prefer it and treat this copy as a hint.
12149
12999
  authorizationHost: external_exports.string().max(255).nullable().optional()
12150
13000
  });
12151
- var upstreamServerInputSchema = upstreamServerSchema.extend({
13001
+ var upstreamServerInputSchema = upstreamServerSchema.omit({ staticHeadersEncrypted: true, staticHeaderKeys: true }).extend({
12152
13002
  id: external_exports.string().uuid().optional(),
12153
13003
  slug: external_exports.string().regex(/^[a-z0-9]+(?:_[a-z0-9]+)*$/, {
12154
13004
  message: "Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)"
@@ -12742,7 +13592,9 @@ var RuleParser = class {
12742
13592
  * Validate basic rule structure
12743
13593
  */
12744
13594
  static validateStructure(rules) {
12745
- return !!(rules && typeof rules === "object" && typeof rules.version === "string" && typeof rules.lastUpdated === "string" && rules.rules && typeof rules.rules === "object");
13595
+ if (!rules || typeof rules !== "object") return false;
13596
+ const candidate = rules;
13597
+ return !!(typeof candidate.version === "string" && typeof candidate.lastUpdated === "string" && candidate.rules && typeof candidate.rules === "object");
12746
13598
  }
12747
13599
  };
12748
13600
 
@@ -12889,6 +13741,40 @@ async function loadRulesAsync(options) {
12889
13741
  return loader.loadRules(options);
12890
13742
  }
12891
13743
 
13744
+ // src/rules/vendor-range-freshness.ts
13745
+ var DEFAULT_MAX_VENDOR_RANGE_AGE_MS = 4 * 24 * 60 * 60 * 1e3;
13746
+ function findStaleVendorRanges(vendors, now, maxAgeMs = DEFAULT_MAX_VENDOR_RANGE_AGE_MS) {
13747
+ const stale = [];
13748
+ for (const v of vendors) {
13749
+ if (v.enabled === false) continue;
13750
+ const parsedMs = Date.parse(v.lastCheckedIso);
13751
+ const ageMs = Number.isNaN(parsedMs) ? Infinity : now.getTime() - parsedMs;
13752
+ if (ageMs > maxAgeMs) {
13753
+ stale.push({ id: v.id, lastCheckedIso: v.lastCheckedIso, ageMs });
13754
+ }
13755
+ }
13756
+ return stale;
13757
+ }
13758
+ var StaleVendorRangesError = class extends Error {
13759
+ constructor(stale) {
13760
+ const detail = stale.map((s) => {
13761
+ const age = s.ageMs === Infinity ? `unparseable/missing last_checked (${JSON.stringify(s.lastCheckedIso)})` : `${(s.ageMs / (24 * 60 * 60 * 1e3)).toFixed(1)}d old`;
13762
+ return `${s.id} (${age})`;
13763
+ }).join(", ");
13764
+ super(
13765
+ `${stale.length} vendor range set(s) exceeded the staleness threshold and must not be served quietly: ${detail}. Refresh has stopped keeping up for these vendors \u2014 investigate scripts/refresh-ai-vendor-ips.ts's recent runs before treating the existing data as trustworthy.`
13766
+ );
13767
+ this.stale = stale;
13768
+ this.name = "StaleVendorRangesError";
13769
+ }
13770
+ };
13771
+ function assertVendorRangesFresh(vendors, now, maxAgeMs = DEFAULT_MAX_VENDOR_RANGE_AGE_MS) {
13772
+ const stale = findStaleVendorRanges(vendors, now, maxAgeMs);
13773
+ if (stale.length > 0) {
13774
+ throw new StaleVendorRangesError(stale);
13775
+ }
13776
+ }
13777
+
12892
13778
  // src/policy/constants.ts
12893
13779
  var ENFORCEMENT_ACTIONS = {
12894
13780
  /** New canonical name for "the engine permits this request through." */
@@ -13029,7 +13915,29 @@ var BlockReasonSchema = external_exports.discriminatedUnion("kind", [
13029
13915
  // index join key). Optional + additive — absent on pre-PR2 payloads.
13030
13916
  policyId: external_exports.string().optional()
13031
13917
  }),
13032
- external_exports.object({ kind: external_exports.literal("ParseError"), detail: external_exports.string() })
13918
+ external_exports.object({
13919
+ // Tier-2 IP+UA cross-match against the vendor SSOT (AIVF-1 Path B).
13920
+ // Emitted when the request carries both a vendor-published IP and a
13921
+ // matching UA pattern. `confidence` is f32 in [0, 1] — NOT the 0-100
13922
+ // scale the rest of the detection detail uses.
13923
+ kind: external_exports.literal("AgentAttribution"),
13924
+ vendor: external_exports.string(),
13925
+ tier: external_exports.number().int(),
13926
+ confidence: external_exports.number().min(0).max(1)
13927
+ }),
13928
+ external_exports.object({ kind: external_exports.literal("ParseError"), detail: external_exports.string() }),
13929
+ external_exports.object({
13930
+ // Tier-3 UA-only pattern-match short-circuit (engine default policy).
13931
+ // Field names are snake_case ON THE WIRE (the Rust enum has no
13932
+ // `rename_all`) and mirror the Rust struct fields verbatim.
13933
+ // `pattern_kind` is `KnownAiAgent` | `AiCrawler` | `HeadlessBrowser`
13934
+ // today; kept a loose string so future engine kinds stay additive.
13935
+ // `confidence` is an integer percent (0-100), unlike AgentAttribution.
13936
+ kind: external_exports.literal("Tier3UAMatch"),
13937
+ pattern_id: external_exports.string(),
13938
+ pattern_kind: external_exports.string(),
13939
+ confidence: external_exports.number().int().min(0).max(100)
13940
+ })
13033
13941
  ]);
13034
13942
  var AssuranceTierSchema = external_exports.enum([
13035
13943
  "anonymous",
@@ -13047,7 +13955,7 @@ var ChallengeParamsSchema = external_exports.object({
13047
13955
  // draft-kya-http-02 §1/§8 — the minimum assurance tier the policy demands
13048
13956
  // of the retry, set by a Cedar `@min_assurance(...)` annotation and
13049
13957
  // advertised by the PEP as `min_assurance` in the WWW-Authenticate
13050
- // Delegation challenge. Optional + additive: absent for MCP-I L2+ handshake
13958
+ // Delegation challenge. Optional + additive: absent for KYA-OS L2+ handshake
13051
13959
  // challenges, so the DIF interop shape is unchanged when unset.
13052
13960
  minAssurance: AssuranceTierSchema.optional(),
13053
13961
  // #3272 PR2: the determining policy's authored Cedar @id. Optional + additive.
@@ -13102,9 +14010,9 @@ var ThresholdConfigSchema = external_exports.object({
13102
14010
  trustSignedRequests: external_exports.boolean().default(DEFAULT_THRESHOLDS.trustSignedRequests)
13103
14011
  });
13104
14012
  var DenyListEntrySchema = external_exports.object({
13105
- /** MCP-I client DID */
14013
+ /** KYA-OS client DID */
13106
14014
  clientDid: external_exports.string().optional(),
13107
- /** Agent DID from MCP-I identity */
14015
+ /** Agent DID from KYA-OS identity */
13108
14016
  agentDid: external_exports.string().optional(),
13109
14017
  /** Human-readable client name (e.g., "ChatGPT") */
13110
14018
  clientName: external_exports.string().optional(),
@@ -13122,9 +14030,9 @@ var DenyListEntrySchema = external_exports.object({
13122
14030
  expiresAt: external_exports.string().optional()
13123
14031
  });
13124
14032
  var AllowListEntrySchema = external_exports.object({
13125
- /** MCP-I client DID */
14033
+ /** KYA-OS client DID */
13126
14034
  clientDid: external_exports.string().optional(),
13127
- /** Agent DID from MCP-I identity */
14035
+ /** Agent DID from KYA-OS identity */
13128
14036
  agentDid: external_exports.string().optional(),
13129
14037
  /** Human-readable client name */
13130
14038
  clientName: external_exports.string().optional(),
@@ -13722,27 +14630,40 @@ function blockApplies(block, request) {
13722
14630
  }
13723
14631
  return true;
13724
14632
  }
13725
- function blockMatchesPath(block, path) {
13726
- const literals = Array.from(
14633
+ function pathLiteralsInBlock(block) {
14634
+ return Array.from(
13727
14635
  block.matchAll(cedarQuotedValueRegExp("resource\\.path (?:like|==) ", "g")),
13728
14636
  (m) => unescapeCedarString(m[1])
13729
14637
  );
14638
+ }
14639
+ function blockMatchesPath(block, path) {
14640
+ const literals = pathLiteralsInBlock(block);
13730
14641
  if (literals.length === 0) return true;
13731
14642
  return literals.some((literal) => pathLiteralMatches(literal, path));
13732
14643
  }
13733
14644
  function escapeRegExp(s) {
13734
14645
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13735
14646
  }
13736
- function blockMatchesEquality(block, attr, value) {
14647
+ function splitCedarBlocks(cedar) {
14648
+ return cedar.split(/\n\s*\n/).map((b) => b.trim()).filter((b) => b.length > 0);
14649
+ }
14650
+ function blockEqualityLiterals(block, attr) {
13737
14651
  const a = escapeRegExp(attr);
13738
- const eq = Array.from(
14652
+ return Array.from(
13739
14653
  block.matchAll(cedarQuotedValueRegExp(`${a} == `, "g")),
13740
14654
  (m) => unescapeCedarString(m[1])
13741
14655
  );
13742
- const neq = Array.from(
14656
+ }
14657
+ function blockExclusionLiterals(block, attr) {
14658
+ const a = escapeRegExp(attr);
14659
+ return Array.from(
13743
14660
  block.matchAll(cedarQuotedValueRegExp(`${a} != `, "g")),
13744
14661
  (m) => unescapeCedarString(m[1])
13745
14662
  );
14663
+ }
14664
+ function blockMatchesEquality(block, attr, value) {
14665
+ const eq = blockEqualityLiterals(block, attr);
14666
+ const neq = blockExclusionLiterals(block, attr);
13746
14667
  if (neq.includes(value)) return false;
13747
14668
  if (eq.length > 0) return eq.includes(value);
13748
14669
  return true;
@@ -13756,6 +14677,25 @@ function pathLiteralMatches(literal, path) {
13756
14677
  return false;
13757
14678
  }
13758
14679
  }
14680
+ function isForbidBlock(block) {
14681
+ return /\bforbid\s*\(/.test(block);
14682
+ }
14683
+ function narrowsPrincipal(block) {
14684
+ if (blockEqualityLiterals(block, "principal.category").length > 0) return true;
14685
+ if (blockExclusionLiterals(block, "principal.category").includes("human")) return true;
14686
+ if (blockEqualityLiterals(block, "principal.name").length > 0) return true;
14687
+ if (/principal\s+is\s+\w/.test(block)) return true;
14688
+ if (/forbid\s*\(\s*principal\s*==/.test(block)) return true;
14689
+ return false;
14690
+ }
14691
+ function isUnnarrowedDenyBlock(block) {
14692
+ return isForbidBlock(block) && !narrowsPrincipal(block);
14693
+ }
14694
+ function pathHasUnnarrowedDenyRule(cedar, path) {
14695
+ return splitCedarBlocks(cedar).some(
14696
+ (block) => isUnnarrowedDenyBlock(block) && blockMatchesPath(block, path)
14697
+ );
14698
+ }
13759
14699
 
13760
14700
  // src/policy/required-scopes.ts
13761
14701
  function requiredScopesForRequest(policySource, request) {
@@ -13791,6 +14731,54 @@ function decisionPolicyId(decision) {
13791
14731
  }
13792
14732
  }
13793
14733
 
14734
+ // src/policy/bespoke-policy.ts
14735
+ var BESPOKE_POLICY_IDS = {
14736
+ denyList: "bespoke-deny-list",
14737
+ allowList: "bespoke-allow-list",
14738
+ pathRule: "bespoke-path-rule",
14739
+ threshold: "bespoke-threshold"
14740
+ };
14741
+ var BESPOKE_POLICY_LABELS = {
14742
+ [BESPOKE_POLICY_IDS.denyList]: "Deny list",
14743
+ [BESPOKE_POLICY_IDS.allowList]: "Allow list",
14744
+ [BESPOKE_POLICY_IDS.pathRule]: "Path rule",
14745
+ [BESPOKE_POLICY_IDS.threshold]: "Confidence threshold"
14746
+ };
14747
+ var BESPOKE_POLICY_ID_SET = new Set(Object.values(BESPOKE_POLICY_IDS));
14748
+ function isBespokePolicyId(policyId) {
14749
+ return typeof policyId === "string" && BESPOKE_POLICY_ID_SET.has(policyId);
14750
+ }
14751
+ function bespokePolicyLabel(policyId) {
14752
+ return BESPOKE_POLICY_LABELS[policyId] ?? null;
14753
+ }
14754
+ var BASELINE_ALLOW_POLICY_ID = "baseline-allow";
14755
+ function isNonNavigablePolicyId(policyId) {
14756
+ return isBespokePolicyId(policyId) || policyId === BASELINE_ALLOW_POLICY_ID;
14757
+ }
14758
+ function nonNavigablePolicyLabel(policyId) {
14759
+ if (policyId === BASELINE_ALLOW_POLICY_ID) return "Default allow";
14760
+ return typeof policyId === "string" ? bespokePolicyLabel(policyId) : null;
14761
+ }
14762
+
14763
+ // src/policy/policy-lint.ts
14764
+ var UNNARROWED_DENY_MESSAGE = 'This rule denies every principal \u2014 including humans \u2014 because it does not narrow the principal. Add a `principal.category == "ai_agent"` (or `principal.name`) condition, or confirm you intend to affect humans.';
14765
+ function blockIdAnnotation(block) {
14766
+ const m = block.match(/@id\("((?:\\.|[^"\\])*)"\)/);
14767
+ return m ? m[1] : void 0;
14768
+ }
14769
+ function lintUnnarrowedDenyRules(cedar) {
14770
+ const findings = [];
14771
+ let searchFrom = 0;
14772
+ for (const block of splitCedarBlocks(cedar)) {
14773
+ if (!isUnnarrowedDenyBlock(block)) continue;
14774
+ const idx = cedar.indexOf(block, searchFrom);
14775
+ const line = idx < 0 ? 1 : cedar.slice(0, idx).split("\n").length;
14776
+ if (idx >= 0) searchFrom = idx + block.length;
14777
+ findings.push({ ruleId: blockIdAnnotation(block), line, message: UNNARROWED_DENY_MESSAGE });
14778
+ }
14779
+ return findings;
14780
+ }
14781
+
13794
14782
  // src/policy/approval-quorum.ts
13795
14783
  function approvalQuorumForRequest(policySource, request) {
13796
14784
  if (!policySource || !policySource.trim()) return null;
@@ -14128,217 +15116,408 @@ function readHeader(input, name) {
14128
15116
  }
14129
15117
  return void 0;
14130
15118
  }
14131
- function serveBodyReadable200(headers, detectionClass) {
15119
+ function serveBodyReadable200(headers, detectionClass, isAgent) {
14132
15120
  const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);
14133
15121
  if (optIn && optIn.trim().length > 0) return true;
14134
- if (detectionClass !== void 0 && detectionClass !== null) {
15122
+ if (isAgent && detectionClass !== void 0 && detectionClass !== null) {
14135
15123
  if (normalizeDetectionClassEnum(detectionClass) === "ai_agent") return true;
14136
15124
  }
14137
15125
  return false;
14138
15126
  }
14139
- function selectBodyReadable200(mode, headers, detectionClass) {
15127
+ function selectBodyReadable200(mode, headers, detectionClass, isAgent) {
14140
15128
  if (mode === "always-200") return true;
14141
- if (mode === "negotiated") return serveBodyReadable200(headers, detectionClass);
15129
+ if (mode === "negotiated") return serveBodyReadable200(headers, detectionClass, isAgent);
14142
15130
  return false;
14143
15131
  }
14144
15132
 
14145
- // src/wire/vault.ts
14146
- var vaultResolveMetaSchema = external_exports.object({
14147
- orgSlug: external_exports.string().optional(),
14148
- upstreamSlug: external_exports.string().optional()
14149
- }).strict();
14150
- var vaultResolveDataSchema = external_exports.object({
14151
- secrets: external_exports.record(external_exports.string()),
14152
- _meta: vaultResolveMetaSchema.optional()
14153
- }).strict();
14154
- var vaultResolveSuccessSchema = external_exports.object({
14155
- success: external_exports.literal(true),
14156
- data: vaultResolveDataSchema
14157
- }).strict();
14158
- var vaultResolveErrorSchema = external_exports.object({
14159
- success: external_exports.literal(false),
14160
- error: external_exports.object({
14161
- code: external_exports.string(),
14162
- message: external_exports.string(),
14163
- data: external_exports.object({
14164
- orgSlug: external_exports.string().optional(),
14165
- upstreamSlug: external_exports.string().optional(),
14166
- retryAfter: external_exports.number().optional()
14167
- }).passthrough().optional()
14168
- }).strict()
14169
- }).strict();
14170
- var vaultResolveResponseSchema = external_exports.discriminatedUnion("success", [
14171
- vaultResolveSuccessSchema,
14172
- vaultResolveErrorSchema
15133
+ // src/mcpi/kya-http-error-codes.ts
15134
+ var KYA_HTTP_ERROR = {
15135
+ // ── 401 (identity / signature) ──────────────────────────────────────────
15136
+ MISSING_SIGNATURE: "kyaos/missing-signature",
15137
+ INVALID_SIGNATURE: "kyaos/invalid-signature",
15138
+ EXPIRED: "kyaos/expired",
15139
+ REPLAY: "kyaos/replay",
15140
+ DID_UNRESOLVABLE: "kyaos/did-unresolvable",
15141
+ AUTHORIZATION_REQUIRED: "kyaos/authorization-required",
15142
+ // ── 403 (delegation / profile) ──────────────────────────────────────────
15143
+ PROFILE_VIOLATION: "kyaos/profile-violation",
15144
+ DELEGATION_REVOKED: "kyaos/delegation-revoked",
15145
+ SCOPE_INSUFFICIENT: "kyaos/scope-insufficient",
15146
+ CHAIN_BROKEN: "kyaos/chain-broken",
15147
+ HOLDER_MISMATCH: "kyaos/holder-mismatch",
15148
+ AUDIENCE_MISMATCH: "kyaos/audience-mismatch",
15149
+ SESSION_MISMATCH: "kyaos/session-mismatch",
15150
+ PICKUP_PINNED: "kyaos/pickup-pinned",
15151
+ // Credential verified but its achieved assurance tier is below the
15152
+ // determining policy's opt-in `@min_assurance` floor (trust-gap G3) — a
15153
+ // bearer credential (attested-bearer, no proof-of-possession) cannot satisfy
15154
+ // a key-bound+ floor. Recovery: a key-bound signed request, not a new
15155
+ // credential.
15156
+ ASSURANCE_INSUFFICIENT: "kyaos/assurance-insufficient",
15157
+ // ── 503 (revocation status unverifiable — RETRYABLE) ─────────────────────
15158
+ // Emitted when a credential DECLARES a `credentialStatus` but its status list
15159
+ // was not supplied / could not be fetched (cold cache, past the 300s status
15160
+ // cap). Fail-closed but retryable: a warmed list may yet verify (#3345 / #3446).
15161
+ STATUS_PENDING: "kyaos/status-pending",
15162
+ // ── pickup flow (404 / 410) ─────────────────────────────────────────────
15163
+ INVALID_SESSION: "kyaos/invalid-session",
15164
+ PICKUP_EXPIRED: "kyaos/pickup-expired"
15165
+ };
15166
+
15167
+ // src/host-adapter/challenge-wire.ts
15168
+ var PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
15169
+ var DEFAULT_POLL_INTERVAL_S = 3;
15170
+ var INVALID_QUOTED_VALUE = /[\u0000-\u001f\u007f"\\]/;
15171
+ var SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
15172
+ var SID = /^kya-[0-9a-f]{16,}$/;
15173
+ var ASSURANCE_TIERS = /* @__PURE__ */ new Set([
15174
+ "anonymous",
15175
+ "attested-bearer",
15176
+ "key-bound",
15177
+ "registered",
15178
+ "delegated"
14173
15179
  ]);
14174
- function canonicalSigningPayload(payload) {
14175
- const json = canonicalize__default.default(payload);
14176
- if (json === void 0) {
14177
- throw new Error("canonicalSigningPayload: payload contains non-serializable values");
14178
- }
14179
- return new TextEncoder().encode(json);
14180
- }
14181
- var REQUIRED_STRING_FIELDS = [
14182
- "aud",
14183
- "iss",
14184
- "sub",
14185
- "nonce",
14186
- "sessionId",
14187
- "requestHash",
14188
- "responseHash"
14189
- ];
14190
- function validateMcpIPayload(value) {
14191
- if (value === null || typeof value !== "object") {
14192
- throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
15180
+ var ChallengeWireError = class extends TypeError {
15181
+ code;
15182
+ constructor(code, message) {
15183
+ super(message);
15184
+ this.name = "ChallengeWireError";
15185
+ this.code = code;
14193
15186
  }
14194
- const obj = value;
14195
- for (const field of REQUIRED_STRING_FIELDS) {
14196
- if (typeof obj[field] !== "string") {
14197
- throw new Error(`missing or non-string required field "${field}" (got ${typeof obj[field]})`);
14198
- }
15187
+ };
15188
+ function generateDelegationSid() {
15189
+ const bytes = new Uint8Array(16);
15190
+ crypto.getRandomValues(bytes);
15191
+ let hex = "";
15192
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
15193
+ return `kya-${hex}`;
15194
+ }
15195
+ function deriveDelegationPickupUri(consentUri, sid) {
15196
+ const consent = parseHttpsUrl("consentUri", consentUri);
15197
+ assertQuotedValue("sid", sid, "invalid-sid");
15198
+ return `${consent.origin}/api/delegation/pickup/${sid}`;
15199
+ }
15200
+ function buildDelegationChallengeHeader(input) {
15201
+ const normalized = validateInput(input);
15202
+ const params = [
15203
+ ["realm", normalized.realm],
15204
+ ["sid", normalized.sid],
15205
+ ["consent_uri", normalized.consentUri],
15206
+ ["pickup_uri", normalized.pickupUri]
15207
+ ];
15208
+ if (normalized.requiredScopes.length > 0) {
15209
+ params.push(["scope", normalized.requiredScopes.join(" ")]);
14199
15210
  }
14200
- if (typeof obj.ts !== "number" || !Number.isFinite(obj.ts)) {
14201
- throw new Error(`missing or non-finite-number required field "ts" (got ${typeof obj.ts})`);
15211
+ if (normalized.minAssurance) {
15212
+ params.push(["min_assurance", normalized.minAssurance]);
14202
15213
  }
14203
- return obj;
14204
- }
14205
- var ED25519_MULTICODEC_PREFIX = new Uint8Array([237, 1]);
14206
- async function parseSigningKey(seed) {
14207
- if (seed.length !== 32) {
14208
- throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);
15214
+ if (input.pollIntervalS !== void 0) {
15215
+ params.push(["interval", String(normalized.pollIntervalS)]);
14209
15216
  }
14210
- const publicKey = await ed25519.getPublicKeyAsync(seed);
14211
- const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);
14212
- multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);
14213
- multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);
14214
- const multibase = base58.base58btc.encode(multibaseBytes);
14215
- const did = `did:key:${multibase}`;
14216
- return {
14217
- // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1
14218
- // tests assert that mutating the input seed after this call does NOT
14219
- // mutate the held key material.
14220
- signingKey: Uint8Array.from(seed),
14221
- publicKey,
14222
- did,
14223
- // mcp-i-core PR #16: the verification-method id is the multibase value
14224
- // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's
14225
- // stage2_did_key_fragment_resolution.
14226
- kid: `${did}#${multibase}`
14227
- };
15217
+ params.push(["kind", normalized.kind]);
15218
+ return `Delegation ${params.map(([name, value]) => `${name}="${value}"`).join(", ")}`;
14228
15219
  }
14229
- function base64UrlEncode(bytes) {
14230
- return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
15220
+ function buildDelegationBearerHeader(realm) {
15221
+ assertRealm(realm);
15222
+ return `Bearer resource_metadata="https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}"`;
14231
15223
  }
14232
- async function signMcpiEnvelope(payload, key) {
14233
- const header = { alg: "EdDSA", kid: key.kid };
14234
- const headerJson = JSON.stringify(header);
14235
- const headerB64 = base64UrlEncode(new TextEncoder().encode(headerJson));
14236
- const payloadB64 = base64UrlEncode(canonicalSigningPayload(payload));
14237
- const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
14238
- const signature = await ed25519.signAsync(signingInput, key.signingKey);
14239
- const signatureB64 = base64UrlEncode(signature);
14240
- return `${headerB64}.${payloadB64}.${signatureB64}`;
15224
+ function buildDelegationInstructions(consentUri, pickupUri, pollIntervalS) {
15225
+ return `This action requires human authorization. Show your user this link and ask them to approve: ${consentUri}. Then poll ${pickupUri} every ${pollIntervalS} seconds. If you can sign HTTP requests, sign each poll with an ephemeral did:key; otherwise generate one random 32-byte token and send it as X-KYA-Pickup-Token on EVERY poll. When the response status is 200, take the 'delegation' value and retry your original request with header 'Authorization: Bearer <delegation>'.`;
14241
15226
  }
14242
-
14243
- // src/canonical-signer/parse.ts
14244
- var JwsParseError = class extends Error {
14245
- constructor(code, message) {
14246
- super(message);
14247
- this.code = code;
14248
- this.name = "JwsParseError";
14249
- }
14250
- };
14251
- function validateJwsHeader(value) {
14252
- if (value === null || typeof value !== "object") {
14253
- throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
15227
+ function buildDelegationChallengeBody(input) {
15228
+ const normalized = validateInput(input);
15229
+ const common = {
15230
+ sid: normalized.sid,
15231
+ consent_uri: normalized.consentUri,
15232
+ pickup_uri: normalized.pickupUri,
15233
+ ...normalized.requiredScopes.length > 0 ? { required_scopes: [...normalized.requiredScopes] } : {},
15234
+ ...normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {},
15235
+ poll_interval_s: normalized.pollIntervalS,
15236
+ challenge_proof: input.challengeProof
15237
+ };
15238
+ if (normalized.kind === "approval_quorum") {
15239
+ return {
15240
+ error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
15241
+ kyaos: {
15242
+ sid: common.sid,
15243
+ kind: "approval_quorum",
15244
+ quorum: normalized.quorum,
15245
+ action_nonce: normalized.actionNonce,
15246
+ consent_uri: common.consent_uri,
15247
+ pickup_uri: common.pickup_uri,
15248
+ ...common.required_scopes ? { required_scopes: common.required_scopes } : {},
15249
+ ...common.min_assurance ? { min_assurance: common.min_assurance } : {},
15250
+ poll_interval_s: common.poll_interval_s,
15251
+ challenge_proof: common.challenge_proof
15252
+ },
15253
+ instructions: buildApprovalQuorumInstructions(normalized)
15254
+ };
14254
15255
  }
14255
- const obj = value;
14256
- if (typeof obj.alg !== "string" || obj.alg.length === 0) {
14257
- throw new Error(`missing or non-string required field "alg" (got ${typeof obj.alg})`);
15256
+ return {
15257
+ error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
15258
+ kyaos: {
15259
+ ...common,
15260
+ action: {
15261
+ type: "delegation",
15262
+ consent_uri: normalized.consentUri,
15263
+ pickup_uri: normalized.pickupUri,
15264
+ poll_interval_s: normalized.pollIntervalS,
15265
+ pin: { header: "X-KYA-Pickup-Token" },
15266
+ retry: { header: "Authorization", scheme: "Bearer", value_from: "delegation" }
15267
+ }
15268
+ },
15269
+ instructions: buildDelegationInstructions(
15270
+ normalized.consentUri,
15271
+ normalized.pickupUri,
15272
+ normalized.pollIntervalS
15273
+ )
15274
+ };
15275
+ }
15276
+ function buildDelegationChallengeEnvelope(input, mode = "spec-401") {
15277
+ const normalized = validateInput(input);
15278
+ if (normalized.kind === "approval_quorum" && mode === "fetcher-200") {
15279
+ throw new ChallengeWireError(
15280
+ "unsupported-envelope",
15281
+ "fetcher-200 is not fixture-defined for approval_quorum"
15282
+ );
14258
15283
  }
14259
- if (typeof obj.kid !== "string" || obj.kid.length === 0) {
14260
- throw new Error(`missing or non-string required field "kid" (got ${typeof obj.kid})`);
15284
+ const body = buildDelegationChallengeBody(input);
15285
+ if (normalized.kind === "approval_quorum") {
15286
+ return {
15287
+ status: 401,
15288
+ headers: [
15289
+ ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
15290
+ ["Retry-After", String(normalized.pollIntervalS)],
15291
+ ["Content-Type", "application/json"],
15292
+ ["Cache-Control", "no-store"]
15293
+ ],
15294
+ body
15295
+ };
14261
15296
  }
14262
- if (obj.typ !== void 0 && typeof obj.typ !== "string") {
14263
- throw new Error(`optional field "typ" must be a string when present (got ${typeof obj.typ})`);
15297
+ const hintHeaders = [
15298
+ ["Content-Type", "application/json"],
15299
+ ["Cache-Control", "no-store"],
15300
+ ["KYA-Auth-Required", "true"],
15301
+ ["KYA-Auth-Url", normalized.consentUri],
15302
+ ["Link", `<${normalized.consentUri}>; rel="kya-authorize"`],
15303
+ ["KYA-Action", "challenge"]
15304
+ ];
15305
+ if (mode === "fetcher-200") {
15306
+ return { status: 200, headers: hintHeaders, body };
14264
15307
  }
14265
- return obj;
15308
+ return {
15309
+ status: 401,
15310
+ headers: [
15311
+ ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
15312
+ ["WWW-Authenticate", `Bearer resource_metadata="${normalized.resourceMetadataUri}"`],
15313
+ ["Retry-After", String(normalized.pollIntervalS)],
15314
+ ...hintHeaders
15315
+ ],
15316
+ body
15317
+ };
14266
15318
  }
14267
- function parseJwsCompact(jws) {
14268
- const parts = jws.split(".");
14269
- if (parts.length !== 3) {
14270
- throw new JwsParseError(
14271
- "WrongSegmentCount",
14272
- `Expected 3 dot-separated segments per RFC 7515 \xA7 3.1; got ${parts.length}`
15319
+ var buildChallengeWire = buildDelegationChallengeEnvelope;
15320
+ function validateInput(input) {
15321
+ assertRealm(input.realm);
15322
+ assertQuotedValue("sid", input.sid, "invalid-sid");
15323
+ if (!SID.test(input.sid)) {
15324
+ throw new ChallengeWireError(
15325
+ "invalid-sid",
15326
+ "sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy"
14273
15327
  );
14274
15328
  }
14275
- const [headerB64, payloadB64, signatureB64] = parts;
14276
- let headerJson;
14277
- try {
14278
- headerJson = JSON.parse(base64UrlDecodeToString(headerB64));
14279
- } catch (cause) {
14280
- throw new JwsParseError("InvalidJson", `JWS header is not valid JSON: ${String(cause)}`);
15329
+ const consent = parseHttpsUrl("consentUri", input.consentUri);
15330
+ const pickup = parseHttpsUrl("pickupUri", input.pickupUri);
15331
+ const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;
15332
+ if (pickup.href !== expectedPickup) {
15333
+ throw new ChallengeWireError(
15334
+ "invalid-uri",
15335
+ "pickupUri must use the registered consent origin and sid"
15336
+ );
14281
15337
  }
14282
- let validatedHeader;
14283
- try {
14284
- validatedHeader = validateJwsHeader(headerJson);
14285
- } catch (cause) {
14286
- throw new JwsParseError(
14287
- "InvalidHeaderShape",
14288
- `JWS header does not match expected shape: ${cause.message}`
15338
+ const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;
15339
+ if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) {
15340
+ throw new ChallengeWireError(
15341
+ "invalid-interval",
15342
+ "pollIntervalS must be an integer from 1 through 999"
14289
15343
  );
14290
15344
  }
14291
- if (validatedHeader.alg !== "EdDSA") {
14292
- throw new JwsParseError(
14293
- "UnsupportedAlgorithm",
14294
- `Unsupported JWS alg "${validatedHeader.alg}"; Phase 1 only supports EdDSA`
15345
+ if (input.challengeProof === void 0 || input.challengeProof === null) {
15346
+ throw new ChallengeWireError("invalid-proof", "challengeProof is required");
15347
+ }
15348
+ const requiredScopes = input.requiredScopes ?? [];
15349
+ for (const scope of requiredScopes) {
15350
+ if (!SCOPE_TOKEN.test(scope)) {
15351
+ throw new ChallengeWireError("invalid-scope", `invalid required scope: ${scope}`);
15352
+ }
15353
+ }
15354
+ if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) {
15355
+ throw new ChallengeWireError(
15356
+ "invalid-assurance",
15357
+ `invalid minAssurance: ${input.minAssurance}`
14295
15358
  );
14296
15359
  }
14297
- const header = {
14298
- alg: "EdDSA",
14299
- kid: validatedHeader.kid,
14300
- ...validatedHeader.typ !== void 0 ? { typ: validatedHeader.typ } : {}
15360
+ const kind = input.kind ?? "delegation";
15361
+ if (kind !== "delegation" && kind !== "approval_quorum") {
15362
+ throw new ChallengeWireError("invalid-kind", `unsupported challenge kind: ${String(kind)}`);
15363
+ }
15364
+ let resourceMetadataUri;
15365
+ let quorum;
15366
+ let actionNonce;
15367
+ if (kind === "delegation") {
15368
+ resourceMetadataUri = parseHttpsUrl(
15369
+ "resourceMetadataUri",
15370
+ input.resourceMetadataUri
15371
+ ).href;
15372
+ const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;
15373
+ if (resourceMetadataUri !== expectedMetadata) {
15374
+ throw new ChallengeWireError(
15375
+ "invalid-uri",
15376
+ "resourceMetadataUri must be the protected resource RFC 9728 metadata URL"
15377
+ );
15378
+ }
15379
+ } else {
15380
+ const approval = input;
15381
+ quorum = approval.quorum;
15382
+ actionNonce = approval.actionNonce;
15383
+ if (!Number.isInteger(quorum) || quorum < 1) {
15384
+ throw new ChallengeWireError("invalid-quorum", "quorum must be a positive integer");
15385
+ }
15386
+ assertQuotedValue("actionNonce", actionNonce, "invalid-action-nonce");
15387
+ }
15388
+ return {
15389
+ realm: input.realm,
15390
+ sid: input.sid,
15391
+ consentUri: consent.href,
15392
+ pickupUri: pickup.href,
15393
+ resourceMetadataUri,
15394
+ requiredScopes,
15395
+ pollIntervalS,
15396
+ minAssurance: input.minAssurance,
15397
+ kind,
15398
+ quorum,
15399
+ actionNonce
14301
15400
  };
14302
- let payloadJson;
14303
- try {
14304
- payloadJson = JSON.parse(base64UrlDecodeToString(payloadB64));
14305
- } catch (cause) {
14306
- throw new JwsParseError("InvalidJson", `JWS payload is not valid JSON: ${String(cause)}`);
15401
+ }
15402
+ function buildApprovalQuorumInstructions(input) {
15403
+ return `This action requires approval from ${input.quorum} human approvers. Show your user this link to begin the approval process: ${input.consentUri}. Then poll ${input.pickupUri} every ${input.pollIntervalS} seconds (sign polls with an ephemeral did:key, or send one random 32-byte X-KYA-Pickup-Token on EVERY poll). When the response status is 200, retry your original request presenting the returned grants in the KYA-Approvals header.`;
15404
+ }
15405
+ function assertRealm(realm) {
15406
+ assertQuotedValue("realm", realm, "invalid-realm");
15407
+ if (realm.includes("/") || realm.includes("@") || realm.includes("?") || realm.includes("#")) {
15408
+ throw new ChallengeWireError("invalid-realm", "realm must be a host with an optional port");
14307
15409
  }
14308
- let payload;
14309
15410
  try {
14310
- payload = validateMcpIPayload(payloadJson);
14311
- } catch (cause) {
14312
- throw new JwsParseError(
14313
- "InvalidPayloadShape",
14314
- `JWS payload does not match McpIPayload shape: ${cause.message}`
15411
+ const parsed = new URL(`https://${realm}`);
15412
+ if (parsed.host !== realm) throw new Error("invalid authority");
15413
+ } catch {
15414
+ throw new ChallengeWireError(
15415
+ "invalid-realm",
15416
+ "realm must be a valid host with an optional port"
14315
15417
  );
14316
15418
  }
14317
- if (!BASE64URL_ALPHABET.test(signatureB64)) {
14318
- throw new JwsParseError(
14319
- "InvalidBase64",
14320
- `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 \xA7 5)`
15419
+ }
15420
+ function assertQuotedValue(name, value, code) {
15421
+ if (typeof value !== "string" || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) {
15422
+ throw new ChallengeWireError(
15423
+ code,
15424
+ `${name} contains characters unsafe for an HTTP quoted-string`
14321
15425
  );
14322
15426
  }
14323
- const signatureBytes = base64UrlDecodeToBytes(signatureB64);
14324
- if (signatureBytes.length !== 64) {
14325
- throw new JwsParseError(
14326
- "InvalidSignatureLength",
14327
- `Ed25519 signatures are 64 bytes (RFC 8032 \xA7 5.1.6); got ${signatureBytes.length}`
15427
+ }
15428
+ function parseHttpsUrl(name, value) {
15429
+ assertQuotedValue(name, value, "invalid-uri");
15430
+ let parsed;
15431
+ try {
15432
+ parsed = new URL(value);
15433
+ } catch {
15434
+ throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL`);
15435
+ }
15436
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
15437
+ throw new ChallengeWireError(
15438
+ "invalid-uri",
15439
+ `${name} must be an absolute HTTPS URL without credentials`
14328
15440
  );
14329
15441
  }
14330
- const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
14331
- return { header, payload, signatureBytes, signingInput };
14332
- }
14333
- var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;
14334
- function base64UrlDecodeToBytes(s) {
14335
- const padded = s.replace(/-/g, "+").replace(/_/g, "/");
14336
- const padLen = padded.length % 4 === 0 ? 0 : 4 - padded.length % 4;
14337
- return new Uint8Array(Buffer.from(padded + "=".repeat(padLen), "base64"));
15442
+ return parsed;
14338
15443
  }
14339
- function base64UrlDecodeToString(s) {
14340
- return Buffer.from(base64UrlDecodeToBytes(s)).toString("utf-8");
15444
+
15445
+ // src/host-adapter/challenge-context.ts
15446
+ var DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3e3;
15447
+ async function resolveChallengeContext(resolver, context, options = {}) {
15448
+ if (!resolver) return void 0;
15449
+ const timeoutMs = options.timeoutMs ?? DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;
15450
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1) {
15451
+ throw new TypeError("challenge context timeout must be a positive integer");
15452
+ }
15453
+ let timeoutId;
15454
+ try {
15455
+ const value = await Promise.race([
15456
+ Promise.resolve(resolver(context)),
15457
+ new Promise((_resolve, reject) => {
15458
+ timeoutId = setTimeout(
15459
+ () => reject(new ChallengeContextTimeoutError(timeoutMs)),
15460
+ timeoutMs
15461
+ );
15462
+ })
15463
+ ]);
15464
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
15465
+ if (!value) return void 0;
15466
+ try {
15467
+ buildChallengeWire(value, "spec-401");
15468
+ return value;
15469
+ } catch (error) {
15470
+ options.onFailure?.({
15471
+ reason: "invalid-context",
15472
+ message: error.message
15473
+ });
15474
+ return void 0;
15475
+ }
15476
+ } catch (error) {
15477
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
15478
+ options.onFailure?.({
15479
+ reason: error instanceof ChallengeContextTimeoutError ? "timeout" : "resolver-error",
15480
+ message: error instanceof ChallengeContextTimeoutError ? error.message : "challenge context resolver failed"
15481
+ });
15482
+ return void 0;
15483
+ }
14341
15484
  }
15485
+ var ChallengeContextTimeoutError = class extends Error {
15486
+ constructor(timeoutMs) {
15487
+ super(`challenge context resolution exceeded ${timeoutMs}ms`);
15488
+ this.name = "ChallengeContextTimeoutError";
15489
+ }
15490
+ };
15491
+
15492
+ // src/wire/vault.ts
15493
+ var vaultResolveMetaSchema = external_exports.object({
15494
+ orgSlug: external_exports.string().optional(),
15495
+ upstreamSlug: external_exports.string().optional()
15496
+ }).strict();
15497
+ var vaultResolveDataSchema = external_exports.object({
15498
+ secrets: external_exports.record(external_exports.string()),
15499
+ _meta: vaultResolveMetaSchema.optional()
15500
+ }).strict();
15501
+ var vaultResolveSuccessSchema = external_exports.object({
15502
+ success: external_exports.literal(true),
15503
+ data: vaultResolveDataSchema
15504
+ }).strict();
15505
+ var vaultResolveErrorSchema = external_exports.object({
15506
+ success: external_exports.literal(false),
15507
+ error: external_exports.object({
15508
+ code: external_exports.string(),
15509
+ message: external_exports.string(),
15510
+ data: external_exports.object({
15511
+ orgSlug: external_exports.string().optional(),
15512
+ upstreamSlug: external_exports.string().optional(),
15513
+ retryAfter: external_exports.number().optional()
15514
+ }).passthrough().optional()
15515
+ }).strict()
15516
+ }).strict();
15517
+ var vaultResolveResponseSchema = external_exports.discriminatedUnion("success", [
15518
+ vaultResolveSuccessSchema,
15519
+ vaultResolveErrorSchema
15520
+ ]);
14342
15521
 
14343
15522
  // src/mcpi/org-did.ts
14344
15523
  var MCPI_ORG_DID_HOST = "kya.vouched.id";
@@ -14385,24 +15564,51 @@ function requestCarriesDelegationProof(headers) {
14385
15564
  }
14386
15565
  return DELEGATION_PROOF_HEADERS.some((name) => isPresent(lowerKeyed.get(name)));
14387
15566
  }
14388
-
14389
- // src/mcpi/principal.ts
14390
15567
  var ANONYMOUS_PRINCIPAL_DID = "did:web:kya.vouched.id:principals:anonymous";
14391
15568
  var MCP_CLIENT_DID_HOST = "knowthat.ai";
14392
15569
  var CLIENT_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;
15570
+ var CIMD_FALLBACK_PREFIX = "cimd-";
15571
+ var CIMD_CLIENT_SLUGS = {
15572
+ "https://claude.ai/oauth/claude-code-client-metadata": "claude-code",
15573
+ "https://vscode.dev/oauth/client-metadata.json": "vscode"
15574
+ };
15575
+ var RESERVED_CIMD_SLUGS = new Set(Object.values(CIMD_CLIENT_SLUGS));
14393
15576
  function deriveMcpClientDid(clientId) {
14394
- if (!CLIENT_ID_PATTERN.test(clientId)) {
15577
+ const cimdUrl = tryParseUrl(clientId);
15578
+ const slug = cimdUrl ? slugForCimdUrl(cimdUrl, clientId) : clientId;
15579
+ if (!CLIENT_ID_PATTERN.test(slug)) {
14395
15580
  throw new Error(`Invalid client id for did:web derivation: ${JSON.stringify(clientId)}`);
14396
15581
  }
14397
- return `did:web:${MCP_CLIENT_DID_HOST}:clients:${clientId}`;
15582
+ if (!cimdUrl && RESERVED_CIMD_SLUGS.has(slug)) {
15583
+ throw new Error(`Reserved CIMD client slug, cannot use as an opaque client id: ${slug}`);
15584
+ }
15585
+ return `did:web:${MCP_CLIENT_DID_HOST}:clients:${slug}`;
15586
+ }
15587
+ function tryParseUrl(value) {
15588
+ try {
15589
+ return new URL(value);
15590
+ } catch {
15591
+ return null;
15592
+ }
15593
+ }
15594
+ function slugForCimdUrl(url, originalClientId) {
15595
+ if (url.protocol !== "https:" || url.pathname === "" || url.pathname === "/") {
15596
+ throw new Error(
15597
+ `Invalid client id for did:web derivation: ${JSON.stringify(originalClientId)}`
15598
+ );
15599
+ }
15600
+ const known = CIMD_CLIENT_SLUGS[originalClientId];
15601
+ if (known) return known;
15602
+ const digest = utils_js.bytesToHex(sha2_js.sha256(new TextEncoder().encode(originalClientId)));
15603
+ return `${CIMD_FALLBACK_PREFIX}${digest.slice(0, 32)}`;
14398
15604
  }
14399
15605
 
14400
15606
  // src/mcpi/reported-identity.ts
14401
- var DidStringSchema = external_exports.string().trim().min(1).regex(/^did:/, "must be a DID (did:web / did:key)");
15607
+ var DidStringSchema2 = external_exports.string().trim().min(1).regex(/^did:/, "must be a DID (did:web / did:key)");
14402
15608
  var NonEmptyTrimmed = external_exports.string().trim().min(1);
14403
15609
  var ReportedAgentSchema = external_exports.object({
14404
15610
  /** The agent's own DID, when it has one (enterprise A2A / provisioned). */
14405
- did: DidStringSchema.optional(),
15611
+ did: DidStringSchema2.optional(),
14406
15612
  /**
14407
15613
  * OAuth `client_id` of an authenticated MCP client. Checkpoint derives the
14408
15614
  * canonical `did:web` from this (DR-9 `deriveMcpClientDid`); the reporter
@@ -14420,7 +15626,7 @@ var ReportedAgentSchema = external_exports.object({
14420
15626
  }).describe("Asserted identity of the acting agent");
14421
15627
  var ReportedPrincipalSchema = external_exports.object({
14422
15628
  /** The principal's DID (the delegation issuer, typically). */
14423
- did: DidStringSchema.optional(),
15629
+ did: DidStringSchema2.optional(),
14424
15630
  /** Issuer-local subject identifier, when the principal has no DID. */
14425
15631
  sub: NonEmptyTrimmed.optional(),
14426
15632
  /** Optional display email. Never the identity key — `did`/`sub` are. */
@@ -14432,9 +15638,9 @@ var ReportedDelegationSchema = external_exports.object({
14432
15638
  /** Delegation credential id — the join key into `delegations`. */
14433
15639
  jti: NonEmptyTrimmed.optional(),
14434
15640
  /** Issuer DID (usually the principal). */
14435
- iss: DidStringSchema.optional(),
15641
+ iss: DidStringSchema2.optional(),
14436
15642
  /** Audience DID (the intended verifier / resource). */
14437
- aud: DidStringSchema.optional(),
15643
+ aud: DidStringSchema2.optional(),
14438
15644
  /** Granted capabilities, e.g. `['vault:read']`. */
14439
15645
  capabilities: external_exports.array(NonEmptyTrimmed).optional(),
14440
15646
  /** Expiry, unix seconds. */
@@ -14448,7 +15654,7 @@ var ReportedIdentitySchema = external_exports.object({
14448
15654
  agent: ReportedAgentSchema.optional(),
14449
15655
  principal: ReportedPrincipalSchema.optional(),
14450
15656
  delegation: ReportedDelegationSchema.optional()
14451
- }).describe("MCP-I reported identity (verifier \u2192 observability plane)");
15657
+ }).describe("KYA-OS reported identity (verifier \u2192 observability plane)");
14452
15658
 
14453
15659
  // src/mcpi/did-key.ts
14454
15660
  var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -14537,28 +15743,105 @@ function encodeDidKeyEd25519(publicKey) {
14537
15743
  return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;
14538
15744
  }
14539
15745
 
14540
- // src/mcpi/kya-http-error-codes.ts
14541
- var KYA_HTTP_ERROR = {
14542
- // ── 401 (identity / signature) ──────────────────────────────────────────
14543
- MISSING_SIGNATURE: "kyaos/missing-signature",
14544
- INVALID_SIGNATURE: "kyaos/invalid-signature",
14545
- EXPIRED: "kyaos/expired",
14546
- REPLAY: "kyaos/replay",
14547
- DID_UNRESOLVABLE: "kyaos/did-unresolvable",
14548
- AUTHORIZATION_REQUIRED: "kyaos/authorization-required",
14549
- // ── 403 (delegation / profile) ──────────────────────────────────────────
14550
- PROFILE_VIOLATION: "kyaos/profile-violation",
14551
- DELEGATION_REVOKED: "kyaos/delegation-revoked",
14552
- SCOPE_INSUFFICIENT: "kyaos/scope-insufficient",
14553
- CHAIN_BROKEN: "kyaos/chain-broken",
14554
- HOLDER_MISMATCH: "kyaos/holder-mismatch",
14555
- AUDIENCE_MISMATCH: "kyaos/audience-mismatch",
14556
- SESSION_MISMATCH: "kyaos/session-mismatch",
14557
- PICKUP_PINNED: "kyaos/pickup-pinned",
14558
- // ── pickup flow (404 / 410) ─────────────────────────────────────────────
14559
- INVALID_SESSION: "kyaos/invalid-session",
14560
- PICKUP_EXPIRED: "kyaos/pickup-expired"
15746
+ // src/mcpi/multibase-ed25519.ts
15747
+ var ED25519_PUB_MULTICODEC = [237, 1];
15748
+ var ED25519_PUBKEY_LENGTH2 = 32;
15749
+ var ED25519_MULTIKEY_LENGTH2 = ED25519_PUB_MULTICODEC.length + ED25519_PUBKEY_LENGTH2;
15750
+ var MAX_ED25519_KEY_BODY_LENGTH = 64;
15751
+ function base64AnyToBytes(body) {
15752
+ if (body.length === 0) return null;
15753
+ let normalized = body.replace(/-/g, "+").replace(/_/g, "/");
15754
+ const remainder = normalized.length % 4;
15755
+ if (remainder === 1) return null;
15756
+ if (remainder === 2) normalized += "==";
15757
+ else if (remainder === 3) normalized += "=";
15758
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return null;
15759
+ try {
15760
+ const bin = atob(normalized);
15761
+ const out = new Uint8Array(bin.length);
15762
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
15763
+ return out;
15764
+ } catch {
15765
+ return null;
15766
+ }
15767
+ }
15768
+ function toRawEd25519Key(decoded) {
15769
+ if (decoded.length === ED25519_PUBKEY_LENGTH2) return decoded;
15770
+ if (decoded.length === ED25519_MULTIKEY_LENGTH2 && decoded[0] === ED25519_PUB_MULTICODEC[0] && decoded[1] === ED25519_PUB_MULTICODEC[1]) {
15771
+ return decoded.slice(ED25519_PUB_MULTICODEC.length);
15772
+ }
15773
+ return null;
15774
+ }
15775
+ function decodeEd25519PublicKeyMultibaseTolerant(mb) {
15776
+ if (typeof mb !== "string" || mb.length < 2) return null;
15777
+ const prefix = mb[0];
15778
+ const body = mb.slice(1);
15779
+ if (body.length > MAX_ED25519_KEY_BODY_LENGTH) return null;
15780
+ let decoded;
15781
+ if (prefix === "z") {
15782
+ decoded = base58btcDecode(body);
15783
+ } else if (prefix === "m" || prefix === "u") {
15784
+ decoded = base64AnyToBytes(body);
15785
+ } else {
15786
+ return null;
15787
+ }
15788
+ if (!decoded) return null;
15789
+ return toRawEd25519Key(decoded);
15790
+ }
15791
+ function encodeEd25519PublicKeyMultibase(rawPubKey) {
15792
+ if (rawPubKey.length !== ED25519_PUBKEY_LENGTH2) {
15793
+ throw new Error(
15794
+ `Ed25519 public key must be ${ED25519_PUBKEY_LENGTH2} bytes, got ${rawPubKey.length}`
15795
+ );
15796
+ }
15797
+ const prefixed = new Uint8Array(ED25519_MULTIKEY_LENGTH2);
15798
+ prefixed[0] = ED25519_PUB_MULTICODEC[0];
15799
+ prefixed[1] = ED25519_PUB_MULTICODEC[1];
15800
+ prefixed.set(rawPubKey, ED25519_PUB_MULTICODEC.length);
15801
+ return "z" + base58btcEncode(prefixed);
15802
+ }
15803
+
15804
+ // src/mcpi/delegation-verdict.ts
15805
+ var REASON_KIND_MAP = {
15806
+ // --- gateway: apps/gateway/src/lib/mcpi-auth-resolver.ts ---
15807
+ missing_bearer_token: "claim",
15808
+ parse_error: "claim",
15809
+ did_resolve_failed: "resolve",
15810
+ signature_invalid: "signature",
15811
+ audience_mismatch: "claim",
15812
+ expired: "time",
15813
+ not_yet_valid: "time",
15814
+ revoked: "revocation",
15815
+ delegation_inactive: "revocation",
15816
+ missing_claim: "claim",
15817
+ claim_invalid: "claim",
15818
+ // --- gateway: apps/gateway/src/lib/dashboard-delegation-verifier.ts ---
15819
+ not_configured: "claim",
15820
+ header_missing: "claim",
15821
+ claim_mismatch: "claim",
15822
+ malformed: "claim",
15823
+ // --- engine-rust: rust/crates/kya-os-engine/src/types.rs BlockReason ---
15824
+ Revoked: "revocation",
15825
+ InvalidSignature: "signature",
15826
+ Unauthenticated: "claim",
15827
+ Expired: "time",
15828
+ OutOfScope: "scope"
14561
15829
  };
15830
+ function toCoarseReasonKind(rawReasonKind) {
15831
+ const coarse = REASON_KIND_MAP[rawReasonKind];
15832
+ if (!coarse) {
15833
+ throw new Error(
15834
+ `toCoarseReasonKind: unrecognized raw reason kind ${JSON.stringify(rawReasonKind)} \u2014 add it to REASON_KIND_MAP in delegation-verdict.ts with a deliberate coarse classification`
15835
+ );
15836
+ }
15837
+ return coarse;
15838
+ }
15839
+ function permitDelegationVerdict() {
15840
+ return { kind: "Permit", reason: null };
15841
+ }
15842
+ function blockDelegationVerdict(rawReasonKind) {
15843
+ return { kind: "Block", reason: { kind: toCoarseReasonKind(rawReasonKind) } };
15844
+ }
14562
15845
 
14563
15846
  // src/parsers/jafar.ts
14564
15847
  var IPV4_CIDR_RE = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\/(?:3[0-2]|[12]?\d)$/;
@@ -14649,11 +15932,18 @@ Object.defineProperty(exports, "validateProviderDefinition", {
14649
15932
  get: function () { return providerRegistry.validateProviderDefinition; }
14650
15933
  });
14651
15934
  exports.ACCEPT_CHALLENGE_HEADER = ACCEPT_CHALLENGE_HEADER;
15935
+ exports.ADMIN_DELTA_BASES = ADMIN_DELTA_BASES;
15936
+ exports.ADMIN_OVERVIEW_CACHE_STATUSES = ADMIN_OVERVIEW_CACHE_STATUSES;
15937
+ exports.ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT = ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT;
15938
+ exports.ADMIN_OVERVIEW_LIST_LIMIT_MAX = ADMIN_OVERVIEW_LIST_LIMIT_MAX;
15939
+ exports.ADMIN_OVERVIEW_SECTIONS = ADMIN_OVERVIEW_SECTIONS;
15940
+ exports.ADMIN_OVERVIEW_WINDOWS = ADMIN_OVERVIEW_WINDOWS;
14652
15941
  exports.AI_AGENT_HEADERS = AI_AGENT_HEADERS;
14653
15942
  exports.ANONYMOUS_PRINCIPAL_DID = ANONYMOUS_PRINCIPAL_DID;
14654
15943
  exports.API_ERRORS = API_ERRORS;
14655
15944
  exports.API_ERROR_CODES = API_ERROR_CODES;
14656
15945
  exports.API_REQUEST_LIMITS = API_REQUEST_LIMITS;
15946
+ exports.ATTESTED_BEARER_MAX_TTL_SECONDS = ATTESTED_BEARER_MAX_TTL_SECONDS;
14657
15947
  exports.AUTHORIZATION_MODES = AUTHORIZATION_MODES;
14658
15948
  exports.AUTH_ERRORS = AUTH_ERRORS;
14659
15949
  exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
@@ -14701,6 +15991,8 @@ exports.ApiResponseSchema = ApiResponseSchema;
14701
15991
  exports.AssuranceTierSchema = AssuranceTierSchema;
14702
15992
  exports.AuthErrorType = AuthErrorType;
14703
15993
  exports.AuthProviderTypeSchema = AuthProviderTypeSchema;
15994
+ exports.BASELINE_ALLOW_POLICY_ID = BASELINE_ALLOW_POLICY_ID;
15995
+ exports.BESPOKE_POLICY_IDS = BESPOKE_POLICY_IDS;
14704
15996
  exports.BLOCKED_PATH = BLOCKED_PATH;
14705
15997
  exports.BOT_USER_AGENT_PATTERNS = BOT_USER_AGENT_PATTERNS;
14706
15998
  exports.BROWSER_PATTERNS = BROWSER_PATTERNS;
@@ -14713,13 +16005,6 @@ exports.BatchEventRequestSchema = BatchEventRequestSchema;
14713
16005
  exports.BatchEventResponseSchema = BatchEventResponseSchema;
14714
16006
  exports.BatchEventSchema = BatchEventSchema;
14715
16007
  exports.BatchPixelEventRequestSchema = BatchPixelEventRequestSchema;
14716
- exports.BeaconBatchSchema = BeaconBatchSchema;
14717
- exports.BeaconCollectorDataSchema = BeaconCollectorDataSchema;
14718
- exports.BeaconConfigSchema = BeaconConfigSchema;
14719
- exports.BeaconEventSchema = BeaconEventSchema;
14720
- exports.BeaconEventTypeSchema = BeaconEventTypeSchema;
14721
- exports.BeaconWorkerMessageSchema = BeaconWorkerMessageSchema;
14722
- exports.BeaconWorkerMessageTypeSchema = BeaconWorkerMessageTypeSchema;
14723
16008
  exports.BehavioralAnalysisSchema = BehavioralAnalysisSchema;
14724
16009
  exports.BehavioralDataSchema = BehavioralDataSchema;
14725
16010
  exports.BehavioralPatternSchema = BehavioralPatternSchema;
@@ -14748,11 +16033,13 @@ exports.CLOUD_PROVIDER_RANGES = CLOUD_PROVIDER_RANGES;
14748
16033
  exports.CONDITION_FIELDS = CONDITION_FIELDS;
14749
16034
  exports.CONDITION_OPERATORS = CONDITION_OPERATORS;
14750
16035
  exports.CONFIDENCE_THRESHOLDS = CONFIDENCE_THRESHOLDS;
16036
+ exports.CORRELATION_ID_HEADER = CORRELATION_ID_HEADER;
14751
16037
  exports.CRISPBudgetSchema = CRISPBudgetSchema;
14752
16038
  exports.CURRENT_POLICY_VERSION = CURRENT_POLICY_VERSION;
14753
16039
  exports.CacheConfigSchema = CacheConfigSchema;
14754
16040
  exports.CachedDetectionDataSchema = CachedDetectionDataSchema;
14755
16041
  exports.ChallengeParamsSchema = ChallengeParamsSchema;
16042
+ exports.ChallengeWireError = ChallengeWireError;
14756
16043
  exports.CircuitBreakerConfigSchema = CircuitBreakerConfigSchema;
14757
16044
  exports.CircuitBreakerStateSchema = CircuitBreakerStateSchema;
14758
16045
  exports.ClickEventSchema = ClickEventSchema;
@@ -14760,7 +16047,6 @@ exports.ClientDetectionSchema = ClientDetectionSchema;
14760
16047
  exports.CollectFingerprintRequestSchema = CollectFingerprintRequestSchema;
14761
16048
  exports.CollectFingerprintResponseSchema = CollectFingerprintResponseSchema;
14762
16049
  exports.CollectedDataSchema = CollectedDataSchema;
14763
- exports.CollectorTypeSchema = CollectorTypeSchema;
14764
16050
  exports.ConditionFieldSchema = ConditionFieldSchema;
14765
16051
  exports.ConditionOperatorSchema = ConditionOperatorSchema;
14766
16052
  exports.ConditionValueSchema = ConditionValueSchema;
@@ -14769,7 +16055,6 @@ exports.ConfidenceLevelSchema = ConfidenceLevelSchema;
14769
16055
  exports.ConfidenceThresholdSchema = ConfidenceThresholdSchema;
14770
16056
  exports.ConfidenceUtils = ConfidenceUtils;
14771
16057
  exports.ConfiguredProviderSchema = ConfiguredProviderSchema;
14772
- exports.ConnectionTypeSchema = ConnectionTypeSchema;
14773
16058
  exports.ConsentAgentMetadataSchema = ConsentAgentMetadataSchema;
14774
16059
  exports.ConsentBrandingSchema = ConsentBrandingSchema;
14775
16060
  exports.ConsentCapabilityGroupSchema = ConsentCapabilityGroupSchema;
@@ -14778,26 +16063,32 @@ exports.ConsentConfigMetadataSchema = ConsentConfigMetadataSchema;
14778
16063
  exports.ConsentConfigSchema = ConsentConfigSchema;
14779
16064
  exports.ConsentTermsSchema = ConsentTermsSchema;
14780
16065
  exports.ConsentUISchema = ConsentUISchema;
16066
+ exports.CorrelationIdSchema = CorrelationIdSchema;
14781
16067
  exports.CreateApiKeySchema = CreateApiKeySchema;
14782
16068
  exports.CreateOrganizationInputSchema = CreateOrganizationInputSchema;
14783
16069
  exports.CreateOrganizationSchema = CreateOrganizationSchema;
14784
16070
  exports.CreatePixelSchema = CreatePixelSchema;
14785
16071
  exports.CreateProfileRequestSchema = CreateProfileRequestSchema;
14786
16072
  exports.CreateProjectSchema = CreateProjectSchema;
16073
+ exports.CreateProvisioningOrganizationRequestSchema = CreateProvisioningOrganizationRequestSchema;
16074
+ exports.CreateProvisioningOrganizationResponseSchema = CreateProvisioningOrganizationResponseSchema;
14787
16075
  exports.CredentialProviderSchema = CredentialProviderSchema;
14788
16076
  exports.CustomRuleSchema = CustomRuleSchema;
14789
16077
  exports.DATABASE_LIMITS = DATABASE_LIMITS;
16078
+ exports.DEFAULT_ADMIN_OVERVIEW_WINDOW = DEFAULT_ADMIN_OVERVIEW_WINDOW;
14790
16079
  exports.DEFAULT_AGENTSHIELD_CONFIG = DEFAULT_AGENTSHIELD_CONFIG;
14791
16080
  exports.DEFAULT_AGENT_TYPES = DEFAULT_AGENT_TYPES;
14792
16081
  exports.DEFAULT_API_KEY_RATE_LIMITS = DEFAULT_API_KEY_RATE_LIMITS;
14793
16082
  exports.DEFAULT_AUTHORIZATION_HOST = DEFAULT_AUTHORIZATION_HOST;
14794
16083
  exports.DEFAULT_BEHAVIORAL_THRESHOLDS = DEFAULT_BEHAVIORAL_THRESHOLDS;
14795
16084
  exports.DEFAULT_CACHE_CONFIG = DEFAULT_CACHE_CONFIG;
16085
+ exports.DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;
14796
16086
  exports.DEFAULT_CONFIDENCE_THRESHOLDS = DEFAULT_CONFIDENCE_THRESHOLDS;
14797
16087
  exports.DEFAULT_CORS_CONFIG = DEFAULT_CORS_CONFIG;
14798
16088
  exports.DEFAULT_DETECTION_OPTIONS = DEFAULT_DETECTION_OPTIONS;
14799
16089
  exports.DEFAULT_ENV_VARS = DEFAULT_ENV_VARS;
14800
16090
  exports.DEFAULT_LOG_CONFIG = DEFAULT_LOG_CONFIG;
16091
+ exports.DEFAULT_MAX_VENDOR_RANGE_AGE_MS = DEFAULT_MAX_VENDOR_RANGE_AGE_MS;
14801
16092
  exports.DEFAULT_PASSWORD_REQUIREMENTS = DEFAULT_PASSWORD_REQUIREMENTS;
14802
16093
  exports.DEFAULT_PIXEL_CONFIG = DEFAULT_PIXEL_CONFIG;
14803
16094
  exports.DEFAULT_POLICY = DEFAULT_POLICY;
@@ -14850,10 +16141,13 @@ exports.DetectionTestResultSchema = DetectionTestResultSchema;
14850
16141
  exports.DetectionViewTypeSchema = DetectionViewTypeSchema;
14851
16142
  exports.ENFORCEMENT_ACTIONS = ENFORCEMENT_ACTIONS;
14852
16143
  exports.ENFORCEMENT_MODES = ENFORCEMENT_MODES;
16144
+ exports.ENTROPY_CONFIDENCE_CEILING = ENTROPY_CONFIDENCE_CEILING;
16145
+ exports.ENTROPY_CONFIDENCE_FLOOR = ENTROPY_CONFIDENCE_FLOOR;
14853
16146
  exports.ERROR_CATEGORIES = ERROR_CATEGORIES;
14854
16147
  exports.ERROR_CODES = ERROR_CODES;
14855
16148
  exports.ERROR_MESSAGES = ERROR_MESSAGES;
14856
16149
  exports.ERROR_STATUS_CODES = ERROR_STATUS_CODES;
16150
+ exports.EXCLUSION_BUCKETS = EXCLUSION_BUCKETS;
14857
16151
  exports.EXPORT_LIMITS = EXPORT_LIMITS;
14858
16152
  exports.EnforcementActionSchema = EnforcementActionSchema;
14859
16153
  exports.EnforcementModeSchema = EnforcementModeSchema;
@@ -14887,6 +16181,8 @@ exports.HeaderRuleSchema = HeaderRuleSchema;
14887
16181
  exports.HeaderRulesSchema = HeaderRulesSchema;
14888
16182
  exports.HealthResponseSchema = HealthResponseSchema;
14889
16183
  exports.HomeRailRollupsRequestSchema = HomeRailRollupsRequestSchema;
16184
+ exports.INSTALLATION_KINDS = INSTALLATION_KINDS;
16185
+ exports.INSTALLATION_TYPES = INSTALLATION_TYPES;
14890
16186
  exports.INTERNAL_ERRORS = INTERNAL_ERRORS;
14891
16187
  exports.InstructPayloadSchema = InstructPayloadSchema;
14892
16188
  exports.IntegrationTypeSchema = IntegrationTypeSchema;
@@ -14894,18 +16190,21 @@ exports.InternalProcessingFlagsSchema = InternalProcessingFlagsSchema;
14894
16190
  exports.IpRangeCollectionSchema = IpRangeCollectionSchema;
14895
16191
  exports.IpRangeRuleSchema = IpRangeRuleSchema;
14896
16192
  exports.JafarParseError = JafarParseError;
14897
- exports.JwsParseError = JwsParseError;
14898
16193
  exports.KNOWN_AGENT_PATTERNS = KNOWN_AGENT_PATTERNS;
14899
16194
  exports.KYA_HTTP_ERROR = KYA_HTTP_ERROR;
14900
16195
  exports.KYA_OS_HANDSHAKE_METHODS = KYA_OS_HANDSHAKE_METHODS;
14901
16196
  exports.KYA_OS_WIRE_METHODS = KYA_OS_WIRE_METHODS;
14902
16197
  exports.KeyboardEventSchema = KeyboardEventSchema;
16198
+ exports.ListProvisioningOrganizationsRequestSchema = ListProvisioningOrganizationsRequestSchema;
16199
+ exports.ListProvisioningOrganizationsResponseSchema = ListProvisioningOrganizationsResponseSchema;
14903
16200
  exports.LoggingConfigSchema = LoggingConfigSchema;
14904
16201
  exports.MATCH_ACTIONS = MATCH_ACTIONS;
14905
16202
  exports.MAX_BULK_BATCH_SIZE = MAX_BULK_BATCH_SIZE;
16203
+ exports.MAX_ED25519_KEY_BODY_LENGTH = MAX_ED25519_KEY_BODY_LENGTH;
14906
16204
  exports.MCPI_ORG_DID_HOST = MCPI_ORG_DID_HOST;
14907
16205
  exports.MCP_CLIENT_DID_HOST = MCP_CLIENT_DID_HOST;
14908
16206
  exports.MOBILE_PATTERNS = MOBILE_PATTERNS;
16207
+ exports.MarketplaceSourceSchema = MarketplaceSourceSchema;
14909
16208
  exports.MessagePrioritySchema = MessagePrioritySchema;
14910
16209
  exports.MiddlewareActionSchema = MiddlewareActionSchema;
14911
16210
  exports.MiddlewareConfigSchema = MiddlewareConfigSchema;
@@ -14938,6 +16237,7 @@ exports.PACKAGE_NAME = PACKAGE_NAME;
14938
16237
  exports.PAGINATION_DEFAULTS = PAGINATION_DEFAULTS;
14939
16238
  exports.PERFORMANCE_THRESHOLDS = PERFORMANCE_THRESHOLDS;
14940
16239
  exports.PERMISSION_ERRORS = PERMISSION_ERRORS;
16240
+ exports.PINNED_SIGNING_VENDORS = PINNED_SIGNING_VENDORS;
14941
16241
  exports.PIXEL_ERRORS = PIXEL_ERRORS;
14942
16242
  exports.PIXEL_EVENT_LIMITS = PIXEL_EVENT_LIMITS;
14943
16243
  exports.PLAN_FEATURE_LIMITS = PLAN_FEATURE_LIMITS;
@@ -14989,6 +16289,11 @@ exports.ProjectsQuerySchema = ProjectsQuerySchema;
14989
16289
  exports.ProtocolVersionSchema = ProtocolVersionSchema;
14990
16290
  exports.ProviderDefinitionSchema = ProviderDefinitionSchema2;
14991
16291
  exports.ProvidersResponseSchema = ProvidersResponseSchema;
16292
+ exports.ProvisionKeyRequestSchema = ProvisionKeyRequestSchema;
16293
+ exports.ProvisionKeyResponseSchema = ProvisionKeyResponseSchema;
16294
+ exports.ProvisioningModeSchema = ProvisioningModeSchema;
16295
+ exports.ProvisioningOrganizationRoleSchema = ProvisioningOrganizationRoleSchema;
16296
+ exports.ProvisioningOrganizationSummarySchema = ProvisioningOrganizationSummarySchema;
14992
16297
  exports.PublicAnalyticsBotTypeSchema = PublicAnalyticsBotTypeSchema;
14993
16298
  exports.PublicAnalyticsSchema = PublicAnalyticsSchema;
14994
16299
  exports.PublicAnalyticsSummarySchema = PublicAnalyticsSummarySchema;
@@ -15004,6 +16309,8 @@ exports.PublishProfileRequestSchema = PublishProfileRequestSchema;
15004
16309
  exports.QueryFilterSchema = QueryFilterSchema;
15005
16310
  exports.QuerySchema = QuerySchema;
15006
16311
  exports.RATE_LIMIT_ERRORS = RATE_LIMIT_ERRORS;
16312
+ exports.REPORT_AI_AGENT_NAMES = REPORT_AI_AGENT_NAMES;
16313
+ exports.REPORT_AI_CRAWLER_NAMES = REPORT_AI_CRAWLER_NAMES;
15007
16314
  exports.RULE_CACHE = RULE_CACHE;
15008
16315
  exports.RULE_CATEGORIES = RULE_CATEGORIES;
15009
16316
  exports.RULE_CDN = RULE_CDN;
@@ -15027,6 +16334,8 @@ exports.RequestContextSchema = RequestContextSchema;
15027
16334
  exports.ResourceUsageSchema = ResourceUsageSchema;
15028
16335
  exports.ResponseActionSchema = ResponseActionSchema;
15029
16336
  exports.RetryStrategySchema = RetryStrategySchema;
16337
+ exports.RevokeProvisionQuerySchema = RevokeProvisionQuerySchema;
16338
+ exports.RevokeProvisionResponseSchema = RevokeProvisionResponseSchema;
15030
16339
  exports.RiskAssessmentSchema = RiskAssessmentSchema;
15031
16340
  exports.RuleLoadOptionsSchema = RuleLoadOptionsSchema;
15032
16341
  exports.RuleLoader = RuleLoader;
@@ -15037,6 +16346,7 @@ exports.RuleUpdateEventSchema = RuleUpdateEventSchema;
15037
16346
  exports.RuleValidationResultSchema = RuleValidationResultSchema;
15038
16347
  exports.RuleValidator = RuleValidator;
15039
16348
  exports.SECURITY_LIMITS = SECURITY_LIMITS;
16349
+ exports.SERVICE_TRAFFIC_KEYS = SERVICE_TRAFFIC_KEYS;
15040
16350
  exports.SESSION_ERRORS = SESSION_ERRORS;
15041
16351
  exports.SESSION_LIMITS = SESSION_LIMITS;
15042
16352
  exports.SLUG_REGEX = SLUG_REGEX;
@@ -15068,6 +16378,9 @@ exports.SignatureRuleSchema = SignatureRuleSchema;
15068
16378
  exports.SignatureVerificationRequestSchema = SignatureVerificationRequestSchema;
15069
16379
  exports.SignatureVerificationResponseSchema = SignatureVerificationResponseSchema;
15070
16380
  exports.SingleItemResponseSchema = SingleItemResponseSchema;
16381
+ exports.SsoLinkRequestSchema = SsoLinkRequestSchema;
16382
+ exports.SsoLinkResponseSchema = SsoLinkResponseSchema;
16383
+ exports.StaleVendorRangesError = StaleVendorRangesError;
15071
16384
  exports.StatsResponseSchema = StatsResponseSchema;
15072
16385
  exports.StatsUpdateEventSchema = StatsUpdateEventSchema;
15073
16386
  exports.StrictEnforcementActionSchema = StrictEnforcementActionSchema;
@@ -15076,6 +16389,7 @@ exports.SystemStatsSchema = SystemStatsSchema;
15076
16389
  exports.TIME_WINDOWS = TIME_WINDOWS;
15077
16390
  exports.TLSFingerprintSchema = TLSFingerprintSchema;
15078
16391
  exports.TRADITIONAL_BOT_PATTERNS = TRADITIONAL_BOT_PATTERNS;
16392
+ exports.TRAFFIC_TAXONOMY_BUCKETS = TRAFFIC_TAXONOMY_BUCKETS;
15079
16393
  exports.TRUSTED_BOTS = TRUSTED_BOTS;
15080
16394
  exports.TestDetectionRequestSchema = TestDetectionRequestSchema;
15081
16395
  exports.ThresholdConfigSchema = ThresholdConfigSchema;
@@ -15087,7 +16401,7 @@ exports.TransportMetricsSchema = TransportMetricsSchema;
15087
16401
  exports.TransportOptionsSchema = TransportOptionsSchema;
15088
16402
  exports.TransportResponseSchema = TransportResponseSchema;
15089
16403
  exports.TransportStateSchema = TransportStateSchema;
15090
- exports.TransportStatusSchema = TransportStatusSchema;
16404
+ exports.UNCALIBRATED_NOISY_OR_PRIOR = UNCALIBRATED_NOISY_OR_PRIOR;
15091
16405
  exports.UPDATE_FREQUENCIES = UPDATE_FREQUENCIES;
15092
16406
  exports.USER_AGENT_PATTERNS = USER_AGENT_PATTERNS;
15093
16407
  exports.UpdateApiKeySchema = UpdateApiKeySchema;
@@ -15106,6 +16420,7 @@ exports.VALIDATION_MODES = VALIDATION_MODES;
15106
16420
  exports.VALIDATION_PATTERNS = VALIDATION_PATTERNS;
15107
16421
  exports.VERDICT_COOKIE_NAME = VERDICT_COOKIE_NAME;
15108
16422
  exports.VERSION = VERSION;
16423
+ exports.VerdictEvidenceSchema = VerdictEvidenceSchema;
15109
16424
  exports.VerificationCacheEntrySchema = VerificationCacheEntrySchema;
15110
16425
  exports.VerificationProviderSchema = VerificationProviderSchema;
15111
16426
  exports.VerificationRequestSchema = VerificationRequestSchema;
@@ -15132,16 +16447,33 @@ exports.WorkerPoolConfigSchema = WorkerPoolConfigSchema;
15132
16447
  exports.WorkerStateSchema = WorkerStateSchema;
15133
16448
  exports.WorkerTaskSchema = WorkerTaskSchema;
15134
16449
  exports.acceptsHtml = acceptsHtml;
16450
+ exports.adminOverviewQuerySchema = adminOverviewQuerySchema;
15135
16451
  exports.approvalQuorumForRequest = approvalQuorumForRequest;
16452
+ exports.assertVendorRangesFresh = assertVendorRangesFresh;
15136
16453
  exports.assignmentChangeRequestSchema = assignmentChangeRequestSchema;
15137
16454
  exports.auditLogQuerySchema = auditLogQuerySchema;
16455
+ exports.base58btcDecode = base58btcDecode;
16456
+ exports.base58btcEncode = base58btcEncode;
15138
16457
  exports.batchAssignmentRequestSchema = batchAssignmentRequestSchema;
16458
+ exports.bespokePolicyLabel = bespokePolicyLabel;
16459
+ exports.blockDelegationVerdict = blockDelegationVerdict;
16460
+ exports.blockEqualityLiterals = blockEqualityLiterals;
16461
+ exports.buildChallengeWire = buildChallengeWire;
16462
+ exports.buildDelegationBearerHeader = buildDelegationBearerHeader;
16463
+ exports.buildDelegationChallengeBody = buildDelegationChallengeBody;
16464
+ exports.buildDelegationChallengeEnvelope = buildDelegationChallengeEnvelope;
16465
+ exports.buildDelegationChallengeHeader = buildDelegationChallengeHeader;
16466
+ exports.buildDelegationInstructions = buildDelegationInstructions;
15139
16467
  exports.buildInitialStepsState = buildInitialStepsState;
16468
+ exports.buildKnownPatternLookup = buildKnownPatternLookup;
16469
+ exports.buildVerdictEvidence = buildVerdictEvidence;
15140
16470
  exports.calculateDeployProgress = calculateDeployProgress;
15141
- exports.canonicalSigningPayload = canonicalSigningPayload;
15142
16471
  exports.cedarQuotedValueRegExp = cedarQuotedValueRegExp;
15143
16472
  exports.changePasswordSchema = changePasswordSchema;
16473
+ exports.classifyAgentTaxonomy = classifyAgentTaxonomy;
15144
16474
  exports.classifyResponseShape = classifyResponseShape;
16475
+ exports.claudeRuntimeLabel = claudeRuntimeLabel;
16476
+ exports.computeEntropyConfidence = computeEntropyConfidence;
15145
16477
  exports.createError = createError;
15146
16478
  exports.createErrorResponse = createErrorResponse;
15147
16479
  exports.createEvaluationContext = createEvaluationContext;
@@ -15155,7 +16487,10 @@ exports.createSuccessResponse = createSuccessResponse;
15155
16487
  exports.createValidationErrorResponse = createValidationErrorResponse;
15156
16488
  exports.decisionPolicyId = decisionPolicyId;
15157
16489
  exports.decodeDidKeyEd25519 = decodeDidKeyEd25519;
16490
+ exports.decodeEd25519PublicKeyMultibaseTolerant = decodeEd25519PublicKeyMultibaseTolerant;
15158
16491
  exports.defaultConfig = defaultConfig;
16492
+ exports.deriveCorrelationId = deriveCorrelationId;
16493
+ exports.deriveDelegationPickupUri = deriveDelegationPickupUri;
15159
16494
  exports.deriveMcpClientDid = deriveMcpClientDid;
15160
16495
  exports.deriveMcpiOrgDid = deriveMcpiOrgDid;
15161
16496
  exports.deriveMcpiOrgKid = deriveMcpiOrgKid;
@@ -15164,13 +16499,16 @@ exports.deriveVerdict = deriveVerdict;
15164
16499
  exports.detectionClassToEnum = detectionClassToEnum;
15165
16500
  exports.discoveredToolSchema = discoveredToolSchema;
15166
16501
  exports.encodeDidKeyEd25519 = encodeDidKeyEd25519;
16502
+ exports.encodeEd25519PublicKeyMultibase = encodeEd25519PublicKeyMultibase;
15167
16503
  exports.encodeVerdictCookie = encodeVerdictCookie;
15168
16504
  exports.enumToDetectionClass = enumToDetectionClass;
15169
16505
  exports.escapeCedarString = escapeCedarString;
15170
16506
  exports.evaluatePolicy = evaluatePolicy;
16507
+ exports.extractCorrelationIdFromHeaders = extractCorrelationIdFromHeaders;
15171
16508
  exports.extractMatch = extractMatch;
15172
16509
  exports.fetchPolicy = fetchPolicy;
15173
16510
  exports.findMatchingPattern = findMatchingPattern;
16511
+ exports.findStaleVendorRanges = findStaleVendorRanges;
15174
16512
  exports.forgotPasswordSchema = forgotPasswordSchema;
15175
16513
  exports.formatConfidence = formatConfidence;
15176
16514
  exports.fromProviderRegistryFormat = fromProviderRegistryFormat;
@@ -15183,6 +16521,7 @@ exports.gatewayInternalDiscoverErrorSchema = gatewayInternalDiscoverErrorSchema;
15183
16521
  exports.gatewayInternalDiscoverSuccessSchema = gatewayInternalDiscoverSuccessSchema;
15184
16522
  exports.gatewayInternalToolsListSchema = gatewayInternalToolsListSchema;
15185
16523
  exports.gatewayToolCallSchema = gatewayToolCallSchema;
16524
+ exports.generateDelegationSid = generateDelegationSid;
15186
16525
  exports.generateTestId = generateTestId;
15187
16526
  exports.getAgentDisplayName = getAgentDisplayName;
15188
16527
  exports.getBotType = getBotType;
@@ -15198,8 +16537,12 @@ exports.getStepOrder = getStepOrder;
15198
16537
  exports.getVerificationMethodDescription = getVerificationMethodDescription;
15199
16538
  exports.getVerificationReliability = getVerificationReliability;
15200
16539
  exports.getVerificationRiskLevel = getVerificationRiskLevel;
16540
+ exports.hasPinnedSigningVendor = hasPinnedSigningVendor;
15201
16541
  exports.initializePolicyFetcher = initializePolicyFetcher;
16542
+ exports.isBespokePolicyId = isBespokePolicyId;
15202
16543
  exports.isBlockingAction = isBlockingAction;
16544
+ exports.isClaudeProductLabel = isClaudeProductLabel;
16545
+ exports.isForbidBlock = isForbidBlock;
15203
16546
  exports.isHighConfidenceVerification = isHighConfidenceVerification;
15204
16547
  exports.isKnownAgentType = isKnownAgentType;
15205
16548
  exports.isKnownAiCrawler = isKnownAiCrawler;
@@ -15208,50 +16551,60 @@ exports.isKyaOsWireMethod = isKyaOsWireMethod;
15208
16551
  exports.isLegacyDetectionClass = isLegacyDetectionClass;
15209
16552
  exports.isLegitimateCategory = isLegitimateCategory;
15210
16553
  exports.isLimitExceeded = isLimitExceeded;
16554
+ exports.isNonNavigablePolicyId = isNonNavigablePolicyId;
15211
16555
  exports.isPassThroughAction = isPassThroughAction;
15212
16556
  exports.isPrivateOrReservedHost = isPrivateOrReservedHost;
15213
16557
  exports.isSupportedAuthType = isSupportedAuthType;
15214
16558
  exports.isTraditionalBot = isTraditionalBot;
16559
+ exports.isUnnarrowedDenyBlock = isUnnarrowedDenyBlock;
15215
16560
  exports.isValidAuthorizationHost = isValidAuthorizationHost;
15216
16561
  exports.isValidFingerprintResponse = isValidFingerprintResponse;
15217
16562
  exports.isValidMcpiOrgSlug = isValidMcpiOrgSlug;
15218
16563
  exports.isValidWasmDetectionResult = isValidWasmDetectionResult;
15219
16564
  exports.isValidWasmRequestMetadata = isValidWasmRequestMetadata;
16565
+ exports.lintUnnarrowedDenyRules = lintUnnarrowedDenyRules;
15220
16566
  exports.loadRulesAsync = loadRulesAsync;
15221
16567
  exports.mapLegacyAuthType = mapLegacyAuthType;
15222
16568
  exports.mapToLegacyAuthType = mapToLegacyAuthType;
15223
16569
  exports.matchPath = matchPath;
15224
16570
  exports.mergeWithDefaults = mergeWithDefaults;
15225
16571
  exports.migrateLegacyDetectionClass = migrateLegacyDetectionClass;
16572
+ exports.nonNavigablePolicyLabel = nonNavigablePolicyLabel;
15226
16573
  exports.normalizeAgentName = normalizeAgentName;
15227
16574
  exports.normalizeConfidence = normalizeConfidence;
15228
16575
  exports.normalizeDetectionClass = normalizeDetectionClass;
15229
16576
  exports.normalizeDetectionClassEnum = normalizeDetectionClassEnum;
16577
+ exports.normalizeHandshakeMethod = normalizeHandshakeMethod;
15230
16578
  exports.normalizeOrganizationName = normalizeOrganizationName;
16579
+ exports.normalizeWireMethod = normalizeWireMethod;
15231
16580
  exports.oauthClientSchema = oauthClientSchema;
15232
16581
  exports.parseAgentName = parseAgentName;
15233
16582
  exports.parseEvaluationContext = parseEvaluationContext;
15234
16583
  exports.parseJafarFeed = parseJafarFeed;
15235
- exports.parseJwsCompact = parseJwsCompact;
15236
16584
  exports.parsePolicyConfig = parsePolicyConfig;
15237
16585
  exports.parseRules = parseRules;
15238
- exports.parseSigningKey = parseSigningKey;
15239
16586
  exports.partial = partial;
15240
16587
  exports.passwordSchema = passwordSchema;
16588
+ exports.pathHasUnnarrowedDenyRule = pathHasUnnarrowedDenyRule;
16589
+ exports.pathLiteralsInBlock = pathLiteralsInBlock;
16590
+ exports.permitDelegationVerdict = permitDelegationVerdict;
15241
16591
  exports.projectResetRequestSchema = projectResetRequestSchema;
16592
+ exports.reconstructConfidenceFromEvidence = reconstructConfidenceFromEvidence;
16593
+ exports.refineClaudeDisplayLabel = refineClaudeDisplayLabel;
15242
16594
  exports.requestCarriesDelegationProof = requestCarriesDelegationProof;
15243
16595
  exports.requiredScopesForRequest = requiredScopesForRequest;
15244
16596
  exports.resetPasswordSchema = resetPasswordSchema;
15245
16597
  exports.resetPolicyFetcher = resetPolicyFetcher;
15246
16598
  exports.resolveAuthorizationHost = resolveAuthorizationHost;
16599
+ exports.resolveChallengeContext = resolveChallengeContext;
15247
16600
  exports.resolveTrustedDelegationRoots = resolveTrustedDelegationRoots;
15248
16601
  exports.safeParsePolicyConfig = safeParsePolicyConfig;
15249
16602
  exports.safeUrl = safeUrl;
15250
16603
  exports.selectBodyReadable200 = selectBodyReadable200;
15251
16604
  exports.serveBodyReadable200 = serveBodyReadable200;
15252
16605
  exports.signInSchema = signInSchema;
15253
- exports.signMcpiEnvelope = signMcpiEnvelope;
15254
16606
  exports.signUpSchema = signUpSchema;
16607
+ exports.splitCedarBlocks = splitCedarBlocks;
15255
16608
  exports.strict = strict;
15256
16609
  exports.supportsClientSide = supportsClientSide;
15257
16610
  exports.supportsHeaders = supportsHeaders;
@@ -15259,8 +16612,10 @@ exports.supportsServerEnhanced = supportsServerEnhanced;
15259
16612
  exports.testPattern = testPattern;
15260
16613
  exports.testPatterns = testPatterns;
15261
16614
  exports.toBareHost = toBareHost;
16615
+ exports.toCoarseReasonKind = toCoarseReasonKind;
15262
16616
  exports.toPercent = toPercent;
15263
16617
  exports.toProviderRegistryFormat = toProviderRegistryFormat;
16618
+ exports.toStoredCorrelationId = toStoredCorrelationId;
15264
16619
  exports.toWasmRequestMetadata = toWasmRequestMetadata;
15265
16620
  exports.unescapeCedarString = unescapeCedarString;
15266
16621
  exports.updateStepsState = updateStepsState;
@@ -15270,7 +16625,6 @@ exports.upstreamServerSchema = upstreamServerSchema;
15270
16625
  exports.validate = validate;
15271
16626
  exports.validateClientDetection = validateClientDetection;
15272
16627
  exports.validateFingerprintRequest = validateFingerprintRequest;
15273
- exports.validateMcpIPayload = validateMcpIPayload;
15274
16628
  exports.validateOrThrow = validateOrThrow;
15275
16629
  exports.validateOrganizationName = validateOrganizationName;
15276
16630
  exports.validateRules = validateRules;