@kya-os/checkpoint-shared 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -1
  3. package/dist/beacon-types/index.d.mts +13 -2
  4. package/dist/beacon-types/index.d.ts +13 -2
  5. package/dist/beacon-types/index.js +35 -3
  6. package/dist/beacon-types/index.mjs +35 -4
  7. package/dist/browser-posture-report.d.mts +85 -0
  8. package/dist/browser-posture-report.d.ts +85 -0
  9. package/dist/browser-posture-report.js +1 -0
  10. package/dist/browser-posture-report.mjs +1 -0
  11. package/dist/browser-posture.d.mts +114 -0
  12. package/dist/browser-posture.d.ts +114 -0
  13. package/dist/browser-posture.js +4204 -0
  14. package/dist/browser-posture.mjs +4187 -0
  15. package/dist/browser.d.mts +35 -1
  16. package/dist/browser.d.ts +35 -1
  17. package/dist/browser.js +1 -1
  18. package/dist/browser.mjs +1 -1
  19. package/dist/canonical-signer/index.js +31 -2
  20. package/dist/canonical-signer/index.mjs +31 -2
  21. package/dist/deploy/index.d.mts +449 -2
  22. package/dist/deploy/index.d.ts +449 -2
  23. package/dist/deploy/index.js +238 -1
  24. package/dist/deploy/index.mjs +228 -2
  25. package/dist/errors/index.d.mts +104 -0
  26. package/dist/errors/index.d.ts +104 -0
  27. package/dist/errors/index.js +338 -0
  28. package/dist/errors/index.mjs +333 -0
  29. package/dist/gateway/index.d.mts +6 -1
  30. package/dist/gateway/index.d.ts +6 -1
  31. package/dist/gateway/index.js +4 -0
  32. package/dist/gateway/index.mjs +4 -1
  33. package/dist/index.d.mts +2388 -851
  34. package/dist/index.d.ts +2388 -851
  35. package/dist/index.js +2684 -686
  36. package/dist/index.mjs +2575 -669
  37. package/dist/mcpi/multibase-ed25519.d.mts +8 -0
  38. package/dist/mcpi/multibase-ed25519.d.ts +8 -0
  39. package/dist/mcpi/multibase-ed25519.js +125 -0
  40. package/dist/mcpi/multibase-ed25519.mjs +119 -0
  41. package/dist/signals/index.d.mts +158 -0
  42. package/dist/signals/index.d.ts +158 -0
  43. package/dist/signals/index.js +1667 -0
  44. package/dist/signals/index.mjs +1637 -0
  45. package/dist/test-fixtures/index.d.mts +37 -1
  46. package/dist/test-fixtures/index.d.ts +37 -1
  47. package/dist/test-fixtures/index.js +92 -1
  48. package/dist/test-fixtures/index.mjs +87 -2
  49. package/fixtures/client-ip-resolution.json +103 -0
  50. package/fixtures/detection/reason-codes.json +35 -0
  51. package/fixtures/detection/signal-exposure-example.json +62 -0
  52. package/fixtures/kya-http/README.md +112 -0
  53. package/fixtures/kya-http/challenge-proof.canonical.json +25 -0
  54. package/fixtures/kya-http/challenge.approval-quorum.json +37 -0
  55. package/fixtures/kya-http/challenge.delegation.fetcher-200.json +55 -0
  56. package/fixtures/kya-http/challenge.delegation.full.json +81 -0
  57. package/fixtures/kya-http/challenge.delegation.minimal.json +57 -0
  58. package/fixtures/kya-http/error-codes.json +35 -0
  59. package/fixtures/kya-http/fetcher-200-predicate.vectors.json +72 -0
  60. package/fixtures/kya-http/negative.challenges.json +54 -0
  61. package/fixtures/kya-http/pickup.transcript.json +96 -0
  62. package/fixtures/kya-http/pickup.transcript.quorum.json +156 -0
  63. package/fixtures/kya-http/protected-resource-metadata.full.json +30 -0
  64. package/fixtures/kya-http/protected-resource-metadata.global.json +28 -0
  65. package/fixtures/kya-http/registration.request.json +33 -0
  66. package/fixtures/kya-http/registration.response.json +32 -0
  67. package/package.json +42 -9
  68. package/src/data/compiled/merged-rules.json +8 -2
package/dist/index.mjs CHANGED
@@ -1,8 +1,7 @@
1
1
  export { AUTH_MODES, CredentialProviderConfigSchema, OAuthProviderConfigSchema, PROVIDER_AUTH_TYPES, ProviderConfigSchema, ProviderDefinitionSchema as ProviderRegistryDefinitionSchema, validateProviderConfig, validateProviderDefinition } from '@kya-os/provider-registry';
2
2
  import * as yaml from 'js-yaml';
3
- import canonicalize from 'canonicalize';
4
- import { getPublicKeyAsync, signAsync } from '@noble/ed25519';
5
- import { base58btc } from 'multiformats/bases/base58';
3
+ import { sha256 } from '@noble/hashes/sha2.js';
4
+ import { bytesToHex } from '@noble/hashes/utils.js';
6
5
 
7
6
  var __defProp = Object.defineProperty;
8
7
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -86,7 +85,7 @@ var require_merged_rules = __commonJS({
86
85
  lastUpdated: "2025-01-10T00:00:00Z"
87
86
  }
88
87
  ],
89
- hash: "58f3ec67889f255c78bc571031af8dca3d9e2b6975ad42803758b2342516070b"
88
+ hash: "01eccdc0313dec99ffa8128c3e4c20818a9e58cfb0c0b41f428d0be5b4dbe5bf"
90
89
  },
91
90
  rules: {
92
91
  userAgents: {
@@ -361,9 +360,15 @@ var require_merged_rules = __commonJS({
361
360
  description: "Perplexity AI assistant (Perplexity-User, Perplexity/N, Comet browser)",
362
361
  category: "ai_assistant"
363
362
  },
363
+ amazon_quick_crawler: {
364
+ patterns: ["Amazon-Quick", "aws-quick"],
365
+ confidence: 0.95,
366
+ category: "scraper",
367
+ description: "Amazon Quick web crawler (formerly Amazon Q)"
368
+ },
364
369
  amazon_q: {
365
370
  patterns: ["NovaAct", "Amazon-Q"],
366
- confidence: 0.95,
371
+ confidence: 0.85,
367
372
  description: "Amazon Q AI assistant",
368
373
  category: "ai_assistant"
369
374
  },
@@ -1523,9 +1528,9 @@ var ParseInputLazyPath = class {
1523
1528
  return this._cachedPath;
1524
1529
  }
1525
1530
  };
1526
- var handleResult = (ctx, result) => {
1527
- if (isValid(result)) {
1528
- return { success: true, data: result.value };
1531
+ var handleResult = (ctx, result2) => {
1532
+ if (isValid(result2)) {
1533
+ return { success: true, data: result2.value };
1529
1534
  } else {
1530
1535
  if (!ctx.common.issues.length) {
1531
1536
  throw new Error("Validation failed but no issues detected.");
@@ -1596,21 +1601,21 @@ var ZodType = class {
1596
1601
  };
1597
1602
  }
1598
1603
  _parseSync(input) {
1599
- const result = this._parse(input);
1600
- if (isAsync(result)) {
1604
+ const result2 = this._parse(input);
1605
+ if (isAsync(result2)) {
1601
1606
  throw new Error("Synchronous parse encountered promise.");
1602
1607
  }
1603
- return result;
1608
+ return result2;
1604
1609
  }
1605
1610
  _parseAsync(input) {
1606
- const result = this._parse(input);
1607
- return Promise.resolve(result);
1611
+ const result2 = this._parse(input);
1612
+ return Promise.resolve(result2);
1608
1613
  }
1609
1614
  parse(data, params) {
1610
- const result = this.safeParse(data, params);
1611
- if (result.success)
1612
- return result.data;
1613
- throw result.error;
1615
+ const result2 = this.safeParse(data, params);
1616
+ if (result2.success)
1617
+ return result2.data;
1618
+ throw result2.error;
1614
1619
  }
1615
1620
  safeParse(data, params) {
1616
1621
  const ctx = {
@@ -1625,8 +1630,8 @@ var ZodType = class {
1625
1630
  data,
1626
1631
  parsedType: getParsedType(data)
1627
1632
  };
1628
- const result = this._parseSync({ data, path: ctx.path, parent: ctx });
1629
- return handleResult(ctx, result);
1633
+ const result2 = this._parseSync({ data, path: ctx.path, parent: ctx });
1634
+ return handleResult(ctx, result2);
1630
1635
  }
1631
1636
  "~validate"(data) {
1632
1637
  const ctx = {
@@ -1642,9 +1647,9 @@ var ZodType = class {
1642
1647
  };
1643
1648
  if (!this["~standard"].async) {
1644
1649
  try {
1645
- const result = this._parseSync({ data, path: [], parent: ctx });
1646
- return isValid(result) ? {
1647
- value: result.value
1650
+ const result2 = this._parseSync({ data, path: [], parent: ctx });
1651
+ return isValid(result2) ? {
1652
+ value: result2.value
1648
1653
  } : {
1649
1654
  issues: ctx.common.issues
1650
1655
  };
@@ -1658,17 +1663,17 @@ var ZodType = class {
1658
1663
  };
1659
1664
  }
1660
1665
  }
1661
- return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
1662
- value: result.value
1666
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result2) => isValid(result2) ? {
1667
+ value: result2.value
1663
1668
  } : {
1664
1669
  issues: ctx.common.issues
1665
1670
  });
1666
1671
  }
1667
1672
  async parseAsync(data, params) {
1668
- const result = await this.safeParseAsync(data, params);
1669
- if (result.success)
1670
- return result.data;
1671
- throw result.error;
1673
+ const result2 = await this.safeParseAsync(data, params);
1674
+ if (result2.success)
1675
+ return result2.data;
1676
+ throw result2.error;
1672
1677
  }
1673
1678
  async safeParseAsync(data, params) {
1674
1679
  const ctx = {
@@ -1684,8 +1689,8 @@ var ZodType = class {
1684
1689
  parsedType: getParsedType(data)
1685
1690
  };
1686
1691
  const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
1687
- const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1688
- return handleResult(ctx, result);
1692
+ const result2 = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
1693
+ return handleResult(ctx, result2);
1689
1694
  }
1690
1695
  refine(check, message) {
1691
1696
  const getIssueProperties = (val) => {
@@ -1698,13 +1703,13 @@ var ZodType = class {
1698
1703
  }
1699
1704
  };
1700
1705
  return this._refinement((val, ctx) => {
1701
- const result = check(val);
1706
+ const result2 = check(val);
1702
1707
  const setError = () => ctx.addIssue({
1703
1708
  code: ZodIssueCode.custom,
1704
1709
  ...getIssueProperties(val)
1705
1710
  });
1706
- if (typeof Promise !== "undefined" && result instanceof Promise) {
1707
- return result.then((data) => {
1711
+ if (typeof Promise !== "undefined" && result2 instanceof Promise) {
1712
+ return result2.then((data) => {
1708
1713
  if (!data) {
1709
1714
  setError();
1710
1715
  return false;
@@ -1713,7 +1718,7 @@ var ZodType = class {
1713
1718
  }
1714
1719
  });
1715
1720
  }
1716
- if (!result) {
1721
+ if (!result2) {
1717
1722
  setError();
1718
1723
  return false;
1719
1724
  } else {
@@ -3208,14 +3213,14 @@ var ZodArray = class _ZodArray extends ZodType {
3208
3213
  if (ctx.common.async) {
3209
3214
  return Promise.all([...ctx.data].map((item, i) => {
3210
3215
  return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3211
- })).then((result2) => {
3212
- return ParseStatus.mergeArray(status, result2);
3216
+ })).then((result3) => {
3217
+ return ParseStatus.mergeArray(status, result3);
3213
3218
  });
3214
3219
  }
3215
- const result = [...ctx.data].map((item, i) => {
3220
+ const result2 = [...ctx.data].map((item, i) => {
3216
3221
  return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
3217
3222
  });
3218
- return ParseStatus.mergeArray(status, result);
3223
+ return ParseStatus.mergeArray(status, result2);
3219
3224
  }
3220
3225
  get element() {
3221
3226
  return this._def.type;
@@ -3620,18 +3625,18 @@ var ZodUnion = class extends ZodType {
3620
3625
  const { ctx } = this._processInputParams(input);
3621
3626
  const options = this._def.options;
3622
3627
  function handleResults(results) {
3623
- for (const result of results) {
3624
- if (result.result.status === "valid") {
3625
- return result.result;
3628
+ for (const result2 of results) {
3629
+ if (result2.result.status === "valid") {
3630
+ return result2.result;
3626
3631
  }
3627
3632
  }
3628
- for (const result of results) {
3629
- if (result.result.status === "dirty") {
3630
- ctx.common.issues.push(...result.ctx.common.issues);
3631
- return result.result;
3633
+ for (const result2 of results) {
3634
+ if (result2.result.status === "dirty") {
3635
+ ctx.common.issues.push(...result2.ctx.common.issues);
3636
+ return result2.result;
3632
3637
  }
3633
3638
  }
3634
- const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
3639
+ const unionErrors = results.map((result2) => new ZodError(result2.ctx.common.issues));
3635
3640
  addIssueToContext(ctx, {
3636
3641
  code: ZodIssueCode.invalid_union,
3637
3642
  unionErrors
@@ -3669,15 +3674,15 @@ var ZodUnion = class extends ZodType {
3669
3674
  },
3670
3675
  parent: null
3671
3676
  };
3672
- const result = option._parseSync({
3677
+ const result2 = option._parseSync({
3673
3678
  data: ctx.data,
3674
3679
  path: ctx.path,
3675
3680
  parent: childCtx
3676
3681
  });
3677
- if (result.status === "valid") {
3678
- return result;
3679
- } else if (result.status === "dirty" && !dirty) {
3680
- dirty = { result, ctx: childCtx };
3682
+ if (result2.status === "valid") {
3683
+ return result2;
3684
+ } else if (result2.status === "dirty" && !dirty) {
3685
+ dirty = { result: result2, ctx: childCtx };
3681
3686
  }
3682
3687
  if (childCtx.common.issues.length) {
3683
3688
  issues.push(childCtx.common.issues);
@@ -4222,9 +4227,9 @@ var ZodFunction = class _ZodFunction extends ZodType {
4222
4227
  error.addIssue(makeArgsIssue(args, e));
4223
4228
  throw error;
4224
4229
  });
4225
- const result = await Reflect.apply(fn, this, parsedArgs);
4226
- const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
4227
- error.addIssue(makeReturnsIssue(result, e));
4230
+ const result2 = await Reflect.apply(fn, this, parsedArgs);
4231
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result2, params).catch((e) => {
4232
+ error.addIssue(makeReturnsIssue(result2, e));
4228
4233
  throw error;
4229
4234
  });
4230
4235
  return parsedReturns;
@@ -4236,10 +4241,10 @@ var ZodFunction = class _ZodFunction extends ZodType {
4236
4241
  if (!parsedArgs.success) {
4237
4242
  throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
4238
4243
  }
4239
- const result = Reflect.apply(fn, this, parsedArgs.data);
4240
- const parsedReturns = me._def.returns.safeParse(result, params);
4244
+ const result2 = Reflect.apply(fn, this, parsedArgs.data);
4245
+ const parsedReturns = me._def.returns.safeParse(result2, params);
4241
4246
  if (!parsedReturns.success) {
4242
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
4247
+ throw new ZodError([makeReturnsIssue(result2, parsedReturns.error)]);
4243
4248
  }
4244
4249
  return parsedReturns.data;
4245
4250
  });
@@ -4491,43 +4496,43 @@ var ZodEffects = class extends ZodType {
4491
4496
  return Promise.resolve(processed).then(async (processed2) => {
4492
4497
  if (status.value === "aborted")
4493
4498
  return INVALID;
4494
- const result = await this._def.schema._parseAsync({
4499
+ const result2 = await this._def.schema._parseAsync({
4495
4500
  data: processed2,
4496
4501
  path: ctx.path,
4497
4502
  parent: ctx
4498
4503
  });
4499
- if (result.status === "aborted")
4504
+ if (result2.status === "aborted")
4500
4505
  return INVALID;
4501
- if (result.status === "dirty")
4502
- return DIRTY(result.value);
4506
+ if (result2.status === "dirty")
4507
+ return DIRTY(result2.value);
4503
4508
  if (status.value === "dirty")
4504
- return DIRTY(result.value);
4505
- return result;
4509
+ return DIRTY(result2.value);
4510
+ return result2;
4506
4511
  });
4507
4512
  } else {
4508
4513
  if (status.value === "aborted")
4509
4514
  return INVALID;
4510
- const result = this._def.schema._parseSync({
4515
+ const result2 = this._def.schema._parseSync({
4511
4516
  data: processed,
4512
4517
  path: ctx.path,
4513
4518
  parent: ctx
4514
4519
  });
4515
- if (result.status === "aborted")
4520
+ if (result2.status === "aborted")
4516
4521
  return INVALID;
4517
- if (result.status === "dirty")
4518
- return DIRTY(result.value);
4522
+ if (result2.status === "dirty")
4523
+ return DIRTY(result2.value);
4519
4524
  if (status.value === "dirty")
4520
- return DIRTY(result.value);
4521
- return result;
4525
+ return DIRTY(result2.value);
4526
+ return result2;
4522
4527
  }
4523
4528
  }
4524
4529
  if (effect.type === "refinement") {
4525
4530
  const executeRefinement = (acc) => {
4526
- const result = effect.refinement(acc, checkCtx);
4531
+ const result2 = effect.refinement(acc, checkCtx);
4527
4532
  if (ctx.common.async) {
4528
- return Promise.resolve(result);
4533
+ return Promise.resolve(result2);
4529
4534
  }
4530
- if (result instanceof Promise) {
4535
+ if (result2 instanceof Promise) {
4531
4536
  throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
4532
4537
  }
4533
4538
  return acc;
@@ -4565,18 +4570,18 @@ var ZodEffects = class extends ZodType {
4565
4570
  });
4566
4571
  if (!isValid(base))
4567
4572
  return INVALID;
4568
- const result = effect.transform(base.value, checkCtx);
4569
- if (result instanceof Promise) {
4573
+ const result2 = effect.transform(base.value, checkCtx);
4574
+ if (result2 instanceof Promise) {
4570
4575
  throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
4571
4576
  }
4572
- return { status: status.value, value: result };
4577
+ return { status: status.value, value: result2 };
4573
4578
  } else {
4574
4579
  return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
4575
4580
  if (!isValid(base))
4576
4581
  return INVALID;
4577
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
4582
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result2) => ({
4578
4583
  status: status.value,
4579
- value: result
4584
+ value: result2
4580
4585
  }));
4581
4586
  });
4582
4587
  }
@@ -4673,18 +4678,18 @@ var ZodCatch = class extends ZodType {
4673
4678
  issues: []
4674
4679
  }
4675
4680
  };
4676
- const result = this._def.innerType._parse({
4681
+ const result2 = this._def.innerType._parse({
4677
4682
  data: newCtx.data,
4678
4683
  path: newCtx.path,
4679
4684
  parent: {
4680
4685
  ...newCtx
4681
4686
  }
4682
4687
  });
4683
- if (isAsync(result)) {
4684
- return result.then((result2) => {
4688
+ if (isAsync(result2)) {
4689
+ return result2.then((result3) => {
4685
4690
  return {
4686
4691
  status: "valid",
4687
- value: result2.status === "valid" ? result2.value : this._def.catchValue({
4692
+ value: result3.status === "valid" ? result3.value : this._def.catchValue({
4688
4693
  get error() {
4689
4694
  return new ZodError(newCtx.common.issues);
4690
4695
  },
@@ -4695,7 +4700,7 @@ var ZodCatch = class extends ZodType {
4695
4700
  } else {
4696
4701
  return {
4697
4702
  status: "valid",
4698
- value: result.status === "valid" ? result.value : this._def.catchValue({
4703
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
4699
4704
  get error() {
4700
4705
  return new ZodError(newCtx.common.issues);
4701
4706
  },
@@ -4809,14 +4814,14 @@ var ZodPipeline = class _ZodPipeline extends ZodType {
4809
4814
  };
4810
4815
  var ZodReadonly = class extends ZodType {
4811
4816
  _parse(input) {
4812
- const result = this._def.innerType._parse(input);
4817
+ const result2 = this._def.innerType._parse(input);
4813
4818
  const freeze = (data) => {
4814
4819
  if (isValid(data)) {
4815
4820
  data.value = Object.freeze(data.value);
4816
4821
  }
4817
4822
  return data;
4818
4823
  };
4819
- return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
4824
+ return isAsync(result2) ? result2.then((data) => freeze(data)) : freeze(result2);
4820
4825
  }
4821
4826
  unwrap() {
4822
4827
  return this._def.innerType;
@@ -4983,7 +4988,7 @@ var DetectionInputSchema = external_exports.object({
4983
4988
  ip: external_exports.string().optional(),
4984
4989
  ipAddress: external_exports.string().optional(),
4985
4990
  // Alias for ip
4986
- headers: external_exports.record(external_exports.string()).optional(),
4991
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
4987
4992
  url: external_exports.string().optional(),
4988
4993
  method: external_exports.string().optional(),
4989
4994
  body: external_exports.unknown().optional(),
@@ -4992,19 +4997,25 @@ var DetectionInputSchema = external_exports.object({
4992
4997
  var RequestContextSchema = external_exports.object({
4993
4998
  userAgent: external_exports.string().optional(),
4994
4999
  ipAddress: external_exports.string().optional(),
4995
- headers: external_exports.record(external_exports.string()).optional(),
5000
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
4996
5001
  url: external_exports.string().optional(),
4997
5002
  method: external_exports.string().optional(),
4998
5003
  body: external_exports.unknown().optional(),
4999
5004
  timestamp: external_exports.date().default(() => /* @__PURE__ */ new Date())
5000
5005
  });
5001
5006
  var DetectionSignalSchema = external_exports.object({
5002
- signalType: external_exports.enum(["signature", "pattern", "behavioral", "network", "fingerprint"]),
5003
- confidence: external_exports.number().min(0).max(100),
5004
- weight: external_exports.number().min(0).max(1),
5005
- source: external_exports.string(),
5006
- explanation: external_exports.string(),
5007
- metadata: external_exports.record(external_exports.unknown()).optional()
5007
+ signalType: external_exports.enum(["signature", "pattern", "behavioral", "network", "fingerprint"]).describe(
5008
+ "Evidence plane this signal was observed on: cryptographic signature, User-Agent/header pattern, behavioral interaction, network/IP, or transport fingerprint."
5009
+ ),
5010
+ confidence: external_exports.number().min(0).max(100).describe("This signal's own confidence contribution on the 0-100 scale."),
5011
+ weight: external_exports.number().min(0).max(1).describe("This signal's relative weight (0-1) in the combined verdict."),
5012
+ source: external_exports.string().describe(
5013
+ "Machine-readable evidence source (e.g. 'user_agent_pattern', 'vendor_ip_feed', 'transport.ja4', 'mcp_i'). New signal families (e.g. request-velocity, platform bot-management corroboration) appear as new source values: additive, never a breaking change."
5014
+ ),
5015
+ explanation: external_exports.string().describe("Human-readable explanation of what this signal observed. Prose, not a contract."),
5016
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
5017
+ "Optional source-specific structured details (e.g. the matched pattern, the vendor feed name)."
5018
+ )
5008
5019
  });
5009
5020
  var ReasoningStepSchema = external_exports.object({
5010
5021
  signalType: external_exports.string(),
@@ -5016,9 +5027,11 @@ var ReasoningStepSchema = external_exports.object({
5016
5027
  });
5017
5028
  var TraceStepSchema = external_exports.object({
5018
5029
  /**
5019
- * Stable stage identifier. Canonical names: `"detection"` | `"identity"`
5020
- * | `"scope"` | `"reputation"` | `"policy"`. Mirrors `TraceStep::name`
5021
- * on the Rust side.
5030
+ * Stable stage identifier. Canonical names: `"detection"` (PlainHttp) or
5031
+ * `"identity"` | `"signature"` | `"revocation"` | `"expiration"` |
5032
+ * `"scope"` | `"reputation"` | `"policy"` (MCP-I's 7-stage pipeline).
5033
+ * Not a union on the wire — new step names are non-breaking. Mirrors
5034
+ * `TraceStep::name` on the Rust side.
5022
5035
  */
5023
5036
  name: external_exports.string(),
5024
5037
  /**
@@ -5044,6 +5057,7 @@ var DetectionReasoningSchema = external_exports.object({
5044
5057
  primaryFactors: external_exports.array(external_exports.string()),
5045
5058
  supportingEvidence: external_exports.array(external_exports.string()),
5046
5059
  confidenceBreakdown: external_exports.record(
5060
+ external_exports.string(),
5047
5061
  external_exports.object({
5048
5062
  confidence: external_exports.number().min(0).max(100),
5049
5063
  weight: external_exports.number().min(0).max(1),
@@ -5060,7 +5074,7 @@ var EngineInfoSchema = external_exports.object({
5060
5074
  rulesetHash: external_exports.string(),
5061
5075
  rulesetVersion: external_exports.string(),
5062
5076
  buildSha: external_exports.string().optional(),
5063
- extras: external_exports.record(external_exports.unknown()).optional()
5077
+ extras: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
5064
5078
  });
5065
5079
  var DetectionDetailSchema = external_exports.object({
5066
5080
  // Core fields
@@ -5113,6 +5127,11 @@ var DetectionDetailSchema = external_exports.object({
5113
5127
  "kyaos_handshake",
5114
5128
  "kya-http",
5115
5129
  "kya-http-delegated",
5130
+ // Tier-1 RFC 9421 (Web Bot Auth) verification. The engine emits this
5131
+ // on a verified HTTP Message Signature (api.rs Tier-1 path); without
5132
+ // it here, Zod-validating a Tier-1 verdict rejects a legitimately
5133
+ // signature-verified agent.
5134
+ "tier1_rfc9421",
5116
5135
  "none",
5117
5136
  "error"
5118
5137
  ]).optional(),
@@ -5133,7 +5152,7 @@ var DetectionDetailSchema = external_exports.object({
5133
5152
  recommendations: external_exports.array(external_exports.string()).optional()
5134
5153
  }).optional(),
5135
5154
  // Metadata
5136
- metadata: external_exports.record(external_exports.unknown()).optional(),
5155
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
5137
5156
  timestamp: external_exports.union([external_exports.date(), external_exports.number()]).default(() => /* @__PURE__ */ new Date()),
5138
5157
  requestId: external_exports.string().optional(),
5139
5158
  /** Engine self-identification — see EngineInfoSchema. Optional for
@@ -5294,7 +5313,7 @@ var AgentPatternSchema = external_exports.object({
5294
5313
  type: AgentTypeSchema,
5295
5314
  name: external_exports.string(),
5296
5315
  patterns: external_exports.array(external_exports.string()),
5297
- headers: external_exports.record(external_exports.string()).optional(),
5316
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
5298
5317
  ipRanges: external_exports.array(external_exports.string()).optional(),
5299
5318
  confidence: external_exports.number().min(0).max(1).default(0.8),
5300
5319
  category: external_exports.enum([
@@ -5383,6 +5402,321 @@ function normalizeConfidence(value, context) {
5383
5402
  }
5384
5403
  return Math.max(0, Math.min(value, 1));
5385
5404
  }
5405
+ var ENTROPY_CONFIDENCE_FLOOR = 0.02;
5406
+ var ENTROPY_CONFIDENCE_CEILING = 0.98;
5407
+ var CONFIDENCE_SCALE_BITS = 8;
5408
+ var GROUP_DISCOUNT = 0.5;
5409
+ var PLANE_DISCOUNT = 0.75;
5410
+ var TIER_INFO_BITS = {
5411
+ high: 6,
5412
+ medium: 3,
5413
+ low: 1
5414
+ };
5415
+ var MIN_COINCIDENCE_PROBABILITY = 1e-6;
5416
+ function signalInfoBits(signal) {
5417
+ if (signal.mode === "never") return 0;
5418
+ if (signal.u !== null && Number.isFinite(signal.u)) {
5419
+ const u = Math.min(Math.max(signal.u, MIN_COINCIDENCE_PROBABILITY), 1);
5420
+ return -Math.log2(u);
5421
+ }
5422
+ return TIER_INFO_BITS[signal.tier] ?? 0;
5423
+ }
5424
+ function sortedGeometricSum(values, discount) {
5425
+ return [...values].sort((a, b) => b - a).reduce((sum, value, rank) => sum + value * discount ** rank, 0);
5426
+ }
5427
+ function computeEntropyConfidence(observed) {
5428
+ const bitsByPlaneAndGroup = /* @__PURE__ */ new Map();
5429
+ for (const signal of observed) {
5430
+ const bits = signalInfoBits(signal);
5431
+ if (bits <= 0) continue;
5432
+ let groups = bitsByPlaneAndGroup.get(signal.plane);
5433
+ if (!groups) {
5434
+ groups = /* @__PURE__ */ new Map();
5435
+ bitsByPlaneAndGroup.set(signal.plane, groups);
5436
+ }
5437
+ const bitsInGroup = groups.get(signal.group);
5438
+ if (bitsInGroup) {
5439
+ bitsInGroup.push(bits);
5440
+ } else {
5441
+ groups.set(signal.group, [bits]);
5442
+ }
5443
+ }
5444
+ let totalBits = 0;
5445
+ for (const groups of bitsByPlaneAndGroup.values()) {
5446
+ const groupContributions = Array.from(
5447
+ groups.values(),
5448
+ (bitsInGroup) => sortedGeometricSum(bitsInGroup, GROUP_DISCOUNT)
5449
+ );
5450
+ totalBits += sortedGeometricSum(groupContributions, PLANE_DISCOUNT);
5451
+ }
5452
+ return ENTROPY_CONFIDENCE_FLOOR + (ENTROPY_CONFIDENCE_CEILING - ENTROPY_CONFIDENCE_FLOOR) * (1 - Math.exp(-totalBits / CONFIDENCE_SCALE_BITS));
5453
+ }
5454
+
5455
+ // src/core/verdict-evidence.ts
5456
+ var VerdictEvidenceSchema = external_exports.object({
5457
+ signal: external_exports.string(),
5458
+ plane: DetectionSignalSchema.shape.signalType,
5459
+ weight: external_exports.number().min(0).max(1),
5460
+ probabilityContribution: external_exports.number().min(0).max(1)
5461
+ });
5462
+ function signalContribution(signal) {
5463
+ return signal.weight * (signal.confidence / 100);
5464
+ }
5465
+ function buildVerdictEvidence(signals) {
5466
+ if (!signals || signals.length === 0) return [];
5467
+ const entries = [];
5468
+ for (const raw of signals) {
5469
+ const parsed = DetectionSignalSchema.safeParse(raw);
5470
+ if (!parsed.success) continue;
5471
+ const signal = parsed.data;
5472
+ entries.push({
5473
+ signal: signal.source,
5474
+ plane: signal.signalType,
5475
+ weight: signal.weight,
5476
+ probabilityContribution: signalContribution(signal)
5477
+ });
5478
+ }
5479
+ entries.sort((a, b) => {
5480
+ if (a.plane !== b.plane) return a.plane < b.plane ? -1 : 1;
5481
+ if (a.signal !== b.signal) return a.signal < b.signal ? -1 : 1;
5482
+ return b.probabilityContribution - a.probabilityContribution;
5483
+ });
5484
+ return entries;
5485
+ }
5486
+ var UNCALIBRATED_NOISY_OR_PRIOR = 0.1;
5487
+ function reconstructConfidenceFromEvidence(evidence) {
5488
+ const probabilityAbsent = evidence.reduce(
5489
+ (acc, entry) => acc * (1 - entry.probabilityContribution),
5490
+ 1 - UNCALIBRATED_NOISY_OR_PRIOR
5491
+ );
5492
+ return (1 - probabilityAbsent) * 100;
5493
+ }
5494
+
5495
+ // src/core/detection-reason-codes.ts
5496
+ var DETECTION_REASON_CODES = {
5497
+ // ── Cryptographic / verified attribution (strongest evidence, first) ────
5498
+ /** `verificationMethod === 'kya-http'` — a kya-http/RFC 9421 signature verified. */
5499
+ SIGNATURE_VERIFIED: "detection/signature-verified",
5500
+ /** `verificationMethod === 'kya-http-delegated'` — a verified delegation credential rode the request. */
5501
+ DELEGATION_VERIFIED: "detection/delegation-verified",
5502
+ /** `verificationMethod === 'mcp-i' | 'kya-os'` (the wire values; `isKyaOsWireMethod`) — the MCP-I/KYA-OS handshake verified. */
5503
+ MCP_I_VERIFIED: "detection/mcp-i-verified",
5504
+ /** `verificationMethod === 'did'` — the worker's DID-header scheme verified an Ed25519 signature against the agent's DID Document. */
5505
+ DID_SIGNATURE_VERIFIED: "detection/did-signature-verified",
5506
+ /** `verificationMethod === 'signature'` — the worker's RFC 9421 signature verifier (ChatGPT et al.) verified against the DB-refreshed key directory. */
5507
+ RFC9421_SIGNATURE_VERIFIED: "detection/rfc9421-signature-verified",
5508
+ /** `verificationMethod` starts with `tier1_` (e.g. `tier1_rfc9421`) — the engine's Tier-1 protocol attribution verified. */
5509
+ TIER1_ATTRIBUTION_VERIFIED: "detection/tier1-attribution-verified",
5510
+ /** `verificationMethod === 'error'` — a presented credential was demoted/rejected during verification; see the sibling `kyaErrorCode`. */
5511
+ VERIFICATION_ERROR: "detection/verification-error",
5512
+ // ── Structured evidence signals (one per distinct `signals[].source`) ───
5513
+ /** A `signals[]` entry with `source === 'user_agent_pattern'` — the User-Agent matched a known pattern. */
5514
+ UA_PATTERN_MATCH: "detection/ua-pattern-match",
5515
+ /** `source === 'header_heuristic'` — a header shape/combination heuristic matched. */
5516
+ HEADER_HEURISTIC: "detection/header-heuristic",
5517
+ /** `source === 'ip_heuristic'` — an IP-based heuristic matched. */
5518
+ IP_HEURISTIC: "detection/ip-heuristic",
5519
+ /** `source === 'vendor_ip_feed'` — the request IP matched a known vendor's published IP range. */
5520
+ VENDOR_IP_CORROBORATED: "detection/vendor-ip-corroborated",
5521
+ /** `source === 'transport.ja4'` — the TLS JA4 fingerprint matched a known client library. */
5522
+ JA4_FINGERPRINT_MATCH: "detection/ja4-fingerprint-match",
5523
+ /** `source === 'client.attributes'` — a pixel/beacon-reported client attribute contributed. */
5524
+ CLIENT_ATTRIBUTE_SIGNAL: "detection/client-attribute-signal",
5525
+ /** `source === 'behavioural.interaction'` — a behavioral/interaction signal contributed. */
5526
+ BEHAVIORAL_SIGNAL: "detection/behavioral-signal",
5527
+ /** `source === 'mcp_i'` — an MCP-I header was present (evidence short of a completed handshake). */
5528
+ MCP_I_SIGNAL: "detection/mcp-i-signal",
5529
+ /** `source === 'kya_http_binding'` — a kya-http binding was presented (evidence short of full verification). */
5530
+ KYA_HTTP_BINDING_SIGNAL: "detection/kya-http-binding-signal",
5531
+ /** `source === 'kya_delegation_bearer'` — a delegation bearer credential was presented. */
5532
+ KYA_DELEGATION_BEARER_SIGNAL: "detection/kya-delegation-bearer-signal",
5533
+ /** A `signals[]` entry whose `source` starts with `tier1_` — raw Tier-1 protocol evidence, short of (or alongside) full verification. */
5534
+ TIER1_ATTRIBUTION_SIGNAL: "detection/tier1-attribution-signal",
5535
+ // ── Classification flags ─────────────────────────────────────────────────
5536
+ /** `isAiCrawler === true` — classified as an AI training crawler (GPTBot, ClaudeBot, etc.), not an interactive agent. */
5537
+ AI_CRAWLER_FLAG: "detection/ai-crawler-flag",
5538
+ // ── Zero-evidence fallbacks — an assumed verdict deserves a code saying so
5539
+ // (in the spirit of #4800): these fire ONLY when nothing above matched,
5540
+ // so the mapping never returns an empty list. ───────────────────────────
5541
+ /** `detectionClass === 'human'` with no contributing signals and no verification — the baseline "nothing matched" human path. */
5542
+ ZERO_EVIDENCE_HUMAN: "detection/zero-evidence-human",
5543
+ /** `detectionClass === 'incomplete_data' | 'unknown'` (or absent) — the engine could not classify confidently. */
5544
+ INCOMPLETE_DATA_OVERRIDE: "detection/incomplete-data-override",
5545
+ /** A non-human, non-incomplete-data class (`ai_agent` / `bot` / `automation`) reached with zero contributing signals and no verification — classified on prior/heuristic grounds alone. */
5546
+ CLASSIFIED_WITHOUT_SIGNAL_EVIDENCE: "detection/classified-without-signal-evidence"
5547
+ };
5548
+
5549
+ // src/utils/verification.ts
5550
+ var KYA_OS_HANDSHAKE_METHODS = {
5551
+ /** New canonical engine value. Not emitted yet — accepted on read. */
5552
+ CANONICAL: "kyaos_handshake",
5553
+ /** @deprecated Legacy engine value. Still emitted by the Rust engine. */
5554
+ LEGACY: "mcp_i_handshake"
5555
+ };
5556
+ var KYA_OS_WIRE_METHODS = {
5557
+ /** New canonical wire value. Not emitted yet — accepted on read. */
5558
+ CANONICAL: "kya-os",
5559
+ /** @deprecated Legacy wire value. Still emitted by the gateway worker. */
5560
+ LEGACY: "mcp-i"
5561
+ };
5562
+ function isKyaOsHandshakeMethod(value) {
5563
+ return value === KYA_OS_HANDSHAKE_METHODS.LEGACY || value === KYA_OS_HANDSHAKE_METHODS.CANONICAL;
5564
+ }
5565
+ function isKyaOsWireMethod(value) {
5566
+ return value === KYA_OS_WIRE_METHODS.LEGACY || value === KYA_OS_WIRE_METHODS.CANONICAL;
5567
+ }
5568
+ function normalizeHandshakeMethod(value) {
5569
+ return isKyaOsHandshakeMethod(value) ? KYA_OS_HANDSHAKE_METHODS.CANONICAL : value;
5570
+ }
5571
+ function normalizeWireMethod(value) {
5572
+ return isKyaOsWireMethod(value) ? KYA_OS_WIRE_METHODS.CANONICAL : value;
5573
+ }
5574
+ function getVerificationMethodDescription(method) {
5575
+ switch (normalizeHandshakeMethod(method)) {
5576
+ case "signature":
5577
+ return "HTTP Signature Verification";
5578
+ case "pattern":
5579
+ return "User-Agent Pattern Matching";
5580
+ case "behavioral":
5581
+ return "Behavioral Analysis";
5582
+ case "network":
5583
+ return "Network-based Detection";
5584
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL:
5585
+ return "MCP Handshake Detection";
5586
+ case "error":
5587
+ return "Detection Error";
5588
+ case "none":
5589
+ default:
5590
+ return "No Verification";
5591
+ }
5592
+ }
5593
+ function getVerificationReliability(method) {
5594
+ switch (normalizeHandshakeMethod(method)) {
5595
+ case "signature":
5596
+ return 1;
5597
+ // Highest reliability
5598
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL:
5599
+ return 0.95;
5600
+ case "behavioral":
5601
+ return 0.8;
5602
+ case "network":
5603
+ return 0.6;
5604
+ case "pattern":
5605
+ return 0.5;
5606
+ case "none":
5607
+ return 0.3;
5608
+ case "error":
5609
+ default:
5610
+ return 0.1;
5611
+ }
5612
+ }
5613
+ function isHighConfidenceVerification(method) {
5614
+ return method === "signature" || isKyaOsHandshakeMethod(method);
5615
+ }
5616
+ function getVerificationRiskLevel(method, confidence) {
5617
+ if (method === "signature") {
5618
+ return "low";
5619
+ }
5620
+ if (isKyaOsHandshakeMethod(method)) {
5621
+ return "low";
5622
+ }
5623
+ if (confidence >= 0.9) {
5624
+ return method === "behavioral" ? "medium" : "high";
5625
+ }
5626
+ if (confidence >= 0.7) {
5627
+ return "medium";
5628
+ }
5629
+ return "high";
5630
+ }
5631
+
5632
+ // src/core/detection-reason-mapping.ts
5633
+ var VERIFICATION_METHOD_CODES = {
5634
+ "kya-http-delegated": DETECTION_REASON_CODES.DELEGATION_VERIFIED,
5635
+ "kya-http": DETECTION_REASON_CODES.SIGNATURE_VERIFIED,
5636
+ did: DETECTION_REASON_CODES.DID_SIGNATURE_VERIFIED,
5637
+ signature: DETECTION_REASON_CODES.RFC9421_SIGNATURE_VERIFIED,
5638
+ error: DETECTION_REASON_CODES.VERIFICATION_ERROR
5639
+ };
5640
+ var SIGNAL_SOURCE_CODES = {
5641
+ mcp_i: DETECTION_REASON_CODES.MCP_I_SIGNAL,
5642
+ kya_http_binding: DETECTION_REASON_CODES.KYA_HTTP_BINDING_SIGNAL,
5643
+ kya_delegation_bearer: DETECTION_REASON_CODES.KYA_DELEGATION_BEARER_SIGNAL,
5644
+ user_agent_pattern: DETECTION_REASON_CODES.UA_PATTERN_MATCH,
5645
+ header_heuristic: DETECTION_REASON_CODES.HEADER_HEURISTIC,
5646
+ ip_heuristic: DETECTION_REASON_CODES.IP_HEURISTIC,
5647
+ vendor_ip_feed: DETECTION_REASON_CODES.VENDOR_IP_CORROBORATED,
5648
+ "transport.ja4": DETECTION_REASON_CODES.JA4_FINGERPRINT_MATCH,
5649
+ "client.attributes": DETECTION_REASON_CODES.CLIENT_ATTRIBUTE_SIGNAL,
5650
+ "behavioural.interaction": DETECTION_REASON_CODES.BEHAVIORAL_SIGNAL
5651
+ };
5652
+ function mapDetectionToReasonCodes(detail) {
5653
+ const codes = [];
5654
+ const seen = /* @__PURE__ */ new Set();
5655
+ const push = (code) => {
5656
+ if (code && !seen.has(code)) {
5657
+ seen.add(code);
5658
+ codes.push(code);
5659
+ }
5660
+ };
5661
+ const verificationMethod = detail.verificationMethod;
5662
+ if (verificationMethod) {
5663
+ if (verificationMethod.startsWith("tier1_")) {
5664
+ push(DETECTION_REASON_CODES.TIER1_ATTRIBUTION_VERIFIED);
5665
+ } else if (
5666
+ // Dual-accept BOTH value spaces for the KYA-OS handshake: the gateway
5667
+ // worker normalizes to the WIRE values (`mcp-i`/`kya-os`) before
5668
+ // calling in, while the enforce route's engine-refined detail carries
5669
+ // the ENGINE values (`mcp_i_handshake`/`kyaos_handshake`). Routing
5670
+ // both through the shared predicates keeps the alias pairs in exactly
5671
+ // one place and closes the exact single-value-space gap Bugbot
5672
+ // caught on PR #4874.
5673
+ isKyaOsWireMethod(verificationMethod) || isKyaOsHandshakeMethod(verificationMethod)
5674
+ ) {
5675
+ push(DETECTION_REASON_CODES.MCP_I_VERIFIED);
5676
+ } else {
5677
+ push(VERIFICATION_METHOD_CODES[verificationMethod]);
5678
+ }
5679
+ }
5680
+ const presentSources = /* @__PURE__ */ new Set();
5681
+ let hasTier1Signal = false;
5682
+ for (const signal of detail.signals ?? []) {
5683
+ presentSources.add(signal.source);
5684
+ if (signal.source.startsWith("tier1_")) hasTier1Signal = true;
5685
+ }
5686
+ for (const source of Object.keys(SIGNAL_SOURCE_CODES)) {
5687
+ if (presentSources.has(source)) push(SIGNAL_SOURCE_CODES[source]);
5688
+ }
5689
+ if (hasTier1Signal) {
5690
+ push(DETECTION_REASON_CODES.TIER1_ATTRIBUTION_SIGNAL);
5691
+ }
5692
+ if (detail.isAiCrawler) {
5693
+ push(DETECTION_REASON_CODES.AI_CRAWLER_FLAG);
5694
+ }
5695
+ if (codes.length === 0) {
5696
+ if (detail.detectionClass === "human") {
5697
+ push(DETECTION_REASON_CODES.ZERO_EVIDENCE_HUMAN);
5698
+ } else if (detail.detectionClass === "incomplete_data" || detail.detectionClass === "unknown" || !detail.detectionClass) {
5699
+ push(DETECTION_REASON_CODES.INCOMPLETE_DATA_OVERRIDE);
5700
+ } else {
5701
+ push(DETECTION_REASON_CODES.CLASSIFIED_WITHOUT_SIGNAL_EVIDENCE);
5702
+ }
5703
+ }
5704
+ return codes;
5705
+ }
5706
+ var MAX_REASON_CODES_ON_WIRE = 5;
5707
+ var MAX_REASON_CODES_HEADER_BYTES = 256;
5708
+ var HEADER_BYTES_ENCODER = new TextEncoder();
5709
+ function formatReasonCodesHeader(codes) {
5710
+ const capped = codes.slice(0, MAX_REASON_CODES_ON_WIRE);
5711
+ while (capped.length > 0) {
5712
+ const joined = capped.join(",");
5713
+ if (HEADER_BYTES_ENCODER.encode(joined).byteLength <= MAX_REASON_CODES_HEADER_BYTES) {
5714
+ return joined;
5715
+ }
5716
+ capped.pop();
5717
+ }
5718
+ return "";
5719
+ }
5386
5720
 
5387
5721
  // src/config/shield.ts
5388
5722
  var CacheConfigSchema = external_exports.object({
@@ -5436,7 +5770,7 @@ var AgentShieldConfigSchema = external_exports.object({
5436
5770
  wasm: WasmConfigSchema.optional(),
5437
5771
  // Custom rules and patterns
5438
5772
  customRules: external_exports.array(external_exports.string()).optional(),
5439
- customPatterns: external_exports.record(external_exports.string()).optional(),
5773
+ customPatterns: external_exports.record(external_exports.string(), external_exports.string()).optional(),
5440
5774
  // Allowlists and blocklists
5441
5775
  allowedAgents: external_exports.array(external_exports.string()).optional(),
5442
5776
  blockedAgents: external_exports.array(external_exports.string()).optional(),
@@ -5473,7 +5807,7 @@ var ResponseActionSchema = external_exports.object({
5473
5807
  statusCode: external_exports.number().default(403),
5474
5808
  message: external_exports.string().default("Access denied"),
5475
5809
  redirect: external_exports.string().optional(),
5476
- addHeaders: external_exports.record(external_exports.string()).optional(),
5810
+ addHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional(),
5477
5811
  customResponse: external_exports.any().optional()
5478
5812
  });
5479
5813
  var EventConfigSchema = external_exports.object({
@@ -5506,7 +5840,7 @@ var MiddlewareSessionDataSchema = external_exports.object({
5506
5840
  firstSeen: external_exports.number(),
5507
5841
  lastSeen: external_exports.number(),
5508
5842
  requestCount: external_exports.number(),
5509
- metadata: external_exports.record(external_exports.any()).optional()
5843
+ metadata: external_exports.record(external_exports.string(), external_exports.any()).optional()
5510
5844
  });
5511
5845
  var MiddlewareConfigSchema = external_exports.object({
5512
5846
  action: MiddlewareActionSchema.default("log"),
@@ -5634,7 +5968,16 @@ var KNOWN_AGENT_PATTERNS = [
5634
5968
  type: "anthropic",
5635
5969
  name: "Anthropic-AI Crawler",
5636
5970
  patterns: ["anthropic-ai"],
5637
- confidence: 0.9,
5971
+ // 0.95, matching every other single-exact-token vendor crawler
5972
+ // (openai-gptbot, anthropic-claudebot, meta-externalagent,
5973
+ // gemini-deep-research, deepseek-bot). Previously 0.9, tied with
5974
+ // anthropic-generic below — classifyByUserAgent picks the first
5975
+ // match on a confidence tie (strict `>`, no stable order), so an
5976
+ // 'anthropic-ai' UA could resolve to either row depending on DB
5977
+ // iteration order, reopening the exact misclassification this
5978
+ // taxonomy split retires the token to fix. Caught by Bugbot on
5979
+ // #4172 once the migration landing this row made the tie live.
5980
+ confidence: 0.95,
5638
5981
  category: "scraper",
5639
5982
  isLegitimate: true
5640
5983
  },
@@ -5711,7 +6054,8 @@ var KNOWN_AGENT_PATTERNS = [
5711
6054
  },
5712
6055
  {
5713
6056
  // ORDERING NOTE: `gemini-deep-research` MUST appear BEFORE
5714
- // `google-bard` so the more-specific 'Gemini-Deep-Research'
6057
+ // `gemini` (renamed from `google-bard`, migration 0201) so the
6058
+ // more-specific 'Gemini-Deep-Research'
5715
6059
  // pattern wins under the engine's first-match-wins iteration over
5716
6060
  // AI_AGENT_PATTERNS. The legacy YAML→Rust output collapsed all
5717
6061
  // Google patterns under a single "Google AI" name with identical
@@ -5730,9 +6074,22 @@ var KNOWN_AGENT_PATTERNS = [
5730
6074
  isLegitimate: true
5731
6075
  },
5732
6076
  {
5733
- id: "google-bard",
6077
+ // Renamed from 'google-bard' (migration 0201, P4 follow-up). The prior
6078
+ // fix (Fix-Gemini-Mislabeled-As-Google-Bard-1) deliberately left the id
6079
+ // as `google-bard` and only renamed the human-facing `name` below,
6080
+ // because the id is the stable codegen/stored key (Rust pattern ids via
6081
+ // build.rs -> known-agent-patterns.json, the agent_types.name DB row,
6082
+ // `agent-classification.service.ts`'s directMappings). This PR does the
6083
+ // full id rename instead: verified zero live project/org policies
6084
+ // (cedar_policy_text, allowed/denied agent-type lists) reference the
6085
+ // 'google-bard' slug (checked against a Neon branch off prod main,
6086
+ // 2026-08-14), so the earlier narrower fix's risk no longer applies.
6087
+ // `agent_types.agent_did` already reads
6088
+ // `did:web:knowthat.ai:agents:gemini` — this id rename just catches the
6089
+ // codegen/DB slug up to what the DID already assumed.
6090
+ id: "gemini",
5734
6091
  type: "google",
5735
- name: "Google Bard",
6092
+ name: "Google Gemini",
5736
6093
  // Engine-Pattern-Codegen-Retirement-1 corrections:
5737
6094
  // - REMOVED `Google-InspectionTool` from this entry. The legacy
5738
6095
  // YAML→Rust pipeline classified Google-InspectionTool as a
@@ -5745,17 +6102,45 @@ var KNOWN_AGENT_PATTERNS = [
5745
6102
  // YAML had it under Google AI) and `GoogleAgent-Mariner`
5746
6103
  // (Google's browser-controlling agent product) — both were in
5747
6104
  // the retired pipeline, never in TS.
5748
- // - The broad 'gemini' pattern below shadows narrower Gemini-*
5749
- // UAs under first-match-wins. The Gemini-Deep-Research entry
5750
- // above must stay ordered first to avoid being shadowed.
6105
+ //
6106
+ // Engine-Pattern-Codegen-Retirement-2 (this PR, Bugbot #ae22713a and
6107
+ // #6984df6d): bare 'gemini'/'palm' matched `GeminiiOS` (Google's own
6108
+ // Gemini app rendering a page in its in-app webview — a HUMAN, not an
6109
+ // agent) as a plain unanchored substring — `build.rs` emits every
6110
+ // pattern here into `format!("(?i){pattern}")` with no escaping and no
6111
+ // boundary, so a literal `'gemini'` compiles to `Regex::new("(?i)gemini")`,
6112
+ // which `.is_match()`-style scanning matches anywhere. That reopened,
6113
+ // one layer down, the exact hole migration 0208 closed on the
6114
+ // DB-side `classifyByUserAgent` path: this PR's own `lookupAgentDid`
6115
+ // fix matches the WASM engine's emitted `name` ('Google Gemini')
6116
+ // against `agent_types.displayName` for the enforce/pixel-track
6117
+ // routes, which run no TS classifier and never touch
6118
+ // `classifyByUserAgent` at all — so `GeminiiOS` could still reach the
6119
+ // live `gemini` DID via this second, engine-only path.
6120
+ //
6121
+ // First attempt was an outright removal, which closed the hole but
6122
+ // also dropped genuine coverage: a bare `Gemini/1.0` or
6123
+ // `Google-Gemini/1.0` UA carrying no specific model suffix no longer
6124
+ // matched anything (caught by Bugbot #6984df6d's follow-up review,
6125
+ // and independently by 4 apps/web unit tests asserting exactly that
6126
+ // coverage — see git history). Word-boundary anchors close the false
6127
+ // positive AND keep the coverage: `\bgemini\b` matches `Gemini/1.0`
6128
+ // and `Google-Gemini/1.0` (boundary before the leading `G`/after `-`,
6129
+ // and before the trailing `/`) but NOT `GeminiiOS` (no boundary
6130
+ // between the two `i`s — both are word characters). Same shape for
6131
+ // `\bpalm\b` vs `palm2` (own explicit token, digit is a word
6132
+ // character so no double-match) vs a hypothetical `PalmOS`-style
6133
+ // collision. TS string literals need `\\b` (double backslash) to
6134
+ // produce a literal `\b` in the resulting string — `\b` alone is the
6135
+ // JS backspace escape, not a regex boundary.
5751
6136
  patterns: [
5752
6137
  "Bard",
5753
- "gemini",
6138
+ "\\bgemini\\b",
5754
6139
  "gemini-pro",
5755
6140
  "gemini-1.5",
5756
6141
  "gemini-1.5-pro",
5757
6142
  "gemini-ultra",
5758
- "palm",
6143
+ "\\bpalm\\b",
5759
6144
  "palm2",
5760
6145
  "LaMDA",
5761
6146
  "GoogleAgent-Mariner"
@@ -6040,15 +6425,50 @@ var KNOWN_AGENT_PATTERNS = [
6040
6425
  category: "scraper",
6041
6426
  isLegitimate: true
6042
6427
  },
6428
+ // Amazon Quick — AWS's rendering web crawler (formerly launched as part
6429
+ // of the "Amazon Q" family, since renamed; docs.aws.amazon.com/quick).
6430
+ // UA convention is `amazon-Quick-on-behalf-of-<id>` / AWS's own
6431
+ // documented `aws-quick-on-behalf-of-<UUID>`. Declared BEFORE
6432
+ // `amazon-q` below: the Rust engine's AI_AGENT_PATTERNS match is
6433
+ // first-match-wins in TS source order (see patterns.rs
6434
+ // `analyze_user_agent`), and 'Amazon-Quick' is a superstring of
6435
+ // 'Amazon-Q' below, so the more specific pattern must be tried first
6436
+ // there. `classifyByUserAgent` (TS/DB path) doesn't use source order —
6437
+ // it tie-breaks on confidence — so this row's confidence must also
6438
+ // stay strictly above `amazon-q`'s (mirrors the anthropic-ai-crawler /
6439
+ // anthropic-generic split: specific crawler token > broad label).
6440
+ // is_legitimate: AWS's docs describe it as a JS-rendering, non-
6441
+ // interactive crawler (no simulated user interaction) — the taxonomy's
6442
+ // `scraper` bucket, not `ai_assistant` (real-time human-driven use).
6443
+ {
6444
+ id: "amazon-quick",
6445
+ type: "amazon",
6446
+ name: "Amazon Quick",
6447
+ patterns: ["Amazon-Quick", "aws-quick"],
6448
+ confidence: 0.95,
6449
+ category: "scraper",
6450
+ isLegitimate: true
6451
+ },
6043
6452
  // Amazon Q + NovaAct — Amazon's AI assistant product family.
6044
6453
  // NovaAct is the AWS-branded browser-controlling agent (parallel to
6045
6454
  // Anthropic's Claude-Code, Google's GoogleAgent-Mariner).
6455
+ //
6456
+ // Confidence intentionally below `amazon-quick` above, by MORE than the
6457
+ // TS/DB path's max multi-pattern bonus (+5 for 2+ pattern matches — see
6458
+ // calculateConfidence in agent-classification.service.ts): 0.85 not 0.90.
6459
+ // A UA containing both of amazon-q's patterns ('Amazon-Q' — substring-
6460
+ // matched by 'Amazon-Quick' — and 'NovaAct', plausible on the same
6461
+ // product family's browser-driving traffic) would score 90 + 5 = 95,
6462
+ // tying amazon-quick's flat 95 and recreating the exact order-dependent
6463
+ // tie this split exists to eliminate (own regression test:
6464
+ // agent-classification-amazon-quick-crawler-tie.test.ts). At 0.85 the
6465
+ // bonus tops out at 85 + 5 = 90, still short of amazon-quick's 95.
6046
6466
  {
6047
6467
  id: "amazon-q",
6048
6468
  type: "amazon",
6049
6469
  name: "Amazon Q",
6050
6470
  patterns: ["Amazon-Q", "NovaAct"],
6051
- confidence: 0.95,
6471
+ confidence: 0.85,
6052
6472
  category: "ai_assistant",
6053
6473
  isLegitimate: true
6054
6474
  },
@@ -6227,21 +6647,21 @@ var TRADITIONAL_BOT_PATTERNS = [
6227
6647
  {
6228
6648
  id: "googlebot",
6229
6649
  type: "search_engine",
6230
- name: "GoogleBot",
6650
+ name: "Googlebot",
6231
6651
  patterns: ["googlebot", "google-structured-data-testing-tool"],
6232
6652
  confidence: 0.95
6233
6653
  },
6234
6654
  {
6235
6655
  id: "bingbot",
6236
6656
  type: "search_engine",
6237
- name: "BingBot",
6657
+ name: "Bingbot",
6238
6658
  patterns: ["bingbot", "bingpreview", "msnbot"],
6239
6659
  confidence: 0.95
6240
6660
  },
6241
6661
  {
6242
6662
  id: "yandexbot",
6243
6663
  type: "search_engine",
6244
- name: "YandexBot",
6664
+ name: "Yandexbot",
6245
6665
  patterns: ["yandexbot", "yandex"],
6246
6666
  confidence: 0.9
6247
6667
  },
@@ -6249,14 +6669,14 @@ var TRADITIONAL_BOT_PATTERNS = [
6249
6669
  {
6250
6670
  id: "facebook",
6251
6671
  type: "social_media",
6252
- name: "Facebook",
6672
+ name: "Meta Crawler",
6253
6673
  patterns: ["facebookexternalhit", "facebookcatalog", "Meta-ExternalAgent"],
6254
6674
  confidence: 0.9
6255
6675
  },
6256
6676
  {
6257
6677
  id: "twitter",
6258
6678
  type: "social_media",
6259
- name: "Twitter",
6679
+ name: "Twitterbot",
6260
6680
  patterns: ["twitterbot"],
6261
6681
  confidence: 0.9
6262
6682
  },
@@ -6271,7 +6691,7 @@ var TRADITIONAL_BOT_PATTERNS = [
6271
6691
  {
6272
6692
  id: "ahrefs",
6273
6693
  type: "seo_tool",
6274
- name: "Ahrefs",
6694
+ name: "Ahrefsbot",
6275
6695
  patterns: ["ahrefsbot"],
6276
6696
  confidence: 0.85
6277
6697
  },
@@ -6279,7 +6699,7 @@ var TRADITIONAL_BOT_PATTERNS = [
6279
6699
  {
6280
6700
  id: "generic-crawler",
6281
6701
  type: "crawler",
6282
- name: "Generic Crawler",
6702
+ name: "Generic Bot",
6283
6703
  patterns: ["crawler", "spider", "bot/"],
6284
6704
  confidence: 0.6
6285
6705
  },
@@ -6487,6 +6907,9 @@ function getEnvVar(key) {
6487
6907
  return process.env[key] || DEFAULT_ENV_VARS[key];
6488
6908
  }
6489
6909
 
6910
+ // src/constants/delegation.ts
6911
+ var ATTESTED_BEARER_MAX_TTL_SECONDS = 900;
6912
+
6490
6913
  // src/constants/errors.ts
6491
6914
  var ERROR_CATEGORIES = {
6492
6915
  AUTH: "AUTH",
@@ -6523,7 +6946,11 @@ var VALIDATION_ERRORS = {
6523
6946
  INVALID_URL: "VALIDATION_INVALID_URL",
6524
6947
  INVALID_UUID: "VALIDATION_INVALID_UUID",
6525
6948
  INVALID_IP_ADDRESS: "VALIDATION_INVALID_IP_ADDRESS",
6526
- INVALID_USER_AGENT: "VALIDATION_INVALID_USER_AGENT"
6949
+ INVALID_USER_AGENT: "VALIDATION_INVALID_USER_AGENT",
6950
+ BAD_REQUEST: "VALIDATION_BAD_REQUEST",
6951
+ INVALID_START_DATE: "VALIDATION_INVALID_START_DATE",
6952
+ INVALID_END_DATE: "VALIDATION_INVALID_END_DATE",
6953
+ INVALID_DATE_RANGE: "VALIDATION_INVALID_DATE_RANGE"
6527
6954
  };
6528
6955
  var DETECTION_ERRORS = {
6529
6956
  DETECTION_FAILED: "DETECTION_FAILED",
@@ -6548,7 +6975,8 @@ var PERMISSION_ERRORS = {
6548
6975
  RESOURCE_ACCESS_DENIED: "PERMISSION_ACCESS_DENIED",
6549
6976
  OPERATION_NOT_ALLOWED: "PERMISSION_OPERATION_NOT_ALLOWED",
6550
6977
  PROJECT_ACCESS_DENIED: "PERMISSION_PROJECT_ACCESS_DENIED",
6551
- PIXEL_ACCESS_DENIED: "PERMISSION_PIXEL_ACCESS_DENIED"
6978
+ PIXEL_ACCESS_DENIED: "PERMISSION_PIXEL_ACCESS_DENIED",
6979
+ FORBIDDEN: "PERMISSION_FORBIDDEN"
6552
6980
  };
6553
6981
  var NETWORK_ERRORS = {
6554
6982
  CONNECTION_FAILED: "NETWORK_CONNECTION_FAILED",
@@ -6565,7 +6993,8 @@ var INTERNAL_ERRORS = {
6565
6993
  CONFIGURATION_ERROR: "INTERNAL_CONFIGURATION_ERROR",
6566
6994
  INITIALIZATION_ERROR: "INTERNAL_INITIALIZATION_ERROR",
6567
6995
  PROCESSING_ERROR: "INTERNAL_PROCESSING_ERROR",
6568
- UNKNOWN_ERROR: "INTERNAL_UNKNOWN_ERROR"
6996
+ UNKNOWN_ERROR: "INTERNAL_UNKNOWN_ERROR",
6997
+ SERVICE_UNAVAILABLE_TRANSIENT: "SERVICE_UNAVAILABLE_TRANSIENT"
6569
6998
  };
6570
6999
  var SESSION_ERRORS = {
6571
7000
  SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
@@ -6583,7 +7012,10 @@ var PIXEL_ERRORS = {
6583
7012
  PIXEL_DOMAIN_NOT_ALLOWED: "PIXEL_DOMAIN_NOT_ALLOWED",
6584
7013
  PIXEL_PATH_SKIPPED: "PIXEL_PATH_SKIPPED",
6585
7014
  PIXEL_EVENT_INVALID: "PIXEL_EVENT_INVALID",
6586
- PIXEL_BATCH_TOO_LARGE: "PIXEL_BATCH_TOO_LARGE"
7015
+ PIXEL_BATCH_TOO_LARGE: "PIXEL_BATCH_TOO_LARGE",
7016
+ MISSING_PIXEL_ID: "MISSING_PIXEL_ID",
7017
+ INVALID_EDGE_SIGNATURE: "INVALID_EDGE_SIGNATURE",
7018
+ DETECTION_STORAGE_FAILED: "DETECTION_STORAGE_FAILED"
6587
7019
  };
6588
7020
  var API_ERRORS = {
6589
7021
  ENDPOINT_NOT_FOUND: "API_ENDPOINT_NOT_FOUND",
@@ -6593,6 +7025,27 @@ var API_ERRORS = {
6593
7025
  RESPONSE_TOO_LARGE: "API_RESPONSE_TOO_LARGE",
6594
7026
  REQUEST_TOO_LARGE: "API_REQUEST_TOO_LARGE"
6595
7027
  };
7028
+ var BILLING_ERRORS = {
7029
+ LIMIT_EXCEEDED: "LIMIT_EXCEEDED",
7030
+ BILLING_SUSPENDED: "BILLING_SUSPENDED",
7031
+ BILLING_GRACE_PERIOD: "BILLING_GRACE_PERIOD"
7032
+ };
7033
+ var RESOURCE_ERRORS = {
7034
+ CONFLICT: "CONFLICT",
7035
+ PROJECT_NOT_FOUND: "PROJECT_NOT_FOUND",
7036
+ REVIEW_REQUIRED: "REVIEW_REQUIRED"
7037
+ };
7038
+ var POLICY_ERRORS = {
7039
+ POLICY_FETCH_FAILED: "POLICY_FETCH_FAILED"
7040
+ };
7041
+ var BARE_ERRORS = {
7042
+ BARE_VALIDATION_ERROR: "VALIDATION_ERROR",
7043
+ BARE_INTERNAL_ERROR: "INTERNAL_ERROR"
7044
+ };
7045
+ var LOWERCASE_ERRORS = {
7046
+ LOWERCASE_INVALID_JSON: "invalid_json",
7047
+ LOWERCASE_VALIDATION_ERROR: "validation_error"
7048
+ };
6596
7049
  var ERROR_CODES = {
6597
7050
  ...AUTH_ERRORS,
6598
7051
  ...VALIDATION_ERRORS,
@@ -6603,7 +7056,12 @@ var ERROR_CODES = {
6603
7056
  ...INTERNAL_ERRORS,
6604
7057
  ...SESSION_ERRORS,
6605
7058
  ...PIXEL_ERRORS,
6606
- ...API_ERRORS
7059
+ ...API_ERRORS,
7060
+ ...BILLING_ERRORS,
7061
+ ...RESOURCE_ERRORS,
7062
+ ...POLICY_ERRORS,
7063
+ ...BARE_ERRORS,
7064
+ ...LOWERCASE_ERRORS
6607
7065
  };
6608
7066
  var ERROR_MESSAGES = {
6609
7067
  // Authentication
@@ -6627,6 +7085,10 @@ var ERROR_MESSAGES = {
6627
7085
  [VALIDATION_ERRORS.INVALID_UUID]: "Invalid UUID format",
6628
7086
  [VALIDATION_ERRORS.INVALID_IP_ADDRESS]: "Invalid IP address format",
6629
7087
  [VALIDATION_ERRORS.INVALID_USER_AGENT]: "Invalid or missing user agent",
7088
+ [VALIDATION_ERRORS.BAD_REQUEST]: "Bad request",
7089
+ [VALIDATION_ERRORS.INVALID_START_DATE]: "Invalid request data",
7090
+ [VALIDATION_ERRORS.INVALID_END_DATE]: "Invalid request data",
7091
+ [VALIDATION_ERRORS.INVALID_DATE_RANGE]: "Invalid request data",
6630
7092
  // Detection
6631
7093
  [DETECTION_ERRORS.DETECTION_FAILED]: "Agent detection failed",
6632
7094
  [DETECTION_ERRORS.INSUFFICIENT_DATA]: "Insufficient data for detection",
@@ -6649,6 +7111,7 @@ var ERROR_MESSAGES = {
6649
7111
  [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: "Operation not allowed",
6650
7112
  [PERMISSION_ERRORS.PROJECT_ACCESS_DENIED]: "Project access denied",
6651
7113
  [PERMISSION_ERRORS.PIXEL_ACCESS_DENIED]: "Pixel access denied",
7114
+ [PERMISSION_ERRORS.FORBIDDEN]: "Access denied",
6652
7115
  // Network
6653
7116
  [NETWORK_ERRORS.CONNECTION_FAILED]: "Connection failed",
6654
7117
  [NETWORK_ERRORS.TIMEOUT]: "Request timeout",
@@ -6664,6 +7127,7 @@ var ERROR_MESSAGES = {
6664
7127
  [INTERNAL_ERRORS.INITIALIZATION_ERROR]: "Initialization error",
6665
7128
  [INTERNAL_ERRORS.PROCESSING_ERROR]: "Processing error",
6666
7129
  [INTERNAL_ERRORS.UNKNOWN_ERROR]: "An unknown error occurred",
7130
+ [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]: "A dependency is temporarily unavailable. Retry shortly.",
6667
7131
  // Session
6668
7132
  [SESSION_ERRORS.SESSION_NOT_FOUND]: "Session not found",
6669
7133
  [SESSION_ERRORS.SESSION_EXPIRED]: "Session has expired",
@@ -6680,20 +7144,49 @@ var ERROR_MESSAGES = {
6680
7144
  [PIXEL_ERRORS.PIXEL_PATH_SKIPPED]: "Path is configured to be skipped",
6681
7145
  [PIXEL_ERRORS.PIXEL_EVENT_INVALID]: "Invalid pixel event",
6682
7146
  [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: "Event batch exceeds maximum size",
7147
+ [PIXEL_ERRORS.MISSING_PIXEL_ID]: "Project ID is required",
7148
+ [PIXEL_ERRORS.INVALID_EDGE_SIGNATURE]: "Invalid request signature",
7149
+ [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: "Failed to store detection data",
6683
7150
  // API
6684
7151
  [API_ERRORS.ENDPOINT_NOT_FOUND]: "API endpoint not found",
6685
7152
  [API_ERRORS.METHOD_NOT_ALLOWED]: "HTTP method not allowed",
6686
7153
  [API_ERRORS.VERSION_NOT_SUPPORTED]: "API version not supported",
6687
7154
  [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: "Content type not supported",
6688
7155
  [API_ERRORS.RESPONSE_TOO_LARGE]: "Response exceeds maximum size",
6689
- [API_ERRORS.REQUEST_TOO_LARGE]: "Request exceeds maximum size"
7156
+ [API_ERRORS.REQUEST_TOO_LARGE]: "Request exceeds maximum size",
7157
+ // Billing
7158
+ [BILLING_ERRORS.LIMIT_EXCEEDED]: "Billing limit exceeded",
7159
+ [BILLING_ERRORS.BILLING_SUSPENDED]: "Account billing suspended",
7160
+ [BILLING_ERRORS.BILLING_GRACE_PERIOD]: "Account in billing grace period",
7161
+ // Resources
7162
+ [RESOURCE_ERRORS.CONFLICT]: "Resource conflict",
7163
+ [RESOURCE_ERRORS.PROJECT_NOT_FOUND]: "Project not found",
7164
+ [RESOURCE_ERRORS.REVIEW_REQUIRED]: "Deploy requires explicit confirmation of the consequential writes it will perform.",
7165
+ // Policy
7166
+ [POLICY_ERRORS.POLICY_FETCH_FAILED]: "Failed to fetch policy",
7167
+ // Bare (un-prefixed, shared across pixel/openclaw/deploy/shopify/bouncer)
7168
+ [BARE_ERRORS.BARE_VALIDATION_ERROR]: "Invalid request data",
7169
+ [BARE_ERRORS.BARE_INTERNAL_ERROR]: "Internal server error",
7170
+ // Lowercase (kya-os events wire format)
7171
+ [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: "Request body must be valid JSON",
7172
+ [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: "Invalid request body"
6690
7173
  };
6691
7174
  var ERROR_STATUS_CODES = {
7175
+ // 200 OK (billing grace period is a soft warning, not a failure)
7176
+ [BILLING_ERRORS.BILLING_GRACE_PERIOD]: 200,
6692
7177
  // 400 Bad Request
6693
7178
  [VALIDATION_ERRORS.INVALID_REQUEST]: 400,
6694
7179
  [VALIDATION_ERRORS.MISSING_REQUIRED_FIELD]: 400,
6695
7180
  [VALIDATION_ERRORS.INVALID_FIELD_TYPE]: 400,
6696
7181
  [VALIDATION_ERRORS.INVALID_FIELD_VALUE]: 400,
7182
+ [VALIDATION_ERRORS.BAD_REQUEST]: 400,
7183
+ [VALIDATION_ERRORS.INVALID_START_DATE]: 400,
7184
+ [VALIDATION_ERRORS.INVALID_END_DATE]: 400,
7185
+ [VALIDATION_ERRORS.INVALID_DATE_RANGE]: 400,
7186
+ [PIXEL_ERRORS.MISSING_PIXEL_ID]: 400,
7187
+ [BARE_ERRORS.BARE_VALIDATION_ERROR]: 400,
7188
+ [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: 400,
7189
+ [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: 400,
6697
7190
  // 401 Unauthorized
6698
7191
  [AUTH_ERRORS.INVALID_API_KEY]: 401,
6699
7192
  [AUTH_ERRORS.EXPIRED_API_KEY]: 401,
@@ -6701,10 +7194,15 @@ var ERROR_STATUS_CODES = {
6701
7194
  [AUTH_ERRORS.EXPIRED_TOKEN]: 401,
6702
7195
  [AUTH_ERRORS.MISSING_CREDENTIALS]: 401,
6703
7196
  [AUTH_ERRORS.UNAUTHORIZED]: 401,
7197
+ // 402 Payment Required
7198
+ [BILLING_ERRORS.LIMIT_EXCEEDED]: 402,
7199
+ [BILLING_ERRORS.BILLING_SUSPENDED]: 402,
6704
7200
  // 403 Forbidden
6705
7201
  [PERMISSION_ERRORS.INSUFFICIENT_PERMISSIONS]: 403,
6706
7202
  [PERMISSION_ERRORS.RESOURCE_ACCESS_DENIED]: 403,
6707
7203
  [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: 403,
7204
+ [PERMISSION_ERRORS.FORBIDDEN]: 403,
7205
+ [PIXEL_ERRORS.INVALID_EDGE_SIGNATURE]: 403,
6708
7206
  // 404 Not Found
6709
7207
  [PERMISSION_ERRORS.RESOURCE_NOT_FOUND]: 404,
6710
7208
  [API_ERRORS.ENDPOINT_NOT_FOUND]: 404,
@@ -6712,11 +7210,20 @@ var ERROR_STATUS_CODES = {
6712
7210
  [SESSION_ERRORS.SESSION_NOT_FOUND]: 404,
6713
7211
  // 405 Method Not Allowed
6714
7212
  [API_ERRORS.METHOD_NOT_ALLOWED]: 405,
7213
+ // 409 Conflict
7214
+ [RESOURCE_ERRORS.CONFLICT]: 409,
7215
+ // NOTE: RESOURCE_ERRORS.PROJECT_NOT_FOUND deliberately has no entry here.
7216
+ // The pixel API emits it with 400, while enforce and the policy
7217
+ // middleware emit it with 404. There is no single correct status, so it
7218
+ // stays unpinned and callers set their own status per surface. Locked by
7219
+ // a test in __tests__/errors.test.ts.
6715
7220
  // 413 Payload Too Large
6716
7221
  [API_ERRORS.REQUEST_TOO_LARGE]: 413,
6717
7222
  [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: 413,
6718
7223
  // 415 Unsupported Media Type
6719
7224
  [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: 415,
7225
+ // 422 Unprocessable Entity
7226
+ [RESOURCE_ERRORS.REVIEW_REQUIRED]: 422,
6720
7227
  // 429 Too Many Requests
6721
7228
  [RATE_LIMIT_ERRORS.RATE_LIMIT_EXCEEDED]: 429,
6722
7229
  [RATE_LIMIT_ERRORS.BURST_LIMIT_EXCEEDED]: 429,
@@ -6725,10 +7232,14 @@ var ERROR_STATUS_CODES = {
6725
7232
  [INTERNAL_ERRORS.INTERNAL_SERVER_ERROR]: 500,
6726
7233
  [INTERNAL_ERRORS.DATABASE_ERROR]: 500,
6727
7234
  [INTERNAL_ERRORS.PROCESSING_ERROR]: 500,
7235
+ [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: 500,
7236
+ [POLICY_ERRORS.POLICY_FETCH_FAILED]: 500,
7237
+ [BARE_ERRORS.BARE_INTERNAL_ERROR]: 500,
6728
7238
  // 502 Bad Gateway
6729
7239
  [NETWORK_ERRORS.UPSTREAM_ERROR]: 502,
6730
7240
  // 503 Service Unavailable
6731
7241
  [INTERNAL_ERRORS.INITIALIZATION_ERROR]: 503,
7242
+ [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]: 503,
6732
7243
  // 504 Gateway Timeout
6733
7244
  [NETWORK_ERRORS.TIMEOUT]: 504
6734
7245
  };
@@ -7067,12 +7578,7 @@ var USER_AGENT_PATTERNS = {
7067
7578
  UPTIMEROBOT: /UptimeRobot/i,
7068
7579
  PINGDOM: /Pingdom/i,
7069
7580
  NEWRELIC: /NewRelicPinger/i,
7070
- DATADOG: /Datadog/i,
7071
- // Security Scanners
7072
- NESSUS: /Nessus/i,
7073
- NMAP: /Nmap/i,
7074
- BURPSUITE: /BurpSuite/i,
7075
- SQLMAP: /sqlmap/i
7581
+ DATADOG: /Datadog/i
7076
7582
  };
7077
7583
  var HEADER_PATTERNS = {
7078
7584
  // AI-specific headers
@@ -7308,7 +7814,7 @@ var DetectionRequestSchema = external_exports.object({
7308
7814
  userAgent: external_exports.string(),
7309
7815
  // Optional fields
7310
7816
  ipAddress: external_exports.string().optional(),
7311
- headers: external_exports.record(external_exports.string()).optional(),
7817
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
7312
7818
  url: external_exports.string().optional(),
7313
7819
  method: external_exports.string().optional(),
7314
7820
  // Behavioral data
@@ -7404,6 +7910,7 @@ var HealthResponseSchema = external_exports.object({
7404
7910
  version: external_exports.string(),
7405
7911
  uptime: external_exports.number().min(0),
7406
7912
  checks: external_exports.record(
7913
+ external_exports.string(),
7407
7914
  external_exports.object({
7408
7915
  status: external_exports.enum(["pass", "fail"]),
7409
7916
  message: external_exports.string().optional()
@@ -7484,13 +7991,13 @@ var PixelEventSchema = external_exports.object({
7484
7991
  // Request Information
7485
7992
  userAgent: external_exports.string(),
7486
7993
  ipAddress: external_exports.string().optional(),
7487
- headers: external_exports.record(external_exports.string()).optional(),
7994
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
7488
7995
  // Detection Results
7489
7996
  detection: DetectionResultSchema.optional(),
7490
7997
  // Behavioral Data
7491
7998
  behavioral: BehavioralSignalsSchema.optional(),
7492
7999
  // Custom Data
7493
- metadata: external_exports.record(external_exports.unknown()).optional(),
8000
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
7494
8001
  customEventName: external_exports.string().optional()
7495
8002
  });
7496
8003
  var BatchPixelEventRequestSchema = external_exports.object({
@@ -7559,6 +8066,40 @@ var ClientDetectionSchema = external_exports.object({
7559
8066
  scrollEvents: external_exports.number().optional(),
7560
8067
  clickEvents: external_exports.number().optional(),
7561
8068
  touchEvents: external_exports.number().optional(),
8069
+ // Input events dispatched with isTrusted:false (synthetic script/extension
8070
+ // input, never real hardware). Provenance signal for content-script agent
8071
+ // drivers — see human-promotion-audit.untrustedInputShare.
8072
+ untrustedEvents: external_exports.number().optional(),
8073
+ // Timing physics, counters only (checkpoint-detector.js). Bucket edges sit
8074
+ // below the floor a hand showed on the lab gauntlet; the server derives
8075
+ // shares and means (lib/detection/timing-physics.ts). No timestamps,
8076
+ // coordinates, or key identity ever ride here. `timingVersion` names the
8077
+ // detector's guard set (IME, modifier, multi-touch skips) so rows from
8078
+ // different sets can be told apart at calibration.
8079
+ timingVersion: external_exports.number().optional(),
8080
+ keyDwellCount: external_exports.number().optional(),
8081
+ keyDwellUnder5: external_exports.number().optional(),
8082
+ keyDwellSumMs: external_exports.number().optional(),
8083
+ keyGapCount: external_exports.number().optional(),
8084
+ keyGapUnder5: external_exports.number().optional(),
8085
+ pressCount: external_exports.number().optional(),
8086
+ pressAdjacencyCount: external_exports.number().int().nonnegative().optional(),
8087
+ pressAdjacentUnder5: external_exports.number().int().nonnegative().optional(),
8088
+ pressUnder10: external_exports.number().optional(),
8089
+ pressSumMs: external_exports.number().optional(),
8090
+ mouseClicks: external_exports.number().optional(),
8091
+ zeroTrailClicks: external_exports.number().optional(),
8092
+ // Path kinematics, counters only (checkpoint-detector.js), for the driver
8093
+ // that manufactures a hand's timing: coalesced samples per pointermove,
8094
+ // and whether consecutive steps repeat their length or their heading.
8095
+ // Mouse pointer only; no coordinate rides here. `kinematicsVersion` names
8096
+ // the rule set (tolerances, pointer filter) the way `timingVersion` does.
8097
+ kinematicsVersion: external_exports.number().optional(),
8098
+ pointerMoves: external_exports.number().optional(),
8099
+ coalescedMoves: external_exports.number().optional(),
8100
+ stepPairs: external_exports.number().optional(),
8101
+ equalSteps: external_exports.number().optional(),
8102
+ straightSteps: external_exports.number().optional(),
7562
8103
  hasInteraction: external_exports.boolean().optional(),
7563
8104
  // Connection info
7564
8105
  connection: external_exports.object({
@@ -7590,7 +8131,12 @@ var PixelTrackingRequestSchema = external_exports.object({
7590
8131
  // User identification
7591
8132
  userId: external_exports.string().nullable().optional(),
7592
8133
  // Identified user ID
7593
- userTraits: external_exports.record(external_exports.unknown()).optional().refine((traits) => !traits || JSON.stringify(traits).length < 1e4, {
8134
+ // Prior (typically anonymous) user id for an `identify` alias. When present
8135
+ // and different from `userId`, the server COPIES older properties from this
8136
+ // profile onto the newly-identified one (properties are never merged across
8137
+ // profiles automatically). Mirrors the analytics-SDK `identify(previousId)` arg.
8138
+ previousId: external_exports.string().optional(),
8139
+ userTraits: external_exports.record(external_exports.string(), external_exports.unknown()).optional().refine((traits) => !traits || JSON.stringify(traits).length < 1e4, {
7594
8140
  message: "User traits too large (max 10KB)"
7595
8141
  }).refine((traits) => !traits || Object.keys(traits).length < 50, {
7596
8142
  message: "Too many user trait properties (max 50)"
@@ -7600,7 +8146,9 @@ var PixelTrackingRequestSchema = external_exports.object({
7600
8146
  const validateDepth = (obj, depth = 0) => {
7601
8147
  if (depth > 3) return false;
7602
8148
  if (typeof obj !== "object" || obj === null) return true;
7603
- return Object.values(obj).every((val) => validateDepth(val, depth + 1));
8149
+ return Object.values(obj).every(
8150
+ (val) => validateDepth(val, depth + 1)
8151
+ );
7604
8152
  };
7605
8153
  return validateDepth(traits);
7606
8154
  },
@@ -7618,7 +8166,7 @@ var PixelTrackingRequestSchema = external_exports.object({
7618
8166
  // Detection data
7619
8167
  userAgent: external_exports.string(),
7620
8168
  // Browser user agent
7621
- headers: external_exports.record(external_exports.string()).optional(),
8169
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
7622
8170
  // Any additional headers
7623
8171
  // Client info
7624
8172
  screenResolution: external_exports.string().optional(),
@@ -7629,6 +8177,20 @@ var PixelTrackingRequestSchema = external_exports.object({
7629
8177
  // "America/New_York"
7630
8178
  language: external_exports.string().optional(),
7631
8179
  // "en-US"
8180
+ platform: external_exports.string().optional(),
8181
+ // navigator.platform
8182
+ cookiesEnabled: external_exports.boolean().optional(),
8183
+ // navigator.cookieEnabled
8184
+ onLine: external_exports.boolean().optional(),
8185
+ // navigator.onLine
8186
+ timezoneOffset: external_exports.number().optional(),
8187
+ // Date.getTimezoneOffset()
8188
+ connectionType: external_exports.string().optional(),
8189
+ // navigator.connection.effectiveType
8190
+ connectionSpeed: external_exports.number().optional(),
8191
+ // navigator.connection.downlink
8192
+ // Device identity — cross-subdomain cookie set by pixel.js
8193
+ deviceId: external_exports.string().optional(),
7632
8194
  // Behavioral (if available)
7633
8195
  timeOnPage: external_exports.number().optional(),
7634
8196
  // Milliseconds
@@ -7638,11 +8200,17 @@ var PixelTrackingRequestSchema = external_exports.object({
7638
8200
  // Number of clicks
7639
8201
  scrollDepth: external_exports.number().optional(),
7640
8202
  // Percentage 0-100
8203
+ pageLoadTime: external_exports.number().optional(),
8204
+ // performance.timing load duration, ms
8205
+ domContentLoadedTime: external_exports.number().optional(),
8206
+ // performance.timing DCL duration, ms
7641
8207
  // Client-side detection data (NEW)
7642
8208
  clientDetection: ClientDetectionSchema.optional(),
7643
8209
  // Request tracking (client-provided, will be validated server-side)
7644
8210
  requestId: external_exports.string().optional(),
7645
8211
  // Unique request ID for deduplication
8212
+ correlationId: external_exports.string().optional(),
8213
+ // Cross-surface correlation id (validated/normalized server-side)
7646
8214
  // Event type for special events
7647
8215
  eventType: external_exports.string().optional(),
7648
8216
  // 'pageview', 'identify', 'logout', etc.
@@ -7739,7 +8307,7 @@ var PixelVerificationStatusSchema = external_exports.object({
7739
8307
  });
7740
8308
  var PixelUserIdentificationSchema = external_exports.object({
7741
8309
  userId: external_exports.string(),
7742
- traits: external_exports.record(external_exports.unknown()).optional().refine((traits) => !traits || JSON.stringify(traits).length < 1e4, {
8310
+ traits: external_exports.record(external_exports.string(), external_exports.unknown()).optional().refine((traits) => !traits || JSON.stringify(traits).length < 1e4, {
7743
8311
  message: "User traits too large (max 10KB)"
7744
8312
  }).refine((traits) => !traits || Object.keys(traits).length < 50, {
7745
8313
  message: "Too many user trait properties (max 50)"
@@ -7771,7 +8339,7 @@ var EventTrackingRequestSchema = external_exports.object({
7771
8339
  referrer: external_exports.string().url().optional(),
7772
8340
  method: external_exports.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).optional(),
7773
8341
  // Headers for additional context
7774
- headers: external_exports.record(external_exports.string()).optional(),
8342
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
7775
8343
  // Behavioral tracking data
7776
8344
  behavioralData: BehavioralDataSchema.optional(),
7777
8345
  // Client-side browser fingerprint (headless/automation tells, interaction).
@@ -7787,7 +8355,7 @@ var EventTrackingRequestSchema = external_exports.object({
7787
8355
  screenResolution: external_exports.string().optional(),
7788
8356
  viewport: external_exports.string().optional(),
7789
8357
  // Custom metadata
7790
- metadata: external_exports.record(external_exports.unknown()).optional()
8358
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
7791
8359
  });
7792
8360
  var EventTrackingResponseSchema = external_exports.object({
7793
8361
  success: external_exports.boolean(),
@@ -7873,7 +8441,7 @@ var EventStorageRecordSchema = external_exports.object({
7873
8441
  scrollDepth: external_exports.number().optional(),
7874
8442
  clickCount: external_exports.number().optional(),
7875
8443
  // Metadata
7876
- metadata: external_exports.record(external_exports.unknown()).optional(),
8444
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
7877
8445
  // Timestamps
7878
8446
  createdAt: external_exports.date(),
7879
8447
  processedAt: external_exports.date()
@@ -7912,7 +8480,7 @@ var SignatureVerificationRequestSchema = external_exports.object({
7912
8480
  // Algorithm hint
7913
8481
  algorithm: SignatureAlgorithmSchema.optional(),
7914
8482
  // Additional headers for context
7915
- headers: external_exports.record(external_exports.string()).optional()
8483
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional()
7916
8484
  });
7917
8485
  var SignatureVerificationResponseSchema = external_exports.object({
7918
8486
  success: external_exports.boolean(),
@@ -8201,6 +8769,67 @@ var BULK_ERROR_CODES = {
8201
8769
  NOT_FOUND: "NOT_FOUND"
8202
8770
  };
8203
8771
 
8772
+ // src/constants/ai-traffic-taxonomy.ts
8773
+ var REPORT_AI_CRAWLER_NAMES = [
8774
+ "GPTBot",
8775
+ "ClaudeBot",
8776
+ "Anthropic-AI Crawler",
8777
+ "PerplexityBot",
8778
+ "Google-Extended",
8779
+ "Gemini-Deep-Research",
8780
+ "Meta-ExternalAgent",
8781
+ "Meta AI",
8782
+ "CohereBot",
8783
+ "DeepSeekBot",
8784
+ "MistralBot",
8785
+ "Amazonbot",
8786
+ "Amazon Bedrock",
8787
+ "Common Crawl",
8788
+ "Bytedance Crawler"
8789
+ ];
8790
+ var REPORT_AI_AGENT_NAMES = [
8791
+ "ChatGPT",
8792
+ "ChatGPT-User",
8793
+ "OpenAI",
8794
+ "Claude",
8795
+ "Claude-User",
8796
+ "Anthropic",
8797
+ "Perplexity",
8798
+ "Perplexity-User",
8799
+ "Google Gemini",
8800
+ "Microsoft Copilot",
8801
+ "DeepSeek AI",
8802
+ "xAI Grok",
8803
+ "Amazon Q",
8804
+ "Kya Agent"
8805
+ ];
8806
+ var CRAWLER_NAME_SET = new Set(REPORT_AI_CRAWLER_NAMES.map((name) => name.toLowerCase()));
8807
+ var AGENT_NAME_SET = new Set(REPORT_AI_AGENT_NAMES.map((name) => name.toLowerCase()));
8808
+ function buildKnownPatternLookup(patterns) {
8809
+ const map = /* @__PURE__ */ new Map();
8810
+ for (const entry of patterns) {
8811
+ const nameKey = entry.name.toLowerCase();
8812
+ const idKey = entry.id.toLowerCase();
8813
+ if (!map.has(nameKey)) map.set(nameKey, entry);
8814
+ if (!map.has(idKey)) map.set(idKey, entry);
8815
+ }
8816
+ return map;
8817
+ }
8818
+ var KNOWN_PATTERN_BY_NAME_OR_ID = buildKnownPatternLookup(KNOWN_AGENT_PATTERNS);
8819
+ function classifyAgentTaxonomy(agentType, detectionClass) {
8820
+ if (detectionClass === "human") return "human";
8821
+ const normalized = agentType?.trim().toLowerCase();
8822
+ if (normalized) {
8823
+ if (CRAWLER_NAME_SET.has(normalized)) return "ai_crawler";
8824
+ if (AGENT_NAME_SET.has(normalized)) return "ai_agent";
8825
+ const known = KNOWN_PATTERN_BY_NAME_OR_ID.get(normalized);
8826
+ if (known) {
8827
+ return (known.category ?? "ai_assistant") === "ai_assistant" ? "ai_agent" : "ai_crawler";
8828
+ }
8829
+ }
8830
+ return detectionClass === "ai_agent" ? "ai_agent" : "other_automation";
8831
+ }
8832
+
8204
8833
  // src/types/entities.ts
8205
8834
  var UserPlanSchema = external_exports.enum(["free", "pro", "enterprise"]);
8206
8835
  var ApiKeyPermissionSchema = external_exports.enum(["read", "write", "admin"]);
@@ -8233,6 +8862,10 @@ var ProjectSchema = external_exports.object({
8233
8862
  name: external_exports.string().min(1).max(255),
8234
8863
  domain: external_exports.string().optional(),
8235
8864
  settings: ProjectSettingsSchema.default({}),
8865
+ // Setup Flow v2 step 1 ("What brings you here?") selections, if this
8866
+ // project was created via that flow — see CreateProjectSchema's own
8867
+ // doc comment. Null/absent for every other creation path.
8868
+ setupGoals: external_exports.array(external_exports.string()).nullable().optional(),
8236
8869
  createdAt: external_exports.date(),
8237
8870
  updatedAt: external_exports.date()
8238
8871
  });
@@ -8245,7 +8878,7 @@ var PixelConfigurationSchema = external_exports.object({
8245
8878
  flushInterval: external_exports.number().min(100).max(6e4).default(5e3),
8246
8879
  enableBehavioralTracking: external_exports.boolean().default(true),
8247
8880
  enableSessionReplay: external_exports.boolean().default(false),
8248
- customHeaders: external_exports.record(external_exports.string()).default({})
8881
+ customHeaders: external_exports.record(external_exports.string(), external_exports.string()).default({})
8249
8882
  });
8250
8883
  var PixelSchema = external_exports.object({
8251
8884
  id: external_exports.string().uuid(),
@@ -8296,7 +8929,7 @@ var DetectionLogSchema = external_exports.object({
8296
8929
  agentType: external_exports.string().optional(),
8297
8930
  userAgent: external_exports.string().optional(),
8298
8931
  ipAddress: external_exports.string().ip().optional(),
8299
- metadata: external_exports.record(external_exports.unknown()).optional(),
8932
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
8300
8933
  sessionId: external_exports.string().optional(),
8301
8934
  createdAt: external_exports.date()
8302
8935
  });
@@ -8403,6 +9036,18 @@ var OAuth2ProviderSchema = BaseAuthProviderSchema.extend({
8403
9036
  tokenEndpoint: external_exports.string().max(500),
8404
9037
  userInfoUrl: httpUrlSchema(500).optional(),
8405
9038
  // User info endpoint for identity resolution
9039
+ /**
9040
+ * Optional dot-path field mapping into the `userInfoUrl` response for
9041
+ * merchant identity extraction (native consent merchant-oauth leg).
9042
+ * When absent, extraction defaults to: userId ← first present of
9043
+ * `sub`/`id`/`customerId`; userEmail ← `email`.
9044
+ */
9045
+ userInfoFields: external_exports.object({
9046
+ userId: external_exports.string().max(255).optional(),
9047
+ // JSON dot-path to the customer id
9048
+ userEmail: external_exports.string().max(255).optional()
9049
+ // JSON dot-path to the customer email
9050
+ }).optional(),
8406
9051
  redirectUri: external_exports.string().max(500),
8407
9052
  scopes: external_exports.array(external_exports.string()).optional(),
8408
9053
  supportsPKCE: external_exports.boolean().optional(),
@@ -8532,6 +9177,9 @@ var ConsentConfigMetadataSchema = external_exports.object({
8532
9177
  updatedAt: external_exports.string().datetime().nullable().optional(),
8533
9178
  bumpedAt: external_exports.string().datetime().nullable().optional()
8534
9179
  });
9180
+ function requiresSensitiveTier(riskLevel) {
9181
+ return riskLevel === "high" || riskLevel === "critical";
9182
+ }
8535
9183
  var ConsentCapabilitySchema = external_exports.object({
8536
9184
  id: external_exports.string().min(1).max(64).regex(
8537
9185
  /^[a-z][a-z0-9._-]*$/,
@@ -8564,6 +9212,14 @@ var ConsentCapabilitySchema = external_exports.object({
8564
9212
  ),
8565
9213
  scopes: external_exports.array(external_exports.string().min(1).max(120)).min(1).max(20),
8566
9214
  category: external_exports.string().max(80).optional()
9215
+ }).superRefine((capability, ctx) => {
9216
+ if (requiresSensitiveTier(capability.riskLevel) && capability.defaultOn) {
9217
+ ctx.addIssue({
9218
+ code: external_exports.ZodIssueCode.custom,
9219
+ path: ["defaultOn"],
9220
+ 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).`
9221
+ });
9222
+ }
8567
9223
  });
8568
9224
  var ConsentCapabilityGroupSchema = external_exports.object({
8569
9225
  id: external_exports.string().min(1).max(64).regex(/^[a-z][a-z0-9._-]*$/),
@@ -8575,8 +9231,16 @@ var ConsentAgentMetadataSchema = external_exports.object({
8575
9231
  did: external_exports.string().min(1).max(500),
8576
9232
  vendor: external_exports.string().max(80).optional(),
8577
9233
  surfaceLabel: external_exports.string().max(40).optional(),
9234
+ // Display-only. NOT authoritative for grant decisions: First-Contact
9235
+ // Scope Cap Rules 2 and 3 read first contact and verification from
9236
+ // server state (see FirstContactScopeCap resolver in
9237
+ // apps/web/lib/bouncer/services), never from this field, because it
9238
+ // sits inside the same config object an operator writes. Kept here only
9239
+ // so already-stored configs (and any future display use) keep parsing.
8578
9240
  verified: external_exports.boolean(),
8579
9241
  logoUrl: httpUrlSchema(500).optional(),
9242
+ // Display-only, same as `verified` above: not consulted for grant
9243
+ // decisions.
8580
9244
  connectedAt: external_exports.string().datetime().optional()
8581
9245
  });
8582
9246
  var ConsentConfigSchema = external_exports.object({
@@ -8590,7 +9254,28 @@ var ConsentConfigSchema = external_exports.object({
8590
9254
  // server renders the new design-language consent screen; when absent the
8591
9255
  // legacy raw-scope checkboxes are shown.
8592
9256
  capabilities: external_exports.array(ConsentCapabilityGroupSchema).max(20).optional(),
9257
+ // Populated server-side only: `UpdateBouncerConfigSchema` (the one
9258
+ // write path) unconditionally rejects a write that sets this, so an
9259
+ // operator can never self-attest an agent's identity or verification
9260
+ // status. Display-only; see `ConsentAgentMetadataSchema` above. NOT
9261
+ // consulted by First-Contact Scope Cap Rules 2/3, which read server
9262
+ // state instead (apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts).
8593
9263
  agentMetadata: ConsentAgentMetadataSchema.optional(),
9264
+ // First-Contact Scope Cap section 3, Rules 2 and 3 opt-in. Per-project,
9265
+ // defaults to off/absent so every existing config, and every config that
9266
+ // hasn't explicitly opted in, renders byte-identically to before this
9267
+ // field existed. Flip to `true` on one project's consentConfig (a
9268
+ // normal PUT/PATCH) to turn the probe gate on for that project.
9269
+ //
9270
+ // This flag is read at RENDER time, not enforced by this schema: Rules 2
9271
+ // and 3 are not write-time properties of a config, they depend on who is
9272
+ // in front of the screen right now, which this schema has no way to
9273
+ // know. See `applyFirstContactScopeCap` in
9274
+ // apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts for
9275
+ // the actual enforcement, which resolves first contact and verification
9276
+ // from server state (delegations, and a verification seam that returns
9277
+ // `indeterminate` until a real agent-verification source exists).
9278
+ firstContactScopeCapEnabled: external_exports.boolean().optional(),
8594
9279
  consentTheme: external_exports.enum(["light", "dark"]).optional(),
8595
9280
  headlineVerb: external_exports.string().min(1).max(40).optional(),
8596
9281
  revocationPath: external_exports.string().min(1).max(120).optional(),
@@ -8637,7 +9322,7 @@ var BouncerConfigSchema = external_exports.object({
8637
9322
  // Consent page configuration
8638
9323
  consentConfig: ConsentConfigSchema.optional(),
8639
9324
  // Tool discovery
8640
- discoveredTools: external_exports.record(external_exports.unknown()).default({}),
9325
+ discoveredTools: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
8641
9326
  mcpServerUrl: httpUrlSchema().nullable().optional(),
8642
9327
  mcpWorkerUrl: httpUrlSchema().nullable().optional(),
8643
9328
  // Organization settings
@@ -8672,7 +9357,15 @@ var UpdateBouncerConfigSchema = external_exports.object({
8672
9357
  mcpServerUrl: httpUrlSchema().nullable().optional(),
8673
9358
  // Organization settings
8674
9359
  isEnabled: external_exports.boolean().optional()
8675
- }).strict();
9360
+ }).strict().superRefine((data, ctx) => {
9361
+ if (data.consentConfig?.agentMetadata !== void 0) {
9362
+ ctx.addIssue({
9363
+ code: external_exports.ZodIssueCode.custom,
9364
+ path: ["consentConfig", "agentMetadata"],
9365
+ 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."
9366
+ });
9367
+ }
9368
+ });
8676
9369
  var RefreshScopesRequestSchema = external_exports.object({
8677
9370
  mcpServerUrl: httpUrlSchema().optional()
8678
9371
  }).strict();
@@ -8682,7 +9375,7 @@ var DelegationSchema = external_exports.object({
8682
9375
  projectId: external_exports.string().uuid(),
8683
9376
  agentDid: external_exports.string().max(500),
8684
9377
  agentName: external_exports.string().max(255).nullable().optional(),
8685
- // User identification - userDid is primary for MCP-I, others for backward compatibility
9378
+ // User identification - userDid is primary for KYA-OS, others for backward compatibility
8686
9379
  userDid: external_exports.string().max(500).nullable().optional(),
8687
9380
  // DID of authorizing user (did:key or did:web)
8688
9381
  userId: external_exports.string().max(500).nullable().optional(),
@@ -8690,14 +9383,14 @@ var DelegationSchema = external_exports.object({
8690
9383
  userIdentifier: external_exports.string().max(500).nullable().optional(),
8691
9384
  // Human-readable (email)
8692
9385
  scopes: external_exports.array(external_exports.string()),
8693
- constraints: external_exports.record(external_exports.unknown()).nullable().optional(),
9386
+ constraints: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional(),
8694
9387
  status: DelegationStatusSchema.default("active"),
8695
9388
  issuedAt: external_exports.string().datetime(),
8696
9389
  expiresAt: external_exports.string().datetime().nullable().optional(),
8697
9390
  revokedAt: external_exports.string().datetime().nullable().optional(),
8698
9391
  revocationReason: external_exports.string().max(500).nullable().optional(),
8699
9392
  credentialJwt: external_exports.string().nullable().optional(),
8700
- metadata: external_exports.record(external_exports.unknown()).default({}),
9393
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).default({}),
8701
9394
  createdAt: external_exports.string().datetime(),
8702
9395
  updatedAt: external_exports.string().datetime()
8703
9396
  });
@@ -8710,15 +9403,15 @@ var BouncerProofSchema = external_exports.object({
8710
9403
  agentDid: external_exports.string().max(500),
8711
9404
  userIdentifier: external_exports.string().max(500).nullable().optional(),
8712
9405
  toolName: external_exports.string().max(255),
8713
- toolArgs: external_exports.record(external_exports.unknown()).nullable().optional(),
8714
- toolResult: external_exports.record(external_exports.unknown()).nullable().optional(),
9406
+ toolArgs: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional(),
9407
+ toolResult: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional(),
8715
9408
  scopes: external_exports.array(external_exports.string()).nullable().optional(),
8716
9409
  signature: external_exports.string(),
8717
9410
  publicKey: external_exports.string(),
8718
9411
  timestamp: external_exports.number().int(),
8719
9412
  // Unix timestamp
8720
9413
  nonce: external_exports.string().max(100),
8721
- crispDelta: external_exports.record(external_exports.unknown()).nullable().optional(),
9414
+ crispDelta: external_exports.record(external_exports.string(), external_exports.unknown()).nullable().optional(),
8722
9415
  outcome: BouncerOutcomeSchema.default("success"),
8723
9416
  errorMessage: external_exports.string().nullable().optional(),
8724
9417
  createdAt: external_exports.string().datetime()
@@ -8774,12 +9467,12 @@ var OAuthProviderMetadataSchema = external_exports.object({
8774
9467
  tokenEndpointAuthMethod: external_exports.enum(["client_secret_post", "client_secret_basic"]).optional(),
8775
9468
  responseType: external_exports.string().optional(),
8776
9469
  grantType: external_exports.string().optional(),
8777
- // MCP-I coordination fields (added per OAUTH_FLOW_COORDINATION_PLAN.md)
9470
+ // KYA-OS coordination fields (added per OAUTH_FLOW_COORDINATION_PLAN.md)
8778
9471
  configured: external_exports.boolean().optional(),
8779
9472
  // Whether this provider is configured for the project
8780
9473
  mode: OAuthModeSchema.optional(),
8781
- // OAuth flow mode: 'direct' (PKCE) or 'proxy' (AgentShield)
8782
- // MCP-I Provider Registry: Secret resolution metadata
9474
+ // OAuth flow mode: 'direct' (PKCE) or 'proxy' (Checkpoint)
9475
+ // KYA-OS Provider Registry: Secret resolution metadata
8783
9476
  metadata: external_exports.object({
8784
9477
  clientSecretName: external_exports.string().optional(),
8785
9478
  clientIdSecretName: external_exports.string().optional(),
@@ -8862,7 +9555,7 @@ external_exports.object({
8862
9555
  function toProviderRegistryFormat(provider) {
8863
9556
  const { type, authorizationUrl, tokenUrl, userInfoUrl, ...rest } = provider;
8864
9557
  const authType = type;
8865
- const result = {
9558
+ const result2 = {
8866
9559
  id: rest.id,
8867
9560
  authType,
8868
9561
  displayName: rest.displayName,
@@ -8870,7 +9563,7 @@ function toProviderRegistryFormat(provider) {
8870
9563
  metadata: rest.metadata
8871
9564
  };
8872
9565
  if (authType === "oauth2" && (authorizationUrl || tokenUrl)) {
8873
- result.oauthConfig = {
9566
+ result2.oauthConfig = {
8874
9567
  authorizationEndpoint: authorizationUrl || "",
8875
9568
  tokenEndpoint: tokenUrl || "",
8876
9569
  userInfoEndpoint: userInfoUrl,
@@ -8879,7 +9572,7 @@ function toProviderRegistryFormat(provider) {
8879
9572
  defaultScopes: rest.defaultScopes || rest.scopes
8880
9573
  };
8881
9574
  }
8882
- return result;
9575
+ return result2;
8883
9576
  }
8884
9577
  function isSupportedAuthType(authType) {
8885
9578
  return authType === "oauth2" || authType === "password";
@@ -9016,7 +9709,7 @@ function validateOrganizationName(name) {
9016
9709
  return { valid: true };
9017
9710
  } catch (error) {
9018
9711
  if (error instanceof external_exports.ZodError) {
9019
- return { valid: false, error: error.errors[0]?.message || "Invalid organization name" };
9712
+ return { valid: false, error: error.issues[0]?.message || "Invalid organization name" };
9020
9713
  }
9021
9714
  return { valid: false, error: "Invalid organization name" };
9022
9715
  }
@@ -9059,10 +9752,11 @@ var ProjectIdSchema = external_exports.string().refine(
9059
9752
  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;
9060
9753
  const ktaIdRegex = /^kta-[a-z0-9]{6}$/;
9061
9754
  const friendlyIdRegex = /^[a-z0-9-]+-[a-z0-9]{6}$/;
9062
- return uuidRegex2.test(val) || ktaIdRegex.test(val) || friendlyIdRegex.test(val);
9755
+ const bareSlugRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
9756
+ return uuidRegex2.test(val) || ktaIdRegex.test(val) || friendlyIdRegex.test(val) || val.length <= 20 && bareSlugRegex.test(val);
9063
9757
  },
9064
9758
  {
9065
- message: 'Invalid project ID format. Must be a UUID, kta-XXXXXX, or friendly ID (e.g., "my-project-a1b2c3")'
9759
+ message: 'Invalid project ID format. Must be a UUID, kta-XXXXXX, or friendly ID (e.g., "my-project-a1b2c3" or "my-project")'
9066
9760
  }
9067
9761
  );
9068
9762
  var OrganizationIdSchema = external_exports.string().refine(
@@ -9088,6 +9782,13 @@ var CreateProjectSchema = external_exports.object({
9088
9782
  // Changed: removed .url() validation to be more lenient
9089
9783
  organizationId: external_exports.string().uuid().optional(),
9090
9784
  // Optional - backend uses auth session as fallback
9785
+ // Setup Flow v2 step 1 ("What brings you here?") — the stable
9786
+ // SetupV2NeedDef.id keys the user selected (apps/web's
9787
+ // lib/setup-v2/flow-types.ts owns the id -> label/product mapping; this
9788
+ // shared package only validates shape, not membership, matching
9789
+ // settings.allowedOrigins/blockedAgents below). Optional: only the
9790
+ // setup-v2 flow ever sends it.
9791
+ setupGoals: external_exports.array(external_exports.string().min(1).max(100)).max(50).optional(),
9091
9792
  settings: external_exports.object({
9092
9793
  blockOnHighConfidence: external_exports.boolean().default(false),
9093
9794
  confidenceThreshold: external_exports.number().min(0).max(1).default(0.8),
@@ -9151,6 +9852,118 @@ var UpdateApiKeySchema = external_exports.object({
9151
9852
  rateLimits: ApiKeyRateLimitsSchema.optional(),
9152
9853
  expiresAt: external_exports.string().datetime().optional().nullable()
9153
9854
  });
9855
+ var MarketplaceSourceSchema = external_exports.enum([
9856
+ "vercel",
9857
+ "shopify",
9858
+ "netlify",
9859
+ "railway",
9860
+ "shopware",
9861
+ "mixer"
9862
+ ]);
9863
+ var ProvisioningModeSchema = external_exports.enum(["observe", "enforce"]);
9864
+ var ProvisionKeyRequestSchema = external_exports.object({
9865
+ source: MarketplaceSourceSchema,
9866
+ /** Provider installation/configuration id (e.g. Vercel configurationId). */
9867
+ externalId: external_exports.string().min(1).max(255),
9868
+ /**
9869
+ * Provider resource id (e.g. one Vercel project); idempotency key with (source, externalId).
9870
+ * Single-resource providers repeat `externalId` here rather than inventing a sentinel — a
9871
+ * Shopware shop, for instance, has no sub-resource comparable to a Vercel project, so its
9872
+ * triple is ('shopware', shopId, shopId). Intentional, not a caller bug.
9873
+ */
9874
+ resourceId: external_exports.string().min(1).max(255),
9875
+ /** Human-readable label for the dashboard (e.g. "Vercel / team_xxx / my-project"). */
9876
+ label: external_exports.string().min(1).max(200),
9877
+ /**
9878
+ * Owner of the provisioned project. `email` is the account-linking key: we find-or-create
9879
+ * the KYA-OS user + personal org from it (Shopify-parity), so an address matching an
9880
+ * existing account provisions INTO that account — including the org it lands in.
9881
+ *
9882
+ * The caller MUST send an address it has verified belongs to the installer. Nothing here
9883
+ * enforces that: there is no verification flag and no per-provider gate, so a wrong address
9884
+ * silently mints a project inside a stranger's org. Adapters carrying a verified identity
9885
+ * (Vercel's OIDC `user_email`, Railway's OIDC userinfo `email`) satisfy this directly;
9886
+ * Shopware satisfies it by convention only, since its app handshake carries no user identity
9887
+ * and the address is merchant-confirmed in the shop admin.
9888
+ *
9889
+ * Rationale, per-provider trust, and the accepted exposure:
9890
+ * `docs/integrations/provisioning-owner-email-trust.md`.
9891
+ */
9892
+ owner: external_exports.object({
9893
+ email: external_exports.string().email(),
9894
+ name: external_exports.string().min(1).max(255).optional()
9895
+ }),
9896
+ /** Recorded on the provision for the dashboard; the SDK's enforcementMode is code-level today. */
9897
+ mode: ProvisioningModeSchema.default("observe"),
9898
+ /**
9899
+ * Org the installer chose in the adapter UI. Treated as a HINT: the backend binds the
9900
+ * installation to it and mints there only when the resolved user OWNS or ADMINISTERS it
9901
+ * (matching the orgs the list endpoint surfaces) — otherwise it falls back to the personal
9902
+ * org (owner/admin backstop in `mintWithinTx`). Omitted = legacy behavior (personal/default
9903
+ * org).
9904
+ */
9905
+ organizationId: external_exports.string().uuid().optional(),
9906
+ /** Optional non-secret provider context (teamId, userId, resource name). */
9907
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
9908
+ });
9909
+ var ProvisionKeyResponseSchema = external_exports.object({
9910
+ /**
9911
+ * Plaintext API key — injected by the adapter as CHECKPOINT_API_KEY. Returned once on mint;
9912
+ * on idempotent re-provision the same key is returned (decrypted from storage).
9913
+ */
9914
+ apiKey: external_exports.string().min(1),
9915
+ /** The KYA-OS project the key is scoped to. */
9916
+ projectId: external_exports.string().uuid(),
9917
+ /** The API key row id (revoke is keyed by source/externalId/resourceId, not this). */
9918
+ apiKeyId: external_exports.string().uuid(),
9919
+ organizationId: external_exports.string().uuid(),
9920
+ /** True when an existing provision was returned rather than a new one created. */
9921
+ idempotent: external_exports.boolean()
9922
+ });
9923
+ var SsoLinkRequestSchema = external_exports.object({
9924
+ source: MarketplaceSourceSchema,
9925
+ /** Provider installation/configuration id (e.g. Vercel configurationId). */
9926
+ externalId: external_exports.string().min(1).max(255),
9927
+ /** Optional provider resource id — present → deep-link to that project; absent → org landing. */
9928
+ resourceId: external_exports.string().min(1).max(255).optional(),
9929
+ /** Verified installer email (the OIDC `user_email` claim). */
9930
+ ownerEmail: external_exports.string().email()
9931
+ });
9932
+ var SsoLinkResponseSchema = external_exports.object({
9933
+ /** Ready-to-redirect URL: the integration 302s the browser here. Establishes the session and lands on the friendly-id dashboard route. */
9934
+ url: external_exports.string().min(1)
9935
+ });
9936
+ var RevokeProvisionQuerySchema = external_exports.object({
9937
+ source: MarketplaceSourceSchema,
9938
+ externalId: external_exports.string().min(1).max(255),
9939
+ resourceId: external_exports.string().min(1).max(255).optional()
9940
+ });
9941
+ var RevokeProvisionResponseSchema = external_exports.object({
9942
+ /** Number of provisions revoked (0 if nothing matched — DELETE is idempotent). */
9943
+ revoked: external_exports.number().int().nonnegative()
9944
+ });
9945
+ var ProvisioningOrganizationRoleSchema = external_exports.enum(["owner", "admin"]);
9946
+ var ProvisioningOrganizationSummarySchema = external_exports.object({
9947
+ id: external_exports.string().uuid(),
9948
+ name: external_exports.string(),
9949
+ slug: external_exports.string(),
9950
+ role: ProvisioningOrganizationRoleSchema
9951
+ });
9952
+ var ListProvisioningOrganizationsRequestSchema = external_exports.object({
9953
+ email: external_exports.string().email()
9954
+ });
9955
+ var ListProvisioningOrganizationsResponseSchema = external_exports.object({
9956
+ organizations: external_exports.array(ProvisioningOrganizationSummarySchema)
9957
+ });
9958
+ var CreateProvisioningOrganizationRequestSchema = external_exports.object({
9959
+ email: external_exports.string().email(),
9960
+ name: CreateOrganizationInputSchema.shape.name,
9961
+ slug: CreateOrganizationInputSchema.shape.slug
9962
+ });
9963
+ var CreateProvisioningOrganizationResponseSchema = external_exports.object({
9964
+ /** The just-created org; `role` is always `owner` (the creator is inserted as owner). */
9965
+ organization: ProvisioningOrganizationSummarySchema
9966
+ });
9154
9967
  var CreateOrganizationSchema = CreateOrganizationInputSchema;
9155
9968
  var UpdateOrganizationSchema = UpdateOrganizationInputSchema;
9156
9969
  external_exports.object({
@@ -9386,6 +10199,26 @@ var PublicApiHeadersSchema = external_exports.object({
9386
10199
  "x-request-id": external_exports.string().optional()
9387
10200
  });
9388
10201
 
10202
+ // src/api/signal-exposure.ts
10203
+ var REASON_CODE_VALUES = Object.values(DETECTION_REASON_CODES);
10204
+ var DetectionReasonCodeSchema = external_exports.enum(REASON_CODE_VALUES).describe(
10205
+ "A machine-readable detection/* reason code from the DETECTION_REASON_CODES registry (see docs/architecture/detection-reason-codes.generated.md)."
10206
+ );
10207
+ var DetectionSignalExposureSchema = external_exports.object({
10208
+ signals: external_exports.array(DetectionSignalSchema).describe(
10209
+ "The engine's full per-signal evidence breakdown, verbatim (not the condensed single-entry summary). Empty when the engine did not run (skipDetection) or faulted. THE extension point: future signal families arrive as new entries/sources here, additively."
10210
+ ),
10211
+ reasonCodes: external_exports.array(DetectionReasonCodeSchema).min(1).describe(
10212
+ "Ordered detection/* reason codes, most-significant-evidence first, derived by the same mapDetectionToReasonCodes projection that feeds the gateway KYA-Reason-Codes header. Never empty: an assumed verdict carries a zero-evidence fallback code."
10213
+ ),
10214
+ confidenceLevel: ConfidenceLevelSchema.optional().describe(
10215
+ "The engine's banded confidence level (low | medium | high | very_high). Omitted when the engine did not produce one (engine fault, skipDetection, or a demoted forged-credential verdict)."
10216
+ ),
10217
+ isAiCrawler: external_exports.boolean().optional().describe(
10218
+ "True when the engine classified the client as an AI training crawler (GPTBot, ClaudeBot, \u2026) rather than an interactive agent. Omitted when the engine did not run."
10219
+ )
10220
+ });
10221
+
9389
10222
  // src/api/fingerprint.ts
9390
10223
  var ClientDetectionSchema2 = external_exports.object({
9391
10224
  // Core detection
@@ -9465,15 +10298,15 @@ var FingerprintAnalysisSchema = external_exports.object({
9465
10298
  });
9466
10299
  var FingerprintDetectRequestSchema = external_exports.object({
9467
10300
  clientDetection: ClientDetectionSchema2,
9468
- metadata: external_exports.record(external_exports.unknown()).optional()
10301
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
9469
10302
  });
9470
10303
  var FingerprintResponseSchema = external_exports.object({
9471
10304
  timestamp: external_exports.string(),
9472
10305
  method: external_exports.string(),
9473
10306
  url: external_exports.string(),
9474
10307
  path: external_exports.string(),
9475
- queryParams: external_exports.record(external_exports.string()),
9476
- headers: external_exports.record(external_exports.string()),
10308
+ queryParams: external_exports.record(external_exports.string(), external_exports.string()),
10309
+ headers: external_exports.record(external_exports.string(), external_exports.string()),
9477
10310
  headerCount: external_exports.number(),
9478
10311
  ip: external_exports.string(),
9479
10312
  httpVersion: external_exports.string(),
@@ -9513,7 +10346,7 @@ var EnhancedFingerprintResponseSchema = external_exports.object({
9513
10346
  http: external_exports.object({
9514
10347
  method: external_exports.string(),
9515
10348
  url: external_exports.string(),
9516
- headers: external_exports.record(external_exports.string()),
10349
+ headers: external_exports.record(external_exports.string(), external_exports.string()),
9517
10350
  headerCount: external_exports.number(),
9518
10351
  ip: external_exports.string(),
9519
10352
  userAgent: external_exports.string()
@@ -9553,7 +10386,7 @@ var FingerprintRecordSchema = external_exports.object({
9553
10386
  ip: external_exports.string(),
9554
10387
  // Headers
9555
10388
  userAgent: external_exports.string().nullable(),
9556
- headers: external_exports.record(external_exports.string()),
10389
+ headers: external_exports.record(external_exports.string(), external_exports.string()),
9557
10390
  // Detection results
9558
10391
  isBot: external_exports.boolean(),
9559
10392
  botType: external_exports.string().nullable(),
@@ -9566,7 +10399,7 @@ var FingerprintRecordSchema = external_exports.object({
9566
10399
  // Metadata
9567
10400
  sessionId: external_exports.string().nullable(),
9568
10401
  projectId: external_exports.string().nullable(),
9569
- metadata: external_exports.record(external_exports.unknown()).nullable()
10402
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).nullable()
9570
10403
  });
9571
10404
  var BotPatternSchema2 = external_exports.object({
9572
10405
  name: external_exports.string(),
@@ -9724,36 +10557,320 @@ var StatsUpdateEventSchema = external_exports.object({
9724
10557
  })
9725
10558
  });
9726
10559
 
9727
- // src/events/deploy-progress.ts
9728
- var DEPLOY_STEPS = [
9729
- { id: "github_verify", label: "Verifying GitHub connection", order: 1 },
9730
- { id: "repo_check", label: "Checking repository availability", order: 2 },
9731
- { id: "project_create", label: "Creating AgentShield project", order: 3 },
9732
- { id: "api_key", label: "Generating API key", order: 4 },
9733
- { id: "scaffold", label: "Scaffolding project files", order: 5 },
9734
- { id: "kta_register", label: "Registering agent for reputation", order: 6 },
9735
- { id: "repo_create", label: "Creating GitHub repository", order: 7 },
9736
- { id: "commit_files", label: "Committing files", order: 8 },
9737
- { id: "add_secrets", label: "Adding repository secrets", order: 9 },
9738
- { id: "cloudflare_deploy", label: "Deploying to Cloudflare", order: 10 },
9739
- { id: "complete", label: "Deployment complete!", order: 11 }
9740
- ];
9741
- var DeployStepIdSchema = external_exports.enum([
9742
- "github_verify",
9743
- "repo_check",
9744
- "project_create",
9745
- "api_key",
9746
- "scaffold",
9747
- "kta_register",
9748
- "repo_create",
9749
- "commit_files",
9750
- "add_secrets",
9751
- "cloudflare_deploy",
9752
- "complete"
10560
+ // src/deploy/index.ts
10561
+ 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>");
10562
+ external_exports.enum([
10563
+ "ams",
10564
+ // Amsterdam, Netherlands
10565
+ "arn",
10566
+ // Stockholm, Sweden
10567
+ "atl",
10568
+ // Atlanta, Georgia (US)
10569
+ "bog",
10570
+ // Bogotá, Colombia
10571
+ "bos",
10572
+ // Boston, Massachusetts (US)
10573
+ "cdg",
10574
+ // Paris, France
10575
+ "den",
10576
+ // Denver, Colorado (US)
10577
+ "dfw",
10578
+ // Dallas, Texas (US)
10579
+ "ewr",
10580
+ // Secaucus, NJ (US)
10581
+ "eze",
10582
+ // Ezeiza, Argentina
10583
+ "fra",
10584
+ // Frankfurt, Germany
10585
+ "gdl",
10586
+ // Guadalajara, Mexico
10587
+ "gig",
10588
+ // Rio de Janeiro, Brazil
10589
+ "gru",
10590
+ // São Paulo, Brazil
10591
+ "hkg",
10592
+ // Hong Kong
10593
+ "iad",
10594
+ // Ashburn, Virginia (US)
10595
+ "jnb",
10596
+ // Johannesburg, South Africa
10597
+ "lax",
10598
+ // Los Angeles, California (US)
10599
+ "lhr",
10600
+ // London, United Kingdom
10601
+ "mad",
10602
+ // Madrid, Spain
10603
+ "mia",
10604
+ // Miami, Florida (US)
10605
+ "nrt",
10606
+ // Tokyo, Japan
10607
+ "ord",
10608
+ // Chicago, Illinois (US)
10609
+ "otp",
10610
+ // Bucharest, Romania
10611
+ "phx",
10612
+ // Phoenix, Arizona (US)
10613
+ "qro",
10614
+ // Querétaro, Mexico
10615
+ "scl",
10616
+ // Santiago, Chile
10617
+ "sea",
10618
+ // Seattle, Washington (US)
10619
+ "sin",
10620
+ // Singapore
10621
+ "sjc",
10622
+ // San Jose, California (US)
10623
+ "syd",
10624
+ // Sydney, Australia
10625
+ "waw",
10626
+ // Warsaw, Poland
10627
+ "yul",
10628
+ // Montreal, Canada
10629
+ "yyz"
10630
+ // Toronto, Canada
9753
10631
  ]);
9754
- var DeployStepStatusSchema = external_exports.enum([
10632
+ external_exports.enum(["byok", "managed", "managed-byoa"]);
10633
+ var AuditAssuranceProfileSchema = external_exports.enum(["AAP-0", "AAP-1", "AAP-2", "AAP-3", "AAP-4"]);
10634
+ var AuditDeliveryModeSchema = external_exports.enum(["best-effort", "buffered", "required"]);
10635
+ var AuditDeploymentConfigSchema = external_exports.object({
10636
+ enabled: external_exports.boolean(),
10637
+ requestedProfile: AuditAssuranceProfileSchema,
10638
+ delivery: AuditDeliveryModeSchema,
10639
+ evidenceMode: external_exports.enum(["none", "encrypted-separate", "encrypted-inline"]),
10640
+ retentionClass: external_exports.string().min(1).max(128),
10641
+ retentionDays: external_exports.number().int().min(0).max(3650),
10642
+ residency: external_exports.enum(["inherit-project", "us", "eu", "global"]),
10643
+ keyCustody: external_exports.enum(["none", "checkpoint-managed", "customer-managed-kms"]),
10644
+ recorderTopology: external_exports.enum(["none", "self-hosted", "managed", "verified-mirror"])
10645
+ }).strict().superRefine((value, context) => {
10646
+ if (!value.enabled && value.requestedProfile !== "AAP-0") {
10647
+ context.addIssue({
10648
+ code: external_exports.ZodIssueCode.custom,
10649
+ path: ["requestedProfile"],
10650
+ message: "Disabled audit configuration must request AAP-0"
10651
+ });
10652
+ }
10653
+ if (value.enabled && value.requestedProfile === "AAP-0") {
10654
+ context.addIssue({
10655
+ code: external_exports.ZodIssueCode.custom,
10656
+ path: ["requestedProfile"],
10657
+ message: "Enabled audit configuration must request AAP-1 or higher"
10658
+ });
10659
+ }
10660
+ if (Number(value.requestedProfile.slice(-1)) >= 2 && value.delivery === "best-effort") {
10661
+ context.addIssue({
10662
+ code: external_exports.ZodIssueCode.custom,
10663
+ path: ["delivery"],
10664
+ message: "AAP-2 or higher cannot use best-effort delivery"
10665
+ });
10666
+ }
10667
+ if (!value.enabled && (value.keyCustody !== "none" || value.recorderTopology !== "none")) {
10668
+ context.addIssue({
10669
+ code: external_exports.ZodIssueCode.custom,
10670
+ message: "Disabled audit configuration cannot claim key custody or recorder topology"
10671
+ });
10672
+ }
10673
+ });
10674
+ var AuditRuntimeCapabilitiesSchema = external_exports.object({
10675
+ recorderTopology: external_exports.enum(["none", "self-hosted", "managed", "verified-mirror"]),
10676
+ delivery: AuditDeliveryModeSchema,
10677
+ journalDurability: external_exports.enum(["none", "ephemeral", "durable"]),
10678
+ atomicAppend: external_exports.boolean(),
10679
+ sourceHighWater: external_exports.boolean(),
10680
+ merkleCheckpoints: external_exports.boolean(),
10681
+ independentObservation: external_exports.boolean(),
10682
+ supportingAnchors: external_exports.array(external_exports.enum(["worm", "rfc3161", "scitt"])),
10683
+ evidenceRetention: external_exports.enum(["none", "inline", "separate"])
10684
+ }).strict();
10685
+ var AuditRuntimeCanaryResultSchema = external_exports.object({
10686
+ passed: external_exports.boolean(),
10687
+ observedAt: external_exports.number().int().nonnegative(),
10688
+ capabilities: AuditRuntimeCapabilitiesSchema,
10689
+ checks: external_exports.array(
10690
+ external_exports.object({
10691
+ id: external_exports.string().min(1).max(128),
10692
+ passed: external_exports.boolean()
10693
+ }).strict()
10694
+ ).min(1),
10695
+ bundleHash: external_exports.string().min(1).max(256).optional()
10696
+ }).strict().superRefine((value, context) => {
10697
+ if (value.passed !== value.checks.every((check) => check.passed)) {
10698
+ context.addIssue({
10699
+ code: external_exports.ZodIssueCode.custom,
10700
+ path: ["passed"],
10701
+ message: "Canary result must equal the aggregate of its mechanical checks"
10702
+ });
10703
+ }
10704
+ });
10705
+ external_exports.object({
10706
+ requestedProfile: AuditAssuranceProfileSchema,
10707
+ effectiveProfile: AuditAssuranceProfileSchema,
10708
+ status: external_exports.enum(["disabled", "ready", "degraded"]),
10709
+ capabilities: AuditRuntimeCapabilitiesSchema.nullable(),
10710
+ canary: AuditRuntimeCanaryResultSchema.nullable(),
10711
+ reasonCodes: external_exports.array(external_exports.string().min(1).max(128))
10712
+ }).strict();
10713
+ external_exports.enum([
9755
10714
  "pending",
9756
- "running",
10715
+ "in_progress",
10716
+ "completed",
10717
+ "failed",
10718
+ "skipped"
10719
+ ]);
10720
+ external_exports.object({
10721
+ /** Agent DID this heartbeat is for */
10722
+ agentDid: DidStringSchema,
10723
+ /** Current compute process status */
10724
+ status: external_exports.enum(["starting", "running", "error", "stopping"]),
10725
+ /** @kya-os/compute package version (from package.json) */
10726
+ computeVersion: external_exports.string().min(1).max(50),
10727
+ /** Installed OpenClaw version (from npm ls) */
10728
+ openclawVersion: external_exports.string().max(50).optional(),
10729
+ /** Fly machine ID (from FLY_MACHINE_ID env var) */
10730
+ machineId: external_exports.string().max(255).optional(),
10731
+ /** Seconds since compute process started */
10732
+ uptimeSeconds: external_exports.number().nonnegative().optional(),
10733
+ /** Current RSS memory in MB */
10734
+ memoryMb: external_exports.number().nonnegative().optional()
10735
+ });
10736
+ var StopCommandSchema = external_exports.object({
10737
+ type: external_exports.literal("stop")
10738
+ }).strict();
10739
+ var RestartCommandSchema = external_exports.object({
10740
+ type: external_exports.literal("restart")
10741
+ }).strict();
10742
+ var UpdateConfigCommandSchema = external_exports.object({
10743
+ type: external_exports.literal("update_config")
10744
+ }).strict();
10745
+ var UpdateVersionCommandSchema = external_exports.object({
10746
+ type: external_exports.literal("update_version"),
10747
+ payload: external_exports.object({
10748
+ /** Target OpenClaw version to install */
10749
+ version: external_exports.string().min(1).max(50)
10750
+ })
10751
+ }).strict();
10752
+ var ComputeCommandSchema = external_exports.discriminatedUnion("type", [
10753
+ StopCommandSchema,
10754
+ RestartCommandSchema,
10755
+ UpdateConfigCommandSchema,
10756
+ UpdateVersionCommandSchema
10757
+ ]);
10758
+ external_exports.object({
10759
+ /** Always true for successful heartbeats */
10760
+ ack: external_exports.literal(true),
10761
+ /** Pending commands for the compute process to execute */
10762
+ commands: external_exports.array(ComputeCommandSchema).default([]),
10763
+ /** ISO timestamp of last config change (compute compares to detect updates) */
10764
+ configUpdatedAt: external_exports.string().datetime().optional()
10765
+ });
10766
+ external_exports.object({
10767
+ /** Schema version — 2 for managed bundles */
10768
+ version: external_exports.number().int().positive(),
10769
+ /** Kill switch — if true, compute must exit immediately */
10770
+ killed: external_exports.boolean(),
10771
+ /** Target OpenClaw version to install */
10772
+ openclawVersion: external_exports.string().min(1).max(50),
10773
+ /** Agent personality/system prompt file contents (max 100KB) */
10774
+ soulFile: external_exports.string().max(1e5).nullable(),
10775
+ /** Gateway auth token for OpenClaw */
10776
+ gatewayToken: external_exports.string().min(1).max(500),
10777
+ /** Channel configurations */
10778
+ channels: external_exports.object({
10779
+ telegram: external_exports.object({
10780
+ enabled: external_exports.boolean(),
10781
+ token: external_exports.string().optional()
10782
+ }).optional(),
10783
+ discord: external_exports.object({
10784
+ enabled: external_exports.boolean(),
10785
+ token: external_exports.string().optional()
10786
+ }).optional(),
10787
+ slack: external_exports.object({
10788
+ enabled: external_exports.boolean(),
10789
+ token: external_exports.string().optional(),
10790
+ appToken: external_exports.string().optional()
10791
+ }).optional(),
10792
+ whatsapp: external_exports.object({
10793
+ enabled: external_exports.boolean()
10794
+ }).strict().optional()
10795
+ }),
10796
+ /** AI provider configuration — key is decrypted, sent over TLS */
10797
+ aiProvider: external_exports.object({
10798
+ type: external_exports.enum(["anthropic", "openai"]),
10799
+ apiKey: external_exports.string().min(1).max(500),
10800
+ /**
10801
+ * Optional base URL override. When set, OpenClaw routes all provider
10802
+ * traffic through this URL instead of the provider's default endpoint.
10803
+ * Used by managed deployments where AgentShield issues a per-deployment
10804
+ * gateway token and proxies to the upstream provider with budget tracking.
10805
+ */
10806
+ baseUrl: external_exports.string().url().optional()
10807
+ }),
10808
+ /**
10809
+ * Optional OpenClaw heartbeat interval (`agents.defaults.heartbeat.every`).
10810
+ * Drives how often OpenClaw wakes the agent for HEARTBEAT.md processing —
10811
+ * the primary token-cost lever. Examples: "30m" (active), "6h" (idle),
10812
+ * "off" (dormant — heartbeat disabled entirely). When absent, the patcher
10813
+ * preserves whatever value already lives in openclaw.json (OpenClaw's
10814
+ * built-in default of "30m").
10815
+ */
10816
+ heartbeatEvery: external_exports.string().min(1).max(20).optional(),
10817
+ /**
10818
+ * Optional override for `agents.defaults.model.primary` (e.g.
10819
+ * "anthropic/claude-haiku-4-5" for idle agents). When absent, the patcher
10820
+ * derives the model from `aiProvider.type` as before. Format must be
10821
+ * "<provider>/<model-id>".
10822
+ */
10823
+ modelOverride: external_exports.string().min(1).max(100).optional(),
10824
+ /** ISO timestamp of last config modification */
10825
+ updatedAt: external_exports.string().datetime()
10826
+ });
10827
+ external_exports.object({
10828
+ /** Whether the agent runtime is healthy */
10829
+ healthy: external_exports.boolean(),
10830
+ /** Seconds since compute process started */
10831
+ uptimeSeconds: external_exports.number().nonnegative(),
10832
+ /** Installed OpenClaw version */
10833
+ openclawVersion: external_exports.string().min(1).max(50),
10834
+ /** @kya-os/compute version */
10835
+ computeVersion: external_exports.string().min(1).max(50),
10836
+ /** Number of active WS connections to control server */
10837
+ activeConnections: external_exports.number().int().nonnegative(),
10838
+ /** Current RSS memory in MB */
10839
+ memoryMb: external_exports.number().nonnegative(),
10840
+ /** CPU usage percentage (0-100) */
10841
+ cpuPercent: external_exports.number().nonnegative().max(100)
10842
+ });
10843
+
10844
+ // src/events/deploy-progress.ts
10845
+ var DEPLOY_STEPS = [
10846
+ { id: "github_verify", label: "Verifying your GitHub connection", order: 1 },
10847
+ { id: "repo_check", label: "Checking your repository name", order: 2 },
10848
+ { id: "project_create", label: "Creating your project", order: 3 },
10849
+ { id: "api_key", label: "Generating your API key", order: 4 },
10850
+ { id: "scaffold", label: "Generating your server files", order: 5 },
10851
+ { id: "kta_register", label: "Setting up your agent identity", order: 6 },
10852
+ { id: "repo_create", label: "Creating your GitHub repository", order: 7 },
10853
+ { id: "commit_files", label: "Committing your server code", order: 8 },
10854
+ { id: "add_secrets", label: "Securing your repository secrets", order: 9 },
10855
+ { id: "cloudflare_deploy", label: "Deploying your server to Cloudflare", order: 10 },
10856
+ { id: "complete", label: "Deployment complete!", order: 11 }
10857
+ ];
10858
+ var DeployStepIdSchema = external_exports.enum([
10859
+ "github_verify",
10860
+ "repo_check",
10861
+ "project_create",
10862
+ "api_key",
10863
+ "scaffold",
10864
+ "kta_register",
10865
+ "repo_create",
10866
+ "commit_files",
10867
+ "add_secrets",
10868
+ "cloudflare_deploy",
10869
+ "complete"
10870
+ ]);
10871
+ var DeployStepStatusSchema = external_exports.enum([
10872
+ "pending",
10873
+ "running",
9757
10874
  "complete",
9758
10875
  "error",
9759
10876
  "skipped"
@@ -9782,12 +10899,16 @@ var DeployProgressEventSchema = external_exports.object({
9782
10899
  projectId: external_exports.string(),
9783
10900
  /** Human-readable project ID for URL construction */
9784
10901
  friendlyId: external_exports.string().nullable().optional(),
10902
+ /** kyaosDeployments row id — drives the live-step "Go to server" deployment-detail link. */
10903
+ deploymentId: external_exports.string().optional(),
9785
10904
  /** Full API key - only shown once at completion! */
9786
10905
  apiKey: external_exports.string(),
9787
10906
  /** Preview (sk_...xxx) for display after initial view */
9788
10907
  apiKeyPreview: external_exports.string(),
9789
10908
  cloudflareUrl: external_exports.string().optional(),
9790
10909
  cloudflareDeployed: external_exports.boolean().optional(),
10910
+ /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */
10911
+ cloudflareError: external_exports.string().optional(),
9791
10912
  /** Agent DID (decentralized identifier) - did:web for reputation enabled, did:key for disabled */
9792
10913
  agentDid: external_exports.string().optional(),
9793
10914
  /** Whether agent was registered with Know That AI for reputation tracking */
@@ -9808,13 +10929,40 @@ var DeploymentMetadataSchema = external_exports.object({
9808
10929
  repoName: external_exports.string(),
9809
10930
  template: external_exports.string(),
9810
10931
  platform: external_exports.string(),
9811
- /** Hosting mode: 'managed' (AgentShield hosted) or 'byok' (Bring Your Own Cloudflare) */
10932
+ /** Hosting mode: 'managed' (Checkpoint hosted) or 'byok' (Bring Your Own Cloudflare) */
9812
10933
  hostingMode: external_exports.enum(["managed", "byok"]).optional().default("byok"),
10934
+ /** 'repo-only' scaffolds + pushes the repo but never triggers the Cloudflare worker upload, regardless of connection state (defaults to 'cloudflare') */
10935
+ deployTarget: external_exports.enum(["cloudflare", "repo-only"]).optional(),
9813
10936
  status: external_exports.enum(["pending", "running", "complete", "error"]),
9814
10937
  /** Enable reputation tracking via Know That AI (defaults to true) */
9815
10938
  enableReputation: external_exports.boolean().optional(),
10939
+ /** Requested audit posture. Old stored metadata may omit this and resolves to AAP-0 at use. */
10940
+ audit: AuditDeploymentConfigSchema.optional(),
9816
10941
  /** Existing project ID to deploy to (if provided, skips project creation) - Unified Project Schema v1.3 */
9817
10942
  existingProjectId: external_exports.string().uuid().optional(),
10943
+ /** Pre-generated source supplied by another intake flow (for example OpenAPI). */
10944
+ generatedFiles: external_exports.array(
10945
+ external_exports.object({
10946
+ path: external_exports.string(),
10947
+ content: external_exports.string(),
10948
+ isBase64: external_exports.boolean().optional()
10949
+ })
10950
+ ).optional(),
10951
+ /** Identity paired with pre-generated source. */
10952
+ generatedIdentity: external_exports.object({
10953
+ did: external_exports.string(),
10954
+ // Optional so historical metadata already sitting in Redis without a
10955
+ // kid still parses. The producing route always populates it now (see
10956
+ // KYA-956 phase 3); the deploy pipeline treats a missing kid as a
10957
+ // scaffold-time failure rather than injecting a broken identity.
10958
+ kid: external_exports.string().optional(),
10959
+ publicKey: external_exports.string(),
10960
+ privateKey: external_exports.string()
10961
+ }).optional(),
10962
+ /** Validated source-specific secrets forwarded to GitHub/Cloudflare. */
10963
+ additionalSecrets: external_exports.record(external_exports.string(), external_exports.string()).optional(),
10964
+ /** Semantic source type used for descriptions and registry metadata. */
10965
+ agentType: external_exports.string().optional(),
9818
10966
  createdAt: external_exports.number(),
9819
10967
  updatedAt: external_exports.number(),
9820
10968
  /** Result data (populated on completion) */
@@ -9828,10 +10976,14 @@ var DeploymentMetadataSchema = external_exports.object({
9828
10976
  projectId: external_exports.string(),
9829
10977
  /** Human-readable project ID for URL construction */
9830
10978
  friendlyId: external_exports.string().nullable().optional(),
10979
+ /** kyaosDeployments row id — powers the live-step deployment-detail link (all sources). */
10980
+ deploymentId: external_exports.string().optional(),
9831
10981
  /** API key preview e.g. "sk_...xxx" (BYOK deploy only) */
9832
10982
  apiKeyPreview: external_exports.string().optional(),
9833
10983
  cloudflareUrl: external_exports.string().optional(),
9834
10984
  cloudflareDeployed: external_exports.boolean().optional(),
10985
+ /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */
10986
+ cloudflareError: external_exports.string().optional(),
9835
10987
  agentDid: external_exports.string().optional(),
9836
10988
  ktaRegistered: external_exports.boolean().optional(),
9837
10989
  ktaClaimUrl: external_exports.string().optional()
@@ -9952,8 +11104,8 @@ function isValidWasmRequestMetadata(value) {
9952
11104
  return WasmRequestMetadataSchema.safeParse(value).success;
9953
11105
  }
9954
11106
  function parseAgentName(value) {
9955
- const result = AgentTypeSchema.safeParse(value);
9956
- return result.success ? result.data : "unknown";
11107
+ const result2 = AgentTypeSchema.safeParse(value);
11108
+ return result2.success ? result2.data : "unknown";
9957
11109
  }
9958
11110
  function normalizeAgentName(value) {
9959
11111
  const normalized = value.toLowerCase().trim();
@@ -10031,13 +11183,13 @@ var SessionDataSchema = external_exports.object({
10031
11183
  // Request Context
10032
11184
  userAgent: external_exports.string().optional(),
10033
11185
  ipAddress: external_exports.string().optional(),
10034
- headers: external_exports.record(external_exports.string()).optional(),
11186
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
10035
11187
  // Behavioral Data
10036
11188
  behavioral: BehavioralSignalsSchema.optional(),
10037
11189
  pageViews: external_exports.number().int().min(0).default(0),
10038
11190
  interactions: external_exports.number().int().min(0).default(0),
10039
11191
  // Custom Metadata
10040
- metadata: external_exports.record(external_exports.unknown()).optional()
11192
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
10041
11193
  });
10042
11194
  var SessionCreateRequestSchema = external_exports.object({
10043
11195
  userId: external_exports.string().optional(),
@@ -10045,10 +11197,10 @@ var SessionCreateRequestSchema = external_exports.object({
10045
11197
  projectId: external_exports.string().optional(),
10046
11198
  userAgent: external_exports.string().optional(),
10047
11199
  ipAddress: external_exports.string().optional(),
10048
- headers: external_exports.record(external_exports.string()).optional(),
11200
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
10049
11201
  ttl: external_exports.number().min(60).default(3600),
10050
11202
  // Time to live in seconds
10051
- metadata: external_exports.record(external_exports.unknown()).optional()
11203
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
10052
11204
  });
10053
11205
  var SessionUpdateRequestSchema = external_exports.object({
10054
11206
  sessionId: external_exports.string(),
@@ -10056,7 +11208,7 @@ var SessionUpdateRequestSchema = external_exports.object({
10056
11208
  state: SessionStateSchema.optional(),
10057
11209
  detectionResult: DetectionResultSchema.optional(),
10058
11210
  behavioral: BehavioralSignalsSchema.optional(),
10059
- metadata: external_exports.record(external_exports.unknown()).optional(),
11211
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
10060
11212
  lastActivityAt: external_exports.date().optional()
10061
11213
  }),
10062
11214
  extendTtl: external_exports.boolean().default(true)
@@ -10075,7 +11227,7 @@ var SessionQueryOptionsSchema = external_exports.object({
10075
11227
  var SessionConfigSchema = external_exports.object({
10076
11228
  // Storage
10077
11229
  storage: SessionStorageTypeSchema.default("memory"),
10078
- storageOptions: external_exports.record(external_exports.unknown()).optional(),
11230
+ storageOptions: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
10079
11231
  // Timing
10080
11232
  ttl: external_exports.number().min(60).default(3600),
10081
11233
  // Default 1 hour
@@ -10122,7 +11274,7 @@ var SessionEventSchema = external_exports.object({
10122
11274
  type: SessionEventTypeSchema,
10123
11275
  sessionId: external_exports.string(),
10124
11276
  timestamp: external_exports.date(),
10125
- data: external_exports.record(external_exports.unknown()).optional()
11277
+ data: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
10126
11278
  });
10127
11279
  var SessionTokenPayloadSchema = external_exports.object({
10128
11280
  sessionId: external_exports.string(),
@@ -10132,124 +11284,8 @@ var SessionTokenPayloadSchema = external_exports.object({
10132
11284
  // Issued at
10133
11285
  exp: external_exports.number(),
10134
11286
  // Expires at
10135
- metadata: external_exports.record(external_exports.unknown()).optional()
10136
- });
10137
-
10138
- // src/types/beacon.ts
10139
- var ConnectionTypeSchema = external_exports.enum([
10140
- "bluetooth",
10141
- "cellular",
10142
- "ethernet",
10143
- "none",
10144
- "wifi",
10145
- "wimax",
10146
- "other",
10147
- "unknown"
10148
- ]);
10149
- var BeaconCollectorDataSchema = external_exports.object({
10150
- // Request Headers
10151
- userAgent: external_exports.string(),
10152
- referer: external_exports.string().optional(),
10153
- acceptLanguage: external_exports.string().optional(),
10154
- acceptEncoding: external_exports.string().optional(),
10155
- // Page Context
10156
- url: external_exports.string().url(),
10157
- timestamp: external_exports.number(),
10158
- sessionId: external_exports.string(),
10159
- // Detection Signals
10160
- screenResolution: external_exports.string().optional(),
10161
- // e.g., "1920x1080"
10162
- viewport: external_exports.string().optional(),
10163
- // e.g., "1200x800"
10164
- timezone: external_exports.string().optional(),
10165
- platform: external_exports.string().optional(),
10166
- // Performance Metrics
10167
- pageLoadTime: external_exports.number().optional(),
10168
- connectionType: ConnectionTypeSchema.optional(),
10169
- connectionSpeed: external_exports.number().optional()
10170
- // Mbps
10171
- });
10172
- var BeaconConfigSchema = external_exports.object({
10173
- // API Configuration
10174
- apiKey: external_exports.string(),
10175
- endpoint: external_exports.string().url().default("https://kya.vouched.id/v1/beacon"),
10176
- // Batching Configuration
10177
- batchSize: external_exports.number().min(1).max(100).default(10),
10178
- flushInterval: external_exports.number().min(1e3).max(6e4).default(5e3),
10179
- // Worker Configuration
10180
- useWorker: external_exports.boolean().default(true),
10181
- workerUrl: external_exports.string().optional(),
10182
- workerConfig: external_exports.object({
10183
- maxRetries: external_exports.number().min(0).max(10).default(3),
10184
- retryDelay: external_exports.number().min(100).max(1e4).default(1e3),
10185
- heartbeatInterval: external_exports.number().min(1e3).max(6e4).default(5e3),
10186
- maxUnhealthyCount: external_exports.number().min(1).max(10).default(3),
10187
- enableResourceMonitoring: external_exports.boolean().default(true),
10188
- enableCompression: external_exports.boolean().default(true),
10189
- compressionThreshold: external_exports.number().min(0).default(5120),
10190
- // 5KB
10191
- messageTimeout: external_exports.number().min(1e3).max(6e4).default(3e4),
10192
- poolSize: external_exports.number().min(1).max(10).default(1),
10193
- autoScale: external_exports.boolean().default(false),
10194
- allowFallback: external_exports.boolean().default(true),
10195
- crossOriginIsolated: external_exports.boolean().default(false)
10196
- }).optional(),
10197
- // Privacy Configuration
10198
- respectDoNotTrack: external_exports.boolean().default(true),
10199
- anonymizeIp: external_exports.boolean().default(false),
10200
- // Session Configuration
10201
- sessionTimeout: external_exports.number().min(6e4).default(18e5),
10202
- // 30 minutes
10203
- sessionCookieName: external_exports.string().default("_as_beacon_session"),
10204
- // Debug Configuration
10205
- debug: external_exports.boolean().default(false),
10206
- logLevel: external_exports.enum(["error", "warn", "info", "debug"]).default("error"),
10207
- // Performance Configuration
10208
- maxQueueSize: external_exports.number().min(10).max(1e3).default(100),
10209
- retryAttempts: external_exports.number().min(0).max(10).default(3),
10210
- retryDelay: external_exports.number().min(1e3).max(6e4).default(2e3)
10211
- });
10212
- var BeaconEventTypeSchema = external_exports.enum([
10213
- "pageview",
10214
- "pageunload",
10215
- "error",
10216
- "custom",
10217
- "heartbeat"
10218
- ]);
10219
- var BeaconEventSchema = external_exports.object({
10220
- type: BeaconEventTypeSchema,
10221
- data: BeaconCollectorDataSchema,
10222
- metadata: external_exports.record(external_exports.unknown()).optional()
10223
- });
10224
- var BeaconBatchSchema = external_exports.object({
10225
- apiKey: external_exports.string(),
10226
- events: external_exports.array(BeaconEventSchema).min(1).max(100),
10227
- sessionId: external_exports.string(),
10228
- batchId: external_exports.string().uuid(),
10229
- timestamp: external_exports.number()
11287
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
10230
11288
  });
10231
- var BeaconWorkerMessageTypeSchema = external_exports.enum([
10232
- "init",
10233
- "collect",
10234
- "flush",
10235
- "config",
10236
- "status",
10237
- "error"
10238
- ]);
10239
- var BeaconWorkerMessageSchema = external_exports.object({
10240
- type: BeaconWorkerMessageTypeSchema,
10241
- id: external_exports.string(),
10242
- payload: external_exports.unknown().optional(),
10243
- timestamp: external_exports.number()
10244
- });
10245
- var TransportStatusSchema = external_exports.enum(["idle", "sending", "success", "failed", "retrying"]);
10246
- var CollectorTypeSchema = external_exports.enum([
10247
- "browser",
10248
- "performance",
10249
- "behavioral",
10250
- "error",
10251
- "custom"
10252
- ]);
10253
11289
 
10254
11290
  // src/types/transport.ts
10255
11291
  var TransportConfigSchema = external_exports.object({
@@ -10442,7 +11478,7 @@ var WorkerErrorSchema = external_exports.object({
10442
11478
  code: external_exports.string().optional(),
10443
11479
  stack: external_exports.string().optional(),
10444
11480
  timestamp: external_exports.number(),
10445
- context: external_exports.record(external_exports.any()).optional(),
11481
+ context: external_exports.record(external_exports.string(), external_exports.any()).optional(),
10446
11482
  recoverable: external_exports.boolean().default(true),
10447
11483
  retryAfter: external_exports.number().optional()
10448
11484
  });
@@ -10522,7 +11558,7 @@ var ProtocolVersionSchema = external_exports.literal("1.0.0");
10522
11558
  // src/types/database.ts
10523
11559
  var BulkOperationParamsSchema = external_exports.object({
10524
11560
  operation: external_exports.enum(["create", "update", "delete", "upsert"]),
10525
- data: external_exports.array(external_exports.record(external_exports.unknown())),
11561
+ data: external_exports.array(external_exports.record(external_exports.string(), external_exports.unknown())),
10526
11562
  options: external_exports.object({
10527
11563
  skipValidation: external_exports.boolean().optional(),
10528
11564
  returnResults: external_exports.boolean().optional(),
@@ -10538,7 +11574,7 @@ var BulkOperationResultSchema = external_exports.object({
10538
11574
  external_exports.object({
10539
11575
  index: external_exports.number(),
10540
11576
  error: external_exports.string(),
10541
- data: external_exports.record(external_exports.unknown()).optional()
11577
+ data: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
10542
11578
  })
10543
11579
  ).default([])
10544
11580
  });
@@ -10624,7 +11660,7 @@ var DetectionMetadataSchema = external_exports.object({
10624
11660
  touchEvents: external_exports.number().optional()
10625
11661
  }).optional(),
10626
11662
  // Custom fields
10627
- custom: external_exports.record(external_exports.unknown()).optional()
11663
+ custom: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
10628
11664
  });
10629
11665
  var AnalyticsExportParamsSchema = external_exports.object({
10630
11666
  format: external_exports.enum(["csv", "json", "xlsx"]).default("json"),
@@ -10675,7 +11711,7 @@ var AnalyticsDataPointSchema = external_exports.object({
10675
11711
  timestamp: external_exports.date(),
10676
11712
  value: external_exports.number(),
10677
11713
  label: external_exports.string().optional(),
10678
- metadata: external_exports.record(external_exports.unknown()).optional()
11714
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
10679
11715
  });
10680
11716
  var AnalyticsSummarySchema = external_exports.object({
10681
11717
  total: external_exports.number(),
@@ -10739,7 +11775,7 @@ var DatabaseDetectionMetadataSchema = external_exports.object({
10739
11775
  // Request context
10740
11776
  userAgent: external_exports.string().optional(),
10741
11777
  ipAddress: external_exports.string().optional(),
10742
- headers: external_exports.record(external_exports.string()).optional(),
11778
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
10743
11779
  // Browser fingerprint data
10744
11780
  clientDetection: external_exports.object({
10745
11781
  headless: external_exports.boolean().optional(),
@@ -10854,7 +11890,7 @@ var CollectedDataSchema = external_exports.object({
10854
11890
  timestamp: external_exports.date()
10855
11891
  }),
10856
11892
  // HEADERS (noscript, middleware, express, edge)
10857
- headers: external_exports.record(external_exports.string()).optional(),
11893
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
10858
11894
  // CLIENT-SIDE (pixel, beacon only)
10859
11895
  clientSide: external_exports.object({
10860
11896
  canvas: external_exports.object({
@@ -10927,7 +11963,7 @@ var CollectedDataSchema = external_exports.object({
10927
11963
  httpVersion: external_exports.string(),
10928
11964
  protocol: external_exports.string(),
10929
11965
  requestSize: external_exports.number().optional(),
10930
- cookies: external_exports.record(external_exports.string()).optional(),
11966
+ cookies: external_exports.record(external_exports.string(), external_exports.string()).optional(),
10931
11967
  sessionData: external_exports.any().optional(),
10932
11968
  geoLocation: external_exports.object({
10933
11969
  country: external_exports.string(),
@@ -11135,7 +12171,7 @@ external_exports.object({
11135
12171
  integrationType: IntegrationTypeSchema,
11136
12172
  userAgent: external_exports.string(),
11137
12173
  ipAddress: external_exports.string(),
11138
- headers: external_exports.record(external_exports.string()).optional(),
12174
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
11139
12175
  // Fingerprint hashes
11140
12176
  canvasHash: external_exports.string().optional(),
11141
12177
  webglHash: external_exports.string().optional(),
@@ -11256,7 +12292,13 @@ function supportsServerEnhanced(integration) {
11256
12292
  return ["middleware", "express"].includes(integration);
11257
12293
  }
11258
12294
 
12295
+ // src/types/signing-vendors.generated.ts
12296
+ var PINNED_SIGNING_VENDORS = ["openai"];
12297
+
11259
12298
  // src/types/agent-classification.ts
12299
+ function hasPinnedSigningVendor(aliases) {
12300
+ return aliases?.some((alias) => PINNED_SIGNING_VENDORS.includes(alias)) ?? false;
12301
+ }
11260
12302
  var AgentCategorySchema = external_exports.enum([
11261
12303
  "ai_assistant",
11262
12304
  // ChatGPT, Claude, Gemini, Perplexity
@@ -11277,6 +12319,68 @@ var AgentCategorySchema = external_exports.enum([
11277
12319
  "unknown"
11278
12320
  // Unclassified agents
11279
12321
  ]);
12322
+ var AGENT_CATEGORY_META = {
12323
+ ai_assistant: {
12324
+ label: "AI assistant",
12325
+ inline: "AI assistant",
12326
+ definition: "An AI assistant acting for a person in real time (ChatGPT, Claude, Perplexity)."
12327
+ },
12328
+ search_engine: {
12329
+ label: "Search engine",
12330
+ inline: "search engine",
12331
+ definition: "An indexing crawler that makes your pages findable (Googlebot, Bingbot)."
12332
+ },
12333
+ social_media: {
12334
+ label: "Social media",
12335
+ inline: "social media",
12336
+ definition: "A crawler building link previews for a social platform."
12337
+ },
12338
+ monitoring: {
12339
+ label: "Monitoring",
12340
+ inline: "monitoring",
12341
+ definition: "An uptime or health checker polling your endpoints."
12342
+ },
12343
+ scraper: {
12344
+ label: "Scraper",
12345
+ inline: "scraper",
12346
+ definition: "Bulk content extraction, including AI training crawlers such as GPTBot and ClaudeBot."
12347
+ },
12348
+ automation: {
12349
+ label: "Automation",
12350
+ inline: "automation",
12351
+ definition: "A headless browser or scripted driver (Puppeteer, Playwright, Selenium)."
12352
+ },
12353
+ security: {
12354
+ label: "Security",
12355
+ inline: "security",
12356
+ definition: "A vulnerability scanner or security research crawler."
12357
+ },
12358
+ analytics: {
12359
+ label: "Analytics",
12360
+ inline: "analytics",
12361
+ definition: "An SEO or analytics tool sampling your pages."
12362
+ },
12363
+ unknown: {
12364
+ label: "Other",
12365
+ inline: "other",
12366
+ definition: "Detected and classified traffic that has not been attributed to a named vendor, usually because it matched only a generic bot signature. Not a detection failure, and worth sampling periodically: a new agent lands here before anyone writes a signature for it."
12367
+ }
12368
+ };
12369
+ function formatUnrecognizedValue(value) {
12370
+ return value.replace(/_/g, " ");
12371
+ }
12372
+ var LEGACY_CATEGORY_SENTINELS = /* @__PURE__ */ new Set(["__uncategorized__", "__unidentified__"]);
12373
+ function formatAgentCategory(value) {
12374
+ if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.label;
12375
+ const meta = AGENT_CATEGORY_META[value];
12376
+ return meta ? meta.label : formatUnrecognizedValue(value);
12377
+ }
12378
+ function formatAgentCategoryInline(value) {
12379
+ if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.inline;
12380
+ const meta = AGENT_CATEGORY_META[value];
12381
+ return meta ? meta.inline : formatUnrecognizedValue(value);
12382
+ }
12383
+ var UNNAMED_AGENT_LABEL = "Unnamed agent";
11280
12384
  var AgentTypeDefinitionSchema = external_exports.object({
11281
12385
  id: external_exports.string().uuid(),
11282
12386
  name: external_exports.string(),
@@ -11287,6 +12391,11 @@ var AgentTypeDefinitionSchema = external_exports.object({
11287
12391
  confidenceThreshold: external_exports.number().min(0).max(100),
11288
12392
  detectionPatterns: external_exports.array(external_exports.string()),
11289
12393
  signatureSupport: external_exports.boolean(),
12394
+ // Vendor tokens (own name + company aliases, e.g. ['chatgpt','openai']) matched
12395
+ // against a host-VERIFIED RFC 9421 Signature-Agent value to attribute a signed
12396
+ // agent to this type at ingest. Optional/additive; empty or absent ⇒ this type is
12397
+ // not resolvable by signature (only signatureSupport vendors carry aliases).
12398
+ signatureVendorAliases: external_exports.array(external_exports.string()).optional(),
11290
12399
  documentationUrl: external_exports.string().optional(),
11291
12400
  createdAt: external_exports.date(),
11292
12401
  updatedAt: external_exports.date()
@@ -11300,14 +12409,14 @@ var AgentClassificationResultSchema = external_exports.object({
11300
12409
  isLegitimate: external_exports.boolean(),
11301
12410
  signatureVerified: external_exports.boolean().optional(),
11302
12411
  matchedPatterns: external_exports.array(external_exports.string()),
11303
- metadata: external_exports.record(external_exports.unknown()).optional()
12412
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
11304
12413
  });
11305
12414
  var AgentClassificationRequestSchema = external_exports.object({
11306
12415
  userAgent: external_exports.string().optional(),
11307
- headers: external_exports.record(external_exports.string()).optional(),
12416
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
11308
12417
  ipAddress: external_exports.string().optional(),
11309
12418
  sessionId: external_exports.string().optional(),
11310
- metadata: external_exports.record(external_exports.unknown()).optional()
12419
+ metadata: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
11311
12420
  });
11312
12421
  var AgentStatisticsSchema = external_exports.object({
11313
12422
  agentTypeId: external_exports.string().uuid(),
@@ -11380,7 +12489,8 @@ var DEFAULT_AGENT_TYPES = [
11380
12489
  description: "OpenAI ChatGPT Browser",
11381
12490
  isLegitimate: true,
11382
12491
  confidenceThreshold: 95,
11383
- signatureSupport: true,
12492
+ signatureSupport: hasPinnedSigningVendor(["chatgpt", "openai"]),
12493
+ signatureVendorAliases: ["chatgpt", "openai"],
11384
12494
  detectionPatterns: ["GPTBot", "ChatGPT-User", "x-gpt-signature"]
11385
12495
  },
11386
12496
  {
@@ -11390,7 +12500,12 @@ var DEFAULT_AGENT_TYPES = [
11390
12500
  description: "Anthropic Claude Assistant",
11391
12501
  isLegitimate: true,
11392
12502
  confidenceThreshold: 95,
11393
- signatureSupport: true,
12503
+ // Derived FALSE today: Anthropic publishes no web-bot-auth key
12504
+ // directory (verified 2026-08-26) and the engine pins no anthropic
12505
+ // key. Flips automatically once anthropic.json lands in vendor-keys
12506
+ // and the manifest is regenerated.
12507
+ signatureSupport: hasPinnedSigningVendor(["claude", "anthropic"]),
12508
+ signatureVendorAliases: ["claude", "anthropic"],
11394
12509
  detectionPatterns: ["Claude-Web", "Claude-User", "anthropic-ai", "x-claude-signature"]
11395
12510
  },
11396
12511
  {
@@ -11457,6 +12572,65 @@ var auditLogQuerySchema = external_exports.object({
11457
12572
  search: external_exports.string().optional()
11458
12573
  });
11459
12574
 
12575
+ // src/types/admin-overview.ts
12576
+ var ADMIN_OVERVIEW_WINDOWS = ["7d", "30d", "90d"];
12577
+ var DEFAULT_ADMIN_OVERVIEW_WINDOW = "30d";
12578
+ var ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT = 100;
12579
+ var ADMIN_OVERVIEW_LIST_LIMIT_MAX = 500;
12580
+ function isCalendarDate(value) {
12581
+ const [year, month, day] = value.split("-").map(Number);
12582
+ if (!year || !month || !day) return false;
12583
+ const date = new Date(Date.UTC(year, month - 1, day));
12584
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
12585
+ }
12586
+ var adminOverviewQuerySchema = external_exports.object({
12587
+ window: external_exports.enum(ADMIN_OVERVIEW_WINDOWS).default(DEFAULT_ADMIN_OVERVIEW_WINDOW),
12588
+ // YYYY-MM-DD, must be a real calendar date (reject 2026-02-30, 2026-13-01, '2026-1-5', ISO datetimes)
12589
+ compareTo: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine(isCalendarDate, {
12590
+ message: "compareTo must be a real calendar date in YYYY-MM-DD form"
12591
+ }).optional(),
12592
+ listLimit: external_exports.coerce.number().int().min(1).max(ADMIN_OVERVIEW_LIST_LIMIT_MAX).default(ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT)
12593
+ });
12594
+ var ADMIN_DELTA_BASES = ["created_at", "rollup", "none"];
12595
+ var INSTALLATION_KINDS = [
12596
+ "agent",
12597
+ "pixel",
12598
+ "middleware",
12599
+ "dns_gateway",
12600
+ "mcp_server",
12601
+ "beacon"
12602
+ ];
12603
+ var INSTALLATION_TYPES = [
12604
+ "pixel",
12605
+ "middleware_node",
12606
+ "middleware_dotnet",
12607
+ "middleware_no_traffic",
12608
+ "dns_gateway",
12609
+ "beacon"
12610
+ ];
12611
+ var TRAFFIC_TAXONOMY_BUCKETS = [
12612
+ "human",
12613
+ "ai_agent",
12614
+ "ai_crawler",
12615
+ "other_automation"
12616
+ ];
12617
+ var EXCLUSION_BUCKETS = [
12618
+ "vouched",
12619
+ "internal_team",
12620
+ "test_pattern",
12621
+ "shopify_review",
12622
+ "cohort"
12623
+ ];
12624
+ var ADMIN_OVERVIEW_SECTIONS = [
12625
+ "ladder",
12626
+ "installations",
12627
+ "traffic",
12628
+ "lists",
12629
+ "hiAi"
12630
+ ];
12631
+ var ADMIN_OVERVIEW_CACHE_STATUSES = ["hit", "stale", "miss", "bypass"];
12632
+ var SERVICE_TRAFFIC_KEYS = [...INSTALLATION_KINDS, "mixed", "none"];
12633
+
11460
12634
  // src/types/api.ts
11461
12635
  var API_ERROR_CODES = {
11462
12636
  // Authentication & Authorization
@@ -11624,87 +12798,6 @@ function createValidationErrorResponse(message, details, meta) {
11624
12798
  };
11625
12799
  }
11626
12800
 
11627
- // src/utils/verification.ts
11628
- var KYA_OS_HANDSHAKE_METHODS = {
11629
- /** New canonical engine value. Not emitted yet — accepted on read. */
11630
- CANONICAL: "kyaos_handshake",
11631
- /** @deprecated Legacy engine value. Still emitted by the Rust engine. */
11632
- LEGACY: "mcp_i_handshake"
11633
- };
11634
- var KYA_OS_WIRE_METHODS = {
11635
- /** New canonical wire value. Not emitted yet — accepted on read. */
11636
- CANONICAL: "kya-os",
11637
- /** @deprecated Legacy wire value. Still emitted by the gateway worker. */
11638
- LEGACY: "mcp-i"
11639
- };
11640
- function isKyaOsHandshakeMethod(value) {
11641
- return value === KYA_OS_HANDSHAKE_METHODS.LEGACY || value === KYA_OS_HANDSHAKE_METHODS.CANONICAL;
11642
- }
11643
- function isKyaOsWireMethod(value) {
11644
- return value === KYA_OS_WIRE_METHODS.LEGACY || value === KYA_OS_WIRE_METHODS.CANONICAL;
11645
- }
11646
- function getVerificationMethodDescription(method) {
11647
- switch (method) {
11648
- case "signature":
11649
- return "HTTP Signature Verification";
11650
- case "pattern":
11651
- return "User-Agent Pattern Matching";
11652
- case "behavioral":
11653
- return "Behavioral Analysis";
11654
- case "network":
11655
- return "Network-based Detection";
11656
- // Dual-accept: legacy `mcp_i_handshake` + canonical `kyaos_handshake`.
11657
- case "mcp_i_handshake":
11658
- case "kyaos_handshake":
11659
- return "MCP Handshake Detection";
11660
- case "error":
11661
- return "Detection Error";
11662
- case "none":
11663
- default:
11664
- return "No Verification";
11665
- }
11666
- }
11667
- function getVerificationReliability(method) {
11668
- switch (method) {
11669
- case "signature":
11670
- return 1;
11671
- // Highest reliability
11672
- // Dual-accept: legacy `mcp_i_handshake` + canonical `kyaos_handshake`.
11673
- case "mcp_i_handshake":
11674
- case "kyaos_handshake":
11675
- return 0.95;
11676
- case "behavioral":
11677
- return 0.8;
11678
- case "network":
11679
- return 0.6;
11680
- case "pattern":
11681
- return 0.5;
11682
- case "none":
11683
- return 0.3;
11684
- case "error":
11685
- default:
11686
- return 0.1;
11687
- }
11688
- }
11689
- function isHighConfidenceVerification(method) {
11690
- return ["signature", "mcp_i_handshake", "kyaos_handshake"].includes(method);
11691
- }
11692
- function getVerificationRiskLevel(method, confidence) {
11693
- if (method === "signature") {
11694
- return "low";
11695
- }
11696
- if (isKyaOsHandshakeMethod(method)) {
11697
- return "low";
11698
- }
11699
- if (confidence >= 0.9) {
11700
- return method === "behavioral" ? "medium" : "high";
11701
- }
11702
- if (confidence >= 0.7) {
11703
- return "medium";
11704
- }
11705
- return "high";
11706
- }
11707
-
11708
12801
  // src/utils/detection-class.ts
11709
12802
  function detectionClassToEnum(detectionClass) {
11710
12803
  switch (detectionClass.type) {
@@ -11767,6 +12860,323 @@ function normalizeDetectionClassEnum(value) {
11767
12860
  return "incomplete_data";
11768
12861
  }
11769
12862
 
12863
+ // src/utils/agent-runtime-label.ts
12864
+ var CLAUDE_CANONICAL_DISPLAY = "Claude";
12865
+ var CLAUDE_DEPRECATED_TWIN = /^Claude \(deprecated/i;
12866
+ function isClaudeProductLabel(displayName) {
12867
+ if (!displayName) return false;
12868
+ const d = displayName.trim();
12869
+ return d === CLAUDE_CANONICAL_DISPLAY || CLAUDE_DEPRECATED_TWIN.test(d);
12870
+ }
12871
+ function hasClaudeCodeToken(userAgent) {
12872
+ const ua = (userAgent ?? "").toLowerCase();
12873
+ return ua.includes("claude-code") || ua.includes("claude code");
12874
+ }
12875
+ function hasClaudeUserToken(userAgent) {
12876
+ return (userAgent ?? "").toLowerCase().includes("claude-user");
12877
+ }
12878
+ function hasClaudeSearchBotToken(userAgent) {
12879
+ return (userAgent ?? "").toLowerCase().includes("claude-searchbot");
12880
+ }
12881
+ function claudeRuntimeLabel(userAgent, runtimeSurface) {
12882
+ const ua = (userAgent ?? "").toLowerCase();
12883
+ if (ua) {
12884
+ const hasClaudeCode = hasClaudeCodeToken(ua);
12885
+ const hasClaudeUser = hasClaudeUserToken(ua);
12886
+ if (hasClaudeCode && hasClaudeUser) return "Claude Code (web fetch)";
12887
+ if (hasClaudeCode) return "Claude Code";
12888
+ if (ua.includes("claude-cowork")) return "Claude Cowork";
12889
+ if (hasClaudeSearchBotToken(ua)) return "Claude SearchBot";
12890
+ if (hasClaudeUser) return "Claude (web fetch)";
12891
+ }
12892
+ if (runtimeSurface === "cli") {
12893
+ if (ua.startsWith("curl/")) return "Claude Code (curl)";
12894
+ if (ua.startsWith("wget/")) return "Claude Code (wget)";
12895
+ return "Claude Code";
12896
+ }
12897
+ if (runtimeSurface === "native_app") return "Claude Desktop";
12898
+ if (runtimeSurface === "browser") return "Claude (browser)";
12899
+ return "Claude";
12900
+ }
12901
+ function refineClaudeDisplayLabel(displayName, userAgent, runtimeSurface) {
12902
+ return isClaudeProductLabel(displayName) ? claudeRuntimeLabel(userAgent, runtimeSurface) : displayName;
12903
+ }
12904
+ function refineSessionGrainClaudeLabel(displayName, runtimeSurface) {
12905
+ return refineClaudeDisplayLabel(displayName, null, runtimeSurface);
12906
+ }
12907
+
12908
+ // src/utils/client-ip.ts
12909
+ var MAX_INPUT_LENGTH = 4096;
12910
+ var MAX_TOKEN_LENGTH = 128;
12911
+ var MAX_FORWARDED_HOPS = 32;
12912
+ function hasControlCharacter(value) {
12913
+ for (let i = 0; i < value.length; i++) {
12914
+ const code = value.charCodeAt(i);
12915
+ if (code <= 31 || code === 127) return true;
12916
+ }
12917
+ return false;
12918
+ }
12919
+ function parsePort(value) {
12920
+ return /^(?:0|[1-9]\d{0,4})$/.test(value) && Number(value) <= 65535;
12921
+ }
12922
+ function parseIpv4(value) {
12923
+ const parts = value.split(".");
12924
+ if (parts.length !== 4) return null;
12925
+ const octets = [];
12926
+ for (const part of parts) {
12927
+ if (!/^\d{1,3}$/.test(part)) return null;
12928
+ const octet = Number(part);
12929
+ if (octet > 255) return null;
12930
+ octets.push(octet);
12931
+ }
12932
+ return octets;
12933
+ }
12934
+ function parseHexGroup(value) {
12935
+ if (!/^[0-9a-fA-F]{1,4}$/.test(value)) return null;
12936
+ return Number.parseInt(value, 16);
12937
+ }
12938
+ function parseIpv6(value) {
12939
+ if (!value || value.includes("%") || hasControlCharacter(value)) return null;
12940
+ let address = value;
12941
+ if (address.includes(".")) {
12942
+ const lastColon = address.lastIndexOf(":");
12943
+ if (lastColon < 0) return null;
12944
+ const ipv4 = parseIpv4(address.slice(lastColon + 1));
12945
+ if (!ipv4) return null;
12946
+ const first = ipv4[0] << 8 | ipv4[1];
12947
+ const second = ipv4[2] << 8 | ipv4[3];
12948
+ address = `${address.slice(0, lastColon + 1)}${first.toString(16)}:${second.toString(16)}`;
12949
+ }
12950
+ const doubleColon = address.indexOf("::");
12951
+ if (doubleColon !== address.lastIndexOf("::")) return null;
12952
+ const parseGroups = (part) => {
12953
+ if (!part) return [];
12954
+ const groups2 = part.split(":");
12955
+ const parsed = [];
12956
+ for (const group of groups2) {
12957
+ const number = parseHexGroup(group);
12958
+ if (number === null) return null;
12959
+ parsed.push(number);
12960
+ }
12961
+ return parsed;
12962
+ };
12963
+ if (doubleColon >= 0) {
12964
+ const head = parseGroups(address.slice(0, doubleColon));
12965
+ const tail = parseGroups(address.slice(doubleColon + 2));
12966
+ if (!head || !tail) return null;
12967
+ const missing = 8 - head.length - tail.length;
12968
+ if (missing < 1) return null;
12969
+ return [...head, ...Array(missing).fill(0), ...tail];
12970
+ }
12971
+ const groups = parseGroups(address);
12972
+ return groups?.length === 8 ? groups : null;
12973
+ }
12974
+ function compressIpv6(groups) {
12975
+ const rendered = groups.map((group) => group.toString(16));
12976
+ let bestStart = -1;
12977
+ let bestLength = 1;
12978
+ let runStart = -1;
12979
+ for (let index = 0; index <= groups.length; index += 1) {
12980
+ if (index < groups.length && groups[index] === 0) {
12981
+ if (runStart < 0) runStart = index;
12982
+ continue;
12983
+ }
12984
+ if (runStart >= 0) {
12985
+ const runLength = index - runStart;
12986
+ if (runLength > bestLength) {
12987
+ bestStart = runStart;
12988
+ bestLength = runLength;
12989
+ }
12990
+ runStart = -1;
12991
+ }
12992
+ }
12993
+ if (bestStart < 0) return rendered.join(":");
12994
+ const before = rendered.slice(0, bestStart).join(":");
12995
+ const after = rendered.slice(bestStart + bestLength).join(":");
12996
+ if (!before && !after) return "::";
12997
+ if (!before) return `::${after}`;
12998
+ if (!after) return `${before}::`;
12999
+ return `${before}::${after}`;
13000
+ }
13001
+ function normalizeToken(rawToken) {
13002
+ const token = rawToken.trim();
13003
+ if (!token || token.length > MAX_TOKEN_LENGTH || hasControlCharacter(token)) return null;
13004
+ let address = token;
13005
+ if (token.startsWith("[")) {
13006
+ const closing = token.indexOf("]");
13007
+ if (closing <= 1) return null;
13008
+ const suffix = token.slice(closing + 1);
13009
+ if (suffix && (!suffix.startsWith(":") || !parsePort(suffix.slice(1)))) return null;
13010
+ address = token.slice(1, closing);
13011
+ } else if ((token.match(/:/g) ?? []).length === 1 && token.includes(".")) {
13012
+ const colon = token.indexOf(":");
13013
+ if (!parsePort(token.slice(colon + 1))) return null;
13014
+ address = token.slice(0, colon);
13015
+ }
13016
+ const ipv4 = parseIpv4(address);
13017
+ if (ipv4) return ipv4.join(".");
13018
+ const ipv6 = parseIpv6(address);
13019
+ return ipv6 ? compressIpv6(ipv6) : null;
13020
+ }
13021
+ function boundedTokens(raw) {
13022
+ if (raw == null || !raw || raw.length > MAX_INPUT_LENGTH || hasControlCharacter(raw)) return null;
13023
+ const tokens = raw.split(",");
13024
+ if (tokens.length > MAX_FORWARDED_HOPS) return null;
13025
+ return tokens;
13026
+ }
13027
+ function normalizeClientIp(raw) {
13028
+ const tokens = boundedTokens(raw);
13029
+ if (!tokens) return null;
13030
+ for (const token of tokens) {
13031
+ const normalized = normalizeToken(token);
13032
+ if (normalized) return normalized;
13033
+ }
13034
+ return null;
13035
+ }
13036
+ function getHeader(headers, name) {
13037
+ if ("get" in headers && typeof headers.get === "function") {
13038
+ return headers.get(name) ?? void 0;
13039
+ }
13040
+ const wanted = name.toLowerCase();
13041
+ for (const [key, value] of Object.entries(headers)) {
13042
+ if (key.toLowerCase() !== wanted || value === void 0) continue;
13043
+ return Array.isArray(value) ? value.join(",") : value;
13044
+ }
13045
+ return void 0;
13046
+ }
13047
+ function result(ip, source, trusted) {
13048
+ return ip ? { ip, source, trusted } : null;
13049
+ }
13050
+ function resolveAddress(raw, source) {
13051
+ return result(normalizeClientIp(raw), source, true);
13052
+ }
13053
+ function resolveExplicit(input) {
13054
+ if (input.explicitAddressTrusted !== true) return null;
13055
+ return result(normalizeClientIp(input.explicitAddress), "explicit", true);
13056
+ }
13057
+ function resolveVercel(input) {
13058
+ const platform = result(
13059
+ normalizeClientIp(getHeader(input.headers, "x-vercel-forwarded-for")),
13060
+ "x-vercel-forwarded-for",
13061
+ true
13062
+ );
13063
+ if (platform) return platform;
13064
+ const overwrittenXff = result(
13065
+ normalizeClientIp(getHeader(input.headers, "x-forwarded-for")),
13066
+ "x-forwarded-for",
13067
+ true
13068
+ );
13069
+ if (overwrittenXff) return overwrittenXff;
13070
+ const realIp = result(
13071
+ normalizeClientIp(getHeader(input.headers, "x-real-ip")),
13072
+ "x-real-ip",
13073
+ false
13074
+ );
13075
+ if (realIp) return realIp;
13076
+ return resolveAddress(input.frameworkAddress, "framework") ?? resolveAddress(input.directAddress, "socket") ?? { ip: null, source: "none", trusted: false };
13077
+ }
13078
+ function resolveCloudflare(input) {
13079
+ const cloudflare = result(
13080
+ normalizeClientIp(getHeader(input.headers, "cf-connecting-ip")),
13081
+ "cf-connecting-ip",
13082
+ true
13083
+ );
13084
+ if (cloudflare) return cloudflare;
13085
+ return resolveAddress(input.directAddress, "socket") ?? resolveAddress(input.frameworkAddress, "framework") ?? result(
13086
+ normalizeClientIp(getHeader(input.headers, "x-forwarded-for")),
13087
+ "x-forwarded-for",
13088
+ false
13089
+ ) ?? result(normalizeClientIp(getHeader(input.headers, "x-real-ip")), "x-real-ip", false) ?? {
13090
+ ip: null,
13091
+ source: "none",
13092
+ trusted: false
13093
+ };
13094
+ }
13095
+ function resolveTrustedProxy(input, trustedHops) {
13096
+ const raw = getHeader(input.headers, "x-forwarded-for");
13097
+ const tokens = boundedTokens(raw);
13098
+ if (tokens && Number.isInteger(trustedHops) && trustedHops > 0 && tokens.length > trustedHops) {
13099
+ const parsed = tokens.map(normalizeToken);
13100
+ const selectedIndex = tokens.length - trustedHops - 1;
13101
+ const selected = parsed[selectedIndex];
13102
+ if (selected && parsed.every((token) => token !== null)) {
13103
+ return { ip: selected, source: "x-forwarded-for", trusted: true };
13104
+ }
13105
+ }
13106
+ return resolveAddress(input.frameworkAddress, "framework") ?? resolveAddress(input.directAddress, "socket") ?? result(normalizeClientIp(getHeader(input.headers, "x-real-ip")), "x-real-ip", false) ?? {
13107
+ ip: null,
13108
+ source: "none",
13109
+ trusted: false
13110
+ };
13111
+ }
13112
+ function resolveClientIp(input) {
13113
+ const explicit = resolveExplicit(input);
13114
+ if (explicit) return explicit;
13115
+ switch (input.policy.platform) {
13116
+ case "vercel":
13117
+ return resolveVercel(input);
13118
+ case "cloudflare":
13119
+ return resolveCloudflare(input);
13120
+ case "trusted-proxy":
13121
+ return resolveTrustedProxy(input, input.policy.trustedHops);
13122
+ case "direct":
13123
+ return resolveAddress(input.frameworkAddress, "framework") ?? resolveAddress(input.directAddress, "socket") ?? {
13124
+ ip: null,
13125
+ source: "none",
13126
+ trusted: false
13127
+ };
13128
+ }
13129
+ }
13130
+
13131
+ // src/utils/correlation-id.ts
13132
+ var CORRELATION_ID_HEADER = "x-kya-correlation-id";
13133
+ var CorrelationIdSchema = external_exports.string().regex(/^[0-9a-f]{32}$/);
13134
+ var TRACEPARENT_RE = /^(?<ver>[0-9a-f]{2})-(?<trace>[0-9a-f]{32})-(?<span>[0-9a-f]{16})-(?<flags>[0-9a-f]{2})$/;
13135
+ var ZERO_TRACE_ID = "0".repeat(32);
13136
+ function getHeader2(headers, name) {
13137
+ const lower = name.toLowerCase();
13138
+ if (typeof headers.get === "function") {
13139
+ const value = headers.get(lower);
13140
+ return value && value.length > 0 ? value : null;
13141
+ }
13142
+ const record = headers;
13143
+ for (const key of Object.keys(record)) {
13144
+ if (key.toLowerCase() !== lower) continue;
13145
+ const raw = record[key];
13146
+ const value = Array.isArray(raw) ? raw[0] : raw;
13147
+ return value && value.length > 0 ? value : null;
13148
+ }
13149
+ return null;
13150
+ }
13151
+ function normalizeHex(value) {
13152
+ if (typeof value !== "string" || value.length === 0) return null;
13153
+ const candidate = value.toLowerCase().replace(/-/g, "");
13154
+ const parsed = CorrelationIdSchema.safeParse(candidate);
13155
+ return parsed.success ? parsed.data : null;
13156
+ }
13157
+ function extractTraceId(traceparent) {
13158
+ if (!traceparent) return null;
13159
+ const match = TRACEPARENT_RE.exec(traceparent);
13160
+ const trace = match?.groups?.trace;
13161
+ if (!trace || trace === ZERO_TRACE_ID) return null;
13162
+ return trace;
13163
+ }
13164
+ function toStoredCorrelationId(value) {
13165
+ return normalizeHex(value);
13166
+ }
13167
+ function extractCorrelationIdFromHeaders(headers) {
13168
+ const fromTrace = extractTraceId(getHeader2(headers, "traceparent"));
13169
+ if (fromTrace) return fromTrace;
13170
+ return normalizeHex(getHeader2(headers, CORRELATION_ID_HEADER));
13171
+ }
13172
+ function deriveCorrelationId(headers, fallback) {
13173
+ const fromHeaders = extractCorrelationIdFromHeaders(headers);
13174
+ if (fromHeaders) return fromHeaders;
13175
+ const fromFallback = normalizeHex(fallback);
13176
+ if (fromFallback) return fromFallback;
13177
+ return globalThis.crypto.randomUUID().replace(/-/g, "").toLowerCase();
13178
+ }
13179
+
11770
13180
  // src/schemas/auth.ts
11771
13181
  var passwordSchema = external_exports.string().min(8, "Password must be at least 8 characters long").max(128, "Password must not exceed 128 characters").regex(
11772
13182
  /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
@@ -11893,7 +13303,7 @@ var discoveredToolSchema = external_exports.object({
11893
13303
  * Schema draft here. The Tool Testing Panel renders a
11894
13304
  * skeleton from whatever it gets.
11895
13305
  */
11896
- inputSchema: external_exports.record(external_exports.unknown()).optional()
13306
+ inputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
11897
13307
  }).strict();
11898
13308
  var upstreamDiscoveryErrorSchema = external_exports.object({
11899
13309
  code: external_exports.enum([
@@ -11914,7 +13324,7 @@ var upstreamDiscoveryErrorSchema = external_exports.object({
11914
13324
  }).strict();
11915
13325
  var gatewayInternalToolsListSchema = external_exports.object({
11916
13326
  totalCount: external_exports.number().int().min(0),
11917
- upstreamCounts: external_exports.record(external_exports.number().int().min(0)),
13327
+ upstreamCounts: external_exports.record(external_exports.string(), external_exports.number().int().min(0)),
11918
13328
  tools: external_exports.array(discoveredToolSchema),
11919
13329
  /**
11920
13330
  * Sparse map keyed by upstream slug. Empty / absent when every
@@ -11922,7 +13332,7 @@ var gatewayInternalToolsListSchema = external_exports.object({
11922
13332
  * when serialized — always-object keeps the shape stable for
11923
13333
  * consumers that read `Object.keys(errors).length`.
11924
13334
  */
11925
- errors: external_exports.record(upstreamDiscoveryErrorSchema)
13335
+ errors: external_exports.record(external_exports.string(), upstreamDiscoveryErrorSchema)
11926
13336
  }).strict();
11927
13337
  var gatewayInternalDiscoverSuccessSchema = external_exports.object({
11928
13338
  tools: external_exports.array(discoveredToolSchema)
@@ -12054,7 +13464,30 @@ var upstreamServerSchema = external_exports.object({
12054
13464
  transport: external_exports.enum(["http", "sse"]).default("http"),
12055
13465
  authType: external_exports.enum(["none", "vault", "static"]).default("none"),
12056
13466
  envVarNames: external_exports.array(external_exports.string()).optional(),
12057
- staticHeaders: external_exports.record(external_exports.string()).optional(),
13467
+ // ─────────────────────────────────────────────────────────────────
13468
+ // Static-header credential plane (hygiene-scorecard gap #1)
13469
+ //
13470
+ // `staticHeaders` (plaintext) is DEPRECATED as an at-rest field —
13471
+ // kept here only so `.parse()` doesn't silently drop rows written
13472
+ // before this fix while they wait to be re-encrypted. It remains the
13473
+ // wire-input field name (the admin form still submits plaintext
13474
+ // header values; the PUT handler encrypts them into
13475
+ // `staticHeadersEncrypted` before persisting and opportunistically
13476
+ // migrates any legacy plaintext it finds on every save that touches
13477
+ // an upstream). Never populated in an API response.
13478
+ staticHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional(),
13479
+ // AES-256-GCM ciphertext (base64: iv|ciphertext|authTag) of the
13480
+ // JSON-serialized staticHeaders map — the at-rest form going
13481
+ // forward. Encrypt/decrypt via `@kya-os/checkpoint-db/crypto`'s
13482
+ // `encryptStaticHeaders`/`resolveStaticHeaders`. Never populated in
13483
+ // an API response — see `staticHeaderKeys` for the redacted view.
13484
+ staticHeadersEncrypted: external_exports.string().nullable().optional(),
13485
+ // Read-only projection of the configured header NAMES (never
13486
+ // values). Populated by the gateway-mcp config GET/PUT response
13487
+ // serializer (`redactGatewayConfig`) so the dashboard can render
13488
+ // "N headers configured" without ever receiving secret material or
13489
+ // ciphertext. Ignored on write — `upstreamServerInputSchema` omits it.
13490
+ staticHeaderKeys: external_exports.array(external_exports.string()).optional(),
12058
13491
  // ─────────────────────────────────────────────────────────────────
12059
13492
  // #1600 Phase 1 Part 2 — credential flow method selection
12060
13493
  //
@@ -12083,10 +13516,39 @@ var upstreamServerSchema = external_exports.object({
12083
13516
  // at `content/docs/govern/connections-github.mdx` for the
12084
13517
  // rationale (scope sprawl hesitancy).
12085
13518
  // ─────────────────────────────────────────────────────────────────
12086
- supportedAuthMethods: external_exports.array(external_exports.enum(["paste", "oauth"])).default(["paste"]),
12087
- oauthProvider: external_exports.enum(["github", "slack", "notion", "linear"]).optional(),
13519
+ supportedAuthMethods: external_exports.array(external_exports.enum(["paste", "oauth"])).default(["paste"]),
13520
+ oauthProvider: external_exports.enum(["github", "slack", "notion", "linear"]).optional(),
13521
+ // ─────────────────────────────────────────────────────────────────
13522
+ // Stateless (UCP-style) upstreams
13523
+ //
13524
+ // Some MCP-transport endpoints reject `initialize` and `tools/list`
13525
+ // outright and treat every POST as an independent request — UCP
13526
+ // servers (ucp.dev) such as the Shopify Global Catalog are the
13527
+ // motivating case. `sessionMode: 'stateless'` tells the gateway to
13528
+ // skip the initialize handshake and the per-user session cache for
13529
+ // this upstream, and to serve its tool list ONLY from a persisted
13530
+ // manifest (live discovery cannot succeed by design, and attempting
13531
+ // it would feed the health tracker until the upstream is marked
13532
+ // down). Absent means the standard MCP handshake — optional rather
13533
+ // than defaulted so the field stays optional on the inferred type
13534
+ // and pre-existing rows/fixtures parse unchanged.
13535
+ //
13536
+ // `ucpProfileUrl` is the UCP agent-profile document the gateway
13537
+ // injects as `arguments.meta["ucp-agent"].profile` on tools/call
13538
+ // when the caller didn't supply its own — UCP servers reject calls
13539
+ // without it. `safeUrl` (not a plain URL check) because the value
13540
+ // is fetched by third-party upstreams and must never point at a
13541
+ // private/internal host.
13542
+ // ─────────────────────────────────────────────────────────────────
13543
+ sessionMode: external_exports.enum(["standard", "stateless"]).optional(),
13544
+ ucpProfileUrl: safeUrl.optional(),
12088
13545
  enabled: external_exports.boolean().default(true),
12089
- healthStatus: external_exports.enum(["healthy", "degraded", "down"]).default("healthy"),
13546
+ // No default on purpose: the gateway's health-tracker persistence is a
13547
+ // v1 no-op (see apps/gateway/src/bootstrap.ts), so nothing writes real
13548
+ // status yet. A `.default('healthy')` here made every upstream render a
13549
+ // false green "Healthy" dot. `undefined` means "never checked" and
13550
+ // consumers must render a neutral "Unchecked" state for it.
13551
+ healthStatus: external_exports.enum(["healthy", "degraded", "down"]).optional(),
12090
13552
  consecutiveFailures: external_exports.number().int().min(0).default(0),
12091
13553
  // ─────────────────────────────────────────────────────────────────
12092
13554
  // v1.1 KTA Trust Layer forward-compat (see #1549)
@@ -12107,7 +13569,7 @@ var upstreamServerSchema = external_exports.object({
12107
13569
  ktaLastFetchedAt: external_exports.string().datetime().nullable().optional(),
12108
13570
  // ─────────────────────────────────────────────────────────────────
12109
13571
  // Per-upstream project lifecycle (Option A — #1566)
12110
- // Links this upstream to a dedicated AgentShield project for
13572
+ // Links this upstream to a dedicated Checkpoint project for
12111
13573
  // per-upstream detection, policy, and audit isolation.
12112
13574
  // ─────────────────────────────────────────────────────────────────
12113
13575
  projectId: external_exports.string().uuid().nullable().optional(),
@@ -12123,7 +13585,7 @@ var upstreamServerSchema = external_exports.object({
12123
13585
  // is AUTHORITATIVE — consumers prefer it and treat this copy as a hint.
12124
13586
  authorizationHost: external_exports.string().max(255).nullable().optional()
12125
13587
  });
12126
- var upstreamServerInputSchema = upstreamServerSchema.extend({
13588
+ var upstreamServerInputSchema = upstreamServerSchema.omit({ staticHeadersEncrypted: true, staticHeaderKeys: true }).extend({
12127
13589
  id: external_exports.string().uuid().optional(),
12128
13590
  slug: external_exports.string().regex(/^[a-z0-9]+(?:_[a-z0-9]+)*$/, {
12129
13591
  message: "Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)"
@@ -12157,7 +13619,7 @@ var DEFAULT_EXTERNAL_ACCESS = {
12157
13619
  var gatewayConfigSchema = external_exports.object({
12158
13620
  enabled: external_exports.boolean().default(false),
12159
13621
  upstreamServers: external_exports.array(upstreamServerSchema).default([]),
12160
- roleScopes: external_exports.record(external_exports.array(external_exports.string())).optional(),
13622
+ roleScopes: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).optional(),
12161
13623
  oauthClients: external_exports.array(oauthClientSchema).default([]),
12162
13624
  rateLimits: external_exports.object({
12163
13625
  toolCallsPerMinute: external_exports.number().int().positive().default(DEFAULT_RATE_LIMITS.toolCallsPerMinute)
@@ -12165,7 +13627,7 @@ var gatewayConfigSchema = external_exports.object({
12165
13627
  externalAccess: external_exports.object({
12166
13628
  enabled: external_exports.boolean().default(DEFAULT_EXTERNAL_ACCESS.enabled),
12167
13629
  allowedDids: external_exports.array(external_exports.string()).default(DEFAULT_EXTERNAL_ACCESS.allowedDids),
12168
- externalScopes: external_exports.record(external_exports.array(external_exports.string())).default(DEFAULT_EXTERNAL_ACCESS.externalScopes)
13630
+ externalScopes: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).default(DEFAULT_EXTERNAL_ACCESS.externalScopes)
12169
13631
  }).default(DEFAULT_EXTERNAL_ACCESS),
12170
13632
  // T6 #2899 M2 — per-org fleet-server endpoint. When set, the gateway's
12171
13633
  // DiscoveryUpstreamProvider injects a synthetic `fleet` upstream so
@@ -12223,11 +13685,11 @@ var gatewayConnectionsSummarySchema = external_exports.object({
12223
13685
 
12224
13686
  // src/schemas/index.ts
12225
13687
  function validate(schema, data) {
12226
- const result = schema.safeParse(data);
12227
- if (result.success) {
12228
- return { success: true, data: result.data };
13688
+ const result2 = schema.safeParse(data);
13689
+ if (result2.success) {
13690
+ return { success: true, data: result2.data };
12229
13691
  }
12230
- return { success: false, error: result.error };
13692
+ return { success: false, error: result2.error };
12231
13693
  }
12232
13694
  function validateOrThrow(schema, data) {
12233
13695
  return schema.parse(data);
@@ -12378,7 +13840,7 @@ var BehavioralThresholdSchema = external_exports.object({
12378
13840
  var BehavioralPatternSchema = external_exports.object({
12379
13841
  name: external_exports.string().min(1),
12380
13842
  type: external_exports.enum(["rapid_requests", "no_interaction", "perfect_scrolling", "sequential_access"]),
12381
- config: external_exports.record(external_exports.any()),
13843
+ config: external_exports.record(external_exports.string(), external_exports.any()),
12382
13844
  confidenceModifier: external_exports.number().min(-1).max(1)
12383
13845
  });
12384
13846
  var BehavioralRulesSchema = external_exports.object({
@@ -12401,13 +13863,13 @@ var HeaderRulesSchema = external_exports.object({
12401
13863
  var IpRangeCollectionSchema = external_exports.union([
12402
13864
  // Old structure with providers
12403
13865
  external_exports.object({
12404
- providers: external_exports.record(IpRangeRuleSchema),
13866
+ providers: external_exports.record(external_exports.string(), IpRangeRuleSchema),
12405
13867
  updateUrl: external_exports.string().url().optional(),
12406
13868
  updateFrequency: external_exports.enum(["hourly", "daily", "weekly", "monthly"]).optional(),
12407
13869
  cacheDuration: external_exports.number().min(0).optional()
12408
13870
  }),
12409
13871
  // New merged structure - IP ranges directly as properties
12410
- external_exports.record(IpRangeRuleSchema).refine(
13872
+ external_exports.record(external_exports.string(), IpRangeRuleSchema).refine(
12411
13873
  (val) => {
12412
13874
  return Object.values(val).some(
12413
13875
  (v) => v && typeof v === "object" && "ranges" in v && Array.isArray(v.ranges)
@@ -12426,9 +13888,9 @@ var DetectionRulesSchema = external_exports.object({
12426
13888
  source: external_exports.string().optional()
12427
13889
  }).optional(),
12428
13890
  rules: external_exports.object({
12429
- userAgents: external_exports.record(UserAgentRuleSchema),
13891
+ userAgents: external_exports.record(external_exports.string(), UserAgentRuleSchema),
12430
13892
  ipRanges: IpRangeCollectionSchema,
12431
- signatures: external_exports.record(SignatureRuleSchema),
13893
+ signatures: external_exports.record(external_exports.string(), SignatureRuleSchema),
12432
13894
  behavioral: BehavioralRulesSchema,
12433
13895
  headers: HeaderRulesSchema
12434
13896
  })
@@ -12470,7 +13932,7 @@ var RuleMatchResultSchema = external_exports.object({
12470
13932
  rule: external_exports.string().optional(),
12471
13933
  category: external_exports.enum(["userAgent", "ipRange", "signature", "behavioral", "header"]).optional(),
12472
13934
  confidence: external_exports.number().min(0).max(1).optional(),
12473
- details: external_exports.record(external_exports.any()).optional()
13935
+ details: external_exports.record(external_exports.string(), external_exports.any()).optional()
12474
13936
  });
12475
13937
  function validateRules(rules) {
12476
13938
  try {
@@ -12480,7 +13942,7 @@ function validateRules(rules) {
12480
13942
  if (error instanceof external_exports.ZodError) {
12481
13943
  return {
12482
13944
  valid: false,
12483
- errors: error.errors.map((e) => ({
13945
+ errors: error.issues.map((e) => ({
12484
13946
  path: e.path.join("."),
12485
13947
  message: e.message,
12486
13948
  type: e.code
@@ -12510,7 +13972,7 @@ function validateRulesLoose(rules) {
12510
13972
  if (error instanceof external_exports.ZodError) {
12511
13973
  return {
12512
13974
  valid: false,
12513
- errors: error.errors.map((e) => ({
13975
+ errors: error.issues.map((e) => ({
12514
13976
  path: e.path.join("."),
12515
13977
  message: e.message,
12516
13978
  type: e.code
@@ -12551,9 +14013,9 @@ var RuleValidator = class {
12551
14013
  * Validate and throw on error
12552
14014
  */
12553
14015
  static validateOrThrow(rules, mode = "strict") {
12554
- const result = this.validate(rules, mode);
12555
- if (!result.valid) {
12556
- const errors = result.errors?.map((e) => `${e.path}: ${e.message}`).join(", ");
14016
+ const result2 = this.validate(rules, mode);
14017
+ if (!result2.valid) {
14018
+ const errors = result2.errors?.map((e) => `${e.path}: ${e.message}`).join(", ");
12557
14019
  throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);
12558
14020
  }
12559
14021
  return rules;
@@ -12566,7 +14028,7 @@ var RuleValidator = class {
12566
14028
  return DetectionRulesSchema.parse(rules);
12567
14029
  } catch (error) {
12568
14030
  if (error instanceof external_exports.ZodError) {
12569
- const errors = error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ");
14031
+ const errors = error.issues.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ");
12570
14032
  throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);
12571
14033
  }
12572
14034
  throw error;
@@ -12624,18 +14086,18 @@ var RuleValidator = class {
12624
14086
  /**
12625
14087
  * Get validation errors as formatted string
12626
14088
  */
12627
- static formatErrors(result) {
12628
- if (result.valid) {
14089
+ static formatErrors(result2) {
14090
+ if (result2.valid) {
12629
14091
  return "";
12630
14092
  }
12631
- const errors = result.errors || [];
14093
+ const errors = result2.errors || [];
12632
14094
  return errors.map((e) => ` - ${e.path}: ${e.message}`).join("\n");
12633
14095
  }
12634
14096
  /**
12635
14097
  * Get validation warnings as formatted string
12636
14098
  */
12637
- static formatWarnings(result) {
12638
- const warnings = result.warnings || [];
14099
+ static formatWarnings(result2) {
14100
+ const warnings = result2.warnings || [];
12639
14101
  return warnings.map((w) => ` - ${w.path}: ${w.message}`).join("\n");
12640
14102
  }
12641
14103
  };
@@ -12717,7 +14179,9 @@ var RuleParser = class {
12717
14179
  * Validate basic rule structure
12718
14180
  */
12719
14181
  static validateStructure(rules) {
12720
- return !!(rules && typeof rules === "object" && typeof rules.version === "string" && typeof rules.lastUpdated === "string" && rules.rules && typeof rules.rules === "object");
14182
+ if (!rules || typeof rules !== "object") return false;
14183
+ const candidate = rules;
14184
+ return !!(typeof candidate.version === "string" && typeof candidate.lastUpdated === "string" && candidate.rules && typeof candidate.rules === "object");
12721
14185
  }
12722
14186
  };
12723
14187
 
@@ -12864,6 +14328,40 @@ async function loadRulesAsync(options) {
12864
14328
  return loader.loadRules(options);
12865
14329
  }
12866
14330
 
14331
+ // src/rules/vendor-range-freshness.ts
14332
+ var DEFAULT_MAX_VENDOR_RANGE_AGE_MS = 4 * 24 * 60 * 60 * 1e3;
14333
+ function findStaleVendorRanges(vendors, now, maxAgeMs = DEFAULT_MAX_VENDOR_RANGE_AGE_MS) {
14334
+ const stale = [];
14335
+ for (const v of vendors) {
14336
+ if (v.enabled === false) continue;
14337
+ const parsedMs = Date.parse(v.lastCheckedIso);
14338
+ const ageMs = Number.isNaN(parsedMs) ? Infinity : now.getTime() - parsedMs;
14339
+ if (ageMs > maxAgeMs) {
14340
+ stale.push({ id: v.id, lastCheckedIso: v.lastCheckedIso, ageMs });
14341
+ }
14342
+ }
14343
+ return stale;
14344
+ }
14345
+ var StaleVendorRangesError = class extends Error {
14346
+ constructor(stale) {
14347
+ const detail = stale.map((s) => {
14348
+ const age = s.ageMs === Infinity ? `unparseable/missing last_checked (${JSON.stringify(s.lastCheckedIso)})` : `${(s.ageMs / (24 * 60 * 60 * 1e3)).toFixed(1)}d old`;
14349
+ return `${s.id} (${age})`;
14350
+ }).join(", ");
14351
+ super(
14352
+ `${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.`
14353
+ );
14354
+ this.stale = stale;
14355
+ this.name = "StaleVendorRangesError";
14356
+ }
14357
+ };
14358
+ function assertVendorRangesFresh(vendors, now, maxAgeMs = DEFAULT_MAX_VENDOR_RANGE_AGE_MS) {
14359
+ const stale = findStaleVendorRanges(vendors, now, maxAgeMs);
14360
+ if (stale.length > 0) {
14361
+ throw new StaleVendorRangesError(stale);
14362
+ }
14363
+ }
14364
+
12867
14365
  // src/policy/constants.ts
12868
14366
  var ENFORCEMENT_ACTIONS = {
12869
14367
  /** New canonical name for "the engine permits this request through." */
@@ -13004,7 +14502,29 @@ var BlockReasonSchema = external_exports.discriminatedUnion("kind", [
13004
14502
  // index join key). Optional + additive — absent on pre-PR2 payloads.
13005
14503
  policyId: external_exports.string().optional()
13006
14504
  }),
13007
- external_exports.object({ kind: external_exports.literal("ParseError"), detail: external_exports.string() })
14505
+ external_exports.object({
14506
+ // Tier-2 IP+UA cross-match against the vendor SSOT (AIVF-1 Path B).
14507
+ // Emitted when the request carries both a vendor-published IP and a
14508
+ // matching UA pattern. `confidence` is f32 in [0, 1] — NOT the 0-100
14509
+ // scale the rest of the detection detail uses.
14510
+ kind: external_exports.literal("AgentAttribution"),
14511
+ vendor: external_exports.string(),
14512
+ tier: external_exports.number().int(),
14513
+ confidence: external_exports.number().min(0).max(1)
14514
+ }),
14515
+ external_exports.object({ kind: external_exports.literal("ParseError"), detail: external_exports.string() }),
14516
+ external_exports.object({
14517
+ // Tier-3 UA-only pattern-match short-circuit (engine default policy).
14518
+ // Field names are snake_case ON THE WIRE (the Rust enum has no
14519
+ // `rename_all`) and mirror the Rust struct fields verbatim.
14520
+ // `pattern_kind` is `KnownAiAgent` | `AiCrawler` | `HeadlessBrowser`
14521
+ // today; kept a loose string so future engine kinds stay additive.
14522
+ // `confidence` is an integer percent (0-100), unlike AgentAttribution.
14523
+ kind: external_exports.literal("Tier3UAMatch"),
14524
+ pattern_id: external_exports.string(),
14525
+ pattern_kind: external_exports.string(),
14526
+ confidence: external_exports.number().int().min(0).max(100)
14527
+ })
13008
14528
  ]);
13009
14529
  var AssuranceTierSchema = external_exports.enum([
13010
14530
  "anonymous",
@@ -13022,7 +14542,7 @@ var ChallengeParamsSchema = external_exports.object({
13022
14542
  // draft-kya-http-02 §1/§8 — the minimum assurance tier the policy demands
13023
14543
  // of the retry, set by a Cedar `@min_assurance(...)` annotation and
13024
14544
  // advertised by the PEP as `min_assurance` in the WWW-Authenticate
13025
- // Delegation challenge. Optional + additive: absent for MCP-I L2+ handshake
14545
+ // Delegation challenge. Optional + additive: absent for KYA-OS L2+ handshake
13026
14546
  // challenges, so the DIF interop shape is unchanged when unset.
13027
14547
  minAssurance: AssuranceTierSchema.optional(),
13028
14548
  // #3272 PR2: the determining policy's authored Cedar @id. Optional + additive.
@@ -13077,9 +14597,9 @@ var ThresholdConfigSchema = external_exports.object({
13077
14597
  trustSignedRequests: external_exports.boolean().default(DEFAULT_THRESHOLDS.trustSignedRequests)
13078
14598
  });
13079
14599
  var DenyListEntrySchema = external_exports.object({
13080
- /** MCP-I client DID */
14600
+ /** KYA-OS client DID */
13081
14601
  clientDid: external_exports.string().optional(),
13082
- /** Agent DID from MCP-I identity */
14602
+ /** Agent DID from KYA-OS identity */
13083
14603
  agentDid: external_exports.string().optional(),
13084
14604
  /** Human-readable client name (e.g., "ChatGPT") */
13085
14605
  clientName: external_exports.string().optional(),
@@ -13097,9 +14617,9 @@ var DenyListEntrySchema = external_exports.object({
13097
14617
  expiresAt: external_exports.string().optional()
13098
14618
  });
13099
14619
  var AllowListEntrySchema = external_exports.object({
13100
- /** MCP-I client DID */
14620
+ /** KYA-OS client DID */
13101
14621
  clientDid: external_exports.string().optional(),
13102
- /** Agent DID from MCP-I identity */
14622
+ /** Agent DID from KYA-OS identity */
13103
14623
  agentDid: external_exports.string().optional(),
13104
14624
  /** Human-readable client name */
13105
14625
  clientName: external_exports.string().optional(),
@@ -13317,8 +14837,8 @@ function parsePolicyConfig(data) {
13317
14837
  return PolicyConfigSchema.parse(data);
13318
14838
  }
13319
14839
  function safeParsePolicyConfig(data) {
13320
- const result = PolicyConfigSchema.safeParse(data);
13321
- return result.success ? result.data : null;
14840
+ const result2 = PolicyConfigSchema.safeParse(data);
14841
+ return result2.success ? result2.data : null;
13322
14842
  }
13323
14843
  function parseEvaluationContext(data) {
13324
14844
  return PolicyEvaluationContextSchema.parse(data);
@@ -13697,27 +15217,40 @@ function blockApplies(block, request) {
13697
15217
  }
13698
15218
  return true;
13699
15219
  }
13700
- function blockMatchesPath(block, path) {
13701
- const literals = Array.from(
15220
+ function pathLiteralsInBlock(block) {
15221
+ return Array.from(
13702
15222
  block.matchAll(cedarQuotedValueRegExp("resource\\.path (?:like|==) ", "g")),
13703
15223
  (m) => unescapeCedarString(m[1])
13704
15224
  );
15225
+ }
15226
+ function blockMatchesPath(block, path) {
15227
+ const literals = pathLiteralsInBlock(block);
13705
15228
  if (literals.length === 0) return true;
13706
15229
  return literals.some((literal) => pathLiteralMatches(literal, path));
13707
15230
  }
13708
15231
  function escapeRegExp(s) {
13709
15232
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13710
15233
  }
13711
- function blockMatchesEquality(block, attr, value) {
15234
+ function splitCedarBlocks(cedar) {
15235
+ return cedar.split(/\n\s*\n/).map((b) => b.trim()).filter((b) => b.length > 0);
15236
+ }
15237
+ function blockEqualityLiterals(block, attr) {
13712
15238
  const a = escapeRegExp(attr);
13713
- const eq = Array.from(
15239
+ return Array.from(
13714
15240
  block.matchAll(cedarQuotedValueRegExp(`${a} == `, "g")),
13715
15241
  (m) => unescapeCedarString(m[1])
13716
15242
  );
13717
- const neq = Array.from(
15243
+ }
15244
+ function blockExclusionLiterals(block, attr) {
15245
+ const a = escapeRegExp(attr);
15246
+ return Array.from(
13718
15247
  block.matchAll(cedarQuotedValueRegExp(`${a} != `, "g")),
13719
15248
  (m) => unescapeCedarString(m[1])
13720
15249
  );
15250
+ }
15251
+ function blockMatchesEquality(block, attr, value) {
15252
+ const eq = blockEqualityLiterals(block, attr);
15253
+ const neq = blockExclusionLiterals(block, attr);
13721
15254
  if (neq.includes(value)) return false;
13722
15255
  if (eq.length > 0) return eq.includes(value);
13723
15256
  return true;
@@ -13731,6 +15264,25 @@ function pathLiteralMatches(literal, path) {
13731
15264
  return false;
13732
15265
  }
13733
15266
  }
15267
+ function isForbidBlock(block) {
15268
+ return /\bforbid\s*\(/.test(block);
15269
+ }
15270
+ function narrowsPrincipal(block) {
15271
+ if (blockEqualityLiterals(block, "principal.category").length > 0) return true;
15272
+ if (blockExclusionLiterals(block, "principal.category").includes("human")) return true;
15273
+ if (blockEqualityLiterals(block, "principal.name").length > 0) return true;
15274
+ if (/principal\s+is\s+\w/.test(block)) return true;
15275
+ if (/forbid\s*\(\s*principal\s*==/.test(block)) return true;
15276
+ return false;
15277
+ }
15278
+ function isUnnarrowedDenyBlock(block) {
15279
+ return isForbidBlock(block) && !narrowsPrincipal(block);
15280
+ }
15281
+ function pathHasUnnarrowedDenyRule(cedar, path) {
15282
+ return splitCedarBlocks(cedar).some(
15283
+ (block) => isUnnarrowedDenyBlock(block) && blockMatchesPath(block, path)
15284
+ );
15285
+ }
13734
15286
 
13735
15287
  // src/policy/required-scopes.ts
13736
15288
  function requiredScopesForRequest(policySource, request) {
@@ -13766,6 +15318,54 @@ function decisionPolicyId(decision) {
13766
15318
  }
13767
15319
  }
13768
15320
 
15321
+ // src/policy/bespoke-policy.ts
15322
+ var BESPOKE_POLICY_IDS = {
15323
+ denyList: "bespoke-deny-list",
15324
+ allowList: "bespoke-allow-list",
15325
+ pathRule: "bespoke-path-rule",
15326
+ threshold: "bespoke-threshold"
15327
+ };
15328
+ var BESPOKE_POLICY_LABELS = {
15329
+ [BESPOKE_POLICY_IDS.denyList]: "Deny list",
15330
+ [BESPOKE_POLICY_IDS.allowList]: "Allow list",
15331
+ [BESPOKE_POLICY_IDS.pathRule]: "Path rule",
15332
+ [BESPOKE_POLICY_IDS.threshold]: "Confidence threshold"
15333
+ };
15334
+ var BESPOKE_POLICY_ID_SET = new Set(Object.values(BESPOKE_POLICY_IDS));
15335
+ function isBespokePolicyId(policyId) {
15336
+ return typeof policyId === "string" && BESPOKE_POLICY_ID_SET.has(policyId);
15337
+ }
15338
+ function bespokePolicyLabel(policyId) {
15339
+ return BESPOKE_POLICY_LABELS[policyId] ?? null;
15340
+ }
15341
+ var BASELINE_ALLOW_POLICY_ID = "baseline-allow";
15342
+ function isNonNavigablePolicyId(policyId) {
15343
+ return isBespokePolicyId(policyId) || policyId === BASELINE_ALLOW_POLICY_ID;
15344
+ }
15345
+ function nonNavigablePolicyLabel(policyId) {
15346
+ if (policyId === BASELINE_ALLOW_POLICY_ID) return "Default allow";
15347
+ return typeof policyId === "string" ? bespokePolicyLabel(policyId) : null;
15348
+ }
15349
+
15350
+ // src/policy/policy-lint.ts
15351
+ 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.';
15352
+ function blockIdAnnotation(block) {
15353
+ const m = block.match(/@id\("((?:\\.|[^"\\])*)"\)/);
15354
+ return m ? m[1] : void 0;
15355
+ }
15356
+ function lintUnnarrowedDenyRules(cedar) {
15357
+ const findings = [];
15358
+ let searchFrom = 0;
15359
+ for (const block of splitCedarBlocks(cedar)) {
15360
+ if (!isUnnarrowedDenyBlock(block)) continue;
15361
+ const idx = cedar.indexOf(block, searchFrom);
15362
+ const line = idx < 0 ? 1 : cedar.slice(0, idx).split("\n").length;
15363
+ if (idx >= 0) searchFrom = idx + block.length;
15364
+ findings.push({ ruleId: blockIdAnnotation(block), line, message: UNNARROWED_DENY_MESSAGE });
15365
+ }
15366
+ return findings;
15367
+ }
15368
+
13769
15369
  // src/policy/approval-quorum.ts
13770
15370
  function approvalQuorumForRequest(policySource, request) {
13771
15371
  if (!policySource || !policySource.trim()) return null;
@@ -14103,217 +15703,408 @@ function readHeader(input, name) {
14103
15703
  }
14104
15704
  return void 0;
14105
15705
  }
14106
- function serveBodyReadable200(headers, detectionClass) {
15706
+ function serveBodyReadable200(headers, detectionClass, isAgent) {
14107
15707
  const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);
14108
15708
  if (optIn && optIn.trim().length > 0) return true;
14109
- if (detectionClass !== void 0 && detectionClass !== null) {
15709
+ if (isAgent && detectionClass !== void 0 && detectionClass !== null) {
14110
15710
  if (normalizeDetectionClassEnum(detectionClass) === "ai_agent") return true;
14111
15711
  }
14112
15712
  return false;
14113
15713
  }
14114
- function selectBodyReadable200(mode, headers, detectionClass) {
15714
+ function selectBodyReadable200(mode, headers, detectionClass, isAgent) {
14115
15715
  if (mode === "always-200") return true;
14116
- if (mode === "negotiated") return serveBodyReadable200(headers, detectionClass);
15716
+ if (mode === "negotiated") return serveBodyReadable200(headers, detectionClass, isAgent);
14117
15717
  return false;
14118
15718
  }
14119
15719
 
14120
- // src/wire/vault.ts
14121
- var vaultResolveMetaSchema = external_exports.object({
14122
- orgSlug: external_exports.string().optional(),
14123
- upstreamSlug: external_exports.string().optional()
14124
- }).strict();
14125
- var vaultResolveDataSchema = external_exports.object({
14126
- secrets: external_exports.record(external_exports.string()),
14127
- _meta: vaultResolveMetaSchema.optional()
14128
- }).strict();
14129
- var vaultResolveSuccessSchema = external_exports.object({
14130
- success: external_exports.literal(true),
14131
- data: vaultResolveDataSchema
14132
- }).strict();
14133
- var vaultResolveErrorSchema = external_exports.object({
14134
- success: external_exports.literal(false),
14135
- error: external_exports.object({
14136
- code: external_exports.string(),
14137
- message: external_exports.string(),
14138
- data: external_exports.object({
14139
- orgSlug: external_exports.string().optional(),
14140
- upstreamSlug: external_exports.string().optional(),
14141
- retryAfter: external_exports.number().optional()
14142
- }).passthrough().optional()
14143
- }).strict()
14144
- }).strict();
14145
- var vaultResolveResponseSchema = external_exports.discriminatedUnion("success", [
14146
- vaultResolveSuccessSchema,
14147
- vaultResolveErrorSchema
15720
+ // src/mcpi/kya-http-error-codes.ts
15721
+ var KYA_HTTP_ERROR = {
15722
+ // ── 401 (identity / signature) ──────────────────────────────────────────
15723
+ MISSING_SIGNATURE: "kyaos/missing-signature",
15724
+ INVALID_SIGNATURE: "kyaos/invalid-signature",
15725
+ EXPIRED: "kyaos/expired",
15726
+ REPLAY: "kyaos/replay",
15727
+ DID_UNRESOLVABLE: "kyaos/did-unresolvable",
15728
+ AUTHORIZATION_REQUIRED: "kyaos/authorization-required",
15729
+ // ── 403 (delegation / profile) ──────────────────────────────────────────
15730
+ PROFILE_VIOLATION: "kyaos/profile-violation",
15731
+ DELEGATION_REVOKED: "kyaos/delegation-revoked",
15732
+ SCOPE_INSUFFICIENT: "kyaos/scope-insufficient",
15733
+ CHAIN_BROKEN: "kyaos/chain-broken",
15734
+ HOLDER_MISMATCH: "kyaos/holder-mismatch",
15735
+ AUDIENCE_MISMATCH: "kyaos/audience-mismatch",
15736
+ SESSION_MISMATCH: "kyaos/session-mismatch",
15737
+ PICKUP_PINNED: "kyaos/pickup-pinned",
15738
+ // Credential verified but its achieved assurance tier is below the
15739
+ // determining policy's opt-in `@min_assurance` floor (trust-gap G3) — a
15740
+ // bearer credential (attested-bearer, no proof-of-possession) cannot satisfy
15741
+ // a key-bound+ floor. Recovery: a key-bound signed request, not a new
15742
+ // credential.
15743
+ ASSURANCE_INSUFFICIENT: "kyaos/assurance-insufficient",
15744
+ // ── 503 (revocation status unverifiable — RETRYABLE) ─────────────────────
15745
+ // Emitted when a credential DECLARES a `credentialStatus` but its status list
15746
+ // was not supplied / could not be fetched (cold cache, past the 300s status
15747
+ // cap). Fail-closed but retryable: a warmed list may yet verify (#3345 / #3446).
15748
+ STATUS_PENDING: "kyaos/status-pending",
15749
+ // ── pickup flow (404 / 410) ─────────────────────────────────────────────
15750
+ INVALID_SESSION: "kyaos/invalid-session",
15751
+ PICKUP_EXPIRED: "kyaos/pickup-expired"
15752
+ };
15753
+
15754
+ // src/host-adapter/challenge-wire.ts
15755
+ var PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
15756
+ var DEFAULT_POLL_INTERVAL_S = 3;
15757
+ var INVALID_QUOTED_VALUE = /[\u0000-\u001f\u007f"\\]/;
15758
+ var SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
15759
+ var SID = /^kya-[0-9a-f]{16,}$/;
15760
+ var ASSURANCE_TIERS = /* @__PURE__ */ new Set([
15761
+ "anonymous",
15762
+ "attested-bearer",
15763
+ "key-bound",
15764
+ "registered",
15765
+ "delegated"
14148
15766
  ]);
14149
- function canonicalSigningPayload(payload) {
14150
- const json = canonicalize(payload);
14151
- if (json === void 0) {
14152
- throw new Error("canonicalSigningPayload: payload contains non-serializable values");
14153
- }
14154
- return new TextEncoder().encode(json);
14155
- }
14156
- var REQUIRED_STRING_FIELDS = [
14157
- "aud",
14158
- "iss",
14159
- "sub",
14160
- "nonce",
14161
- "sessionId",
14162
- "requestHash",
14163
- "responseHash"
14164
- ];
14165
- function validateMcpIPayload(value) {
14166
- if (value === null || typeof value !== "object") {
14167
- throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
15767
+ var ChallengeWireError = class extends TypeError {
15768
+ code;
15769
+ constructor(code, message) {
15770
+ super(message);
15771
+ this.name = "ChallengeWireError";
15772
+ this.code = code;
14168
15773
  }
14169
- const obj = value;
14170
- for (const field of REQUIRED_STRING_FIELDS) {
14171
- if (typeof obj[field] !== "string") {
14172
- throw new Error(`missing or non-string required field "${field}" (got ${typeof obj[field]})`);
14173
- }
15774
+ };
15775
+ function generateDelegationSid() {
15776
+ const bytes = new Uint8Array(16);
15777
+ crypto.getRandomValues(bytes);
15778
+ let hex = "";
15779
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
15780
+ return `kya-${hex}`;
15781
+ }
15782
+ function deriveDelegationPickupUri(consentUri, sid) {
15783
+ const consent = parseHttpsUrl("consentUri", consentUri);
15784
+ assertQuotedValue("sid", sid, "invalid-sid");
15785
+ return `${consent.origin}/api/delegation/pickup/${sid}`;
15786
+ }
15787
+ function buildDelegationChallengeHeader(input) {
15788
+ const normalized = validateInput(input);
15789
+ const params = [
15790
+ ["realm", normalized.realm],
15791
+ ["sid", normalized.sid],
15792
+ ["consent_uri", normalized.consentUri],
15793
+ ["pickup_uri", normalized.pickupUri]
15794
+ ];
15795
+ if (normalized.requiredScopes.length > 0) {
15796
+ params.push(["scope", normalized.requiredScopes.join(" ")]);
14174
15797
  }
14175
- if (typeof obj.ts !== "number" || !Number.isFinite(obj.ts)) {
14176
- throw new Error(`missing or non-finite-number required field "ts" (got ${typeof obj.ts})`);
15798
+ if (normalized.minAssurance) {
15799
+ params.push(["min_assurance", normalized.minAssurance]);
14177
15800
  }
14178
- return obj;
14179
- }
14180
- var ED25519_MULTICODEC_PREFIX = new Uint8Array([237, 1]);
14181
- async function parseSigningKey(seed) {
14182
- if (seed.length !== 32) {
14183
- throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);
15801
+ if (input.pollIntervalS !== void 0) {
15802
+ params.push(["interval", String(normalized.pollIntervalS)]);
14184
15803
  }
14185
- const publicKey = await getPublicKeyAsync(seed);
14186
- const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);
14187
- multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);
14188
- multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);
14189
- const multibase = base58btc.encode(multibaseBytes);
14190
- const did = `did:key:${multibase}`;
14191
- return {
14192
- // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1
14193
- // tests assert that mutating the input seed after this call does NOT
14194
- // mutate the held key material.
14195
- signingKey: Uint8Array.from(seed),
14196
- publicKey,
14197
- did,
14198
- // mcp-i-core PR #16: the verification-method id is the multibase value
14199
- // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's
14200
- // stage2_did_key_fragment_resolution.
14201
- kid: `${did}#${multibase}`
14202
- };
15804
+ params.push(["kind", normalized.kind]);
15805
+ return `Delegation ${params.map(([name, value]) => `${name}="${value}"`).join(", ")}`;
14203
15806
  }
14204
- function base64UrlEncode(bytes) {
14205
- return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
15807
+ function buildDelegationBearerHeader(realm) {
15808
+ assertRealm(realm);
15809
+ return `Bearer resource_metadata="https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}"`;
14206
15810
  }
14207
- async function signMcpiEnvelope(payload, key) {
14208
- const header = { alg: "EdDSA", kid: key.kid };
14209
- const headerJson = JSON.stringify(header);
14210
- const headerB64 = base64UrlEncode(new TextEncoder().encode(headerJson));
14211
- const payloadB64 = base64UrlEncode(canonicalSigningPayload(payload));
14212
- const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
14213
- const signature = await signAsync(signingInput, key.signingKey);
14214
- const signatureB64 = base64UrlEncode(signature);
14215
- return `${headerB64}.${payloadB64}.${signatureB64}`;
15811
+ function buildDelegationInstructions(consentUri, pickupUri, pollIntervalS) {
15812
+ 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>'.`;
14216
15813
  }
14217
-
14218
- // src/canonical-signer/parse.ts
14219
- var JwsParseError = class extends Error {
14220
- constructor(code, message) {
14221
- super(message);
14222
- this.code = code;
14223
- this.name = "JwsParseError";
14224
- }
14225
- };
14226
- function validateJwsHeader(value) {
14227
- if (value === null || typeof value !== "object") {
14228
- throw new Error(`expected JSON object, got ${value === null ? "null" : typeof value}`);
15814
+ function buildDelegationChallengeBody(input) {
15815
+ const normalized = validateInput(input);
15816
+ const common = {
15817
+ sid: normalized.sid,
15818
+ consent_uri: normalized.consentUri,
15819
+ pickup_uri: normalized.pickupUri,
15820
+ ...normalized.requiredScopes.length > 0 ? { required_scopes: [...normalized.requiredScopes] } : {},
15821
+ ...normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {},
15822
+ poll_interval_s: normalized.pollIntervalS,
15823
+ challenge_proof: input.challengeProof
15824
+ };
15825
+ if (normalized.kind === "approval_quorum") {
15826
+ return {
15827
+ error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
15828
+ kyaos: {
15829
+ sid: common.sid,
15830
+ kind: "approval_quorum",
15831
+ quorum: normalized.quorum,
15832
+ action_nonce: normalized.actionNonce,
15833
+ consent_uri: common.consent_uri,
15834
+ pickup_uri: common.pickup_uri,
15835
+ ...common.required_scopes ? { required_scopes: common.required_scopes } : {},
15836
+ ...common.min_assurance ? { min_assurance: common.min_assurance } : {},
15837
+ poll_interval_s: common.poll_interval_s,
15838
+ challenge_proof: common.challenge_proof
15839
+ },
15840
+ instructions: buildApprovalQuorumInstructions(normalized)
15841
+ };
14229
15842
  }
14230
- const obj = value;
14231
- if (typeof obj.alg !== "string" || obj.alg.length === 0) {
14232
- throw new Error(`missing or non-string required field "alg" (got ${typeof obj.alg})`);
15843
+ return {
15844
+ error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
15845
+ kyaos: {
15846
+ ...common,
15847
+ action: {
15848
+ type: "delegation",
15849
+ consent_uri: normalized.consentUri,
15850
+ pickup_uri: normalized.pickupUri,
15851
+ poll_interval_s: normalized.pollIntervalS,
15852
+ pin: { header: "X-KYA-Pickup-Token" },
15853
+ retry: { header: "Authorization", scheme: "Bearer", value_from: "delegation" }
15854
+ }
15855
+ },
15856
+ instructions: buildDelegationInstructions(
15857
+ normalized.consentUri,
15858
+ normalized.pickupUri,
15859
+ normalized.pollIntervalS
15860
+ )
15861
+ };
15862
+ }
15863
+ function buildDelegationChallengeEnvelope(input, mode = "spec-401") {
15864
+ const normalized = validateInput(input);
15865
+ if (normalized.kind === "approval_quorum" && mode === "fetcher-200") {
15866
+ throw new ChallengeWireError(
15867
+ "unsupported-envelope",
15868
+ "fetcher-200 is not fixture-defined for approval_quorum"
15869
+ );
14233
15870
  }
14234
- if (typeof obj.kid !== "string" || obj.kid.length === 0) {
14235
- throw new Error(`missing or non-string required field "kid" (got ${typeof obj.kid})`);
15871
+ const body = buildDelegationChallengeBody(input);
15872
+ if (normalized.kind === "approval_quorum") {
15873
+ return {
15874
+ status: 401,
15875
+ headers: [
15876
+ ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
15877
+ ["Retry-After", String(normalized.pollIntervalS)],
15878
+ ["Content-Type", "application/json"],
15879
+ ["Cache-Control", "no-store"]
15880
+ ],
15881
+ body
15882
+ };
14236
15883
  }
14237
- if (obj.typ !== void 0 && typeof obj.typ !== "string") {
14238
- throw new Error(`optional field "typ" must be a string when present (got ${typeof obj.typ})`);
15884
+ const hintHeaders = [
15885
+ ["Content-Type", "application/json"],
15886
+ ["Cache-Control", "no-store"],
15887
+ ["KYA-Auth-Required", "true"],
15888
+ ["KYA-Auth-Url", normalized.consentUri],
15889
+ ["Link", `<${normalized.consentUri}>; rel="kya-authorize"`],
15890
+ ["KYA-Action", "challenge"]
15891
+ ];
15892
+ if (mode === "fetcher-200") {
15893
+ return { status: 200, headers: hintHeaders, body };
14239
15894
  }
14240
- return obj;
15895
+ return {
15896
+ status: 401,
15897
+ headers: [
15898
+ ["WWW-Authenticate", buildDelegationChallengeHeader(input)],
15899
+ ["WWW-Authenticate", `Bearer resource_metadata="${normalized.resourceMetadataUri}"`],
15900
+ ["Retry-After", String(normalized.pollIntervalS)],
15901
+ ...hintHeaders
15902
+ ],
15903
+ body
15904
+ };
14241
15905
  }
14242
- function parseJwsCompact(jws) {
14243
- const parts = jws.split(".");
14244
- if (parts.length !== 3) {
14245
- throw new JwsParseError(
14246
- "WrongSegmentCount",
14247
- `Expected 3 dot-separated segments per RFC 7515 \xA7 3.1; got ${parts.length}`
15906
+ var buildChallengeWire = buildDelegationChallengeEnvelope;
15907
+ function validateInput(input) {
15908
+ assertRealm(input.realm);
15909
+ assertQuotedValue("sid", input.sid, "invalid-sid");
15910
+ if (!SID.test(input.sid)) {
15911
+ throw new ChallengeWireError(
15912
+ "invalid-sid",
15913
+ "sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy"
14248
15914
  );
14249
15915
  }
14250
- const [headerB64, payloadB64, signatureB64] = parts;
14251
- let headerJson;
14252
- try {
14253
- headerJson = JSON.parse(base64UrlDecodeToString(headerB64));
14254
- } catch (cause) {
14255
- throw new JwsParseError("InvalidJson", `JWS header is not valid JSON: ${String(cause)}`);
15916
+ const consent = parseHttpsUrl("consentUri", input.consentUri);
15917
+ const pickup = parseHttpsUrl("pickupUri", input.pickupUri);
15918
+ const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;
15919
+ if (pickup.href !== expectedPickup) {
15920
+ throw new ChallengeWireError(
15921
+ "invalid-uri",
15922
+ "pickupUri must use the registered consent origin and sid"
15923
+ );
14256
15924
  }
14257
- let validatedHeader;
14258
- try {
14259
- validatedHeader = validateJwsHeader(headerJson);
14260
- } catch (cause) {
14261
- throw new JwsParseError(
14262
- "InvalidHeaderShape",
14263
- `JWS header does not match expected shape: ${cause.message}`
15925
+ const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;
15926
+ if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) {
15927
+ throw new ChallengeWireError(
15928
+ "invalid-interval",
15929
+ "pollIntervalS must be an integer from 1 through 999"
14264
15930
  );
14265
15931
  }
14266
- if (validatedHeader.alg !== "EdDSA") {
14267
- throw new JwsParseError(
14268
- "UnsupportedAlgorithm",
14269
- `Unsupported JWS alg "${validatedHeader.alg}"; Phase 1 only supports EdDSA`
15932
+ if (input.challengeProof === void 0 || input.challengeProof === null) {
15933
+ throw new ChallengeWireError("invalid-proof", "challengeProof is required");
15934
+ }
15935
+ const requiredScopes = input.requiredScopes ?? [];
15936
+ for (const scope of requiredScopes) {
15937
+ if (!SCOPE_TOKEN.test(scope)) {
15938
+ throw new ChallengeWireError("invalid-scope", `invalid required scope: ${scope}`);
15939
+ }
15940
+ }
15941
+ if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) {
15942
+ throw new ChallengeWireError(
15943
+ "invalid-assurance",
15944
+ `invalid minAssurance: ${input.minAssurance}`
14270
15945
  );
14271
15946
  }
14272
- const header = {
14273
- alg: "EdDSA",
14274
- kid: validatedHeader.kid,
14275
- ...validatedHeader.typ !== void 0 ? { typ: validatedHeader.typ } : {}
15947
+ const kind = input.kind ?? "delegation";
15948
+ if (kind !== "delegation" && kind !== "approval_quorum") {
15949
+ throw new ChallengeWireError("invalid-kind", `unsupported challenge kind: ${String(kind)}`);
15950
+ }
15951
+ let resourceMetadataUri;
15952
+ let quorum;
15953
+ let actionNonce;
15954
+ if (kind === "delegation") {
15955
+ resourceMetadataUri = parseHttpsUrl(
15956
+ "resourceMetadataUri",
15957
+ input.resourceMetadataUri
15958
+ ).href;
15959
+ const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;
15960
+ if (resourceMetadataUri !== expectedMetadata) {
15961
+ throw new ChallengeWireError(
15962
+ "invalid-uri",
15963
+ "resourceMetadataUri must be the protected resource RFC 9728 metadata URL"
15964
+ );
15965
+ }
15966
+ } else {
15967
+ const approval = input;
15968
+ quorum = approval.quorum;
15969
+ actionNonce = approval.actionNonce;
15970
+ if (!Number.isInteger(quorum) || quorum < 1) {
15971
+ throw new ChallengeWireError("invalid-quorum", "quorum must be a positive integer");
15972
+ }
15973
+ assertQuotedValue("actionNonce", actionNonce, "invalid-action-nonce");
15974
+ }
15975
+ return {
15976
+ realm: input.realm,
15977
+ sid: input.sid,
15978
+ consentUri: consent.href,
15979
+ pickupUri: pickup.href,
15980
+ resourceMetadataUri,
15981
+ requiredScopes,
15982
+ pollIntervalS,
15983
+ minAssurance: input.minAssurance,
15984
+ kind,
15985
+ quorum,
15986
+ actionNonce
14276
15987
  };
14277
- let payloadJson;
14278
- try {
14279
- payloadJson = JSON.parse(base64UrlDecodeToString(payloadB64));
14280
- } catch (cause) {
14281
- throw new JwsParseError("InvalidJson", `JWS payload is not valid JSON: ${String(cause)}`);
15988
+ }
15989
+ function buildApprovalQuorumInstructions(input) {
15990
+ 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.`;
15991
+ }
15992
+ function assertRealm(realm) {
15993
+ assertQuotedValue("realm", realm, "invalid-realm");
15994
+ if (realm.includes("/") || realm.includes("@") || realm.includes("?") || realm.includes("#")) {
15995
+ throw new ChallengeWireError("invalid-realm", "realm must be a host with an optional port");
14282
15996
  }
14283
- let payload;
14284
15997
  try {
14285
- payload = validateMcpIPayload(payloadJson);
14286
- } catch (cause) {
14287
- throw new JwsParseError(
14288
- "InvalidPayloadShape",
14289
- `JWS payload does not match McpIPayload shape: ${cause.message}`
15998
+ const parsed = new URL(`https://${realm}`);
15999
+ if (parsed.host !== realm) throw new Error("invalid authority");
16000
+ } catch {
16001
+ throw new ChallengeWireError(
16002
+ "invalid-realm",
16003
+ "realm must be a valid host with an optional port"
14290
16004
  );
14291
16005
  }
14292
- if (!BASE64URL_ALPHABET.test(signatureB64)) {
14293
- throw new JwsParseError(
14294
- "InvalidBase64",
14295
- `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 \xA7 5)`
16006
+ }
16007
+ function assertQuotedValue(name, value, code) {
16008
+ if (typeof value !== "string" || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) {
16009
+ throw new ChallengeWireError(
16010
+ code,
16011
+ `${name} contains characters unsafe for an HTTP quoted-string`
14296
16012
  );
14297
16013
  }
14298
- const signatureBytes = base64UrlDecodeToBytes(signatureB64);
14299
- if (signatureBytes.length !== 64) {
14300
- throw new JwsParseError(
14301
- "InvalidSignatureLength",
14302
- `Ed25519 signatures are 64 bytes (RFC 8032 \xA7 5.1.6); got ${signatureBytes.length}`
16014
+ }
16015
+ function parseHttpsUrl(name, value) {
16016
+ assertQuotedValue(name, value, "invalid-uri");
16017
+ let parsed;
16018
+ try {
16019
+ parsed = new URL(value);
16020
+ } catch {
16021
+ throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL`);
16022
+ }
16023
+ if (parsed.protocol !== "https:" || parsed.username || parsed.password) {
16024
+ throw new ChallengeWireError(
16025
+ "invalid-uri",
16026
+ `${name} must be an absolute HTTPS URL without credentials`
14303
16027
  );
14304
16028
  }
14305
- const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);
14306
- return { header, payload, signatureBytes, signingInput };
14307
- }
14308
- var BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;
14309
- function base64UrlDecodeToBytes(s) {
14310
- const padded = s.replace(/-/g, "+").replace(/_/g, "/");
14311
- const padLen = padded.length % 4 === 0 ? 0 : 4 - padded.length % 4;
14312
- return new Uint8Array(Buffer.from(padded + "=".repeat(padLen), "base64"));
16029
+ return parsed;
14313
16030
  }
14314
- function base64UrlDecodeToString(s) {
14315
- return Buffer.from(base64UrlDecodeToBytes(s)).toString("utf-8");
16031
+
16032
+ // src/host-adapter/challenge-context.ts
16033
+ var DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3e3;
16034
+ async function resolveChallengeContext(resolver, context, options = {}) {
16035
+ if (!resolver) return void 0;
16036
+ const timeoutMs = options.timeoutMs ?? DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;
16037
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1) {
16038
+ throw new TypeError("challenge context timeout must be a positive integer");
16039
+ }
16040
+ let timeoutId;
16041
+ try {
16042
+ const value = await Promise.race([
16043
+ Promise.resolve(resolver(context)),
16044
+ new Promise((_resolve, reject) => {
16045
+ timeoutId = setTimeout(
16046
+ () => reject(new ChallengeContextTimeoutError(timeoutMs)),
16047
+ timeoutMs
16048
+ );
16049
+ })
16050
+ ]);
16051
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
16052
+ if (!value) return void 0;
16053
+ try {
16054
+ buildChallengeWire(value, "spec-401");
16055
+ return value;
16056
+ } catch (error) {
16057
+ options.onFailure?.({
16058
+ reason: "invalid-context",
16059
+ message: error.message
16060
+ });
16061
+ return void 0;
16062
+ }
16063
+ } catch (error) {
16064
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
16065
+ options.onFailure?.({
16066
+ reason: error instanceof ChallengeContextTimeoutError ? "timeout" : "resolver-error",
16067
+ message: error instanceof ChallengeContextTimeoutError ? error.message : "challenge context resolver failed"
16068
+ });
16069
+ return void 0;
16070
+ }
14316
16071
  }
16072
+ var ChallengeContextTimeoutError = class extends Error {
16073
+ constructor(timeoutMs) {
16074
+ super(`challenge context resolution exceeded ${timeoutMs}ms`);
16075
+ this.name = "ChallengeContextTimeoutError";
16076
+ }
16077
+ };
16078
+
16079
+ // src/wire/vault.ts
16080
+ var vaultResolveMetaSchema = external_exports.object({
16081
+ orgSlug: external_exports.string().optional(),
16082
+ upstreamSlug: external_exports.string().optional()
16083
+ }).strict();
16084
+ var vaultResolveDataSchema = external_exports.object({
16085
+ secrets: external_exports.record(external_exports.string(), external_exports.string()),
16086
+ _meta: vaultResolveMetaSchema.optional()
16087
+ }).strict();
16088
+ var vaultResolveSuccessSchema = external_exports.object({
16089
+ success: external_exports.literal(true),
16090
+ data: vaultResolveDataSchema
16091
+ }).strict();
16092
+ var vaultResolveErrorSchema = external_exports.object({
16093
+ success: external_exports.literal(false),
16094
+ error: external_exports.object({
16095
+ code: external_exports.string(),
16096
+ message: external_exports.string(),
16097
+ data: external_exports.object({
16098
+ orgSlug: external_exports.string().optional(),
16099
+ upstreamSlug: external_exports.string().optional(),
16100
+ retryAfter: external_exports.number().optional()
16101
+ }).passthrough().optional()
16102
+ }).strict()
16103
+ }).strict();
16104
+ var vaultResolveResponseSchema = external_exports.discriminatedUnion("success", [
16105
+ vaultResolveSuccessSchema,
16106
+ vaultResolveErrorSchema
16107
+ ]);
14317
16108
 
14318
16109
  // src/mcpi/org-did.ts
14319
16110
  var MCPI_ORG_DID_HOST = "kya.vouched.id";
@@ -14360,24 +16151,51 @@ function requestCarriesDelegationProof(headers) {
14360
16151
  }
14361
16152
  return DELEGATION_PROOF_HEADERS.some((name) => isPresent(lowerKeyed.get(name)));
14362
16153
  }
14363
-
14364
- // src/mcpi/principal.ts
14365
16154
  var ANONYMOUS_PRINCIPAL_DID = "did:web:kya.vouched.id:principals:anonymous";
14366
16155
  var MCP_CLIENT_DID_HOST = "knowthat.ai";
14367
16156
  var CLIENT_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;
16157
+ var CIMD_FALLBACK_PREFIX = "cimd-";
16158
+ var CIMD_CLIENT_SLUGS = {
16159
+ "https://claude.ai/oauth/claude-code-client-metadata": "claude-code",
16160
+ "https://vscode.dev/oauth/client-metadata.json": "vscode"
16161
+ };
16162
+ var RESERVED_CIMD_SLUGS = new Set(Object.values(CIMD_CLIENT_SLUGS));
14368
16163
  function deriveMcpClientDid(clientId) {
14369
- if (!CLIENT_ID_PATTERN.test(clientId)) {
16164
+ const cimdUrl = tryParseUrl(clientId);
16165
+ const slug = cimdUrl ? slugForCimdUrl(cimdUrl, clientId) : clientId;
16166
+ if (!CLIENT_ID_PATTERN.test(slug)) {
14370
16167
  throw new Error(`Invalid client id for did:web derivation: ${JSON.stringify(clientId)}`);
14371
16168
  }
14372
- return `did:web:${MCP_CLIENT_DID_HOST}:clients:${clientId}`;
16169
+ if (!cimdUrl && RESERVED_CIMD_SLUGS.has(slug)) {
16170
+ throw new Error(`Reserved CIMD client slug, cannot use as an opaque client id: ${slug}`);
16171
+ }
16172
+ return `did:web:${MCP_CLIENT_DID_HOST}:clients:${slug}`;
16173
+ }
16174
+ function tryParseUrl(value) {
16175
+ try {
16176
+ return new URL(value);
16177
+ } catch {
16178
+ return null;
16179
+ }
16180
+ }
16181
+ function slugForCimdUrl(url, originalClientId) {
16182
+ if (url.protocol !== "https:" || url.pathname === "" || url.pathname === "/") {
16183
+ throw new Error(
16184
+ `Invalid client id for did:web derivation: ${JSON.stringify(originalClientId)}`
16185
+ );
16186
+ }
16187
+ const known = CIMD_CLIENT_SLUGS[originalClientId];
16188
+ if (known) return known;
16189
+ const digest = bytesToHex(sha256(new TextEncoder().encode(originalClientId)));
16190
+ return `${CIMD_FALLBACK_PREFIX}${digest.slice(0, 32)}`;
14373
16191
  }
14374
16192
 
14375
16193
  // src/mcpi/reported-identity.ts
14376
- var DidStringSchema = external_exports.string().trim().min(1).regex(/^did:/, "must be a DID (did:web / did:key)");
16194
+ var DidStringSchema2 = external_exports.string().trim().min(1).regex(/^did:/, "must be a DID (did:web / did:key)");
14377
16195
  var NonEmptyTrimmed = external_exports.string().trim().min(1);
14378
16196
  var ReportedAgentSchema = external_exports.object({
14379
16197
  /** The agent's own DID, when it has one (enterprise A2A / provisioned). */
14380
- did: DidStringSchema.optional(),
16198
+ did: DidStringSchema2.optional(),
14381
16199
  /**
14382
16200
  * OAuth `client_id` of an authenticated MCP client. Checkpoint derives the
14383
16201
  * canonical `did:web` from this (DR-9 `deriveMcpClientDid`); the reporter
@@ -14395,7 +16213,7 @@ var ReportedAgentSchema = external_exports.object({
14395
16213
  }).describe("Asserted identity of the acting agent");
14396
16214
  var ReportedPrincipalSchema = external_exports.object({
14397
16215
  /** The principal's DID (the delegation issuer, typically). */
14398
- did: DidStringSchema.optional(),
16216
+ did: DidStringSchema2.optional(),
14399
16217
  /** Issuer-local subject identifier, when the principal has no DID. */
14400
16218
  sub: NonEmptyTrimmed.optional(),
14401
16219
  /** Optional display email. Never the identity key — `did`/`sub` are. */
@@ -14403,13 +16221,24 @@ var ReportedPrincipalSchema = external_exports.object({
14403
16221
  }).describe("Asserted identity of the principal the agent acted for");
14404
16222
  var DelegationResultSchema = external_exports.enum(["verified", "failed", "not_presented"]);
14405
16223
  var DelegationVerifiedBySchema = external_exports.enum(["reporter", "gateway", "checkpoint"]);
16224
+ var REGISTERED_SID_MAX_LENGTH = 100;
16225
+ var SID_ATTRIBUTABLE_RESULT = "verified";
14406
16226
  var ReportedDelegationSchema = external_exports.object({
14407
16227
  /** Delegation credential id — the join key into `delegations`. */
14408
16228
  jti: NonEmptyTrimmed.optional(),
16229
+ /**
16230
+ * The registered session anchor: the draft-kya-http-02 `sid` claim of the
16231
+ * presented credential (the top-level VC-JWT `sid` minted in
16232
+ * `mint-vc-jwt.ts`), distinct from any gateway or MCP session id. Optional,
16233
+ * and attributed to a session timeline only when `result` is `verified`
16234
+ * ({@link SID_ATTRIBUTABLE_RESULT}); ingest nulls it for any other result.
16235
+ * No refine here: the identity block must never fail a request.
16236
+ */
16237
+ sid: NonEmptyTrimmed.max(REGISTERED_SID_MAX_LENGTH).optional(),
14409
16238
  /** Issuer DID (usually the principal). */
14410
- iss: DidStringSchema.optional(),
16239
+ iss: DidStringSchema2.optional(),
14411
16240
  /** Audience DID (the intended verifier / resource). */
14412
- aud: DidStringSchema.optional(),
16241
+ aud: DidStringSchema2.optional(),
14413
16242
  /** Granted capabilities, e.g. `['vault:read']`. */
14414
16243
  capabilities: external_exports.array(NonEmptyTrimmed).optional(),
14415
16244
  /** Expiry, unix seconds. */
@@ -14423,7 +16252,7 @@ var ReportedIdentitySchema = external_exports.object({
14423
16252
  agent: ReportedAgentSchema.optional(),
14424
16253
  principal: ReportedPrincipalSchema.optional(),
14425
16254
  delegation: ReportedDelegationSchema.optional()
14426
- }).describe("MCP-I reported identity (verifier \u2192 observability plane)");
16255
+ }).describe("KYA-OS reported identity (verifier \u2192 observability plane)");
14427
16256
 
14428
16257
  // src/mcpi/did-key.ts
14429
16258
  var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
@@ -14512,28 +16341,105 @@ function encodeDidKeyEd25519(publicKey) {
14512
16341
  return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;
14513
16342
  }
14514
16343
 
14515
- // src/mcpi/kya-http-error-codes.ts
14516
- var KYA_HTTP_ERROR = {
14517
- // ── 401 (identity / signature) ──────────────────────────────────────────
14518
- MISSING_SIGNATURE: "kyaos/missing-signature",
14519
- INVALID_SIGNATURE: "kyaos/invalid-signature",
14520
- EXPIRED: "kyaos/expired",
14521
- REPLAY: "kyaos/replay",
14522
- DID_UNRESOLVABLE: "kyaos/did-unresolvable",
14523
- AUTHORIZATION_REQUIRED: "kyaos/authorization-required",
14524
- // ── 403 (delegation / profile) ──────────────────────────────────────────
14525
- PROFILE_VIOLATION: "kyaos/profile-violation",
14526
- DELEGATION_REVOKED: "kyaos/delegation-revoked",
14527
- SCOPE_INSUFFICIENT: "kyaos/scope-insufficient",
14528
- CHAIN_BROKEN: "kyaos/chain-broken",
14529
- HOLDER_MISMATCH: "kyaos/holder-mismatch",
14530
- AUDIENCE_MISMATCH: "kyaos/audience-mismatch",
14531
- SESSION_MISMATCH: "kyaos/session-mismatch",
14532
- PICKUP_PINNED: "kyaos/pickup-pinned",
14533
- // ── pickup flow (404 / 410) ─────────────────────────────────────────────
14534
- INVALID_SESSION: "kyaos/invalid-session",
14535
- PICKUP_EXPIRED: "kyaos/pickup-expired"
16344
+ // src/mcpi/multibase-ed25519.ts
16345
+ var ED25519_PUB_MULTICODEC = [237, 1];
16346
+ var ED25519_PUBKEY_LENGTH2 = 32;
16347
+ var ED25519_MULTIKEY_LENGTH2 = ED25519_PUB_MULTICODEC.length + ED25519_PUBKEY_LENGTH2;
16348
+ var MAX_ED25519_KEY_BODY_LENGTH = 64;
16349
+ function base64AnyToBytes(body) {
16350
+ if (body.length === 0) return null;
16351
+ let normalized = body.replace(/-/g, "+").replace(/_/g, "/");
16352
+ const remainder = normalized.length % 4;
16353
+ if (remainder === 1) return null;
16354
+ if (remainder === 2) normalized += "==";
16355
+ else if (remainder === 3) normalized += "=";
16356
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return null;
16357
+ try {
16358
+ const bin = atob(normalized);
16359
+ const out = new Uint8Array(bin.length);
16360
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
16361
+ return out;
16362
+ } catch {
16363
+ return null;
16364
+ }
16365
+ }
16366
+ function toRawEd25519Key(decoded) {
16367
+ if (decoded.length === ED25519_PUBKEY_LENGTH2) return decoded;
16368
+ if (decoded.length === ED25519_MULTIKEY_LENGTH2 && decoded[0] === ED25519_PUB_MULTICODEC[0] && decoded[1] === ED25519_PUB_MULTICODEC[1]) {
16369
+ return decoded.slice(ED25519_PUB_MULTICODEC.length);
16370
+ }
16371
+ return null;
16372
+ }
16373
+ function decodeEd25519PublicKeyMultibaseTolerant(mb) {
16374
+ if (typeof mb !== "string" || mb.length < 2) return null;
16375
+ const prefix = mb[0];
16376
+ const body = mb.slice(1);
16377
+ if (body.length > MAX_ED25519_KEY_BODY_LENGTH) return null;
16378
+ let decoded;
16379
+ if (prefix === "z") {
16380
+ decoded = base58btcDecode(body);
16381
+ } else if (prefix === "m" || prefix === "u") {
16382
+ decoded = base64AnyToBytes(body);
16383
+ } else {
16384
+ return null;
16385
+ }
16386
+ if (!decoded) return null;
16387
+ return toRawEd25519Key(decoded);
16388
+ }
16389
+ function encodeEd25519PublicKeyMultibase(rawPubKey) {
16390
+ if (rawPubKey.length !== ED25519_PUBKEY_LENGTH2) {
16391
+ throw new Error(
16392
+ `Ed25519 public key must be ${ED25519_PUBKEY_LENGTH2} bytes, got ${rawPubKey.length}`
16393
+ );
16394
+ }
16395
+ const prefixed = new Uint8Array(ED25519_MULTIKEY_LENGTH2);
16396
+ prefixed[0] = ED25519_PUB_MULTICODEC[0];
16397
+ prefixed[1] = ED25519_PUB_MULTICODEC[1];
16398
+ prefixed.set(rawPubKey, ED25519_PUB_MULTICODEC.length);
16399
+ return "z" + base58btcEncode(prefixed);
16400
+ }
16401
+
16402
+ // src/mcpi/delegation-verdict.ts
16403
+ var REASON_KIND_MAP = {
16404
+ // --- gateway: apps/gateway/src/lib/mcpi-auth-resolver.ts ---
16405
+ missing_bearer_token: "claim",
16406
+ parse_error: "claim",
16407
+ did_resolve_failed: "resolve",
16408
+ signature_invalid: "signature",
16409
+ audience_mismatch: "claim",
16410
+ expired: "time",
16411
+ not_yet_valid: "time",
16412
+ revoked: "revocation",
16413
+ delegation_inactive: "revocation",
16414
+ missing_claim: "claim",
16415
+ claim_invalid: "claim",
16416
+ // --- gateway: apps/gateway/src/lib/dashboard-delegation-verifier.ts ---
16417
+ not_configured: "claim",
16418
+ header_missing: "claim",
16419
+ claim_mismatch: "claim",
16420
+ malformed: "claim",
16421
+ // --- engine-rust: rust/crates/kya-os-engine/src/types.rs BlockReason ---
16422
+ Revoked: "revocation",
16423
+ InvalidSignature: "signature",
16424
+ Unauthenticated: "claim",
16425
+ Expired: "time",
16426
+ OutOfScope: "scope"
14536
16427
  };
16428
+ function toCoarseReasonKind(rawReasonKind) {
16429
+ const coarse = REASON_KIND_MAP[rawReasonKind];
16430
+ if (!coarse) {
16431
+ throw new Error(
16432
+ `toCoarseReasonKind: unrecognized raw reason kind ${JSON.stringify(rawReasonKind)} \u2014 add it to REASON_KIND_MAP in delegation-verdict.ts with a deliberate coarse classification`
16433
+ );
16434
+ }
16435
+ return coarse;
16436
+ }
16437
+ function permitDelegationVerdict() {
16438
+ return { kind: "Permit", reason: null };
16439
+ }
16440
+ function blockDelegationVerdict(rawReasonKind) {
16441
+ return { kind: "Block", reason: { kind: toCoarseReasonKind(rawReasonKind) } };
16442
+ }
14537
16443
 
14538
16444
  // src/parsers/jafar.ts
14539
16445
  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)$/;
@@ -14577,18 +16483,18 @@ function parseJafarFeed(json) {
14577
16483
  } catch (err) {
14578
16484
  throw new JafarParseError("JAFAR feed is not valid JSON", err);
14579
16485
  }
14580
- const result = jafarFeedSchema.safeParse(raw);
14581
- if (!result.success) {
16486
+ const result2 = jafarFeedSchema.safeParse(raw);
16487
+ if (!result2.success) {
14582
16488
  throw new JafarParseError(
14583
- `JAFAR feed failed schema validation: ${result.error.message}`,
14584
- result.error
16489
+ `JAFAR feed failed schema validation: ${result2.error.message}`,
16490
+ result2.error
14585
16491
  );
14586
16492
  }
14587
- return result.data;
16493
+ return result2.data;
14588
16494
  }
14589
16495
 
14590
16496
  // src/index.ts
14591
16497
  var VERSION = "0.1.0";
14592
16498
  var PACKAGE_NAME = "@kya-os/checkpoint-shared";
14593
16499
 
14594
- export { ACCEPT_CHALLENGE_HEADER, AI_AGENT_HEADERS, ANONYMOUS_PRINCIPAL_DID, API_ERRORS, API_ERROR_CODES, API_REQUEST_LIMITS, AUTHORIZATION_MODES, AUTH_ERRORS, AUTH_ERROR_MESSAGES, AccountSchema, AddFingerprintToProfileRequestSchema, AddUpdateProviderRequestSchema, AdminQueryParamsSchema, AgentCategorySchema, AgentClassificationRequestSchema, AgentClassificationResultSchema, AgentClassificationSchema, AgentInfoSchema, AgentPatternSchema, AgentProfileSchema, AgentShieldConfigSchema, AgentSourceDistributionSchema, AgentStatisticsSchema, AgentTypeDefinitionSchema, AgentTypeSchema, AggregationTypeSchema, AllowListEntrySchema, AnalyticsAgentSourcesQuerySchema, AnalyticsAgentTypesQuerySchema, AnalyticsChartDataSchema, AnalyticsDataPointSchema, AnalyticsExportParamsSchema, AnalyticsExportQuerySchema, AnalyticsQuerySchema2 as AnalyticsQuerySchema, AnalyticsRealtimeQuerySchema, AnalyticsSessionsQuerySchema, AnalyticsSessionsResponseSchema, AnalyticsSummarySchema2 as AnalyticsSessionsSummarySchema, AnalyticsSummarySchema, AnalyticsTimeSeriesSchema, AnalyticsTimeWindowSchema, ApiKeyPermissionSchema, ApiKeyRateLimitsSchema, ApiKeySchema, ApiKeysBulkCreateItemSchema, ApiKeysBulkRequestSchema, ApiKeysBulkRevokeItemSchema, ApiKeysBulkUpdateItemSchema, ApiKeysQuerySchema, ApiResponseSchema, AssuranceTierSchema, AuthErrorType, AuthProviderTypeSchema, BLOCKED_PATH, BOT_USER_AGENT_PATTERNS, BROWSER_PATTERNS, BULK_ERROR_CODES, BaseAuthProviderSchema, BaseBulkRequestSchema, BatchDetectionRequestSchema, BatchDetectionResponseSchema, BatchEventRequestSchema, BatchEventResponseSchema, BatchEventSchema, BatchPixelEventRequestSchema, BeaconBatchSchema, BeaconCollectorDataSchema, BeaconConfigSchema, BeaconEventSchema, BeaconEventTypeSchema, BeaconWorkerMessageSchema, BeaconWorkerMessageTypeSchema, BehavioralAnalysisSchema, BehavioralDataSchema, BehavioralPatternSchema, BehavioralRulesSchema, BehavioralSignalsSchema, BehavioralThresholdSchema, BlockEventSchema, BlockReasonSchema, BotPatternSchema2 as BotPatternSchema, BotTypeSchema, BouncerConfigSchema, BouncerOutcomeSchema, BouncerProofSchema, BrowserInfoSchema, BulkDeletePreviewStatsSchema, BulkDeleteResponseSchema, BulkOperationOptionsSchema, BulkOperationParamsSchema, BulkOperationResultSchema, BulkOperationTypeSchema, BulkResponseSchema, BulkResultItemSchema, CACHE_LIMITS, CACHE_TTL, CLOUD_PROVIDER_RANGES, CONDITION_FIELDS, CONDITION_OPERATORS, CONFIDENCE_THRESHOLDS, CRISPBudgetSchema, CURRENT_POLICY_VERSION, CacheConfigSchema, CachedDetectionDataSchema, ChallengeParamsSchema, CircuitBreakerConfigSchema, CircuitBreakerStateSchema, ClickEventSchema, ClientDetectionSchema, CollectFingerprintRequestSchema, CollectFingerprintResponseSchema, CollectedDataSchema, CollectorTypeSchema, ConditionFieldSchema, ConditionOperatorSchema, ConditionValueSchema, ConfidenceBreakdownSchema, ConfidenceLevelSchema, ConfidenceThresholdSchema, ConfidenceUtils, ConfiguredProviderSchema, ConnectionTypeSchema, ConsentAgentMetadataSchema, ConsentBrandingSchema, ConsentCapabilityGroupSchema, ConsentCapabilitySchema, ConsentConfigMetadataSchema, ConsentConfigSchema, ConsentTermsSchema, ConsentUISchema, CreateApiKeySchema, CreateOrganizationInputSchema, CreateOrganizationSchema, CreatePixelSchema, CreateProfileRequestSchema, CreateProjectSchema, CredentialProviderSchema, CustomRuleSchema, DATABASE_LIMITS, DEFAULT_AGENTSHIELD_CONFIG, DEFAULT_AGENT_TYPES, DEFAULT_API_KEY_RATE_LIMITS, DEFAULT_AUTHORIZATION_HOST, DEFAULT_BEHAVIORAL_THRESHOLDS, DEFAULT_CACHE_CONFIG, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CORS_CONFIG, DEFAULT_DETECTION_OPTIONS, DEFAULT_ENV_VARS, DEFAULT_LOG_CONFIG, DEFAULT_PASSWORD_REQUIREMENTS, DEFAULT_PIXEL_CONFIG, DEFAULT_POLICY, DEFAULT_PROJECT_SETTINGS, DEFAULT_RESPONSE_HEADERS, DEFAULT_RETRY_CONFIG, DEFAULT_RULE_PRIORITY, DEFAULT_SESSION_CONFIG, DEFAULT_THRESHOLDS, DEFAULT_TIMEOUTS, DEFAULT_WEBHOOK_EVENTS, DELEGATION_PROOF_HEADERS, DEPLOY_STEPS, DETECTION_ERRORS, DETECTION_LIMITS, DashboardStatsRequestSchema, DatabaseDetectionMetadataSchema, DatabaseStatusSchema, DecisionSchema, DelegationPollingStatusSchema, DelegationResultSchema, DelegationSchema, DelegationStatusSchema, DelegationVerifiedBySchema, DeleteAccountSchema, DenyListEntrySchema, DeployProgressEventSchema, DeployStepIdSchema, DeployStepStateSchema, DeployStepStatusSchema, DeploymentMetadataSchema, DetectionClassSchema, DetectionDetailSchema, DetectionErrorDetailsSchema, DetectionEventSchema, DetectionInputSchema, DetectionLogSchema, DetectionMetadataSchema, DetectionModeSchema, DetectionOptionsSchema, DetectionReasoningSchema, DetectionRequestSchema, DetectionResponseSchema, DetectionResultSchema, DetectionRuleSchema, DetectionRulesSchema, DetectionSignalSchema, DetectionStatusSchema, DetectionTestResultSchema, DetectionViewTypeSchema, ENFORCEMENT_ACTIONS, ENFORCEMENT_MODES, ERROR_CATEGORIES, ERROR_CODES, ERROR_MESSAGES, ERROR_STATUS_CODES, EXPORT_LIMITS, EnforcementActionSchema, EnforcementModeSchema, EngineInfoSchema, EnhancedFingerprintResponseSchema, ErrorResponseSchema, EventConfigSchema, EventStorageRecordSchema, EventTrackingRequestSchema, EventTrackingResponseSchema, ExportAnalyticsSchema, ExpressMiddlewareOptionsSchema, FallbackOptionsSchema, FilterOperatorSchema, FingerprintAnalysisSchema, ClientDetectionSchema2 as FingerprintClientDetectionSchema, FingerprintDetectRequestSchema, FingerprintRecordSchema, FingerprintResponseSchema, FingerprintSearchQuerySchema, ForgeabilityRiskSchema, GrowthBatchRequestSchema, GrowthConfigurationResetSchema, GrowthConfigurationThresholdsSchema, GrowthConfigurationUpdateSchema, GrowthOpportunitiesQuerySchema, GrowthOpportunityUpdateSchema, HEADER_PATTERNS, HTTP_STATUS, HeaderRuleSchema, HeaderRulesSchema, HealthResponseSchema, HomeRailRollupsRequestSchema, INTERNAL_ERRORS, InstructPayloadSchema, IntegrationTypeSchema, InternalProcessingFlagsSchema, IpRangeCollectionSchema, IpRangeRuleSchema, JafarParseError, JwsParseError, KNOWN_AGENT_PATTERNS, KYA_HTTP_ERROR, KYA_OS_HANDSHAKE_METHODS, KYA_OS_WIRE_METHODS, KeyboardEventSchema, LoggingConfigSchema, MATCH_ACTIONS, MAX_BULK_BATCH_SIZE, MCPI_ORG_DID_HOST, MCP_CLIENT_DID_HOST, MOBILE_PATTERNS, MessagePrioritySchema, MiddlewareActionSchema, MiddlewareConfigSchema, MiddlewareSessionConfigSchema, MiddlewareSessionDataSchema, MigrationStatusSchema, MouseEventSchema, NETWORK_ERRORS, NetworkConfigSchema, NetworkInfoSchema, NetworkTimingSchema, NextMiddlewareOptionsSchema, OAuth2ProviderSchema, OAuthConnectionStatusSchema, OAuthModeSchema, OAuthProviderMetadataSchema, OAuthProviderTypeSchema, OAuthProvidersMapSchema, OAuthTokensResponseSchema, OS_PATTERNS, OfflineQueueEntrySchema, OrganizationErrorCode, OrganizationIdSchema, OrganizationRoleSchema, OrganizationSettingsSchema, OrganizationSsoModeSchema, OrganizationSsoProviderSchema, OrganizationSsoSettingsSchema, PACKAGE_NAME, PAGINATION_DEFAULTS, PERFORMANCE_THRESHOLDS, PERMISSION_ERRORS, PIXEL_ERRORS, PIXEL_EVENT_LIMITS, PLAN_FEATURE_LIMITS, PLAN_RATE_LIMITS, POLICY_MATCH_TYPES, PUBLIC_API_ERROR_CODES, PageContextSchema, PaginatedResponseSchema, PaginationInfoSchema, PaginationParamsSchema, PaginationResponseSchema, PatternUpdateRequestSchema, PerformanceRecalculationRequestSchema, PixelAnalyticsSchema, PixelConfigurationSchema, PixelEventSchema, PixelEventTypeSchema, PixelInitSchema, PixelInstallConfigSchema, PixelSchema, PixelSessionSchema, PixelStatsSchema, PixelTrackingRequestSchema, PixelTrackingResponseSchema, PixelUserIdentificationSchema, PixelVerificationStatusSchema, PixelsBulkCreateItemSchema, PixelsBulkDeleteItemSchema, PixelsBulkRegenerateItemSchema, PixelsBulkRequestSchema, PixelsBulkUpdateItemSchema, PixelsQuerySchema, PolicyConditionSchema, PolicyConfigSchema, PolicyEvaluationContextSchema, PolicyEvaluationResultSchema, PolicyFetcher, PolicyMatchTypeSchema, PolicyMetadataSchema, PolicyRuleSchema, ProjectIdSchema, ProjectSchema, ProjectSettingsSchema, ProjectsBulkCreateItemSchema, ProjectsBulkDeleteItemSchema, ProjectsBulkRequestSchema, ProjectsBulkUpdateItemSchema, ProjectsQuerySchema, ProtocolVersionSchema, ProviderDefinitionSchema2 as ProviderDefinitionSchema, ProvidersResponseSchema, PublicAnalyticsBotTypeSchema, PublicAnalyticsSchema, PublicAnalyticsSummarySchema, PublicAnalyticsTimeSeriesPointSchema, PublicApiHeadersSchema, PublicApiQueryParamsSchema, PublicApiResponseSchema, PublicDetectionSchema, PublicKeyConfigSchema, PaginationResponseSchema as PublicPaginationResponseSchema, PublicProjectSchema, PublishProfileRequestSchema, QueryFilterSchema, QuerySchema, RATE_LIMIT_ERRORS, RULE_CACHE, RULE_CATEGORIES, RULE_CDN, RULE_ERRORS, RULE_PATHS, RULE_VERSION, RealtimeEventSchema, RealtimeEventTypeSchema, ReasoningStepSchema, RecommendationGenerationSchema, RecommendationQuerySchema, RedirectTargetSchema, RedisSessionDataSchema, RedisStatsSchema, RefreshScopesRequestSchema, ReportedAgentSchema, ReportedDelegationSchema, ReportedIdentitySchema, ReportedPrincipalSchema, RequestContextSchema, ResourceUsageSchema, ResponseActionSchema, RetryStrategySchema, RiskAssessmentSchema, RuleLoadOptionsSchema, RuleLoader, RuleMatchResultSchema, RuleMetadataSchema, RuleParser, RuleUpdateEventSchema, RuleValidationResultSchema, RuleValidator, SECURITY_LIMITS, SESSION_ERRORS, SESSION_LIMITS, SLUG_REGEX, SUSPICIOUS_HEADERS, SUSPICIOUS_PATTERNS, ScopeSchema, ScrollEventSchema, SdkSessionDataSchema, SessionConfigSchema, SessionCreateRequestSchema, SessionDataSchema, SessionEventSchema, SessionEventTypeSchema, SessionQueryOptionsSchema, SessionSchema, SessionStateSchema, SessionStorageTypeSchema, SessionTokenPayloadSchema, SessionUpdateRequestSchema, AgentTypeDistributionSchema as SharedAgentTypeDistributionSchema, ConfidenceDistributionSchema as SharedConfidenceDistributionSchema, ShopifyProjectProvisionRequestSchema, ShopifyProjectProvisionResultSchema, ShopifyProjectSettingsUpdateSchema, ShopifyStatsResponseSchema, ShopifyThreatSchema, SignatureAlgorithmSchema, SignatureRuleSchema, SignatureVerificationRequestSchema, SignatureVerificationResponseSchema, SingleItemResponseSchema, StatsResponseSchema, StatsUpdateEventSchema, StrictEnforcementActionSchema, SuggestedActionSchema, SystemStatsSchema, TIME_WINDOWS, TLSFingerprintSchema, TRADITIONAL_BOT_PATTERNS, TRUSTED_BOTS, TestDetectionRequestSchema, ThresholdConfigSchema, ToolConsentOverridesSchema, TouchEventSchema, TraceStepSchema, TransportConfigSchema, TransportMetricsSchema, TransportOptionsSchema, TransportResponseSchema, TransportStateSchema, TransportStatusSchema, UPDATE_FREQUENCIES, USER_AGENT_PATTERNS, UpdateApiKeySchema, UpdateBouncerConfigSchema, UpdateOrganizationInputSchema, UpdateOrganizationSchema, UpdatePixelSchema, UpdateProfileRequestSchema, UpdateProjectSchema, UpdateSettingsSchema, UserAgentRuleSchema, UserPlanSchema, UserSchema, VALIDATION_ERRORS, VALIDATION_MODES, VALIDATION_PATTERNS, VERDICT_COOKIE_NAME, VERSION, VerificationCacheEntrySchema, VerificationProviderSchema, VerificationRequestSchema, VerificationResponseSchema, VerificationTokenSchema, WEBHOOK_LIMITS, WasmAgentNameSchema, AgentTypeSchema as WasmAgentTypeSchema, WasmConfigSchema, WasmDetectionResultSchema, WasmRequestMetadataSchema, WasmRiskLevel, WasmVerificationMethod, WorkerActionSchema, WorkerCapabilitiesSchema, WorkerConfigSchema, WorkerErrorSchema, WorkerErrorTypeSchema, WorkerHealthStatusSchema, WorkerMessageSchema, WorkerMessageTypeSchema, WorkerMetricsSchema, WorkerPoolConfigSchema, WorkerStateSchema, WorkerTaskSchema, acceptsHtml, approvalQuorumForRequest, assignmentChangeRequestSchema, auditLogQuerySchema, batchAssignmentRequestSchema, buildInitialStepsState, calculateDeployProgress, canonicalSigningPayload, cedarQuotedValueRegExp, changePasswordSchema, classifyResponseShape, createError, createErrorResponse, createEvaluationContext, createPaginatedResponse, createPaginatedResponseSchema, createPolicyFetcher, createPublicErrorResponse, createPublicPaginatedResponse, createPublicSuccessResponse, createSuccessResponse, createValidationErrorResponse, decisionPolicyId, decodeDidKeyEd25519, defaultConfig, deriveMcpClientDid, deriveMcpiOrgDid, deriveMcpiOrgKid, deriveMcpiUserDid, deriveVerdict, detectionClassToEnum, discoveredToolSchema, encodeDidKeyEd25519, encodeVerdictCookie, enumToDetectionClass, escapeCedarString, evaluatePolicy, extractMatch, fetchPolicy, findMatchingPattern, forgotPasswordSchema, formatConfidence, fromProviderRegistryFormat, fromProviderRegistryFormatSafe, gatewayConfigInputSchema, gatewayConfigSchema, gatewayConnectedAgentSchema, gatewayConnectionsSummarySchema, gatewayInternalDiscoverErrorSchema, gatewayInternalDiscoverSuccessSchema, gatewayInternalToolsListSchema, gatewayToolCallSchema, generateTestId, getAgentDisplayName, getBotType, getCategoryBadgeVariant, getCategoryColor, getConfidenceLevel, getDefaultPolicyFetcher, getEnvVar, getRateLimitWindow, getRemainingQuota, getStepInfo, getStepOrder, getVerificationMethodDescription, getVerificationReliability, getVerificationRiskLevel, initializePolicyFetcher, isBlockingAction, isHighConfidenceVerification, isKnownAgentType, isKnownAiCrawler, isKyaOsHandshakeMethod, isKyaOsWireMethod, isLegacyDetectionClass, isLegitimateCategory, isLimitExceeded, isPassThroughAction, isPrivateOrReservedHost, isSupportedAuthType, isTraditionalBot, isValidAuthorizationHost, isValidFingerprintResponse, isValidMcpiOrgSlug, isValidWasmDetectionResult, isValidWasmRequestMetadata, loadRulesAsync, mapLegacyAuthType, mapToLegacyAuthType, matchPath, mergeWithDefaults, migrateLegacyDetectionClass, normalizeAgentName, normalizeConfidence, normalizeDetectionClass, normalizeDetectionClassEnum, normalizeOrganizationName, oauthClientSchema, parseAgentName, parseEvaluationContext, parseJafarFeed, parseJwsCompact, parsePolicyConfig, parseRules, parseSigningKey, partial, passwordSchema, projectResetRequestSchema, requestCarriesDelegationProof, requiredScopesForRequest, resetPasswordSchema, resetPolicyFetcher, resolveAuthorizationHost, resolveTrustedDelegationRoots, safeParsePolicyConfig, safeUrl, selectBodyReadable200, serveBodyReadable200, signInSchema, signMcpiEnvelope, signUpSchema, strict, supportsClientSide, supportsHeaders, supportsServerEnhanced, testPattern, testPatterns, toBareHost, toPercent, toProviderRegistryFormat, toWasmRequestMetadata, unescapeCedarString, updateStepsState, upstreamDiscoveryErrorSchema, upstreamServerInputSchema, upstreamServerSchema, validate, validateClientDetection, validateFingerprintRequest, validateMcpIPayload, validateOrThrow, validateOrganizationName, validateRules, validateRulesLoose, validateStepUpQuorum, vaultResolveDataSchema, vaultResolveErrorSchema, vaultResolveMetaSchema, vaultResolveResponseSchema, vaultResolveSuccessSchema, verifyEmailSchema, wasmToDetectionResult };
16500
+ export { ACCEPT_CHALLENGE_HEADER, ADMIN_DELTA_BASES, ADMIN_OVERVIEW_CACHE_STATUSES, ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT, ADMIN_OVERVIEW_LIST_LIMIT_MAX, ADMIN_OVERVIEW_SECTIONS, ADMIN_OVERVIEW_WINDOWS, AGENT_CATEGORY_META, AI_AGENT_HEADERS, ANONYMOUS_PRINCIPAL_DID, API_ERRORS, API_ERROR_CODES, API_REQUEST_LIMITS, ATTESTED_BEARER_MAX_TTL_SECONDS, AUTHORIZATION_MODES, AUTH_ERRORS, AUTH_ERROR_MESSAGES, AccountSchema, AddFingerprintToProfileRequestSchema, AddUpdateProviderRequestSchema, AdminQueryParamsSchema, AgentCategorySchema, AgentClassificationRequestSchema, AgentClassificationResultSchema, AgentClassificationSchema, AgentInfoSchema, AgentPatternSchema, AgentProfileSchema, AgentShieldConfigSchema, AgentSourceDistributionSchema, AgentStatisticsSchema, AgentTypeDefinitionSchema, AgentTypeSchema, AggregationTypeSchema, AllowListEntrySchema, AnalyticsAgentSourcesQuerySchema, AnalyticsAgentTypesQuerySchema, AnalyticsChartDataSchema, AnalyticsDataPointSchema, AnalyticsExportParamsSchema, AnalyticsExportQuerySchema, AnalyticsQuerySchema2 as AnalyticsQuerySchema, AnalyticsRealtimeQuerySchema, AnalyticsSessionsQuerySchema, AnalyticsSessionsResponseSchema, AnalyticsSummarySchema2 as AnalyticsSessionsSummarySchema, AnalyticsSummarySchema, AnalyticsTimeSeriesSchema, AnalyticsTimeWindowSchema, ApiKeyPermissionSchema, ApiKeyRateLimitsSchema, ApiKeySchema, ApiKeysBulkCreateItemSchema, ApiKeysBulkRequestSchema, ApiKeysBulkRevokeItemSchema, ApiKeysBulkUpdateItemSchema, ApiKeysQuerySchema, ApiResponseSchema, AssuranceTierSchema, AuthErrorType, AuthProviderTypeSchema, BARE_ERRORS, BASELINE_ALLOW_POLICY_ID, BESPOKE_POLICY_IDS, BILLING_ERRORS, BLOCKED_PATH, BOT_USER_AGENT_PATTERNS, BROWSER_PATTERNS, BULK_ERROR_CODES, BaseAuthProviderSchema, BaseBulkRequestSchema, BatchDetectionRequestSchema, BatchDetectionResponseSchema, BatchEventRequestSchema, BatchEventResponseSchema, BatchEventSchema, BatchPixelEventRequestSchema, BehavioralAnalysisSchema, BehavioralDataSchema, BehavioralPatternSchema, BehavioralRulesSchema, BehavioralSignalsSchema, BehavioralThresholdSchema, BlockEventSchema, BlockReasonSchema, BotPatternSchema2 as BotPatternSchema, BotTypeSchema, BouncerConfigSchema, BouncerOutcomeSchema, BouncerProofSchema, BrowserInfoSchema, BulkDeletePreviewStatsSchema, BulkDeleteResponseSchema, BulkOperationOptionsSchema, BulkOperationParamsSchema, BulkOperationResultSchema, BulkOperationTypeSchema, BulkResponseSchema, BulkResultItemSchema, CACHE_LIMITS, CACHE_TTL, CLOUD_PROVIDER_RANGES, CONDITION_FIELDS, CONDITION_OPERATORS, CONFIDENCE_THRESHOLDS, CORRELATION_ID_HEADER, CRISPBudgetSchema, CURRENT_POLICY_VERSION, CacheConfigSchema, CachedDetectionDataSchema, ChallengeParamsSchema, ChallengeWireError, CircuitBreakerConfigSchema, CircuitBreakerStateSchema, ClickEventSchema, ClientDetectionSchema, CollectFingerprintRequestSchema, CollectFingerprintResponseSchema, CollectedDataSchema, ConditionFieldSchema, ConditionOperatorSchema, ConditionValueSchema, ConfidenceBreakdownSchema, ConfidenceLevelSchema, ConfidenceThresholdSchema, ConfidenceUtils, ConfiguredProviderSchema, ConsentAgentMetadataSchema, ConsentBrandingSchema, ConsentCapabilityGroupSchema, ConsentCapabilitySchema, ConsentConfigMetadataSchema, ConsentConfigSchema, ConsentTermsSchema, ConsentUISchema, CorrelationIdSchema, CreateApiKeySchema, CreateOrganizationInputSchema, CreateOrganizationSchema, CreatePixelSchema, CreateProfileRequestSchema, CreateProjectSchema, CreateProvisioningOrganizationRequestSchema, CreateProvisioningOrganizationResponseSchema, CredentialProviderSchema, CustomRuleSchema, DATABASE_LIMITS, DEFAULT_ADMIN_OVERVIEW_WINDOW, DEFAULT_AGENTSHIELD_CONFIG, DEFAULT_AGENT_TYPES, DEFAULT_API_KEY_RATE_LIMITS, DEFAULT_AUTHORIZATION_HOST, DEFAULT_BEHAVIORAL_THRESHOLDS, DEFAULT_CACHE_CONFIG, DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, DEFAULT_CONFIDENCE_THRESHOLDS, DEFAULT_CORS_CONFIG, DEFAULT_DETECTION_OPTIONS, DEFAULT_ENV_VARS, DEFAULT_LOG_CONFIG, DEFAULT_MAX_VENDOR_RANGE_AGE_MS, DEFAULT_PASSWORD_REQUIREMENTS, DEFAULT_PIXEL_CONFIG, DEFAULT_POLICY, DEFAULT_PROJECT_SETTINGS, DEFAULT_RESPONSE_HEADERS, DEFAULT_RETRY_CONFIG, DEFAULT_RULE_PRIORITY, DEFAULT_SESSION_CONFIG, DEFAULT_THRESHOLDS, DEFAULT_TIMEOUTS, DEFAULT_WEBHOOK_EVENTS, DELEGATION_PROOF_HEADERS, DEPLOY_STEPS, DETECTION_ERRORS, DETECTION_LIMITS, DETECTION_REASON_CODES, DashboardStatsRequestSchema, DatabaseDetectionMetadataSchema, DatabaseStatusSchema, DecisionSchema, DelegationPollingStatusSchema, DelegationResultSchema, DelegationSchema, DelegationStatusSchema, DelegationVerifiedBySchema, DeleteAccountSchema, DenyListEntrySchema, DeployProgressEventSchema, DeployStepIdSchema, DeployStepStateSchema, DeployStepStatusSchema, DeploymentMetadataSchema, DetectionClassSchema, DetectionDetailSchema, DetectionErrorDetailsSchema, DetectionEventSchema, DetectionInputSchema, DetectionLogSchema, DetectionMetadataSchema, DetectionModeSchema, DetectionOptionsSchema, DetectionReasonCodeSchema, DetectionReasoningSchema, DetectionRequestSchema, DetectionResponseSchema, DetectionResultSchema, DetectionRuleSchema, DetectionRulesSchema, DetectionSignalExposureSchema, DetectionSignalSchema, DetectionStatusSchema, DetectionTestResultSchema, DetectionViewTypeSchema, ENFORCEMENT_ACTIONS, ENFORCEMENT_MODES, ENTROPY_CONFIDENCE_CEILING, ENTROPY_CONFIDENCE_FLOOR, ERROR_CATEGORIES, ERROR_CODES, ERROR_MESSAGES, ERROR_STATUS_CODES, EXCLUSION_BUCKETS, EXPORT_LIMITS, EnforcementActionSchema, EnforcementModeSchema, EngineInfoSchema, EnhancedFingerprintResponseSchema, ErrorResponseSchema, EventConfigSchema, EventStorageRecordSchema, EventTrackingRequestSchema, EventTrackingResponseSchema, ExportAnalyticsSchema, ExpressMiddlewareOptionsSchema, FallbackOptionsSchema, FilterOperatorSchema, FingerprintAnalysisSchema, ClientDetectionSchema2 as FingerprintClientDetectionSchema, FingerprintDetectRequestSchema, FingerprintRecordSchema, FingerprintResponseSchema, FingerprintSearchQuerySchema, ForgeabilityRiskSchema, GrowthBatchRequestSchema, GrowthConfigurationResetSchema, GrowthConfigurationThresholdsSchema, GrowthConfigurationUpdateSchema, GrowthOpportunitiesQuerySchema, GrowthOpportunityUpdateSchema, HEADER_PATTERNS, HTTP_STATUS, HeaderRuleSchema, HeaderRulesSchema, HealthResponseSchema, HomeRailRollupsRequestSchema, INSTALLATION_KINDS, INSTALLATION_TYPES, INTERNAL_ERRORS, InstructPayloadSchema, IntegrationTypeSchema, InternalProcessingFlagsSchema, IpRangeCollectionSchema, IpRangeRuleSchema, JafarParseError, KNOWN_AGENT_PATTERNS, KYA_HTTP_ERROR, KYA_OS_HANDSHAKE_METHODS, KYA_OS_WIRE_METHODS, KeyboardEventSchema, LOWERCASE_ERRORS, ListProvisioningOrganizationsRequestSchema, ListProvisioningOrganizationsResponseSchema, LoggingConfigSchema, MATCH_ACTIONS, MAX_BULK_BATCH_SIZE, MAX_ED25519_KEY_BODY_LENGTH, MAX_REASON_CODES_HEADER_BYTES, MAX_REASON_CODES_ON_WIRE, MCPI_ORG_DID_HOST, MCP_CLIENT_DID_HOST, MOBILE_PATTERNS, MarketplaceSourceSchema, MessagePrioritySchema, MiddlewareActionSchema, MiddlewareConfigSchema, MiddlewareSessionConfigSchema, MiddlewareSessionDataSchema, MigrationStatusSchema, MouseEventSchema, NETWORK_ERRORS, NetworkConfigSchema, NetworkInfoSchema, NetworkTimingSchema, NextMiddlewareOptionsSchema, OAuth2ProviderSchema, OAuthConnectionStatusSchema, OAuthModeSchema, OAuthProviderMetadataSchema, OAuthProviderTypeSchema, OAuthProvidersMapSchema, OAuthTokensResponseSchema, OS_PATTERNS, OfflineQueueEntrySchema, OrganizationErrorCode, OrganizationIdSchema, OrganizationRoleSchema, OrganizationSettingsSchema, OrganizationSsoModeSchema, OrganizationSsoProviderSchema, OrganizationSsoSettingsSchema, PACKAGE_NAME, PAGINATION_DEFAULTS, PERFORMANCE_THRESHOLDS, PERMISSION_ERRORS, PINNED_SIGNING_VENDORS, PIXEL_ERRORS, PIXEL_EVENT_LIMITS, PLAN_FEATURE_LIMITS, PLAN_RATE_LIMITS, POLICY_ERRORS, POLICY_MATCH_TYPES, PUBLIC_API_ERROR_CODES, PageContextSchema, PaginatedResponseSchema, PaginationInfoSchema, PaginationParamsSchema, PaginationResponseSchema, PatternUpdateRequestSchema, PerformanceRecalculationRequestSchema, PixelAnalyticsSchema, PixelConfigurationSchema, PixelEventSchema, PixelEventTypeSchema, PixelInitSchema, PixelInstallConfigSchema, PixelSchema, PixelSessionSchema, PixelStatsSchema, PixelTrackingRequestSchema, PixelTrackingResponseSchema, PixelUserIdentificationSchema, PixelVerificationStatusSchema, PixelsBulkCreateItemSchema, PixelsBulkDeleteItemSchema, PixelsBulkRegenerateItemSchema, PixelsBulkRequestSchema, PixelsBulkUpdateItemSchema, PixelsQuerySchema, PolicyConditionSchema, PolicyConfigSchema, PolicyEvaluationContextSchema, PolicyEvaluationResultSchema, PolicyFetcher, PolicyMatchTypeSchema, PolicyMetadataSchema, PolicyRuleSchema, ProjectIdSchema, ProjectSchema, ProjectSettingsSchema, ProjectsBulkCreateItemSchema, ProjectsBulkDeleteItemSchema, ProjectsBulkRequestSchema, ProjectsBulkUpdateItemSchema, ProjectsQuerySchema, ProtocolVersionSchema, ProviderDefinitionSchema2 as ProviderDefinitionSchema, ProvidersResponseSchema, ProvisionKeyRequestSchema, ProvisionKeyResponseSchema, ProvisioningModeSchema, ProvisioningOrganizationRoleSchema, ProvisioningOrganizationSummarySchema, PublicAnalyticsBotTypeSchema, PublicAnalyticsSchema, PublicAnalyticsSummarySchema, PublicAnalyticsTimeSeriesPointSchema, PublicApiHeadersSchema, PublicApiQueryParamsSchema, PublicApiResponseSchema, PublicDetectionSchema, PublicKeyConfigSchema, PaginationResponseSchema as PublicPaginationResponseSchema, PublicProjectSchema, PublishProfileRequestSchema, QueryFilterSchema, QuerySchema, RATE_LIMIT_ERRORS, REGISTERED_SID_MAX_LENGTH, REPORT_AI_AGENT_NAMES, REPORT_AI_CRAWLER_NAMES, RESOURCE_ERRORS, RULE_CACHE, RULE_CATEGORIES, RULE_CDN, RULE_ERRORS, RULE_PATHS, RULE_VERSION, RealtimeEventSchema, RealtimeEventTypeSchema, ReasoningStepSchema, RecommendationGenerationSchema, RecommendationQuerySchema, RedirectTargetSchema, RedisSessionDataSchema, RedisStatsSchema, RefreshScopesRequestSchema, ReportedAgentSchema, ReportedDelegationSchema, ReportedIdentitySchema, ReportedPrincipalSchema, RequestContextSchema, ResourceUsageSchema, ResponseActionSchema, RetryStrategySchema, RevokeProvisionQuerySchema, RevokeProvisionResponseSchema, RiskAssessmentSchema, RuleLoadOptionsSchema, RuleLoader, RuleMatchResultSchema, RuleMetadataSchema, RuleParser, RuleUpdateEventSchema, RuleValidationResultSchema, RuleValidator, SECURITY_LIMITS, SERVICE_TRAFFIC_KEYS, SESSION_ERRORS, SESSION_LIMITS, SID_ATTRIBUTABLE_RESULT, SLUG_REGEX, SUSPICIOUS_HEADERS, SUSPICIOUS_PATTERNS, ScopeSchema, ScrollEventSchema, SdkSessionDataSchema, SessionConfigSchema, SessionCreateRequestSchema, SessionDataSchema, SessionEventSchema, SessionEventTypeSchema, SessionQueryOptionsSchema, SessionSchema, SessionStateSchema, SessionStorageTypeSchema, SessionTokenPayloadSchema, SessionUpdateRequestSchema, AgentTypeDistributionSchema as SharedAgentTypeDistributionSchema, ConfidenceDistributionSchema as SharedConfidenceDistributionSchema, ShopifyProjectProvisionRequestSchema, ShopifyProjectProvisionResultSchema, ShopifyProjectSettingsUpdateSchema, ShopifyStatsResponseSchema, ShopifyThreatSchema, SignatureAlgorithmSchema, SignatureRuleSchema, SignatureVerificationRequestSchema, SignatureVerificationResponseSchema, SingleItemResponseSchema, SsoLinkRequestSchema, SsoLinkResponseSchema, StaleVendorRangesError, StatsResponseSchema, StatsUpdateEventSchema, StrictEnforcementActionSchema, SuggestedActionSchema, SystemStatsSchema, TIME_WINDOWS, TLSFingerprintSchema, TRADITIONAL_BOT_PATTERNS, TRAFFIC_TAXONOMY_BUCKETS, TRUSTED_BOTS, TestDetectionRequestSchema, ThresholdConfigSchema, ToolConsentOverridesSchema, TouchEventSchema, TraceStepSchema, TransportConfigSchema, TransportMetricsSchema, TransportOptionsSchema, TransportResponseSchema, TransportStateSchema, UNCALIBRATED_NOISY_OR_PRIOR, UNNAMED_AGENT_LABEL, UPDATE_FREQUENCIES, USER_AGENT_PATTERNS, UpdateApiKeySchema, UpdateBouncerConfigSchema, UpdateOrganizationInputSchema, UpdateOrganizationSchema, UpdatePixelSchema, UpdateProfileRequestSchema, UpdateProjectSchema, UpdateSettingsSchema, UserAgentRuleSchema, UserPlanSchema, UserSchema, VALIDATION_ERRORS, VALIDATION_MODES, VALIDATION_PATTERNS, VERDICT_COOKIE_NAME, VERSION, VerdictEvidenceSchema, VerificationCacheEntrySchema, VerificationProviderSchema, VerificationRequestSchema, VerificationResponseSchema, VerificationTokenSchema, WEBHOOK_LIMITS, WasmAgentNameSchema, AgentTypeSchema as WasmAgentTypeSchema, WasmConfigSchema, WasmDetectionResultSchema, WasmRequestMetadataSchema, WasmRiskLevel, WasmVerificationMethod, WorkerActionSchema, WorkerCapabilitiesSchema, WorkerConfigSchema, WorkerErrorSchema, WorkerErrorTypeSchema, WorkerHealthStatusSchema, WorkerMessageSchema, WorkerMessageTypeSchema, WorkerMetricsSchema, WorkerPoolConfigSchema, WorkerStateSchema, WorkerTaskSchema, acceptsHtml, adminOverviewQuerySchema, approvalQuorumForRequest, assertVendorRangesFresh, assignmentChangeRequestSchema, auditLogQuerySchema, base58btcDecode, base58btcEncode, batchAssignmentRequestSchema, bespokePolicyLabel, blockDelegationVerdict, blockEqualityLiterals, buildChallengeWire, buildDelegationBearerHeader, buildDelegationChallengeBody, buildDelegationChallengeEnvelope, buildDelegationChallengeHeader, buildDelegationInstructions, buildInitialStepsState, buildKnownPatternLookup, buildVerdictEvidence, calculateDeployProgress, cedarQuotedValueRegExp, changePasswordSchema, classifyAgentTaxonomy, classifyResponseShape, claudeRuntimeLabel, computeEntropyConfidence, createError, createErrorResponse, createEvaluationContext, createPaginatedResponse, createPaginatedResponseSchema, createPolicyFetcher, createPublicErrorResponse, createPublicPaginatedResponse, createPublicSuccessResponse, createSuccessResponse, createValidationErrorResponse, decisionPolicyId, decodeDidKeyEd25519, decodeEd25519PublicKeyMultibaseTolerant, defaultConfig, deriveCorrelationId, deriveDelegationPickupUri, deriveMcpClientDid, deriveMcpiOrgDid, deriveMcpiOrgKid, deriveMcpiUserDid, deriveVerdict, detectionClassToEnum, discoveredToolSchema, encodeDidKeyEd25519, encodeEd25519PublicKeyMultibase, encodeVerdictCookie, enumToDetectionClass, escapeCedarString, evaluatePolicy, extractCorrelationIdFromHeaders, extractMatch, fetchPolicy, findMatchingPattern, findStaleVendorRanges, forgotPasswordSchema, formatAgentCategory, formatAgentCategoryInline, formatConfidence, formatReasonCodesHeader, fromProviderRegistryFormat, fromProviderRegistryFormatSafe, gatewayConfigInputSchema, gatewayConfigSchema, gatewayConnectedAgentSchema, gatewayConnectionsSummarySchema, gatewayInternalDiscoverErrorSchema, gatewayInternalDiscoverSuccessSchema, gatewayInternalToolsListSchema, gatewayToolCallSchema, generateDelegationSid, generateTestId, getAgentDisplayName, getBotType, getCategoryBadgeVariant, getCategoryColor, getConfidenceLevel, getDefaultPolicyFetcher, getEnvVar, getRateLimitWindow, getRemainingQuota, getStepInfo, getStepOrder, getVerificationMethodDescription, getVerificationReliability, getVerificationRiskLevel, hasClaudeCodeToken, hasClaudeSearchBotToken, hasClaudeUserToken, hasPinnedSigningVendor, initializePolicyFetcher, isBespokePolicyId, isBlockingAction, isClaudeProductLabel, isForbidBlock, isHighConfidenceVerification, isKnownAgentType, isKnownAiCrawler, isKyaOsHandshakeMethod, isKyaOsWireMethod, isLegacyDetectionClass, isLegitimateCategory, isLimitExceeded, isNonNavigablePolicyId, isPassThroughAction, isPrivateOrReservedHost, isSupportedAuthType, isTraditionalBot, isUnnarrowedDenyBlock, isValidAuthorizationHost, isValidFingerprintResponse, isValidMcpiOrgSlug, isValidWasmDetectionResult, isValidWasmRequestMetadata, lintUnnarrowedDenyRules, loadRulesAsync, mapDetectionToReasonCodes, mapLegacyAuthType, mapToLegacyAuthType, matchPath, mergeWithDefaults, migrateLegacyDetectionClass, nonNavigablePolicyLabel, normalizeAgentName, normalizeClientIp, normalizeConfidence, normalizeDetectionClass, normalizeDetectionClassEnum, normalizeHandshakeMethod, normalizeOrganizationName, normalizeWireMethod, oauthClientSchema, parseAgentName, parseEvaluationContext, parseJafarFeed, parsePolicyConfig, parseRules, partial, passwordSchema, pathHasUnnarrowedDenyRule, pathLiteralsInBlock, permitDelegationVerdict, projectResetRequestSchema, reconstructConfidenceFromEvidence, refineClaudeDisplayLabel, refineSessionGrainClaudeLabel, requestCarriesDelegationProof, requiredScopesForRequest, resetPasswordSchema, resetPolicyFetcher, resolveAuthorizationHost, resolveChallengeContext, resolveClientIp, resolveTrustedDelegationRoots, safeParsePolicyConfig, safeUrl, selectBodyReadable200, serveBodyReadable200, signInSchema, signUpSchema, splitCedarBlocks, strict, supportsClientSide, supportsHeaders, supportsServerEnhanced, testPattern, testPatterns, toBareHost, toCoarseReasonKind, toPercent, toProviderRegistryFormat, toStoredCorrelationId, toWasmRequestMetadata, unescapeCedarString, updateStepsState, upstreamDiscoveryErrorSchema, upstreamServerInputSchema, upstreamServerSchema, validate, validateClientDetection, validateFingerprintRequest, validateOrThrow, validateOrganizationName, validateRules, validateRulesLoose, validateStepUpQuorum, vaultResolveDataSchema, vaultResolveErrorSchema, vaultResolveMetaSchema, vaultResolveResponseSchema, vaultResolveSuccessSchema, verifyEmailSchema, wasmToDetectionResult };